]> git.decadent.org.uk Git - nfs-utils.git/blob - utils/statd/sm-notify.c
sm-notify: Use my_name when sending SM_NOTIFY requests
[nfs-utils.git] / utils / statd / sm-notify.c
1 /*
2  * Send NSM notify calls to all hosts listed in /var/lib/sm
3  *
4  * Copyright (C) 2004-2006 Olaf Kirch <okir@suse.de>
5  */
6
7 #ifdef HAVE_CONFIG_H
8 #include <config.h>
9 #endif
10
11 #include <err.h>
12 #include <sys/types.h>
13 #include <sys/socket.h>
14 #include <sys/stat.h>
15 #include <sys/poll.h>
16 #include <sys/param.h>
17 #include <sys/syslog.h>
18 #include <arpa/inet.h>
19 #include <dirent.h>
20 #include <time.h>
21 #include <stdio.h>
22 #include <getopt.h>
23 #include <stdlib.h>
24 #include <fcntl.h>
25 #include <unistd.h>
26 #include <string.h>
27 #include <stdarg.h>
28 #include <netdb.h>
29 #include <errno.h>
30 #include <grp.h>
31
32 #include "sockaddr.h"
33 #include "xlog.h"
34 #include "nsm.h"
35 #include "nfsrpc.h"
36
37 #ifndef HAVE_DECL_AI_ADDRCONFIG
38 #define AI_ADDRCONFIG   0
39 #endif
40
41 #define NSM_TIMEOUT     2
42 #define NSM_MAX_TIMEOUT 120     /* don't make this too big */
43
44 struct nsm_host {
45         struct nsm_host *       next;
46         char *                  name;
47         char *                  mon_name;
48         char *                  my_name;
49         struct addrinfo         *ai;
50         time_t                  last_used;
51         time_t                  send_next;
52         unsigned int            timeout;
53         unsigned int            retries;
54         uint32_t                xid;
55 };
56
57 static char             nsm_hostname[SM_MAXSTRLEN + 1];
58 static int              nsm_state;
59 static int              nsm_family = AF_INET;
60 static int              opt_debug = 0;
61 static _Bool            opt_update_state = true;
62 static unsigned int     opt_max_retry = 15 * 60;
63 static char *           opt_srcaddr = NULL;
64 static char *           opt_srcport = NULL;
65
66 static void             notify(const int sock);
67 static int              notify_host(int, struct nsm_host *);
68 static void             recv_reply(int);
69 static void             insert_host(struct nsm_host *);
70 static struct nsm_host *find_host(uint32_t);
71 static int              record_pid(void);
72
73 static struct nsm_host *        hosts = NULL;
74
75 __attribute_malloc__
76 static struct addrinfo *
77 smn_lookup(const char *name)
78 {
79         struct addrinfo *ai = NULL;
80         struct addrinfo hint = {
81                 .ai_flags       = AI_ADDRCONFIG,
82                 .ai_family      = (nsm_family == AF_INET ? AF_INET: AF_UNSPEC),
83                 .ai_protocol    = (int)IPPROTO_UDP,
84         };
85         int error;
86
87         error = getaddrinfo(name, NULL, &hint, &ai);
88         if (error != 0) {
89                 xlog(D_GENERAL, "getaddrinfo(3): %s", gai_strerror(error));
90                 return NULL;
91         }
92
93         return ai;
94 }
95
96 __attribute_malloc__
97 static struct nsm_host *
98 smn_alloc_host(const char *hostname, const char *mon_name,
99                 const char *my_name, const time_t timestamp)
100 {
101         struct nsm_host *host;
102
103         host = calloc(1, sizeof(*host));
104         if (host == NULL)
105                 goto out_nomem;
106
107         host->name = strdup(hostname);
108         host->mon_name = strdup(mon_name);
109         host->my_name = strdup(my_name);
110         if (host->name == NULL ||
111             host->mon_name == NULL ||
112             host->my_name == NULL) {
113                 free(host->my_name);
114                 free(host->mon_name);
115                 free(host->name);
116                 free(host);
117                 goto out_nomem;
118         }
119
120         host->last_used = timestamp;
121         host->timeout = NSM_TIMEOUT;
122         host->retries = 100;            /* force address retry */
123
124         return host;
125
126 out_nomem:
127         xlog_warn("Unable to allocate memory");
128         return NULL;
129 }
130
131 static void smn_forget_host(struct nsm_host *host)
132 {
133         xlog(D_CALL, "Removing %s (%s, %s) from notify list",
134                         host->name, host->mon_name, host->my_name);
135
136         nsm_delete_notified_host(host->name, host->mon_name, host->my_name);
137
138         free(host->my_name);
139         free(host->mon_name);
140         free(host->name);
141         if (host->ai)
142                 freeaddrinfo(host->ai);
143
144         free(host);
145 }
146
147 static unsigned int
148 smn_get_host(const char *hostname,
149                 __attribute__ ((unused)) const struct sockaddr *sap,
150                 const struct mon *m, const time_t timestamp)
151 {
152         struct nsm_host *host;
153
154         host = smn_alloc_host(hostname,
155                 m->mon_id.mon_name, m->mon_id.my_id.my_name, timestamp);
156         if (host == NULL)
157                 return 0;
158
159         insert_host(host);
160         xlog(D_GENERAL, "Added host %s to notify list", hostname);
161         return 1;
162 }
163
164 #ifdef IPV6_SUPPORTED
165 static int smn_socket(void)
166 {
167         int sock;
168
169         /*
170          * Use an AF_INET socket if IPv6 is disabled on the
171          * local system.
172          */
173         sock = socket(AF_INET6, SOCK_DGRAM, 0);
174         if (sock == -1) {
175                 if (errno != EAFNOSUPPORT) {
176                         xlog(L_ERROR, "Failed to create RPC socket: %m");
177                         return -1;
178                 }
179                 sock = socket(AF_INET, SOCK_DGRAM, 0);
180                 if (sock < 0) {
181                         xlog(L_ERROR, "Failed to create RPC socket: %m");
182                         return -1;
183                 }
184         } else
185                 nsm_family = AF_INET6;
186
187         if (fcntl(sock, F_SETFL, O_NONBLOCK) == -1) {
188                 xlog(L_ERROR, "fcntl(3) on RPC socket failed: %m");
189                 goto out_close;
190         }
191
192         /*
193          * TI-RPC over IPv6 (udp6/tcp6) does not handle IPv4.  However,
194          * since sm-notify open-codes all of its RPC support, it can
195          * use a single socket and let the local network stack provide
196          * the correct mapping between address families automatically.
197          * This is the same thing that is done in the kernel.
198          */
199         if (nsm_family == AF_INET6) {
200                 const int zero = 0;
201                 socklen_t zerolen = (socklen_t)sizeof(zero);
202
203                 if (setsockopt(sock, SOL_IPV6, IPV6_V6ONLY,
204                                         (char *)&zero, zerolen) == -1) {
205                         xlog(L_ERROR, "setsockopt(3) on RPC socket failed: %m");
206                         goto out_close;
207                 }
208         }
209
210         return sock;
211
212 out_close:
213         (void)close(sock);
214         return -1;
215 }
216 #else   /* !IPV6_SUPPORTED */
217 static int smn_socket(void)
218 {
219         int sock;
220
221         sock = socket(AF_INET, SOCK_DGRAM, 0);
222         if (sock == -1) {
223                 xlog(L_ERROR, "Failed to create RPC socket: %m");
224                 return -1;
225         }
226
227         if (fcntl(sock, F_SETFL, O_NONBLOCK) == -1) {
228                 xlog(L_ERROR, "fcntl(3) on RPC socket failed: %m");
229                 (void)close(sock);
230                 return -1;
231         }
232
233         return sock;
234 }
235 #endif  /* !IPV6_SUPPORTED */
236
237 /*
238  * If admin specified a source address or srcport, then convert those
239  * to a sockaddr and return it.   Otherwise, return an ANYADDR address.
240  */
241 __attribute_malloc__
242 static struct addrinfo *
243 smn_bind_address(const char *srcaddr, const char *srcport)
244 {
245         struct addrinfo *ai = NULL;
246         struct addrinfo hint = {
247                 .ai_flags       = AI_NUMERICSERV,
248                 .ai_family      = nsm_family,
249                 .ai_protocol    = (int)IPPROTO_UDP,
250         };
251         int error;
252
253         if (srcaddr == NULL)
254                 hint.ai_flags |= AI_PASSIVE;
255
256         if (srcport == NULL)
257                 error = getaddrinfo(srcaddr, "", &hint, &ai);
258         else
259                 error = getaddrinfo(srcaddr, srcport, &hint, &ai);
260         if (error != 0) {
261                 xlog(L_ERROR,
262                         "Invalid bind address or port for RPC socket: %s",
263                                 gai_strerror(error));
264                 return NULL;
265         }
266
267         return ai;
268 }
269
270 #ifdef HAVE_LIBTIRPC
271 static int
272 smn_bindresvport(int sock, struct sockaddr *sap)
273 {
274         return bindresvport_sa(sock, sap);
275 }
276
277 #else   /* !HAVE_LIBTIRPC */
278 static int
279 smn_bindresvport(int sock, struct sockaddr *sap)
280 {
281         if (sap->sa_family != AF_INET) {
282                 errno = EAFNOSUPPORT;
283                 return -1;
284         }
285
286         return bindresvport(sock, (struct sockaddr_in *)(char *)sap);
287 }
288 #endif  /* !HAVE_LIBTIRPC */
289
290 /*
291  * Prepare a socket for sending RPC requests
292  *
293  * Returns a bound datagram socket file descriptor, or -1 if
294  * an error occurs.
295  */
296 static int
297 smn_create_socket(const char *srcaddr, const char *srcport)
298 {
299         int sock, retry_cnt = 0;
300         struct addrinfo *ai;
301
302 retry:
303         sock = smn_socket();
304         if (sock == -1)
305                 return -1;
306
307         ai = smn_bind_address(srcaddr, srcport);
308         if (ai == NULL) {
309                 (void)close(sock);
310                 return -1;
311         }
312
313         /* Use source port if provided on the command line,
314          * otherwise use bindresvport */
315         if (srcport) {
316                 if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
317                         xlog(L_ERROR, "Failed to bind RPC socket: %m");
318                         freeaddrinfo(ai);
319                         (void)close(sock);
320                         return -1;
321                 }
322         } else {
323                 struct servent *se;
324
325                 if (smn_bindresvport(sock, ai->ai_addr) == -1) {
326                         xlog(L_ERROR,
327                                 "bindresvport on RPC socket failed: %m");
328                         freeaddrinfo(ai);
329                         (void)close(sock);
330                         return -1;
331                 }
332
333                 /* try to avoid known ports */
334                 se = getservbyport((int)nfs_get_port(ai->ai_addr), "udp");
335                 if (se != NULL && retry_cnt < 100) {
336                         retry_cnt++;
337                         freeaddrinfo(ai);
338                         (void)close(sock);
339                         goto retry;
340                 }
341         }
342
343         freeaddrinfo(ai);
344         return sock;
345 }
346
347 int
348 main(int argc, char **argv)
349 {
350         int     c, sock, force = 0;
351         char *  progname;
352
353         progname = strrchr(argv[0], '/');
354         if (progname != NULL)
355                 progname++;
356         else
357                 progname = argv[0];
358
359         while ((c = getopt(argc, argv, "dm:np:v:P:f")) != -1) {
360                 switch (c) {
361                 case 'f':
362                         force = 1;
363                         break;
364                 case 'd':
365                         opt_debug++;
366                         break;
367                 case 'm':
368                         opt_max_retry = atoi(optarg) * 60;
369                         break;
370                 case 'n':
371                         opt_update_state = false;
372                         break;
373                 case 'p':
374                         opt_srcport = optarg;
375                         break;
376                 case 'v':
377                         opt_srcaddr = optarg;
378                         break;
379                 case 'P':
380                         if (!nsm_setup_pathnames(argv[0], optarg))
381                                 exit(1);
382                         break;
383
384                 default:
385                         goto usage;
386                 }
387         }
388
389         if (optind < argc) {
390 usage:          fprintf(stderr,
391                         "Usage: %s -notify [-dfq] [-m max-retry-minutes] [-p srcport]\n"
392                         "            [-P /path/to/state/directory] [-v my_host_name]\n",
393                         progname);
394                 exit(1);
395         }
396
397         xlog_syslog(1);
398         if (opt_debug) {
399                 xlog_stderr(1);
400                 xlog_config(D_ALL, 1);
401         } else
402                 xlog_stderr(0);
403
404         xlog_open(progname);
405         xlog(L_NOTICE, "Version " VERSION " starting");
406
407         if (nsm_is_default_parentdir()) {
408                 if (record_pid() == 0 && force == 0 && opt_update_state) {
409                         /* already run, don't try again */
410                         xlog(L_NOTICE, "Already notifying clients; Exiting!");
411                         exit(0);
412                 }
413         }
414
415         if (opt_srcaddr != NULL) {
416                 struct addrinfo *ai = NULL;
417                 struct addrinfo hint = {
418                         .ai_family      = AF_UNSPEC,
419                         .ai_flags       = AI_NUMERICHOST,
420                 };
421
422                 if (getaddrinfo(opt_srcaddr, NULL, &hint, &ai))
423                         /* not a presentation address - use it */
424                         strncpy(nsm_hostname, opt_srcaddr, sizeof(nsm_hostname));
425                 else {
426                         /* was a presentation address - look it up in
427                          * /etc/hosts, so it can be used for my_name */
428                         int error;
429
430                         freeaddrinfo(ai);
431                         hint.ai_flags = AI_CANONNAME;
432                         error = getaddrinfo(opt_srcaddr, NULL, &hint, &ai);
433                         if (error != 0) {
434                                 xlog(L_ERROR, "Bind address %s is unusable: %s",
435                                                 opt_srcaddr, gai_strerror(error));
436                                 exit(1);
437                         }
438                         strncpy(nsm_hostname, ai->ai_canonname,
439                                                         sizeof(nsm_hostname));
440                         freeaddrinfo(ai);
441                 }
442         }
443
444         (void)nsm_retire_monitored_hosts();
445         if (nsm_load_notify_list(smn_get_host) == 0) {
446                 xlog(D_GENERAL, "No hosts to notify; exiting");
447                 return 0;
448         }
449
450         nsm_state = nsm_get_state(opt_update_state);
451         if (nsm_state == 0)
452                 exit(1);
453         nsm_update_kernel_state(nsm_state);
454
455         if (!opt_debug) {
456                 xlog(L_NOTICE, "Backgrounding to notify hosts...\n");
457
458                 if (daemon(0, 0) < 0) {
459                         xlog(L_ERROR, "unable to background: %m");
460                         exit(1);
461                 }
462
463                 close(0);
464                 close(1);
465                 close(2);
466         }
467
468         sock = smn_create_socket(opt_srcaddr, opt_srcport);
469         if (sock == -1)
470                 exit(1);
471
472         if (!nsm_drop_privileges(-1))
473                 exit(1);
474
475         notify(sock);
476
477         if (hosts) {
478                 struct nsm_host *hp;
479
480                 while ((hp = hosts) != 0) {
481                         hosts = hp->next;
482                         xlog(L_NOTICE, "Unable to notify %s, giving up",
483                                 hp->name);
484                 }
485                 exit(1);
486         }
487
488         exit(0);
489 }
490
491 /*
492  * Notify hosts
493  */
494 static void
495 notify(const int sock)
496 {
497         time_t  failtime = 0;
498
499         if (opt_max_retry)
500                 failtime = time(NULL) + opt_max_retry;
501
502         while (hosts) {
503                 struct pollfd   pfd;
504                 time_t          now = time(NULL);
505                 unsigned int    sent = 0;
506                 struct nsm_host *hp;
507                 long            wait;
508
509                 if (failtime && now >= failtime)
510                         break;
511
512                 while (hosts && ((wait = hosts->send_next - now) <= 0)) {
513                         /* Never send more than 10 packets at once */
514                         if (sent++ >= 10)
515                                 break;
516
517                         /* Remove queue head */
518                         hp = hosts;
519                         hosts = hp->next;
520
521                         if (notify_host(sock, hp))
522                                 continue;
523
524                         /* Set the timeout for this call, using an
525                            exponential timeout strategy */
526                         wait = hp->timeout;
527                         if ((hp->timeout <<= 1) > NSM_MAX_TIMEOUT)
528                                 hp->timeout = NSM_MAX_TIMEOUT;
529                         hp->send_next = now + wait;
530                         hp->retries++;
531
532                         insert_host(hp);
533                 }
534                 if (hosts == NULL)
535                         return;
536
537                 xlog(D_GENERAL, "Host %s due in %ld seconds",
538                                 hosts->name, wait);
539
540                 pfd.fd = sock;
541                 pfd.events = POLLIN;
542
543                 wait *= 1000;
544                 if (wait < 100)
545                         wait = 100;
546                 if (poll(&pfd, 1, wait) != 1)
547                         continue;
548
549                 recv_reply(sock);
550         }
551 }
552
553 /*
554  * Send notification to a single host
555  */
556 static int
557 notify_host(int sock, struct nsm_host *host)
558 {
559         const char *my_name = (opt_srcaddr != NULL ?
560                                         nsm_hostname : host->my_name);
561         struct sockaddr *sap;
562         socklen_t salen;
563
564         if (host->ai == NULL) {
565                 host->ai = smn_lookup(host->name);
566                 if (host->ai == NULL) {
567                         xlog_warn("DNS resolution of %s failed; "
568                                 "retrying later", host->name);
569                         return 0;
570                 }
571         }
572
573         /* If we retransmitted 4 times, reset the port to force
574          * a new portmap lookup (in case statd was restarted).
575          * We also rotate through multiple IP addresses at this
576          * point.
577          */
578         if (host->retries >= 4) {
579                 /* don't rotate if there is only one addrinfo */
580                 if (host->ai->ai_next != NULL) {
581                         struct addrinfo *first = host->ai;
582                         struct addrinfo **next = &host->ai;
583
584                         /* remove the first entry from the list */
585                         host->ai = first->ai_next;
586                         first->ai_next = NULL;
587                         /* find the end of the list */
588                         next = &first->ai_next;
589                         while ( *next )
590                                 next = & (*next)->ai_next;
591                         /* put first entry at end */
592                         *next = first;
593                 }
594
595                 nfs_set_port(host->ai->ai_addr, 0);
596                 host->retries = 0;
597         }
598
599         sap = host->ai->ai_addr;
600         salen = host->ai->ai_addrlen;
601
602         if (nfs_get_port(sap) == 0)
603                 host->xid = nsm_xmit_rpcbind(sock, sap, SM_PROG, SM_VERS);
604         else
605                 host->xid = nsm_xmit_notify(sock, sap, salen,
606                                         SM_PROG, my_name, nsm_state);
607
608         return 0;
609 }
610
611 /*
612  * Extract the returned port number and set up the SM_NOTIFY call.
613  */
614 static void
615 recv_rpcbind_reply(struct sockaddr *sap, struct nsm_host *host, XDR *xdr)
616 {
617         uint16_t port = nsm_recv_rpcbind(sap->sa_family, xdr);
618
619         host->send_next = time(NULL);
620         host->xid = 0;
621
622         if (port == 0) {
623                 /* No binding for statd... */
624                 xlog(D_GENERAL, "No statd on host %s", host->name);
625                 host->timeout = NSM_MAX_TIMEOUT;
626                 host->send_next += NSM_MAX_TIMEOUT;
627         } else {
628                 nfs_set_port(sap, port);
629                 if (host->timeout >= NSM_MAX_TIMEOUT / 4)
630                         host->timeout = NSM_MAX_TIMEOUT / 4;
631         }
632
633         insert_host(host);
634 }
635
636 /*
637  * Successful NOTIFY call. Server returns void, so nothing
638  * we need to do here.
639  */
640 static void
641 recv_notify_reply(struct nsm_host *host)
642 {
643         xlog(D_GENERAL, "Host %s notified successfully", host->name);
644
645         smn_forget_host(host);
646 }
647
648 /*
649  * Receive reply from remote host
650  */
651 static void
652 recv_reply(int sock)
653 {
654         struct nsm_host *hp;
655         struct sockaddr *sap;
656         char msgbuf[NSM_MAXMSGSIZE];
657         uint32_t        xid;
658         ssize_t         msglen;
659         XDR             xdr;
660
661         memset(msgbuf, 0 , sizeof(msgbuf));
662         msglen = recv(sock, msgbuf, sizeof(msgbuf), 0);
663         if (msglen < 0)
664                 return;
665
666         xlog(D_GENERAL, "Received packet...");
667
668         memset(&xdr, 0, sizeof(xdr));
669         xdrmem_create(&xdr, msgbuf, (unsigned int)msglen, XDR_DECODE);
670         xid = nsm_parse_reply(&xdr);
671         if (xid == 0)
672                 goto out;
673
674         /* Before we look at the data, find the host struct for
675            this reply */
676         if ((hp = find_host(xid)) == NULL)
677                 goto out;
678
679         sap = hp->ai->ai_addr;
680         if (nfs_get_port(sap) == 0)
681                 recv_rpcbind_reply(sap, hp, &xdr);
682         else
683                 recv_notify_reply(hp);
684
685 out:
686         xdr_destroy(&xdr);
687 }
688
689 /*
690  * Insert host into sorted list
691  */
692 static void
693 insert_host(struct nsm_host *host)
694 {
695         struct nsm_host **where, *p;
696
697         where = &hosts;
698         while ((p = *where) != 0) {
699                 /* Sort in ascending order of timeout */
700                 if (host->send_next < p->send_next)
701                         break;
702                 /* If we have the same timeout, put the
703                  * most recently used host first.
704                  * This makes sure that "recent" hosts
705                  * get notified first.
706                  */
707                 if (host->send_next == p->send_next
708                  && host->last_used > p->last_used)
709                         break;
710                 where = &p->next;
711         }
712
713         host->next = *where;
714         *where = host;
715 }
716
717 /*
718  * Find host given the XID
719  */
720 static struct nsm_host *
721 find_host(uint32_t xid)
722 {
723         struct nsm_host **where, *p;
724
725         where = &hosts;
726         while ((p = *where) != 0) {
727                 if (p->xid == xid) {
728                         *where = p->next;
729                         return p;
730                 }
731                 where = &p->next;
732         }
733         return NULL;
734 }
735
736 /*
737  * Record pid in /var/run/sm-notify.pid
738  * This file should remain until a reboot, even if the
739  * program exits.
740  * If file already exists, fail.
741  */
742 static int record_pid(void)
743 {
744         char pid[20];
745         ssize_t len;
746         int fd;
747
748         (void)snprintf(pid, sizeof(pid), "%d\n", (int)getpid());
749         fd = open("/var/run/sm-notify.pid", O_CREAT|O_EXCL|O_WRONLY, 0600);
750         if (fd < 0)
751                 return 0;
752
753         len = write(fd, pid, strlen(pid));
754         if ((len < 0) || ((size_t)len != strlen(pid))) {
755                 xlog_warn("Writing to pid file failed: errno %d (%m)",
756                                 errno);
757         }
758
759         (void)close(fd);
760         return 1;
761 }