xref: /openbsd/usr.sbin/rpc.statd/statd.c (revision 3bef86f7)
1 /*	$OpenBSD: statd.c,v 1.6 2023/01/04 14:42:46 jsg Exp $	*/
2 
3 /*
4  * Copyright (c) 1995
5  *	A.R. Gordon (andrew.gordon@net-tel.co.uk).  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed for the FreeBSD project
18  * 4. Neither the name of the author nor the names of any co-contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY ANDREW GORDON AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  */
35 
36 /* main() function for status monitor daemon.  Some of the code in this	*/
37 /* file was generated by running rpcgen /usr/include/rpcsvc/sm_inter.x	*/
38 /* The actual program logic is in the file procs.c			*/
39 
40 #include <sys/wait.h>
41 
42 #include <err.h>
43 #include <ctype.h>
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <signal.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <syslog.h>
51 #include <unistd.h>
52 #include <db.h>
53 
54 #include <rpc/rpc.h>
55 
56 #include "statd.h"
57 
58 struct sigaction sa;
59 int		debug = 0;		/* Controls syslog() for debug msgs */
60 int		_rpcsvcdirty = 0;	/* XXX ??? */
61 static DB	*db;			/* Database file */
62 
63 Header		 status_info;
64 
65 static char undefdata[] = "\0\1\2\3\4\5\6\7";
66 static DBT undefkey = {
67 	undefdata,
68 	sizeof(undefdata)
69 };
70 extern char *__progname;
71 
72 /* statd.c */
73 static int walk_one(int (*fun )(DBT *, HostInfo *, void *), DBT *, DBT *, void *);
74 static int walk_db(int (*fun )(DBT *, HostInfo *, void *), void *);
75 static int reset_host(DBT *, HostInfo *, void *);
76 static int check_work(DBT *, HostInfo *, void *);
77 static int unmon_host(DBT *, HostInfo *, void *);
78 static int notify_one(DBT *, HostInfo *, void *);
79 static void init_file(char *);
80 static int notify_one_host(char *);
81 static __dead void die(int);
82 
83 int main(int, char **);
84 
85 int
86 main(int argc, char **argv)
87 {
88 	SVCXPRT *transp;
89 	int ch;
90 	struct sigaction nsa;
91 
92 	while ((ch = getopt(argc, argv, "d")) != (-1)) {
93 		switch (ch) {
94 		case 'd':
95 			debug = 1;
96 			break;
97 		default:
98 			fprintf(stderr, "usage: %s [-d]\n", __progname);
99 			exit(1);
100 			/* NOTREACHED */
101 		}
102 	}
103 	pmap_unset(SM_PROG, SM_VERS);
104 
105 	transp = svcudp_create(RPC_ANYSOCK);
106 	if (transp == NULL) {
107 		errx(1, "cannot create udp service.");
108 		/* NOTREACHED */
109 	}
110 	if (!svc_register(transp, SM_PROG, SM_VERS, sm_prog_1, IPPROTO_UDP)) {
111 		errx(1, "unable to register (SM_PROG, SM_VERS, udp).");
112 		/* NOTREACHED */
113 	}
114 	transp = svctcp_create(RPC_ANYSOCK, 0, 0);
115 	if (transp == NULL) {
116 		errx(1, "cannot create tcp service.");
117 		/* NOTREACHED */
118 	}
119 	if (!svc_register(transp, SM_PROG, SM_VERS, sm_prog_1, IPPROTO_TCP)) {
120 		errx(1, "unable to register (SM_PROG, SM_VERS, tcp).");
121 		/* NOTREACHED */
122 	}
123 
124 	init_file("/var/db/statd.status");
125 
126 	/*
127 	 * Note that it is NOT sensible to run this program from inetd - the
128 	 * protocol assumes that it will run immediately at boot time.
129 	 */
130 	daemon(0, 0);
131 
132 	sigemptyset(&nsa.sa_mask);
133 	nsa.sa_flags = SA_NOCLDSTOP|SA_NOCLDWAIT;
134 	nsa.sa_handler = SIG_IGN;
135 	sigaction(SIGCHLD, &nsa, NULL);
136 
137 	openlog("rpc.statd", 0, LOG_DAEMON);
138 	if (debug)
139 		syslog(LOG_INFO, "Starting - debug enabled");
140 	else
141 		syslog(LOG_INFO, "Starting");
142 
143 	sa.sa_handler = die;
144 	sa.sa_flags = 0;
145 	sigemptyset(&sa.sa_mask);
146 	sigaction(SIGTERM, &sa, NULL);
147 	sigaction(SIGQUIT, &sa, NULL);
148 	sigaction(SIGHUP, &sa, NULL);
149 	sigaction(SIGINT, &sa, NULL);
150 
151 	sa.sa_handler = SIG_IGN;
152 	sa.sa_flags = SA_RESTART;
153 	sigemptyset(&sa.sa_mask);
154 	sigaddset(&sa.sa_mask, SIGALRM);
155 
156 	/* Initialisation now complete - start operating */
157 
158 	/* Notify hosts that need it */
159 	notify_handler(0);
160 
161 	while (1)
162 		svc_run();		/* Should never return */
163 	die(0);
164 }
165 
166 /* notify_handler ---------------------------------------------------------- */
167 /*
168  * Purpose:	Catch SIGALRM and collect process status
169  * Returns:	Nothing.
170  * Notes:	No special action required, other than to collect the
171  *		process status and hence allow the child to die:
172  *		we only use child processes for asynchronous transmission
173  *		of SM_NOTIFY to other systems, so it is normal for the
174  *		children to exit when they have done their work.
175  */
176 void
177 notify_handler(int sig)
178 {
179 	time_t now;
180 
181 	NO_ALARM;
182 	sa.sa_handler = SIG_IGN;
183 	sigaction(SIGALRM, &sa, NULL);
184 
185 	now = time(NULL);
186 
187 	walk_db(notify_one, &now);
188 
189 	if (walk_db(check_work, &now) == 0) {
190 		/*
191 		 * No more work to be done.
192 		 */
193 		CLR_ALARM;
194 		return;
195 	}
196 	sync_file();
197 	ALARM;
198 	alarm(5);
199 }
200 
201 /* sync_file --------------------------------------------------------------- */
202 /*
203  * Purpose:	Packaged call of msync() to flush changes to mmap()ed file
204  * Returns:	Nothing.  Errors to syslog.
205  */
206 void
207 sync_file()
208 {
209 	DBT data;
210 
211 	data.data = &status_info;
212 	data.size = sizeof(status_info);
213 	switch ((*db->put)(db, &undefkey, &data, 0)) {
214 	case 0:
215 		return;
216 	case -1:
217 		goto bad;
218 	default:
219 		abort();
220 	}
221 	if ((*db->sync)(db, 0) == -1) {
222 bad:
223 		syslog(LOG_ERR, "database corrupted %m");
224 		die(1);
225 	}
226 }
227 
228 /* change_host -------------------------------------------------------------- */
229 /*
230  * Purpose:	Update/Create an entry for host
231  * Returns:	Nothing
232  * Notes:
233  *
234  */
235 void
236 change_host(char *hostnamep, HostInfo *hp)
237 {
238 	DBT key, data;
239 	char *ptr;
240 	char hostname[HOST_NAME_MAX+1 + 1];
241 	HostInfo h;
242 
243 	strlcpy(hostname, hostnamep, sizeof(hostname));
244 	h = *hp;
245 
246 	for (ptr = hostname; *ptr; ptr++)
247 		if (isupper((unsigned char) *ptr))
248 			*ptr = tolower((unsigned char) *ptr);
249 
250 	key.data = hostname;
251 	key.size = ptr - hostname + 1;
252 	data.data = &h;
253 	data.size = sizeof(h);
254 
255 	switch ((*db->put)(db, &key, &data, 0)) {
256 	case -1:
257 		syslog(LOG_ERR, "database corrupted %m");
258 		die(1);
259 	case 0:
260 		return;
261 	default:
262 		abort();
263 	}
264 }
265 
266 
267 /* find_host -------------------------------------------------------------- */
268 /*
269  * Purpose:	Find the entry in the status file for a given host
270  * Returns:	Copy of entry in hd, or NULL
271  * Notes:
272  *
273  */
274 HostInfo *
275 find_host(char *hostname, HostInfo *hp)
276 {
277 	DBT key, data;
278 	char *ptr;
279 
280 	for (ptr = hostname; *ptr; ptr++)
281 		if (isupper((unsigned char) *ptr))
282 			*ptr = tolower((unsigned char) *ptr);
283 
284 	key.data = hostname;
285 	key.size = ptr - hostname + 1;
286 	switch ((*db->get)(db, &key, &data, 0)) {
287 	case 0:
288 		if (data.size != sizeof(*hp))
289 			goto bad;
290 		return memcpy(hp, data.data, sizeof(*hp));
291 	case 1:
292 		return NULL;
293 	case -1:
294 		goto bad;
295 	default:
296 		abort();
297 	}
298 
299 bad:
300 	syslog(LOG_ERR, "Database corrupted %m");
301 	return NULL;
302 }
303 
304 /* walk_one ------------------------------------------------------------- */
305 /*
306  * Purpose:	Call the given function if the element is valid
307  * Returns:	Nothing - exits on error
308  * Notes:
309  */
310 static int
311 walk_one(int (*fun)(DBT *, HostInfo *, void *), DBT *key, DBT *data, void *ptr)
312 {
313 	HostInfo h;
314 	if (key->size == undefkey.size &&
315 	    memcmp(key->data, undefkey.data, key->size) == 0)
316 		return 0;
317 	if (data->size != sizeof(HostInfo)) {
318 		syslog(LOG_ERR, "Bad data in database");
319 		die(1);
320 	}
321 	memcpy(&h, data->data, sizeof(h));
322 	return (*fun)(key, &h, ptr);
323 }
324 
325 /* walk_db -------------------------------------------------------------- */
326 /*
327  * Purpose:	Iterate over all elements calling the given function
328  * Returns:	-1 if function failed, 0 on success
329  * Notes:
330  */
331 static int
332 walk_db(int (*fun)(DBT *, HostInfo *, void *), void *ptr)
333 {
334 	DBT key, data;
335 
336 	switch ((*db->seq)(db, &key, &data, R_FIRST)) {
337 	case -1:
338 		goto bad;
339 	case 1:
340 		/* We should have at least the magic entry at this point */
341 		abort();
342 	case 0:
343 		if (walk_one(fun, &key, &data, ptr) == -1)
344 			return -1;
345 		break;
346 	default:
347 		abort();
348 	}
349 
350 	for (;;)
351 		switch ((*db->seq)(db, &key, &data, R_NEXT)) {
352 		case -1:
353 			goto bad;
354 		case 0:
355 			if (walk_one(fun, &key, &data, ptr) == -1)
356 				return -1;
357 			break;
358 		case 1:
359 			return 0;
360 		default:
361 			abort();
362 		}
363 bad:
364 	syslog(LOG_ERR, "Corrupted database %m");
365 	die(1);
366 }
367 
368 /* reset_host ------------------------------------------------------------ */
369 /*
370  * Purpose:	Clean up existing hosts in file.
371  * Returns:	Always success 0.
372  * Notes:	Clean-up of existing file - monitored hosts will have a
373  *		pointer to a list of clients, which refers to memory in
374  *		the previous incarnation of the program and so are
375  *		meaningless now.  These pointers are zeroed and the fact
376  *		that the host was previously monitored is recorded by
377  *		setting the notifyReqd flag, which will in due course
378  *		cause a SM_NOTIFY to be sent.
379  *
380  *		Note that if we crash twice in quick succession, some hosts
381  *		may already have notifyReqd set, where we didn't manage to
382  *		notify them before the second crash occurred.
383  */
384 static int
385 reset_host(DBT *key, HostInfo *hi, void *ptr)
386 {
387 	if (hi->monList) {
388 		hi->notifyReqd = *(time_t *) ptr;
389 		hi->attempts = 0;
390 		hi->monList = NULL;
391 		change_host((char *)key->data, hi);
392 	}
393 	return 0;
394 }
395 
396 /* check_work ------------------------------------------------------------ */
397 /*
398  * Purpose:	Check if there is work to be done.
399  * Returns:	0 if there is no work to be done -1 if there is.
400  * Notes:
401  */
402 static int
403 check_work(DBT *key, HostInfo *hi, void *ptr)
404 {
405 	return hi->notifyReqd ? -1 : 0;
406 }
407 
408 /* unmon_host ------------------------------------------------------------ */
409 /*
410  * Purpose:	Unmonitor a host
411  * Returns:	0
412  * Notes:
413  */
414 static int
415 unmon_host(DBT *key, HostInfo *hi, void *ptr)
416 {
417 	char *name = key->data;
418 
419 	if (do_unmon(name, hi, ptr))
420 		change_host(name, hi);
421 	return 0;
422 }
423 
424 /* notify_one ------------------------------------------------------------ */
425 /*
426  * Purpose:	Notify one host.
427  * Returns:	0 if success -1 on failure
428  * Notes:
429  */
430 static int
431 notify_one(DBT *key, HostInfo *hi, void *ptr)
432 {
433 	time_t now = *(time_t *) ptr;
434 	char *name = key->data;
435 	int error;
436 
437 	if (hi->notifyReqd == 0 || hi->notifyReqd > now)
438 		return 0;
439 
440 	/*
441 	 * If one of the initial attempts fails, we wait
442 	 * for a while and have another go.  This is necessary
443 	 * because when we have crashed, (eg. a power outage)
444 	 * it is quite possible that we won't be able to
445 	 * contact all monitored hosts immediately on restart,
446 	 * either because they crashed too and take longer
447 	 * to come up (in which case the notification isn't
448 	 * really required), or more importantly if some
449 	 * router etc. needed to reach the monitored host
450 	 * has not come back up yet.  In this case, we will
451 	 * be a bit late in re-establishing locks (after the
452 	 * grace period) but that is the best we can do.  We
453 	 * try 10 times at 5 sec intervals, 10 more times at
454 	 * 1 minute intervals, then 24 more times at hourly
455 	 * intervals, finally giving up altogether if the
456 	 * host hasn't come back to life after 24 hours.
457 	 */
458 	if (notify_one_host(name) || hi->attempts++ >= 44) {
459 		error = 0;
460 		hi->notifyReqd = 0;
461 		hi->attempts = 0;
462 	} else {
463 		error = -1;
464 		if (hi->attempts < 10)
465 			hi->notifyReqd += 5;
466 		else if (hi->attempts < 20)
467 			hi->notifyReqd += 60;
468 		else
469 			hi->notifyReqd += 60 * 60;
470 	}
471 	change_host(name, hi);
472 	return error;
473 }
474 
475 /* init_file -------------------------------------------------------------- */
476 /*
477  * Purpose:	Open file, create if necessary, initialise it.
478  * Returns:	Nothing - exits on error
479  * Notes:	Called before process becomes daemon, hence logs to
480  *		stderr rather than syslog.
481  *		Opens the file, then mmap()s it for ease of access.
482  *		Also performs initial clean-up of the file, zeroing
483  *		monitor list pointers, setting the notifyReqd flag in
484  *		all hosts that had a monitor list, and incrementing
485  *		the state number to the next even value.
486  */
487 static void
488 init_file(char *filename)
489 {
490 	DBT data;
491 
492 	db = dbopen(filename, O_RDWR|O_CREAT|O_NDELAY|O_EXLOCK, 0644, DB_HASH,
493 	    NULL);
494 	if (db == NULL)
495 		err(1, "Cannot open `%s'", filename);
496 
497 	switch ((*db->get)(db, &undefkey, &data, 0)) {
498 	case 1:
499 		/* New database */
500 		memset(&status_info, 0, sizeof(status_info));
501 		sync_file();
502 		return;
503 	case -1:
504 		err(1, "error accessing database (%m)");
505 	case 0:
506 		/* Existing database */
507 		if (data.size != sizeof(status_info))
508 			errx(1, "database corrupted %lu != %lu",
509 			    (u_long)data.size, (u_long)sizeof(status_info));
510 		memcpy(&status_info, data.data, data.size);
511 		break;
512 	default:
513 		abort();
514 	}
515 
516 	reset_database();
517 	return;
518 }
519 
520 /* reset_database --------------------------------------------------------- */
521 /*
522  * Purpose:	Clears the statd database
523  * Returns:	Nothing
524  * Notes:	If this is not called on reset, it will leak memory.
525  */
526 void
527 reset_database(void)
528 {
529 	time_t now = time(NULL);
530 	walk_db(reset_host, &now);
531 
532 	/* Select the next higher even number for the state counter */
533 	status_info.ourState =
534 	    (status_info.ourState + 2) & 0xfffffffe;
535 	status_info.ourState++;	/* XXX - ??? */
536 	sync_file();
537 }
538 
539 /* unmon_hosts --------------------------------------------------------- */
540 /*
541  * Purpose:	Unmonitor all the hosts
542  * Returns:	Nothing
543  * Notes:
544  */
545 void
546 unmon_hosts(void)
547 {
548 	time_t now = time(NULL);
549 	walk_db(unmon_host, &now);
550 	sync_file();
551 }
552 
553 static int
554 notify_one_host(char *hostname)
555 {
556 	struct timeval timeout = {20, 0};	/* 20 secs timeout */
557 	CLIENT *cli;
558 	char dummy;
559 	stat_chge arg;
560 	char our_hostname[HOST_NAME_MAX+1 + 1];
561 
562 	gethostname(our_hostname, sizeof(our_hostname));
563 	our_hostname[sizeof(our_hostname) - 1] = '\0';
564 	arg.mon_name = our_hostname;
565 	arg.state = status_info.ourState;
566 
567 	if (debug)
568 		syslog(LOG_DEBUG, "Sending SM_NOTIFY to host %s from %s",
569 		    hostname, our_hostname);
570 
571 	cli = clnt_create(hostname, SM_PROG, SM_VERS, "udp");
572 	if (!cli) {
573 		syslog(LOG_ERR, "Failed to contact host %s%s", hostname,
574 		    clnt_spcreateerror(""));
575 		return (FALSE);
576 	}
577 	if (clnt_call(cli, SM_NOTIFY, xdr_stat_chge, &arg, xdr_void,
578 	    &dummy, timeout) != RPC_SUCCESS) {
579 		syslog(LOG_ERR, "Failed to contact rpc.statd at host %s",
580 		    hostname);
581 		clnt_destroy(cli);
582 		return (FALSE);
583 	}
584 	clnt_destroy(cli);
585 	return (TRUE);
586 }
587 
588 static __dead void
589 die(int n)
590 {
591 	(*db->close)(db);
592 	exit(n);
593 }
594