2 * Copyright (c) 1985, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * @(#) Copyright (c) 1985, 1993 The Regents of the University of California. All rights reserved.
30 * @(#)timed.c 8.1 (Berkeley) 6/6/93
31 * $FreeBSD: src/usr.sbin/timed/timed/timed.c,v 1.9 1999/08/28 01:20:19 peter Exp $
38 #include <sys/ioctl.h>
40 #include "pathnames.h"
42 #include <sys/types.h>
43 #include <sys/times.h>
46 int sock, sock_raw = -1;
48 u_short sequence; /* sequence number */
52 int nslavenets; /* nets were I could be a slave */
53 int nmasternets; /* nets were I could be a master */
54 int nignorednets; /* ignored nets */
55 int nnets; /* nets I am connected to */
57 FILE *fd; /* trace file FD */
61 struct netinfo *nettab = NULL;
62 struct netinfo *slavenet;
73 struct hosttbl hosttbl[NHOSTS+1]; /* known hosts */
75 static struct goodhost { /* hosts that we trust */
76 char name[MAXHOSTNAMELEN];
77 struct goodhost *next;
81 static char *goodgroup; /* net group of trusted hosts */
82 static void checkignorednets(void);
83 static void pickslavenet(struct netinfo *);
84 static void add_good_host(char *, int);
85 static void usage(void);
88 * The timedaemons synchronize the clocks of hosts in a local area network.
89 * One daemon runs as master, all the others as slaves. The master
90 * performs the task of computing clock differences and sends correction
91 * values to the slaves.
92 * Slaves start an election to choose a new master when the latter disappears
93 * because of a machine crash, network partition, or when killed.
94 * A resolution protocol is used to kill all but one of the masters
95 * that happen to exist in segments of a partitioned network when the
96 * network partition is fixed.
98 * Authors: Riccardo Gusella & Stefano Zatti
100 * overhauled at Silicon Graphics
103 main(int argc, char *argv[])
108 struct timeval ntime;
109 struct servent *srvp;
110 char buf[BUFSIZ], *cp, *cplim;
112 struct ifreq ifreq, ifreqf, *ifr;
114 struct netinfo *ntip;
115 struct netinfo *savefromnet;
116 struct netent *nentp;
118 struct sockaddr_in server;
128 while ((c = getopt(argc, argv, "Mtdn:i:F:G:P:")) != -1) {
140 errx(1, "-i and -n make no sense together");
149 errx(1, "-i and -n make no sense together");
157 add_good_host(optarg,1);
158 while (optind < argc && argv[optind][0] != '-')
159 add_good_host(argv[optind++], 1);
166 if (goodgroup != NULL)
167 errx(1, "only one net group");
178 /* If we care about which machine is the master, then we must
179 * be willing to be a master
181 if (NULL != goodgroup || NULL != goodhosts)
184 if (gethostname(hostname, sizeof(hostname) - 1) < 0)
185 err(1, "gethostname");
193 if (goodhosts != NULL) /* trust ourself */
194 add_good_host(hostname,1);
196 srvp = getservbyname("timed", "udp");
198 errx(1, "unknown service 'timed/udp'");
200 bzero(&server, sizeof(struct sockaddr_in));
201 server.sin_port = srvp->s_port;
202 server.sin_family = AF_INET;
203 sock = socket(AF_INET, SOCK_DGRAM, 0);
206 if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&on,
208 err(1, "setsockopt");
209 if (bind(sock, (struct sockaddr*)&server, sizeof(server))) {
210 if (errno == EADDRINUSE)
211 warnx("time daemon already running");
217 /* choose a unique seed for random number generation */
218 gettimeofday(&ntime, 0);
219 srandom(ntime.tv_sec + ntime.tv_usec);
221 sequence = random(); /* initial seq number */
223 /* rounds kernel variable time to multiple of 5 ms. */
225 ntime.tv_usec = -((ntime.tv_usec/1000) % 5) * 1000;
226 adjtime(&ntime, NULL);
228 for (nt = nets; nt; nt = nt->next) {
229 nentp = getnetbyname(nt->name);
231 nt->net = inet_network(nt->name);
232 if (nt->net != (long)INADDR_NONE)
233 nentp = getnetbyaddr(nt->net, AF_INET);
236 nt->net = nentp->n_net;
237 } else if (nt->net == (long)INADDR_NONE) {
238 errx(1, "unknown net %s", nt->name);
239 } else if (nt->net == (long)INADDR_ANY) {
240 errx(1, "bad net %s", nt->name);
242 warnx("warning: %s unknown in /etc/networks",
246 if (0 == (nt->net & 0xff000000))
248 if (0 == (nt->net & 0xff000000))
250 if (0 == (nt->net & 0xff000000))
253 ifc.ifc_len = sizeof(buf);
255 if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0)
256 err(1, "get interface configuration");
259 #define size(p) max((p).sa_len, sizeof(p))
260 cplim = buf + ifc.ifc_len; /*skip over if's with big ifr_addr's */
261 for (cp = buf; cp < cplim;
262 cp += sizeof (ifr->ifr_name) + size(ifr->ifr_addr)) {
263 ifr = (struct ifreq *)cp;
264 if (ifr->ifr_addr.sa_family != AF_INET)
267 ntp = (struct netinfo*)malloc(sizeof(struct netinfo));
268 bzero(ntp,sizeof(*ntp));
269 ntp->my_addr=((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr;
270 ntp->status = NOMASTER;
274 if (ioctl(sock, SIOCGIFFLAGS, (char *)&ifreqf) < 0) {
275 warn("get interface flags");
278 if ((ifreqf.ifr_flags & IFF_UP) == 0)
280 if ((ifreqf.ifr_flags & IFF_BROADCAST) == 0 &&
281 (ifreqf.ifr_flags & IFF_POINTOPOINT) == 0) {
286 if (ioctl(sock, SIOCGIFNETMASK, (char *)&ifreq) < 0) {
290 ntp->mask = ((struct sockaddr_in *)
291 &ifreq.ifr_addr)->sin_addr.s_addr;
293 if (ifreqf.ifr_flags & IFF_BROADCAST) {
294 if (ioctl(sock, SIOCGIFBRDADDR, (char *)&ifreq) < 0) {
295 warn("get broadaddr");
298 ntp->dest_addr = *(struct sockaddr_in *)&ifreq.ifr_broadaddr;
299 /* What if the broadcast address is all ones?
300 * So we cannot just mask ntp->dest_addr. */
301 ntp->net = ntp->my_addr;
302 ntp->net.s_addr &= ntp->mask;
304 if (ioctl(sock, SIOCGIFDSTADDR,
305 (char *)&ifreq) < 0) {
306 warn("get destaddr");
309 ntp->dest_addr = *(struct sockaddr_in *)&ifreq.ifr_dstaddr;
310 ntp->net = ntp->dest_addr.sin_addr;
313 ntp->dest_addr.sin_port = port;
315 for (nt = nets; nt; nt = nt->next) {
316 if (ntp->net.s_addr == htonl(nt->net))
319 if ((nflag && !nt) || (iflag && nt))
323 if (nettab == NULL) {
334 errx(1, "no network usable");
337 /* microseconds to delay before responding to a broadcast */
338 delay1 = casual(1, 100*1000);
340 /* election timer delay in secs. */
341 delay2 = casual(MINTOUT, MAXTOUT);
349 openlog("timed", LOG_CONS|LOG_PID, LOG_DAEMON);
352 * keep returning here
354 ret = setjmp(jmpenv);
355 savefromnet = fromnet;
366 /* Just lost our master */
367 if (slavenet != NULL)
368 slavenet->status = election(slavenet);
369 if (!slavenet || slavenet->status == MASTER) {
373 makeslave(slavenet); /* prune extras */
378 /* Just been told to quit */
380 pickslavenet(savefromnet);
385 if (!(status & MASTER) && sock_raw != -1) {
386 /* sock_raw is not being used now */
391 if (status == MASTER)
397 if (sock_raw != -1) {
403 /* we just lost our master or were told to quit */
406 for (ntp = nettab; ntp != NULL; ntp = ntp->next) {
407 if (ntp->status == MASTER) {
409 ntp->status = NOMASTER;
428 "usage: timed [-dtM] [-i net|-n net] [-F host1 host2 ...] [-G netgp]\n");
431 "usage: timed [-dtM] [-i net|-n net] [-F host1 host2 ...]\n");
437 * suppress an upstart, untrustworthy, self-appointed master
440 suppress(struct sockaddr_in *addr, char *name, struct netinfo *net)
442 struct sockaddr_in tgt;
443 char tname[MAXHOSTNAMELEN];
445 static struct timeval wait;
448 fprintf(fd, "suppress: %s\n", name);
450 strlcpy(tname, name, sizeof(tname));
452 while (0 != readmsg(TSP_ANY, ANYADDR, &wait, net)) {
454 fprintf(fd, "suppress:\tdiscarded packet from %s\n",
458 syslog(LOG_NOTICE, "suppressing false master %s", tname);
459 msg.tsp_type = TSP_QUIT;
460 strlcpy(msg.tsp_name, hostname, sizeof(msg.tsp_name));
461 acksend(&msg, &tgt, tname, TSP_ACK, 0, 1);
465 lookformaster(struct netinfo *ntp)
467 struct tsp resp, conflict, *answer;
468 struct timeval ntime;
469 char mastername[MAXHOSTNAMELEN];
470 struct sockaddr_in masteraddr;
475 /* look for master */
476 resp.tsp_type = TSP_MASTERREQ;
477 strlcpy(resp.tsp_name, hostname, sizeof(resp.tsp_name));
478 answer = acksend(&resp, &ntp->dest_addr, ANYADDR,
479 TSP_MASTERACK, ntp, 0);
480 if (answer != NULL && !good_host_name(answer->tsp_name)) {
481 suppress(&from, answer->tsp_name, ntp);
482 ntp->status = NOMASTER;
485 if (answer == NULL) {
487 * Various conditions can cause conflict: races between
488 * two just started timedaemons when no master is
489 * present, or timedaemons started during an election.
490 * A conservative approach is taken. Give up and became a
491 * slave, postponing election of a master until first
494 ntime.tv_sec = ntime.tv_usec = 0;
495 answer = readmsg(TSP_MASTERREQ, ANYADDR, &ntime, ntp);
496 if (answer != NULL) {
497 if (!good_host_name(answer->tsp_name)) {
498 suppress(&from, answer->tsp_name, ntp);
499 ntp->status = NOMASTER;
504 ntime.tv_sec = ntime.tv_usec = 0;
505 answer = readmsg(TSP_MASTERUP, ANYADDR, &ntime, ntp);
506 if (answer != NULL) {
507 if (!good_host_name(answer->tsp_name)) {
508 suppress(&from, answer->tsp_name, ntp);
509 ntp->status = NOMASTER;
514 ntime.tv_sec = ntime.tv_usec = 0;
515 answer = readmsg(TSP_ELECTION, ANYADDR, &ntime, ntp);
516 if (answer != NULL) {
517 if (!good_host_name(answer->tsp_name)) {
518 suppress(&from, answer->tsp_name, ntp);
519 ntp->status = NOMASTER;
525 ntp->status = MASTER;
527 ntp->status = NOMASTER;
532 strlcpy(mastername, answer->tsp_name, sizeof(mastername));
536 * If network has been partitioned, there might be other
537 * masters; tell the one we have just acknowledged that
538 * it has to gain control over the others.
541 ntime.tv_usec = 300000;
542 answer = readmsg(TSP_MASTERACK, ANYADDR, &ntime, ntp);
544 * checking also not to send CONFLICT to ack'ed master
545 * due to duplicated MASTERACKs
547 if (answer != NULL &&
548 strcmp(answer->tsp_name, mastername) != 0) {
549 conflict.tsp_type = TSP_CONFLICT;
550 strlcpy(conflict.tsp_name, hostname, sizeof(conflict.tsp_name));
551 if (!acksend(&conflict, &masteraddr, mastername,
554 "error on sending TSP_CONFLICT");
560 * based on the current network configuration, set the status, and count
569 nmasternets = nslavenets = nnets = nignorednets = 0;
571 fprintf(fd, "Net status:\n");
572 for (ntp = nettab; ntp != NULL; ntp = ntp->next) {
573 switch ((int)ntp->status) {
586 fprintf(fd, "\t%-16s", inet_ntoa(ntp->net));
587 switch ((int)ntp->status) {
589 fprintf(fd, "NOMASTER\n");
592 fprintf(fd, "MASTER\n");
595 fprintf(fd, "SLAVE\n");
598 fprintf(fd, "IGNORE\n");
601 fprintf(fd, "invalid state %d\n",
607 status |= ntp->status;
612 "\tnets=%d masters=%d slaves=%d ignored=%d delay2=%ld\n",
613 nnets, nmasternets, nslavenets, nignorednets, delay2);
617 makeslave(struct netinfo *net)
621 for (ntp = nettab; ntp != NULL; ntp = ntp->next) {
622 if (ntp->status == SLAVE && ntp != net)
623 ntp->status = IGNORE;
629 * Try to become master over ignored nets..
632 checkignorednets(void)
636 for (ntp = nettab; ntp != NULL; ntp = ntp->next) {
637 if (!Mflag && ntp->status == SLAVE)
640 if (ntp->status == IGNORE || ntp->status == NOMASTER) {
642 if (!Mflag && ntp->status == SLAVE)
649 * choose a good network on which to be a slave
650 * The ignored networks must have already been checked.
651 * Take a hint about for a good network.
654 pickslavenet(struct netinfo *ntp)
657 if (slavenet != NULL && slavenet->status == SLAVE) {
658 makeslave(slavenet); /* prune extras */
662 if (ntp == NULL || ntp->status != SLAVE) {
663 for (ntp = nettab; ntp != NULL; ntp = ntp->next) {
664 if (ntp->status == SLAVE)
672 * returns a random number in the range [inf, sup]
675 casual(long inf, long sup)
679 value = ((double)(random() & 0x7fffffff)) / (0x7fffffff*1.0);
680 return(inf + (sup - inf)*value);
689 gettimeofday(&tv, NULL);
691 return (ctime(&tv_sec));
695 addnetname(char *name)
697 struct nets **netlist = &nets;
700 netlist = &((*netlist)->next);
701 *netlist = (struct nets *)malloc(sizeof **netlist);
702 if (*netlist == NULL)
703 errx(1, "malloc failed");
704 bzero((char *)*netlist, sizeof(**netlist));
705 (*netlist)->name = name;
708 /* note a host as trustworthy */
710 add_good_host(char *name,
711 int perm) /* 1=not part of the netgroup */
713 struct goodhost *ghp;
714 struct hostent *hentp;
716 ghp = (struct goodhost*)malloc(sizeof(*ghp));
718 syslog(LOG_ERR, "malloc failed");
722 bzero((char*)ghp, sizeof(*ghp));
723 strlcpy(&ghp->name[0], name, sizeof(ghp->name));
724 ghp->next = goodhosts;
728 hentp = gethostbyname(name);
729 if (NULL == hentp && perm)
730 warnx("unknown host %s", name);
734 /* update our image of the net-group of trustworthy hosts
737 get_goodgroup(int force)
739 # define NG_DELAY (30*60*CLK_TCK) /* 30 minutes */
740 static unsigned long last_update = -NG_DELAY;
741 unsigned long new_update;
742 struct goodhost *ghp, **ghpp;
745 char *mach, *usr, *dom;
750 /* if no netgroup, then we are finished */
751 if (goodgroup == NULL || !Mflag)
754 /* Do not chatter with the netgroup master too often.
756 new_update = times(&tm);
757 if (new_update < last_update + NG_DELAY
760 last_update = new_update;
762 /* forget the old temporary entries */
764 while (NULL != (ghp = *ghpp)) {
774 /* quit now if we are not one of the trusted masters
776 if (!innetgr(goodgroup, &hostname[0], 0,0)) {
778 fprintf(fd, "get_goodgroup: %s not in %s\n",
779 &hostname[0], goodgroup);
783 fprintf(fd, "get_goodgroup: %s in %s\n",
784 &hostname[0], goodgroup);
786 /* mark the entire netgroup as trusted */
787 setnetgrent(goodgroup);
788 while (getnetgrent(&mach,&usr,&dom)) {
790 add_good_host(mach,0);
794 /* update list of slaves */
795 for (htp = self.l_fwd; htp != &self; htp = htp->l_fwd) {
796 htp->good = good_host_name(&htp->name[0]);
802 /* see if a machine is trustworthy
804 int /* 1=trust hp to change our date */
805 good_host_name(char *name)
807 struct goodhost *ghp = goodhosts;
810 if (!ghp || !Mflag) /* trust everyone if no one named */
815 if (c == ghp->name[0]
816 && !strcasecmp(name, ghp->name))
817 return 1; /* found him, so say so */
818 } while (NULL != (ghp = ghp->next));
820 if (!strcasecmp(name,hostname)) /* trust ourself */
823 return 0; /* did not find him */