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