xref: /netbsd/usr.sbin/rwhod/rwhod.c (revision c4a72b64)
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.19 2002/08/02 02:38:15 christos 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 
75 #include "utmpentry.h"
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;
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 	getboottime(0);
154 	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
155 		syslog(LOG_ERR, "socket: %m");
156 		exit(1);
157 	}
158 	if (setsockopt(s, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) < 0) {
159 		syslog(LOG_ERR, "setsockopt SO_BROADCAST: %m");
160 		exit(1);
161 	}
162 	memset(&sin, 0, sizeof(sin));
163 	sin.sin_family = AF_INET;
164 	sin.sin_port = sp->s_port;
165 	if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
166 		syslog(LOG_ERR, "bind: %m");
167 		exit(1);
168 	}
169 	if (!configure(s))
170 		exit(1);
171 	signal(SIGALRM, onalrm);
172 	onalrm(0);
173 	for (;;) {
174 		struct whod wd;
175 		int cc, whod, len = sizeof(from);
176 
177 		cc = recvfrom(s, (char *)&wd, sizeof(struct whod), 0,
178 			(struct sockaddr *)&from, &len);
179 		if (cc <= 0) {
180 			if (cc < 0 && errno != EINTR)
181 				syslog(LOG_WARNING, "recv: %m");
182 			continue;
183 		}
184 		if (from.sin_port != sp->s_port) {
185 			syslog(LOG_WARNING, "%d: bad from port",
186 				ntohs(from.sin_port));
187 			continue;
188 		}
189 		if (cc < WHDRSIZE) {
190 			syslog(LOG_WARNING, "Short packet from %s",
191 				inet_ntoa(from.sin_addr));
192 			continue;
193 		}
194 
195 		if (wd.wd_vers != WHODVERSION)
196 			continue;
197 		if (wd.wd_type != WHODTYPE_STATUS)
198 			continue;
199 		/*
200 		 * Ensure null termination of the name within the packet.
201 		 * Otherwise we might overflow or read past the end.
202 		 */
203 		wd.wd_hostname[sizeof(wd.wd_hostname)-1] = 0;
204 		if (!verify(wd.wd_hostname)) {
205 			syslog(LOG_WARNING, "malformed host name from %s",
206 				inet_ntoa(from.sin_addr));
207 			continue;
208 		}
209 		snprintf(path, sizeof(path), "whod.%s", wd.wd_hostname);
210 		/*
211 		 * Rather than truncating and growing the file each time,
212 		 * use ftruncate if size is less than previous size.
213 		 */
214 		whod = open(path, O_WRONLY | O_CREAT, 0644);
215 		if (whod < 0) {
216 			syslog(LOG_WARNING, "%s: %m", path);
217 			continue;
218 		}
219 #if ENDIAN != BIG_ENDIAN
220 		{
221 			int i, n = (cc - WHDRSIZE)/sizeof(struct whoent);
222 			struct whoent *we;
223 
224 			/* undo header byte swapping before writing to file */
225 			wd.wd_sendtime = ntohl(wd.wd_sendtime);
226 			for (i = 0; i < 3; i++)
227 				wd.wd_loadav[i] = ntohl(wd.wd_loadav[i]);
228 			wd.wd_boottime = ntohl(wd.wd_boottime);
229 			we = wd.wd_we;
230 			for (i = 0; i < n; i++) {
231 				we->we_idle = ntohl(we->we_idle);
232 				we->we_utmp.out_time =
233 				    ntohl(we->we_utmp.out_time);
234 				we++;
235 			}
236 		}
237 #endif
238 		(void)time((time_t *)&wd.wd_recvtime);
239 		(void)write(whod, (char *)&wd, cc);
240 		if (fstat(whod, &st) < 0 || st.st_size > cc)
241 			ftruncate(whod, cc);
242 		(void)close(whod);
243 	}
244 }
245 
246 /*
247  * Check out host name for unprintables
248  * and other funnies before allowing a file
249  * to be created.  Sorry, but blanks aren't allowed.
250  */
251 int
252 verify(name)
253 	char *name;
254 {
255 	int size = 0;
256 
257 	while (*name) {
258 		if (!isascii(*name) || !(isalnum(*name) || ispunct(*name)))
259 			return (0);
260 		name++, size++;
261 	}
262 	return (size > 0);
263 }
264 
265 int	alarmcount;
266 
267 void
268 onalrm(signo)
269 	int signo;
270 {
271 	struct neighbor *np;
272 	struct whoent *we = mywd.wd_we, *wlast;
273 	int i;
274 	struct stat stb;
275 	double avenrun[3];
276 	time_t now;
277 	int cc;
278 	static struct utmpentry *ohead = NULL;
279 	struct utmpentry *ep;
280 	int utmpent = 0;
281 
282 	now = time(NULL);
283 	if (alarmcount % 10 == 0)
284 		getboottime(0);
285 	alarmcount++;
286 
287 	(void)getutentries(NULL, &ep);
288 	if (ep != ohead) {
289 		freeutentries(ep);
290 		wlast = &mywd.wd_we[1024 / sizeof(struct whoent) - 1];
291 		for (; ep; ep = ep->next) {
292 			(void)strncpy(we->we_utmp.out_line, ep->line,
293 			    sizeof(we->we_utmp.out_line) - 1);
294 			(void)strncpy(we->we_utmp.out_name, ep->name,
295 			    sizeof(we->we_utmp.out_name) - 1);
296 			we->we_utmp.out_time = htonl(ep->tv.tv_sec);
297 			if (we >= wlast)
298 				break;
299 			we++;
300 		}
301 		utmpent = we - mywd.wd_we;
302 	}
303 
304 	/*
305 	 * The test on utmpent looks silly---after all, if no one is
306 	 * logged on, why worry about efficiency?---but is useful on
307 	 * (e.g.) compute servers.
308 	 */
309 	if (utmpent && chdir(_PATH_DEV)) {
310 		syslog(LOG_ERR, "chdir(%s): %m", _PATH_DEV);
311 		exit(1);
312 	}
313 	we = mywd.wd_we;
314 	for (i = 0; i < utmpent; i++) {
315 		if (stat(we->we_utmp.out_line, &stb) >= 0)
316 			we->we_idle = htonl(now - stb.st_atime);
317 		we++;
318 	}
319 	(void)getloadavg(avenrun, sizeof(avenrun)/sizeof(avenrun[0]));
320 	for (i = 0; i < 3; i++)
321 		mywd.wd_loadav[i] = htonl((u_long)(avenrun[i] * 100));
322 	cc = (char *)we - (char *)&mywd;
323 	mywd.wd_sendtime = htonl(time(0));
324 	mywd.wd_vers = WHODVERSION;
325 	mywd.wd_type = WHODTYPE_STATUS;
326 	for (np = neighbors; np != NULL; np = np->n_next)
327 		(void)sendto(s, (char *)&mywd, cc, 0,
328 				np->n_addr, np->n_addrlen);
329 	if (utmpent && chdir(_PATH_RWHODIR)) {
330 		syslog(LOG_ERR, "chdir(%s): %m", _PATH_RWHODIR);
331 		exit(1);
332 	}
333 	(void)alarm(AL_INTERVAL);
334 }
335 
336 void
337 getboottime(signo)
338 	int signo;
339 {
340 	int mib[2];
341 	size_t size;
342 	struct timeval tm;
343 
344 	mib[0] = CTL_KERN;
345 	mib[1] = KERN_BOOTTIME;
346 	size = sizeof(tm);
347 	if (sysctl(mib, 2, &tm, &size, NULL, 0) == -1) {
348 		syslog(LOG_ERR, "cannot get boottime: %m");
349 		exit(1);
350 	}
351 	mywd.wd_boottime = htonl(tm.tv_sec);
352 }
353 
354 void
355 quit(msg)
356 	char *msg;
357 {
358 	syslog(LOG_ERR, "%s", msg);
359 	exit(1);
360 }
361 
362 #define ROUNDUP(a) \
363 	((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
364 #define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len))
365 
366 void
367 rt_xaddrs(cp, cplim, rtinfo)
368 	caddr_t cp, cplim;
369 	struct rt_addrinfo *rtinfo;
370 {
371 	struct sockaddr *sa;
372 	int i;
373 
374 	memset(rtinfo->rti_info, 0, sizeof(rtinfo->rti_info));
375 	for (i = 0; (i < RTAX_MAX) && (cp < cplim); i++) {
376 		if ((rtinfo->rti_addrs & (1 << i)) == 0)
377 			continue;
378 		rtinfo->rti_info[i] = sa = (struct sockaddr *)cp;
379 		ADVANCE(cp, sa);
380 	}
381 }
382 
383 /*
384  * Figure out device configuration and select
385  * networks which deserve status information.
386  */
387 int
388 configure(s)
389 	int s;
390 {
391 	struct neighbor *np;
392 	struct if_msghdr *ifm;
393 	struct ifa_msghdr *ifam;
394 	struct sockaddr_dl *sdl;
395 	size_t needed;
396 	int mib[6], flags = 0, len;
397 	char *buf, *lim, *next;
398 	struct rt_addrinfo info;
399 
400 	mib[0] = CTL_NET;
401 	mib[1] = PF_ROUTE;
402 	mib[2] = 0;
403 	mib[3] = AF_INET;
404 	mib[4] = NET_RT_IFLIST;
405 	mib[5] = 0;
406 	if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
407 		quit("route-sysctl-estimate");
408 	if ((buf = malloc(needed)) == NULL)
409 		quit("malloc");
410 	if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0)
411 		quit("actual retrieval of interface table");
412 	lim = buf + needed;
413 
414 	sdl = NULL;		/* XXX just to keep gcc -Wall happy */
415 	for (next = buf; next < lim; next += ifm->ifm_msglen) {
416 		ifm = (struct if_msghdr *)next;
417 		if (ifm->ifm_type == RTM_IFINFO) {
418 			sdl = (struct sockaddr_dl *)(ifm + 1);
419 			flags = ifm->ifm_flags;
420 			continue;
421 		}
422 		if ((flags & IFF_UP) == 0 ||
423 		    (flags & (IFF_BROADCAST|IFF_POINTOPOINT)) == 0)
424 			continue;
425 		if (ifm->ifm_type != RTM_NEWADDR)
426 			quit("out of sync parsing NET_RT_IFLIST");
427 		ifam = (struct ifa_msghdr *)ifm;
428 		info.rti_addrs = ifam->ifam_addrs;
429 		rt_xaddrs((char *)(ifam + 1), ifam->ifam_msglen + (char *)ifam,
430 			&info);
431 		/* gag, wish we could get rid of Internet dependencies */
432 #define dstaddr	info.rti_info[RTAX_BRD]
433 #define IPADDR_SA(x) ((struct sockaddr_in *)(x))->sin_addr.s_addr
434 #define PORT_SA(x) ((struct sockaddr_in *)(x))->sin_port
435 		if (dstaddr == 0 || dstaddr->sa_family != AF_INET)
436 			continue;
437 		PORT_SA(dstaddr) = sp->s_port;
438 		for (np = neighbors; np != NULL; np = np->n_next)
439 			if (memcmp(sdl->sdl_data, np->n_name,
440 				   sdl->sdl_nlen) == 0 &&
441 			    IPADDR_SA(np->n_addr) == IPADDR_SA(dstaddr))
442 				break;
443 		if (np != NULL)
444 			continue;
445 		len = sizeof(*np) + dstaddr->sa_len + sdl->sdl_nlen + 1;
446 		np = (struct neighbor *)malloc(len);
447 		if (np == NULL)
448 			quit("malloc of neighbor structure");
449 		memset(np, 0, len);
450 		np->n_flags = flags;
451 		np->n_addr = (struct sockaddr *)(np + 1);
452 		np->n_addrlen = dstaddr->sa_len;
453 		np->n_name = np->n_addrlen + (char *)np->n_addr;
454 		np->n_next = neighbors;
455 		neighbors = np;
456 		memcpy((char *)np->n_addr, (char *)dstaddr, np->n_addrlen);
457 		memcpy(np->n_name, sdl->sdl_data, sdl->sdl_nlen);
458 	}
459 	free(buf);
460 	return (1);
461 }
462 
463 #ifdef DEBUG
464 void
465 Sendto(s, buf, cc, flags, to, tolen)
466 	int s;
467 	char *buf;
468 	int cc, flags;
469 	char *to;
470 	int tolen;
471 {
472 	struct whod *w = (struct whod *)buf;
473 	struct whoent *we;
474 	struct sockaddr_in *sin = (struct sockaddr_in *)to;
475 
476 	printf("sendto %x.%d\n", ntohl(sin->sin_addr), ntohs(sin->sin_port));
477 	printf("hostname %s %s\n", w->wd_hostname,
478 	   interval(ntohl(w->wd_sendtime) - ntohl(w->wd_boottime), "  up"));
479 	printf("load %4.2f, %4.2f, %4.2f\n",
480 	    ntohl(w->wd_loadav[0]) / 100.0, ntohl(w->wd_loadav[1]) / 100.0,
481 	    ntohl(w->wd_loadav[2]) / 100.0);
482 	cc -= WHDRSIZE;
483 	for (we = w->wd_we, cc /= sizeof(struct whoent); cc > 0; cc--, we++) {
484 		time_t t = ntohl(we->we_utmp.out_time);
485 		printf("%-8.8s %s:%s %.12s",
486 			we->we_utmp.out_name,
487 			w->wd_hostname, we->we_utmp.out_line,
488 			ctime(&t)+4);
489 		we->we_idle = ntohl(we->we_idle) / 60;
490 		if (we->we_idle) {
491 			if (we->we_idle >= 100*60)
492 				we->we_idle = 100*60 - 1;
493 			if (we->we_idle >= 60)
494 				printf(" %2d", we->we_idle / 60);
495 			else
496 				printf("   ");
497 			printf(":%02d", we->we_idle % 60);
498 		}
499 		printf("\n");
500 	}
501 }
502 
503 char *
504 interval(time, updown)
505 	int time;
506 	char *updown;
507 {
508 	static char resbuf[32];
509 	int days, hours, minutes;
510 
511 	if (time < 0 || time > 3*30*24*60*60) {
512 		(void)sprintf(resbuf, "   %s ??:??", updown);
513 		return (resbuf);
514 	}
515 	minutes = (time + 59) / 60;		/* round to minutes */
516 	hours = minutes / 60; minutes %= 60;
517 	days = hours / 24; hours %= 24;
518 	if (days)
519 		(void)sprintf(resbuf, "%s %2d+%02d:%02d",
520 		    updown, days, hours, minutes);
521 	else
522 		(void)sprintf(resbuf, "%s    %2d:%02d",
523 		    updown, hours, minutes);
524 	return (resbuf);
525 }
526 #endif
527