1/*
2 * Copyright (c) 1983, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
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 * 4. 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.
16 *
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
27 * SUCH DAMAGE.
28 */
29
30#ifndef lint
31__attribute__((__used__))
32static const char copyright[] =
33"@(#) Copyright (c) 1983, 1993\n\
34	The Regents of the University of California.  All rights reserved.\n";
35#endif /* not lint */
36
37#if 0
38#ifndef lint
39static char sccsid[] = "@(#)rwhod.c	8.1 (Berkeley) 6/6/93";
40#endif /* not lint */
41#endif
42
43#include <sys/cdefs.h>
44__FBSDID("$FreeBSD: src/usr.sbin/rwhod/rwhod.c,v 1.23 2005/06/03 17:38:33 ssouhlal Exp $");
45
46#include <sys/param.h>
47#include <sys/socket.h>
48#include <sys/stat.h>
49#include <sys/signal.h>
50#include <sys/ioctl.h>
51#include <sys/sysctl.h>
52
53#include <net/if.h>
54#include <net/if_dl.h>
55#include <netinet/in.h>
56#include <arpa/inet.h>
57#include <protocols/rwhod.h>
58
59#include <ctype.h>
60#include <err.h>
61#include <errno.h>
62#include <fcntl.h>
63#include <netdb.h>
64#include <paths.h>
65#include <stdio.h>
66#include <stdlib.h>
67#include <string.h>
68#include <syslog.h>
69#include <timeconv.h>
70#include <unistd.h>
71#ifdef __APPLE__
72#include <utmpx.h>
73#include <net/route.h>
74#else
75#include <utmp.h>
76#endif
77#include <pwd.h>
78#include <grp.h>
79
80/*
81 * This version of Berkeley's rwhod has been modified to use IP multicast
82 * datagrams, under control of a new command-line option:
83 *
84 *	rwhod -m	causes rwhod to use IP multicast (instead of
85 *			broadcast or unicast) on all interfaces that have
86 *			the IFF_MULTICAST flag set in their "ifnet" structs
87 *			(excluding the loopback interface).  The multicast
88 *			reports are sent with a time-to-live of 1, to prevent
89 *			forwarding beyond the directly-connected subnet(s).
90 *
91 *	rwhod -m <ttl>	causes rwhod to send IP multicast datagrams with a
92 *			time-to-live of <ttl>, via a SINGLE interface rather
93 *			than all interfaces.  <ttl> must be between 0 and
94 *			MAX_MULTICAST_SCOPE, defined below.  Note that "-m 1"
95 *			is different than "-m", in that "-m 1" specifies
96 *			transmission on one interface only.
97 *
98 * When "-m" is used without a <ttl> argument, the program accepts multicast
99 * rwhod reports from all multicast-capable interfaces.  If a <ttl> argument
100 * is given, it accepts multicast reports from only one interface, the one
101 * on which reports are sent (which may be controlled via the host's routing
102 * table).  Regardless of the "-m" option, the program accepts broadcast or
103 * unicast reports from all interfaces.  Thus, this program will hear the
104 * reports of old, non-multicasting rwhods, but, if multicasting is used,
105 * those old rwhods won't hear the reports generated by this program.
106 *
107 *                  -- Steve Deering, Stanford University, February 1989
108 */
109
110#define	UNPRIV_USER		"daemon"
111#define	UNPRIV_GROUP		"daemon"
112
113#define NO_MULTICAST		0	  /* multicast modes */
114#define PER_INTERFACE_MULTICAST	1
115#define SCOPED_MULTICAST	2
116
117#define MAX_MULTICAST_SCOPE	32	  /* "site-wide", by convention */
118
119#define INADDR_WHOD_GROUP (u_long)0xe0000103      /* 224.0.1.3 */
120					  /* (belongs in protocols/rwhod.h) */
121
122int			insecure_mode;
123int			quiet_mode;
124int			iff_flag = IFF_POINTOPOINT;
125int			multicast_mode  = NO_MULTICAST;
126int			multicast_scope;
127struct sockaddr_in	multicast_addr  =
128	{ sizeof multicast_addr, AF_INET, 0, { 0 }, { 0 } };
129
130/*
131 * Alarm interval. Don't forget to change the down time check in ruptime
132 * if this is changed.
133 */
134#define AL_INTERVAL (3 * 60)
135
136char	myname[MAXHOSTNAMELEN];
137
138/*
139 * We communicate with each neighbor in a list constructed at the time we're
140 * started up.  Neighbors are currently directly connected via a hardware
141 * interface.
142 */
143struct	neighbor {
144	struct	neighbor *n_next;
145	char	*n_name;		/* interface name */
146	struct	sockaddr *n_addr;		/* who to send to */
147	int	n_addrlen;		/* size of address */
148	int	n_flags;		/* should forward?, interface flags */
149};
150
151struct	neighbor *neighbors;
152struct	whod mywd;
153struct	servent *sp;
154int	s, utmpf;
155
156#define	WHDRSIZE	(int)(sizeof(mywd) - sizeof(mywd.wd_we))
157
158void	 run_as(uid_t *, gid_t *);
159int	 configure(int);
160void	 getboottime(int);
161void	 onalrm(int);
162void	 quit(const char *);
163void	 rt_xaddrs(caddr_t, caddr_t, struct rt_addrinfo *);
164int	 verify(char *, int);
165static void usage(void);
166#ifdef DEBUG
167char	*interval(int, char *);
168void	 Sendto(int, const void *, size_t, int, const struct sockaddr *, int);
169#define	 sendto Sendto
170#endif
171
172int
173main(int argc, char *argv[])
174{
175	struct sockaddr_in from;
176	struct stat st;
177	char path[64];
178	int on = 1;
179	char *cp;
180	struct sockaddr_in soin;
181	uid_t unpriv_uid;
182	gid_t unpriv_gid;
183
184	if (getuid())
185		errx(1, "not super user");
186
187	run_as(&unpriv_uid, &unpriv_gid);
188
189	argv++; argc--;
190	while (argc > 0 && *argv[0] == '-') {
191		if (strcmp(*argv, "-m") == 0) {
192			if (argc > 1 && isdigit(*(argv + 1)[0])) {
193				argv++, argc--;
194				multicast_mode  = SCOPED_MULTICAST;
195				multicast_scope = atoi(*argv);
196				if (multicast_scope > MAX_MULTICAST_SCOPE)
197					errx(1, "ttl must not exceed %u",
198					MAX_MULTICAST_SCOPE);
199			}
200			else multicast_mode = PER_INTERFACE_MULTICAST;
201		}
202		else if (strcmp(*argv, "-i") == 0)
203			insecure_mode = 1;
204		else if (strcmp(*argv, "-l") == 0)
205			quiet_mode = 1;
206		else if (strcmp(*argv, "-p") == 0)
207			iff_flag = 0;
208		else
209			usage();
210		argv++, argc--;
211	}
212	if (argc > 0)
213		usage();
214#ifndef DEBUG
215	daemon(1, 0);
216#endif
217	(void) signal(SIGHUP, getboottime);
218	openlog("rwhod", LOG_PID, LOG_DAEMON);
219	sp = getservbyname("who", "udp");
220	if (sp == NULL) {
221		syslog(LOG_ERR, "who/udp: unknown service");
222		exit(1);
223	}
224	if (chdir(_PATH_RWHODIR) < 0) {
225		syslog(LOG_ERR, "%s: %m", _PATH_RWHODIR);
226		exit(1);
227	}
228	/*
229	 * Establish host name as returned by system.
230	 */
231	if (gethostname(myname, sizeof(myname) - 1) < 0) {
232		syslog(LOG_ERR, "gethostname: %m");
233		exit(1);
234	}
235	if ((cp = index(myname, '.')) != NULL)
236		*cp = '\0';
237	strncpy(mywd.wd_hostname, myname, sizeof(mywd.wd_hostname) - 1);
238	mywd.wd_hostname[sizeof(mywd.wd_hostname) - 1] = '\0';
239#ifdef __APPLE__
240	utmpf = open(_PATH_UTMPX, O_RDONLY|O_CREAT, 0644);
241#else
242	utmpf = open(_PATH_UTMP, O_RDONLY|O_CREAT, 0644);
243#endif
244	if (utmpf < 0) {
245#ifdef __APPLE__
246		syslog(LOG_ERR, "%s: %m", _PATH_UTMPX);
247#else
248		syslog(LOG_ERR, "%s: %m", _PATH_UTMP);
249#endif
250		exit(1);
251	}
252	getboottime(0);
253	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
254		syslog(LOG_ERR, "socket: %m");
255		exit(1);
256	}
257	if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) < 0) {
258		syslog(LOG_ERR, "setsockopt SO_BROADCAST: %m");
259		exit(1);
260	}
261	memset(&soin, 0, sizeof(soin));
262	soin.sin_len = sizeof(soin);
263	soin.sin_family = AF_INET;
264	soin.sin_port = sp->s_port;
265	if (bind(s, (struct sockaddr *)&soin, sizeof(soin)) < 0) {
266		syslog(LOG_ERR, "bind: %m");
267		exit(1);
268	}
269	setgid(unpriv_gid);
270	setgroups(1, &unpriv_gid);	/* XXX BOGUS groups[0] = egid */
271	setuid(unpriv_uid);
272	if (!configure(s))
273		exit(1);
274	if (!quiet_mode) {
275		signal(SIGALRM, onalrm);
276		onalrm(0);
277	}
278	for (;;) {
279		struct whod wd;
280		socklen_t len = sizeof(from);
281		int cc, whod;
282		time_t t;
283
284		cc = recvfrom(s, (char *)&wd, sizeof(struct whod), 0,
285			(struct sockaddr *)&from, &len);
286		if (cc <= 0) {
287			if (cc < 0 && errno != EINTR)
288				syslog(LOG_WARNING, "recv: %m");
289			continue;
290		}
291		if (from.sin_port != sp->s_port && !insecure_mode) {
292			syslog(LOG_WARNING, "%d: bad source port from %s",
293			    ntohs(from.sin_port), inet_ntoa(from.sin_addr));
294			continue;
295		}
296		if (cc < WHDRSIZE) {
297			syslog(LOG_WARNING, "short packet from %s",
298			    inet_ntoa(from.sin_addr));
299			continue;
300		}
301		if (wd.wd_vers != WHODVERSION)
302			continue;
303		if (wd.wd_type != WHODTYPE_STATUS)
304			continue;
305		if (!verify(wd.wd_hostname, sizeof wd.wd_hostname)) {
306			syslog(LOG_WARNING, "malformed host name from %s",
307			    inet_ntoa(from.sin_addr));
308			continue;
309		}
310		(void) snprintf(path, sizeof path, "whod.%s", wd.wd_hostname);
311		/*
312		 * Rather than truncating and growing the file each time,
313		 * use ftruncate if size is less than previous size.
314		 */
315		whod = open(path, O_WRONLY | O_CREAT, 0644);
316		if (whod < 0) {
317			syslog(LOG_WARNING, "%s: %m", path);
318			continue;
319		}
320#if ENDIAN != BIG_ENDIAN
321		{
322			int i, n = (cc - WHDRSIZE)/sizeof(struct whoent);
323			struct whoent *we;
324
325			/* undo header byte swapping before writing to file */
326			wd.wd_sendtime = ntohl(wd.wd_sendtime);
327			for (i = 0; i < 3; i++)
328				wd.wd_loadav[i] = ntohl(wd.wd_loadav[i]);
329			wd.wd_boottime = ntohl(wd.wd_boottime);
330			we = wd.wd_we;
331			for (i = 0; i < n; i++) {
332				we->we_idle = ntohl(we->we_idle);
333				we->we_utmp.out_time =
334				    ntohl(we->we_utmp.out_time);
335				we++;
336			}
337		}
338#endif
339		(void) time(&t);
340		wd.wd_recvtime = _time_to_int(t);
341		(void) write(whod, (char *)&wd, cc);
342		if (fstat(whod, &st) < 0 || st.st_size > cc)
343			ftruncate(whod, cc);
344		(void) close(whod);
345	}
346}
347
348static void
349usage()
350{
351	fprintf(stderr, "usage: rwhod [-i] [-p] [-l] [-m [ttl]]\n");
352	exit(1);
353}
354
355void
356run_as(uid, gid)
357	uid_t *uid;
358	gid_t *gid;
359{
360	struct passwd *pw;
361	struct group *gr;
362
363	pw = getpwnam(UNPRIV_USER);
364	if (!pw) {
365		syslog(LOG_ERR, "getpwnam(%s): %m", UNPRIV_USER);
366		exit(1);
367	}
368	*uid = pw->pw_uid;
369
370	gr = getgrnam(UNPRIV_GROUP);
371	if (!gr) {
372		syslog(LOG_ERR, "getgrnam(%s): %m", UNPRIV_GROUP);
373		exit(1);
374	}
375	*gid = gr->gr_gid;
376}
377
378/*
379 * Check out host name for unprintables
380 * and other funnies before allowing a file
381 * to be created.  Sorry, but blanks aren't allowed.
382 */
383int
384verify(name, maxlen)
385	register char *name;
386	register int   maxlen;
387{
388	register int size = 0;
389
390	while (*name && size < maxlen - 1) {
391		if (!isascii(*name) || !(isalnum(*name) || ispunct(*name)))
392			return (0);
393		name++, size++;
394	}
395	*name = '\0';
396	return (size > 0);
397}
398
399int	utmptime;
400int	utmpent;
401int	utmpsize = 0;
402#ifndef __APPLE__
403struct	utmp *utmp;
404#endif
405int	alarmcount;
406
407void
408onalrm(signo)
409	int signo __unused;
410{
411	register struct neighbor *np;
412	register struct whoent *we = mywd.wd_we, *wlast;
413	register int i;
414	struct stat stb;
415	double avenrun[3];
416	time_t now;
417	int cc;
418#ifdef __APPLE__
419	struct utmpx *u;
420#endif
421
422	now = time(NULL);
423	if (alarmcount % 10 == 0)
424		getboottime(0);
425	alarmcount++;
426	(void) fstat(utmpf, &stb);
427	if ((stb.st_mtime != utmptime) || (stb.st_size > utmpsize)) {
428		utmptime = stb.st_mtime;
429#ifdef __APPLE__
430		utmpsize = stb.st_size > utmpsize;
431		wlast = &mywd.wd_we[1024 / sizeof(struct whoent) - 1];
432		utmpent = 0;
433		setutxent();
434		while ((u = getutxent()) != NULL)
435			if (u->ut_user[0] && u->ut_type == USER_PROCESS) {
436				memcpy(we->we_utmp.out_line, u->ut_line,
437				   sizeof(we->we_utmp.out_line));
438				memcpy(we->we_utmp.out_name, u->ut_user,
439				   sizeof(we->we_utmp.out_name));
440				we->we_utmp.out_time = htonl(u->ut_tv.tv_sec);
441				if (++we > wlast)
442					break;
443			}
444		endutxent();
445#else
446		if (stb.st_size > utmpsize) {
447			utmpsize = stb.st_size + 10 * sizeof(struct utmp);
448			utmp = (struct utmp *)reallocf(utmp, utmpsize);
449			if (utmp == NULL) {
450				syslog(LOG_WARNING, "malloc failed");
451				utmpsize = 0;
452				goto done;
453			}
454		}
455		(void) lseek(utmpf, (off_t)0, L_SET);
456		cc = read(utmpf, (char *)utmp, stb.st_size);
457		if (cc < 0) {
458			syslog(LOG_ERR, "read(%s): %m", _PATH_UTMP);
459			goto done;
460		}
461		wlast = &mywd.wd_we[1024 / sizeof(struct whoent) - 1];
462		utmpent = cc / sizeof(struct utmp);
463		for (i = 0; i < utmpent; i++)
464			if (utmp[i].ut_name[0]) {
465				memcpy(we->we_utmp.out_line, utmp[i].ut_line,
466				   sizeof(utmp[i].ut_line));
467				memcpy(we->we_utmp.out_name, utmp[i].ut_name,
468				   sizeof(utmp[i].ut_name));
469				we->we_utmp.out_time = htonl(utmp[i].ut_time);
470				if (we >= wlast)
471					break;
472				we++;
473			}
474#endif
475		utmpent = we - mywd.wd_we;
476	}
477
478	/*
479	 * The test on utmpent looks silly---after all, if no one is
480	 * logged on, why worry about efficiency?---but is useful on
481	 * (e.g.) compute servers.
482	 */
483	if (utmpent && chdir(_PATH_DEV)) {
484		syslog(LOG_ERR, "chdir(%s): %m", _PATH_DEV);
485		exit(1);
486	}
487	we = mywd.wd_we;
488	for (i = 0; i < utmpent; i++) {
489		if (stat(we->we_utmp.out_line, &stb) >= 0)
490			we->we_idle = htonl(now - stb.st_atime);
491		we++;
492	}
493	(void)getloadavg(avenrun, sizeof(avenrun)/sizeof(avenrun[0]));
494	for (i = 0; i < 3; i++)
495		mywd.wd_loadav[i] = htonl((u_long)(avenrun[i] * 100));
496	cc = (char *)we - (char *)&mywd;
497	mywd.wd_sendtime = htonl(_time_to_time32(time(NULL)));
498	mywd.wd_vers = WHODVERSION;
499	mywd.wd_type = WHODTYPE_STATUS;
500	if (multicast_mode == SCOPED_MULTICAST) {
501		(void) sendto(s, (char *)&mywd, cc, 0,
502				(struct sockaddr *)&multicast_addr,
503				sizeof(multicast_addr));
504	}
505	else for (np = neighbors; np != NULL; np = np->n_next) {
506		if (multicast_mode == PER_INTERFACE_MULTICAST &&
507		    np->n_flags & IFF_MULTICAST) {
508			/*
509			 * Select the outgoing interface for the multicast.
510			 */
511			if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF,
512			    &(((struct sockaddr_in *)np->n_addr)->sin_addr),
513			    sizeof(struct in_addr)) < 0) {
514				syslog(LOG_ERR,
515					"setsockopt IP_MULTICAST_IF: %m");
516				exit(1);
517			}
518			(void) sendto(s, (char *)&mywd, cc, 0,
519				(struct sockaddr *)&multicast_addr,
520				sizeof(multicast_addr));
521		} else (void) sendto(s, (char *)&mywd, cc, 0,
522					np->n_addr, np->n_addrlen);
523	}
524	if (utmpent && chdir(_PATH_RWHODIR)) {
525		syslog(LOG_ERR, "chdir(%s): %m", _PATH_RWHODIR);
526		exit(1);
527	}
528#ifndef __APPLE__
529done:
530#endif
531	(void) alarm(AL_INTERVAL);
532}
533
534void
535getboottime(signo)
536	int signo __unused;
537{
538	int mib[2];
539	size_t size;
540	struct timeval tm;
541
542	mib[0] = CTL_KERN;
543	mib[1] = KERN_BOOTTIME;
544	size = sizeof(tm);
545	if (sysctl(mib, 2, &tm, &size, NULL, 0) == -1) {
546		syslog(LOG_ERR, "cannot get boottime: %m");
547		exit(1);
548	}
549	mywd.wd_boottime = htonl(_time_to_time32(tm.tv_sec));
550}
551
552void
553quit(msg)
554	const char *msg;
555{
556	syslog(LOG_ERR, "%s", msg);
557	exit(1);
558}
559
560#ifdef __APPLE__
561/*
562 * This macro returns the size of a struct sockaddr when passed
563 * through a routing socket. Basically we round up sa_len to
564 * a multiple of sizeof(long), with a minimum of sizeof(long).
565 * The check for a NULL pointer is just a convenience, probably never used.
566 * The case sa_len == 0 should only apply to empty structures.
567 */
568#define SA_SIZE(sa)												\
569	(	(!(sa) || ((struct sockaddr *)(sa))->sa_len == 0) ?		\
570		sizeof(long)		:									\
571		1 + ( (((struct sockaddr *)(sa))->sa_len - 1) | (sizeof(long) - 1) ) )
572#endif
573
574void
575rt_xaddrs(cp, cplim, rtinfo)
576	register caddr_t cp, cplim;
577	register struct rt_addrinfo *rtinfo;
578{
579	register struct sockaddr *sa;
580	register int i;
581
582	memset(rtinfo->rti_info, 0, sizeof(rtinfo->rti_info));
583	for (i = 0; (i < RTAX_MAX) && (cp < cplim); i++) {
584		if ((rtinfo->rti_addrs & (1 << i)) == 0)
585			continue;
586		rtinfo->rti_info[i] = sa = (struct sockaddr *)cp;
587		cp += SA_SIZE(sa);
588	}
589}
590
591/*
592 * Figure out device configuration and select
593 * networks which deserve status information.
594 */
595int
596configure(so)
597	int so;
598{
599	register struct neighbor *np;
600	register struct if_msghdr *ifm;
601	register struct ifa_msghdr *ifam;
602	struct sockaddr_dl *sdl;
603	size_t needed;
604	int mib[6], flags = 0, len;
605	char *buf, *lim, *next;
606	struct rt_addrinfo info;
607
608	if (multicast_mode != NO_MULTICAST) {
609		multicast_addr.sin_addr.s_addr = htonl(INADDR_WHOD_GROUP);
610		multicast_addr.sin_port = sp->s_port;
611	}
612
613	if (multicast_mode == SCOPED_MULTICAST) {
614		struct ip_mreq mreq;
615		unsigned char ttl;
616
617		mreq.imr_multiaddr.s_addr = htonl(INADDR_WHOD_GROUP);
618		mreq.imr_interface.s_addr = htonl(INADDR_ANY);
619		if (setsockopt(so, IPPROTO_IP, IP_ADD_MEMBERSHIP,
620					&mreq, sizeof(mreq)) < 0) {
621			syslog(LOG_ERR,
622				"setsockopt IP_ADD_MEMBERSHIP: %m");
623			return(0);
624		}
625		ttl = multicast_scope;
626		if (setsockopt(so, IPPROTO_IP, IP_MULTICAST_TTL,
627					&ttl, sizeof(ttl)) < 0) {
628			syslog(LOG_ERR,
629				"setsockopt IP_MULTICAST_TTL: %m");
630			return(0);
631		}
632		return(1);
633	}
634
635	mib[0] = CTL_NET;
636	mib[1] = PF_ROUTE;
637	mib[2] = 0;
638	mib[3] = AF_INET;
639	mib[4] = NET_RT_IFLIST;
640	mib[5] = 0;
641	if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
642		quit("route-sysctl-estimate");
643	if ((buf = malloc(needed)) == NULL)
644		quit("malloc");
645	if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0)
646		quit("actual retrieval of interface table");
647	lim = buf + needed;
648
649	sdl = NULL;		/* XXX just to keep gcc -Wall happy */
650	for (next = buf; next < lim; next += ifm->ifm_msglen) {
651		ifm = (struct if_msghdr *)next;
652		if (ifm->ifm_type == RTM_IFINFO) {
653			sdl = (struct sockaddr_dl *)(ifm + 1);
654			flags = ifm->ifm_flags;
655			continue;
656		}
657		if ((flags & IFF_UP) == 0 ||
658		    (flags & (((multicast_mode == PER_INTERFACE_MULTICAST) ?
659				IFF_MULTICAST : 0) |
660				IFF_BROADCAST|iff_flag)) == 0)
661			continue;
662		if (ifm->ifm_type != RTM_NEWADDR)
663			quit("out of sync parsing NET_RT_IFLIST");
664		ifam = (struct ifa_msghdr *)ifm;
665		info.rti_addrs = ifam->ifam_addrs;
666		rt_xaddrs((char *)(ifam + 1), ifam->ifam_msglen + (char *)ifam,
667			&info);
668		/* gag, wish we could get rid of Internet dependencies */
669#define dstaddr	info.rti_info[RTAX_BRD]
670#define ifaddr info.rti_info[RTAX_IFA]
671#define IPADDR_SA(x) ((struct sockaddr_in *)(x))->sin_addr.s_addr
672#define PORT_SA(x) ((struct sockaddr_in *)(x))->sin_port
673		if (dstaddr == 0 || dstaddr->sa_family != AF_INET)
674			continue;
675		PORT_SA(dstaddr) = sp->s_port;
676		for (np = neighbors; np != NULL; np = np->n_next)
677			if (memcmp(sdl->sdl_data, np->n_name,
678				   sdl->sdl_nlen) == 0 &&
679			    IPADDR_SA(np->n_addr) == IPADDR_SA(dstaddr))
680				break;
681		if (np != NULL)
682			continue;
683		len = sizeof(*np) + dstaddr->sa_len + sdl->sdl_nlen + 1;
684		np = (struct neighbor *)malloc(len);
685		if (np == NULL)
686			quit("malloc of neighbor structure");
687		memset(np, 0, len);
688		np->n_flags = flags;
689		np->n_addr = (struct sockaddr *)(np + 1);
690		np->n_addrlen = dstaddr->sa_len;
691		np->n_name = np->n_addrlen + (char *)np->n_addr;
692		memcpy((char *)np->n_addr, (char *)dstaddr, np->n_addrlen);
693		memcpy(np->n_name, sdl->sdl_data, sdl->sdl_nlen);
694		if (multicast_mode == PER_INTERFACE_MULTICAST &&
695		    (flags & IFF_MULTICAST) &&
696		   !(flags & IFF_LOOPBACK)) {
697			struct ip_mreq mreq;
698
699			memcpy((char *)np->n_addr, (char *)ifaddr,
700				np->n_addrlen);
701			mreq.imr_multiaddr.s_addr = htonl(INADDR_WHOD_GROUP);
702			mreq.imr_interface.s_addr =
703			  ((struct sockaddr_in *)np->n_addr)->sin_addr.s_addr;
704			if (setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP,
705						&mreq, sizeof(mreq)) < 0) {
706				syslog(LOG_ERR,
707				    "setsockopt IP_ADD_MEMBERSHIP: %m");
708#if 0
709				/* Fall back to broadcast on this if. */
710				np->n_flags &= ~IFF_MULTICAST;
711#else
712				free((char *)np);
713				continue;
714#endif
715			}
716		}
717		np->n_next = neighbors;
718		neighbors = np;
719	}
720	free(buf);
721	return (1);
722}
723
724#ifdef DEBUG
725void
726Sendto(s, buf, cc, flags, to, tolen)
727	int s;
728	const void *buf;
729	size_t cc;
730	int flags;
731	const struct sockaddr *to;
732	int tolen;
733{
734	register struct whod *w = (struct whod *)buf;
735	register struct whoent *we;
736	struct sockaddr_in *sin = (struct sockaddr_in *)to;
737
738	printf("sendto %x.%d\n", ntohl(sin->sin_addr.s_addr),
739				 ntohs(sin->sin_port));
740	printf("hostname %s %s\n", w->wd_hostname,
741	   interval(ntohl(w->wd_sendtime) - ntohl(w->wd_boottime), "  up"));
742	printf("load %4.2f, %4.2f, %4.2f\n",
743	    ntohl(w->wd_loadav[0]) / 100.0, ntohl(w->wd_loadav[1]) / 100.0,
744	    ntohl(w->wd_loadav[2]) / 100.0);
745	cc -= WHDRSIZE;
746	for (we = w->wd_we, cc /= sizeof(struct whoent); cc > 0; cc--, we++) {
747		time_t t = _time32_to_time(ntohl(we->we_utmp.out_time));
748		printf("%-8.8s %s:%s %.12s",
749			we->we_utmp.out_name,
750			w->wd_hostname, we->we_utmp.out_line,
751			ctime(&t)+4);
752		we->we_idle = ntohl(we->we_idle) / 60;
753		if (we->we_idle) {
754			if (we->we_idle >= 100*60)
755				we->we_idle = 100*60 - 1;
756			if (we->we_idle >= 60)
757				printf(" %2d", we->we_idle / 60);
758			else
759				printf("   ");
760			printf(":%02d", we->we_idle % 60);
761		}
762		printf("\n");
763	}
764}
765
766char *
767interval(time, updown)
768	int time;
769	char *updown;
770{
771	static char resbuf[32];
772	int days, hours, minutes;
773
774	if (time < 0 || time > 3*30*24*60*60) {
775		(void) sprintf(resbuf, "   %s ??:??", updown);
776		return (resbuf);
777	}
778	minutes = (time + 59) / 60;		/* round to minutes */
779	hours = minutes / 60; minutes %= 60;
780	days = hours / 24; hours %= 24;
781	if (days)
782		(void) sprintf(resbuf, "%s %2d+%02d:%02d",
783		    updown, days, hours, minutes);
784	else
785		(void) sprintf(resbuf, "%s    %2d:%02d",
786		    updown, hours, minutes);
787	return (resbuf);
788}
789#endif
790