2 * Send NSM notify calls to all hosts listed in /var/lib/sm
4 * Copyright (C) 2004-2006 Olaf Kirch <okir@suse.de>
11 #include <sys/types.h>
12 #include <sys/socket.h>
15 #include <sys/param.h>
16 #include <sys/syslog.h>
17 #include <arpa/inet.h>
35 # define BASEDIR NFS_STATEDIR
37 # define BASEDIR "/var/lib/nfs"
41 #define DEFAULT_SM_STATE_PATH BASEDIR "/state"
42 #define DEFAULT_SM_DIR_PATH BASEDIR "/sm"
43 #define DEFAULT_SM_BAK_PATH DEFAULT_SM_DIR_PATH ".bak"
45 char *_SM_BASE_PATH = BASEDIR;
46 char *_SM_STATE_PATH = DEFAULT_SM_STATE_PATH;
47 char *_SM_DIR_PATH = DEFAULT_SM_DIR_PATH;
48 char *_SM_BAK_PATH = DEFAULT_SM_BAK_PATH;
50 #define NSM_PROG 100024
51 #define NSM_PROGRAM 100024
55 #define NSM_MAX_TIMEOUT 120 /* don't make this too big */
56 #define MAXMSGSIZE 256
59 struct nsm_host * next;
62 struct sockaddr_storage addr;
71 static char nsm_hostname[256];
72 static uint32_t nsm_state;
73 static int opt_debug = 0;
74 static int opt_update_state = 1;
75 static unsigned int opt_max_retry = 15 * 60;
76 static char * opt_srcaddr = 0;
77 static uint16_t opt_srcport = 0;
79 static unsigned int nsm_get_state(int);
80 static void notify(void);
81 static int notify_host(int, struct nsm_host *);
82 static void recv_reply(int);
83 static void backup_hosts(const char *, const char *);
84 static void get_hosts(const char *);
85 static void insert_host(struct nsm_host *);
86 static struct nsm_host *find_host(uint32_t);
87 static int record_pid(void);
88 static void drop_privs(void);
89 static void set_kernel_nsm_state(int state);
91 static struct nsm_host * hosts = NULL;
94 * Address handling utilities
97 static unsigned short smn_get_port(const struct sockaddr *sap)
99 switch (sap->sa_family) {
101 return ntohs(((struct sockaddr_in *)sap)->sin_port);
103 return ntohs(((struct sockaddr_in6 *)sap)->sin6_port);
108 static void smn_set_port(struct sockaddr *sap, const unsigned short port)
110 switch (sap->sa_family) {
112 ((struct sockaddr_in *)sap)->sin_port = htons(port);
115 ((struct sockaddr_in6 *)sap)->sin6_port = htons(port);
120 static struct addrinfo *smn_lookup(const char *name)
122 struct addrinfo *ai, hint = {
123 #if HAVE_DECL_AI_ADDRCONFIG
124 .ai_flags = AI_ADDRCONFIG,
125 #endif /* HAVE_DECL_AI_ADDRCONFIG */
126 .ai_family = AF_INET,
127 .ai_protocol = IPPROTO_UDP,
131 error = getaddrinfo(name, NULL, &hint, &ai);
133 xlog(D_GENERAL, "getaddrinfo(3): %s", gai_strerror(error));
140 static void smn_forget_host(struct nsm_host *host)
146 freeaddrinfo(host->ai);
152 main(int argc, char **argv)
158 progname = strrchr(argv[0], '/');
159 if (progname != NULL)
164 while ((c = getopt(argc, argv, "dm:np:v:P:f")) != -1) {
173 opt_max_retry = atoi(optarg) * 60;
176 opt_update_state = 0;
179 opt_srcport = atoi(optarg);
182 opt_srcaddr = optarg;
185 _SM_BASE_PATH = strdup(optarg);
186 _SM_STATE_PATH = malloc(strlen(optarg)+1+sizeof("state"));
187 _SM_DIR_PATH = malloc(strlen(optarg)+1+sizeof("sm"));
188 _SM_BAK_PATH = malloc(strlen(optarg)+1+sizeof("sm.bak"));
189 if (_SM_BASE_PATH == NULL ||
190 _SM_STATE_PATH == NULL ||
191 _SM_DIR_PATH == NULL ||
192 _SM_BAK_PATH == NULL) {
193 fprintf(stderr, "unable to allocate memory");
196 strcat(strcpy(_SM_STATE_PATH, _SM_BASE_PATH), "/state");
197 strcat(strcpy(_SM_DIR_PATH, _SM_BASE_PATH), "/sm");
198 strcat(strcpy(_SM_BAK_PATH, _SM_BASE_PATH), "/sm.bak");
207 usage: fprintf(stderr,
208 "Usage: %s -notify [-dfq] [-m max-retry-minutes] [-p srcport]\n"
209 " [-P /path/to/state/directory] [-v my_host_name]\n",
217 xlog_config(D_ALL, 1);
222 xlog(L_NOTICE, "Version " VERSION " starting");
224 if (strcmp(_SM_BASE_PATH, BASEDIR) == 0) {
225 if (record_pid() == 0 && force == 0 && opt_update_state == 1) {
226 /* already run, don't try again */
227 xlog(L_NOTICE, "Already notifying clients; Exiting!");
233 strncpy(nsm_hostname, opt_srcaddr, sizeof(nsm_hostname)-1);
235 if (gethostname(nsm_hostname, sizeof(nsm_hostname)) < 0) {
236 xlog(L_ERROR, "Failed to obtain name of local host: %m");
240 backup_hosts(_SM_DIR_PATH, _SM_BAK_PATH);
241 get_hosts(_SM_BAK_PATH);
243 /* If there are not hosts to notify, just exit */
245 xlog(D_GENERAL, "No hosts to notify; exiting");
249 /* Get and update the NSM state. This will call sync() */
250 nsm_state = nsm_get_state(opt_update_state);
251 set_kernel_nsm_state(nsm_state);
254 xlog(L_NOTICE, "Backgrounding to notify hosts...\n");
256 if (daemon(0, 0) < 0) {
257 xlog(L_ERROR, "unable to background: %m");
271 while ((hp = hosts) != 0) {
273 xlog(L_NOTICE, "Unable to notify %s, giving up",
288 struct sockaddr_storage address;
289 struct sockaddr *local_addr = (struct sockaddr *)&address;
295 sock = socket(AF_INET, SOCK_DGRAM, 0);
297 xlog(L_ERROR, "Failed to create RPC socket: %m");
300 fcntl(sock, F_SETFL, O_NONBLOCK);
302 memset(&address, 0, sizeof(address));
303 local_addr->sa_family = AF_INET; /* Default to IPv4 */
305 /* Bind source IP if provided on command line */
307 struct addrinfo *ai = smn_lookup(opt_srcaddr);
310 "Not a valid hostname or address: \"%s\"",
315 /* We know it's IPv4 at this point */
316 memcpy(local_addr, ai->ai_addr, ai->ai_addrlen);
321 /* Use source port if provided on the command line,
322 * otherwise use bindresvport */
324 smn_set_port(local_addr, opt_srcport);
325 if (bind(sock, local_addr, sizeof(struct sockaddr_in)) < 0) {
326 xlog(L_ERROR, "Failed to bind RPC socket: %m");
331 struct sockaddr_in *sin = (struct sockaddr_in *)local_addr;
332 (void) bindresvport(sock, sin);
333 /* try to avoid known ports */
334 se = getservbyport(sin->sin_port, "udp");
335 if (se && retry_cnt < 100) {
343 failtime = time(NULL) + opt_max_retry;
349 time_t now = time(NULL);
350 unsigned int sent = 0;
354 if (failtime && now >= failtime)
357 while (hosts && ((wait = hosts->send_next - now) <= 0)) {
358 /* Never send more than 10 packets at once */
362 /* Remove queue head */
366 if (notify_host(sock, hp))
369 /* Set the timeout for this call, using an
370 exponential timeout strategy */
372 if ((hp->timeout <<= 1) > NSM_MAX_TIMEOUT)
373 hp->timeout = NSM_MAX_TIMEOUT;
374 hp->send_next = now + wait;
382 xlog(D_GENERAL, "Host %s due in %ld seconds",
391 if (poll(&pfd, 1, wait) != 1)
399 * Send notification to a single host
402 notify_host(int sock, struct nsm_host *host)
404 struct sockaddr_storage address;
405 struct sockaddr *dest = (struct sockaddr *)&address;
406 socklen_t destlen = sizeof(address);
407 static unsigned int xid = 0;
408 uint32_t msgbuf[MAXMSGSIZE], *p;
412 xid = getpid() + time(NULL);
416 if (host->ai == NULL) {
417 host->ai = smn_lookup(host->name);
418 if (host->ai == NULL) {
419 xlog_warn("DNS resolution of %s failed; "
420 "retrying later", host->name);
425 memset(msgbuf, 0, sizeof(msgbuf));
427 *p++ = htonl(host->xid);
431 /* If we retransmitted 4 times, reset the port to force
432 * a new portmap lookup (in case statd was restarted).
433 * We also rotate through multiple IP addresses at this
436 if (host->retries >= 4) {
437 /* don't rotate if there is only one addrinfo */
438 if (host->ai->ai_next == NULL)
439 memcpy(&host->addr, host->ai->ai_addr,
440 host->ai->ai_addrlen);
442 struct addrinfo *first = host->ai;
443 struct addrinfo **next = &host->ai;
445 /* remove the first entry from the list */
446 host->ai = first->ai_next;
447 first->ai_next = NULL;
448 /* find the end of the list */
449 next = &first->ai_next;
451 next = & (*next)->ai_next;
452 /* put first entry at end */
454 memcpy(&host->addr, first->ai_addr,
458 smn_set_port((struct sockaddr *)&host->addr, 0);
462 memcpy(dest, &host->addr, destlen);
463 if (smn_get_port(dest) == 0) {
464 /* Build a PMAP packet */
465 xlog(D_GENERAL, "Sending portmap query to %s", host->name);
467 smn_set_port(dest, 111);
468 *p++ = htonl(100000);
476 *p++ = htonl(NSM_PROGRAM);
477 *p++ = htonl(NSM_VERSION);
478 *p++ = htonl(IPPROTO_UDP);
481 /* Build an SM_NOTIFY packet */
482 xlog(D_GENERAL, "Sending SM_NOTIFY to %s", host->name);
484 *p++ = htonl(NSM_PROGRAM);
485 *p++ = htonl(NSM_VERSION);
486 *p++ = htonl(NSM_NOTIFY);
493 len = strlen(nsm_hostname);
495 memcpy(p, nsm_hostname, len);
497 *p++ = htonl(nsm_state);
499 len = (p - msgbuf) << 2;
501 if (sendto(sock, msgbuf, len, 0, dest, destlen) < 0)
502 xlog_warn("Sending Reboot Notification to "
503 "'%s' failed: errno %d (%m)", host->name, errno);
509 * Receive reply from remote host
515 struct sockaddr *sap;
516 uint32_t msgbuf[MAXMSGSIZE], *p, *end;
520 res = recv(sock, msgbuf, sizeof(msgbuf), 0);
524 xlog(D_GENERAL, "Received packet...");
527 end = p + (res >> 2);
530 if (*p++ != htonl(1) /* must be REPLY */
531 || *p++ != htonl(0) /* must be ACCEPTED */
532 || *p++ != htonl(0) /* must be NULL verifier */
534 || *p++ != htonl(0)) /* must be SUCCESS */
537 /* Before we look at the data, find the host struct for
539 if ((hp = find_host(xid)) == NULL)
541 sap = (struct sockaddr *)&hp->addr;
543 if (smn_get_port(sap) == 0) {
544 /* This was a portmap request */
551 hp->send_next = time(NULL);
553 /* No binding for statd. Delay the next
554 * portmap query for max timeout */
555 xlog(D_GENERAL, "No statd on %s", hp->name);
556 hp->timeout = NSM_MAX_TIMEOUT;
557 hp->send_next += NSM_MAX_TIMEOUT;
559 smn_set_port(sap, port);
560 if (hp->timeout >= NSM_MAX_TIMEOUT / 4)
561 hp->timeout = NSM_MAX_TIMEOUT / 4;
565 /* Successful NOTIFY call. Server returns void,
566 * so nothing we need to do here (except
567 * check that we didn't read past the end of the
571 xlog(D_GENERAL, "Host %s notified successfully",
578 fail: /* Re-insert the host */
583 * Back up all hosts from the sm directory to sm.bak
586 backup_hosts(const char *dirname, const char *bakname)
591 if (!(dir = opendir(dirname))) {
592 xlog_warn("Failed to open %s: %m", dirname);
596 while ((de = readdir(dir)) != NULL) {
597 char src[1024], dst[1024];
599 if (de->d_name[0] == '.')
602 snprintf(src, sizeof(src), "%s/%s", dirname, de->d_name);
603 snprintf(dst, sizeof(dst), "%s/%s", bakname, de->d_name);
604 if (rename(src, dst) < 0)
605 xlog_warn("Failed to rename %s -> %s: %m", src, dst);
611 * Get all entries from sm.bak and convert them to host entries
614 get_hosts(const char *dirname)
616 struct nsm_host *host;
620 if (!(dir = opendir(dirname))) {
621 xlog_warn("Failed to open %s: %m", dirname);
626 while ((de = readdir(dir)) != NULL) {
630 if (de->d_name[0] == '.')
633 host = calloc(1, sizeof(*host));
635 xlog_warn("Unable to allocate memory");
639 snprintf(path, sizeof(path), "%s/%s", dirname, de->d_name);
640 if (stat(path, &stb) < 0)
643 host->last_used = stb.st_mtime;
644 host->timeout = NSM_TIMEOUT;
645 host->path = strdup(path);
646 host->name = strdup(de->d_name);
647 host->retries = 100; /* force address retry */
659 * Insert host into sorted list
662 insert_host(struct nsm_host *host)
664 struct nsm_host **where, *p;
667 while ((p = *where) != 0) {
668 /* Sort in ascending order of timeout */
669 if (host->send_next < p->send_next)
671 /* If we have the same timeout, put the
672 * most recently used host first.
673 * This makes sure that "recent" hosts
674 * get notified first.
676 if (host->send_next == p->send_next
677 && host->last_used > p->last_used)
687 * Find host given the XID
689 static struct nsm_host *
690 find_host(uint32_t xid)
692 struct nsm_host **where, *p;
695 while ((p = *where) != 0) {
707 * Retrieve the current NSM state
710 nsm_get_state(int update)
712 char newfile[PATH_MAX];
715 if ((fd = open(_SM_STATE_PATH, O_RDONLY)) < 0) {
716 xlog_warn("%s: %m", _SM_STATE_PATH);
717 xlog_warn("Creating %s, set initial state 1",
722 if (read(fd, &state, sizeof(state)) != sizeof(state)) {
723 xlog_warn("%s: bad file size, setting state = 1",
736 snprintf(newfile, sizeof(newfile),
737 "%s.new", _SM_STATE_PATH);
738 if ((fd = open(newfile, O_CREAT|O_WRONLY, 0644)) < 0) {
739 xlog(L_ERROR, "Cannot create %s: %m", newfile);
742 if (write(fd, &state, sizeof(state)) != sizeof(state)) {
744 "Failed to write state to %s", newfile);
748 if (rename(newfile, _SM_STATE_PATH) < 0) {
750 "Cannot create %s: %m", _SM_STATE_PATH);
760 * Record pid in /var/run/sm-notify.pid
761 * This file should remain until a reboot, even if the
763 * If file already exists, fail.
765 static int record_pid(void)
770 snprintf(pid, 20, "%d\n", getpid());
771 fd = open("/var/run/sm-notify.pid", O_CREAT|O_EXCL|O_WRONLY, 0600);
774 if (write(fd, pid, strlen(pid)) != strlen(pid)) {
775 xlog_warn("Writing to pid file failed: errno %d (%m)",
782 /* Drop privileges to match owner of state-directory
783 * (in case a reply triggers some unknown bug).
785 static void drop_privs(void)
789 if (stat(_SM_DIR_PATH, &st) == -1 &&
790 stat(_SM_BASE_PATH, &st) == -1) {
795 if (st.st_uid == 0) {
796 xlog_warn("Running as 'root'. "
797 "chown %s to choose different user", _SM_DIR_PATH);
802 if (setgid(st.st_gid) == -1
803 || setuid(st.st_uid) == -1) {
804 xlog(L_ERROR, "Fail to drop privileges");
809 static void set_kernel_nsm_state(int state)
812 const char *file = "/proc/sys/fs/nfs/nsm_local_state";
814 fd = open(file ,O_WRONLY);
817 snprintf(buf, sizeof(buf), "%d", state);
818 if (write(fd, buf, strlen(buf)) != strlen(buf)) {
819 xlog_warn("Writing to '%s' failed: errno %d (%m)",