2 * Send NSM notify calls to all hosts listed in /var/lib/sm
4 * Copyright (C) 2004-2006 Olaf Kirch <okir@suse.de>
8 #include <sys/socket.h>
11 #include <sys/param.h>
12 #include <sys/syslog.h>
13 #include <arpa/inet.h>
29 # define BASEDIR NFS_STATEDIR
31 # define BASEDIR "/var/lib/nfs"
35 #define DEFAULT_SM_STATE_PATH BASEDIR "/state"
36 #define DEFAULT_SM_DIR_PATH BASEDIR "/sm"
37 #define DEFAULT_SM_BAK_PATH DEFAULT_SM_DIR_PATH ".bak"
39 char *_SM_BASE_PATH = BASEDIR;
40 char *_SM_STATE_PATH = DEFAULT_SM_STATE_PATH;
41 char *_SM_DIR_PATH = DEFAULT_SM_DIR_PATH;
42 char *_SM_BAK_PATH = DEFAULT_SM_BAK_PATH;
44 #define NSM_PROG 100024
45 #define NSM_PROGRAM 100024
49 #define NSM_MAX_TIMEOUT 120 /* don't make this too big */
50 #define MAXMSGSIZE 256
52 typedef struct sockaddr_storage nsm_address;
55 struct nsm_host * next;
66 static char nsm_hostname[256];
67 static uint32_t nsm_state;
68 static int opt_debug = 0;
69 static int opt_quiet = 0;
70 static int opt_update_state = 1;
71 static unsigned int opt_max_retry = 15 * 60;
72 static char * opt_srcaddr = 0;
73 static uint16_t opt_srcport = 0;
74 static int log_syslog = 0;
76 static unsigned int nsm_get_state(int);
77 static void notify(void);
78 static void notify_host(int, struct nsm_host *);
79 static void recv_reply(int);
80 static void backup_hosts(const char *, const char *);
81 static void get_hosts(const char *);
82 static void insert_host(struct nsm_host *);
83 struct nsm_host * find_host(uint32_t);
84 static int addr_get_port(nsm_address *);
85 static void addr_set_port(nsm_address *, int);
86 static int host_lookup(int, const char *, nsm_address *);
87 void nsm_log(int fac, const char *fmt, ...);
88 static int record_pid();
89 static void drop_privs(void);
91 static struct nsm_host * hosts = NULL;
94 main(int argc, char **argv)
99 while ((c = getopt(argc, argv, "dm:np:v:qP:f")) != -1) {
108 opt_max_retry = atoi(optarg) * 60;
111 opt_update_state = 0;
114 opt_srcport = atoi(optarg);
117 opt_srcaddr = optarg;
123 _SM_BASE_PATH = strdup(optarg);
124 _SM_STATE_PATH = malloc(strlen(optarg)+1+sizeof("state"));
125 _SM_DIR_PATH = malloc(strlen(optarg)+1+sizeof("sm"));
126 _SM_BAK_PATH = malloc(strlen(optarg)+1+sizeof("sm.bak"));
127 if (_SM_BASE_PATH == NULL ||
128 _SM_STATE_PATH == NULL ||
129 _SM_DIR_PATH == NULL ||
130 _SM_BAK_PATH == NULL) {
131 nsm_log(LOG_WARNING, "unable to allocate memory");
134 strcat(strcpy(_SM_STATE_PATH, _SM_BASE_PATH), "/state");
135 strcat(strcpy(_SM_DIR_PATH, _SM_BASE_PATH), "/sm");
136 strcat(strcpy(_SM_BAK_PATH, _SM_BASE_PATH), "/sm.bak");
145 usage: fprintf(stderr,
146 "Usage: sm-notify [-dfq] [-m max-retry-minutes] [-p srcport]\n"
147 " [-P /path/to/state/directory] [-v my_host_name]\n");
151 if (strcmp(_SM_BASE_PATH, BASEDIR) == 0) {
152 if (record_pid() == 0 && force == 0 && opt_update_state == 0)
153 /* already run, don't try again */
158 strncpy(nsm_hostname, opt_srcaddr, sizeof(nsm_hostname)-1);
160 if (gethostname(nsm_hostname, sizeof(nsm_hostname)) < 0) {
161 perror("gethostname");
165 backup_hosts(_SM_DIR_PATH, _SM_BAK_PATH);
166 get_hosts(_SM_BAK_PATH);
170 printf("Backgrounding to notify hosts...\n");
172 openlog("sm-notify", LOG_PID, LOG_DAEMON);
175 if (daemon(0, 0) < 0) {
176 nsm_log(LOG_WARNING, "unable to background: %s",
186 /* Get and update the NSM state. This will call sync() */
187 nsm_state = nsm_get_state(opt_update_state);
194 while ((hp = hosts) != 0) {
197 "Unable to notify %s, giving up",
212 nsm_address local_addr;
216 sock = socket(AF_INET, SOCK_DGRAM, 0);
221 fcntl(sock, F_SETFL, O_NONBLOCK);
223 memset(&local_addr, 0, sizeof(local_addr));
224 local_addr.ss_family = AF_INET; /* Default to IPv4 */
226 /* Bind source IP if provided on command line */
228 if (!host_lookup(AF_INET, opt_srcaddr, &local_addr)) {
230 "Not a valid hostname or address: \"%s\"\n",
234 /* We know it's IPv4 at this point */
237 /* Use source port if provided on the command line,
238 * otherwise use bindresvport */
240 addr_set_port(&local_addr, opt_srcport);
241 if (bind(sock, (struct sockaddr *) &local_addr, sizeof(local_addr)) < 0) {
246 (void) bindresvport(sock, (struct sockaddr_in *) &local_addr);
250 failtime = time(NULL) + opt_max_retry;
256 time_t now = time(NULL);
257 unsigned int sent = 0;
261 if (failtime && now >= failtime)
264 while ((wait = hosts->send_next - now) <= 0) {
265 /* Never send more than 10 packets at once */
269 /* Remove queue head */
273 notify_host(sock, hp);
275 /* Set the timeout for this call, using an
276 exponential timeout strategy */
278 if ((hp->timeout <<= 1) > NSM_MAX_TIMEOUT)
279 hp->timeout = NSM_MAX_TIMEOUT;
280 hp->send_next = now + wait;
286 nsm_log(LOG_DEBUG, "Host %s due in %ld seconds",
295 if (poll(&pfd, 1, wait) != 1)
303 * Send notification to a single host
306 notify_host(int sock, struct nsm_host *host)
308 static unsigned int xid = 0;
310 uint32_t msgbuf[MAXMSGSIZE], *p;
314 xid = getpid() + time(NULL);
318 memset(msgbuf, 0, sizeof(msgbuf));
320 *p++ = htonl(host->xid);
324 /* If we retransmitted 4 times, reset the port to force
325 * a new portmap lookup (in case statd was restarted)
327 if (host->retries >= 4) {
328 addr_set_port(&host->addr, 0);
333 if (addr_get_port(&dest) == 0) {
334 /* Build a PMAP packet */
335 nsm_log(LOG_DEBUG, "Sending portmap query to %s", host->name);
337 addr_set_port(&dest, 111);
338 *p++ = htonl(100000);
346 *p++ = htonl(NSM_PROGRAM);
347 *p++ = htonl(NSM_VERSION);
348 *p++ = htonl(IPPROTO_UDP);
351 /* Build an SM_NOTIFY packet */
352 nsm_log(LOG_DEBUG, "Sending SM_NOTIFY to %s", host->name);
354 *p++ = htonl(NSM_PROGRAM);
355 *p++ = htonl(NSM_VERSION);
356 *p++ = htonl(NSM_NOTIFY);
363 len = strlen(nsm_hostname);
365 memcpy(p, nsm_hostname, len);
367 *p++ = htonl(nsm_state);
369 len = (p - msgbuf) << 2;
371 sendto(sock, msgbuf, len, 0, (struct sockaddr *) &dest, sizeof(dest));
375 * Receive reply from remote host
381 uint32_t msgbuf[MAXMSGSIZE], *p, *end;
385 res = recv(sock, msgbuf, sizeof(msgbuf), 0);
389 nsm_log(LOG_DEBUG, "Received packet...");
392 end = p + (res >> 2);
395 if (*p++ != htonl(1) /* must be REPLY */
396 || *p++ != htonl(0) /* must be ACCEPTED */
397 || *p++ != htonl(0) /* must be NULL verifier */
399 || *p++ != htonl(0)) /* must be SUCCESS */
402 /* Before we look at the data, find the host struct for
404 if ((hp = find_host(xid)) == NULL)
407 if (addr_get_port(&hp->addr) == 0) {
408 /* This was a portmap request */
415 hp->send_next = time(NULL);
417 /* No binding for statd. Delay the next
418 * portmap query for max timeout */
419 nsm_log(LOG_DEBUG, "No statd on %s", hp->name);
420 hp->timeout = NSM_MAX_TIMEOUT;
421 hp->send_next += NSM_MAX_TIMEOUT;
423 addr_set_port(&hp->addr, port);
424 if (hp->timeout >= NSM_MAX_TIMEOUT / 4)
425 hp->timeout = NSM_MAX_TIMEOUT / 4;
429 /* Successful NOTIFY call. Server returns void,
430 * so nothing we need to do here (except
431 * check that we didn't read past the end of the
435 nsm_log(LOG_DEBUG, "Host %s notified successfully", hp->name);
444 fail: /* Re-insert the host */
449 * Back up all hosts from the sm directory to sm.bak
452 backup_hosts(const char *dirname, const char *bakname)
457 if (!(dir = opendir(dirname))) {
462 while ((de = readdir(dir)) != NULL) {
463 char src[1024], dst[1024];
465 if (de->d_name[0] == '.')
468 snprintf(src, sizeof(src), "%s/%s", dirname, de->d_name);
469 snprintf(dst, sizeof(dst), "%s/%s", bakname, de->d_name);
470 if (rename(src, dst) < 0) {
472 "Failed to rename %s -> %s: %m",
480 * Get all entries from sm.bak and convert them to host names
483 get_hosts(const char *dirname)
485 struct nsm_host *host;
489 if (!(dir = opendir(dirname))) {
495 while ((de = readdir(dir)) != NULL) {
499 if (de->d_name[0] == '.')
502 host = calloc(1, sizeof(*host));
504 snprintf(path, sizeof(path), "%s/%s", dirname, de->d_name);
505 if (!host_lookup(AF_UNSPEC, de->d_name, &host->addr)) {
507 "%s doesn't seem to be a valid address, skipped",
513 if (stat(path, &stb) < 0)
515 host->last_used = stb.st_mtime;
516 host->timeout = NSM_TIMEOUT;
517 host->path = strdup(path);
518 host->name = strdup(de->d_name);
530 * Insert host into sorted list
533 insert_host(struct nsm_host *host)
535 struct nsm_host **where, *p;
538 while ((p = *where) != 0) {
539 /* Sort in ascending order of timeout */
540 if (host->send_next < p->send_next)
542 /* If we have the same timeout, put the
543 * most recently used host first.
544 * This makes sure that "recent" hosts
545 * get notified first.
547 if (host->send_next == p->send_next
548 && host->last_used > p->last_used)
558 * Find host given the XID
561 find_host(uint32_t xid)
563 struct nsm_host **where, *p;
566 while ((p = *where) != 0) {
578 * Retrieve the current NSM state
581 nsm_get_state(int update)
583 char newfile[PATH_MAX];
586 if ((fd = open(_SM_STATE_PATH, O_RDONLY)) < 0) {
588 nsm_log(LOG_WARNING, "%s: %m", _SM_STATE_PATH);
589 nsm_log(LOG_WARNING, "Creating %s, set initial state 1",
595 if (read(fd, &state, sizeof(state)) != sizeof(state)) {
597 "%s: bad file size, setting state = 1",
610 snprintf(newfile, sizeof(newfile),
611 "%s.new", _SM_STATE_PATH);
612 if ((fd = open(newfile, O_CREAT|O_WRONLY, 0644)) < 0) {
613 nsm_log(LOG_WARNING, "Cannot create %s: %m", newfile);
616 if (write(fd, &state, sizeof(state)) != sizeof(state)) {
618 "Failed to write state to %s", newfile);
622 if (rename(newfile, _SM_STATE_PATH) < 0) {
624 "Cannot create %s: %m", _SM_STATE_PATH);
634 * Address handling utilities
638 addr_get_port(nsm_address *addr)
640 switch (((struct sockaddr *) addr)->sa_family) {
642 return ntohs(((struct sockaddr_in *) addr)->sin_port);
644 return ntohs(((struct sockaddr_in6 *) addr)->sin6_port);
650 addr_set_port(nsm_address *addr, int port)
652 switch (((struct sockaddr *) addr)->sa_family) {
654 ((struct sockaddr_in *) addr)->sin_port = htons(port);
657 ((struct sockaddr_in6 *) addr)->sin6_port = htons(port);
662 host_lookup(int af, const char *name, nsm_address *addr)
664 struct addrinfo hints, *ai;
667 memset(&hints, 0, sizeof(hints));
668 hints.ai_family = af;
670 if (getaddrinfo(name, NULL, &hints, &ai) != 0)
673 if (ai->ai_addrlen < sizeof(*addr)) {
674 memcpy(addr, ai->ai_addr, ai->ai_addrlen);
686 nsm_log(int fac, const char *fmt, ...)
690 if (fac == LOG_DEBUG && !opt_debug)
695 vsyslog(fac, fmt, ap);
697 vfprintf(stderr, fmt, ap);
704 * Record pid in /var/run/sm-notify.pid
705 * This file should remain until a reboot, even if the
707 * If file already exists, fail.
709 static int record_pid()
714 snprintf(pid, 20, "%d\n", getpid());
715 fd = open("/var/run/sm-notify.pid", O_CREAT|O_EXCL|O_WRONLY, 0600);
718 write(fd, pid, strlen(pid));
723 /* Drop privileges to match owner of state-directory
724 * (in case a reply triggers some unknown bug).
726 static void drop_privs(void)
730 if (stat(_SM_DIR_PATH, &st) == -1 &&
731 stat(_SM_BASE_PATH, &st) == -1) {
736 if (st.st_uid == 0) {
738 "sm-notify running as root. chown %s to choose different user\n",
744 if (setgid(st.st_gid) == -1
745 || setuid(st.st_uid) == -1) {
746 nsm_log(LOG_ERR, "Fail to drop privileges");