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