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