statd.c revision 1.13 1 /* $NetBSD: statd.c,v 1.13 1999/06/06 02:52:16 thorpej 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.13 1999/06/06 02:52:16 thorpej 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
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
62 #include <rpc/rpc.h>
63
64 #include "statd.h"
65
66 struct sigaction sa;
67 int debug = 0; /* Controls syslog() for debug msgs */
68 int _rpcsvcdirty = 0; /* XXX ??? */
69 static DB *db; /* Database file */
70
71 Header status_info;
72
73 static char undefdata[] = "\0\1\2\3\4\5\6\7";
74 static DBT undefkey = {
75 undefdata,
76 sizeof(undefdata)
77 };
78 extern char *__progname;
79
80
81 /* statd.c */
82 static int walk_one __P((int (*fun )__P ((DBT *, DBT *, void *)), DBT *, DBT *, void *));
83 static int walk_db __P((int (*fun )__P ((DBT *, DBT *, void *)), void *));
84 static int reset_host __P((DBT *, DBT *, void *));
85 static int check_work __P((DBT *, DBT *, void *));
86 static int unmon_host __P((DBT *, DBT *, void *));
87 static int notify_one __P((DBT *, DBT *, void *));
88 static void init_file __P((char *));
89 static int notify_one_host __P((char *));
90 static void die __P((int)) __attribute__((__noreturn__));
91
92 int main __P((int, char **));
93
94 int
95 main(argc, argv)
96 int argc;
97 char **argv;
98 {
99 SVCXPRT *transp;
100 int ch;
101
102 while ((ch = getopt(argc, argv, "d")) != (-1)) {
103 switch (ch) {
104 case 'd':
105 debug = 1;
106 break;
107 default:
108 case '?':
109 (void) fprintf(stderr, "Usage: %s [-d]", __progname);
110 /* NOTREACHED */
111 }
112 }
113 (void)pmap_unset(SM_PROG, SM_VERS);
114
115 transp = svcudp_create(RPC_ANYSOCK);
116 if (transp == NULL) {
117 errx(1, "cannot create udp service.");
118 /* NOTREACHED */
119 }
120 if (!svc_register(transp, SM_PROG, SM_VERS, sm_prog_1, IPPROTO_UDP)) {
121 errx(1, "unable to register (SM_PROG, SM_VERS, udp).");
122 /* NOTREACHED */
123 }
124 transp = svctcp_create(RPC_ANYSOCK, 0, 0);
125 if (transp == NULL) {
126 errx(1, "cannot create tcp service.");
127 /* NOTREACHED */
128 }
129 if (!svc_register(transp, SM_PROG, SM_VERS, sm_prog_1, IPPROTO_TCP)) {
130 errx(1, "unable to register (SM_PROG, SM_VERS, tcp).");
131 /* NOTREACHED */
132 }
133 init_file("/var/db/statd.status");
134
135 /*
136 * Note that it is NOT sensible to run this program from inetd - the
137 * protocol assumes that it will run immediately at boot time.
138 */
139 if (!debug)
140 daemon(0, 0);
141 pidfile(NULL);
142 openlog("rpc.statd", 0, LOG_DAEMON);
143 if (debug)
144 syslog(LOG_INFO, "Starting - debug enabled");
145 else
146 syslog(LOG_INFO, "Starting");
147
148 sa.sa_handler = die;
149 sa.sa_flags = 0;
150 sigemptyset(&sa.sa_mask);
151 (void)sigaction(SIGTERM, &sa, NULL);
152 (void)sigaction(SIGQUIT, &sa, NULL);
153 (void)sigaction(SIGHUP, &sa, NULL);
154 (void)sigaction(SIGINT, &sa, NULL);
155
156 sa.sa_handler = SIG_IGN;
157 sa.sa_flags = SA_RESTART;
158 sigemptyset(&sa.sa_mask);
159 sigaddset(&sa.sa_mask, SIGALRM);
160
161 /* Initialisation now complete - start operating */
162
163 /* Notify hosts that need it */
164 notify_handler(0);
165
166 while (1)
167 svc_run(); /* Should never return */
168 die(0);
169 }
170
171 /* notify_handler ---------------------------------------------------------- */
172 /*
173 * Purpose: Catch SIGALRM and collect process status
174 * Returns: Nothing.
175 * Notes: No special action required, other than to collect the
176 * process status and hence allow the child to die:
177 * we only use child processes for asynchronous transmission
178 * of SM_NOTIFY to other systems, so it is normal for the
179 * children to exit when they have done their work.
180 */
181 void
182 notify_handler(sig)
183 int sig;
184 {
185 time_t now;
186
187 NO_ALARM;
188 sa.sa_handler = SIG_IGN;
189 (void)sigaction(SIGALRM, &sa, NULL);
190
191 now = time(NULL);
192
193 (void) walk_db(notify_one, &now);
194
195 if (walk_db(check_work, &now) == 0) {
196 /*
197 * No more work to be done.
198 */
199 CLR_ALARM;
200 return;
201 }
202 sync_file();
203 ALARM;
204 alarm(5);
205 }
206
207 /* sync_file --------------------------------------------------------------- */
208 /*
209 * Purpose: Packaged call of msync() to flush changes to mmap()ed file
210 * Returns: Nothing. Errors to syslog.
211 */
212 void
213 sync_file()
214 {
215 DBT data;
216
217 data.data = &status_info;
218 data.size = sizeof(status_info);
219 switch ((*db->put)(db, &undefkey, &data, 0)) {
220 case 0:
221 return;
222 case -1:
223 goto bad;
224 default:
225 abort();
226 }
227 if ((*db->sync)(db, 0) == -1) {
228 bad:
229 syslog(LOG_ERR, "database corrupted %m");
230 die(1);
231 }
232 }
233
234 /* change_host -------------------------------------------------------------- */
235 /*
236 * Purpose: Update/Create an entry for host
237 * Returns: Nothing
238 * Notes:
239 *
240 */
241 void
242 change_host(hostname, hp)
243 char *hostname;
244 HostInfo *hp;
245 {
246 DBT key, data;
247 char *ptr;
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 = hp;
256 data.size = sizeof(*hp);
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(hostname, hp)
279 char *hostname;
280 HostInfo *hp;
281 {
282 DBT key, data;
283 char *ptr;
284
285 for (ptr = hostname; *ptr; ptr++)
286 if (isupper((unsigned char) *ptr))
287 *ptr = tolower((unsigned char) *ptr);
288
289 key.data = hostname;
290 key.size = ptr - hostname + 1;
291 switch ((*db->get)(db, &key, &data, 0)) {
292 case 0:
293 if (data.size != sizeof(*hp))
294 goto bad;
295 return memcpy(hp, data.data, sizeof(*hp));
296 case 1:
297 return NULL;
298 case -1:
299 goto bad;
300 default:
301 abort();
302 }
303
304 bad:
305 syslog(LOG_ERR, "Database corrupted %m");
306 return NULL;
307 }
308
309 /* walk_one ------------------------------------------------------------- */
310 /*
311 * Purpose: Call the given function if the element is valid
312 * Returns: Nothing - exits on error
313 * Notes:
314 */
315 static int
316 walk_one(fun, key, data, ptr)
317 int (*fun) __P((DBT *, DBT *, void *));
318 DBT *key, *data;
319 void *ptr;
320 {
321 if (key->size == undefkey.size &&
322 memcmp(key->data, undefkey.data, key->size) == 0)
323 return 0;
324 if (data->size != sizeof(HostInfo)) {
325 syslog(LOG_ERR, "Bad data in database");
326 die(1);
327 }
328
329 return (*fun)(key, data, ptr);
330 }
331
332 /* walk_db -------------------------------------------------------------- */
333 /*
334 * Purpose: Iterate over all elements calling the given function
335 * Returns: -1 if function failed, 0 on success
336 * Notes:
337 */
338 static int
339 walk_db(fun, ptr)
340 int (*fun) __P((DBT *, DBT *, void *));
341 void *ptr;
342 {
343 DBT key, data;
344
345 switch ((*db->seq)(db, &key, &data, R_FIRST)) {
346 case -1:
347 goto bad;
348 case 1:
349 /* We should have at least the magic entry at this point */
350 abort();
351 case 0:
352 if (walk_one(fun, &key, &data, ptr) == -1)
353 return -1;
354 break;
355 default:
356 abort();
357 }
358
359
360 for (;;)
361 switch ((*db->seq)(db, &key, &data, R_NEXT)) {
362 case -1:
363 goto bad;
364 case 1:
365 if (walk_one(fun, &key, &data, ptr) == -1)
366 return -1;
367 break;
368 case 0:
369 return 0;
370 default:
371 abort();
372 }
373 bad:
374 syslog(LOG_ERR, "Corrupted database %m");
375 die(1);
376 }
377
378 /* reset_host ------------------------------------------------------------ */
379 /*
380 * Purpose: Clean up existing hosts in file.
381 * Returns: Always success 0.
382 * Notes: Clean-up of existing file - monitored hosts will have a
383 * pointer to a list of clients, which refers to memory in
384 * the previous incarnation of the program and so are
385 * meaningless now. These pointers are zeroed and the fact
386 * that the host was previously monitored is recorded by
387 * setting the notifyReqd flag, which will in due course
388 * cause a SM_NOTIFY to be sent.
389 *
390 * Note that if we crash twice in quick succession, some hosts
391 * may already have notifyReqd set, where we didn't manage to
392 * notify them before the second crash occurred.
393 */
394 static int
395 reset_host(key, data, ptr)
396 DBT *key, *data;
397 void *ptr;
398 {
399 HostInfo *hi = data->data;
400
401 if (hi->monList) {
402 hi->notifyReqd = *(time_t *) data;
403 hi->attempts = 0;
404 hi->monList = NULL;
405 }
406 return 0;
407 }
408
409 /* check_work ------------------------------------------------------------ */
410 /*
411 * Purpose: Check if there is work to be done.
412 * Returns: 0 if there is no work to be done -1 if there is.
413 * Notes:
414 */
415 static int
416 check_work(key, data, ptr)
417 DBT *key, *data;
418 void *ptr;
419 {
420 HostInfo *hi = data->data;
421
422 return hi->notifyReqd ? -1 : 0;
423 }
424
425 /* unmon_host ------------------------------------------------------------ */
426 /*
427 * Purpose: Unmonitor a host
428 * Returns: 0
429 * Notes:
430 */
431 static int
432 unmon_host(key, data, ptr)
433 DBT *key, *data;
434 void *ptr;
435 {
436 char *name = key->data;
437 HostInfo *hi = data->data;
438
439 if (do_unmon(name, hi, ptr))
440 change_host(name, hi);
441 return 0;
442 }
443
444 /* notify_one ------------------------------------------------------------ */
445 /*
446 * Purpose: Notify one host.
447 * Returns: 0 if success -1 on failure
448 * Notes:
449 */
450 static int
451 notify_one(key, data, ptr)
452 DBT *key, *data;
453 void *ptr;
454 {
455 time_t now = *(time_t *) ptr;
456 char *name = key->data;
457 HostInfo *hi = data->data;
458
459 if (hi->notifyReqd == 0 || hi->notifyReqd > now)
460 return 0;
461
462 if (notify_one_host(name)) {
463 give_up:
464 hi->notifyReqd = 0;
465 hi->attempts = 0;
466 switch ((*db->put)(db, key, data, 0)) {
467 case -1:
468 syslog(LOG_ERR, "Error storing %s (%m)", name);
469 case 0:
470 return 0;
471
472 default:
473 abort();
474 }
475 }
476 else {
477 /*
478 * If one of the initial attempts fails, we wait
479 * for a while and have another go. This is necessary
480 * because when we have crashed, (eg. a power outage)
481 * it is quite possible that we won't be able to
482 * contact all monitored hosts immediately on restart,
483 * either because they crashed too and take longer
484 * to come up (in which case the notification isn't
485 * really required), or more importantly if some
486 * router etc. needed to reach the monitored host
487 * has not come back up yet. In this case, we will
488 * be a bit late in re-establishing locks (after the
489 * grace period) but that is the best we can do. We
490 * try 10 times at 5 sec intervals, 10 more times at
491 * 1 minute intervals, then 24 more times at hourly
492 * intervals, finally giving up altogether if the
493 * host hasn't come back to life after 24 hours.
494 */
495 if (hi->attempts++ >= 44)
496 goto give_up;
497 else if (hi->attempts < 10)
498 hi->notifyReqd += 5;
499 else if (hi->attempts < 20)
500 hi->notifyReqd += 60;
501 else
502 hi->notifyReqd += 60 * 60;
503 return -1;
504 }
505 }
506
507 /* init_file -------------------------------------------------------------- */
508 /*
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.
518 */
519 static void
520 init_file(filename)
521 char *filename;
522 {
523 DBT data;
524
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);
529
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;
536
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 break;
545 default:
546 abort();
547 }
548
549 reset_database();
550 return;
551 }
552
553 /* reset_database --------------------------------------------------------- */
554 /*
555 * Purpose: Clears the statd database
556 * Returns: Nothing
557 * Notes: If this is not called on reset, it will leak memory.
558 */
559 void
560 reset_database()
561 {
562 time_t now = time(NULL);
563 walk_db(reset_host, &now);
564
565 /* Select the next higher even number for the state counter */
566 status_info.ourState =
567 (status_info.ourState + 2) & 0xfffffffe;
568 status_info.ourState++; /* XXX - ??? */
569 sync_file();
570 }
571
572 /* unmon_hosts --------------------------------------------------------- */
573 /*
574 * Purpose: Unmonitor all the hosts
575 * Returns: Nothing
576 * Notes:
577 */
578 void
579 unmon_hosts()
580 {
581 time_t now = time(NULL);
582 walk_db(unmon_host, &now);
583 sync_file();
584 }
585
586 static int
587 notify_one_host(hostname)
588 char *hostname;
589 {
590 struct timeval timeout = {20, 0}; /* 20 secs timeout */
591 CLIENT *cli;
592 char dummy;
593 stat_chge arg;
594 char our_hostname[MAXHOSTNAMELEN + 1];
595
596 gethostname(our_hostname, sizeof(our_hostname));
597 our_hostname[sizeof(our_hostname) - 1] = '\0';
598 our_hostname[SM_MAXSTRLEN] = '\0';
599 arg.mon_name = our_hostname;
600 arg.state = status_info.ourState;
601
602 if (debug)
603 syslog(LOG_DEBUG, "Sending SM_NOTIFY to host %s from %s",
604 hostname, our_hostname);
605
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);
611 }
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);
618 }
619 clnt_destroy(cli);
620 return (TRUE);
621 }
622
623
624 static void
625 die(n)
626 int n;
627 {
628 (*db->close)(db);
629 exit(n);
630 }
631