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