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