11553Srgrimes/*-
21553Srgrimes * Copyright (c) 1985, 1993
31553Srgrimes *	The Regents of the University of California.  All rights reserved.
41553Srgrimes *
51553Srgrimes * Redistribution and use in source and binary forms, with or without
61553Srgrimes * modification, are permitted provided that the following conditions
71553Srgrimes * are met:
81553Srgrimes * 1. Redistributions of source code must retain the above copyright
91553Srgrimes *    notice, this list of conditions and the following disclaimer.
101553Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
111553Srgrimes *    notice, this list of conditions and the following disclaimer in the
121553Srgrimes *    documentation and/or other materials provided with the distribution.
131553Srgrimes * 4. Neither the name of the University nor the names of its contributors
141553Srgrimes *    may be used to endorse or promote products derived from this software
151553Srgrimes *    without specific prior written permission.
161553Srgrimes *
171553Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
181553Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
191553Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
201553Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
211553Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
221553Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
231553Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
241553Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
251553Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
261553Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
271553Srgrimes * SUCH DAMAGE.
281553Srgrimes */
291553Srgrimes
301553Srgrimes#ifndef lint
3130642Scharnierstatic const char copyright[] =
321553Srgrimes"@(#) Copyright (c) 1985, 1993\n\
331553Srgrimes	The Regents of the University of California.  All rights reserved.\n";
341553Srgrimes#endif /* not lint */
351553Srgrimes
36117278Scharnier#if 0
371553Srgrimes#ifndef lint
381553Srgrimesstatic char sccsid[] = "@(#)timed.c	8.1 (Berkeley) 6/6/93";
39117278Scharnier#endif /* not lint */
4030642Scharnier#endif
411553Srgrimes
42117278Scharnier#include <sys/cdefs.h>
43117278Scharnier__FBSDID("$FreeBSD$");
44117278Scharnier
451553Srgrimes#define TSPTYPES
461553Srgrimes#include "globals.h"
471553Srgrimes#include <net/if.h>
481553Srgrimes#include <sys/file.h>
491553Srgrimes#include <sys/ioctl.h>
501553Srgrimes#include <setjmp.h>
511553Srgrimes#include "pathnames.h"
521553Srgrimes#include <math.h>
531553Srgrimes#include <sys/types.h>
541553Srgrimes#include <sys/times.h>
551553Srgrimes
561553Srgrimesint trace = 0;
571553Srgrimesint sock, sock_raw = -1;
581553Srgrimesint status = 0;
591553Srgrimesu_short sequence;			/* sequence number */
601553Srgrimeslong delay1;
611553Srgrimeslong delay2;
621553Srgrimes
631553Srgrimesint nslavenets;				/* nets were I could be a slave */
641553Srgrimesint nmasternets;			/* nets were I could be a master */
651553Srgrimesint nignorednets;			/* ignored nets */
661553Srgrimesint nnets;				/* nets I am connected to */
671553Srgrimes
681553SrgrimesFILE *fd;				/* trace file FD */
691553Srgrimes
701553Srgrimesjmp_buf jmpenv;
711553Srgrimes
721553Srgrimesstruct netinfo *nettab = 0;
731553Srgrimesstruct netinfo *slavenet;
741553Srgrimesint Mflag;
751553Srgrimesint justquit = 0;
761553Srgrimesint debug;
771553Srgrimes
781553Srgrimesstatic struct nets {
791553Srgrimes	char	*name;
801553Srgrimes	long	net;
811553Srgrimes	struct nets *next;
821553Srgrimes} *nets = 0;
831553Srgrimes
841553Srgrimesstruct hosttbl hosttbl[NHOSTS+1];	/* known hosts */
851553Srgrimes
861553Srgrimesstatic struct goodhost {		/* hosts that we trust */
8730872Scharnier	char	name[MAXHOSTNAMELEN];
881553Srgrimes	struct goodhost *next;
891553Srgrimes	char	perm;
901553Srgrimes} *goodhosts;
911553Srgrimes
921553Srgrimesstatic char *goodgroup;			/* net group of trusted hosts */
93117278Scharnierstatic void checkignorednets(void);
94117278Scharnierstatic void pickslavenet(struct netinfo *);
95117278Scharnierstatic void add_good_host(char *, int);
96117278Scharnierstatic void usage(void);
971553Srgrimes
981553Srgrimes/*
991553Srgrimes * The timedaemons synchronize the clocks of hosts in a local area network.
1001553Srgrimes * One daemon runs as master, all the others as slaves. The master
1011553Srgrimes * performs the task of computing clock differences and sends correction
1021553Srgrimes * values to the slaves.
1031553Srgrimes * Slaves start an election to choose a new master when the latter disappears
1041553Srgrimes * because of a machine crash, network partition, or when killed.
1051553Srgrimes * A resolution protocol is used to kill all but one of the masters
1061553Srgrimes * that happen to exist in segments of a partitioned network when the
1071553Srgrimes * network partition is fixed.
1081553Srgrimes *
1091553Srgrimes * Authors: Riccardo Gusella & Stefano Zatti
1101553Srgrimes *
1111553Srgrimes * overhauled at Silicon Graphics
1121553Srgrimes */
1131553Srgrimesint
1141553Srgrimesmain(argc, argv)
1151553Srgrimes	int argc;
1161553Srgrimes	char *argv[];
1171553Srgrimes{
1181553Srgrimes	int on;
1191553Srgrimes	int ret;
1201553Srgrimes	int nflag, iflag;
1211553Srgrimes	struct timeval ntime;
1221553Srgrimes	struct servent *srvp;
1231553Srgrimes	char buf[BUFSIZ], *cp, *cplim;
1241553Srgrimes	struct ifconf ifc;
1251553Srgrimes	struct ifreq ifreq, ifreqf, *ifr;
1261553Srgrimes	register struct netinfo *ntp;
1271553Srgrimes	struct netinfo *ntip;
1281553Srgrimes	struct netinfo *savefromnet;
1291553Srgrimes	struct netent *nentp;
1301553Srgrimes	struct nets *nt;
1311553Srgrimes	struct sockaddr_in server;
1321553Srgrimes	u_short port;
133179485Simp	int c;
1341553Srgrimes
1351553Srgrimes#ifdef lint
1361553Srgrimes	ntip = NULL;
1371553Srgrimes#endif
1381553Srgrimes
1391553Srgrimes	on = 1;
1401553Srgrimes	nflag = OFF;
1411553Srgrimes	iflag = OFF;
1421553Srgrimes
1431553Srgrimes
1441553Srgrimes	opterr = 0;
14524428Simp	while ((c = getopt(argc, argv, "Mtdn:i:F:G:P:")) != -1) {
1461553Srgrimes		switch (c) {
1471553Srgrimes		case 'M':
1481553Srgrimes			Mflag = 1;
1491553Srgrimes			break;
1501553Srgrimes
1511553Srgrimes		case 't':
1521553Srgrimes			trace = 1;
1531553Srgrimes			break;
1541553Srgrimes
1551553Srgrimes		case 'n':
1561553Srgrimes			if (iflag) {
15730642Scharnier				errx(1, "-i and -n make no sense together");
1581553Srgrimes			} else {
1591553Srgrimes				nflag = ON;
1601553Srgrimes				addnetname(optarg);
1611553Srgrimes			}
1621553Srgrimes			break;
1631553Srgrimes
1641553Srgrimes		case 'i':
1651553Srgrimes			if (nflag) {
16630642Scharnier				errx(1, "-i and -n make no sense together");
1671553Srgrimes			} else {
1681553Srgrimes				iflag = ON;
1691553Srgrimes				addnetname(optarg);
1701553Srgrimes			}
1711553Srgrimes			break;
1721553Srgrimes
1731553Srgrimes		case 'F':
1741553Srgrimes			add_good_host(optarg,1);
1751553Srgrimes			while (optind < argc && argv[optind][0] != '-')
1761553Srgrimes				add_good_host(argv[optind++], 1);
1771553Srgrimes			break;
1781553Srgrimes
1791553Srgrimes		case 'd':
1801553Srgrimes			debug = 1;
1811553Srgrimes			break;
1821553Srgrimes		case 'G':
18330642Scharnier			if (goodgroup != 0)
18430642Scharnier				errx(1, "only one net group");
1851553Srgrimes			goodgroup = optarg;
1861553Srgrimes			break;
1871553Srgrimes
1881553Srgrimes		default:
18930642Scharnier			usage();
1901553Srgrimes			break;
1911553Srgrimes		}
1921553Srgrimes	}
19330642Scharnier	if (optind < argc)
19430642Scharnier		usage();
1951553Srgrimes
1961553Srgrimes	/* If we care about which machine is the master, then we must
1971553Srgrimes	 *	be willing to be a master
1981553Srgrimes	 */
1991553Srgrimes	if (0 != goodgroup || 0 != goodhosts)
2001553Srgrimes		Mflag = 1;
2011553Srgrimes
20230642Scharnier	if (gethostname(hostname, sizeof(hostname) - 1) < 0)
20330642Scharnier		err(1, "gethostname");
2041553Srgrimes	self.l_bak = &self;
2051553Srgrimes	self.l_fwd = &self;
2061553Srgrimes	self.h_bak = &self;
2071553Srgrimes	self.h_fwd = &self;
2081553Srgrimes	self.head = 1;
2091553Srgrimes	self.good = 1;
2101553Srgrimes
2111553Srgrimes	if (goodhosts != 0)		/* trust ourself */
2121553Srgrimes		add_good_host(hostname,1);
2131553Srgrimes
2141553Srgrimes	srvp = getservbyname("timed", "udp");
21530642Scharnier	if (srvp == 0)
216117278Scharnier		errx(1, "timed/udp: unknown service");
2171553Srgrimes	port = srvp->s_port;
2188532Sdg	bzero(&server, sizeof(struct sockaddr_in));
2191553Srgrimes	server.sin_port = srvp->s_port;
2201553Srgrimes	server.sin_family = AF_INET;
2211553Srgrimes	sock = socket(AF_INET, SOCK_DGRAM, 0);
22230642Scharnier	if (sock < 0)
22330642Scharnier		err(1, "socket");
2241553Srgrimes	if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&on,
22530642Scharnier							sizeof(on)) < 0)
22630642Scharnier		err(1, "setsockopt");
2271553Srgrimes	if (bind(sock, (struct sockaddr*)&server, sizeof(server))) {
2281553Srgrimes		if (errno == EADDRINUSE)
22930642Scharnier			warnx("time daemon already running");
2301553Srgrimes		else
23130642Scharnier			warn("bind");
2321553Srgrimes		exit(1);
2331553Srgrimes	}
2341553Srgrimes
2351553Srgrimes	/* choose a unique seed for random number generation */
2361553Srgrimes	(void)gettimeofday(&ntime, 0);
2371553Srgrimes	srandom(ntime.tv_sec + ntime.tv_usec);
2381553Srgrimes
2391553Srgrimes	sequence = random();     /* initial seq number */
2401553Srgrimes
2411553Srgrimes	/* rounds kernel variable time to multiple of 5 ms. */
2421553Srgrimes	ntime.tv_sec = 0;
2431553Srgrimes	ntime.tv_usec = -((ntime.tv_usec/1000) % 5) * 1000;
2441553Srgrimes	(void)adjtime(&ntime, (struct timeval *)0);
2451553Srgrimes
2461553Srgrimes	for (nt = nets; nt; nt = nt->next) {
2471553Srgrimes		nentp = getnetbyname(nt->name);
2481553Srgrimes		if (nentp == 0) {
2491553Srgrimes			nt->net = inet_network(nt->name);
2501553Srgrimes			if (nt->net != INADDR_NONE)
2511553Srgrimes				nentp = getnetbyaddr(nt->net, AF_INET);
2521553Srgrimes		}
2531553Srgrimes		if (nentp != 0) {
2541553Srgrimes			nt->net = nentp->n_net;
2551553Srgrimes		} else if (nt->net == INADDR_NONE) {
25630642Scharnier			errx(1, "unknown net %s", nt->name);
2571553Srgrimes		} else if (nt->net == INADDR_ANY) {
25830642Scharnier			errx(1, "bad net %s", nt->name);
2591553Srgrimes		} else {
26030642Scharnier			warnx("warning: %s unknown in /etc/networks",
2611553Srgrimes				nt->name);
2621553Srgrimes		}
2631553Srgrimes
2641553Srgrimes		if (0 == (nt->net & 0xff000000))
2651553Srgrimes		    nt->net <<= 8;
2661553Srgrimes		if (0 == (nt->net & 0xff000000))
2671553Srgrimes		    nt->net <<= 8;
2681553Srgrimes		if (0 == (nt->net & 0xff000000))
2691553Srgrimes		    nt->net <<= 8;
2701553Srgrimes	}
2711553Srgrimes	ifc.ifc_len = sizeof(buf);
2721553Srgrimes	ifc.ifc_buf = buf;
27330642Scharnier	if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0)
27430642Scharnier		err(1, "get interface configuration");
2751553Srgrimes	ntp = NULL;
2761553Srgrimes#define size(p)	max((p).sa_len, sizeof(p))
2771553Srgrimes	cplim = buf + ifc.ifc_len; /*skip over if's with big ifr_addr's */
2781553Srgrimes	for (cp = buf; cp < cplim;
2791553Srgrimes			cp += sizeof (ifr->ifr_name) + size(ifr->ifr_addr)) {
2801553Srgrimes		ifr = (struct ifreq *)cp;
2811553Srgrimes		if (ifr->ifr_addr.sa_family != AF_INET)
2821553Srgrimes			continue;
2831553Srgrimes		if (!ntp)
2841553Srgrimes			ntp = (struct netinfo*)malloc(sizeof(struct netinfo));
2851553Srgrimes		bzero(ntp,sizeof(*ntp));
2861553Srgrimes		ntp->my_addr=((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr;
2871553Srgrimes		ntp->status = NOMASTER;
2881553Srgrimes		ifreq = *ifr;
2891553Srgrimes		ifreqf = *ifr;
2901553Srgrimes
2911553Srgrimes		if (ioctl(sock, SIOCGIFFLAGS, (char *)&ifreqf) < 0) {
29230642Scharnier			warn("get interface flags");
2931553Srgrimes			continue;
2941553Srgrimes		}
2951553Srgrimes		if ((ifreqf.ifr_flags & IFF_UP) == 0)
2961553Srgrimes			continue;
2971553Srgrimes		if ((ifreqf.ifr_flags & IFF_BROADCAST) == 0 &&
2981553Srgrimes		    (ifreqf.ifr_flags & IFF_POINTOPOINT) == 0) {
2991553Srgrimes			continue;
3001553Srgrimes		}
3011553Srgrimes
3021553Srgrimes
3031553Srgrimes		if (ioctl(sock, SIOCGIFNETMASK, (char *)&ifreq) < 0) {
30430642Scharnier			warn("get netmask");
3051553Srgrimes			continue;
3061553Srgrimes		}
3071553Srgrimes		ntp->mask = ((struct sockaddr_in *)
3081553Srgrimes			&ifreq.ifr_addr)->sin_addr.s_addr;
3091553Srgrimes
3101553Srgrimes		if (ifreqf.ifr_flags & IFF_BROADCAST) {
3111553Srgrimes			if (ioctl(sock, SIOCGIFBRDADDR, (char *)&ifreq) < 0) {
31230642Scharnier				warn("get broadaddr");
3131553Srgrimes				continue;
3141553Srgrimes			}
3151553Srgrimes			ntp->dest_addr = *(struct sockaddr_in *)&ifreq.ifr_broadaddr;
3161553Srgrimes			/* What if the broadcast address is all ones?
3171553Srgrimes			 * So we cannot just mask ntp->dest_addr.  */
3181553Srgrimes			ntp->net = ntp->my_addr;
3191553Srgrimes			ntp->net.s_addr &= ntp->mask;
3201553Srgrimes		} else {
3211553Srgrimes			if (ioctl(sock, SIOCGIFDSTADDR,
3221553Srgrimes						(char *)&ifreq) < 0) {
32330642Scharnier				warn("get destaddr");
3241553Srgrimes				continue;
3251553Srgrimes			}
3261553Srgrimes			ntp->dest_addr = *(struct sockaddr_in *)&ifreq.ifr_dstaddr;
3271553Srgrimes			ntp->net = ntp->dest_addr.sin_addr;
3281553Srgrimes		}
3291553Srgrimes
3301553Srgrimes		ntp->dest_addr.sin_port = port;
3311553Srgrimes
3321553Srgrimes		for (nt = nets; nt; nt = nt->next) {
33328547Sjlemon			if (ntp->net.s_addr == htonl(nt->net))
3341553Srgrimes				break;
3351553Srgrimes		}
33630642Scharnier		if ((nflag && !nt) || (iflag && nt))
3371553Srgrimes			continue;
3381553Srgrimes
3391553Srgrimes		ntp->next = NULL;
3401553Srgrimes		if (nettab == NULL) {
3411553Srgrimes			nettab = ntp;
3421553Srgrimes		} else {
3431553Srgrimes			ntip->next = ntp;
3441553Srgrimes		}
3451553Srgrimes		ntip = ntp;
3461553Srgrimes		ntp = NULL;
3471553Srgrimes	}
3481553Srgrimes	if (ntp)
3491553Srgrimes		(void) free((char *)ntp);
35030642Scharnier	if (nettab == NULL)
35130642Scharnier		errx(1, "no network usable");
3521553Srgrimes
3531553Srgrimes	/* microseconds to delay before responding to a broadcast */
3541553Srgrimes	delay1 = casual(1, 100*1000);
3551553Srgrimes
3561553Srgrimes	/* election timer delay in secs. */
3571553Srgrimes	delay2 = casual(MINTOUT, MAXTOUT);
3581553Srgrimes
3591553Srgrimes	if (!debug)
3601553Srgrimes		daemon(debug, 0);
3611553Srgrimes
3621553Srgrimes	if (trace)
3631553Srgrimes		traceon();
3641553Srgrimes	openlog("timed", LOG_CONS|LOG_PID, LOG_DAEMON);
3651553Srgrimes
3661553Srgrimes	/*
3671553Srgrimes	 * keep returning here
3681553Srgrimes	 */
3691553Srgrimes	ret = setjmp(jmpenv);
3701553Srgrimes	savefromnet = fromnet;
3711553Srgrimes	setstatus();
3721553Srgrimes
3731553Srgrimes	if (Mflag) {
3741553Srgrimes		switch (ret) {
3751553Srgrimes
3761553Srgrimes		case 0:
3771553Srgrimes			checkignorednets();
3781553Srgrimes			pickslavenet(0);
3791553Srgrimes			break;
3801553Srgrimes		case 1:
3811553Srgrimes			/* Just lost our master */
3821553Srgrimes			if (slavenet != 0)
3831553Srgrimes				slavenet->status = election(slavenet);
3841553Srgrimes			if (!slavenet || slavenet->status == MASTER) {
3851553Srgrimes				checkignorednets();
3861553Srgrimes				pickslavenet(0);
3871553Srgrimes			} else {
3881553Srgrimes				makeslave(slavenet);	/* prune extras */
3891553Srgrimes			}
3901553Srgrimes			break;
3911553Srgrimes
3921553Srgrimes		case 2:
3931553Srgrimes			/* Just been told to quit */
3941553Srgrimes			justquit = 1;
3951553Srgrimes			pickslavenet(savefromnet);
3961553Srgrimes			break;
3971553Srgrimes		}
3981553Srgrimes
3991553Srgrimes		setstatus();
4001553Srgrimes		if (!(status & MASTER) && sock_raw != -1) {
4011553Srgrimes			/* sock_raw is not being used now */
4021553Srgrimes			(void)close(sock_raw);
4031553Srgrimes			sock_raw = -1;
4041553Srgrimes		}
4051553Srgrimes
4061553Srgrimes		if (status == MASTER)
4071553Srgrimes			master();
4081553Srgrimes		else
4091553Srgrimes			slave();
4101553Srgrimes
4111553Srgrimes	} else {
4121553Srgrimes		if (sock_raw != -1) {
4131553Srgrimes			(void)close(sock_raw);
4141553Srgrimes			sock_raw = -1;
4151553Srgrimes		}
4161553Srgrimes
4171553Srgrimes		if (ret) {
4181553Srgrimes			/* we just lost our master or were told to quit */
4191553Srgrimes			justquit = 1;
4201553Srgrimes		}
4211553Srgrimes		for (ntp = nettab; ntp != NULL; ntp = ntp->next) {
422240626Skevlo			if (ntp->status == MASTER) {
4231553Srgrimes				rmnetmachs(ntp);
4241553Srgrimes				ntp->status = NOMASTER;
425240626Skevlo			}
4261553Srgrimes		}
4271553Srgrimes		checkignorednets();
4281553Srgrimes		pickslavenet(0);
4291553Srgrimes		setstatus();
4301553Srgrimes
4311553Srgrimes		slave();
4321553Srgrimes	}
4331553Srgrimes	/* NOTREACHED */
4341553Srgrimes	return(0);
4351553Srgrimes}
4361553Srgrimes
43730642Scharnierstatic void
43830642Scharnierusage()
43930642Scharnier{
44030642Scharnier#ifdef HAVENIS
44130642Scharnier	fprintf(stderr,
44230642Scharnier"usage: timed [-dtM] [-i net|-n net] [-F host1 host2 ...] [-G netgp]\n");
44330642Scharnier#else
44430642Scharnier	fprintf(stderr,
44530642Scharnier"usage: timed [-dtM] [-i net|-n net] [-F host1 host2 ...]\n");
44630642Scharnier#endif /* HAVENIS */
44730642Scharnier	exit(1);
44830642Scharnier}
44930642Scharnier
4501553Srgrimes/*
4511553Srgrimes * suppress an upstart, untrustworthy, self-appointed master
4521553Srgrimes */
4531553Srgrimesvoid
4541553Srgrimessuppress(addr, name,net)
4551553Srgrimes	struct sockaddr_in *addr;
4561553Srgrimes	char *name;
4571553Srgrimes	struct netinfo *net;
4581553Srgrimes{
4591553Srgrimes	struct sockaddr_in tgt;
4601553Srgrimes	char tname[MAXHOSTNAMELEN];
4611553Srgrimes	struct tsp msg;
4621553Srgrimes	static struct timeval wait;
4631553Srgrimes
4641553Srgrimes	if (trace)
4651553Srgrimes		fprintf(fd, "suppress: %s\n", name);
4661553Srgrimes	tgt = *addr;
46730830Scharnier	(void)strcpy(tname, name);
4681553Srgrimes
4691553Srgrimes	while (0 != readmsg(TSP_ANY, ANYADDR, &wait, net)) {
4701553Srgrimes		if (trace)
4711553Srgrimes			fprintf(fd, "suppress:\tdiscarded packet from %s\n",
4721553Srgrimes				    name);
4731553Srgrimes	}
4741553Srgrimes
4751553Srgrimes	syslog(LOG_NOTICE, "suppressing false master %s", tname);
4761553Srgrimes	msg.tsp_type = TSP_QUIT;
47730830Scharnier	(void)strcpy(msg.tsp_name, hostname);
4781553Srgrimes	(void)acksend(&msg, &tgt, tname, TSP_ACK, 0, 1);
4791553Srgrimes}
4801553Srgrimes
4811553Srgrimesvoid
4821553Srgrimeslookformaster(ntp)
4831553Srgrimes	struct netinfo *ntp;
4841553Srgrimes{
4851553Srgrimes	struct tsp resp, conflict, *answer;
4861553Srgrimes	struct timeval ntime;
4871553Srgrimes	char mastername[MAXHOSTNAMELEN];
4881553Srgrimes	struct sockaddr_in masteraddr;
4891553Srgrimes
4901553Srgrimes	get_goodgroup(0);
4911553Srgrimes	ntp->status = SLAVE;
4921553Srgrimes
4931553Srgrimes	/* look for master */
4941553Srgrimes	resp.tsp_type = TSP_MASTERREQ;
49530830Scharnier	(void)strcpy(resp.tsp_name, hostname);
4961553Srgrimes	answer = acksend(&resp, &ntp->dest_addr, ANYADDR,
4971553Srgrimes			 TSP_MASTERACK, ntp, 0);
4981553Srgrimes	if (answer != 0 && !good_host_name(answer->tsp_name)) {
4991553Srgrimes		suppress(&from, answer->tsp_name, ntp);
5001553Srgrimes		ntp->status = NOMASTER;
5011553Srgrimes		answer = 0;
5021553Srgrimes	}
5031553Srgrimes	if (answer == 0) {
5041553Srgrimes		/*
5051553Srgrimes		 * Various conditions can cause conflict: races between
5061553Srgrimes		 * two just started timedaemons when no master is
5071553Srgrimes		 * present, or timedaemons started during an election.
5081553Srgrimes		 * A conservative approach is taken.  Give up and became a
5091553Srgrimes		 * slave, postponing election of a master until first
5101553Srgrimes		 * timer expires.
5111553Srgrimes		 */
5121553Srgrimes		ntime.tv_sec = ntime.tv_usec = 0;
5131553Srgrimes		answer = readmsg(TSP_MASTERREQ, ANYADDR, &ntime, ntp);
5141553Srgrimes		if (answer != 0) {
5151553Srgrimes			if (!good_host_name(answer->tsp_name)) {
5161553Srgrimes				suppress(&from, answer->tsp_name, ntp);
5171553Srgrimes				ntp->status = NOMASTER;
5181553Srgrimes			}
5191553Srgrimes			return;
5201553Srgrimes		}
5211553Srgrimes
5221553Srgrimes		ntime.tv_sec = ntime.tv_usec = 0;
5231553Srgrimes		answer = readmsg(TSP_MASTERUP, ANYADDR, &ntime, ntp);
5241553Srgrimes		if (answer != 0) {
5251553Srgrimes			if (!good_host_name(answer->tsp_name)) {
5261553Srgrimes				suppress(&from, answer->tsp_name, ntp);
5271553Srgrimes				ntp->status = NOMASTER;
5281553Srgrimes			}
5291553Srgrimes			return;
5301553Srgrimes		}
5311553Srgrimes
5321553Srgrimes		ntime.tv_sec = ntime.tv_usec = 0;
5331553Srgrimes		answer = readmsg(TSP_ELECTION, ANYADDR, &ntime, ntp);
5341553Srgrimes		if (answer != 0) {
5351553Srgrimes			if (!good_host_name(answer->tsp_name)) {
5361553Srgrimes				suppress(&from, answer->tsp_name, ntp);
5371553Srgrimes				ntp->status = NOMASTER;
5381553Srgrimes			}
5391553Srgrimes			return;
5401553Srgrimes		}
5411553Srgrimes
5421553Srgrimes		if (Mflag)
5431553Srgrimes			ntp->status = MASTER;
5441553Srgrimes		else
5451553Srgrimes			ntp->status = NOMASTER;
5461553Srgrimes		return;
5471553Srgrimes	}
5481553Srgrimes
5491553Srgrimes	ntp->status = SLAVE;
55030830Scharnier	(void)strcpy(mastername, answer->tsp_name);
5511553Srgrimes	masteraddr = from;
5521553Srgrimes
5531553Srgrimes	/*
5541553Srgrimes	 * If network has been partitioned, there might be other
5551553Srgrimes	 * masters; tell the one we have just acknowledged that
5561553Srgrimes	 * it has to gain control over the others.
5571553Srgrimes	 */
5581553Srgrimes	ntime.tv_sec = 0;
5591553Srgrimes	ntime.tv_usec = 300000;
5601553Srgrimes	answer = readmsg(TSP_MASTERACK, ANYADDR, &ntime, ntp);
5611553Srgrimes	/*
5621553Srgrimes	 * checking also not to send CONFLICT to ack'ed master
5631553Srgrimes	 * due to duplicated MASTERACKs
5641553Srgrimes	 */
5651553Srgrimes	if (answer != NULL &&
5661553Srgrimes	    strcmp(answer->tsp_name, mastername) != 0) {
5671553Srgrimes		conflict.tsp_type = TSP_CONFLICT;
56830830Scharnier		(void)strcpy(conflict.tsp_name, hostname);
5691553Srgrimes		if (!acksend(&conflict, &masteraddr, mastername,
5701553Srgrimes			     TSP_ACK, 0, 0)) {
5711553Srgrimes			syslog(LOG_ERR,
5721553Srgrimes			       "error on sending TSP_CONFLICT");
5731553Srgrimes		}
5741553Srgrimes	}
5751553Srgrimes}
5761553Srgrimes
5771553Srgrimes/*
5781553Srgrimes * based on the current network configuration, set the status, and count
5791553Srgrimes * networks;
5801553Srgrimes */
5811553Srgrimesvoid
5821553Srgrimessetstatus()
5831553Srgrimes{
5841553Srgrimes	struct netinfo *ntp;
5851553Srgrimes
5861553Srgrimes	status = 0;
5871553Srgrimes	nmasternets = nslavenets = nnets = nignorednets = 0;
5881553Srgrimes	if (trace)
5891553Srgrimes		fprintf(fd, "Net status:\n");
5901553Srgrimes	for (ntp = nettab; ntp != NULL; ntp = ntp->next) {
5911553Srgrimes		switch ((int)ntp->status) {
5921553Srgrimes		case MASTER:
5931553Srgrimes			nmasternets++;
5941553Srgrimes			break;
5951553Srgrimes		case SLAVE:
5961553Srgrimes			nslavenets++;
5971553Srgrimes			break;
5981553Srgrimes		case NOMASTER:
5991553Srgrimes		case IGNORE:
6001553Srgrimes			nignorednets++;
6011553Srgrimes			break;
6021553Srgrimes		}
6031553Srgrimes		if (trace) {
6041553Srgrimes			fprintf(fd, "\t%-16s", inet_ntoa(ntp->net));
6051553Srgrimes			switch ((int)ntp->status) {
6061553Srgrimes			case NOMASTER:
6071553Srgrimes				fprintf(fd, "NOMASTER\n");
6081553Srgrimes				break;
6091553Srgrimes			case MASTER:
6101553Srgrimes				fprintf(fd, "MASTER\n");
6111553Srgrimes				break;
6121553Srgrimes			case SLAVE:
6131553Srgrimes				fprintf(fd, "SLAVE\n");
6141553Srgrimes				break;
6151553Srgrimes			case IGNORE:
6161553Srgrimes				fprintf(fd, "IGNORE\n");
6171553Srgrimes				break;
6181553Srgrimes			default:
6191553Srgrimes				fprintf(fd, "invalid state %d\n",
6201553Srgrimes					(int)ntp->status);
6211553Srgrimes				break;
6221553Srgrimes			}
6231553Srgrimes		}
6241553Srgrimes		nnets++;
6251553Srgrimes		status |= ntp->status;
6261553Srgrimes	}
6271553Srgrimes	status &= ~IGNORE;
6281553Srgrimes	if (trace)
6291553Srgrimes		fprintf(fd,
63037268Sbde		    "\tnets=%d masters=%d slaves=%d ignored=%d delay2=%ld\n",
63137268Sbde		    nnets, nmasternets, nslavenets, nignorednets, delay2);
6321553Srgrimes}
6331553Srgrimes
6341553Srgrimesvoid
6351553Srgrimesmakeslave(net)
6361553Srgrimes	struct netinfo *net;
6371553Srgrimes{
6381553Srgrimes	register struct netinfo *ntp;
6391553Srgrimes
6401553Srgrimes	for (ntp = nettab; ntp != NULL; ntp = ntp->next) {
6411553Srgrimes		if (ntp->status == SLAVE && ntp != net)
6421553Srgrimes			ntp->status = IGNORE;
6431553Srgrimes	}
6441553Srgrimes	slavenet = net;
6451553Srgrimes}
6461553Srgrimes
6471553Srgrimes/*
6481553Srgrimes * Try to become master over ignored nets..
6491553Srgrimes */
6501553Srgrimesstatic void
6511553Srgrimescheckignorednets()
6521553Srgrimes{
6531553Srgrimes	register struct netinfo *ntp;
6541553Srgrimes
6551553Srgrimes	for (ntp = nettab; ntp != NULL; ntp = ntp->next) {
6561553Srgrimes		if (!Mflag && ntp->status == SLAVE)
6571553Srgrimes			break;
6581553Srgrimes
6591553Srgrimes		if (ntp->status == IGNORE || ntp->status == NOMASTER) {
6601553Srgrimes			lookformaster(ntp);
6611553Srgrimes			if (!Mflag && ntp->status == SLAVE)
6621553Srgrimes				break;
6631553Srgrimes		}
6641553Srgrimes	}
6651553Srgrimes}
6661553Srgrimes
6671553Srgrimes/*
6681553Srgrimes * choose a good network on which to be a slave
6691553Srgrimes *	The ignored networks must have already been checked.
6701553Srgrimes *	Take a hint about for a good network.
6711553Srgrimes */
6721553Srgrimesstatic void
6731553Srgrimespickslavenet(ntp)
6741553Srgrimes	struct netinfo *ntp;
6751553Srgrimes{
6761553Srgrimes	if (slavenet != 0 && slavenet->status == SLAVE) {
6771553Srgrimes		makeslave(slavenet);		/* prune extras */
6781553Srgrimes		return;
6791553Srgrimes	}
6801553Srgrimes
6811553Srgrimes	if (ntp == 0 || ntp->status != SLAVE) {
6821553Srgrimes		for (ntp = nettab; ntp != 0; ntp = ntp->next) {
6831553Srgrimes			if (ntp->status == SLAVE)
6841553Srgrimes				break;
6851553Srgrimes		}
6861553Srgrimes	}
6871553Srgrimes	makeslave(ntp);
6881553Srgrimes}
6891553Srgrimes
6901553Srgrimes/*
6911553Srgrimes * returns a random number in the range [inf, sup]
6921553Srgrimes */
6931553Srgrimeslong
6941553Srgrimescasual(inf, sup)
6951553Srgrimes	long inf, sup;
6961553Srgrimes{
6971553Srgrimes	double value;
6981553Srgrimes
6991553Srgrimes	value = ((double)(random() & 0x7fffffff)) / (0x7fffffff*1.0);
7001553Srgrimes	return(inf + (sup - inf)*value);
7011553Srgrimes}
7021553Srgrimes
7031553Srgrimeschar *
7041553Srgrimesdate()
7051553Srgrimes{
7061553Srgrimes	struct	timeval tv;
70737268Sbde	time_t	tv_sec;
7081553Srgrimes
7091553Srgrimes	(void)gettimeofday(&tv, (struct timezone *)0);
71037268Sbde	tv_sec = tv.tv_sec;
71137268Sbde	return (ctime(&tv_sec));
7121553Srgrimes}
7131553Srgrimes
7141553Srgrimesvoid
7151553Srgrimesaddnetname(name)
7161553Srgrimes	char *name;
7171553Srgrimes{
7181553Srgrimes	register struct nets **netlist = &nets;
7191553Srgrimes
7201553Srgrimes	while (*netlist)
7211553Srgrimes		netlist = &((*netlist)->next);
7221553Srgrimes	*netlist = (struct nets *)malloc(sizeof **netlist);
72330642Scharnier	if (*netlist == 0)
72430642Scharnier		errx(1, "malloc failed");
7251553Srgrimes	bzero((char *)*netlist, sizeof(**netlist));
7261553Srgrimes	(*netlist)->name = name;
7271553Srgrimes}
7281553Srgrimes
7291553Srgrimes/* note a host as trustworthy */
7301553Srgrimesstatic void
7311553Srgrimesadd_good_host(name, perm)
7321553Srgrimes	char *name;
7331553Srgrimes	int perm;			/* 1=not part of the netgroup */
7341553Srgrimes{
7351553Srgrimes	register struct goodhost *ghp;
7361553Srgrimes	register struct hostent *hentp;
7371553Srgrimes
7381553Srgrimes	ghp = (struct goodhost*)malloc(sizeof(*ghp));
7391553Srgrimes	if (!ghp) {
7401553Srgrimes		syslog(LOG_ERR, "malloc failed");
7411553Srgrimes		exit(1);
7421553Srgrimes	}
7431553Srgrimes
7441553Srgrimes	bzero((char*)ghp, sizeof(*ghp));
7451553Srgrimes	(void)strncpy(&ghp->name[0], name, sizeof(ghp->name));
7461553Srgrimes	ghp->next = goodhosts;
7471553Srgrimes	ghp->perm = perm;
7481553Srgrimes	goodhosts = ghp;
7491553Srgrimes
7501553Srgrimes	hentp = gethostbyname(name);
7511553Srgrimes	if (0 == hentp && perm)
75230642Scharnier		warnx("unknown host %s", name);
7531553Srgrimes}
7541553Srgrimes
7551553Srgrimes
7561553Srgrimes/* update our image of the net-group of trustworthy hosts
7571553Srgrimes */
7581553Srgrimesvoid
7591553Srgrimesget_goodgroup(force)
7601553Srgrimes	int force;
7611553Srgrimes{
7621553Srgrimes# define NG_DELAY (30*60*CLK_TCK)	/* 30 minutes */
7631553Srgrimes	static unsigned long last_update = -NG_DELAY;
7641553Srgrimes	unsigned long new_update;
76530642Scharnier	struct goodhost *ghp, **ghpp;
76630642Scharnier#ifdef HAVENIS
7671553Srgrimes	struct hosttbl *htp;
7681553Srgrimes	char *mach, *usr, *dom;
76930642Scharnier#endif /* HAVENIS */
7701553Srgrimes	struct tms tm;
7711553Srgrimes
7721553Srgrimes
7731553Srgrimes	/* if no netgroup, then we are finished */
7741553Srgrimes	if (goodgroup == 0 || !Mflag)
7751553Srgrimes		return;
7761553Srgrimes
7771553Srgrimes	/* Do not chatter with the netgroup master too often.
7781553Srgrimes	 */
7791553Srgrimes	new_update = times(&tm);
7801553Srgrimes	if (new_update < last_update + NG_DELAY
7811553Srgrimes	    && !force)
7821553Srgrimes		return;
7831553Srgrimes	last_update = new_update;
7841553Srgrimes
7851553Srgrimes	/* forget the old temporary entries */
7861553Srgrimes	ghpp = &goodhosts;
7871553Srgrimes	while (0 != (ghp = *ghpp)) {
7881553Srgrimes		if (!ghp->perm) {
7891553Srgrimes			*ghpp = ghp->next;
7901553Srgrimes			free((char*)ghp);
7911553Srgrimes		} else {
7921553Srgrimes			ghpp = &ghp->next;
7931553Srgrimes		}
7941553Srgrimes	}
7951553Srgrimes
7961553Srgrimes#ifdef HAVENIS
7971553Srgrimes	/* quit now if we are not one of the trusted masters
7981553Srgrimes	 */
7991553Srgrimes	if (!innetgr(goodgroup, &hostname[0], 0,0)) {
8001553Srgrimes		if (trace)
8011553Srgrimes			(void)fprintf(fd, "get_goodgroup: %s not in %s\n",
8021553Srgrimes				      &hostname[0], goodgroup);
8031553Srgrimes		return;
8041553Srgrimes	}
8051553Srgrimes	if (trace)
8061553Srgrimes		(void)fprintf(fd, "get_goodgroup: %s in %s\n",
8071553Srgrimes				  &hostname[0], goodgroup);
8081553Srgrimes
8091553Srgrimes	/* mark the entire netgroup as trusted */
8101553Srgrimes	(void)setnetgrent(goodgroup);
8111553Srgrimes	while (getnetgrent(&mach,&usr,&dom)) {
8121553Srgrimes		if (0 != mach)
8131553Srgrimes			add_good_host(mach,0);
8141553Srgrimes	}
8151553Srgrimes	(void)endnetgrent();
8161553Srgrimes
8171553Srgrimes	/* update list of slaves */
8181553Srgrimes	for (htp = self.l_fwd; htp != &self; htp = htp->l_fwd) {
8191553Srgrimes		htp->good = good_host_name(&htp->name[0]);
8201553Srgrimes	}
8211553Srgrimes#endif /* HAVENIS */
8221553Srgrimes}
8231553Srgrimes
8241553Srgrimes
8251553Srgrimes/* see if a machine is trustworthy
8261553Srgrimes */
8271553Srgrimesint					/* 1=trust hp to change our date */
8281553Srgrimesgood_host_name(name)
8291553Srgrimes	char *name;
8301553Srgrimes{
8311553Srgrimes	register struct goodhost *ghp = goodhosts;
8321553Srgrimes	register char c;
8331553Srgrimes
8341553Srgrimes	if (!ghp || !Mflag)		/* trust everyone if no one named */
8351553Srgrimes		return 1;
8361553Srgrimes
8371553Srgrimes	c = *name;
8381553Srgrimes	do {
8391553Srgrimes		if (c == ghp->name[0]
8401553Srgrimes		    && !strcasecmp(name, ghp->name))
8411553Srgrimes			return 1;	/* found him, so say so */
8421553Srgrimes	} while (0 != (ghp = ghp->next));
8431553Srgrimes
8441553Srgrimes	if (!strcasecmp(name,hostname))	/* trust ourself */
8451553Srgrimes		return 1;
8461553Srgrimes
8471553Srgrimes	return 0;			/* did not find him */
8481553Srgrimes}
849