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