rwhod.c revision 1.30 1 /* $NetBSD: rwhod.c,v 1.30 2005/07/05 02:46:36 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.30 2005/07/05 02:46:36 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 static ssize_t Sendto(int, const void *, size_t, int,
116 const struct sockaddr *, socklen_t);
117 #else
118 #define Sendto sendto
119 #endif
120
121 int
122 main(int argc, char *argv[])
123 {
124 int s, ch;
125 int time_interval = 180; /* Default time (180 seconds) */
126 char *cp, *ep;
127 socklen_t on = 1;
128 struct sockaddr_in sasin;
129 struct pollfd pfd[1];
130 struct timeval delta, next, now;
131
132 setprogname(argv[0]);
133
134 if (getuid())
135 errx(EXIT_FAILURE, "not super user");
136
137 while ((ch = getopt(argc, argv, "i:")) != -1) {
138 switch (ch) {
139 case 'i':
140 time_interval = (int)strtol(optarg, &ep, 10);
141
142 switch (*ep) {
143 case '\0':
144 break;
145 case 'm':
146 case 'M':
147 /* Time in minutes. */
148 time_interval *= 60;
149 if (ep[1] == '\0')
150 break;
151 /*FALLTHROUGH*/
152 default:
153 errx(1, "Invalid argument: `%s'", optarg);
154 }
155
156 if (time_interval <= 0)
157 errx(1, "Interval must be greater than 0");
158
159 if (time_interval > MAX_INTERVAL)
160 errx(1, "Interval cannot be greater than"
161 " %d minutes", MAX_INTERVAL / 60);
162 break;
163 default:
164 usage();
165 }
166 }
167
168 sp = getservbyname("who", "udp");
169 if (sp == NULL)
170 errx(EXIT_FAILURE, "udp/who: unknown service");
171 #ifndef DEBUG
172 (void)daemon(1, 0);
173 (void)pidfile(NULL);
174 #endif
175 if (chdir(_PATH_RWHODIR) < 0)
176 err(EXIT_FAILURE, "%s", _PATH_RWHODIR);
177 (void)signal(SIGHUP, sighup);
178 openlog(getprogname(), LOG_PID, LOG_DAEMON);
179 /*
180 * Establish host name as returned by system.
181 */
182 if (gethostname(myname, sizeof(myname) - 1) < 0) {
183 syslog(LOG_ERR, "gethostname: %m");
184 exit(EXIT_FAILURE);
185 }
186 myname[sizeof(myname) - 1] = '\0';
187 if ((cp = strchr(myname, '.')) != NULL)
188 *cp = '\0';
189 (void)strncpy(mywd.wd_hostname, myname, sizeof(mywd.wd_hostname) - 1);
190 getboottime();
191 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
192 syslog(LOG_ERR, "socket: %m");
193 exit(EXIT_FAILURE);
194 }
195 if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) < 0) {
196 syslog(LOG_ERR, "setsockopt SO_BROADCAST: %m");
197 exit(EXIT_FAILURE);
198 }
199 (void)memset(&sasin, 0, sizeof(sasin));
200 sasin.sin_family = AF_INET;
201 sasin.sin_port = sp->s_port;
202 if (bind(s, (struct sockaddr *)&sasin, sizeof(sasin)) < 0) {
203 syslog(LOG_ERR, "bind: %m");
204 exit(EXIT_FAILURE);
205 }
206 if (!configure(s))
207 exit(EXIT_FAILURE);
208
209 send_host_information(s);
210 delta.tv_sec = time_interval;
211 delta.tv_usec = 0;
212 gettimeofday(&now, NULL);
213 timeradd(&now, &delta, &next);
214
215 pfd[0].fd = s;
216 pfd[0].events = POLLIN;
217
218 for (;;) {
219 int n;
220
221 n = poll(pfd, 1, 1000);
222
223 if (onsighup) {
224 onsighup = 0;
225 getboottime();
226 }
227
228 if (n == 1)
229 handleread(s);
230
231 (void)gettimeofday(&now, NULL);
232 if (timercmp(&now, &next, >)) {
233 send_host_information(s);
234 timeradd(&now, &delta, &next);
235 }
236 }
237
238 /* NOTREACHED */
239 return 0;
240 }
241
242 static void
243 sighup(int signo __unused)
244 {
245 onsighup = 1;
246 }
247
248 static void
249 handleread(int s)
250 {
251 struct sockaddr_in from;
252 struct stat st;
253 char path[64];
254 struct whod wd;
255 int cc, whod;
256 socklen_t len = sizeof(from);
257
258 cc = recvfrom(s, (char *)&wd, sizeof(struct whod), 0,
259 (struct sockaddr *)&from, &len);
260 if (cc <= 0) {
261 if (cc < 0 && errno != EINTR)
262 syslog(LOG_WARNING, "recv: %m");
263 return;
264 }
265 if (from.sin_port != sp->s_port) {
266 syslog(LOG_WARNING, "%d: bad from port",
267 ntohs(from.sin_port));
268 return;
269 }
270 if (cc < WHDRSIZE) {
271 syslog(LOG_WARNING, "Short packet from %s",
272 inet_ntoa(from.sin_addr));
273 return;
274 }
275
276 if (wd.wd_vers != WHODVERSION)
277 return;
278 if (wd.wd_type != WHODTYPE_STATUS)
279 return;
280 /*
281 * Ensure null termination of the name within the packet.
282 * Otherwise we might overflow or read past the end.
283 */
284 wd.wd_hostname[sizeof(wd.wd_hostname)-1] = 0;
285 if (!verify(wd.wd_hostname)) {
286 syslog(LOG_WARNING, "malformed host name from %s",
287 inet_ntoa(from.sin_addr));
288 return;
289 }
290 (void)snprintf(path, sizeof(path), "whod.%s", wd.wd_hostname);
291 /*
292 * Rather than truncating and growing the file each time,
293 * use ftruncate if size is less than previous size.
294 */
295 whod = open(path, O_WRONLY | O_CREAT, 0644);
296 if (whod < 0) {
297 syslog(LOG_WARNING, "%s: %m", path);
298 return;
299 }
300 #if ENDIAN != BIG_ENDIAN
301 {
302 int i, n = (cc - WHDRSIZE) / sizeof(struct whoent);
303 struct whoent *we;
304
305 /* undo header byte swapping before writing to file */
306 wd.wd_sendtime = ntohl(wd.wd_sendtime);
307 for (i = 0; i < 3; i++)
308 wd.wd_loadav[i] = ntohl(wd.wd_loadav[i]);
309 wd.wd_boottime = ntohl(wd.wd_boottime);
310 we = wd.wd_we;
311 for (i = 0; i < n; i++) {
312 we->we_idle = ntohl(we->we_idle);
313 we->we_utmp.out_time =
314 ntohl(we->we_utmp.out_time);
315 we++;
316 }
317 }
318 #endif
319 (void)time((time_t *)&wd.wd_recvtime);
320 (void)write(whod, (char *)&wd, cc);
321 if (fstat(whod, &st) < 0 || st.st_size > cc)
322 (void)ftruncate(whod, cc);
323 (void)close(whod);
324 }
325
326 /*
327 * Check out host name for unprintables
328 * and other funnies before allowing a file
329 * to be created. Sorry, but blanks aren't allowed.
330 */
331 static int
332 verify(const char *name)
333 {
334 int size = 0;
335
336 while (*name) {
337 if (!isascii((unsigned char)*name) ||
338 !(isalnum((unsigned char)*name) ||
339 ispunct((unsigned char)*name)))
340 return 0;
341 name++, size++;
342 }
343 return size > 0;
344 }
345
346 static void
347 send_host_information(int s)
348 {
349 struct neighbor *np;
350 struct whoent *we = mywd.wd_we, *wlast;
351 int i, cc, utmpent = 0;
352 struct stat stb;
353 double avenrun[3];
354 time_t now;
355 static struct utmpentry *ohead = NULL;
356 struct utmpentry *ep;
357 static int count = 0;
358
359 now = time(NULL);
360 if (count % 10 == 0)
361 getboottime();
362 count++;
363
364 (void)getutentries(NULL, &ep);
365 if (ep != ohead) {
366 freeutentries(ep);
367 wlast = &mywd.wd_we[1024 / sizeof(struct whoent) - 1];
368 for (; ep; ep = ep->next) {
369 (void)strncpy(we->we_utmp.out_line, ep->line,
370 sizeof(we->we_utmp.out_line) - 1);
371 (void)strncpy(we->we_utmp.out_name, ep->name,
372 sizeof(we->we_utmp.out_name) - 1);
373 we->we_utmp.out_time = htonl(ep->tv.tv_sec);
374 if (we >= wlast)
375 break;
376 we++;
377 }
378 utmpent = we - mywd.wd_we;
379 }
380
381 /*
382 * The test on utmpent looks silly---after all, if no one is
383 * logged on, why worry about efficiency?---but is useful on
384 * (e.g.) compute servers.
385 */
386 if (utmpent && chdir(_PATH_DEV)) {
387 syslog(LOG_ERR, "chdir(%s): %m", _PATH_DEV);
388 exit(EXIT_FAILURE);
389 }
390 we = mywd.wd_we;
391 for (i = 0; i < utmpent; i++) {
392 if (stat(we->we_utmp.out_line, &stb) >= 0)
393 we->we_idle = htonl(now - stb.st_atime);
394 we++;
395 }
396 (void)getloadavg(avenrun, sizeof(avenrun)/sizeof(avenrun[0]));
397 for (i = 0; i < 3; i++)
398 mywd.wd_loadav[i] = htonl((u_long)(avenrun[i] * 100));
399 cc = (char *)we - (char *)&mywd;
400 mywd.wd_sendtime = htonl(time(0));
401 mywd.wd_vers = WHODVERSION;
402 mywd.wd_type = WHODTYPE_STATUS;
403 for (np = neighbors; np != NULL; np = np->n_next)
404 (void)Sendto(s, (char *)&mywd, cc, 0,
405 np->n_addr, np->n_addrlen);
406 if (utmpent && chdir(_PATH_RWHODIR)) {
407 syslog(LOG_ERR, "chdir(%s): %m", _PATH_RWHODIR);
408 exit(EXIT_FAILURE);
409 }
410 }
411
412 static void
413 getboottime(void)
414 {
415 int mib[2];
416 size_t size;
417 struct timeval tm;
418
419 mib[0] = CTL_KERN;
420 mib[1] = KERN_BOOTTIME;
421 size = sizeof(tm);
422 if (sysctl(mib, 2, &tm, &size, NULL, 0) == -1) {
423 syslog(LOG_ERR, "cannot get boottime: %m");
424 exit(EXIT_FAILURE);
425 }
426 mywd.wd_boottime = htonl(tm.tv_sec);
427 }
428
429 static void
430 quit(const char *msg)
431 {
432 syslog(LOG_ERR, "%s", msg);
433 exit(EXIT_FAILURE);
434 }
435
436 #define ROUNDUP(a) \
437 ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
438 #define ADVANCE(x, n) ((char *)(x) + ROUNDUP((n)->sa_len))
439
440 static void
441 rt_xaddrs(void *cp, void *cplim, struct rt_addrinfo *rtinfo)
442 {
443 struct sockaddr *sa;
444 int i;
445
446 (void)memset(rtinfo->rti_info, 0, sizeof(rtinfo->rti_info));
447 for (i = 0; (i < RTAX_MAX) && (cp < cplim); i++) {
448 if ((rtinfo->rti_addrs & (1 << i)) == 0)
449 continue;
450 rtinfo->rti_info[i] = sa = (struct sockaddr *)cp;
451 cp = ADVANCE(cp, sa);
452 }
453 }
454
455 /*
456 * Figure out device configuration and select
457 * networks which deserve status information.
458 */
459 static int
460 configure(int s)
461 {
462 struct neighbor *np;
463 struct if_msghdr *ifm;
464 struct ifa_msghdr *ifam;
465 struct sockaddr_dl *sdl;
466 size_t needed;
467 int mib[6], flags = 0, len;
468 char *buf, *lim, *next;
469 struct rt_addrinfo info;
470 struct sockaddr_in dstaddr;
471
472 mib[0] = CTL_NET;
473 mib[1] = PF_ROUTE;
474 mib[2] = 0;
475 mib[3] = AF_INET;
476 mib[4] = NET_RT_IFLIST;
477 mib[5] = 0;
478 if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
479 quit("route-sysctl-estimate");
480 if ((buf = malloc(needed)) == NULL)
481 quit("malloc");
482 if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0)
483 quit("actual retrieval of interface table");
484 lim = buf + needed;
485
486 sdl = NULL; /* XXX just to keep gcc -Wall happy */
487 for (next = buf; next < lim; next += ifm->ifm_msglen) {
488 ifm = (struct if_msghdr *)next;
489 if (ifm->ifm_type == RTM_IFINFO) {
490 sdl = (struct sockaddr_dl *)(ifm + 1);
491 flags = ifm->ifm_flags;
492 continue;
493 }
494 if ((flags & IFF_UP) == 0 ||
495 (flags & (IFF_BROADCAST|IFF_POINTOPOINT)) == 0)
496 continue;
497 if (ifm->ifm_type != RTM_NEWADDR)
498 quit("out of sync parsing NET_RT_IFLIST");
499 ifam = (struct ifa_msghdr *)ifm;
500 info.rti_addrs = ifam->ifam_addrs;
501 rt_xaddrs((ifam + 1), ifam->ifam_msglen + (char *)ifam, &info);
502 /* gag, wish we could get rid of Internet dependencies */
503 if (info.rti_info[RTAX_BRD] == NULL ||
504 info.rti_info[RTAX_BRD]->sa_family != AF_INET)
505 continue;
506 (void)memcpy(&dstaddr, info.rti_info[RTAX_BRD],
507 sizeof(dstaddr));
508 #define IPADDR_SA(x) ((struct sockaddr_in *)(x))->sin_addr.s_addr
509 #define PORT_SA(x) ((struct sockaddr_in *)(x))->sin_port
510 PORT_SA(&dstaddr) = sp->s_port;
511 for (np = neighbors; np != NULL; np = np->n_next)
512 if (memcmp(sdl->sdl_data, np->n_name,
513 sdl->sdl_nlen) == 0 &&
514 IPADDR_SA(np->n_addr) == IPADDR_SA(&dstaddr))
515 break;
516 if (np != NULL)
517 continue;
518 len = sizeof(*np) + dstaddr.sin_len + sdl->sdl_nlen + 1;
519 np = (struct neighbor *)malloc(len);
520 if (np == NULL)
521 quit("malloc of neighbor structure");
522 (void)memset(np, 0, len);
523 np->n_flags = flags;
524 np->n_addr = (struct sockaddr *)(np + 1);
525 np->n_addrlen = dstaddr.sin_len;
526 np->n_name = np->n_addrlen + (char *)np->n_addr;
527 np->n_next = neighbors;
528 neighbors = np;
529 (void)memcpy(np->n_addr, &dstaddr, np->n_addrlen);
530 (void)memcpy(np->n_name, sdl->sdl_data, sdl->sdl_nlen);
531 }
532 free(buf);
533 return (1);
534 }
535
536 #ifdef DEBUG
537 static ssize_t
538 Sendto(int s, const void *buf, size_t cc, int flags, const struct sockaddr *to,
539 socklen_t tolen)
540 {
541 struct whod *w = (struct whod *)buf;
542 struct whoent *we;
543 struct sockaddr_in *sasin = (struct sockaddr_in *)to;
544 ssize_t ret;
545
546 ret = sendto(s, buf, cc, flags, to, tolen);
547
548 printf("sendto %s.%d\n", inet_ntoa(sasin->sin_addr),
549 ntohs(sasin->sin_port));
550 printf("hostname %s %s\n", w->wd_hostname,
551 interval(ntohl(w->wd_sendtime) - ntohl(w->wd_boottime), " up"));
552 printf("load %4.2f, %4.2f, %4.2f\n",
553 ntohl(w->wd_loadav[0]) / 100.0, ntohl(w->wd_loadav[1]) / 100.0,
554 ntohl(w->wd_loadav[2]) / 100.0);
555 cc -= WHDRSIZE;
556 for (we = w->wd_we, cc /= sizeof(struct whoent); cc > 0; cc--, we++) {
557 time_t t = ntohl(we->we_utmp.out_time);
558 printf("%-8.8s %s:%s %.12s", we->we_utmp.out_name,
559 w->wd_hostname, we->we_utmp.out_line, ctime(&t)+4);
560 we->we_idle = ntohl(we->we_idle) / 60;
561 if (we->we_idle) {
562 if (we->we_idle >= 100*60)
563 we->we_idle = 100*60 - 1;
564 if (we->we_idle >= 60)
565 printf(" %2d", we->we_idle / 60);
566 else
567 printf(" ");
568 printf(":%02d", we->we_idle % 60);
569 }
570 printf("\n");
571 }
572 return ret;
573 }
574
575 static char *
576 interval(int time, const char *updown)
577 {
578 static char resbuf[32];
579 int days, hours, minutes;
580
581 if (time < 0 || time > 3*30*24*60*60) {
582 (void)snprintf(resbuf, sizeof(resbuf), " %s ??:??", updown);
583 return (resbuf);
584 }
585 minutes = (time + 59) / 60; /* round to minutes */
586 hours = minutes / 60; minutes %= 60;
587 days = hours / 24; hours %= 24;
588 if (days)
589 (void)snprintf(resbuf, sizeof(resbuf), "%s %2d+%02d:%02d",
590 updown, days, hours, minutes);
591 else
592 (void)snprintf(resbuf, sizeof(resbuf), "%s %2d:%02d",
593 updown, hours, minutes);
594 return resbuf;
595 }
596 #endif
597
598 static void
599 usage(void)
600 {
601 (void)fprintf(stderr, "Usage: %s [-i <time>]\n", getprogname());
602 exit(EXIT_FAILURE);
603 }
604