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