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. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 static const char copyright[] =
36 "@(#) Copyright (c) 1985, 1993\n\
37 The Regents of the University of California. All rights reserved.\n";
42 static char sccsid[] = "@(#)timed.c 8.1 (Berkeley) 6/6/93";
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
53 #include <sys/ioctl.h>
55 #include "pathnames.h"
57 #include <sys/types.h>
58 #include <sys/times.h>
61 int sock, sock_raw = -1;
63 u_short sequence; /* sequence number */
67 int nslavenets; /* nets were I could be a slave */
68 int nmasternets; /* nets were I could be a master */
69 int nignorednets; /* ignored nets */
70 int nnets; /* nets I am connected to */
72 FILE *fd; /* trace file FD */
76 struct netinfo *nettab = 0;
77 struct netinfo *slavenet;
88 struct hosttbl hosttbl[NHOSTS+1]; /* known hosts */
90 static struct goodhost { /* hosts that we trust */
91 char name[MAXHOSTNAMELEN];
92 struct goodhost *next;
96 static char *goodgroup; /* net group of trusted hosts */
97 static void checkignorednets(void);
98 static void pickslavenet(struct netinfo *);
99 static void add_good_host(char *, int);
100 static void usage(void);
103 * The timedaemons synchronize the clocks of hosts in a local area network.
104 * One daemon runs as master, all the others as slaves. The master
105 * performs the task of computing clock differences and sends correction
106 * values to the slaves.
107 * Slaves start an election to choose a new master when the latter disappears
108 * because of a machine crash, network partition, or when killed.
109 * A resolution protocol is used to kill all but one of the masters
110 * that happen to exist in segments of a partitioned network when the
111 * network partition is fixed.
113 * Authors: Riccardo Gusella & Stefano Zatti
115 * overhauled at Silicon Graphics
125 struct timeval ntime;
126 struct servent *srvp;
127 char buf[BUFSIZ], *cp, *cplim;
129 struct ifreq ifreq, ifreqf, *ifr;
130 register struct netinfo *ntp;
131 struct netinfo *ntip;
132 struct netinfo *savefromnet;
133 struct netent *nentp;
135 struct sockaddr_in server;
149 while ((c = getopt(argc, argv, "Mtdn:i:F:G:P:")) != -1) {
161 errx(1, "-i and -n make no sense together");
170 errx(1, "-i and -n make no sense together");
178 add_good_host(optarg,1);
179 while (optind < argc && argv[optind][0] != '-')
180 add_good_host(argv[optind++], 1);
188 errx(1, "only one net group");
200 /* If we care about which machine is the master, then we must
201 * be willing to be a master
203 if (0 != goodgroup || 0 != goodhosts)
206 if (gethostname(hostname, sizeof(hostname) - 1) < 0)
207 err(1, "gethostname");
215 if (goodhosts != 0) /* trust ourself */
216 add_good_host(hostname,1);
218 srvp = getservbyname("timed", "udp");
220 errx(1, "timed/udp: unknown service");
222 bzero(&server, sizeof(struct sockaddr_in));
223 server.sin_port = srvp->s_port;
224 server.sin_family = AF_INET;
225 sock = socket(AF_INET, SOCK_DGRAM, 0);
228 if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&on,
230 err(1, "setsockopt");
231 if (bind(sock, (struct sockaddr*)&server, sizeof(server))) {
232 if (errno == EADDRINUSE)
233 warnx("time daemon already running");
239 /* choose a unique seed for random number generation */
240 (void)gettimeofday(&ntime, 0);
241 srandom(ntime.tv_sec + ntime.tv_usec);
243 sequence = random(); /* initial seq number */
245 /* rounds kernel variable time to multiple of 5 ms. */
247 ntime.tv_usec = -((ntime.tv_usec/1000) % 5) * 1000;
248 (void)adjtime(&ntime, (struct timeval *)0);
250 for (nt = nets; nt; nt = nt->next) {
251 nentp = getnetbyname(nt->name);
253 nt->net = inet_network(nt->name);
254 if (nt->net != INADDR_NONE)
255 nentp = getnetbyaddr(nt->net, AF_INET);
258 nt->net = nentp->n_net;
259 } else if (nt->net == INADDR_NONE) {
260 errx(1, "unknown net %s", nt->name);
261 } else if (nt->net == INADDR_ANY) {
262 errx(1, "bad net %s", nt->name);
264 warnx("warning: %s unknown in /etc/networks",
268 if (0 == (nt->net & 0xff000000))
270 if (0 == (nt->net & 0xff000000))
272 if (0 == (nt->net & 0xff000000))
275 ifc.ifc_len = sizeof(buf);
277 if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0)
278 err(1, "get interface configuration");
280 #define size(p) max((p).sa_len, sizeof(p))
281 cplim = buf + ifc.ifc_len; /*skip over if's with big ifr_addr's */
282 for (cp = buf; cp < cplim;
283 cp += sizeof (ifr->ifr_name) + size(ifr->ifr_addr)) {
284 ifr = (struct ifreq *)cp;
285 if (ifr->ifr_addr.sa_family != AF_INET)
288 ntp = (struct netinfo*)malloc(sizeof(struct netinfo));
289 bzero(ntp,sizeof(*ntp));
290 ntp->my_addr=((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr;
291 ntp->status = NOMASTER;
295 if (ioctl(sock, SIOCGIFFLAGS, (char *)&ifreqf) < 0) {
296 warn("get interface flags");
299 if ((ifreqf.ifr_flags & IFF_UP) == 0)
301 if ((ifreqf.ifr_flags & IFF_BROADCAST) == 0 &&
302 (ifreqf.ifr_flags & IFF_POINTOPOINT) == 0) {
307 if (ioctl(sock, SIOCGIFNETMASK, (char *)&ifreq) < 0) {
311 ntp->mask = ((struct sockaddr_in *)
312 &ifreq.ifr_addr)->sin_addr.s_addr;
314 if (ifreqf.ifr_flags & IFF_BROADCAST) {
315 if (ioctl(sock, SIOCGIFBRDADDR, (char *)&ifreq) < 0) {
316 warn("get broadaddr");
319 ntp->dest_addr = *(struct sockaddr_in *)&ifreq.ifr_broadaddr;
320 /* What if the broadcast address is all ones?
321 * So we cannot just mask ntp->dest_addr. */
322 ntp->net = ntp->my_addr;
323 ntp->net.s_addr &= ntp->mask;
325 if (ioctl(sock, SIOCGIFDSTADDR,
326 (char *)&ifreq) < 0) {
327 warn("get destaddr");
330 ntp->dest_addr = *(struct sockaddr_in *)&ifreq.ifr_dstaddr;
331 ntp->net = ntp->dest_addr.sin_addr;
334 ntp->dest_addr.sin_port = port;
336 for (nt = nets; nt; nt = nt->next) {
337 if (ntp->net.s_addr == htonl(nt->net))
340 if ((nflag && !nt) || (iflag && nt))
344 if (nettab == NULL) {
353 (void) free((char *)ntp);
355 errx(1, "no network usable");
357 /* microseconds to delay before responding to a broadcast */
358 delay1 = casual(1, 100*1000);
360 /* election timer delay in secs. */
361 delay2 = casual(MINTOUT, MAXTOUT);
368 openlog("timed", LOG_CONS|LOG_PID, LOG_DAEMON);
371 * keep returning here
373 ret = setjmp(jmpenv);
374 savefromnet = fromnet;
385 /* Just lost our master */
387 slavenet->status = election(slavenet);
388 if (!slavenet || slavenet->status == MASTER) {
392 makeslave(slavenet); /* prune extras */
397 /* Just been told to quit */
399 pickslavenet(savefromnet);
404 if (!(status & MASTER) && sock_raw != -1) {
405 /* sock_raw is not being used now */
406 (void)close(sock_raw);
410 if (status == MASTER)
416 if (sock_raw != -1) {
417 (void)close(sock_raw);
422 /* we just lost our master or were told to quit */
425 for (ntp = nettab; ntp != NULL; ntp = ntp->next) {
426 if (ntp->status == MASTER)
428 ntp->status = NOMASTER;
445 "usage: timed [-dtM] [-i net|-n net] [-F host1 host2 ...] [-G netgp]\n");
448 "usage: timed [-dtM] [-i net|-n net] [-F host1 host2 ...]\n");
454 * suppress an upstart, untrustworthy, self-appointed master
457 suppress(addr, name,net)
458 struct sockaddr_in *addr;
462 struct sockaddr_in tgt;
463 char tname[MAXHOSTNAMELEN];
465 static struct timeval wait;
468 fprintf(fd, "suppress: %s\n", name);
470 (void)strcpy(tname, name);
472 while (0 != readmsg(TSP_ANY, ANYADDR, &wait, net)) {
474 fprintf(fd, "suppress:\tdiscarded packet from %s\n",
478 syslog(LOG_NOTICE, "suppressing false master %s", tname);
479 msg.tsp_type = TSP_QUIT;
480 (void)strcpy(msg.tsp_name, hostname);
481 (void)acksend(&msg, &tgt, tname, TSP_ACK, 0, 1);
488 struct tsp resp, conflict, *answer;
489 struct timeval ntime;
490 char mastername[MAXHOSTNAMELEN];
491 struct sockaddr_in masteraddr;
496 /* look for master */
497 resp.tsp_type = TSP_MASTERREQ;
498 (void)strcpy(resp.tsp_name, hostname);
499 answer = acksend(&resp, &ntp->dest_addr, ANYADDR,
500 TSP_MASTERACK, ntp, 0);
501 if (answer != 0 && !good_host_name(answer->tsp_name)) {
502 suppress(&from, answer->tsp_name, ntp);
503 ntp->status = NOMASTER;
508 * Various conditions can cause conflict: races between
509 * two just started timedaemons when no master is
510 * present, or timedaemons started during an election.
511 * A conservative approach is taken. Give up and became a
512 * slave, postponing election of a master until first
515 ntime.tv_sec = ntime.tv_usec = 0;
516 answer = readmsg(TSP_MASTERREQ, ANYADDR, &ntime, ntp);
518 if (!good_host_name(answer->tsp_name)) {
519 suppress(&from, answer->tsp_name, ntp);
520 ntp->status = NOMASTER;
525 ntime.tv_sec = ntime.tv_usec = 0;
526 answer = readmsg(TSP_MASTERUP, ANYADDR, &ntime, ntp);
528 if (!good_host_name(answer->tsp_name)) {
529 suppress(&from, answer->tsp_name, ntp);
530 ntp->status = NOMASTER;
535 ntime.tv_sec = ntime.tv_usec = 0;
536 answer = readmsg(TSP_ELECTION, ANYADDR, &ntime, ntp);
538 if (!good_host_name(answer->tsp_name)) {
539 suppress(&from, answer->tsp_name, ntp);
540 ntp->status = NOMASTER;
546 ntp->status = MASTER;
548 ntp->status = NOMASTER;
553 (void)strcpy(mastername, answer->tsp_name);
557 * If network has been partitioned, there might be other
558 * masters; tell the one we have just acknowledged that
559 * it has to gain control over the others.
562 ntime.tv_usec = 300000;
563 answer = readmsg(TSP_MASTERACK, ANYADDR, &ntime, ntp);
565 * checking also not to send CONFLICT to ack'ed master
566 * due to duplicated MASTERACKs
568 if (answer != NULL &&
569 strcmp(answer->tsp_name, mastername) != 0) {
570 conflict.tsp_type = TSP_CONFLICT;
571 (void)strcpy(conflict.tsp_name, hostname);
572 if (!acksend(&conflict, &masteraddr, mastername,
575 "error on sending TSP_CONFLICT");
581 * based on the current network configuration, set the status, and count
590 nmasternets = nslavenets = nnets = nignorednets = 0;
592 fprintf(fd, "Net status:\n");
593 for (ntp = nettab; ntp != NULL; ntp = ntp->next) {
594 switch ((int)ntp->status) {
607 fprintf(fd, "\t%-16s", inet_ntoa(ntp->net));
608 switch ((int)ntp->status) {
610 fprintf(fd, "NOMASTER\n");
613 fprintf(fd, "MASTER\n");
616 fprintf(fd, "SLAVE\n");
619 fprintf(fd, "IGNORE\n");
622 fprintf(fd, "invalid state %d\n",
628 status |= ntp->status;
633 "\tnets=%d masters=%d slaves=%d ignored=%d delay2=%ld\n",
634 nnets, nmasternets, nslavenets, nignorednets, delay2);
641 register struct netinfo *ntp;
643 for (ntp = nettab; ntp != NULL; ntp = ntp->next) {
644 if (ntp->status == SLAVE && ntp != net)
645 ntp->status = IGNORE;
651 * Try to become master over ignored nets..
656 register struct netinfo *ntp;
658 for (ntp = nettab; ntp != NULL; ntp = ntp->next) {
659 if (!Mflag && ntp->status == SLAVE)
662 if (ntp->status == IGNORE || ntp->status == NOMASTER) {
664 if (!Mflag && ntp->status == SLAVE)
671 * choose a good network on which to be a slave
672 * The ignored networks must have already been checked.
673 * Take a hint about for a good network.
679 if (slavenet != 0 && slavenet->status == SLAVE) {
680 makeslave(slavenet); /* prune extras */
684 if (ntp == 0 || ntp->status != SLAVE) {
685 for (ntp = nettab; ntp != 0; ntp = ntp->next) {
686 if (ntp->status == SLAVE)
694 * returns a random number in the range [inf, sup]
702 value = ((double)(random() & 0x7fffffff)) / (0x7fffffff*1.0);
703 return(inf + (sup - inf)*value);
712 (void)gettimeofday(&tv, (struct timezone *)0);
714 return (ctime(&tv_sec));
721 register struct nets **netlist = &nets;
724 netlist = &((*netlist)->next);
725 *netlist = (struct nets *)malloc(sizeof **netlist);
727 errx(1, "malloc failed");
728 bzero((char *)*netlist, sizeof(**netlist));
729 (*netlist)->name = name;
732 /* note a host as trustworthy */
734 add_good_host(name, perm)
736 int perm; /* 1=not part of the netgroup */
738 register struct goodhost *ghp;
739 register struct hostent *hentp;
741 ghp = (struct goodhost*)malloc(sizeof(*ghp));
743 syslog(LOG_ERR, "malloc failed");
747 bzero((char*)ghp, sizeof(*ghp));
748 (void)strncpy(&ghp->name[0], name, sizeof(ghp->name));
749 ghp->next = goodhosts;
753 hentp = gethostbyname(name);
754 if (0 == hentp && perm)
755 warnx("unknown host %s", name);
759 /* update our image of the net-group of trustworthy hosts
765 # define NG_DELAY (30*60*CLK_TCK) /* 30 minutes */
766 static unsigned long last_update = -NG_DELAY;
767 unsigned long new_update;
768 struct goodhost *ghp, **ghpp;
771 char *mach, *usr, *dom;
776 /* if no netgroup, then we are finished */
777 if (goodgroup == 0 || !Mflag)
780 /* Do not chatter with the netgroup master too often.
782 new_update = times(&tm);
783 if (new_update < last_update + NG_DELAY
786 last_update = new_update;
788 /* forget the old temporary entries */
790 while (0 != (ghp = *ghpp)) {
800 /* quit now if we are not one of the trusted masters
802 if (!innetgr(goodgroup, &hostname[0], 0,0)) {
804 (void)fprintf(fd, "get_goodgroup: %s not in %s\n",
805 &hostname[0], goodgroup);
809 (void)fprintf(fd, "get_goodgroup: %s in %s\n",
810 &hostname[0], goodgroup);
812 /* mark the entire netgroup as trusted */
813 (void)setnetgrent(goodgroup);
814 while (getnetgrent(&mach,&usr,&dom)) {
816 add_good_host(mach,0);
820 /* update list of slaves */
821 for (htp = self.l_fwd; htp != &self; htp = htp->l_fwd) {
822 htp->good = good_host_name(&htp->name[0]);
828 /* see if a machine is trustworthy
830 int /* 1=trust hp to change our date */
834 register struct goodhost *ghp = goodhosts;
837 if (!ghp || !Mflag) /* trust everyone if no one named */
842 if (c == ghp->name[0]
843 && !strcasecmp(name, ghp->name))
844 return 1; /* found him, so say so */
845 } while (0 != (ghp = ghp->next));
847 if (!strcasecmp(name,hostname)) /* trust ourself */
850 return 0; /* did not find him */