]> git.decadent.org.uk Git - nfs-utils.git/blob - utils/mount/network.c
223121092bedbbd7e16b8cafacaa88b63355c3b1
[nfs-utils.git] / utils / mount / network.c
1 /*
2  * network.c -- Provide common network functions for NFS mount/umount
3  *
4  * Copyright (C) 2007 Oracle.  All rights reserved.
5  * Copyright (C) 2007 Chuck Lever <chuck.lever@oracle.com>
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public
18  * License along with this program; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 021110-1307, USA.
21  *
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27
28 #include <ctype.h>
29 #include <unistd.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <stdlib.h>
33 #include <errno.h>
34 #include <netdb.h>
35 #include <time.h>
36
37 #include <sys/types.h>
38 #include <sys/socket.h>
39 #include <sys/wait.h>
40 #include <netinet/in.h>
41 #include <rpc/rpc.h>
42 #include <rpc/pmap_prot.h>
43 #include <rpc/pmap_clnt.h>
44
45 #include "xcommon.h"
46 #include "mount.h"
47 #include "nls.h"
48 #include "nfs_mount.h"
49 #include "mount_constants.h"
50 #include "nfsrpc.h"
51 #include "network.h"
52
53 /*
54  * Earlier versions of glibc's /usr/include/netdb.h exclude these
55  * definitions because it was thought they were not part of a stable
56  * POSIX standard.  However, they are defined by RFC 2553 and 3493
57  * and in POSIX 1003.1-2001, so these definitions were added in later
58  * versions of netdb.h.
59  */
60 #ifndef AI_V4MAPPED
61 #define AI_V4MAPPED     0x0008  /* IPv4-mapped addresses are acceptable.  */
62 #endif  /* AI_V4MAPPED */
63 #ifndef AI_ALL
64 #define AI_ALL          0x0010  /* Return both IPv4 and IPv6 addresses.  */
65 #endif  /* AI_ALL */
66 #ifndef AI_ADDRCONFIG
67 #define AI_ADDRCONFIG   0x0020  /* Use configuration of this host to choose \
68                                    returned address type.  */
69 #endif  /* AI_ADDRCONFIG */
70
71 #define PMAP_TIMEOUT    (10)
72 #define CONNECT_TIMEOUT (20)
73 #define MOUNT_TIMEOUT   (30)
74
75 #if SIZEOF_SOCKLEN_T - 0 == 0
76 #define socklen_t unsigned int
77 #endif
78
79 extern int nfs_mount_data_version;
80 extern char *progname;
81 extern int verbose;
82
83 static const char *nfs_ns_pgmtbl[] = {
84         "status",
85         NULL,
86 };
87
88 static const unsigned long nfs_to_mnt[] = {
89         0,
90         0,
91         1,
92         3,
93 };
94
95 static const unsigned long mnt_to_nfs[] = {
96         0,
97         2,
98         2,
99         3,
100 };
101
102 /*
103  * Map an NFS version into the corresponding Mountd version
104  */
105 unsigned long nfsvers_to_mnt(const unsigned long vers)
106 {
107         if (vers <= 3)
108                 return nfs_to_mnt[vers];
109         return 0;
110 }
111
112 /*
113  * Map a Mountd version into the corresponding NFS version
114  */
115 static unsigned long mntvers_to_nfs(const unsigned long vers)
116 {
117         if (vers <= 3)
118                 return mnt_to_nfs[vers];
119         return 0;
120 }
121
122 static const unsigned int probe_udp_only[] = {
123         IPPROTO_UDP,
124         0,
125 };
126
127 static const unsigned int probe_udp_first[] = {
128         IPPROTO_UDP,
129         IPPROTO_TCP,
130         0,
131 };
132
133 static const unsigned int probe_tcp_first[] = {
134         IPPROTO_TCP,
135         IPPROTO_UDP,
136         0,
137 };
138
139 static const unsigned long probe_nfs2_only[] = {
140         2,
141         0,
142 };
143
144 static const unsigned long probe_nfs3_first[] = {
145         3,
146         2,
147         0,
148 };
149
150 static const unsigned long probe_mnt1_first[] = {
151         1,
152         2,
153         0,
154 };
155
156 static const unsigned long probe_mnt3_first[] = {
157         3,
158         1,
159         2,
160         0,
161 };
162
163 /**
164  * nfs_name_to_address - resolve hostname to an IPv4 or IPv6 socket address
165  * @hostname: pointer to C string containing DNS hostname to resolve
166  * @sap: pointer to buffer to fill with socket address
167  * @len: IN: size of buffer to fill; OUT: size of socket address
168  *
169  * Returns 1 and places a socket address at @sap if successful;
170  * otherwise zero.
171  */
172 int nfs_name_to_address(const char *hostname,
173                         const sa_family_t af_hint,
174                         struct sockaddr *sap, socklen_t *salen)
175 {
176         struct addrinfo *gai_results;
177         struct addrinfo gai_hint = {
178                 .ai_family      = af_hint,
179                 .ai_flags       = AI_ADDRCONFIG,
180         };
181         socklen_t len = *salen;
182         int error, ret = 0;
183
184         if (af_hint == AF_INET6)
185                 gai_hint.ai_flags |= AI_V4MAPPED|AI_ALL;
186
187         *salen = 0;
188
189         error = getaddrinfo(hostname, NULL, &gai_hint, &gai_results);
190         if (error) {
191                 nfs_error(_("%s: DNS resolution failed for %s: %s"),
192                         progname, hostname, (error == EAI_SYSTEM ?
193                                 strerror(errno) : gai_strerror(error)));
194                 return ret;
195         }
196
197         switch (gai_results->ai_addr->sa_family) {
198         case AF_INET:
199         case AF_INET6:
200                 if (len >= gai_results->ai_addrlen) {
201                         *salen = gai_results->ai_addrlen;
202                         memcpy(sap, gai_results->ai_addr, *salen);
203                         ret = 1;
204                 }
205                 break;
206         default:
207                 /* things are really broken if we get here, so warn */
208                 nfs_error(_("%s: unrecognized DNS resolution results for %s"),
209                                 progname, hostname);
210                 break;
211         }
212
213         freeaddrinfo(gai_results);
214         return ret;
215 }
216
217 /**
218  * nfs_gethostbyname - resolve a hostname to an IPv4 address
219  * @hostname: pointer to a C string containing a DNS hostname
220  * @saddr: returns an IPv4 address 
221  *
222  * Returns 1 if successful, otherwise zero.
223  */
224 int nfs_gethostbyname(const char *hostname, struct sockaddr_in *sin)
225 {
226         socklen_t len = sizeof(*sin);
227
228         return nfs_name_to_address(hostname, AF_INET,
229                                         (struct sockaddr *)sin, &len);
230 }
231
232 /**
233  * nfs_string_to_sockaddr - convert string address to sockaddr
234  * @address:    pointer to presentation format address to convert
235  * @addrlen:    length of presentation address
236  * @sap:        pointer to socket address buffer to fill in
237  * @salen:      IN: length of address buffer
238  *              OUT: length of converted socket address
239  *
240  * Convert a presentation format address string to a socket address.
241  * Similar to nfs_name_to_address(), but the DNS query is squelched,
242  * and won't make any noise if the getaddrinfo() call fails.
243  *
244  * Returns 1 and fills in @sap and @salen if successful; otherwise zero.
245  *
246  * See RFC 4038 section 5.1 or RFC 3513 section 2.2 for more details
247  * on presenting IPv6 addresses as text strings.
248  */
249 int nfs_string_to_sockaddr(const char *address, const size_t addrlen,
250                            struct sockaddr *sap, socklen_t *salen)
251 {
252         struct addrinfo *gai_results;
253         struct addrinfo gai_hint = {
254                 .ai_flags       = AI_NUMERICHOST,
255         };
256         socklen_t len = *salen;
257         int ret = 0;
258
259         *salen = 0;
260
261         if (getaddrinfo(address, NULL, &gai_hint, &gai_results) == 0) {
262                 switch (gai_results->ai_addr->sa_family) {
263                 case AF_INET:
264                 case AF_INET6:
265                         if (len >= gai_results->ai_addrlen) {
266                                 *salen = gai_results->ai_addrlen;
267                                 memcpy(sap, gai_results->ai_addr, *salen);
268                                 ret = 1;
269                         }
270                         break;
271                 }
272                 freeaddrinfo(gai_results);
273         }
274
275         return ret;
276 }
277
278 /**
279  * nfs_present_sockaddr - convert sockaddr to string
280  * @sap: pointer to socket address to convert
281  * @salen: length of socket address
282  * @buf: pointer to buffer to fill in
283  * @buflen: length of buffer
284  *
285  * Convert the passed-in sockaddr-style address to presentation format.
286  * The presentation format address is placed in @buf and is
287  * '\0'-terminated.
288  *
289  * Returns 1 if successful; otherwise zero.
290  *
291  * See RFC 4038 section 5.1 or RFC 3513 section 2.2 for more details
292  * on presenting IPv6 addresses as text strings.
293  */
294 int nfs_present_sockaddr(const struct sockaddr *sap, const socklen_t salen,
295                          char *buf, const size_t buflen)
296 {
297 #ifdef HAVE_GETNAMEINFO
298         int result;
299
300         result = getnameinfo(sap, salen, buf, buflen,
301                                         NULL, 0, NI_NUMERICHOST);
302         if (!result)
303                 return 1;
304
305         nfs_error(_("%s: invalid server address: %s"), progname,
306                         gai_strerror(result));
307         return 0;
308 #else   /* HAVE_GETNAMEINFO */
309         char *addr;
310
311         if (sap->sa_family == AF_INET) {
312                 addr = inet_ntoa(((struct sockaddr_in *)sap)->sin_addr);
313                 if (addr && strlen(addr) < buflen) {
314                         strcpy(buf, addr);
315                         return 1;
316                 }
317         }
318
319         nfs_error(_("%s: invalid server address"), progname);
320         return 0;
321 #endif  /* HAVE_GETNAMEINFO */
322 }
323
324 /*
325  * Attempt to connect a socket, but time out after "timeout" seconds.
326  *
327  * On error return, caller closes the socket.
328  */
329 static int connect_to(int fd, struct sockaddr *addr,
330                         socklen_t addrlen, int timeout)
331 {
332         int ret, saved;
333         fd_set rset, wset;
334         struct timeval tv = {
335                 .tv_sec = timeout,
336         };
337
338         saved = fcntl(fd, F_GETFL, 0);
339         fcntl(fd, F_SETFL, saved | O_NONBLOCK);
340
341         ret = connect(fd, addr, addrlen);
342         if (ret < 0 && errno != EINPROGRESS)
343                 return -1;
344         if (ret == 0)
345                 goto out;
346
347         FD_ZERO(&rset);
348         FD_SET(fd, &rset);
349         wset = rset;
350         ret = select(fd + 1, &rset, &wset, NULL, &tv);
351         if (ret == 0) {
352                 errno = ETIMEDOUT;
353                 return -1;
354         }
355         if (FD_ISSET(fd, &rset) || FD_ISSET(fd, &wset)) {
356                 int error;
357                 socklen_t len = sizeof(error);
358                 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &len) < 0)
359                         return -1;
360                 if (error) {
361                         errno = error;
362                         return -1;
363                 }
364         } else
365                 return -1;
366
367 out:
368         fcntl(fd, F_SETFL, saved);
369         return 0;
370 }
371
372 /*
373  * Create a socket that is locally bound to a reserved or non-reserved port.
374  *
375  * The caller should check rpc_createerr to determine the cause of any error.
376  */
377 static int get_socket(struct sockaddr_in *saddr, unsigned int p_prot,
378                         unsigned int timeout, int resvp, int conn)
379 {
380         int so, cc, type;
381         struct sockaddr_in laddr;
382         socklen_t namelen = sizeof(laddr);
383
384         type = (p_prot == IPPROTO_UDP ? SOCK_DGRAM : SOCK_STREAM);
385         if ((so = socket (AF_INET, type, p_prot)) < 0)
386                 goto err_socket;
387
388         laddr.sin_family = AF_INET;
389         laddr.sin_port = 0;
390         laddr.sin_addr.s_addr = htonl(INADDR_ANY);
391         if (resvp) {
392                 if (bindresvport(so, &laddr) < 0)
393                         goto err_bindresvport;
394         } else {
395                 cc = bind(so, (struct sockaddr *)&laddr, namelen);
396                 if (cc < 0)
397                         goto err_bind;
398         }
399         if (type == SOCK_STREAM || (conn && type == SOCK_DGRAM)) {
400                 cc = connect_to(so, (struct sockaddr *)saddr, namelen,
401                                 timeout);
402                 if (cc < 0)
403                         goto err_connect;
404         }
405         return so;
406
407 err_socket:
408         rpc_createerr.cf_stat = RPC_SYSTEMERROR;
409         rpc_createerr.cf_error.re_errno = errno;
410         if (verbose) {
411                 nfs_error(_("%s: Unable to create %s socket: errno %d (%s)\n"),
412                         progname, p_prot == IPPROTO_UDP ? _("UDP") : _("TCP"),
413                         errno, strerror(errno));
414         }
415         return RPC_ANYSOCK;
416
417 err_bindresvport:
418         rpc_createerr.cf_stat = RPC_SYSTEMERROR;
419         rpc_createerr.cf_error.re_errno = errno;
420         if (verbose) {
421                 nfs_error(_("%s: Unable to bindresvport %s socket: errno %d"
422                                 " (%s)\n"),
423                         progname, p_prot == IPPROTO_UDP ? _("UDP") : _("TCP"),
424                         errno, strerror(errno));
425         }
426         close(so);
427         return RPC_ANYSOCK;
428
429 err_bind:
430         rpc_createerr.cf_stat = RPC_SYSTEMERROR;
431         rpc_createerr.cf_error.re_errno = errno;
432         if (verbose) {
433                 nfs_error(_("%s: Unable to bind to %s socket: errno %d (%s)\n"),
434                         progname, p_prot == IPPROTO_UDP ? _("UDP") : _("TCP"),
435                         errno, strerror(errno));
436         }
437         close(so);
438         return RPC_ANYSOCK;
439
440 err_connect:
441         rpc_createerr.cf_stat = RPC_SYSTEMERROR;
442         rpc_createerr.cf_error.re_errno = errno;
443         if (verbose) {
444                 nfs_error(_("%s: Unable to connect to %s:%d, errno %d (%s)\n"),
445                         progname, inet_ntoa(saddr->sin_addr),
446                         ntohs(saddr->sin_port), errno, strerror(errno));
447         }
448         close(so);
449         return RPC_ANYSOCK;
450 }
451
452 /*
453  * getport() is very similar to pmap_getport() with the exception that
454  * this version tries to use an ephemeral port, since reserved ports are
455  * not needed for GETPORT queries.  This conserves the very limited
456  * reserved port space, which helps reduce failed socket binds
457  * during mount storms.
458  *
459  * A side effect of calling this function is that rpccreateerr is set.
460  */
461 static unsigned short getport(struct sockaddr_in *saddr,
462                                 unsigned long program,
463                                 unsigned long version,
464                                 unsigned int proto)
465 {
466         struct sockaddr_in bind_saddr;
467         unsigned short port = 0;
468         int socket;
469         CLIENT *clnt = NULL;
470         enum clnt_stat stat;
471  
472         bind_saddr = *saddr;
473         bind_saddr.sin_port = htons(PMAPPORT);
474
475         socket = get_socket(&bind_saddr, proto, PMAP_TIMEOUT, FALSE, TRUE);
476         if (socket == RPC_ANYSOCK) {
477                 if (proto == IPPROTO_TCP &&
478                     rpc_createerr.cf_error.re_errno == ETIMEDOUT)
479                         rpc_createerr.cf_stat = RPC_TIMEDOUT;
480                 return 0;
481         }
482
483         switch (proto) {
484         case IPPROTO_UDP:
485                 clnt = clntudp_bufcreate(&bind_saddr,
486                                          PMAPPROG, PMAPVERS,
487                                          RETRY_TIMEOUT, &socket,
488                                          RPCSMALLMSGSIZE,
489                                          RPCSMALLMSGSIZE);
490                 break;
491         case IPPROTO_TCP:
492                 clnt = clnttcp_create(&bind_saddr,
493                                       PMAPPROG, PMAPVERS,
494                                       &socket,
495                                       RPCSMALLMSGSIZE, RPCSMALLMSGSIZE);
496                 break;
497         }
498         if (clnt != NULL) {
499                 struct pmap parms = {
500                         .pm_prog        = program,
501                         .pm_vers        = version,
502                         .pm_prot        = proto,
503                 };
504
505                 stat = clnt_call(clnt, PMAPPROC_GETPORT,
506                                  (xdrproc_t)xdr_pmap, (caddr_t)&parms,
507                                  (xdrproc_t)xdr_u_short, (caddr_t)&port,
508                                  TIMEOUT);
509                 if (stat) {
510                         clnt_geterr(clnt, &rpc_createerr.cf_error);
511                         rpc_createerr.cf_stat = stat;
512                 }
513                 clnt_destroy(clnt);
514                 if (stat != RPC_SUCCESS)
515                         port = 0;
516                 else if (port == 0)
517                         rpc_createerr.cf_stat = RPC_PROGNOTREGISTERED;
518         }
519         close(socket);
520
521         return port;
522 }
523
524 /*
525  * Use the portmapper to discover whether or not the service we want is
526  * available. The lists 'versions' and 'protos' define ordered sequences
527  * of service versions and udp/tcp protocols to probe for.
528  */
529 static int probe_port(clnt_addr_t *server, const unsigned long *versions,
530                         const unsigned int *protos)
531 {
532         struct sockaddr_in *saddr = &server->saddr;
533         struct pmap *pmap = &server->pmap;
534         const unsigned long prog = pmap->pm_prog, *p_vers;
535         const unsigned int prot = (u_int)pmap->pm_prot, *p_prot;
536         const u_short port = (u_short) pmap->pm_port;
537         unsigned long vers = pmap->pm_vers;
538         unsigned short p_port;
539
540         p_prot = prot ? &prot : protos;
541         p_vers = vers ? &vers : versions;
542         rpc_createerr.cf_stat = 0;
543         for (;;) {
544                 p_port = getport(saddr, prog, *p_vers, *p_prot);
545                 if (p_port) {
546                         if (!port || port == p_port) {
547                                 saddr->sin_port = htons(p_port);
548                                 if (verbose) {
549                                         printf(_("%s: trying %s prog %ld vers "
550                                                 "%ld prot %s port %d\n"),
551                                                 progname,
552                                                 inet_ntoa(saddr->sin_addr),
553                                                 prog, *p_vers,
554                                                 *p_prot == IPPROTO_UDP ?
555                                                         _("UDP") : _("TCP"),
556                                                 p_port);
557                                 }
558                                 if (clnt_ping(saddr, prog, *p_vers, *p_prot, NULL))
559                                         goto out_ok;
560                         }
561                 }
562                 if (rpc_createerr.cf_stat != RPC_PROGNOTREGISTERED &&
563                     rpc_createerr.cf_stat != RPC_TIMEDOUT &&
564                     rpc_createerr.cf_stat != RPC_CANTRECV &&
565                     rpc_createerr.cf_stat != RPC_PROGVERSMISMATCH)
566                         goto out_bad;
567
568                 if (!prot) {
569                         if (*++p_prot)
570                                 continue;
571                         p_prot = protos;
572                 }
573                 if (rpc_createerr.cf_stat == RPC_TIMEDOUT ||
574                     rpc_createerr.cf_stat == RPC_CANTRECV)
575                         goto out_bad;
576
577                 if (vers || !*++p_vers)
578                         break;
579         }
580
581 out_bad:
582         return 0;
583
584 out_ok:
585         if (!vers)
586                 pmap->pm_vers = *p_vers;
587         if (!prot)
588                 pmap->pm_prot = *p_prot;
589         if (!port)
590                 pmap->pm_port = p_port;
591         rpc_createerr.cf_stat = 0;
592         return 1;
593 }
594
595 static int probe_nfsport(clnt_addr_t *nfs_server)
596 {
597         struct pmap *pmap = &nfs_server->pmap;
598
599         if (pmap->pm_vers && pmap->pm_prot && pmap->pm_port)
600                 return 1;
601
602         if (nfs_mount_data_version >= 4)
603                 return probe_port(nfs_server, probe_nfs3_first, probe_tcp_first);
604         else
605                 return probe_port(nfs_server, probe_nfs2_only, probe_udp_only);
606 }
607
608 static int probe_mntport(clnt_addr_t *mnt_server)
609 {
610         struct pmap *pmap = &mnt_server->pmap;
611
612         if (pmap->pm_vers && pmap->pm_prot && pmap->pm_port)
613                 return 1;
614
615         if (nfs_mount_data_version >= 4)
616                 return probe_port(mnt_server, probe_mnt3_first, probe_udp_first);
617         else
618                 return probe_port(mnt_server, probe_mnt1_first, probe_udp_only);
619 }
620
621 /**
622  * probe_bothports - discover the RPC endpoints of mountd and NFS server
623  * @mnt_server: pointer to address and pmap argument for mountd results
624  * @nfs_server: pointer to address and pmap argument for NFS server
625  *
626  * Returns 1 if successful, otherwise zero if some error occurred.
627  * Note that the arguments are both input and output arguments.
628  *
629  * A side effect of calling this function is that rpccreateerr is set.
630  */
631 int probe_bothports(clnt_addr_t *mnt_server, clnt_addr_t *nfs_server)
632 {
633         struct pmap *nfs_pmap = &nfs_server->pmap;
634         struct pmap *mnt_pmap = &mnt_server->pmap;
635         struct pmap save_nfs, save_mnt;
636         int res;
637         const unsigned long *probe_vers;
638
639         if (mnt_pmap->pm_vers && !nfs_pmap->pm_vers)
640                 nfs_pmap->pm_vers = mntvers_to_nfs(mnt_pmap->pm_vers);
641         else if (nfs_pmap->pm_vers && !mnt_pmap->pm_vers)
642                 mnt_pmap->pm_vers = nfsvers_to_mnt(nfs_pmap->pm_vers);
643         if (nfs_pmap->pm_vers)
644                 goto version_fixed;
645
646         memcpy(&save_nfs, nfs_pmap, sizeof(save_nfs));
647         memcpy(&save_mnt, mnt_pmap, sizeof(save_mnt));
648         probe_vers = (nfs_mount_data_version >= 4) ?
649                         probe_mnt3_first : probe_mnt1_first;
650
651         for (; *probe_vers; probe_vers++) {
652                 nfs_pmap->pm_vers = mntvers_to_nfs(*probe_vers);
653                 if ((res = probe_nfsport(nfs_server) != 0)) {
654                         mnt_pmap->pm_vers = *probe_vers;
655                         if ((res = probe_mntport(mnt_server)) != 0)
656                                 return 1;
657                         memcpy(mnt_pmap, &save_mnt, sizeof(*mnt_pmap));
658                 }
659                 switch (rpc_createerr.cf_stat) {
660                 case RPC_PROGVERSMISMATCH:
661                 case RPC_PROGNOTREGISTERED:
662                         break;
663                 default:
664                         goto out_bad;
665                 }
666                 memcpy(nfs_pmap, &save_nfs, sizeof(*nfs_pmap));
667         }
668
669 out_bad:
670         return 0;
671
672 version_fixed:
673         if (!probe_nfsport(nfs_server))
674                 goto out_bad;
675         return probe_mntport(mnt_server);
676 }
677
678 static int nfs_probe_statd(void)
679 {
680         struct sockaddr_in addr = {
681                 .sin_family             = AF_INET,
682                 .sin_addr.s_addr        = htonl(INADDR_LOOPBACK),
683         };
684         rpcprog_t program = nfs_getrpcbyname(NSMPROG, nfs_ns_pgmtbl);
685
686         return nfs_getport_ping((struct sockaddr *)&addr, sizeof(addr),
687                                 program, (rpcvers_t)1, IPPROTO_UDP);
688 }
689
690 /**
691  * start_statd - attempt to start rpc.statd
692  *
693  * Returns 1 if statd is running; otherwise zero.
694  */
695 int start_statd(void)
696 {
697 #ifdef START_STATD
698         struct stat stb;
699 #endif
700
701         if (nfs_probe_statd())
702                 return 1;
703
704 #ifdef START_STATD
705         if (stat(START_STATD, &stb) == 0) {
706                 if (S_ISREG(stb.st_mode) && (stb.st_mode & S_IXUSR)) {
707                         pid_t pid = fork();
708                         switch (pid) {
709                         case 0: /* child */
710                                 execl(START_STATD, START_STATD, NULL);
711                                 exit(1);
712                         case -1: /* error */
713                                 nfs_error(_("fork failed: %s"),
714                                                         strerror(errno));
715                                 break;
716                         default: /* parent */
717                                 waitpid(pid, NULL,0);
718                                 break;
719                         }
720                         if (nfs_probe_statd())
721                                 return 1;
722                 }
723         }
724 #endif
725
726         return 0;
727 }
728
729 /**
730  * nfs_call_umount - ask the server to remove a share from it's rmtab
731  * @mnt_server: address of RPC MNT program server
732  * @argp: directory path of share to "unmount"
733  *
734  * Returns one if the unmount call succeeded; zero if the unmount
735  * failed for any reason.
736  *
737  * Note that a side effect of calling this function is that rpccreateerr
738  * is set.
739  */
740 int nfs_call_umount(clnt_addr_t *mnt_server, dirpath *argp)
741 {
742         CLIENT *clnt;
743         enum clnt_stat res = 0;
744         int msock;
745
746         if (!probe_mntport(mnt_server))
747                 return 0;
748         clnt = mnt_openclnt(mnt_server, &msock);
749         if (!clnt)
750                 return 0;
751         res = clnt_call(clnt, MOUNTPROC_UMNT,
752                         (xdrproc_t)xdr_dirpath, (caddr_t)argp,
753                         (xdrproc_t)xdr_void, NULL,
754                         TIMEOUT);
755         mnt_closeclnt(clnt, msock);
756
757         if (res == RPC_SUCCESS)
758                 return 1;
759         return 0;
760 }
761
762 /**
763  * mnt_openclnt - get a handle for a remote mountd service
764  * @mnt_server: address and pmap arguments of mountd service
765  * @msock: returns a file descriptor of the underlying transport socket
766  *
767  * Returns an active handle for the remote's mountd service
768  */
769 CLIENT *mnt_openclnt(clnt_addr_t *mnt_server, int *msock)
770 {
771         struct sockaddr_in *mnt_saddr = &mnt_server->saddr;
772         struct pmap *mnt_pmap = &mnt_server->pmap;
773         CLIENT *clnt = NULL;
774
775         mnt_saddr->sin_port = htons((u_short)mnt_pmap->pm_port);
776         *msock = get_socket(mnt_saddr, mnt_pmap->pm_prot, MOUNT_TIMEOUT,
777                                 TRUE, FALSE);
778         if (*msock == RPC_ANYSOCK) {
779                 if (rpc_createerr.cf_error.re_errno == EADDRINUSE)
780                         /*
781                          * Probably in-use by a TIME_WAIT connection,
782                          * It is worth waiting a while and trying again.
783                          */
784                         rpc_createerr.cf_stat = RPC_TIMEDOUT;
785                 return NULL;
786         }
787
788         switch (mnt_pmap->pm_prot) {
789         case IPPROTO_UDP:
790                 clnt = clntudp_bufcreate(mnt_saddr,
791                                          mnt_pmap->pm_prog, mnt_pmap->pm_vers,
792                                          RETRY_TIMEOUT, msock,
793                                          MNT_SENDBUFSIZE, MNT_RECVBUFSIZE);
794                 break;
795         case IPPROTO_TCP:
796                 clnt = clnttcp_create(mnt_saddr,
797                                       mnt_pmap->pm_prog, mnt_pmap->pm_vers,
798                                       msock,
799                                       MNT_SENDBUFSIZE, MNT_RECVBUFSIZE);
800                 break;
801         }
802         if (clnt) {
803                 /* try to mount hostname:dirname */
804                 clnt->cl_auth = authunix_create_default();
805                 return clnt;
806         }
807         return NULL;
808 }
809
810 /**
811  * mnt_closeclnt - terminate a handle for a remote mountd service
812  * @clnt: pointer to an active handle for a remote mountd service
813  * @msock: file descriptor of the underlying transport socket
814  *
815  */
816 void mnt_closeclnt(CLIENT *clnt, int msock)
817 {
818         auth_destroy(clnt->cl_auth);
819         clnt_destroy(clnt);
820         close(msock);
821 }
822
823 /**
824  * clnt_ping - send an RPC ping to the remote RPC service endpoint
825  * @saddr: server's address
826  * @prog: target RPC program number
827  * @vers: target RPC version number
828  * @prot: target RPC protocol
829  * @caddr: filled in with our network address
830  *
831  * Sigh... getport() doesn't actually check the version number.
832  * In order to make sure that the server actually supports the service
833  * we're requesting, we open and RPC client, and fire off a NULL
834  * RPC call.
835  *
836  * caddr is the network address that the server will use to call us back.
837  * On multi-homed clients, this address depends on which NIC we use to
838  * route requests to the server.
839  *
840  * Returns one if successful, otherwise zero.
841  */
842 int clnt_ping(struct sockaddr_in *saddr, const unsigned long prog,
843                 const unsigned long vers, const unsigned int prot,
844                 struct sockaddr_in *caddr)
845 {
846         CLIENT *clnt = NULL;
847         int sock, stat;
848         static char clnt_res;
849         struct sockaddr dissolve;
850
851         rpc_createerr.cf_stat = stat = 0;
852         sock = get_socket(saddr, prot, CONNECT_TIMEOUT, FALSE, TRUE);
853         if (sock == RPC_ANYSOCK) {
854                 if (rpc_createerr.cf_error.re_errno == ETIMEDOUT) {
855                         /*
856                          * TCP timeout. Bubble up the error to see 
857                          * how it should be handled.
858                          */
859                         rpc_createerr.cf_stat = RPC_TIMEDOUT;
860                 }
861                 return 0;
862         }
863
864         if (caddr) {
865                 /* Get the address of our end of this connection */
866                 socklen_t len = sizeof(*caddr);
867                 if (getsockname(sock, caddr, &len) != 0)
868                         caddr->sin_family = 0;
869         }
870
871         switch(prot) {
872         case IPPROTO_UDP:
873                 /* The socket is connected (so we could getsockname successfully),
874                  * but some servers on multi-homed hosts reply from
875                  * the wrong address, so if we stay connected, we lose the reply.
876                  */
877                 dissolve.sa_family = AF_UNSPEC;
878                 connect(sock, &dissolve, sizeof(dissolve));
879
880                 clnt = clntudp_bufcreate(saddr, prog, vers,
881                                          RETRY_TIMEOUT, &sock,
882                                          RPCSMALLMSGSIZE, RPCSMALLMSGSIZE);
883                 break;
884         case IPPROTO_TCP:
885                 clnt = clnttcp_create(saddr, prog, vers, &sock,
886                                       RPCSMALLMSGSIZE, RPCSMALLMSGSIZE);
887                 break;
888         }
889         if (!clnt) {
890                 close(sock);
891                 return 0;
892         }
893         memset(&clnt_res, 0, sizeof(clnt_res));
894         stat = clnt_call(clnt, NULLPROC,
895                          (xdrproc_t)xdr_void, (caddr_t)NULL,
896                          (xdrproc_t)xdr_void, (caddr_t)&clnt_res,
897                          TIMEOUT);
898         if (stat) {
899                 clnt_geterr(clnt, &rpc_createerr.cf_error);
900                 rpc_createerr.cf_stat = stat;
901         }
902         clnt_destroy(clnt);
903         close(sock);
904
905         if (stat == RPC_SUCCESS)
906                 return 1;
907         else
908                 return 0;
909 }
910
911 /*
912  * Try a getsockname() on a connected datagram socket.
913  *
914  * Returns 1 and fills in @buf if successful; otherwise, zero.
915  *
916  * A connected datagram socket prevents leaving a socket in TIME_WAIT.
917  * This conserves the ephemeral port number space, helping reduce failed
918  * socket binds during mount storms.
919  */
920 static int nfs_ca_sockname(const struct sockaddr *sap, const socklen_t salen,
921                            struct sockaddr *buf, socklen_t *buflen)
922 {
923         struct sockaddr_in sin = {
924                 .sin_family             = AF_INET,
925                 .sin_addr.s_addr        = htonl(INADDR_ANY),
926         };
927         struct sockaddr_in6 sin6 = {
928                 .sin6_family            = AF_INET6,
929                 .sin6_addr              = IN6ADDR_ANY_INIT,
930         };
931         int sock;
932
933         sock = socket(sap->sa_family, SOCK_DGRAM, IPPROTO_UDP);
934         if (sock < 0)
935                 return 0;
936
937         switch (sap->sa_family) {
938         case AF_INET:
939                 if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
940                         close(sock);
941                         return 0;
942                 }
943                 break;
944         case AF_INET6:
945                 if (bind(sock, (struct sockaddr *)&sin6, sizeof(sin6)) < 0) {
946                         close(sock);
947                         return 0;
948                 }
949                 break;
950         default:
951                 errno = EAFNOSUPPORT;
952                 return 0;
953         }
954
955         if (connect(sock, sap, salen) < 0) {
956                 close(sock);
957                 return 0;
958         }
959
960         return !getsockname(sock, buf, buflen);
961 }
962
963 /*
964  * Try to generate an address that prevents the server from calling us.
965  *
966  * Returns 1 and fills in @buf if successful; otherwise, zero.
967  */
968 static int nfs_ca_gai(const struct sockaddr *sap, const socklen_t salen,
969                       struct sockaddr *buf, socklen_t *buflen)
970 {
971         struct addrinfo *gai_results;
972         struct addrinfo gai_hint = {
973                 .ai_family      = sap->sa_family,
974                 .ai_flags       = AI_PASSIVE,   /* ANYADDR */
975         };
976
977         if (getaddrinfo(NULL, "", &gai_hint, &gai_results))
978                 return 0;
979
980         *buflen = gai_results->ai_addrlen;
981         memcpy(buf, gai_results->ai_addr, *buflen);
982
983         freeaddrinfo(gai_results);
984
985         return 1;
986 }
987
988 /**
989  * nfs_callback_address - acquire our local network address
990  * @sap: pointer to address of remote
991  * @sap_len: length of address
992  * @buf: pointer to buffer to be filled in with local network address
993  * @buflen: IN: length of buffer to fill in; OUT: length of filled-in address
994  *
995  * Discover a network address that an NFSv4 server can use to call us back.
996  * On multi-homed clients, this address depends on which NIC we use to
997  * route requests to the server.
998  *
999  * Returns 1 and fills in @buf if an unambiguous local address is
1000  * available; returns 1 and fills in an appropriate ANYADDR address
1001  * if a local address isn't available; otherwise, returns zero.
1002  */
1003 int nfs_callback_address(const struct sockaddr *sap, const socklen_t salen,
1004                          struct sockaddr *buf, socklen_t *buflen)
1005 {
1006         struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)buf;
1007
1008         if (nfs_ca_sockname(sap, salen, buf, buflen) == 0)
1009                 if (nfs_ca_gai(sap, salen, buf, buflen) == 0)
1010                         goto out_failed;
1011
1012         /*
1013          * The server can't use an interface ID that was generated
1014          * here on the client, so always clear sin6_scope_id.
1015          */
1016         if (sin6->sin6_family == AF_INET6)
1017                 sin6->sin6_scope_id = 0;
1018
1019         return 1;
1020
1021 out_failed:
1022         *buflen = 0;
1023         if (verbose)
1024                 nfs_error(_("%s: failed to construct callback address"));
1025         return 0;
1026
1027 }