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