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
30 #ifndef lint
31 static char copyright[] =
32 "@(#) Copyright (c) 1983, 1993\n\
33 The Regents of the University of California. All rights reserved.\n";
34 #endif /* not lint */
35
36 #ifndef lint
37 /*static char sccsid[] = "@(#)rwhod.c 8.1 (Berkeley) 6/6/93";*/
38 static char rcsid[] = "$OpenBSD: rwhod.c,v 1.30 2004/09/16 08:55:00 deraadt Exp $";
39 #endif /* not lint */
40
41 #include <sys/param.h>
42 #include <sys/socket.h>
43 #include <sys/stat.h>
44 #include <sys/signal.h>
45 #include <sys/ioctl.h>
46 #include <sys/sysctl.h>
47
48 #include <net/if.h>
49 #include <net/if_dl.h>
50 #include <net/route.h>
51 #include <netinet/in.h>
52 #include <protocols/rwhod.h>
53 #include <arpa/inet.h>
54
55 #include <ctype.h>
56 #include <errno.h>
57 #include <fcntl.h>
58 #include <poll.h>
59 #include <netdb.h>
60 #include <paths.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <syslog.h>
65 #include <unistd.h>
66 #include <utmp.h>
67 #include <err.h>
68
69 /*
70 * Alarm interval. Don't forget to change the down time check in ruptime
71 * if this is changed.
72 */
73 #define AL_INTERVAL (3 * 60)
74
75 char myname[MAXHOSTNAMELEN];
76
77 int debug;
78
79 /*
80 * We communicate with each neighbor in a list constructed at the time we're
81 * started up. Neighbors are currently directly connected via a hardware
82 * interface.
83 */
84 struct neighbor {
85 struct neighbor *n_next;
86 char *n_name; /* interface name */
87 struct sockaddr *n_addr; /* who to send to */
88 int n_addrlen; /* size of address */
89 int n_flags; /* should forward?, interface flags */
90 };
91
92 struct neighbor *neighbors;
93 struct whod mywd;
94 struct servent *sp;
95 int s, utmpf;
96
97 volatile sig_atomic_t gothup;
98
99 #define WHDRSIZE (sizeof(mywd) - sizeof(mywd.wd_we))
100
101 int configure(void);
102 void getboottime(void);
103 void hup(int);
104 void timer(void);
105 void quit(char *);
106 void rt_xaddrs(caddr_t, caddr_t, struct rt_addrinfo *);
107 int verify(char *);
108 void handleread(int s);
109 int Sendto(int, const void *, size_t, int, const struct sockaddr *,
110 socklen_t);
111 char *interval(int, char *);
112
113 /* ARGSUSED */
114 void
hup(int signo)115 hup(int signo)
116 {
117 gothup = 1;
118 }
119
120 void
usage(void)121 usage(void)
122 {
123 extern char *__progname;
124 fprintf(stderr, "usage: %s [-d]\n", __progname);
125 exit(1);
126 }
127
128 int
main(int argc,char * argv[])129 main(int argc, char *argv[])
130 {
131 struct timeval start, next, delta, now;
132 struct sockaddr_in sin;
133 struct pollfd pfd[1];
134 int on = 1, ch;
135 char *cp;
136
137 while ((ch = getopt(argc, argv, "d")) != -1) {
138 switch (ch) {
139 case 'd':
140 debug = 1;
141 break;
142 default:
143 usage();
144 }
145 }
146
147 if (getuid())
148 errx(1, "not super user");
149 sp = getservbyname("who", "udp");
150 if (sp == NULL)
151 errx(1, "udp/who: unknown service");
152 if (chdir(_PATH_RWHODIR) < 0)
153 err(1, "%s", _PATH_RWHODIR);
154 if (!debug)
155 daemon(1, 0);
156
157 (void) signal(SIGHUP, hup);
158 openlog("rwhod", LOG_PID, LOG_DAEMON);
159 /*
160 * Establish host name as returned by system.
161 */
162 if (gethostname(myname, sizeof(myname)) < 0) {
163 syslog(LOG_ERR, "gethostname: %m");
164 exit(1);
165 }
166 if ((cp = strchr(myname, '.')) != NULL)
167 *cp = '\0';
168 strncpy(mywd.wd_hostname, myname, sizeof(mywd.wd_hostname) - 1);
169 mywd.wd_hostname[sizeof(mywd.wd_hostname) - 1] = '\0';
170 utmpf = open(_PATH_UTMP, O_RDONLY|O_CREAT, 0644);
171 if (utmpf < 0) {
172 syslog(LOG_ERR, "%s: %m", _PATH_UTMP);
173 exit(1);
174 }
175 getboottime();
176 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
177 syslog(LOG_ERR, "socket: %m");
178 exit(1);
179 }
180 if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) < 0) {
181 syslog(LOG_ERR, "setsockopt SO_BROADCAST: %m");
182 exit(1);
183 }
184 memset(&sin, 0, sizeof(sin));
185 sin.sin_addr.s_addr = INADDR_ANY;
186 sin.sin_family = AF_INET;
187 sin.sin_port = sp->s_port;
188 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
189 syslog(LOG_ERR, "bind: %m");
190 exit(1);
191 }
192 if (!configure())
193 exit(1);
194 timer();
195
196 gettimeofday(&start, NULL);
197 delta.tv_sec = AL_INTERVAL;
198 delta.tv_usec = 0;
199 timeradd(&start, &delta, &next);
200
201 pfd[0].fd = s;
202 pfd[0].events = POLLIN;
203
204 for (;;) {
205 int n;
206
207 n = poll(pfd, 1, 1000);
208
209 if (n == 1)
210 handleread(s);
211
212 if (gothup) {
213 gothup = 0;
214 getboottime();
215 }
216
217 gettimeofday(&now, NULL);
218 if (timercmp(&now, &next, >)) {
219 timer();
220 timeradd(&now, &delta, &next);
221 }
222 }
223 }
224
225 void
handleread(int s)226 handleread(int s)
227 {
228 struct sockaddr_in from;
229 struct stat st;
230 char path[64];
231 struct whod wd;
232 int cc, whod;
233 socklen_t len = sizeof(from);
234
235 cc = recvfrom(s, (char *)&wd, sizeof(struct whod), 0,
236 (struct sockaddr *)&from, &len);
237 if (cc <= 0) {
238 if (cc < 0 && errno != EINTR)
239 syslog(LOG_WARNING, "recv: %m");
240 return;
241 }
242 if (from.sin_port != sp->s_port) {
243 syslog(LOG_WARNING, "%d: bad source port from %s",
244 ntohs(from.sin_port), inet_ntoa(from.sin_addr));
245 return;
246 }
247 if (cc < WHDRSIZE) {
248 syslog(LOG_WARNING, "short packet from %s",
249 inet_ntoa(from.sin_addr));
250 return;
251 }
252 if (wd.wd_vers != WHODVERSION)
253 return;
254 if (wd.wd_type != WHODTYPE_STATUS)
255 return;
256 wd.wd_hostname[sizeof(wd.wd_hostname)-1] = '\0';
257 if (!verify(wd.wd_hostname)) {
258 syslog(LOG_WARNING, "malformed host name from %s",
259 inet_ntoa(from.sin_addr));
260 return;
261 }
262 if (debug)
263 printf("host %s\n", wd.wd_hostname);
264
265 (void) snprintf(path, sizeof path, "whod.%s", wd.wd_hostname);
266 /*
267 * Rather than truncating and growing the file each time,
268 * use ftruncate if size is less than previous size.
269 */
270 whod = open(path, O_WRONLY | O_CREAT, 0644);
271 if (whod < 0) {
272 syslog(LOG_WARNING, "%s: %m", path);
273 return;
274 }
275 #if ENDIAN != BIG_ENDIAN
276 {
277 int i, n = (cc - WHDRSIZE)/sizeof(struct whoent);
278 struct whoent *we;
279
280 /* undo header byte swapping before writing to file */
281 wd.wd_sendtime = ntohl(wd.wd_sendtime);
282 for (i = 0; i < 3; i++)
283 wd.wd_loadav[i] = ntohl(wd.wd_loadav[i]);
284 wd.wd_boottime = ntohl(wd.wd_boottime);
285 we = wd.wd_we;
286 for (i = 0; i < n; i++) {
287 we->we_idle = ntohl(we->we_idle);
288 we->we_utmp.out_time =
289 ntohl(we->we_utmp.out_time);
290 we++;
291 }
292 }
293 #endif
294 (void) time((time_t *)&wd.wd_recvtime);
295 (void) write(whod, (char *)&wd, cc);
296 if (fstat(whod, &st) < 0 || st.st_size > cc)
297 ftruncate(whod, (off_t)cc);
298 (void) close(whod);
299 }
300
301 /*
302 * Check out host name for unprintables
303 * and other funnies before allowing a file
304 * to be created. Sorry, but blanks aren't allowed.
305 */
306 int
verify(char * p)307 verify(char *p)
308 {
309 char c;
310
311 /*
312 * Many people do not obey RFC 822 and 1035. The valid
313 * characters are a-z, A-Z, 0-9, '-' and . But the others
314 * tested for below can happen, and we must be more permissive
315 * than the resolver until those idiots clean up their act.
316 */
317 if (*p == '.' || *p == '-')
318 return 0;
319 while ((c = *p++)) {
320 if (('a' <= c && c <= 'z') ||
321 ('A' <= c && c <= 'Z') ||
322 ('0' <= c && c <= '9'))
323 continue;
324 if (c == '.' && *p == '.')
325 return 0;
326 if (c == '.' || c == '-')
327 continue;
328 return 0;
329 }
330 return 1;
331 }
332
333 int utmptime;
334 int utmpent;
335 int utmpsize = 0;
336 struct utmp *utmp;
337 int alarmcount;
338
339 void
timer(void)340 timer(void)
341 {
342 struct neighbor *np;
343 struct whoent *we = mywd.wd_we, *wlast;
344 int i;
345 struct stat stb;
346 double avenrun[3];
347 time_t now;
348 struct utmp *nutmp;
349 int cc;
350
351 now = time(NULL);
352 if (alarmcount % 10 == 0)
353 getboottime();
354 alarmcount++;
355 (void) fstat(utmpf, &stb);
356
357 /* implicitly safe truncation */
358 if (stb.st_size > 1024*1024 * sizeof(struct utmp))
359 stb.st_size = 1024*1024 * sizeof(struct utmp);
360
361 if ((stb.st_mtime != utmptime) || (stb.st_size > utmpsize)) {
362 utmptime = stb.st_mtime;
363 if (stb.st_size > utmpsize) {
364 int nutmpsize = stb.st_size + 10 * sizeof(struct utmp);
365 nutmp = (struct utmp *)realloc(utmp, nutmpsize);
366 if (!nutmp) {
367 warnx("malloc failed");
368 free(utmp);
369 utmpsize = 0;
370 return;
371 }
372 utmp = nutmp;
373 utmpsize = nutmpsize;
374 }
375 (void) lseek(utmpf, (off_t)0, SEEK_SET);
376 cc = read(utmpf, (char *)utmp, (size_t)stb.st_size);
377 if (cc < 0) {
378 warnx("%s", _PATH_UTMP);
379 return;
380 }
381 wlast = &mywd.wd_we[1024 / sizeof(struct whoent) - 1];
382 utmpent = cc / sizeof(struct utmp);
383 for (i = 0; i < utmpent; i++)
384 if (utmp[i].ut_name[0]) {
385 memcpy(we->we_utmp.out_line, utmp[i].ut_line,
386 sizeof(utmp[i].ut_line));
387 memcpy(we->we_utmp.out_name, utmp[i].ut_name,
388 sizeof(utmp[i].ut_name));
389 we->we_utmp.out_time = htonl(utmp[i].ut_time);
390 if (we >= wlast)
391 break;
392 we++;
393 }
394 utmpent = we - mywd.wd_we;
395 }
396
397 /*
398 * The test on utmpent looks silly---after all, if no one is
399 * logged on, why worry about efficiency?---but is useful on
400 * (e.g.) compute servers.
401 */
402 if (utmpent && chdir(_PATH_DEV)) {
403 syslog(LOG_ERR, "chdir(%s): %m", _PATH_DEV);
404 exit(1);
405 }
406 we = mywd.wd_we;
407 for (i = 0; i < utmpent; i++) {
408 if (stat(we->we_utmp.out_line, &stb) >= 0)
409 we->we_idle = htonl(now - stb.st_atime);
410 we++;
411 }
412 (void)getloadavg(avenrun, sizeof(avenrun)/sizeof(avenrun[0]));
413 for (i = 0; i < 3; i++)
414 mywd.wd_loadav[i] = htonl((u_long)(avenrun[i] * 100));
415 cc = (char *)we - (char *)&mywd;
416 mywd.wd_sendtime = htonl(time(0));
417 mywd.wd_vers = WHODVERSION;
418 mywd.wd_type = WHODTYPE_STATUS;
419 for (np = neighbors; np != NULL; np = np->n_next)
420 (void)Sendto(s, &mywd, cc, 0, np->n_addr, np->n_addrlen);
421 if (utmpent && chdir(_PATH_RWHODIR)) {
422 syslog(LOG_ERR, "chdir(%s): %m", _PATH_RWHODIR);
423 exit(1);
424 }
425 }
426
427 void
getboottime(void)428 getboottime(void)
429 {
430 int mib[2];
431 size_t size;
432 struct timeval tm;
433
434 mib[0] = CTL_KERN;
435 mib[1] = KERN_BOOTTIME;
436 size = sizeof(tm);
437 if (sysctl(mib, 2, &tm, &size, NULL, 0) == -1) {
438 syslog(LOG_ERR, "cannot get boottime: %m");
439 exit(1);
440 }
441 mywd.wd_boottime = htonl(tm.tv_sec);
442 }
443
444 void
quit(char * msg)445 quit(char *msg)
446 {
447 syslog(LOG_ERR, "%s", msg);
448 exit(1);
449 }
450
451 #define ROUNDUP(a) \
452 ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
453 #define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))
454
455 void
rt_xaddrs(caddr_t cp,caddr_t cplim,struct rt_addrinfo * rtinfo)456 rt_xaddrs(caddr_t cp, caddr_t cplim, struct rt_addrinfo *rtinfo)
457 {
458 struct sockaddr *sa;
459 int i;
460
461 memset(rtinfo->rti_info, 0, sizeof(rtinfo->rti_info));
462 for (i = 0; (i < RTAX_MAX) && (cp < cplim); i++) {
463 if ((rtinfo->rti_addrs & (1 << i)) == 0)
464 continue;
465 rtinfo->rti_info[i] = sa = (struct sockaddr *)cp;
466 ADVANCE(cp, sa);
467 }
468 }
469
470 /*
471 * Figure out device configuration and select
472 * networks which deserve status information.
473 */
474 int
configure(void)475 configure(void)
476 {
477 struct neighbor *np;
478 struct if_msghdr *ifm;
479 struct ifa_msghdr *ifam;
480 struct sockaddr_dl *sdl;
481 size_t needed;
482 int mib[6], flags = 0, len;
483 char *buf, *lim, *next;
484 struct rt_addrinfo info;
485
486 mib[0] = CTL_NET;
487 mib[1] = PF_ROUTE;
488 mib[2] = 0;
489 mib[3] = AF_INET;
490 mib[4] = NET_RT_IFLIST;
491 mib[5] = 0;
492 if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
493 quit("route-sysctl-estimate");
494 if ((buf = malloc(needed)) == NULL)
495 quit("malloc");
496 if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0)
497 quit("actual retrieval of interface table");
498 lim = buf + needed;
499
500 sdl = NULL; /* XXX just to keep gcc -Wall happy */
501 for (next = buf; next < lim; next += ifm->ifm_msglen) {
502 ifm = (struct if_msghdr *)next;
503 if (ifm->ifm_type == RTM_IFINFO) {
504 sdl = (struct sockaddr_dl *)(ifm + 1);
505 flags = ifm->ifm_flags;
506 continue;
507 }
508 if ((flags & IFF_UP) == 0 ||
509 (flags & (IFF_BROADCAST|IFF_POINTOPOINT)) == 0)
510 continue;
511 if (ifm->ifm_type != RTM_NEWADDR)
512 quit("out of sync parsing NET_RT_IFLIST");
513 ifam = (struct ifa_msghdr *)ifm;
514 info.rti_addrs = ifam->ifam_addrs;
515 rt_xaddrs((char *)(ifam + 1), ifam->ifam_msglen + (char *)ifam,
516 &info);
517 /* gag, wish we could get rid of Internet dependencies */
518 #define dstaddr info.rti_info[RTAX_BRD]
519 #define IPADDR_SA(x) ((struct sockaddr_in *)(x))->sin_addr.s_addr
520 #define PORT_SA(x) ((struct sockaddr_in *)(x))->sin_port
521 if (dstaddr == 0 || dstaddr->sa_family != AF_INET)
522 continue;
523 PORT_SA(dstaddr) = sp->s_port;
524 for (np = neighbors; np != NULL; np = np->n_next)
525 if (memcmp(sdl->sdl_data, np->n_name,
526 sdl->sdl_nlen) == 0 &&
527 IPADDR_SA(np->n_addr) == IPADDR_SA(dstaddr))
528 break;
529 if (np != NULL)
530 continue;
531 len = sizeof(*np) + dstaddr->sa_len + sdl->sdl_nlen + 1;
532 np = (struct neighbor *)malloc(len);
533 if (np == NULL)
534 quit("malloc of neighbor structure");
535 memset(np, 0, len);
536 np->n_flags = flags;
537 np->n_addr = (struct sockaddr *)(np + 1);
538 np->n_addrlen = dstaddr->sa_len;
539 np->n_name = np->n_addrlen + (char *)np->n_addr;
540 np->n_next = neighbors;
541 neighbors = np;
542 memcpy((char *)np->n_addr, (char *)dstaddr, np->n_addrlen);
543 memcpy(np->n_name, sdl->sdl_data, sdl->sdl_nlen);
544 }
545 free(buf);
546 return (1);
547 }
548
549 int
Sendto(int s,const void * buf,size_t cc,int flags,const struct sockaddr * to,socklen_t tolen)550 Sendto(int s, const void *buf, size_t cc, int flags,
551 const struct sockaddr *to, socklen_t tolen)
552 {
553 struct whod *w = (struct whod *)buf;
554 struct whoent *we;
555 struct sockaddr_in *sin = (struct sockaddr_in *)to;
556 int ret;
557
558 ret = sendto(s, buf, cc, flags, to, tolen);
559 if (debug) {
560 printf("sendto %s.%d\n", inet_ntoa(sin->sin_addr),
561 ntohs(sin->sin_port));
562 printf("hostname %s %s\n", w->wd_hostname,
563 interval(ntohl(w->wd_sendtime) - ntohl(w->wd_boottime),
564 " up"));
565 printf("load %4.2f, %4.2f, %4.2f\n",
566 ntohl(w->wd_loadav[0]) / 100.0,
567 ntohl(w->wd_loadav[1]) / 100.0,
568 ntohl(w->wd_loadav[2]) / 100.0);
569 cc -= WHDRSIZE;
570 for (we = w->wd_we, cc /= sizeof(struct whoent); cc > 0;
571 cc--, we++) {
572 time_t t = ntohl(we->we_utmp.out_time);
573 printf("%-8.8s %s:%s %.12s",
574 we->we_utmp.out_name,
575 w->wd_hostname, we->we_utmp.out_line,
576 ctime(&t)+4);
577 we->we_idle = ntohl(we->we_idle) / 60;
578 if (we->we_idle) {
579 if (we->we_idle >= 100*60)
580 we->we_idle = 100*60 - 1;
581 if (we->we_idle >= 60)
582 printf(" %2d", we->we_idle / 60);
583 else
584 printf(" ");
585 printf(":%02u", we->we_idle % 60);
586 }
587 printf("\n");
588 }
589 }
590 return (ret);
591 }
592
593 char *
interval(int time,char * updown)594 interval(int time, char *updown)
595 {
596 static char resbuf[32];
597 int days, hours, minutes;
598
599 if (time < 0 || time > 3*30*24*60*60) {
600 (void) snprintf(resbuf, sizeof(resbuf),
601 " %s ??:??", updown);
602 return (resbuf);
603 }
604 minutes = (time + 59) / 60; /* round to minutes */
605 hours = minutes / 60; minutes %= 60;
606 days = hours / 24; hours %= 24;
607 if (days)
608 (void) snprintf(resbuf, sizeof(resbuf),
609 "%s %2d+%02d:%02d", updown, days, hours, minutes);
610 else
611 (void) snprintf(resbuf, sizeof(resbuf),
612 "%s %2d:%02d", updown, hours, minutes);
613 return (resbuf);
614 }
615