rwhod.c revision 1.29 1 /* $NetBSD: rwhod.c,v 1.29 2005/07/01 15:31:18 christos Exp $ */
2
3 /*
4 * Copyright (c) 1983, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32 #include <sys/cdefs.h>
33 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1983, 1993\n\
35 The Regents of the University of California. All rights reserved.\n");
36 #endif /* not lint */
37
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)rwhod.c 8.1 (Berkeley) 6/6/93";
41 #else
42 __RCSID("$NetBSD: rwhod.c,v 1.29 2005/07/01 15:31:18 christos Exp $");
43 #endif
44 #endif /* not lint */
45
46 #include <sys/param.h>
47 #include <sys/socket.h>
48 #include <sys/stat.h>
49 #include <sys/signal.h>
50 #include <sys/ioctl.h>
51 #include <sys/sysctl.h>
52
53 #include <net/if.h>
54 #include <net/if_dl.h>
55 #include <net/route.h>
56 #include <netinet/in.h>
57 #include <protocols/rwhod.h>
58 #include <arpa/inet.h>
59
60 #include <ctype.h>
61 #include <err.h>
62 #include <errno.h>
63 #include <fcntl.h>
64 #include <netdb.h>
65 #include <paths.h>
66 #include <poll.h>
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <string.h>
70 #include <syslog.h>
71 #include <unistd.h>
72 #include <util.h>
73
74 #include "utmpentry.h"
75
76 #define CHECK_INTERVAL (3 * 60)
77
78 /* Time interval limit; ruptime will think that we are down > than this */
79 #define MAX_INTERVAL (11 * 60)
80
81
82 static char myname[MAXHOSTNAMELEN + 1];
83
84 /*
85 * We communicate with each neighbor in a list constructed at the time we're
86 * started up. Neighbors are currently directly connected via a hardware
87 * interface.
88 */
89 struct neighbor {
90 struct neighbor *n_next;
91 char *n_name; /* interface name */
92 struct sockaddr *n_addr; /* who to send to */
93 int n_addrlen; /* size of address */
94 int n_flags; /* should forward?, interface flags */
95 };
96
97 static struct neighbor *neighbors;
98 static struct whod mywd;
99 static struct servent *sp;
100 static volatile sig_atomic_t onsighup;
101
102 #define WHDRSIZE (sizeof(mywd) - sizeof(mywd.wd_we))
103
104 static int configure(int);
105 static void getboottime(void);
106 static void send_host_information(int);
107 static void sighup(int);
108 static void handleread(int);
109 static void quit(const char *);
110 static void rt_xaddrs(void *, void *, struct rt_addrinfo *);
111 static void usage(void) __attribute__((__noreturn__));
112 static int verify(const char *);
113 #ifdef DEBUG
114 static char *interval(int, const char *);
115 #define sendto Sendto
116 static ssize_t Sendto(int, const void *, size_t, int,
117 const struct sockaddr *, socklen_t);
118 #endif
119
120 int
121 main(int argc, char *argv[])
122 {
123 int s, ch;
124 int time_interval = 180; /* Default time (180 seconds) */
125 char *cp, *ep;
126 socklen_t on = 1;
127 struct sockaddr_in sasin;
128 struct pollfd pfd[1];
129 struct timeval delta, next, now;
130
131 setprogname(argv[0]);
132
133 if (getuid())
134 errx(EXIT_FAILURE, "not super user");
135
136 while ((ch = getopt(argc, argv, "i:")) != -1) {
137 switch (ch) {
138 case 'i':
139 time_interval = (int)strtol(optarg, &ep, 10);
140
141 switch (*ep) {
142 case '\0':
143 break;
144 case 'm':
145 case 'M':
146 /* Time in minutes. */
147 time_interval *= 60;
148 if (ep[1] == '\0')
149 break;
150 /*FALLTHROUGH*/
151 default:
152 errx(1, "Invalid argument: `%s'", optarg);
153 }
154
155 if (time_interval <= 0)
156 errx(1, "Interval must be greater than 0");
157
158 if (time_interval > MAX_INTERVAL)
159 errx(1, "Interval cannot be greater than"
160 " %d minutes", MAX_INTERVAL / 60);
161 break;
162 default:
163 usage();
164 }
165 }
166
167 sp = getservbyname("who", "udp");
168 if (sp == NULL)
169 errx(EXIT_FAILURE, "udp/who: unknown service");
170 #ifndef DEBUG
171 (void)daemon(1, 0);
172 (void)pidfile(NULL);
173 #endif
174 if (chdir(_PATH_RWHODIR) < 0)
175 err(EXIT_FAILURE, "%s", _PATH_RWHODIR);
176 (void)signal(SIGHUP, sighup);
177 openlog("rwhod", LOG_PID, LOG_DAEMON);
178 /*
179 * Establish host name as returned by system.
180 */
181 if (gethostname(myname, sizeof(myname) - 1) < 0) {
182 syslog(LOG_ERR, "gethostname: %m");
183 exit(EXIT_FAILURE);
184 }
185 myname[sizeof(myname) - 1] = '\0';
186 if ((cp = strchr(myname, '.')) != NULL)
187 *cp = '\0';
188 (void)strncpy(mywd.wd_hostname, myname, sizeof(mywd.wd_hostname) - 1);
189 getboottime();
190 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
191 syslog(LOG_ERR, "socket: %m");
192 exit(EXIT_FAILURE);
193 }
194 if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) < 0) {
195 syslog(LOG_ERR, "setsockopt SO_BROADCAST: %m");
196 exit(EXIT_FAILURE);
197 }
198 (void)memset(&sasin, 0, sizeof(sasin));
199 sasin.sin_family = AF_INET;
200 sasin.sin_port = sp->s_port;
201 if (bind(s, (struct sockaddr *)&sasin, sizeof(sasin)) < 0) {
202 syslog(LOG_ERR, "bind: %m");
203 exit(EXIT_FAILURE);
204 }
205 if (!configure(s))
206 exit(EXIT_FAILURE);
207
208 send_host_information(s);
209 delta.tv_sec = time_interval;
210 delta.tv_usec = 0;
211 gettimeofday(&now, NULL);
212 timeradd(&now, &delta, &next);
213
214 pfd[0].fd = s;
215 pfd[0].events = POLLIN;
216
217 for (;;) {
218 int n;
219
220 n = poll(pfd, 1, 1000);
221
222 if (onsighup) {
223 onsighup = 0;
224 getboottime();
225 }
226
227 if (n == 1)
228 handleread(s);
229
230 (void)gettimeofday(&now, NULL);
231 if (timercmp(&now, &next, >)) {
232 send_host_information(s);
233 timeradd(&now, &delta, &next);
234 }
235 }
236
237 /* NOTREACHED */
238 return 0;
239 }
240
241 static void
242 sighup(int signo __unused)
243 {
244 onsighup = 1;
245 }
246
247 static void
248 handleread(int s)
249 {
250 struct sockaddr_in from;
251 struct stat st;
252 char path[64];
253 struct whod wd;
254 int cc, whod;
255 socklen_t len = sizeof(from);
256
257 cc = recvfrom(s, (char *)&wd, sizeof(struct whod), 0,
258 (struct sockaddr *)&from, &len);
259 if (cc <= 0) {
260 if (cc < 0 && errno != EINTR)
261 syslog(LOG_WARNING, "recv: %m");
262 return;
263 }
264 if (from.sin_port != sp->s_port) {
265 syslog(LOG_WARNING, "%d: bad from port",
266 ntohs(from.sin_port));
267 return;
268 }
269 if (cc < WHDRSIZE) {
270 syslog(LOG_WARNING, "Short packet from %s",
271 inet_ntoa(from.sin_addr));
272 return;
273 }
274
275 if (wd.wd_vers != WHODVERSION)
276 return;
277 if (wd.wd_type != WHODTYPE_STATUS)
278 return;
279 /*
280 * Ensure null termination of the name within the packet.
281 * Otherwise we might overflow or read past the end.
282 */
283 wd.wd_hostname[sizeof(wd.wd_hostname)-1] = 0;
284 if (!verify(wd.wd_hostname)) {
285 syslog(LOG_WARNING, "malformed host name from %s",
286 inet_ntoa(from.sin_addr));
287 return;
288 }
289 (void)snprintf(path, sizeof(path), "whod.%s", wd.wd_hostname);
290 /*
291 * Rather than truncating and growing the file each time,
292 * use ftruncate if size is less than previous size.
293 */
294 whod = open(path, O_WRONLY | O_CREAT, 0644);
295 if (whod < 0) {
296 syslog(LOG_WARNING, "%s: %m", path);
297 return;
298 }
299 #if ENDIAN != BIG_ENDIAN
300 {
301 int i, n = (cc - WHDRSIZE) / sizeof(struct whoent);
302 struct whoent *we;
303
304 /* undo header byte swapping before writing to file */
305 wd.wd_sendtime = ntohl(wd.wd_sendtime);
306 for (i = 0; i < 3; i++)
307 wd.wd_loadav[i] = ntohl(wd.wd_loadav[i]);
308 wd.wd_boottime = ntohl(wd.wd_boottime);
309 we = wd.wd_we;
310 for (i = 0; i < n; i++) {
311 we->we_idle = ntohl(we->we_idle);
312 we->we_utmp.out_time =
313 ntohl(we->we_utmp.out_time);
314 we++;
315 }
316 }
317 #endif
318 (void)time((time_t *)&wd.wd_recvtime);
319 (void)write(whod, (char *)&wd, cc);
320 if (fstat(whod, &st) < 0 || st.st_size > cc)
321 (void)ftruncate(whod, cc);
322 (void)close(whod);
323 }
324
325 /*
326 * Check out host name for unprintables
327 * and other funnies before allowing a file
328 * to be created. Sorry, but blanks aren't allowed.
329 */
330 static int
331 verify(const char *name)
332 {
333 int size = 0;
334
335 while (*name) {
336 if (!isascii((unsigned char)*name) ||
337 !(isalnum((unsigned char)*name) ||
338 ispunct((unsigned char)*name)))
339 return 0;
340 name++, size++;
341 }
342 return size > 0;
343 }
344
345 static void
346 send_host_information(int s)
347 {
348 struct neighbor *np;
349 struct whoent *we = mywd.wd_we, *wlast;
350 int i, cc, utmpent = 0;
351 struct stat stb;
352 double avenrun[3];
353 time_t now;
354 static struct utmpentry *ohead = NULL;
355 struct utmpentry *ep;
356 static int count = 0;
357
358 now = time(NULL);
359 if (count % 10 == 0)
360 getboottime();
361 count++;
362
363 (void)getutentries(NULL, &ep);
364 if (ep != ohead) {
365 freeutentries(ep);
366 wlast = &mywd.wd_we[1024 / sizeof(struct whoent) - 1];
367 for (; ep; ep = ep->next) {
368 (void)strncpy(we->we_utmp.out_line, ep->line,
369 sizeof(we->we_utmp.out_line) - 1);
370 (void)strncpy(we->we_utmp.out_name, ep->name,
371 sizeof(we->we_utmp.out_name) - 1);
372 we->we_utmp.out_time = htonl(ep->tv.tv_sec);
373 if (we >= wlast)
374 break;
375 we++;
376 }
377 utmpent = we - mywd.wd_we;
378 }
379
380 /*
381 * The test on utmpent looks silly---after all, if no one is
382 * logged on, why worry about efficiency?---but is useful on
383 * (e.g.) compute servers.
384 */
385 if (utmpent && chdir(_PATH_DEV)) {
386 syslog(LOG_ERR, "chdir(%s): %m", _PATH_DEV);
387 exit(EXIT_FAILURE);
388 }
389 we = mywd.wd_we;
390 for (i = 0; i < utmpent; i++) {
391 if (stat(we->we_utmp.out_line, &stb) >= 0)
392 we->we_idle = htonl(now - stb.st_atime);
393 we++;
394 }
395 (void)getloadavg(avenrun, sizeof(avenrun)/sizeof(avenrun[0]));
396 for (i = 0; i < 3; i++)
397 mywd.wd_loadav[i] = htonl((u_long)(avenrun[i] * 100));
398 cc = (char *)we - (char *)&mywd;
399 mywd.wd_sendtime = htonl(time(0));
400 mywd.wd_vers = WHODVERSION;
401 mywd.wd_type = WHODTYPE_STATUS;
402 for (np = neighbors; np != NULL; np = np->n_next)
403 (void)sendto(s, (char *)&mywd, cc, 0,
404 np->n_addr, np->n_addrlen);
405 if (utmpent && chdir(_PATH_RWHODIR)) {
406 syslog(LOG_ERR, "chdir(%s): %m", _PATH_RWHODIR);
407 exit(EXIT_FAILURE);
408 }
409 }
410
411 static void
412 getboottime(void)
413 {
414 int mib[2];
415 size_t size;
416 struct timeval tm;
417
418 mib[0] = CTL_KERN;
419 mib[1] = KERN_BOOTTIME;
420 size = sizeof(tm);
421 if (sysctl(mib, 2, &tm, &size, NULL, 0) == -1) {
422 syslog(LOG_ERR, "cannot get boottime: %m");
423 exit(EXIT_FAILURE);
424 }
425 mywd.wd_boottime = htonl(tm.tv_sec);
426 }
427
428 static void
429 quit(const char *msg)
430 {
431 syslog(LOG_ERR, "%s", msg);
432 exit(EXIT_FAILURE);
433 }
434
435 #define ROUNDUP(a) \
436 ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
437 #define ADVANCE(x, n) ((char *)(x) + ROUNDUP((n)->sa_len))
438
439 static void
440 rt_xaddrs(void *cp, void *cplim, struct rt_addrinfo *rtinfo)
441 {
442 struct sockaddr *sa;
443 int i;
444
445 (void)memset(rtinfo->rti_info, 0, sizeof(rtinfo->rti_info));
446 for (i = 0; (i < RTAX_MAX) && (cp < cplim); i++) {
447 if ((rtinfo->rti_addrs & (1 << i)) == 0)
448 continue;
449 rtinfo->rti_info[i] = sa = (struct sockaddr *)cp;
450 cp = ADVANCE(cp, sa);
451 }
452 }
453
454 /*
455 * Figure out device configuration and select
456 * networks which deserve status information.
457 */
458 static int
459 configure(int s)
460 {
461 struct neighbor *np;
462 struct if_msghdr *ifm;
463 struct ifa_msghdr *ifam;
464 struct sockaddr_dl *sdl;
465 size_t needed;
466 int mib[6], flags = 0, len;
467 char *buf, *lim, *next;
468 struct rt_addrinfo info;
469 struct sockaddr_in dstaddr;
470
471 mib[0] = CTL_NET;
472 mib[1] = PF_ROUTE;
473 mib[2] = 0;
474 mib[3] = AF_INET;
475 mib[4] = NET_RT_IFLIST;
476 mib[5] = 0;
477 if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
478 quit("route-sysctl-estimate");
479 if ((buf = malloc(needed)) == NULL)
480 quit("malloc");
481 if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0)
482 quit("actual retrieval of interface table");
483 lim = buf + needed;
484
485 sdl = NULL; /* XXX just to keep gcc -Wall happy */
486 for (next = buf; next < lim; next += ifm->ifm_msglen) {
487 ifm = (struct if_msghdr *)next;
488 if (ifm->ifm_type == RTM_IFINFO) {
489 sdl = (struct sockaddr_dl *)(ifm + 1);
490 flags = ifm->ifm_flags;
491 continue;
492 }
493 if ((flags & IFF_UP) == 0 ||
494 (flags & (IFF_BROADCAST|IFF_POINTOPOINT)) == 0)
495 continue;
496 if (ifm->ifm_type != RTM_NEWADDR)
497 quit("out of sync parsing NET_RT_IFLIST");
498 ifam = (struct ifa_msghdr *)ifm;
499 info.rti_addrs = ifam->ifam_addrs;
500 rt_xaddrs((ifam + 1), ifam->ifam_msglen + (char *)ifam, &info);
501 /* gag, wish we could get rid of Internet dependencies */
502 if (info.rti_info[RTAX_BRD] == NULL ||
503 info.rti_info[RTAX_BRD]->sa_family != AF_INET)
504 continue;
505 (void)memcpy(&dstaddr, info.rti_info[RTAX_BRD],
506 sizeof(dstaddr));
507 #define IPADDR_SA(x) ((struct sockaddr_in *)(x))->sin_addr.s_addr
508 #define PORT_SA(x) ((struct sockaddr_in *)(x))->sin_port
509 PORT_SA(&dstaddr) = sp->s_port;
510 for (np = neighbors; np != NULL; np = np->n_next)
511 if (memcmp(sdl->sdl_data, np->n_name,
512 sdl->sdl_nlen) == 0 &&
513 IPADDR_SA(np->n_addr) == IPADDR_SA(&dstaddr))
514 break;
515 if (np != NULL)
516 continue;
517 len = sizeof(*np) + dstaddr.sin_len + sdl->sdl_nlen + 1;
518 np = (struct neighbor *)malloc(len);
519 if (np == NULL)
520 quit("malloc of neighbor structure");
521 (void)memset(np, 0, len);
522 np->n_flags = flags;
523 np->n_addr = (struct sockaddr *)(np + 1);
524 np->n_addrlen = dstaddr.sin_len;
525 np->n_name = np->n_addrlen + (char *)np->n_addr;
526 np->n_next = neighbors;
527 neighbors = np;
528 (void)memcpy(np->n_addr, &dstaddr, np->n_addrlen);
529 (void)memcpy(np->n_name, sdl->sdl_data, sdl->sdl_nlen);
530 }
531 free(buf);
532 return (1);
533 }
534
535 #ifdef DEBUG
536 static ssize_t
537 Sendto(int s, const void *buf, size_t cc, int flags, const struct sockaddr *to,
538 socklen_t tolen)
539 {
540 struct whod *w = (struct whod *)buf;
541 struct whoent *we;
542 struct sockaddr_in *sasin = (struct sockaddr_in *)to;
543
544 printf("sendto %s.%d\n", inet_ntoa(sasin->sin_addr),
545 ntohs(sasin->sin_port));
546 printf("hostname %s %s\n", w->wd_hostname,
547 interval(ntohl(w->wd_sendtime) - ntohl(w->wd_boottime), " up"));
548 printf("load %4.2f, %4.2f, %4.2f\n",
549 ntohl(w->wd_loadav[0]) / 100.0, ntohl(w->wd_loadav[1]) / 100.0,
550 ntohl(w->wd_loadav[2]) / 100.0);
551 cc -= WHDRSIZE;
552 for (we = w->wd_we, cc /= sizeof(struct whoent); cc > 0; cc--, we++) {
553 time_t t = ntohl(we->we_utmp.out_time);
554 printf("%-8.8s %s:%s %.12s", we->we_utmp.out_name,
555 w->wd_hostname, we->we_utmp.out_line, ctime(&t)+4);
556 we->we_idle = ntohl(we->we_idle) / 60;
557 if (we->we_idle) {
558 if (we->we_idle >= 100*60)
559 we->we_idle = 100*60 - 1;
560 if (we->we_idle >= 60)
561 printf(" %2d", we->we_idle / 60);
562 else
563 printf(" ");
564 printf(":%02d", we->we_idle % 60);
565 }
566 printf("\n");
567 }
568 return (ssize_t)cc;
569 }
570
571 static char *
572 interval(int time, const char *updown)
573 {
574 static char resbuf[32];
575 int days, hours, minutes;
576
577 if (time < 0 || time > 3*30*24*60*60) {
578 (void)snprintf(resbuf, sizeof(resbuf), " %s ??:??", updown);
579 return (resbuf);
580 }
581 minutes = (time + 59) / 60; /* round to minutes */
582 hours = minutes / 60; minutes %= 60;
583 days = hours / 24; hours %= 24;
584 if (days)
585 (void)snprintf(resbuf, sizeof(resbuf), "%s %2d+%02d:%02d",
586 updown, days, hours, minutes);
587 else
588 (void)snprintf(resbuf, sizeof(resbuf), "%s %2d:%02d",
589 updown, hours, minutes);
590 return resbuf;
591 }
592 #endif
593
594 static void
595 usage(void)
596 {
597 fprintf(stderr, "Usage: %s [-g <time>]", getprogname());
598 exit(1);
599 }
600