1 /* $NetBSD: statd.c,v 1.2 1997/05/17 15:52:52 christos 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 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.2 1997/05/17 15:52:52 christos 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 __P((struct svc_req *, SVCXPRT *)); 67 static void handle_sigchld __P((int)); 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) 152 int sig; 153 { 154 int pid, status; 155 pid = wait4(-1, &status, WNOHANG, (struct rusage *) 0); 156 if (!pid) 157 syslog(LOG_ERR, "Phantom SIGCHLD??"); 158 else if (status) 159 syslog(LOG_ERR, "Child %d failed with status %d", pid, 160 WEXITSTATUS(status)); 161 else if (debug) 162 syslog(LOG_DEBUG, "Child %d exited OK", pid); 163 } 164 165 /* sync_file --------------------------------------------------------------- */ 166 /* 167 * Purpose: Packaged call of msync() to flush changes to mmap()ed file 168 * Returns: Nothing. Errors to syslog. 169 */ 170 void 171 sync_file() 172 { 173 if (msync((void *)status_info, 0) < 0) 174 syslog(LOG_ERR, "msync() failed: %s", strerror(errno)); 175 } 176 177 /* find_host -------------------------------------------------------------- */ 178 /* 179 * Purpose: Find the entry in the status file for a given host 180 * Returns: Pointer to that entry in the mmap() region, or NULL. 181 * Notes: Also creates entries if requested. 182 * Failure to create also returns NULL. 183 */ 184 HostInfo * 185 find_host(hostname, create) 186 char *hostname; 187 int create; 188 { 189 HostInfo *hp; 190 HostInfo *spare_slot = NULL; 191 HostInfo *result = NULL; 192 int i; 193 194 for (i = 0, hp = status_info->hosts; i < status_info->noOfHosts; 195 i++, hp++) { 196 if (!strncasecmp(hostname, hp->hostname, SM_MAXSTRLEN)) { 197 result = hp; 198 break; 199 } 200 if (!spare_slot && !hp->monList && !hp->notifyReqd) 201 spare_slot = hp; 202 } 203 204 /* Return if entry found, or if not asked to create one. */ 205 if (result || !create) 206 return (result); 207 208 /* 209 * Now create an entry, using the spare slot if one was found or 210 * adding to the end of the list otherwise, extending file if req'd 211 */ 212 if (!spare_slot) { 213 off_t desired_size; 214 spare_slot = &status_info->hosts[status_info->noOfHosts]; 215 desired_size = ((char *)spare_slot - (char *)status_info) + 216 sizeof(HostInfo); 217 218 if (desired_size > status_file_len) { 219 /* Extend file by writing 1 byte of junk at the 220 * desired end pos */ 221 lseek(status_fd, desired_size - 1, SEEK_SET); 222 i = write(status_fd, &i, 1); 223 if (i < 1) { 224 syslog(LOG_ERR, "Unable to extend status file"); 225 return (NULL); 226 } 227 status_file_len = desired_size; 228 } 229 status_info->noOfHosts++; 230 } 231 /* 232 * Initialise the spare slot that has been found/created 233 * Note that we do not msync(), since the caller is presumed to be 234 * about to modify the entry further 235 */ 236 memset(spare_slot, 0, sizeof(HostInfo)); 237 strncpy(spare_slot->hostname, hostname, SM_MAXSTRLEN); 238 return (spare_slot); 239 } 240 241 /* init_file -------------------------------------------------------------- */ 242 /* 243 * Purpose: Open file, create if necessary, initialise it. 244 * Returns: Nothing - exits on error 245 * Notes: Called before process becomes daemon, hence logs to 246 * stderr rather than syslog. 247 * Opens the file, then mmap()s it for ease of access. 248 * Also performs initial clean-up of the file, zeroing 249 * monitor list pointers, setting the notifyReqd flag in 250 * all hosts that had a monitor list, and incrementing 251 * the state number to the next even value. 252 */ 253 void 254 init_file(filename) 255 char *filename; 256 { 257 char buf[HEADER_LEN]; 258 int new_file = FALSE; 259 int i; 260 261 /* try to open existing file - if not present, create one */ 262 status_fd = open(filename, O_RDWR); 263 if ((status_fd < 0) && (errno == ENOENT)) { 264 status_fd = open(filename, O_RDWR | O_CREAT, 0644); 265 new_file = TRUE; 266 } 267 if (status_fd < 0) { 268 err(1, "unable to open status file %s", filename); 269 /* NOTREACHED */ 270 } 271 272 /* 273 * File now open. mmap() it, with a generous size to allow for 274 * later growth, where we will extend the file but not re-map it. 275 */ 276 status_info = (FileLayout *)mmap(NULL, 0x10000000, 277 PROT_READ | PROT_WRITE, MAP_SHARED, status_fd, 0); 278 279 if (status_info == (FileLayout *)(-1)) { 280 perror("rpc.statd"); 281 fprintf(stderr, "Unable to mmap() status file\n"); 282 } 283 status_file_len = lseek(status_fd, 0L, SEEK_END); 284 285 /* 286 * If the file was not newly created, validate the contents, and if 287 * defective, re-create from scratch. 288 */ 289 if (!new_file) { 290 if ((status_file_len < HEADER_LEN) || (status_file_len < 291 (HEADER_LEN + sizeof(HostInfo) * status_info->noOfHosts))) { 292 fprintf(stderr, "rpc.statd: status file is corrupt\n"); 293 new_file = TRUE; 294 } 295 } 296 /* Initialisation of a new, empty file. */ 297 if (new_file) { 298 memset(buf, 0, sizeof(buf)); 299 lseek(status_fd, 0L, SEEK_SET); 300 write(status_fd, buf, HEADER_LEN); 301 status_file_len = HEADER_LEN; 302 } else { 303 /* 304 * Clean-up of existing file - monitored hosts will have a 305 * pointer to a list of clients, which refers to memory in 306 * the previous incarnation of the program and so are 307 * meaningless now. These pointers are zeroed and the fact 308 * that the host was previously monitored is recorded by 309 * setting the notifyReqd flag, which will in due course 310 * cause a SM_NOTIFY to be sent. 311 * 312 * Note that if we crash twice in quick succession, some hosts 313 * may already have notifyReqd set, where we didn't manage to 314 * notify them before the second crash occurred. 315 */ 316 for (i = 0; i < status_info->noOfHosts; i++) { 317 HostInfo *this_host = &status_info->hosts[i]; 318 319 if (this_host->monList) { 320 this_host->notifyReqd = TRUE; 321 this_host->monList = NULL; 322 } 323 } 324 /* Select the next higher even number for the state counter */ 325 status_info->ourState = 326 (status_info->ourState + 2) & 0xfffffffe; 327 status_info->ourState++; /* XXX - ??? */ 328 } 329 } 330 331 /* notify_one_host --------------------------------------------------------- */ 332 /* 333 * Purpose: Perform SM_NOTIFY procedure at specified host 334 * Returns: TRUE if success, FALSE if failed. 335 */ 336 static int 337 notify_one_host(hostname) 338 char *hostname; 339 { 340 struct timeval timeout = {20, 0}; /* 20 secs timeout */ 341 CLIENT *cli; 342 char dummy; 343 stat_chge arg; 344 char our_hostname[SM_MAXSTRLEN + 1]; 345 346 gethostname(our_hostname, sizeof(our_hostname)); 347 our_hostname[SM_MAXSTRLEN] = '\0'; 348 arg.mon_name = our_hostname; 349 arg.state = status_info->ourState; 350 351 if (debug) 352 syslog(LOG_DEBUG, "Sending SM_NOTIFY to host %s from %s", 353 hostname, our_hostname); 354 355 cli = clnt_create(hostname, SM_PROG, SM_VERS, "udp"); 356 if (!cli) { 357 syslog(LOG_ERR, "Failed to contact host %s%s", hostname, 358 clnt_spcreateerror("")); 359 return (FALSE); 360 } 361 if (clnt_call(cli, SM_NOTIFY, xdr_stat_chge, &arg, xdr_void, 362 &dummy, timeout) != RPC_SUCCESS) { 363 syslog(LOG_ERR, "Failed to contact rpc.statd at host %s", 364 hostname); 365 clnt_destroy(cli); 366 return (FALSE); 367 } 368 clnt_destroy(cli); 369 return (TRUE); 370 } 371 372 /* notify_hosts ------------------------------------------------------------ */ 373 /* 374 * Purpose: Send SM_NOTIFY to all hosts marked as requiring it 375 * Returns: Nothing, immediately - forks a process to do the work. 376 * Notes: Does nothing if there are no monitored hosts. 377 * Called after all the initialisation has been done - 378 * logs to syslog. 379 */ 380 void 381 notify_hosts(void) 382 { 383 HostInfo *hp; 384 int i, attempts; 385 int work_to_do = FALSE; 386 pid_t pid; 387 388 /* First check if there is in fact any work to do. */ 389 for (i = status_info->noOfHosts, hp = status_info->hosts; i; 390 i--, hp++) { 391 if (hp->notifyReqd) { 392 work_to_do = TRUE; 393 break; 394 } 395 } 396 397 if (!work_to_do) 398 return; /* No work found */ 399 400 pid = fork(); 401 if (pid == -1) { 402 syslog(LOG_ERR, "Unable to fork notify process - %s", 403 strerror(errno)); 404 return; 405 } 406 if (pid) 407 return; 408 409 /* 410 * Here in the child process. We continue until all the hosts marked 411 * as requiring notification have been duly notified. 412 * If one of the initial attempts fails, we sleep for a while and 413 * have another go. This is necessary because when we have crashed, 414 * (eg. a power outage) it is quite possible that we won't be able to 415 * contact all monitored hosts immediately on restart, either because 416 * they crashed too and take longer to come up (in which case the 417 * notification isn't really required), or more importantly if some 418 * router etc. needed to reach the monitored host has not come back 419 * up yet. In this case, we will be a bit late in re-establishing 420 * locks (after the grace period) but that is the best we can do. 421 * We try 10 times at 5 sec intervals, 10 more times at 1 minute 422 * intervals, then 24 more times at hourly intervals, finally 423 * giving up altogether if the host hasn't come back to life after 424 * 24 hours. 425 */ 426 for (attempts = 0; attempts < 44; attempts++) { 427 work_to_do = FALSE; /* Unless anything fails */ 428 for (i = status_info->noOfHosts, hp = status_info->hosts; i > 0; 429 i--, hp++) { 430 if (hp->notifyReqd) { 431 if (notify_one_host(hp->hostname)) { 432 hp->notifyReqd = FALSE; 433 sync_file(); 434 } else 435 work_to_do = TRUE; 436 } 437 } 438 if (!work_to_do) 439 break; 440 if (attempts < 10) 441 sleep(5); 442 else 443 if (attempts < 20) 444 sleep(60); 445 else 446 sleep(60 * 60); 447 } 448 exit(0); 449 } 450