No empty .Rs/.Re
[netbsd-mini2440.git] / usr.sbin / rpc.statd / statd.c
blob17552401a5ee1222e7d6fd26b136b729081a84fc
1 /* $NetBSD: statd.c,v 1.28 2007/12/15 19:44:56 perry Exp $ */
3 /*
4 * Copyright (c) 1997 Christos Zoulas. All rights reserved.
5 * Copyright (c) 1995
6 * A.R. Gordon (andrew.gordon@net-tel.co.uk). All rights reserved.
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.
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.
38 #include <sys/cdefs.h>
39 #ifndef lint
40 __RCSID("$NetBSD: statd.c,v 1.28 2007/12/15 19:44:56 perry Exp $");
41 #endif
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 */
47 #include <sys/param.h>
48 #include <sys/wait.h>
50 #include <err.h>
51 #include <ctype.h>
52 #include <errno.h>
53 #include <fcntl.h>
54 #include <signal.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <syslog.h>
59 #include <unistd.h>
60 #include <util.h>
61 #include <db.h>
62 #include <netconfig.h>
64 #include <rpc/rpc.h>
66 #include "statd.h"
68 struct sigaction sa;
69 int debug = 0; /* Controls syslog() for debug msgs */
70 int _rpcsvcdirty = 0; /* XXX ??? */
71 static DB *db; /* Database file */
73 Header status_info;
75 static char undefdata[] = "\0\1\2\3\4\5\6\7";
76 static DBT undefkey = {
77 undefdata,
78 sizeof(undefdata)
82 /* statd.c */
83 static int walk_one __P((int (*fun )__P ((DBT *, HostInfo *, void *)), DBT *, DBT *, void *));
84 static int walk_db __P((int (*fun )__P ((DBT *, HostInfo *, void *)), void *));
85 static int reset_host __P((DBT *, HostInfo *, void *));
86 static int check_work __P((DBT *, HostInfo *, void *));
87 static int unmon_host __P((DBT *, HostInfo *, void *));
88 static int notify_one __P((DBT *, HostInfo *, void *));
89 static void init_file __P((const char *));
90 static int notify_one_host __P((const char *));
91 static void die __P((int)) __dead;
93 int main __P((int, char **));
95 int
96 main(argc, argv)
97 int argc;
98 char **argv;
100 int ch;
101 struct sigaction nsa;
102 int maxrec = RPC_MAXDATASIZE;
104 while ((ch = getopt(argc, argv, "d")) != (-1)) {
105 switch (ch) {
106 case 'd':
107 debug = 1;
108 break;
109 default:
110 case '?':
111 (void)fprintf(stderr, "usage: %s [-d]\n",
112 getprogname());
113 exit(1);
114 /* NOTREACHED */
117 (void)rpcb_unset(SM_PROG, SM_VERS, NULL);
119 rpc_control(RPC_SVC_CONNMAXREC_SET, &maxrec);
121 if (!svc_create(sm_prog_1, SM_PROG, SM_VERS, "udp")) {
122 errx(1, "cannot create udp service.");
123 /* NOTREACHED */
125 if (!svc_create(sm_prog_1, SM_PROG, SM_VERS, "tcp")) {
126 errx(1, "cannot create udp service.");
127 /* NOTREACHED */
130 init_file("/var/db/statd.status");
133 * Note that it is NOT sensible to run this program from inetd - the
134 * protocol assumes that it will run immediately at boot time.
136 if (!debug)
137 daemon(0, 0);
139 sigemptyset(&nsa.sa_mask);
140 nsa.sa_flags = SA_NOCLDSTOP|SA_NOCLDWAIT;
141 nsa.sa_handler = SIG_IGN;
142 (void)sigaction(SIGCHLD, &nsa, NULL);
144 pidfile(NULL);
145 openlog("rpc.statd", 0, LOG_DAEMON);
146 if (debug)
147 syslog(LOG_INFO, "Starting - debug enabled");
148 else
149 syslog(LOG_INFO, "Starting");
151 sa.sa_handler = die;
152 sa.sa_flags = 0;
153 sigemptyset(&sa.sa_mask);
154 (void)sigaction(SIGTERM, &sa, NULL);
155 (void)sigaction(SIGQUIT, &sa, NULL);
156 (void)sigaction(SIGHUP, &sa, NULL);
157 (void)sigaction(SIGINT, &sa, NULL);
159 sa.sa_handler = SIG_IGN;
160 sa.sa_flags = SA_RESTART;
161 sigemptyset(&sa.sa_mask);
162 sigaddset(&sa.sa_mask, SIGALRM);
164 /* Initialisation now complete - start operating */
166 /* Notify hosts that need it */
167 notify_handler(0);
169 while (1)
170 svc_run(); /* Should never return */
171 die(0);
174 /* notify_handler ---------------------------------------------------------- */
176 * Purpose: Catch SIGALRM and collect process status
177 * Returns: Nothing.
178 * Notes: No special action required, other than to collect the
179 * process status and hence allow the child to die:
180 * we only use child processes for asynchronous transmission
181 * of SM_NOTIFY to other systems, so it is normal for the
182 * children to exit when they have done their work.
184 void
185 notify_handler(sig)
186 int sig;
188 time_t now;
190 NO_ALARM;
191 sa.sa_handler = SIG_IGN;
192 (void)sigaction(SIGALRM, &sa, NULL);
194 now = time(NULL);
196 (void) walk_db(notify_one, &now);
198 if (walk_db(check_work, &now) == 0) {
200 * No more work to be done.
202 CLR_ALARM;
203 return;
205 sync_file();
206 ALARM;
207 alarm(5);
210 /* sync_file --------------------------------------------------------------- */
212 * Purpose: Packaged call of msync() to flush changes to mmap()ed file
213 * Returns: Nothing. Errors to syslog.
215 void
216 sync_file()
218 DBT data;
220 data.data = &status_info;
221 data.size = sizeof(status_info);
222 switch ((*db->put)(db, &undefkey, &data, 0)) {
223 case 0:
224 return;
225 case -1:
226 goto bad;
227 default:
228 abort();
230 if ((*db->sync)(db, 0) == -1) {
231 bad:
232 syslog(LOG_ERR, "database corrupted %m");
233 die(1);
237 /* change_host -------------------------------------------------------------- */
239 * Purpose: Update/Create an entry for host
240 * Returns: Nothing
241 * Notes:
244 void
245 change_host(hostnamep, hp)
246 char *hostnamep;
247 HostInfo *hp;
249 DBT key, data;
250 char *ptr;
251 char hostname[MAXHOSTNAMELEN + 1];
252 HostInfo h;
254 strncpy(hostname, hostnamep, MAXHOSTNAMELEN + 1);
255 h = *hp;
257 for (ptr = hostname; *ptr; ptr++)
258 if (isupper((unsigned char) *ptr))
259 *ptr = tolower((unsigned char) *ptr);
261 key.data = hostname;
262 key.size = ptr - hostname + 1;
263 data.data = &h;
264 data.size = sizeof(h);
266 switch ((*db->put)(db, &key, &data, 0)) {
267 case -1:
268 syslog(LOG_ERR, "database corrupted %m");
269 die(1);
270 case 0:
271 return;
272 default:
273 abort();
278 /* find_host -------------------------------------------------------------- */
280 * Purpose: Find the entry in the status file for a given host
281 * Returns: Copy of entry in hd, or NULL
282 * Notes:
285 HostInfo *
286 find_host(hostname, hp)
287 char *hostname;
288 HostInfo *hp;
290 DBT key, data;
291 char *ptr;
293 for (ptr = hostname; *ptr; ptr++)
294 if (isupper((unsigned char) *ptr))
295 *ptr = tolower((unsigned char) *ptr);
297 key.data = hostname;
298 key.size = ptr - hostname + 1;
299 switch ((*db->get)(db, &key, &data, 0)) {
300 case 0:
301 if (data.size != sizeof(*hp))
302 goto bad;
303 return memcpy(hp, data.data, sizeof(*hp));
304 case 1:
305 return NULL;
306 case -1:
307 goto bad;
308 default:
309 abort();
312 bad:
313 syslog(LOG_ERR, "Database corrupted %m");
314 return NULL;
317 /* walk_one ------------------------------------------------------------- */
319 * Purpose: Call the given function if the element is valid
320 * Returns: Nothing - exits on error
321 * Notes:
323 static int
324 walk_one(fun, key, data, ptr)
325 int (*fun) __P((DBT *, HostInfo *, void *));
326 DBT *key, *data;
327 void *ptr;
329 HostInfo h;
330 if (key->size == undefkey.size &&
331 memcmp(key->data, undefkey.data, key->size) == 0)
332 return 0;
333 if (data->size != sizeof(HostInfo)) {
334 syslog(LOG_ERR, "Bad data in database");
335 die(1);
337 memcpy(&h, data->data, sizeof(h));
338 return (*fun)(key, &h, ptr);
341 /* walk_db -------------------------------------------------------------- */
343 * Purpose: Iterate over all elements calling the given function
344 * Returns: -1 if function failed, 0 on success
345 * Notes:
347 static int
348 walk_db(fun, ptr)
349 int (*fun) __P((DBT *, HostInfo *, void *));
350 void *ptr;
352 DBT key, data;
354 switch ((*db->seq)(db, &key, &data, R_FIRST)) {
355 case -1:
356 goto bad;
357 case 1:
358 /* We should have at least the magic entry at this point */
359 abort();
360 case 0:
361 if (walk_one(fun, &key, &data, ptr) == -1)
362 return -1;
363 break;
364 default:
365 abort();
369 for (;;)
370 switch ((*db->seq)(db, &key, &data, R_NEXT)) {
371 case -1:
372 goto bad;
373 case 0:
374 if (walk_one(fun, &key, &data, ptr) == -1)
375 return -1;
376 break;
377 case 1:
378 return 0;
379 default:
380 abort();
382 bad:
383 syslog(LOG_ERR, "Corrupted database %m");
384 die(1);
387 /* reset_host ------------------------------------------------------------ */
389 * Purpose: Clean up existing hosts in file.
390 * Returns: Always success 0.
391 * Notes: Clean-up of existing file - monitored hosts will have a
392 * pointer to a list of clients, which refers to memory in
393 * the previous incarnation of the program and so are
394 * meaningless now. These pointers are zeroed and the fact
395 * that the host was previously monitored is recorded by
396 * setting the notifyReqd flag, which will in due course
397 * cause a SM_NOTIFY to be sent.
399 * Note that if we crash twice in quick succession, some hosts
400 * may already have notifyReqd set, where we didn't manage to
401 * notify them before the second crash occurred.
403 static int
404 reset_host(key, hi, ptr)
405 DBT *key;
406 HostInfo *hi;
407 void *ptr;
410 if (hi->monList) {
411 hi->notifyReqd = *(time_t *) ptr;
412 hi->attempts = 0;
413 hi->monList = NULL;
414 change_host((char *)key->data, hi);
416 return 0;
419 /* check_work ------------------------------------------------------------ */
421 * Purpose: Check if there is work to be done.
422 * Returns: 0 if there is no work to be done -1 if there is.
423 * Notes:
425 static int
426 check_work(key, hi, ptr)
427 DBT *key;
428 HostInfo *hi;
429 void *ptr;
431 return hi->notifyReqd ? -1 : 0;
434 /* unmon_host ------------------------------------------------------------ */
436 * Purpose: Unmonitor a host
437 * Returns: 0
438 * Notes:
440 static int
441 unmon_host(key, hi, ptr)
442 DBT *key;
443 HostInfo *hi;
444 void *ptr;
446 char *name = key->data;
448 if (do_unmon(name, hi, ptr))
449 change_host(name, hi);
450 return 0;
453 /* notify_one ------------------------------------------------------------ */
455 * Purpose: Notify one host.
456 * Returns: 0 if success -1 on failure
457 * Notes:
459 static int
460 notify_one(key, hi, ptr)
461 DBT *key;
462 HostInfo *hi;
463 void *ptr;
465 time_t now = *(time_t *) ptr;
466 char *name = key->data;
467 int error;
469 if (hi->notifyReqd == 0 || hi->notifyReqd > now)
470 return 0;
473 * If one of the initial attempts fails, we wait
474 * for a while and have another go. This is necessary
475 * because when we have crashed, (eg. a power outage)
476 * it is quite possible that we won't be able to
477 * contact all monitored hosts immediately on restart,
478 * either because they crashed too and take longer
479 * to come up (in which case the notification isn't
480 * really required), or more importantly if some
481 * router etc. needed to reach the monitored host
482 * has not come back up yet. In this case, we will
483 * be a bit late in re-establishing locks (after the
484 * grace period) but that is the best we can do. We
485 * try 10 times at 5 sec intervals, 10 more times at
486 * 1 minute intervals, then 24 more times at hourly
487 * intervals, finally giving up altogether if the
488 * host hasn't come back to life after 24 hours.
490 if (notify_one_host(name) || hi->attempts++ >= 44) {
491 error = 0;
492 hi->notifyReqd = 0;
493 hi->attempts = 0;
494 } else {
495 error = -1;
496 if (hi->attempts < 10)
497 hi->notifyReqd += 5;
498 else if (hi->attempts < 20)
499 hi->notifyReqd += 60;
500 else
501 hi->notifyReqd += 60 * 60;
503 change_host(name, hi);
504 return error;
507 /* init_file -------------------------------------------------------------- */
509 * Purpose: Open file, create if necessary, initialise it.
510 * Returns: Nothing - exits on error
511 * Notes: Called before process becomes daemon, hence logs to
512 * stderr rather than syslog.
513 * Opens the file, then mmap()s it for ease of access.
514 * Also performs initial clean-up of the file, zeroing
515 * monitor list pointers, setting the notifyReqd flag in
516 * all hosts that had a monitor list, and incrementing
517 * the state number to the next even value.
519 static void
520 init_file(filename)
521 const char *filename;
523 DBT data;
525 db = dbopen(filename, O_RDWR|O_CREAT|O_NDELAY|O_EXLOCK, 0644, DB_HASH,
526 NULL);
527 if (db == NULL)
528 err(1, "Cannot open `%s'", filename);
530 switch ((*db->get)(db, &undefkey, &data, 0)) {
531 case 1:
532 /* New database */
533 (void)memset(&status_info, 0, sizeof(status_info));
534 sync_file();
535 return;
537 case -1:
538 err(1, "error accessing database (%m)");
539 case 0:
540 /* Existing database */
541 if (data.size != sizeof(status_info))
542 errx(1, "database corrupted %lu != %lu",
543 (u_long)data.size, (u_long)sizeof(status_info));
544 memcpy(&status_info, data.data, data.size);
545 break;
546 default:
547 abort();
550 reset_database();
551 return;
554 /* reset_database --------------------------------------------------------- */
556 * Purpose: Clears the statd database
557 * Returns: Nothing
558 * Notes: If this is not called on reset, it will leak memory.
560 void
561 reset_database()
563 time_t now = time(NULL);
564 walk_db(reset_host, &now);
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();
573 /* unmon_hosts --------------------------------------------------------- */
575 * Purpose: Unmonitor all the hosts
576 * Returns: Nothing
577 * Notes:
579 void
580 unmon_hosts()
582 time_t now = time(NULL);
583 walk_db(unmon_host, &now);
584 sync_file();
587 static int
588 notify_one_host(hostname)
589 const char *hostname;
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];
597 gethostname(our_hostname, sizeof(our_hostname));
598 our_hostname[sizeof(our_hostname) - 1] = '\0';
599 arg.mon_name = our_hostname;
600 arg.state = status_info.ourState;
602 if (debug)
603 syslog(LOG_DEBUG, "Sending SM_NOTIFY to host %s from %s",
604 hostname, our_hostname);
606 cli = clnt_create(hostname, SM_PROG, SM_VERS, "udp");
607 if (!cli) {
608 syslog(LOG_ERR, "Failed to contact host %s%s", hostname,
609 clnt_spcreateerror(""));
610 return (FALSE);
612 if (clnt_call(cli, SM_NOTIFY, xdr_stat_chge, &arg, xdr_void,
613 &dummy, timeout) != RPC_SUCCESS) {
614 syslog(LOG_ERR, "Failed to contact rpc.statd at host %s",
615 hostname);
616 clnt_destroy(cli);
617 return (FALSE);
619 clnt_destroy(cli);
620 return (TRUE);
624 static void
625 die(n)
626 int n;
628 (*db->close)(db);
629 exit(n);