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>
33 # define BASEDIR NFS_STATEDIR
35 # define BASEDIR "/var/lib/nfs"
39 #define DEFAULT_SM_STATE_PATH BASEDIR "/state"
40 #define DEFAULT_SM_DIR_PATH BASEDIR "/sm"
41 #define DEFAULT_SM_BAK_PATH DEFAULT_SM_DIR_PATH ".bak"
43 char *_SM_BASE_PATH = BASEDIR;
44 char *_SM_STATE_PATH = DEFAULT_SM_STATE_PATH;
45 char *_SM_DIR_PATH = DEFAULT_SM_DIR_PATH;
46 char *_SM_BAK_PATH = DEFAULT_SM_BAK_PATH;
48 #define NSM_PROG 100024
49 #define NSM_PROGRAM 100024
53 #define NSM_MAX_TIMEOUT 120 /* don't make this too big */
54 #define MAXMSGSIZE 256
57 struct nsm_host * next;
60 struct sockaddr_storage addr;
69 static char nsm_hostname[256];
70 static uint32_t nsm_state;
71 static int opt_debug = 0;
72 static int opt_quiet = 0;
73 static int opt_update_state = 1;
74 static unsigned int opt_max_retry = 15 * 60;
75 static char * opt_srcaddr = 0;
76 static uint16_t opt_srcport = 0;
77 static int log_syslog = 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 void nsm_log(int fac, const char *fmt, ...);
88 static int record_pid(void);
89 static void drop_privs(void);
90 static void set_kernel_nsm_state(int state);
92 static struct nsm_host * hosts = NULL;
95 * Address handling utilities
98 static unsigned short smn_get_port(const struct sockaddr *sap)
100 switch (sap->sa_family) {
102 return ntohs(((struct sockaddr_in *)sap)->sin_port);
104 return ntohs(((struct sockaddr_in6 *)sap)->sin6_port);
109 static void smn_set_port(struct sockaddr *sap, const unsigned short port)
111 switch (sap->sa_family) {
113 ((struct sockaddr_in *)sap)->sin_port = htons(port);
116 ((struct sockaddr_in6 *)sap)->sin6_port = htons(port);
121 static struct addrinfo *smn_lookup(const sa_family_t family, const char *name)
123 struct addrinfo *ai, hint = {
125 .ai_protocol = IPPROTO_UDP,
128 if (getaddrinfo(name, NULL, &hint, &ai) != 0)
135 main(int argc, char **argv)
140 while ((c = getopt(argc, argv, "dm:np:v:qP:f")) != -1) {
149 opt_max_retry = atoi(optarg) * 60;
152 opt_update_state = 0;
155 opt_srcport = atoi(optarg);
158 opt_srcaddr = optarg;
164 _SM_BASE_PATH = strdup(optarg);
165 _SM_STATE_PATH = malloc(strlen(optarg)+1+sizeof("state"));
166 _SM_DIR_PATH = malloc(strlen(optarg)+1+sizeof("sm"));
167 _SM_BAK_PATH = malloc(strlen(optarg)+1+sizeof("sm.bak"));
168 if (_SM_BASE_PATH == NULL ||
169 _SM_STATE_PATH == NULL ||
170 _SM_DIR_PATH == NULL ||
171 _SM_BAK_PATH == NULL) {
172 nsm_log(LOG_ERR, "unable to allocate memory");
175 strcat(strcpy(_SM_STATE_PATH, _SM_BASE_PATH), "/state");
176 strcat(strcpy(_SM_DIR_PATH, _SM_BASE_PATH), "/sm");
177 strcat(strcpy(_SM_BAK_PATH, _SM_BASE_PATH), "/sm.bak");
186 usage: fprintf(stderr,
187 "Usage: sm-notify [-dfq] [-m max-retry-minutes] [-p srcport]\n"
188 " [-P /path/to/state/directory] [-v my_host_name]\n");
193 openlog("sm-notify", LOG_PID, LOG_DAEMON);
195 if (strcmp(_SM_BASE_PATH, BASEDIR) == 0) {
196 if (record_pid() == 0 && force == 0 && opt_update_state == 1) {
197 /* already run, don't try again */
198 nsm_log(LOG_NOTICE, "Already notifying clients; Exiting!");
204 strncpy(nsm_hostname, opt_srcaddr, sizeof(nsm_hostname)-1);
206 if (gethostname(nsm_hostname, sizeof(nsm_hostname)) < 0) {
207 nsm_log(LOG_ERR, "Failed to obtain name of local host: %s",
212 backup_hosts(_SM_DIR_PATH, _SM_BAK_PATH);
213 get_hosts(_SM_BAK_PATH);
215 /* If there are not hosts to notify, just exit */
217 nsm_log(LOG_DEBUG, "No hosts to notify; exiting");
221 /* Get and update the NSM state. This will call sync() */
222 nsm_state = nsm_get_state(opt_update_state);
223 set_kernel_nsm_state(nsm_state);
227 printf("Backgrounding to notify hosts...\n");
229 if (daemon(0, 0) < 0) {
230 nsm_log(LOG_ERR, "unable to background: %s",
245 while ((hp = hosts) != 0) {
248 "Unable to notify %s, giving up",
263 struct sockaddr_storage address;
264 struct sockaddr *local_addr = (struct sockaddr *)&address;
270 sock = socket(AF_INET, SOCK_DGRAM, 0);
272 nsm_log(LOG_ERR, "Failed to create RPC socket: %s",
276 fcntl(sock, F_SETFL, O_NONBLOCK);
278 memset(&address, 0, sizeof(address));
279 local_addr->sa_family = AF_INET; /* Default to IPv4 */
281 /* Bind source IP if provided on command line */
283 struct addrinfo *ai = smn_lookup(AF_INET, opt_srcaddr);
286 "Not a valid hostname or address: \"%s\"",
291 /* We know it's IPv4 at this point */
292 memcpy(local_addr, ai->ai_addr, ai->ai_addrlen);
297 /* Use source port if provided on the command line,
298 * otherwise use bindresvport */
300 smn_set_port(local_addr, opt_srcport);
301 if (bind(sock, local_addr, sizeof(struct sockaddr_in)) < 0) {
302 nsm_log(LOG_ERR, "Failed to bind RPC socket: %s",
308 struct sockaddr_in *sin = (struct sockaddr_in *)local_addr;
309 (void) bindresvport(sock, sin);
310 /* try to avoid known ports */
311 se = getservbyport(sin->sin_port, "udp");
312 if (se && retry_cnt < 100) {
320 failtime = time(NULL) + opt_max_retry;
326 time_t now = time(NULL);
327 unsigned int sent = 0;
331 if (failtime && now >= failtime)
334 while (hosts && ((wait = hosts->send_next - now) <= 0)) {
335 /* Never send more than 10 packets at once */
339 /* Remove queue head */
343 if (notify_host(sock, hp)){
351 /* Set the timeout for this call, using an
352 exponential timeout strategy */
354 if ((hp->timeout <<= 1) > NSM_MAX_TIMEOUT)
355 hp->timeout = NSM_MAX_TIMEOUT;
356 hp->send_next = now + wait;
364 nsm_log(LOG_DEBUG, "Host %s due in %ld seconds",
373 if (poll(&pfd, 1, wait) != 1)
381 * Send notification to a single host
384 notify_host(int sock, struct nsm_host *host)
386 struct sockaddr_storage address;
387 struct sockaddr *dest = (struct sockaddr *)&address;
388 socklen_t destlen = sizeof(address);
389 static unsigned int xid = 0;
390 uint32_t msgbuf[MAXMSGSIZE], *p;
394 xid = getpid() + time(NULL);
398 if (host->ai == NULL) {
399 host->ai = smn_lookup(AF_UNSPEC, host->name);
400 if (host->ai == NULL) {
402 "%s doesn't seem to be a valid address,"
403 " skipped", host->name);
408 memset(msgbuf, 0, sizeof(msgbuf));
410 *p++ = htonl(host->xid);
414 /* If we retransmitted 4 times, reset the port to force
415 * a new portmap lookup (in case statd was restarted).
416 * We also rotate through multiple IP addresses at this
419 if (host->retries >= 4) {
420 struct addrinfo *first = host->ai;
421 struct addrinfo **next = &host->ai;
423 /* remove the first entry from the list */
424 host->ai = first->ai_next;
425 first->ai_next = NULL;
426 /* find the end of the list */
427 next = &first->ai_next;
429 next = & (*next)->ai_next;
430 /* put first entry at end */
432 memcpy(&host->addr, first->ai_addr, first->ai_addrlen);
433 smn_set_port((struct sockaddr *)&host->addr, 0);
437 memcpy(dest, &host->addr, destlen);
438 if (smn_get_port(dest) == 0) {
439 /* Build a PMAP packet */
440 nsm_log(LOG_DEBUG, "Sending portmap query to %s", host->name);
442 smn_set_port(dest, 111);
443 *p++ = htonl(100000);
451 *p++ = htonl(NSM_PROGRAM);
452 *p++ = htonl(NSM_VERSION);
453 *p++ = htonl(IPPROTO_UDP);
456 /* Build an SM_NOTIFY packet */
457 nsm_log(LOG_DEBUG, "Sending SM_NOTIFY to %s", host->name);
459 *p++ = htonl(NSM_PROGRAM);
460 *p++ = htonl(NSM_VERSION);
461 *p++ = htonl(NSM_NOTIFY);
468 len = strlen(nsm_hostname);
470 memcpy(p, nsm_hostname, len);
472 *p++ = htonl(nsm_state);
474 len = (p - msgbuf) << 2;
476 if (sendto(sock, msgbuf, len, 0, dest, destlen) < 0)
477 nsm_log(LOG_WARNING, "Sending Reboot Notification to "
478 "'%s' failed: errno %d (%s)", host->name, errno, strerror(errno));
484 * Receive reply from remote host
490 struct sockaddr *sap;
491 uint32_t msgbuf[MAXMSGSIZE], *p, *end;
495 res = recv(sock, msgbuf, sizeof(msgbuf), 0);
499 nsm_log(LOG_DEBUG, "Received packet...");
502 end = p + (res >> 2);
505 if (*p++ != htonl(1) /* must be REPLY */
506 || *p++ != htonl(0) /* must be ACCEPTED */
507 || *p++ != htonl(0) /* must be NULL verifier */
509 || *p++ != htonl(0)) /* must be SUCCESS */
512 /* Before we look at the data, find the host struct for
514 if ((hp = find_host(xid)) == NULL)
516 sap = (struct sockaddr *)&hp->addr;
518 if (smn_get_port(sap) == 0) {
519 /* This was a portmap request */
526 hp->send_next = time(NULL);
528 /* No binding for statd. Delay the next
529 * portmap query for max timeout */
530 nsm_log(LOG_DEBUG, "No statd on %s", hp->name);
531 hp->timeout = NSM_MAX_TIMEOUT;
532 hp->send_next += NSM_MAX_TIMEOUT;
534 smn_set_port(sap, port);
535 if (hp->timeout >= NSM_MAX_TIMEOUT / 4)
536 hp->timeout = NSM_MAX_TIMEOUT / 4;
540 /* Successful NOTIFY call. Server returns void,
541 * so nothing we need to do here (except
542 * check that we didn't read past the end of the
546 nsm_log(LOG_DEBUG, "Host %s notified successfully",
552 freeaddrinfo(hp->ai);
557 fail: /* Re-insert the host */
562 * Back up all hosts from the sm directory to sm.bak
565 backup_hosts(const char *dirname, const char *bakname)
570 if (!(dir = opendir(dirname))) {
572 "Failed to open %s: %s", dirname, strerror(errno));
576 while ((de = readdir(dir)) != NULL) {
577 char src[1024], dst[1024];
579 if (de->d_name[0] == '.')
582 snprintf(src, sizeof(src), "%s/%s", dirname, de->d_name);
583 snprintf(dst, sizeof(dst), "%s/%s", bakname, de->d_name);
584 if (rename(src, dst) < 0) {
586 "Failed to rename %s -> %s: %m",
594 * Get all entries from sm.bak and convert them to host entries
597 get_hosts(const char *dirname)
599 struct nsm_host *host;
603 if (!(dir = opendir(dirname))) {
605 "Failed to open %s: %s", dirname, strerror(errno));
610 while ((de = readdir(dir)) != NULL) {
614 if (de->d_name[0] == '.')
617 host = calloc(1, sizeof(*host));
619 nsm_log(LOG_WARNING, "Unable to allocate memory");
623 snprintf(path, sizeof(path), "%s/%s", dirname, de->d_name);
624 if (stat(path, &stb) < 0)
627 host->last_used = stb.st_mtime;
628 host->timeout = NSM_TIMEOUT;
629 host->path = strdup(path);
630 host->name = strdup(de->d_name);
631 host->retries = 100; /* force address retry */
643 * Insert host into sorted list
646 insert_host(struct nsm_host *host)
648 struct nsm_host **where, *p;
651 while ((p = *where) != 0) {
652 /* Sort in ascending order of timeout */
653 if (host->send_next < p->send_next)
655 /* If we have the same timeout, put the
656 * most recently used host first.
657 * This makes sure that "recent" hosts
658 * get notified first.
660 if (host->send_next == p->send_next
661 && host->last_used > p->last_used)
671 * Find host given the XID
673 static struct nsm_host *
674 find_host(uint32_t xid)
676 struct nsm_host **where, *p;
679 while ((p = *where) != 0) {
691 * Retrieve the current NSM state
694 nsm_get_state(int update)
696 char newfile[PATH_MAX];
699 if ((fd = open(_SM_STATE_PATH, O_RDONLY)) < 0) {
701 nsm_log(LOG_WARNING, "%s: %m", _SM_STATE_PATH);
702 nsm_log(LOG_WARNING, "Creating %s, set initial state 1",
708 if (read(fd, &state, sizeof(state)) != sizeof(state)) {
710 "%s: bad file size, setting state = 1",
723 snprintf(newfile, sizeof(newfile),
724 "%s.new", _SM_STATE_PATH);
725 if ((fd = open(newfile, O_CREAT|O_WRONLY, 0644)) < 0) {
726 nsm_log(LOG_ERR, "Cannot create %s: %m", newfile);
729 if (write(fd, &state, sizeof(state)) != sizeof(state)) {
731 "Failed to write state to %s", newfile);
735 if (rename(newfile, _SM_STATE_PATH) < 0) {
737 "Cannot create %s: %m", _SM_STATE_PATH);
750 nsm_log(int fac, const char *fmt, ...)
754 if (fac == LOG_DEBUG && !opt_debug)
759 vsyslog(fac, fmt, ap);
761 vfprintf(stderr, fmt, ap);
768 * Record pid in /var/run/sm-notify.pid
769 * This file should remain until a reboot, even if the
771 * If file already exists, fail.
773 static int record_pid(void)
778 snprintf(pid, 20, "%d\n", getpid());
779 fd = open("/var/run/sm-notify.pid", O_CREAT|O_EXCL|O_WRONLY, 0600);
782 write(fd, pid, strlen(pid));
787 /* Drop privileges to match owner of state-directory
788 * (in case a reply triggers some unknown bug).
790 static void drop_privs(void)
794 if (stat(_SM_DIR_PATH, &st) == -1 &&
795 stat(_SM_BASE_PATH, &st) == -1) {
800 if (st.st_uid == 0) {
802 "sm-notify running as root. chown %s to choose different user",
808 if (setgid(st.st_gid) == -1
809 || setuid(st.st_uid) == -1) {
810 nsm_log(LOG_ERR, "Fail to drop privileges");
815 static void set_kernel_nsm_state(int state)
819 fd = open("/proc/sys/fs/nfs/nsm_local_state",O_WRONLY);
822 snprintf(buf, sizeof(buf), "%d", state);
823 write(fd, buf, strlen(buf));