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