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