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