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