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