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