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