Home | History | Annotate | Line # | Download | only in rpc.statd
statd.c revision 1.16
      1 /*	$NetBSD: statd.c,v 1.16 2000/06/09 09:57:29 bouyer 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.16 2000/06/09 09:57:29 bouyer 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 *, HostInfo *, void *)), DBT *, DBT *, void *));
     83 static int walk_db __P((int (*fun )__P ((DBT *, HostInfo *, void *)), void *));
     84 static int reset_host __P((DBT *, HostInfo *, void *));
     85 static int check_work __P((DBT *, HostInfo *, void *));
     86 static int unmon_host __P((DBT *, HostInfo *, void *));
     87 static int notify_one __P((DBT *, HostInfo *, 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 *, HostInfo *, void *));
    319 	DBT *key, *data;
    320 	void *ptr;
    321 {
    322 	HostInfo h;
    323 	if (key->size == undefkey.size &&
    324 	    memcmp(key->data, undefkey.data, key->size) == 0)
    325 		return 0;
    326 	if (data->size != sizeof(HostInfo)) {
    327 		syslog(LOG_ERR, "Bad data in database");
    328 		die(1);
    329 	}
    330 	memcpy(&h, data->data, sizeof(h));
    331 	return (*fun)(key, &h, ptr);
    332 }
    333 
    334 /* walk_db -------------------------------------------------------------- */
    335 /*
    336  * Purpose:	Iterate over all elements calling the given function
    337  * Returns:	-1 if function failed, 0 on success
    338  * Notes:
    339  */
    340 static int
    341 walk_db(fun, ptr)
    342 	int (*fun) __P((DBT *, HostInfo *, void *));
    343 	void *ptr;
    344 {
    345 	DBT key, data;
    346 
    347 	switch ((*db->seq)(db, &key, &data, R_FIRST)) {
    348 	case -1:
    349 		goto bad;
    350 	case 1:
    351 		/* We should have at least the magic entry at this point */
    352 		abort();
    353 	case 0:
    354 		if (walk_one(fun, &key, &data, ptr) == -1)
    355 			return -1;
    356 		break;
    357 	default:
    358 		abort();
    359 	}
    360 
    361 
    362 	for (;;)
    363 		switch ((*db->seq)(db, &key, &data, R_NEXT)) {
    364 		case -1:
    365 			goto bad;
    366 		case 0:
    367 			if (walk_one(fun, &key, &data, ptr) == -1)
    368 				return -1;
    369 			break;
    370 		case 1:
    371 			return 0;
    372 		default:
    373 			abort();
    374 		}
    375 bad:
    376 	syslog(LOG_ERR, "Corrupted database %m");
    377 	die(1);
    378 }
    379 
    380 /* reset_host ------------------------------------------------------------ */
    381 /*
    382  * Purpose:	Clean up existing hosts in file.
    383  * Returns:	Always success 0.
    384  * Notes:	Clean-up of existing file - monitored hosts will have a
    385  *		pointer to a list of clients, which refers to memory in
    386  *		the previous incarnation of the program and so are
    387  *		meaningless now.  These pointers are zeroed and the fact
    388  *		that the host was previously monitored is recorded by
    389  *		setting the notifyReqd flag, which will in due course
    390  *		cause a SM_NOTIFY to be sent.
    391  *
    392  *		Note that if we crash twice in quick succession, some hosts
    393  *		may already have notifyReqd set, where we didn't manage to
    394  *		notify them before the second crash occurred.
    395  */
    396 static int
    397 reset_host(key, hi, ptr)
    398 	DBT *key;
    399 	HostInfo *hi;
    400 	void *ptr;
    401 {
    402 
    403 	if (hi->monList) {
    404 		hi->notifyReqd = *(time_t *) ptr;
    405 		hi->attempts = 0;
    406 		hi->monList = NULL;
    407 	}
    408 	return 0;
    409 }
    410 
    411 /* check_work ------------------------------------------------------------ */
    412 /*
    413  * Purpose:	Check if there is work to be done.
    414  * Returns:	0 if there is no work to be done -1 if there is.
    415  * Notes:
    416  */
    417 static int
    418 check_work(key, hi, ptr)
    419 	DBT *key;
    420 	HostInfo *hi;
    421 	void *ptr;
    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, hi, ptr)
    434 	DBT *key;
    435 	HostInfo *hi;
    436 	void *ptr;
    437 {
    438 	char *name = key->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, hi, ptr)
    453 	DBT *key;
    454 	HostInfo *hi;
    455 	void *ptr;
    456 {
    457 	time_t now = *(time_t *) ptr;
    458 	char *name = key->data;
    459 	DBT data;
    460 
    461 	if (hi->notifyReqd == 0 || hi->notifyReqd > now)
    462 		return 0;
    463 
    464 	if (notify_one_host(name)) {
    465 give_up:
    466 		hi->notifyReqd = 0;
    467 		hi->attempts = 0;
    468 		data.data = hi;
    469 		data.size = sizeof(*hi);
    470 		switch ((*db->put)(db, key, &data, 0)) {
    471 		case -1:
    472 			syslog(LOG_ERR, "Error storing %s (%m)", name);
    473 		case 0:
    474 			return 0;
    475 
    476 		default:
    477 			abort();
    478 		}
    479 	}
    480 	else {
    481 		/*
    482 		 * If one of the initial attempts fails, we wait
    483 		 * for a while and have another go.  This is necessary
    484 		 * because when we have crashed, (eg. a power outage)
    485 		 * it is quite possible that we won't be able to
    486 		 * contact all monitored hosts immediately on restart,
    487 		 * either because they crashed too and take longer
    488 		 * to come up (in which case the notification isn't
    489 		 * really required), or more importantly if some
    490 		 * router etc. needed to reach the monitored host
    491 		 * has not come back up yet.  In this case, we will
    492 		 * be a bit late in re-establishing locks (after the
    493 		 * grace period) but that is the best we can do.  We
    494 		 * try 10 times at 5 sec intervals, 10 more times at
    495 		 * 1 minute intervals, then 24 more times at hourly
    496 		 * intervals, finally giving up altogether if the
    497 		 * host hasn't come back to life after 24 hours.
    498 		 */
    499 		if (hi->attempts++ >= 44)
    500 			goto give_up;
    501 		else if (hi->attempts < 10)
    502 			hi->notifyReqd += 5;
    503 		else if (hi->attempts < 20)
    504 			hi->notifyReqd += 60;
    505 		else
    506 			hi->notifyReqd += 60 * 60;
    507 		return -1;
    508 	}
    509 }
    510 
    511 /* init_file -------------------------------------------------------------- */
    512 /*
    513  * Purpose:	Open file, create if necessary, initialise it.
    514  * Returns:	Nothing - exits on error
    515  * Notes:	Called before process becomes daemon, hence logs to
    516  *		stderr rather than syslog.
    517  *		Opens the file, then mmap()s it for ease of access.
    518  *		Also performs initial clean-up of the file, zeroing
    519  *		monitor list pointers, setting the notifyReqd flag in
    520  *		all hosts that had a monitor list, and incrementing
    521  *		the state number to the next even value.
    522  */
    523 static void
    524 init_file(filename)
    525 	char *filename;
    526 {
    527 	DBT data;
    528 
    529 	db = dbopen(filename, O_RDWR|O_CREAT|O_NDELAY|O_EXLOCK, 0644, DB_HASH,
    530 	    NULL);
    531 	if (db == NULL)
    532 		err(1, "Cannot open `%s'", filename);
    533 
    534 	switch ((*db->get)(db, &undefkey, &data, 0)) {
    535 	case 1:
    536 		/* New database */
    537 		(void)memset(&status_info, 0, sizeof(status_info));
    538 		sync_file();
    539 		return;
    540 
    541 	case -1:
    542 		err(1, "error accessing database (%m)");
    543 	case 0:
    544 		/* Existing database */
    545 		if (data.size != sizeof(status_info))
    546 			errx(1, "database corrupted %lu != %lu",
    547 			    (u_long)data.size, (u_long)sizeof(status_info));
    548 		break;
    549 	default:
    550 		abort();
    551 	}
    552 
    553 	reset_database();
    554 	return;
    555 }
    556 
    557 /* reset_database --------------------------------------------------------- */
    558 /*
    559  * Purpose:	Clears the statd database
    560  * Returns:	Nothing
    561  * Notes:	If this is not called on reset, it will leak memory.
    562  */
    563 void
    564 reset_database()
    565 {
    566 	time_t now = time(NULL);
    567 	walk_db(reset_host, &now);
    568 
    569 	/* Select the next higher even number for the state counter */
    570 	status_info.ourState =
    571 	    (status_info.ourState + 2) & 0xfffffffe;
    572 	status_info.ourState++;	/* XXX - ??? */
    573 	sync_file();
    574 }
    575 
    576 /* unmon_hosts --------------------------------------------------------- */
    577 /*
    578  * Purpose:	Unmonitor all the hosts
    579  * Returns:	Nothing
    580  * Notes:
    581  */
    582 void
    583 unmon_hosts()
    584 {
    585 	time_t now = time(NULL);
    586 	walk_db(unmon_host, &now);
    587 	sync_file();
    588 }
    589 
    590 static int
    591 notify_one_host(hostname)
    592 	char *hostname;
    593 {
    594 	struct timeval timeout = {20, 0};	/* 20 secs timeout */
    595 	CLIENT *cli;
    596 	char dummy;
    597 	stat_chge arg;
    598 	char our_hostname[MAXHOSTNAMELEN + 1];
    599 
    600 	gethostname(our_hostname, sizeof(our_hostname));
    601 	our_hostname[sizeof(our_hostname) - 1] = '\0';
    602 	our_hostname[SM_MAXSTRLEN] = '\0';
    603 	arg.mon_name = our_hostname;
    604 	arg.state = status_info.ourState;
    605 
    606 	if (debug)
    607 		syslog(LOG_DEBUG, "Sending SM_NOTIFY to host %s from %s",
    608 		    hostname, our_hostname);
    609 
    610 	cli = clnt_create(hostname, SM_PROG, SM_VERS, "udp");
    611 	if (!cli) {
    612 		syslog(LOG_ERR, "Failed to contact host %s%s", hostname,
    613 		    clnt_spcreateerror(""));
    614 		return (FALSE);
    615 	}
    616 	if (clnt_call(cli, SM_NOTIFY, xdr_stat_chge, &arg, xdr_void,
    617 	    &dummy, timeout) != RPC_SUCCESS) {
    618 		syslog(LOG_ERR, "Failed to contact rpc.statd at host %s",
    619 		    hostname);
    620 		clnt_destroy(cli);
    621 		return (FALSE);
    622 	}
    623 	clnt_destroy(cli);
    624 	return (TRUE);
    625 }
    626 
    627 
    628 static void
    629 die(n)
    630 	int n;
    631 {
    632 	(*db->close)(db);
    633 	exit(n);
    634 }
    635