d7c00cef713618ce3fcd437e12bb3bd507c6c9a4
[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 #define ROUNDUP(a) \
578         ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
579 #define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))
580
581 void
582 rt_xaddrs(caddr_t cp, caddr_t cplim, struct rt_addrinfo *rtinfo)
583 {
584         struct sockaddr *sa;
585         int i;
586
587         memset(rtinfo->rti_info, 0, sizeof(rtinfo->rti_info));
588         for (i = 0; (i < RTAX_MAX) && (cp < cplim); i++) {
589                 if ((rtinfo->rti_addrs & (1 << i)) == 0)
590                         continue;
591                 rtinfo->rti_info[i] = sa = (struct sockaddr *)cp;
592                 ADVANCE(cp, sa);
593         }
594 }
595
596 /*
597  * Figure out device configuration and select
598  * networks which deserve status information.
599  */
600 int
601 configure(int c_sock)
602 {
603         struct neighbor *np;
604         struct if_msghdr *ifm;
605         struct ifa_msghdr *ifam;
606         struct sockaddr_dl *sdl;
607         size_t needed;
608         int mib[6], flags = 0, len;
609         char *buf, *lim, *next;
610         struct rt_addrinfo info;
611
612         if (multicast_mode != NO_MULTICAST) {
613                 multicast_addr.sin_len = sizeof(multicast_addr);
614                 multicast_addr.sin_family = AF_INET;
615                 multicast_addr.sin_addr.s_addr = htonl(INADDR_WHOD_GROUP);
616                 multicast_addr.sin_port = sp->s_port;
617         }
618
619         if (multicast_mode == SCOPED_MULTICAST) {
620                 struct ip_mreq mreq;
621                 unsigned char ttl;
622
623                 mreq.imr_multiaddr.s_addr = htonl(INADDR_WHOD_GROUP);
624                 mreq.imr_interface.s_addr = htonl(INADDR_ANY);
625                 if (setsockopt(c_sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,
626                                         &mreq, sizeof(mreq)) < 0) {
627                         syslog(LOG_ERR,
628                                 "setsockopt IP_ADD_MEMBERSHIP: %m");
629                         return(0);
630                 }
631                 ttl = multicast_scope;
632                 if (setsockopt(c_sock, IPPROTO_IP, IP_MULTICAST_TTL,
633                                         &ttl, sizeof(ttl)) < 0) {
634                         syslog(LOG_ERR,
635                                 "setsockopt IP_MULTICAST_TTL: %m");
636                         return(0);
637                 }
638                 return(1);
639         }
640
641         mib[0] = CTL_NET;
642         mib[1] = PF_ROUTE;
643         mib[2] = 0;
644         mib[3] = AF_INET;
645         mib[4] = NET_RT_IFLIST;
646         mib[5] = 0;
647         if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
648                 quit("route-sysctl-estimate", WITH_ERRNO);
649         if ((buf = malloc(needed)) == NULL)
650                 quit("malloc", WITH_ERRNO);
651         if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0)
652                 quit("actual retrieval of interface table", WITH_ERRNO);
653         lim = buf + needed;
654
655         sdl = NULL;             /* XXX just to keep gcc -Wall happy */
656         for (next = buf; next < lim; next += ifm->ifm_msglen) {
657                 ifm = (struct if_msghdr *)next;
658                 if (ifm->ifm_type == RTM_IFINFO) {
659                         sdl = (struct sockaddr_dl *)(ifm + 1);
660                         flags = ifm->ifm_flags;
661                         continue;
662                 }
663                 if ((flags & IFF_UP) == 0 ||
664                     (flags & (((multicast_mode == PER_INTERFACE_MULTICAST) ?
665                                 IFF_MULTICAST : 0) |
666                                 IFF_BROADCAST|iff_flag)) == 0)
667                         continue;
668                 if (ifm->ifm_type != RTM_NEWADDR)
669                         quit("out of sync parsing NET_RT_IFLIST", WITHOUT_ERRNO);
670                 ifam = (struct ifa_msghdr *)ifm;
671                 info.rti_addrs = ifam->ifam_addrs;
672                 rt_xaddrs((char *)(ifam + 1), ifam->ifam_msglen + (char *)ifam,
673                         &info);
674                 /* gag, wish we could get rid of Internet dependencies */
675 #define dstaddr info.rti_info[RTAX_BRD]
676 #define ifaddr info.rti_info[RTAX_IFA]
677 #define IPADDR_SA(x) ((struct sockaddr_in *)(x))->sin_addr.s_addr
678 #define PORT_SA(x) ((struct sockaddr_in *)(x))->sin_port
679                 if (dstaddr == 0 || dstaddr->sa_family != AF_INET)
680                         continue;
681                 PORT_SA(dstaddr) = sp->s_port;
682                 for (np = neighbors; np != NULL; np = np->n_next)
683                         if (memcmp(sdl->sdl_data, np->n_name,
684                                    sdl->sdl_nlen) == 0 &&
685                             IPADDR_SA(np->n_addr) == IPADDR_SA(dstaddr))
686                                 break;
687                 if (np != NULL)
688                         continue;
689                 len = sizeof(*np) + dstaddr->sa_len + sdl->sdl_nlen + 1;
690                 np = (struct neighbor *)malloc(len);
691                 if (np == NULL)
692                         quit("malloc of neighbor structure", WITH_ERRNO);
693                 memset(np, 0, len);
694                 np->n_flags = flags;
695                 np->n_addr = (struct sockaddr *)(np + 1);
696                 np->n_addrlen = dstaddr->sa_len;
697                 np->n_name = np->n_addrlen + (char *)np->n_addr;
698                 memcpy((char *)np->n_addr, (char *)dstaddr, np->n_addrlen);
699                 memcpy(np->n_name, sdl->sdl_data, sdl->sdl_nlen);
700                 if (multicast_mode == PER_INTERFACE_MULTICAST &&
701                     (flags & IFF_MULTICAST) &&
702                    !(flags & IFF_LOOPBACK)) {
703                         struct ip_mreq mreq;
704
705                         memcpy((char *)np->n_addr, (char *)ifaddr,
706                                 np->n_addrlen);
707                         mreq.imr_multiaddr.s_addr = htonl(INADDR_WHOD_GROUP);
708                         mreq.imr_interface.s_addr =
709                           ((struct sockaddr_in *)np->n_addr)->sin_addr.s_addr;
710                         if (setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP,
711                                                 &mreq, sizeof(mreq)) < 0) {
712                                 syslog(LOG_ERR,
713                                     "setsockopt IP_ADD_MEMBERSHIP: %m");
714 #if 0
715                                 /* Fall back to broadcast on this if. */
716                                 np->n_flags &= ~IFF_MULTICAST;
717 #else
718                                 free((char *)np);
719                                 continue;
720 #endif
721                         }
722                 }
723                 np->n_next = neighbors;
724                 neighbors = np;
725         }
726         free(buf);
727         return (1);
728 }
729
730 #ifdef DEBUG
731 ssize_t
732 Sendto(int s_debug, const void *buf, size_t cc, int flags,
733        const struct sockaddr *to, int tolen)
734 {
735         const struct whod *w = (const struct whod *)buf;
736         const struct whoent *we;
737         const struct sockaddr_in *sock_in = (const struct sockaddr_in *)to;
738         ssize_t ret;
739         int idle_time;
740
741         ret = sendto(s_debug, buf, cc, flags, to, tolen);
742
743         printf("sendto %s:%d\n", inet_ntoa(sock_in->sin_addr),
744                                  ntohs(sock_in->sin_port));
745         printf("hostname %s %s\n", w->wd_hostname,
746            interval(ntohl(w->wd_sendtime) - ntohl(w->wd_boottime), "  up"));
747         printf("load %4.2f, %4.2f, %4.2f\n",
748             ntohl(w->wd_loadav[0]) / 100.0, ntohl(w->wd_loadav[1]) / 100.0,
749             ntohl(w->wd_loadav[2]) / 100.0);
750         cc -= WHDRSIZE;
751         for (we = w->wd_we, cc /= sizeof(struct whoent); cc > 0; cc--, we++) {
752                 time_t t = ntohl(we->we_utmp.out_time);
753                 idle_time = we->we_idle;
754                 printf("%-8.8s %s:%s %.12s",
755                         we->we_utmp.out_name,
756                         w->wd_hostname, we->we_utmp.out_line,
757                         ctime(&t)+4);
758                 idle_time = ntohl(we->we_idle) / 60;
759                 if (idle_time) {
760                         if (idle_time >= 100*60)
761                                 idle_time = 100*60 - 1;
762                         if (idle_time >= 60)
763                                 printf(" %2d", idle_time / 60);
764                         else
765                                 printf("   ");
766                         printf(":%02d", idle_time % 60);
767                 }
768                 printf("\n");
769         }
770         return(ret);
771 }
772
773 char *
774 interval(int inter_time, const char *updown)
775 {
776         static char resbuf[32];
777         int days, hours, minutes;
778
779         if (inter_time < 0 || inter_time > 3*30*24*60*60) {
780                 snprintf(resbuf, sizeof(resbuf), "   %s ??:??", updown);
781                 return (resbuf);
782         }
783         minutes = (inter_time + 59) / 60;               /* round to minutes */
784         hours = minutes / 60; minutes %= 60;
785         days = hours / 24; hours %= 24;
786         if (days)
787                 snprintf(resbuf, sizeof(resbuf), "%s %2d+%02d:%02d",
788                     updown, days, hours, minutes);
789         else
790                 snprintf(resbuf, sizeof(resbuf), "%s    %2d:%02d",
791                     updown, hours, minutes);
792         return (resbuf);
793 }
794 #endif