Home | History | Annotate | Line # | Download | only in rpc.statd
statd.c revision 1.5
      1 /*	$NetBSD: statd.c,v 1.5 1997/10/17 16:03:04 lukem 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  * 4. Neither the name of the author nor the names of any co-contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY ANDREW GORDON AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  *
     34  */
     35 
     36 #include <sys/cdefs.h>
     37 #ifndef lint
     38 __RCSID("$NetBSD: statd.c,v 1.5 1997/10/17 16:03:04 lukem Exp $");
     39 #endif
     40 
     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/types.h>
     47 #include <sys/mman.h>
     48 #include <sys/wait.h>
     49 
     50 #include <err.h>
     51 #include <errno.h>
     52 #include <fcntl.h>
     53 #include <signal.h>
     54 #include <stdio.h>
     55 #include <string.h>
     56 #include <syslog.h>
     57 #include <unistd.h>
     58 
     59 #include <rpc/rpc.h>
     60 
     61 #include "statd.h"
     62 
     63 int     	debug = 0;		/* Controls syslog() for debug msgs */
     64 int     	_rpcsvcdirty = 0;	/* XXX ??? */
     65 FileLayout	*status_info;		/* Pointer to mmap()ed status file */
     66 static int	status_fd;		/* File descriptor for the open file */
     67 static off_t	status_file_len;	/* Current on-disc length of file */
     68 
     69 	int	main __P((int, char **));
     70 static	void	handle_sigchld __P((int));
     71 extern	void	sm_prog_1 __P((struct svc_req *, SVCXPRT *));
     72 
     73 int
     74 main(argc, argv)
     75 	int argc;
     76 	char **argv;
     77 {
     78 	SVCXPRT *transp;
     79 	struct sigaction sa;
     80 	int ch;
     81 
     82 	while ((ch = getopt(argc, argv, "d")) != (-1)) {
     83 		switch (ch) {
     84 		case 'd':
     85 			debug = 1;
     86 			break;
     87 		default:
     88 		case '?':
     89 			errx(1, "usage: rpc.statd [-d]");
     90 			/* NOTREACHED */
     91 		}
     92 	}
     93 	(void)pmap_unset(SM_PROG, SM_VERS);
     94 
     95 	transp = svcudp_create(RPC_ANYSOCK);
     96 	if (transp == NULL) {
     97 		errx(1, "cannot create udp service.");
     98 		/* NOTREACHED */
     99 	}
    100 	if (!svc_register(transp, SM_PROG, SM_VERS, sm_prog_1, IPPROTO_UDP)) {
    101 		errx(1, "unable to register (SM_PROG, SM_VERS, udp).");
    102 		/* NOTREACHED */
    103 	}
    104 	transp = svctcp_create(RPC_ANYSOCK, 0, 0);
    105 	if (transp == NULL) {
    106 		errx(1, "cannot create tcp service.");
    107 		/* NOTREACHED */
    108 	}
    109 	if (!svc_register(transp, SM_PROG, SM_VERS, sm_prog_1, IPPROTO_TCP)) {
    110 		errx(1, "unable to register (SM_PROG, SM_VERS, tcp).");
    111 		/* NOTREACHED */
    112 	}
    113 	init_file("/var/db/statd.status");
    114 
    115 	/*
    116 	 * Note that it is NOT sensible to run this program from inetd - the
    117 	 * protocol assumes that it will run immediately at boot time.
    118 	 */
    119 	daemon(0, 0);
    120 	openlog("rpc.statd", 0, LOG_DAEMON);
    121 	if (debug)
    122 		syslog(LOG_INFO, "Starting - debug enabled");
    123 	else
    124 		syslog(LOG_INFO, "Starting");
    125 
    126 	/* Install signal handler to collect exit status of child processes */
    127 	sa.sa_handler = handle_sigchld;
    128 	sigemptyset(&sa.sa_mask);
    129 	sigaddset(&sa.sa_mask, SIGCHLD);
    130 	sa.sa_flags = SA_RESTART;
    131 	sigaction(SIGCHLD, &sa, NULL);
    132 
    133 	/* Initialisation now complete - start operating */
    134 
    135 	/*
    136 	 * notify_hosts() forks a process (if necessary) to do the
    137 	 * SM_NOTIFY calls, which may be slow.
    138 	 */
    139 	notify_hosts();
    140 
    141 	svc_run();		/* Should never return */
    142 	exit(1);
    143 }
    144 
    145 /* handle_sigchld ---------------------------------------------------------- */
    146 /*
    147  * Purpose:	Catch SIGCHLD and collect process status
    148  * Returns:	Nothing.
    149  * Notes:	No special action required, other than to collect the
    150  *		process status and hence allow the child to die:
    151  *		we only use child processes for asynchronous transmission
    152  *		of SM_NOTIFY to other systems, so it is normal for the
    153  *		children to exit when they have done their work.
    154  */
    155 static void
    156 handle_sigchld(sig)
    157 	int sig;
    158 {
    159 	int     pid, status;
    160 	pid = wait4(-1, &status, WNOHANG, (struct rusage *) 0);
    161 	if (!pid)
    162 		syslog(LOG_ERR, "Phantom SIGCHLD??");
    163 	else if (status)
    164 		syslog(LOG_ERR, "Child %d failed with status %d", pid,
    165 		    WEXITSTATUS(status));
    166 	else if (debug)
    167 		syslog(LOG_DEBUG, "Child %d exited OK", pid);
    168 }
    169 
    170 /* sync_file --------------------------------------------------------------- */
    171 /*
    172  * Purpose:	Packaged call of msync() to flush changes to mmap()ed file
    173  * Returns:	Nothing.  Errors to syslog.
    174  */
    175 void
    176 sync_file()
    177 {
    178 	if (msync((caddr_t)status_info, 0) < 0)
    179 		syslog(LOG_ERR, "msync() failed: %s", strerror(errno));
    180 }
    181 
    182 /* find_host -------------------------------------------------------------- */
    183 /*
    184  * Purpose:	Find the entry in the status file for a given host
    185  * Returns:	Pointer to that entry in the mmap() region, or NULL.
    186  * Notes:	Also creates entries if requested.
    187  *		Failure to create also returns NULL.
    188  */
    189 HostInfo *
    190 find_host(hostname, create)
    191 	char *hostname;
    192 	int create;
    193 {
    194 	HostInfo *hp;
    195 	HostInfo *spare_slot = NULL;
    196 	HostInfo *result = NULL;
    197 	int i;
    198 
    199 	for (i = 0, hp = status_info->hosts; i < status_info->noOfHosts;
    200 	    i++, hp++) {
    201 		if (!strncasecmp(hostname, hp->hostname, SM_MAXSTRLEN)) {
    202 			result = hp;
    203 			break;
    204 		}
    205 		if (!spare_slot && !hp->monList && !hp->notifyReqd)
    206 			spare_slot = hp;
    207 	}
    208 
    209 	/* Return if entry found, or if not asked to create one. */
    210 	if (result || !create)
    211 		return (result);
    212 
    213 	/*
    214 	 * Now create an entry, using the spare slot if one was found or
    215 	 * adding to the end of the list otherwise, extending file if req'd
    216 	 */
    217 	if (!spare_slot) {
    218 		off_t desired_size;
    219 		spare_slot = &status_info->hosts[status_info->noOfHosts];
    220 		desired_size = ((char *)spare_slot - (char *)status_info) +
    221 		    sizeof(HostInfo);
    222 
    223 		if (desired_size > status_file_len) {
    224 			/* Extend file by writing 1 byte of junk at the
    225 			 * desired end pos	 */
    226 			lseek(status_fd, desired_size - 1, SEEK_SET);
    227 			i = write(status_fd, &i, 1);
    228 			if (i < 1) {
    229 				syslog(LOG_ERR, "Unable to extend status file");
    230 				return (NULL);
    231 			}
    232 			status_file_len = desired_size;
    233 		}
    234 		status_info->noOfHosts++;
    235 	}
    236 	/*
    237 	 * Initialise the spare slot that has been found/created
    238 	 * Note that we do not msync(), since the caller is presumed to be
    239 	 * about to modify the entry further
    240 	 */
    241 	memset(spare_slot, 0, sizeof(HostInfo));
    242 	strncpy(spare_slot->hostname, hostname, SM_MAXSTRLEN);
    243 	return (spare_slot);
    244 }
    245 
    246 /* init_file -------------------------------------------------------------- */
    247 /*
    248  * Purpose:	Open file, create if necessary, initialise it.
    249  * Returns:	Nothing - exits on error
    250  * Notes:	Called before process becomes daemon, hence logs to
    251  *		stderr rather than syslog.
    252  *		Opens the file, then mmap()s it for ease of access.
    253  *		Also performs initial clean-up of the file, zeroing
    254  *		monitor list pointers, setting the notifyReqd flag in
    255  *		all hosts that had a monitor list, and incrementing
    256  *		the state number to the next even value.
    257  */
    258 void
    259 init_file(filename)
    260 	char *filename;
    261 {
    262 	char buf[HEADER_LEN];
    263 	int new_file = FALSE;
    264 	int i;
    265 
    266 	/* try to open existing file - if not present, create one */
    267 	status_fd = open(filename, O_RDWR);
    268 	if ((status_fd < 0) && (errno == ENOENT)) {
    269 		status_fd = open(filename, O_RDWR | O_CREAT, 0644);
    270 		new_file = TRUE;
    271 	}
    272 	if (status_fd < 0) {
    273 		err(1, "unable to open status file %s", filename);
    274 		/* NOTREACHED */
    275 	}
    276 
    277 	/*
    278 	 * File now open.  mmap() it, with a generous size to allow for
    279 	 * later growth, where we will extend the file but not re-map it.
    280 	 */
    281 	status_info = (FileLayout *)mmap(NULL, 0x10000000,
    282 	    PROT_READ | PROT_WRITE, MAP_SHARED, status_fd, 0);
    283 
    284 	if (status_info == (FileLayout *)(-1)) {
    285 		perror("rpc.statd");
    286 		fprintf(stderr, "Unable to mmap() status file\n");
    287 	}
    288 	status_file_len = lseek(status_fd, 0L, SEEK_END);
    289 
    290 	/*
    291 	 * If the file was not newly created, validate the contents, and if
    292 	 * defective, re-create from scratch.
    293 	 */
    294 	if (!new_file) {
    295 		if ((status_file_len < HEADER_LEN) || (status_file_len <
    296 		    (HEADER_LEN + sizeof(HostInfo) * status_info->noOfHosts))) {
    297 			fprintf(stderr, "rpc.statd: status file is corrupt\n");
    298 			new_file = TRUE;
    299 		}
    300 	}
    301 	/* Initialisation of a new, empty file. */
    302 	if (new_file) {
    303 		memset(buf, 0, sizeof(buf));
    304 		lseek(status_fd, 0L, SEEK_SET);
    305 		write(status_fd, buf, HEADER_LEN);
    306 		status_file_len = HEADER_LEN;
    307 	} else {
    308 		/*
    309 		 * Clean-up of existing file - monitored hosts will have a
    310 		 * pointer to a list of clients, which refers to memory in
    311 		 * the previous incarnation of the program and so are
    312 		 * meaningless now.  These pointers are zeroed and the fact
    313 		 * that the host was previously monitored is recorded by
    314 		 * setting the notifyReqd flag, which will in due course
    315 		 * cause a SM_NOTIFY to be sent.
    316 		 *
    317 		 * Note that if we crash twice in quick succession, some hosts
    318 		 * may already have notifyReqd set, where we didn't manage to
    319 		 * notify them before the second crash occurred.
    320 		 */
    321 		for (i = 0; i < status_info->noOfHosts; i++) {
    322 			HostInfo *this_host = &status_info->hosts[i];
    323 
    324 			if (this_host->monList) {
    325 				this_host->notifyReqd = TRUE;
    326 				this_host->monList = NULL;
    327 			}
    328 		}
    329 		/* Select the next higher even number for the state counter */
    330 		status_info->ourState =
    331 		    (status_info->ourState + 2) & 0xfffffffe;
    332 		status_info->ourState++;	/* XXX - ??? */
    333 	}
    334 }
    335 
    336 /* notify_one_host --------------------------------------------------------- */
    337 /*
    338  * Purpose:	Perform SM_NOTIFY procedure at specified host
    339  * Returns:	TRUE if success, FALSE if failed.
    340  */
    341 static int
    342 notify_one_host(hostname)
    343 	char *hostname;
    344 {
    345 	struct timeval timeout = {20, 0};	/* 20 secs timeout */
    346 	CLIENT *cli;
    347 	char dummy;
    348 	stat_chge arg;
    349 	char our_hostname[SM_MAXSTRLEN + 1];
    350 
    351 	gethostname(our_hostname, sizeof(our_hostname));
    352 	our_hostname[SM_MAXSTRLEN] = '\0';
    353 	arg.mon_name = our_hostname;
    354 	arg.state = status_info->ourState;
    355 
    356 	if (debug)
    357 		syslog(LOG_DEBUG, "Sending SM_NOTIFY to host %s from %s",
    358 		    hostname, our_hostname);
    359 
    360 	cli = clnt_create(hostname, SM_PROG, SM_VERS, "udp");
    361 	if (!cli) {
    362 		syslog(LOG_ERR, "Failed to contact host %s%s", hostname,
    363 		    clnt_spcreateerror(""));
    364 		return (FALSE);
    365 	}
    366 	if (clnt_call(cli, SM_NOTIFY, xdr_stat_chge, &arg, xdr_void,
    367 	    &dummy, timeout) != RPC_SUCCESS) {
    368 		syslog(LOG_ERR, "Failed to contact rpc.statd at host %s",
    369 		    hostname);
    370 		clnt_destroy(cli);
    371 		return (FALSE);
    372 	}
    373 	clnt_destroy(cli);
    374 	return (TRUE);
    375 }
    376 
    377 /* notify_hosts ------------------------------------------------------------ */
    378 /*
    379  * Purpose:	Send SM_NOTIFY to all hosts marked as requiring it
    380  * Returns:	Nothing, immediately - forks a process to do the work.
    381  * Notes:	Does nothing if there are no monitored hosts.
    382  *		Called after all the initialisation has been done -
    383  *		logs to syslog.
    384  */
    385 void
    386 notify_hosts(void)
    387 {
    388 	HostInfo *hp;
    389 	int i, attempts;
    390 	int work_to_do = FALSE;
    391 	pid_t pid;
    392 
    393 	/* First check if there is in fact any work to do. */
    394 	for (i = status_info->noOfHosts, hp = status_info->hosts; i;
    395 	    i--, hp++) {
    396 		if (hp->notifyReqd) {
    397 			work_to_do = TRUE;
    398 			break;
    399 		}
    400 	}
    401 
    402 	if (!work_to_do)
    403 		return;		/* No work found */
    404 
    405 	pid = fork();
    406 	if (pid == -1) {
    407 		syslog(LOG_ERR, "Unable to fork notify process - %s",
    408 		    strerror(errno));
    409 		return;
    410 	}
    411 	if (pid)
    412 		return;
    413 
    414 	/*
    415 	 * Here in the child process.  We continue until all the hosts marked
    416 	 * as requiring notification have been duly notified.
    417 	 * If one of the initial attempts fails, we sleep for a while and
    418 	 * have another go.  This is necessary because when we have crashed,
    419 	 * (eg. a power outage) it is quite possible that we won't be able to
    420 	 * contact all monitored hosts immediately on restart, either because
    421 	 * they crashed too and take longer to come up (in which case the
    422 	 * notification isn't really required), or more importantly if some
    423 	 * router etc. needed to reach the monitored host has not come back
    424 	 * up yet.  In this case, we will be a bit late in re-establishing
    425 	 * locks (after the grace period) but that is the best we can do.
    426 	 * We try 10 times at 5 sec intervals, 10 more times at 1 minute
    427 	 * intervals, then 24 more times at hourly intervals, finally
    428 	 * giving up altogether if the host hasn't come back to life after
    429 	 * 24 hours.
    430 	 */
    431 	for (attempts = 0; attempts < 44; attempts++) {
    432 		work_to_do = FALSE;	/* Unless anything fails */
    433 		for (i = status_info->noOfHosts, hp = status_info->hosts; i > 0;
    434 		    i--, hp++) {
    435 			if (hp->notifyReqd) {
    436 				if (notify_one_host(hp->hostname)) {
    437 					hp->notifyReqd = FALSE;
    438 					sync_file();
    439 				} else
    440 					work_to_do = TRUE;
    441 			}
    442 		}
    443 		if (!work_to_do)
    444 			break;
    445 		if (attempts < 10)
    446 			sleep(5);
    447 		else
    448 			if (attempts < 20)
    449 				sleep(60);
    450 			else
    451 				sleep(60 * 60);
    452 	}
    453 	exit(0);
    454 }
    455