]> git.decadent.org.uk Git - nfs-utils.git/blob - utils/statd/sm-notify.c
libnsm.a: Add support for multiple lines in monitor record files
[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[256];
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) {
416                 strncpy(nsm_hostname, opt_srcaddr, sizeof(nsm_hostname)-1);
417         } else
418         if (gethostname(nsm_hostname, sizeof(nsm_hostname)) < 0) {
419                 xlog(L_ERROR, "Failed to obtain name of local host: %m");
420                 exit(1);
421         }
422
423         (void)nsm_retire_monitored_hosts();
424         if (nsm_load_notify_list(smn_get_host) == 0) {
425                 xlog(D_GENERAL, "No hosts to notify; exiting");
426                 return 0;
427         }
428
429         nsm_state = nsm_get_state(opt_update_state);
430         if (nsm_state == 0)
431                 exit(1);
432         nsm_update_kernel_state(nsm_state);
433
434         if (!opt_debug) {
435                 xlog(L_NOTICE, "Backgrounding to notify hosts...\n");
436
437                 if (daemon(0, 0) < 0) {
438                         xlog(L_ERROR, "unable to background: %m");
439                         exit(1);
440                 }
441
442                 close(0);
443                 close(1);
444                 close(2);
445         }
446
447         sock = smn_create_socket(opt_srcaddr, opt_srcport);
448         if (sock == -1)
449                 exit(1);
450
451         if (!nsm_drop_privileges(-1))
452                 exit(1);
453
454         notify(sock);
455
456         if (hosts) {
457                 struct nsm_host *hp;
458
459                 while ((hp = hosts) != 0) {
460                         hosts = hp->next;
461                         xlog(L_NOTICE, "Unable to notify %s, giving up",
462                                 hp->name);
463                 }
464                 exit(1);
465         }
466
467         exit(0);
468 }
469
470 /*
471  * Notify hosts
472  */
473 static void
474 notify(const int sock)
475 {
476         time_t  failtime = 0;
477
478         if (opt_max_retry)
479                 failtime = time(NULL) + opt_max_retry;
480
481         while (hosts) {
482                 struct pollfd   pfd;
483                 time_t          now = time(NULL);
484                 unsigned int    sent = 0;
485                 struct nsm_host *hp;
486                 long            wait;
487
488                 if (failtime && now >= failtime)
489                         break;
490
491                 while (hosts && ((wait = hosts->send_next - now) <= 0)) {
492                         /* Never send more than 10 packets at once */
493                         if (sent++ >= 10)
494                                 break;
495
496                         /* Remove queue head */
497                         hp = hosts;
498                         hosts = hp->next;
499
500                         if (notify_host(sock, hp))
501                                 continue;
502
503                         /* Set the timeout for this call, using an
504                            exponential timeout strategy */
505                         wait = hp->timeout;
506                         if ((hp->timeout <<= 1) > NSM_MAX_TIMEOUT)
507                                 hp->timeout = NSM_MAX_TIMEOUT;
508                         hp->send_next = now + wait;
509                         hp->retries++;
510
511                         insert_host(hp);
512                 }
513                 if (hosts == NULL)
514                         return;
515
516                 xlog(D_GENERAL, "Host %s due in %ld seconds",
517                                 hosts->name, wait);
518
519                 pfd.fd = sock;
520                 pfd.events = POLLIN;
521
522                 wait *= 1000;
523                 if (wait < 100)
524                         wait = 100;
525                 if (poll(&pfd, 1, wait) != 1)
526                         continue;
527
528                 recv_reply(sock);
529         }
530 }
531
532 /*
533  * Send notification to a single host
534  */
535 static int
536 notify_host(int sock, struct nsm_host *host)
537 {
538         struct sockaddr *sap;
539         socklen_t salen;
540
541         if (host->ai == NULL) {
542                 host->ai = smn_lookup(host->name);
543                 if (host->ai == NULL) {
544                         xlog_warn("DNS resolution of %s failed; "
545                                 "retrying later", host->name);
546                         return 0;
547                 }
548         }
549
550         /* If we retransmitted 4 times, reset the port to force
551          * a new portmap lookup (in case statd was restarted).
552          * We also rotate through multiple IP addresses at this
553          * point.
554          */
555         if (host->retries >= 4) {
556                 /* don't rotate if there is only one addrinfo */
557                 if (host->ai->ai_next != NULL) {
558                         struct addrinfo *first = host->ai;
559                         struct addrinfo **next = &host->ai;
560
561                         /* remove the first entry from the list */
562                         host->ai = first->ai_next;
563                         first->ai_next = NULL;
564                         /* find the end of the list */
565                         next = &first->ai_next;
566                         while ( *next )
567                                 next = & (*next)->ai_next;
568                         /* put first entry at end */
569                         *next = first;
570                 }
571
572                 nfs_set_port(host->ai->ai_addr, 0);
573                 host->retries = 0;
574         }
575
576         sap = host->ai->ai_addr;
577         salen = host->ai->ai_addrlen;
578
579         if (nfs_get_port(sap) == 0)
580                 host->xid = nsm_xmit_rpcbind(sock, sap, SM_PROG, SM_VERS);
581         else
582                 host->xid = nsm_xmit_notify(sock, sap, salen,
583                                 SM_PROG, nsm_hostname, nsm_state);
584         
585         return 0;
586 }
587
588 /*
589  * Extract the returned port number and set up the SM_NOTIFY call.
590  */
591 static void
592 recv_rpcbind_reply(struct sockaddr *sap, struct nsm_host *host, XDR *xdr)
593 {
594         uint16_t port = nsm_recv_rpcbind(sap->sa_family, xdr);
595
596         host->send_next = time(NULL);
597         host->xid = 0;
598
599         if (port == 0) {
600                 /* No binding for statd... */
601                 xlog(D_GENERAL, "No statd on host %s", host->name);
602                 host->timeout = NSM_MAX_TIMEOUT;
603                 host->send_next += NSM_MAX_TIMEOUT;
604         } else {
605                 nfs_set_port(sap, port);
606                 if (host->timeout >= NSM_MAX_TIMEOUT / 4)
607                         host->timeout = NSM_MAX_TIMEOUT / 4;
608         }
609
610         insert_host(host);
611 }
612
613 /*
614  * Successful NOTIFY call. Server returns void, so nothing
615  * we need to do here.
616  */
617 static void
618 recv_notify_reply(struct nsm_host *host)
619 {
620         xlog(D_GENERAL, "Host %s notified successfully", host->name);
621
622         smn_forget_host(host);
623 }
624
625 /*
626  * Receive reply from remote host
627  */
628 static void
629 recv_reply(int sock)
630 {
631         struct nsm_host *hp;
632         struct sockaddr *sap;
633         char msgbuf[NSM_MAXMSGSIZE];
634         uint32_t        xid;
635         ssize_t         msglen;
636         XDR             xdr;
637
638         memset(msgbuf, 0 , sizeof(msgbuf));
639         msglen = recv(sock, msgbuf, sizeof(msgbuf), 0);
640         if (msglen < 0)
641                 return;
642
643         xlog(D_GENERAL, "Received packet...");
644
645         memset(&xdr, 0, sizeof(xdr));
646         xdrmem_create(&xdr, msgbuf, (unsigned int)msglen, XDR_DECODE);
647         xid = nsm_parse_reply(&xdr);
648         if (xid == 0)
649                 goto out;
650
651         /* Before we look at the data, find the host struct for
652            this reply */
653         if ((hp = find_host(xid)) == NULL)
654                 goto out;
655
656         sap = hp->ai->ai_addr;
657         if (nfs_get_port(sap) == 0)
658                 recv_rpcbind_reply(sap, hp, &xdr);
659         else
660                 recv_notify_reply(hp);
661
662 out:
663         xdr_destroy(&xdr);
664 }
665
666 /*
667  * Insert host into sorted list
668  */
669 static void
670 insert_host(struct nsm_host *host)
671 {
672         struct nsm_host **where, *p;
673
674         where = &hosts;
675         while ((p = *where) != 0) {
676                 /* Sort in ascending order of timeout */
677                 if (host->send_next < p->send_next)
678                         break;
679                 /* If we have the same timeout, put the
680                  * most recently used host first.
681                  * This makes sure that "recent" hosts
682                  * get notified first.
683                  */
684                 if (host->send_next == p->send_next
685                  && host->last_used > p->last_used)
686                         break;
687                 where = &p->next;
688         }
689
690         host->next = *where;
691         *where = host;
692 }
693
694 /*
695  * Find host given the XID
696  */
697 static struct nsm_host *
698 find_host(uint32_t xid)
699 {
700         struct nsm_host **where, *p;
701
702         where = &hosts;
703         while ((p = *where) != 0) {
704                 if (p->xid == xid) {
705                         *where = p->next;
706                         return p;
707                 }
708                 where = &p->next;
709         }
710         return NULL;
711 }
712
713 /*
714  * Record pid in /var/run/sm-notify.pid
715  * This file should remain until a reboot, even if the
716  * program exits.
717  * If file already exists, fail.
718  */
719 static int record_pid(void)
720 {
721         char pid[20];
722         ssize_t len;
723         int fd;
724
725         (void)snprintf(pid, sizeof(pid), "%d\n", (int)getpid());
726         fd = open("/var/run/sm-notify.pid", O_CREAT|O_EXCL|O_WRONLY, 0600);
727         if (fd < 0)
728                 return 0;
729
730         len = write(fd, pid, strlen(pid));
731         if ((len < 0) || ((size_t)len != strlen(pid))) {
732                 xlog_warn("Writing to pid file failed: errno %d (%m)",
733                                 errno);
734         }
735
736         (void)close(fd);
737         return 1;
738 }