2 * Copyright (c) 1983, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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 * 4. 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.
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
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 $
35 #include <sys/param.h>
36 #include <sys/socket.h>
38 #include <sys/signal.h>
39 #include <sys/ioctl.h>
40 #include <sys/sysctl.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>
67 * This version of Berkeley's rwhod has been modified to use IP multicast
68 * datagrams, under control of a new command-line option:
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).
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.
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.
93 * -- Steve Deering, Stanford University, February 1989
96 #define UNPRIV_USER "daemon"
97 #define UNPRIV_GROUP "daemon"
99 #define WITH_ERRNO 1 /* Write to syslog with errno (%m) */
100 #define WITHOUT_ERRNO 0 /* Write to syslog without errno */
102 #define NO_MULTICAST 0 /* multicast modes */
103 #define PER_INTERFACE_MULTICAST 1
104 #define SCOPED_MULTICAST 2
106 #define MAX_MULTICAST_SCOPE 32 /* "site-wide", by convention */
108 #define INADDR_WHOD_GROUP (u_long)0xe0000103 /* 224.0.1.3 */
109 /* (belongs in protocols/rwhod.h) */
113 int iff_flag = IFF_POINTOPOINT;
114 int multicast_mode = NO_MULTICAST;
116 struct sockaddr_in multicast_addr;
118 char myname[MAXHOSTNAMELEN];
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
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 */
133 struct neighbor *neighbors;
137 volatile sig_atomic_t onsighup;
139 #define WHDRSIZE (sizeof(mywd) - sizeof(mywd.wd_we))
141 void run_as(uid_t *, gid_t *);
143 void getboottime(void);
144 void send_host_information(void);
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 *);
154 char *interval(int, const char *);
155 ssize_t Sendto(int, const void *, size_t, int,
156 const struct sockaddr *, int);
158 #define Sendto sendto
162 main(int argc, char *argv[])
164 struct pollfd pfd[1];
167 int send_time = 180; /* Default time, 180 seconds (3 minutes) */
168 struct sockaddr_in m_sin;
173 struct timeval next, now;
176 errx(1, "not super user");
178 run_as(&unpriv_uid, &unpriv_gid);
181 while (argc > 0 && *argv[0] == '-') {
182 if (strcmp(*argv, "-m") == 0) {
183 if (argc > 1 && *(argv + 1)[0] != '-') {
184 /* Argument has been given */
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);
195 else multicast_mode = PER_INTERFACE_MULTICAST;
196 } else if (strcmp(*argv, "-g") == 0) {
197 if (argc > 1 && *(argv + 1)[0] != '-') {
199 send_time = (int)strtol(*argv, &ep, 10);
201 errx(1, "time must be greater than 0");
205 errx(1, "invalid argument: %s", *argv);
206 if (*ep == 'M' || *ep == 'm') {
207 /* Time in minutes. */
210 errx(1, "invalid argument: %s", *argv);
214 errx(1, "cannot be greater than 180 seconds (3 minutes)");
216 errx(1, "missing argument");
217 } else if (strcmp(*argv, "-i") == 0)
219 else if (strcmp(*argv, "-l") == 0)
221 else if (strcmp(*argv, "-p") == 0)
234 openlog("rwhod", LOG_PID, LOG_DAEMON);
235 sp = getservbyname("who", "udp");
237 quit("udp/who: unknown service", WITHOUT_ERRNO);
239 if (chdir(_PATH_RWHODIR) < 0)
240 quit(_PATH_RWHODIR, WITH_ERRNO);
243 * Establish host name as returned by system.
245 if (gethostname(myname, sizeof(myname)) < 0)
246 quit("gethostname", WITH_ERRNO);
248 if ((cp = strchr(myname, '.')) != NULL)
250 strlcpy(mywd.wd_hostname, myname, sizeof(mywd.wd_hostname));
251 utmpf = open(_PATH_UTMP, O_RDONLY|O_CREAT, 0644);
253 quit(_PATH_UTMP, WITH_ERRNO);
256 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
257 quit("socket", WITH_ERRNO);
259 if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) < 0)
260 quit("setsockopt SO_BROADCAST", WITH_ERRNO);
262 memset(&m_sin, 0, sizeof(m_sin));
263 m_sin.sin_len = sizeof(m_sin);
264 m_sin.sin_family = AF_INET;
265 m_sin.sin_port = sp->s_port;
266 if (bind(s, (struct sockaddr *)&m_sin, sizeof(m_sin)) < 0)
267 quit("bind", WITH_ERRNO);
270 setgroups(1, &unpriv_gid); /* XXX BOGUS groups[0] = egid */
276 send_host_information();
278 gettimeofday(&now, NULL);
279 timeadd(&now, delta, &next);
283 pfd[0].events = POLLIN;
288 n = poll(pfd, 1, 1000);
298 gettimeofday(&now, NULL);
299 if (now.tv_sec > next.tv_sec) {
300 send_host_information();
301 timeadd(&now, delta, &next);
308 timeadd(struct timeval *now, time_t delta, struct timeval *next)
310 (next)->tv_sec = (now)->tv_sec + delta;
316 struct sockaddr_in from;
321 socklen_t len = sizeof(from);
323 cc = recvfrom(sock, (char *)&wd, sizeof(struct whod), 0,
324 (struct sockaddr *)&from, &len);
328 if (cc < 0 && errno != EINTR) {
329 syslog(LOG_WARNING, "recv: %m");
333 if (from.sin_port != sp->s_port && !insecure_mode) {
334 syslog(LOG_WARNING, "%d: bad source port from %s",
335 ntohs(from.sin_port), inet_ntoa(from.sin_addr));
338 if (cc < (int)WHDRSIZE) {
339 syslog(LOG_WARNING, "short packet from %s",
340 inet_ntoa(from.sin_addr));
343 if (wd.wd_vers != WHODVERSION)
345 if (wd.wd_type != WHODTYPE_STATUS)
347 if (!verify(wd.wd_hostname, sizeof wd.wd_hostname)) {
348 syslog(LOG_WARNING, "malformed host name from %s",
349 inet_ntoa(from.sin_addr));
352 snprintf(path, sizeof path, "whod.%s", wd.wd_hostname);
354 * Rather than truncating and growing the file each time,
355 * use ftruncate if size is less than previous size.
357 whod = open(path, O_WRONLY | O_CREAT, 0644);
359 syslog(LOG_WARNING, "%s: %m", path);
362 #if ENDIAN != BIG_ENDIAN
364 int i, n = (cc - WHDRSIZE)/sizeof(struct whoent);
367 /* undo header byte swapping before writing to file */
368 wd.wd_sendtime = ntohl(wd.wd_sendtime);
369 for (i = 0; i < 3; i++)
370 wd.wd_loadav[i] = ntohl(wd.wd_loadav[i]);
371 wd.wd_boottime = ntohl(wd.wd_boottime);
373 for (i = 0; i < n; i++) {
374 we->we_idle = ntohl(we->we_idle);
375 we->we_utmp.out_time =
376 ntohl(we->we_utmp.out_time);
381 wd.wd_recvtime = time(NULL);
382 write(whod, (char *)&wd, cc);
383 if (fstat(whod, &st) < 0 || st.st_size > cc)
391 fprintf(stderr, "usage: rwhod [-i] [-p] [-l] [-m [ttl]]\n");
396 hup(int signo __unused)
402 run_as(uid_t *uid, gid_t *gid)
407 pw = getpwnam(UNPRIV_USER);
409 quit("getpwnam(daemon)", WITH_ERRNO);
413 gr = getgrnam(UNPRIV_GROUP);
415 quit("getgrnam(daemon)", WITH_ERRNO);
421 * Check out host name for unprintables
422 * and other funnies before allowing a file
423 * to be created. Sorry, but blanks aren't allowed.
426 verify(char *name, int maxlen)
430 while (*name && size < maxlen - 1) {
431 if (!isascii(*name) || !(isalnum(*name) || ispunct(*name)))
446 send_host_information(void)
449 struct whoent *we = mywd.wd_we, *wlast;
457 if (alarmcount % 10 == 0)
461 if ((stb.st_mtime != utmptime) || (stb.st_size > utmpsize)) {
462 utmptime = stb.st_mtime;
463 if (stb.st_size > utmpsize) {
464 utmpsize = stb.st_size + 10 * sizeof(struct utmp);
465 utmp = reallocf(utmp, utmpsize);
467 syslog(LOG_WARNING, "malloc failed: %m");
472 lseek(utmpf, (off_t)0, L_SET);
473 cc = read(utmpf, (char *)utmp, stb.st_size);
475 syslog(LOG_ERR, "read(%s): %m", _PATH_UTMP);
478 wlast = &mywd.wd_we[1024 / sizeof(struct whoent) - 1];
479 utmpent = cc / sizeof(struct utmp);
480 for (i = 0; i < utmpent; i++)
481 if (utmp[i].ut_name[0]) {
482 memcpy(we->we_utmp.out_line, utmp[i].ut_line,
483 sizeof(utmp[i].ut_line));
484 memcpy(we->we_utmp.out_name, utmp[i].ut_name,
485 sizeof(utmp[i].ut_name));
486 we->we_utmp.out_time = htonl(utmp[i].ut_time);
491 utmpent = we - mywd.wd_we;
495 * The test on utmpent looks silly---after all, if no one is
496 * logged on, why worry about efficiency?---but is useful on
497 * (e.g.) compute servers.
499 if (utmpent && chdir(_PATH_DEV)) {
500 syslog(LOG_ERR, "chdir(%s): %m", _PATH_DEV);
505 for (i = 0; i < utmpent; i++) {
506 if (stat(we->we_utmp.out_line, &stb) >= 0)
507 we->we_idle = htonl(now - stb.st_atime);
510 getloadavg(avenrun, sizeof(avenrun)/sizeof(avenrun[0]));
511 for (i = 0; i < 3; i++)
512 mywd.wd_loadav[i] = htonl((u_long)(avenrun[i] * 100));
513 cc = (char *)we - (char *)&mywd;
514 mywd.wd_sendtime = htonl(time(0));
515 mywd.wd_vers = WHODVERSION;
516 mywd.wd_type = WHODTYPE_STATUS;
517 if (multicast_mode == SCOPED_MULTICAST) {
518 Sendto(s, (char *)&mywd, cc, 0,
519 (struct sockaddr *)&multicast_addr,
520 sizeof(multicast_addr));
522 else for (np = neighbors; np != NULL; np = np->n_next) {
523 if (multicast_mode == PER_INTERFACE_MULTICAST &&
524 np->n_flags & IFF_MULTICAST) {
526 * Select the outgoing interface for the multicast.
528 if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF,
529 &(((struct sockaddr_in *)np->n_addr)->sin_addr),
530 sizeof(struct in_addr)) < 0) {
531 quit("setsockopt IP_MULTICAST_IF", WITH_ERRNO);
533 Sendto(s, (char *)&mywd, cc, 0,
534 (struct sockaddr *)&multicast_addr,
535 sizeof(multicast_addr));
536 } else Sendto(s, (char *)&mywd, cc, 0,
537 np->n_addr, np->n_addrlen);
539 if (utmpent && chdir(_PATH_RWHODIR)) {
540 syslog(LOG_ERR, "chdir(%s): %m", _PATH_RWHODIR);
553 mib[1] = KERN_BOOTTIME;
555 if (sysctl(mib, 2, &tm, &size, NULL, 0) == -1)
556 quit("cannot get boottime", WITH_ERRNO);
558 mywd.wd_boottime = htonl(tm.tv_sec);
562 * If wrterrno == WITH_ERRNO, we will print
563 * errno. If not, we leave errno out.
566 quit(const char *msg, int wrterrno)
569 syslog(LOG_ERR, "%s: %m", msg);
571 syslog(LOG_ERR, "%s", msg);
576 ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
577 #define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))
580 rt_xaddrs(caddr_t cp, caddr_t cplim, struct rt_addrinfo *rtinfo)
585 memset(rtinfo->rti_info, 0, sizeof(rtinfo->rti_info));
586 for (i = 0; (i < RTAX_MAX) && (cp < cplim); i++) {
587 if ((rtinfo->rti_addrs & (1 << i)) == 0)
589 rtinfo->rti_info[i] = sa = (struct sockaddr *)cp;
595 * Figure out device configuration and select
596 * networks which deserve status information.
599 configure(int c_sock)
602 struct if_msghdr *ifm;
603 struct ifa_msghdr *ifam;
604 struct sockaddr_dl *sdl;
606 int mib[6], flags = 0, len;
607 char *buf, *lim, *next;
608 struct rt_addrinfo info;
610 if (multicast_mode != NO_MULTICAST) {
611 multicast_addr.sin_len = sizeof(multicast_addr);
612 multicast_addr.sin_family = AF_INET;
613 multicast_addr.sin_addr.s_addr = htonl(INADDR_WHOD_GROUP);
614 multicast_addr.sin_port = sp->s_port;
617 if (multicast_mode == SCOPED_MULTICAST) {
621 mreq.imr_multiaddr.s_addr = htonl(INADDR_WHOD_GROUP);
622 mreq.imr_interface.s_addr = htonl(INADDR_ANY);
623 if (setsockopt(c_sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,
624 &mreq, sizeof(mreq)) < 0) {
626 "setsockopt IP_ADD_MEMBERSHIP: %m");
629 ttl = multicast_scope;
630 if (setsockopt(c_sock, IPPROTO_IP, IP_MULTICAST_TTL,
631 &ttl, sizeof(ttl)) < 0) {
633 "setsockopt IP_MULTICAST_TTL: %m");
643 mib[4] = NET_RT_IFLIST;
645 if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
646 quit("route-sysctl-estimate", WITH_ERRNO);
647 if ((buf = malloc(needed)) == NULL)
648 quit("malloc", WITH_ERRNO);
649 if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0)
650 quit("actual retrieval of interface table", WITH_ERRNO);
653 sdl = NULL; /* XXX just to keep gcc -Wall happy */
654 for (next = buf; next < lim; next += ifm->ifm_msglen) {
655 ifm = (struct if_msghdr *)next;
656 if (ifm->ifm_type == RTM_IFINFO) {
657 sdl = (struct sockaddr_dl *)(ifm + 1);
658 flags = ifm->ifm_flags;
661 if ((flags & IFF_UP) == 0 ||
662 (flags & (((multicast_mode == PER_INTERFACE_MULTICAST) ?
664 IFF_BROADCAST|iff_flag)) == 0)
666 if (ifm->ifm_type != RTM_NEWADDR)
667 quit("out of sync parsing NET_RT_IFLIST", WITHOUT_ERRNO);
668 ifam = (struct ifa_msghdr *)ifm;
669 info.rti_addrs = ifam->ifam_addrs;
670 rt_xaddrs((char *)(ifam + 1), ifam->ifam_msglen + (char *)ifam,
672 /* gag, wish we could get rid of Internet dependencies */
673 #define dstaddr info.rti_info[RTAX_BRD]
674 #define ifaddr info.rti_info[RTAX_IFA]
675 #define IPADDR_SA(x) ((struct sockaddr_in *)(x))->sin_addr.s_addr
676 #define PORT_SA(x) ((struct sockaddr_in *)(x))->sin_port
677 if (dstaddr == 0 || dstaddr->sa_family != AF_INET)
679 PORT_SA(dstaddr) = sp->s_port;
680 for (np = neighbors; np != NULL; np = np->n_next)
681 if (memcmp(sdl->sdl_data, np->n_name,
682 sdl->sdl_nlen) == 0 &&
683 IPADDR_SA(np->n_addr) == IPADDR_SA(dstaddr))
687 len = sizeof(*np) + dstaddr->sa_len + sdl->sdl_nlen + 1;
688 np = (struct neighbor *)malloc(len);
690 quit("malloc of neighbor structure", WITH_ERRNO);
693 np->n_addr = (struct sockaddr *)(np + 1);
694 np->n_addrlen = dstaddr->sa_len;
695 np->n_name = np->n_addrlen + (char *)np->n_addr;
696 memcpy((char *)np->n_addr, (char *)dstaddr, np->n_addrlen);
697 memcpy(np->n_name, sdl->sdl_data, sdl->sdl_nlen);
698 if (multicast_mode == PER_INTERFACE_MULTICAST &&
699 (flags & IFF_MULTICAST) &&
700 !(flags & IFF_LOOPBACK)) {
703 memcpy((char *)np->n_addr, (char *)ifaddr,
705 mreq.imr_multiaddr.s_addr = htonl(INADDR_WHOD_GROUP);
706 mreq.imr_interface.s_addr =
707 ((struct sockaddr_in *)np->n_addr)->sin_addr.s_addr;
708 if (setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP,
709 &mreq, sizeof(mreq)) < 0) {
711 "setsockopt IP_ADD_MEMBERSHIP: %m");
713 /* Fall back to broadcast on this if. */
714 np->n_flags &= ~IFF_MULTICAST;
721 np->n_next = neighbors;
730 Sendto(int s_debug, const void *buf, size_t cc, int flags,
731 const struct sockaddr *to, int tolen)
733 const struct whod *w = (const struct whod *)buf;
734 const struct whoent *we;
735 const struct sockaddr_in *sock_in = (const struct sockaddr_in *)to;
739 ret = sendto(s_debug, buf, cc, flags, to, tolen);
741 printf("sendto %s:%d\n", inet_ntoa(sock_in->sin_addr),
742 ntohs(sock_in->sin_port));
743 printf("hostname %s %s\n", w->wd_hostname,
744 interval(ntohl(w->wd_sendtime) - ntohl(w->wd_boottime), " up"));
745 printf("load %4.2f, %4.2f, %4.2f\n",
746 ntohl(w->wd_loadav[0]) / 100.0, ntohl(w->wd_loadav[1]) / 100.0,
747 ntohl(w->wd_loadav[2]) / 100.0);
749 for (we = w->wd_we, cc /= sizeof(struct whoent); cc > 0; cc--, we++) {
750 time_t t = ntohl(we->we_utmp.out_time);
751 idle_time = we->we_idle;
752 printf("%-8.8s %s:%s %.12s",
753 we->we_utmp.out_name,
754 w->wd_hostname, we->we_utmp.out_line,
756 idle_time = ntohl(we->we_idle) / 60;
758 if (idle_time >= 100*60)
759 idle_time = 100*60 - 1;
761 printf(" %2d", idle_time / 60);
764 printf(":%02d", idle_time % 60);
772 interval(int inter_time, const char *updown)
774 static char resbuf[32];
775 int days, hours, minutes;
777 if (inter_time < 0 || inter_time > 3*30*24*60*60) {
778 snprintf(resbuf, sizeof(resbuf), " %s ??:??", updown);
781 minutes = (inter_time + 59) / 60; /* round to minutes */
782 hours = minutes / 60; minutes %= 60;
783 days = hours / 24; hours %= 24;
785 snprintf(resbuf, sizeof(resbuf), "%s %2d+%02d:%02d",
786 updown, days, hours, minutes);
788 snprintf(resbuf, sizeof(resbuf), "%s %2d:%02d",
789 updown, hours, minutes);