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