Home | History | Annotate | Line # | Download | only in rpc.statd
statd.c revision 1.32
      1 /*	$NetBSD: statd.c,v 1.32 2018/01/23 21:06:26 sevan Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1995
      5  *	A.R. Gordon (andrew.gordon (at) net-tel.co.uk).  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. All advertising materials mentioning features or use of this software
     16  *    must display the following acknowledgement:
     17  *	This product includes software developed for the FreeBSD project
     18  *	This product includes software developed by Christos Zoulas.
     19  * 4. Neither the name of the author nor the names of any co-contributors
     20  *    may be used to endorse or promote products derived from this software
     21  *    without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY ANDREW GORDON AND CONTRIBUTORS ``AS IS'' AND
     24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     33  * SUCH DAMAGE.
     34  *
     35  */
     36 
     37 #include <sys/cdefs.h>
     38 #ifndef lint
     39 __RCSID("$NetBSD: statd.c,v 1.32 2018/01/23 21:06:26 sevan Exp $");
     40 #endif
     41 
     42 /* main() function for status monitor daemon.  Some of the code in this	*/
     43 /* file was generated by running rpcgen /usr/include/rpcsvc/sm_inter.x	*/
     44 /* The actual program logic is in the file procs.c			*/
     45 
     46 #include <sys/param.h>
     47 #include <sys/wait.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 #include <netconfig.h>
     62 
     63 #include <rpc/rpc.h>
     64 
     65 #include "statd.h"
     66 
     67 struct sigaction sa;
     68 int     	debug = 0;		/* Controls syslog() for debug msgs */
     69 int     	_rpcsvcdirty = 0;	/* XXX ??? */
     70 static DB	*db;			/* Database file */
     71 
     72 Header		 status_info;
     73 
     74 static char undefdata[] = "\0\1\2\3\4\5\6\7";
     75 static DBT undefkey = {
     76 	undefdata,
     77 	sizeof(undefdata)
     78 };
     79 
     80 
     81 /* statd.c */
     82 static int walk_one(int (*fun )(DBT *, HostInfo *, void *), DBT *, DBT *, void *);
     83 static int walk_db(int (*fun )(DBT *, HostInfo *, void *), void *);
     84 static int reset_host(DBT *, HostInfo *, void *);
     85 static int check_work(DBT *, HostInfo *, void *);
     86 static int unmon_host(DBT *, HostInfo *, void *);
     87 static int notify_one(DBT *, HostInfo *, void *);
     88 static void init_file(const char *);
     89 static int notify_one_host(const char *);
     90 static void die(int) __dead;
     91 
     92 int
     93 main(int argc, char *argv[])
     94 {
     95 	int ch;
     96 	struct sigaction nsa;
     97 	int maxrec = RPC_MAXDATASIZE;
     98 
     99 	while ((ch = getopt(argc, argv, "d")) != (-1)) {
    100 		switch (ch) {
    101 		case 'd':
    102 			debug = 1;
    103 			break;
    104 		default:
    105 		case '?':
    106 			(void)fprintf(stderr, "usage: %s [-d]\n",
    107 			    getprogname());
    108 			exit(1);
    109 			/* NOTREACHED */
    110 		}
    111 	}
    112 	(void)rpcb_unset(SM_PROG, SM_VERS, NULL);
    113 
    114 	rpc_control(RPC_SVC_CONNMAXREC_SET, &maxrec);
    115 
    116 	if (!svc_create(sm_prog_1, SM_PROG, SM_VERS, "udp")) {
    117 		errx(EXIT_FAILURE, "cannot create udp service.");
    118 		/* NOTREACHED */
    119 	}
    120 	if (!svc_create(sm_prog_1, SM_PROG, SM_VERS, "tcp")) {
    121 		errx(EXIT_FAILURE, "cannot create udp service.");
    122 		/* NOTREACHED */
    123 	}
    124 
    125 	init_file("/var/db/statd.status");
    126 
    127 	/*
    128 	 * Note that it is NOT sensible to run this program from inetd - the
    129 	 * protocol assumes that it will run immediately at boot time.
    130 	 */
    131 	if (!debug)
    132 		daemon(0, 0);
    133 
    134 	sigemptyset(&nsa.sa_mask);
    135 	nsa.sa_flags = SA_NOCLDSTOP|SA_NOCLDWAIT;
    136 	nsa.sa_handler = SIG_IGN;
    137 	(void)sigaction(SIGCHLD, &nsa, NULL);
    138 
    139 	pidfile(NULL);
    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 	(void)sigaction(SIGTERM, &sa, NULL);
    150 	(void)sigaction(SIGQUIT, &sa, NULL);
    151 	(void)sigaction(SIGHUP, &sa, NULL);
    152 	(void)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 	(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(char *hostnamep, HostInfo *hp)
    240 {
    241 	DBT key, data;
    242 	char *ptr;
    243 	char hostname[MAXHOSTNAMELEN + 1];
    244 	HostInfo h;
    245 
    246 	strncpy(hostname, hostnamep, MAXHOSTNAMELEN + 1);
    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 
    354 	for (;;)
    355 		switch ((*db->seq)(db, &key, &data, R_NEXT)) {
    356 		case -1:
    357 			goto bad;
    358 		case 0:
    359 			if (walk_one(fun, &key, &data, ptr) == -1)
    360 				return -1;
    361 			break;
    362 		case 1:
    363 			return 0;
    364 		default:
    365 			abort();
    366 		}
    367 bad:
    368 	syslog(LOG_ERR, "Corrupted database %m");
    369 	die(1);
    370 }
    371 
    372 /* reset_host ------------------------------------------------------------ */
    373 /*
    374  * Purpose:	Clean up existing hosts in file.
    375  * Returns:	Always success 0.
    376  * Notes:	Clean-up of existing file - monitored hosts will have a
    377  *		pointer to a list of clients, which refers to memory in
    378  *		the previous incarnation of the program and so are
    379  *		meaningless now.  These pointers are zeroed and the fact
    380  *		that the host was previously monitored is recorded by
    381  *		setting the notifyReqd flag, which will in due course
    382  *		cause a SM_NOTIFY to be sent.
    383  *
    384  *		Note that if we crash twice in quick succession, some hosts
    385  *		may already have notifyReqd set, where we didn't manage to
    386  *		notify them before the second crash occurred.
    387  */
    388 static int
    389 reset_host(DBT *key, HostInfo *hi, void *ptr)
    390 {
    391 
    392 	if (hi->monList) {
    393 		hi->notifyReqd = *(time_t *) ptr;
    394 		hi->attempts = 0;
    395 		hi->monList = NULL;
    396 		change_host((char *)key->data, hi);
    397 	}
    398 	return 0;
    399 }
    400 
    401 /* check_work ------------------------------------------------------------ */
    402 /*
    403  * Purpose:	Check if there is work to be done.
    404  * Returns:	0 if there is no work to be done -1 if there is.
    405  * Notes:
    406  */
    407 static int
    408 check_work(DBT *key, HostInfo *hi, void *ptr)
    409 {
    410 	return hi->notifyReqd ? -1 : 0;
    411 }
    412 
    413 /* unmon_host ------------------------------------------------------------ */
    414 /*
    415  * Purpose:	Unmonitor a host
    416  * Returns:	0
    417  * Notes:
    418  */
    419 static int
    420 unmon_host(DBT *key, HostInfo *hi, void *ptr)
    421 {
    422 	char *name = key->data;
    423 
    424 	if (do_unmon(name, hi, ptr))
    425 		change_host(name, hi);
    426 	return 0;
    427 }
    428 
    429 /* notify_one ------------------------------------------------------------ */
    430 /*
    431  * Purpose:	Notify one host.
    432  * Returns:	0 if success -1 on failure
    433  * Notes:
    434  */
    435 static int
    436 notify_one(DBT *key, HostInfo *hi, void *ptr)
    437 {
    438 	time_t now = *(time_t *) ptr;
    439 	char *name = key->data;
    440 	int error;
    441 
    442 	if (hi->notifyReqd == 0 || hi->notifyReqd > now)
    443 		return 0;
    444 
    445 	/*
    446 	 * If one of the initial attempts fails, we wait
    447 	 * for a while and have another go.  This is necessary
    448 	 * because when we have crashed, (eg. a power outage)
    449 	 * it is quite possible that we won't be able to
    450 	 * contact all monitored hosts immediately on restart,
    451 	 * either because they crashed too and take longer
    452 	 * to come up (in which case the notification isn't
    453 	 * really required), or more importantly if some
    454 	 * router etc. needed to reach the monitored host
    455 	 * has not come back up yet.  In this case, we will
    456 	 * be a bit late in re-establishing locks (after the
    457 	 * grace period) but that is the best we can do.  We
    458 	 * try 10 times at 5 sec intervals, 10 more times at
    459 	 * 1 minute intervals, then 24 more times at hourly
    460 	 * intervals, finally giving up altogether if the
    461 	 * host hasn't come back to life after 24 hours.
    462 	 */
    463 	if (notify_one_host(name) || hi->attempts++ >= 44) {
    464 		error = 0;
    465 		hi->notifyReqd = 0;
    466 		hi->attempts = 0;
    467 	} else {
    468 		error = -1;
    469 		if (hi->attempts < 10)
    470 			hi->notifyReqd += 5;
    471 		else if (hi->attempts < 20)
    472 			hi->notifyReqd += 60;
    473 		else
    474 			hi->notifyReqd += 60 * 60;
    475 	}
    476 	change_host(name, hi);
    477 	return error;
    478 }
    479 
    480 /* init_file -------------------------------------------------------------- */
    481 /*
    482  * Purpose:	Open file, create if necessary, initialise it.
    483  * Returns:	Nothing - exits on error
    484  * Notes:	Called before process becomes daemon, hence logs to
    485  *		stderr rather than syslog.
    486  *		Opens the file, then mmap()s it for ease of access.
    487  *		Also performs initial clean-up of the file, zeroing
    488  *		monitor list pointers, setting the notifyReqd flag in
    489  *		all hosts that had a monitor list, and incrementing
    490  *		the state number to the next even value.
    491  */
    492 static void
    493 init_file(const char *filename)
    494 {
    495 	DBT data;
    496 
    497 	db = dbopen(filename, O_RDWR|O_CREAT|O_NDELAY|O_EXLOCK, 0644, DB_HASH,
    498 	    NULL);
    499 	if (db == NULL)
    500 		err(EXIT_FAILURE, "Cannot open `%s'", filename);
    501 
    502 	switch ((*db->get)(db, &undefkey, &data, 0)) {
    503 	case 1:
    504 		/* New database */
    505 		(void)memset(&status_info, 0, sizeof(status_info));
    506 		sync_file();
    507 		return;
    508 
    509 	case -1:
    510 		err(EXIT_FAILURE, "error accessing database (%s)", strerror(errno));
    511 	case 0:
    512 		/* Existing database */
    513 		if (data.size != sizeof(status_info))
    514 			errx(EXIT_FAILURE, "database corrupted %lu != %lu",
    515 			    (u_long)data.size, (u_long)sizeof(status_info));
    516 		memcpy(&status_info, data.data, data.size);
    517 		break;
    518 	default:
    519 		abort();
    520 	}
    521 
    522 	reset_database();
    523 	return;
    524 }
    525 
    526 /* reset_database --------------------------------------------------------- */
    527 /*
    528  * Purpose:	Clears the statd database
    529  * Returns:	Nothing
    530  * Notes:	If this is not called on reset, it will leak memory.
    531  */
    532 void
    533 reset_database()
    534 {
    535 	time_t now = time(NULL);
    536 	walk_db(reset_host, &now);
    537 
    538 	/* Select the next higher even number for the state counter */
    539 	status_info.ourState =
    540 	    (status_info.ourState + 2) & 0xfffffffe;
    541 	status_info.ourState++;	/* XXX - ??? */
    542 	sync_file();
    543 }
    544 
    545 /* unmon_hosts --------------------------------------------------------- */
    546 /*
    547  * Purpose:	Unmonitor all the hosts
    548  * Returns:	Nothing
    549  * Notes:
    550  */
    551 void
    552 unmon_hosts()
    553 {
    554 	time_t now = time(NULL);
    555 	walk_db(unmon_host, &now);
    556 	sync_file();
    557 }
    558 
    559 static int
    560 notify_one_host(const char *hostname)
    561 {
    562 	struct timeval timeout = {20, 0};	/* 20 secs timeout */
    563 	CLIENT *cli;
    564 	char dummy;
    565 	stat_chge arg;
    566 	char our_hostname[MAXHOSTNAMELEN + 1];
    567 
    568 	gethostname(our_hostname, sizeof(our_hostname));
    569 	our_hostname[sizeof(our_hostname) - 1] = '\0';
    570 	arg.mon_name = our_hostname;
    571 	arg.state = status_info.ourState;
    572 
    573 	if (debug)
    574 		syslog(LOG_DEBUG, "Sending SM_NOTIFY to host %s from %s",
    575 		    hostname, our_hostname);
    576 
    577 	cli = clnt_create(hostname, SM_PROG, SM_VERS, "udp");
    578 	if (!cli) {
    579 		syslog(LOG_ERR, "Failed to contact host %s%s", hostname,
    580 		    clnt_spcreateerror(""));
    581 		return (FALSE);
    582 	}
    583 	if (clnt_call(cli, SM_NOTIFY, xdr_stat_chge, &arg, xdr_void,
    584 	    &dummy, timeout) != RPC_SUCCESS) {
    585 		syslog(LOG_ERR, "Failed to contact rpc.statd at host %s",
    586 		    hostname);
    587 		clnt_destroy(cli);
    588 		return (FALSE);
    589 	}
    590 	clnt_destroy(cli);
    591 	return (TRUE);
    592 }
    593 
    594 
    595 static void
    596 die(int n)
    597 {
    598 	(*db->close)(db);
    599 	exit(n);
    600 }
    601