statd.c revision 1.23.2.1 1 /* $NetBSD: statd.c,v 1.23.2.1 2006/03/28 23:20:44 riz 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.23.2.1 2006/03/28 23:20:44 riz 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 #include <sys/wait.h>
49
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>
63
64 #include <rpc/rpc.h>
65
66 #include "statd.h"
67
68 struct sigaction sa;
69 int debug = 0; /* Controls syslog() for debug msgs */
70 int _rpcsvcdirty = 0; /* XXX ??? */
71 static DB *db; /* Database file */
72
73 Header status_info;
74
75 static char undefdata[] = "\0\1\2\3\4\5\6\7";
76 static DBT undefkey = {
77 undefdata,
78 sizeof(undefdata)
79 };
80
81
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((char *));
90 static int notify_one_host __P((char *));
91 static void die __P((int)) __attribute__((__noreturn__));
92
93 int main __P((int, char **));
94
95 int
96 main(argc, argv)
97 int argc;
98 char **argv;
99 {
100 int ch;
101 struct sigaction nsa;
102 int maxrec = RPC_MAXDATASIZE;
103
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 */
115 }
116 }
117 (void)rpcb_unset(SM_PROG, SM_VERS, NULL);
118
119 rpc_control(RPC_SVC_CONNMAXREC_SET, &maxrec);
120
121 if (!svc_create(sm_prog_1, SM_PROG, SM_VERS, "udp")) {
122 errx(1, "cannot create udp service.");
123 /* NOTREACHED */
124 }
125 if (!svc_create(sm_prog_1, SM_PROG, SM_VERS, "tcp")) {
126 errx(1, "cannot create udp service.");
127 /* NOTREACHED */
128 }
129
130 init_file("/var/db/statd.status");
131
132 /*
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.
135 */
136 if (!debug)
137 daemon(0, 0);
138
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);
143
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");
150
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);
158
159 sa.sa_handler = SIG_IGN;
160 sa.sa_flags = SA_RESTART;
161 sigemptyset(&sa.sa_mask);
162 sigaddset(&sa.sa_mask, SIGALRM);
163
164 /* Initialisation now complete - start operating */
165
166 /* Notify hosts that need it */
167 notify_handler(0);
168
169 while (1)
170 svc_run(); /* Should never return */
171 die(0);
172 }
173
174 /* notify_handler ---------------------------------------------------------- */
175 /*
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.
183 */
184 void
185 notify_handler(sig)
186 int sig;
187 {
188 time_t now;
189
190 NO_ALARM;
191 sa.sa_handler = SIG_IGN;
192 (void)sigaction(SIGALRM, &sa, NULL);
193
194 now = time(NULL);
195
196 (void) walk_db(notify_one, &now);
197
198 if (walk_db(check_work, &now) == 0) {
199 /*
200 * No more work to be done.
201 */
202 CLR_ALARM;
203 return;
204 }
205 sync_file();
206 ALARM;
207 alarm(5);
208 }
209
210 /* sync_file --------------------------------------------------------------- */
211 /*
212 * Purpose: Packaged call of msync() to flush changes to mmap()ed file
213 * Returns: Nothing. Errors to syslog.
214 */
215 void
216 sync_file()
217 {
218 DBT data;
219
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();
229 }
230 if ((*db->sync)(db, 0) == -1) {
231 bad:
232 syslog(LOG_ERR, "database corrupted %m");
233 die(1);
234 }
235 }
236
237 /* change_host -------------------------------------------------------------- */
238 /*
239 * Purpose: Update/Create an entry for host
240 * Returns: Nothing
241 * Notes:
242 *
243 */
244 void
245 change_host(hostname, hp)
246 char *hostname;
247 HostInfo *hp;
248 {
249 DBT key, data;
250 char *ptr;
251
252 for (ptr = hostname; *ptr; ptr++)
253 if (isupper((unsigned char) *ptr))
254 *ptr = tolower((unsigned char) *ptr);
255
256 key.data = hostname;
257 key.size = ptr - hostname + 1;
258 data.data = hp;
259 data.size = sizeof(*hp);
260
261 switch ((*db->put)(db, &key, &data, 0)) {
262 case -1:
263 syslog(LOG_ERR, "database corrupted %m");
264 die(1);
265 case 0:
266 return;
267 default:
268 abort();
269 }
270 }
271
272
273 /* find_host -------------------------------------------------------------- */
274 /*
275 * Purpose: Find the entry in the status file for a given host
276 * Returns: Copy of entry in hd, or NULL
277 * Notes:
278 *
279 */
280 HostInfo *
281 find_host(hostname, hp)
282 char *hostname;
283 HostInfo *hp;
284 {
285 DBT key, data;
286 char *ptr;
287
288 for (ptr = hostname; *ptr; ptr++)
289 if (isupper((unsigned char) *ptr))
290 *ptr = tolower((unsigned char) *ptr);
291
292 key.data = hostname;
293 key.size = ptr - hostname + 1;
294 switch ((*db->get)(db, &key, &data, 0)) {
295 case 0:
296 if (data.size != sizeof(*hp))
297 goto bad;
298 return memcpy(hp, data.data, sizeof(*hp));
299 case 1:
300 return NULL;
301 case -1:
302 goto bad;
303 default:
304 abort();
305 }
306
307 bad:
308 syslog(LOG_ERR, "Database corrupted %m");
309 return NULL;
310 }
311
312 /* walk_one ------------------------------------------------------------- */
313 /*
314 * Purpose: Call the given function if the element is valid
315 * Returns: Nothing - exits on error
316 * Notes:
317 */
318 static int
319 walk_one(fun, key, data, ptr)
320 int (*fun) __P((DBT *, HostInfo *, void *));
321 DBT *key, *data;
322 void *ptr;
323 {
324 HostInfo h;
325 if (key->size == undefkey.size &&
326 memcmp(key->data, undefkey.data, key->size) == 0)
327 return 0;
328 if (data->size != sizeof(HostInfo)) {
329 syslog(LOG_ERR, "Bad data in database");
330 die(1);
331 }
332 memcpy(&h, data->data, sizeof(h));
333 return (*fun)(key, &h, ptr);
334 }
335
336 /* walk_db -------------------------------------------------------------- */
337 /*
338 * Purpose: Iterate over all elements calling the given function
339 * Returns: -1 if function failed, 0 on success
340 * Notes:
341 */
342 static int
343 walk_db(fun, ptr)
344 int (*fun) __P((DBT *, HostInfo *, void *));
345 void *ptr;
346 {
347 DBT key, data;
348
349 switch ((*db->seq)(db, &key, &data, R_FIRST)) {
350 case -1:
351 goto bad;
352 case 1:
353 /* We should have at least the magic entry at this point */
354 abort();
355 case 0:
356 if (walk_one(fun, &key, &data, ptr) == -1)
357 return -1;
358 break;
359 default:
360 abort();
361 }
362
363
364 for (;;)
365 switch ((*db->seq)(db, &key, &data, R_NEXT)) {
366 case -1:
367 goto bad;
368 case 0:
369 if (walk_one(fun, &key, &data, ptr) == -1)
370 return -1;
371 break;
372 case 1:
373 return 0;
374 default:
375 abort();
376 }
377 bad:
378 syslog(LOG_ERR, "Corrupted database %m");
379 die(1);
380 }
381
382 /* reset_host ------------------------------------------------------------ */
383 /*
384 * Purpose: Clean up existing hosts in file.
385 * Returns: Always success 0.
386 * Notes: Clean-up of existing file - monitored hosts will have a
387 * pointer to a list of clients, which refers to memory in
388 * the previous incarnation of the program and so are
389 * meaningless now. These pointers are zeroed and the fact
390 * that the host was previously monitored is recorded by
391 * setting the notifyReqd flag, which will in due course
392 * cause a SM_NOTIFY to be sent.
393 *
394 * Note that if we crash twice in quick succession, some hosts
395 * may already have notifyReqd set, where we didn't manage to
396 * notify them before the second crash occurred.
397 */
398 static int
399 reset_host(key, hi, ptr)
400 DBT *key;
401 HostInfo *hi;
402 void *ptr;
403 {
404
405 if (hi->monList) {
406 hi->notifyReqd = *(time_t *) ptr;
407 hi->attempts = 0;
408 hi->monList = NULL;
409 change_host((char *)key->data, hi);
410 }
411 return 0;
412 }
413
414 /* check_work ------------------------------------------------------------ */
415 /*
416 * Purpose: Check if there is work to be done.
417 * Returns: 0 if there is no work to be done -1 if there is.
418 * Notes:
419 */
420 static int
421 check_work(key, hi, ptr)
422 DBT *key;
423 HostInfo *hi;
424 void *ptr;
425 {
426 return hi->notifyReqd ? -1 : 0;
427 }
428
429 /* unmon_host ------------------------------------------------------------ */
430 /*
431 * Purpose: Unmonitor a host
432 * Returns: 0
433 * Notes:
434 */
435 static int
436 unmon_host(key, hi, ptr)
437 DBT *key;
438 HostInfo *hi;
439 void *ptr;
440 {
441 char *name = key->data;
442
443 if (do_unmon(name, hi, ptr))
444 change_host(name, hi);
445 return 0;
446 }
447
448 /* notify_one ------------------------------------------------------------ */
449 /*
450 * Purpose: Notify one host.
451 * Returns: 0 if success -1 on failure
452 * Notes:
453 */
454 static int
455 notify_one(key, hi, ptr)
456 DBT *key;
457 HostInfo *hi;
458 void *ptr;
459 {
460 time_t now = *(time_t *) ptr;
461 char *name = key->data;
462 DBT data;
463
464 if (hi->notifyReqd == 0 || hi->notifyReqd > now)
465 return 0;
466
467 if (notify_one_host(name)) {
468 give_up:
469 hi->notifyReqd = 0;
470 hi->attempts = 0;
471 data.data = hi;
472 data.size = sizeof(*hi);
473 switch ((*db->put)(db, key, &data, 0)) {
474 case -1:
475 syslog(LOG_ERR, "Error storing %s (%m)", name);
476 case 0:
477 return 0;
478
479 default:
480 abort();
481 }
482 }
483 else {
484 /*
485 * If one of the initial attempts fails, we wait
486 * for a while and have another go. This is necessary
487 * because when we have crashed, (eg. a power outage)
488 * it is quite possible that we won't be able to
489 * contact all monitored hosts immediately on restart,
490 * either because they crashed too and take longer
491 * to come up (in which case the notification isn't
492 * really required), or more importantly if some
493 * router etc. needed to reach the monitored host
494 * has not come back up yet. In this case, we will
495 * be a bit late in re-establishing locks (after the
496 * grace period) but that is the best we can do. We
497 * try 10 times at 5 sec intervals, 10 more times at
498 * 1 minute intervals, then 24 more times at hourly
499 * intervals, finally giving up altogether if the
500 * host hasn't come back to life after 24 hours.
501 */
502 if (hi->attempts++ >= 44)
503 goto give_up;
504 else if (hi->attempts < 10)
505 hi->notifyReqd += 5;
506 else if (hi->attempts < 20)
507 hi->notifyReqd += 60;
508 else
509 hi->notifyReqd += 60 * 60;
510 return -1;
511 }
512 }
513
514 /* init_file -------------------------------------------------------------- */
515 /*
516 * Purpose: Open file, create if necessary, initialise it.
517 * Returns: Nothing - exits on error
518 * Notes: Called before process becomes daemon, hence logs to
519 * stderr rather than syslog.
520 * Opens the file, then mmap()s it for ease of access.
521 * Also performs initial clean-up of the file, zeroing
522 * monitor list pointers, setting the notifyReqd flag in
523 * all hosts that had a monitor list, and incrementing
524 * the state number to the next even value.
525 */
526 static void
527 init_file(filename)
528 char *filename;
529 {
530 DBT data;
531
532 db = dbopen(filename, O_RDWR|O_CREAT|O_NDELAY|O_EXLOCK, 0644, DB_HASH,
533 NULL);
534 if (db == NULL)
535 err(1, "Cannot open `%s'", filename);
536
537 switch ((*db->get)(db, &undefkey, &data, 0)) {
538 case 1:
539 /* New database */
540 (void)memset(&status_info, 0, sizeof(status_info));
541 sync_file();
542 return;
543
544 case -1:
545 err(1, "error accessing database (%m)");
546 case 0:
547 /* Existing database */
548 if (data.size != sizeof(status_info))
549 errx(1, "database corrupted %lu != %lu",
550 (u_long)data.size, (u_long)sizeof(status_info));
551 memcpy(&status_info, data.data, data.size);
552 break;
553 default:
554 abort();
555 }
556
557 reset_database();
558 return;
559 }
560
561 /* reset_database --------------------------------------------------------- */
562 /*
563 * Purpose: Clears the statd database
564 * Returns: Nothing
565 * Notes: If this is not called on reset, it will leak memory.
566 */
567 void
568 reset_database()
569 {
570 time_t now = time(NULL);
571 walk_db(reset_host, &now);
572
573 /* Select the next higher even number for the state counter */
574 status_info.ourState =
575 (status_info.ourState + 2) & 0xfffffffe;
576 status_info.ourState++; /* XXX - ??? */
577 sync_file();
578 }
579
580 /* unmon_hosts --------------------------------------------------------- */
581 /*
582 * Purpose: Unmonitor all the hosts
583 * Returns: Nothing
584 * Notes:
585 */
586 void
587 unmon_hosts()
588 {
589 time_t now = time(NULL);
590 walk_db(unmon_host, &now);
591 sync_file();
592 }
593
594 static int
595 notify_one_host(hostname)
596 char *hostname;
597 {
598 struct timeval timeout = {20, 0}; /* 20 secs timeout */
599 CLIENT *cli;
600 char dummy;
601 stat_chge arg;
602 char our_hostname[MAXHOSTNAMELEN + 1];
603
604 gethostname(our_hostname, sizeof(our_hostname));
605 our_hostname[sizeof(our_hostname) - 1] = '\0';
606 our_hostname[SM_MAXSTRLEN] = '\0';
607 arg.mon_name = our_hostname;
608 arg.state = status_info.ourState;
609
610 if (debug)
611 syslog(LOG_DEBUG, "Sending SM_NOTIFY to host %s from %s",
612 hostname, our_hostname);
613
614 cli = clnt_create(hostname, SM_PROG, SM_VERS, "udp");
615 if (!cli) {
616 syslog(LOG_ERR, "Failed to contact host %s%s", hostname,
617 clnt_spcreateerror(""));
618 return (FALSE);
619 }
620 if (clnt_call(cli, SM_NOTIFY, xdr_stat_chge, &arg, xdr_void,
621 &dummy, timeout) != RPC_SUCCESS) {
622 syslog(LOG_ERR, "Failed to contact rpc.statd at host %s",
623 hostname);
624 clnt_destroy(cli);
625 return (FALSE);
626 }
627 clnt_destroy(cli);
628 return (TRUE);
629 }
630
631
632 static void
633 die(n)
634 int n;
635 {
636 (*db->close)(db);
637 exit(n);
638 }
639