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