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