]> git.decadent.org.uk Git - nfs-utils.git/blob - utils/mount/network.c
55b2cabd4f7cea8ae2d21b5200257fafa00ee3ce
[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 static void nfs_set_port(struct sockaddr *sap, const unsigned short port)
164 {
165         switch (sap->sa_family) {
166         case AF_INET:
167                 ((struct sockaddr_in *)sap)->sin_port = htons(port);
168                 break;
169         case AF_INET6:
170                 ((struct sockaddr_in6 *)sap)->sin6_port = htons(port);
171                 break;
172         default:
173                 nfs_error(_("%s: unrecognized address family in %s"),
174                         progname, __func__);
175         }
176 }
177
178 /**
179  * nfs_name_to_address - resolve hostname to an IPv4 or IPv6 socket address
180  * @hostname: pointer to C string containing DNS hostname to resolve
181  * @sap: pointer to buffer to fill with socket address
182  * @len: IN: size of buffer to fill; OUT: size of socket address
183  *
184  * Returns 1 and places a socket address at @sap if successful;
185  * otherwise zero.
186  */
187 int nfs_name_to_address(const char *hostname,
188                         const sa_family_t af_hint,
189                         struct sockaddr *sap, socklen_t *salen)
190 {
191         struct addrinfo *gai_results;
192         struct addrinfo gai_hint = {
193                 .ai_family      = af_hint,
194                 .ai_flags       = AI_ADDRCONFIG,
195         };
196         socklen_t len = *salen;
197         int error, ret = 0;
198
199         if (af_hint == AF_INET6)
200                 gai_hint.ai_flags |= AI_V4MAPPED|AI_ALL;
201
202         *salen = 0;
203
204         error = getaddrinfo(hostname, NULL, &gai_hint, &gai_results);
205         if (error) {
206                 nfs_error(_("%s: DNS resolution failed for %s: %s"),
207                         progname, hostname, (error == EAI_SYSTEM ?
208                                 strerror(errno) : gai_strerror(error)));
209                 return ret;
210         }
211
212         switch (gai_results->ai_addr->sa_family) {
213         case AF_INET:
214         case AF_INET6:
215                 if (len >= gai_results->ai_addrlen) {
216                         *salen = gai_results->ai_addrlen;
217                         memcpy(sap, gai_results->ai_addr, *salen);
218                         ret = 1;
219                 }
220                 break;
221         default:
222                 /* things are really broken if we get here, so warn */
223                 nfs_error(_("%s: unrecognized DNS resolution results for %s"),
224                                 progname, hostname);
225                 break;
226         }
227
228         freeaddrinfo(gai_results);
229         return ret;
230 }
231
232 /**
233  * nfs_gethostbyname - resolve a hostname to an IPv4 address
234  * @hostname: pointer to a C string containing a DNS hostname
235  * @saddr: returns an IPv4 address 
236  *
237  * Returns 1 if successful, otherwise zero.
238  */
239 int nfs_gethostbyname(const char *hostname, struct sockaddr_in *sin)
240 {
241         socklen_t len = sizeof(*sin);
242
243         return nfs_name_to_address(hostname, AF_INET,
244                                         (struct sockaddr *)sin, &len);
245 }
246
247 /**
248  * nfs_string_to_sockaddr - convert string address to sockaddr
249  * @address:    pointer to presentation format address to convert
250  * @addrlen:    length of presentation address
251  * @sap:        pointer to socket address buffer to fill in
252  * @salen:      IN: length of address buffer
253  *              OUT: length of converted socket address
254  *
255  * Convert a presentation format address string to a socket address.
256  * Similar to nfs_name_to_address(), but the DNS query is squelched,
257  * and won't make any noise if the getaddrinfo() call fails.
258  *
259  * Returns 1 and fills in @sap and @salen if successful; otherwise zero.
260  *
261  * See RFC 4038 section 5.1 or RFC 3513 section 2.2 for more details
262  * on presenting IPv6 addresses as text strings.
263  */
264 int nfs_string_to_sockaddr(const char *address, const size_t addrlen,
265                            struct sockaddr *sap, socklen_t *salen)
266 {
267         struct addrinfo *gai_results;
268         struct addrinfo gai_hint = {
269                 .ai_flags       = AI_NUMERICHOST,
270         };
271         socklen_t len = *salen;
272         int ret = 0;
273
274         *salen = 0;
275
276         if (getaddrinfo(address, NULL, &gai_hint, &gai_results) == 0) {
277                 switch (gai_results->ai_addr->sa_family) {
278                 case AF_INET:
279                 case AF_INET6:
280                         if (len >= gai_results->ai_addrlen) {
281                                 *salen = gai_results->ai_addrlen;
282                                 memcpy(sap, gai_results->ai_addr, *salen);
283                                 ret = 1;
284                         }
285                         break;
286                 }
287                 freeaddrinfo(gai_results);
288         }
289
290         return ret;
291 }
292
293 /**
294  * nfs_present_sockaddr - convert sockaddr to string
295  * @sap: pointer to socket address to convert
296  * @salen: length of socket address
297  * @buf: pointer to buffer to fill in
298  * @buflen: length of buffer
299  *
300  * Convert the passed-in sockaddr-style address to presentation format.
301  * The presentation format address is placed in @buf and is
302  * '\0'-terminated.
303  *
304  * Returns 1 if successful; otherwise zero.
305  *
306  * See RFC 4038 section 5.1 or RFC 3513 section 2.2 for more details
307  * on presenting IPv6 addresses as text strings.
308  */
309 int nfs_present_sockaddr(const struct sockaddr *sap, const socklen_t salen,
310                          char *buf, const size_t buflen)
311 {
312 #ifdef HAVE_GETNAMEINFO
313         int result;
314
315         result = getnameinfo(sap, salen, buf, buflen,
316                                         NULL, 0, NI_NUMERICHOST);
317         if (!result)
318                 return 1;
319
320         nfs_error(_("%s: invalid server address: %s"), progname,
321                         gai_strerror(result));
322         return 0;
323 #else   /* HAVE_GETNAMEINFO */
324         char *addr;
325
326         if (sap->sa_family == AF_INET) {
327                 addr = inet_ntoa(((struct sockaddr_in *)sap)->sin_addr);
328                 if (addr && strlen(addr) < buflen) {
329                         strcpy(buf, addr);
330                         return 1;
331                 }
332         }
333
334         nfs_error(_("%s: invalid server address"), progname);
335         return 0;
336 #endif  /* HAVE_GETNAMEINFO */
337 }
338
339 /*
340  * Attempt to connect a socket, but time out after "timeout" seconds.
341  *
342  * On error return, caller closes the socket.
343  */
344 static int connect_to(int fd, struct sockaddr *addr,
345                         socklen_t addrlen, int timeout)
346 {
347         int ret, saved;
348         fd_set rset, wset;
349         struct timeval tv = {
350                 .tv_sec = timeout,
351         };
352
353         saved = fcntl(fd, F_GETFL, 0);
354         fcntl(fd, F_SETFL, saved | O_NONBLOCK);
355
356         ret = connect(fd, addr, addrlen);
357         if (ret < 0 && errno != EINPROGRESS)
358                 return -1;
359         if (ret == 0)
360                 goto out;
361
362         FD_ZERO(&rset);
363         FD_SET(fd, &rset);
364         wset = rset;
365         ret = select(fd + 1, &rset, &wset, NULL, &tv);
366         if (ret == 0) {
367                 errno = ETIMEDOUT;
368                 return -1;
369         }
370         if (FD_ISSET(fd, &rset) || FD_ISSET(fd, &wset)) {
371                 int error;
372                 socklen_t len = sizeof(error);
373                 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &len) < 0)
374                         return -1;
375                 if (error) {
376                         errno = error;
377                         return -1;
378                 }
379         } else
380                 return -1;
381
382 out:
383         fcntl(fd, F_SETFL, saved);
384         return 0;
385 }
386
387 /*
388  * Create a socket that is locally bound to a reserved or non-reserved port.
389  *
390  * The caller should check rpc_createerr to determine the cause of any error.
391  */
392 static int get_socket(struct sockaddr_in *saddr, unsigned int p_prot,
393                         unsigned int timeout, int resvp, int conn)
394 {
395         int so, cc, type;
396         struct sockaddr_in laddr;
397         socklen_t namelen = sizeof(laddr);
398
399         type = (p_prot == IPPROTO_UDP ? SOCK_DGRAM : SOCK_STREAM);
400         if ((so = socket (AF_INET, type, p_prot)) < 0)
401                 goto err_socket;
402
403         laddr.sin_family = AF_INET;
404         laddr.sin_port = 0;
405         laddr.sin_addr.s_addr = htonl(INADDR_ANY);
406         if (resvp) {
407                 if (bindresvport(so, &laddr) < 0)
408                         goto err_bindresvport;
409         } else {
410                 cc = bind(so, (struct sockaddr *)&laddr, namelen);
411                 if (cc < 0)
412                         goto err_bind;
413         }
414         if (type == SOCK_STREAM || (conn && type == SOCK_DGRAM)) {
415                 cc = connect_to(so, (struct sockaddr *)saddr, namelen,
416                                 timeout);
417                 if (cc < 0)
418                         goto err_connect;
419         }
420         return so;
421
422 err_socket:
423         rpc_createerr.cf_stat = RPC_SYSTEMERROR;
424         rpc_createerr.cf_error.re_errno = errno;
425         if (verbose) {
426                 nfs_error(_("%s: Unable to create %s socket: errno %d (%s)\n"),
427                         progname, p_prot == IPPROTO_UDP ? _("UDP") : _("TCP"),
428                         errno, strerror(errno));
429         }
430         return RPC_ANYSOCK;
431
432 err_bindresvport:
433         rpc_createerr.cf_stat = RPC_SYSTEMERROR;
434         rpc_createerr.cf_error.re_errno = errno;
435         if (verbose) {
436                 nfs_error(_("%s: Unable to bindresvport %s socket: errno %d"
437                                 " (%s)\n"),
438                         progname, p_prot == IPPROTO_UDP ? _("UDP") : _("TCP"),
439                         errno, strerror(errno));
440         }
441         close(so);
442         return RPC_ANYSOCK;
443
444 err_bind:
445         rpc_createerr.cf_stat = RPC_SYSTEMERROR;
446         rpc_createerr.cf_error.re_errno = errno;
447         if (verbose) {
448                 nfs_error(_("%s: Unable to bind to %s socket: errno %d (%s)\n"),
449                         progname, p_prot == IPPROTO_UDP ? _("UDP") : _("TCP"),
450                         errno, strerror(errno));
451         }
452         close(so);
453         return RPC_ANYSOCK;
454
455 err_connect:
456         rpc_createerr.cf_stat = RPC_SYSTEMERROR;
457         rpc_createerr.cf_error.re_errno = errno;
458         if (verbose) {
459                 nfs_error(_("%s: Unable to connect to %s:%d, errno %d (%s)\n"),
460                         progname, inet_ntoa(saddr->sin_addr),
461                         ntohs(saddr->sin_port), errno, strerror(errno));
462         }
463         close(so);
464         return RPC_ANYSOCK;
465 }
466
467 static void nfs_pp_debug(const struct sockaddr *sap, const socklen_t salen,
468                          const rpcprog_t program, const rpcvers_t version,
469                          const unsigned short protocol,
470                          const unsigned short port)
471 {
472         char buf[NI_MAXHOST];
473
474         if (!verbose)
475                 return;
476
477         if (nfs_present_sockaddr(sap, salen, buf, sizeof(buf)) == 0) {
478                 buf[0] = '\0';
479                 strcat(buf, "unknown host");
480         }
481
482         fprintf(stderr, _("%s: trying %s prog %ld vers %ld prot %s port %d\n"),
483                         progname, buf, program, version,
484                         (protocol == IPPROTO_UDP ? _("UDP") : _("TCP")),
485                         port);
486 }
487
488 /*
489  * Use the portmapper to discover whether or not the service we want is
490  * available. The lists 'versions' and 'protos' define ordered sequences
491  * of service versions and udp/tcp protocols to probe for.
492  *
493  * Returns 1 if the requested service port is unambiguous and pingable;
494  * @pmap is filled in with the version, port, and transport protocol used
495  * during the successful ping.  Note that if a port is already specified
496  * in @pmap and it matches the rpcbind query result, nfs_probe_port() does
497  * not perform an RPC ping.
498  * 
499  * If an error occurs or the requested service isn't available, zero is
500  * returned; rpccreateerr.cf_stat is set to reflect the nature of the error.
501  */
502 static int nfs_probe_port(const struct sockaddr *sap, const socklen_t salen,
503                           struct pmap *pmap, const unsigned long *versions,
504                           const unsigned int *protos)
505 {
506         struct sockaddr_storage address;
507         struct sockaddr *saddr = (struct sockaddr *)&address;
508         const unsigned long prog = pmap->pm_prog, *p_vers;
509         const unsigned int prot = (u_int)pmap->pm_prot, *p_prot;
510         const u_short port = (u_short) pmap->pm_port;
511         unsigned long vers = pmap->pm_vers;
512         unsigned short p_port;
513
514         memcpy(saddr, sap, salen);
515         p_prot = prot ? &prot : protos;
516         p_vers = vers ? &vers : versions;
517         rpc_createerr.cf_stat = 0;
518
519         for (;;) {
520                 p_port = nfs_getport(saddr, salen, prog, *p_vers, *p_prot);
521                 if (p_port) {
522                         if (!port || port == p_port) {
523                                 nfs_set_port(saddr, p_port);
524                                 nfs_pp_debug(saddr, salen, prog, *p_vers,
525                                                 *p_prot, p_port);
526                                 if (nfs_rpc_ping(saddr, salen, prog,
527                                                         *p_vers, *p_prot, NULL))
528                                         goto out_ok;
529                         }
530                 }
531                 if (rpc_createerr.cf_stat != RPC_PROGNOTREGISTERED &&
532                     rpc_createerr.cf_stat != RPC_TIMEDOUT &&
533                     rpc_createerr.cf_stat != RPC_CANTRECV &&
534                     rpc_createerr.cf_stat != RPC_PROGVERSMISMATCH)
535                         goto out_bad;
536
537                 if (!prot) {
538                         if (*++p_prot)
539                                 continue;
540                         p_prot = protos;
541                 }
542                 if (rpc_createerr.cf_stat == RPC_TIMEDOUT ||
543                     rpc_createerr.cf_stat == RPC_CANTRECV)
544                         goto out_bad;
545
546                 if (vers || !*++p_vers)
547                         break;
548         }
549
550 out_bad:
551         return 0;
552
553 out_ok:
554         if (!vers)
555                 pmap->pm_vers = *p_vers;
556         if (!prot)
557                 pmap->pm_prot = *p_prot;
558         if (!port)
559                 pmap->pm_port = p_port;
560         rpc_createerr.cf_stat = 0;
561         return 1;
562 }
563
564 /*
565  * Probe a server's NFS service to determine which versions and
566  * transport protocols are supported.
567  *
568  * Returns 1 if the requested service port is unambiguous and pingable;
569  * @pmap is filled in with the version, port, and transport protocol used
570  * during the successful ping.  If all three are already specified, simply
571  * return success without an rpcbind query or RPC ping (we may be trying
572  * to mount an NFS service that is not advertised via rpcbind).
573  *
574  * If an error occurs or the requested service isn't available, zero is
575  * returned; rpccreateerr.cf_stat is set to reflect the nature of the error.
576  */
577 static int nfs_probe_nfsport(const struct sockaddr *sap, const socklen_t salen,
578                                 struct pmap *pmap)
579 {
580         if (pmap->pm_vers && pmap->pm_prot && pmap->pm_port)
581                 return 1;
582
583         if (nfs_mount_data_version >= 4)
584                 return nfs_probe_port(sap, salen, pmap,
585                                         probe_nfs3_first, probe_tcp_first);
586         else
587                 return nfs_probe_port(sap, salen, pmap,
588                                         probe_nfs2_only, probe_udp_only);
589 }
590
591 /*
592  * Probe a server's mountd service to determine which versions and
593  * transport protocols are supported.
594  *
595  * Returns 1 if the requested service port is unambiguous and pingable;
596  * @pmap is filled in with the version, port, and transport protocol used
597  * during the successful ping.  If all three are already specified, simply
598  * return success without an rpcbind query or RPC ping (we may be trying
599  * to mount an NFS service that is not advertised via rpcbind).
600  * 
601  * If an error occurs or the requested service isn't available, zero is
602  * returned; rpccreateerr.cf_stat is set to reflect the nature of the error.
603  */
604 static int nfs_probe_mntport(const struct sockaddr *sap, const socklen_t salen,
605                                 struct pmap *pmap)
606 {
607         if (pmap->pm_vers && pmap->pm_prot && pmap->pm_port)
608                 return 1;
609
610         if (nfs_mount_data_version >= 4)
611                 return nfs_probe_port(sap, salen, pmap,
612                                         probe_mnt3_first, probe_udp_first);
613         else
614                 return nfs_probe_port(sap, salen, pmap,
615                                         probe_mnt1_first, probe_udp_only);
616 }
617
618 /**
619  * probe_bothports - discover the RPC endpoints of mountd and NFS server
620  * @mnt_server: pointer to address and pmap argument for mountd results
621  * @nfs_server: pointer to address and pmap argument for NFS server
622  *
623  * Returns 1 if successful, otherwise zero if some error occurred.
624  * Note that the arguments are both input and output arguments.
625  *
626  * A side effect of calling this function is that rpccreateerr is set.
627  */
628 int probe_bothports(clnt_addr_t *mnt_server, clnt_addr_t *nfs_server)
629 {
630         struct sockaddr *nfs_saddr = (struct sockaddr *)&nfs_server->saddr;
631         socklen_t nfs_salen = sizeof(nfs_server->saddr);
632         struct sockaddr *mnt_saddr = (struct sockaddr *)&mnt_server->saddr;
633         socklen_t mnt_salen = sizeof(mnt_server->saddr);
634         struct pmap *nfs_pmap = &nfs_server->pmap;
635         struct pmap *mnt_pmap = &mnt_server->pmap;
636         struct pmap save_nfs, save_mnt;
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 (nfs_probe_nfsport(nfs_saddr, nfs_salen, nfs_pmap) != 0) {
654                         mnt_pmap->pm_vers = *probe_vers;
655                         if (nfs_probe_mntport(mnt_saddr, mnt_salen, mnt_pmap) != 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 (!nfs_probe_nfsport(nfs_saddr, nfs_salen, nfs_pmap))
674                 goto out_bad;
675         return nfs_probe_mntport(mnt_saddr, mnt_salen, mnt_pmap);
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         struct sockaddr *sap = (struct sockaddr *)&mnt_server->saddr;
743         socklen_t salen = sizeof(mnt_server->saddr);
744         struct pmap *pmap = &mnt_server->pmap;
745         CLIENT *clnt;
746         enum clnt_stat res = 0;
747         int msock;
748
749         if (!nfs_probe_mntport(sap, salen, pmap))
750                 return 0;
751         clnt = mnt_openclnt(mnt_server, &msock);
752         if (!clnt)
753                 return 0;
754         res = clnt_call(clnt, MOUNTPROC_UMNT,
755                         (xdrproc_t)xdr_dirpath, (caddr_t)argp,
756                         (xdrproc_t)xdr_void, NULL,
757                         TIMEOUT);
758         mnt_closeclnt(clnt, msock);
759
760         if (res == RPC_SUCCESS)
761                 return 1;
762         return 0;
763 }
764
765 /**
766  * mnt_openclnt - get a handle for a remote mountd service
767  * @mnt_server: address and pmap arguments of mountd service
768  * @msock: returns a file descriptor of the underlying transport socket
769  *
770  * Returns an active handle for the remote's mountd service
771  */
772 CLIENT *mnt_openclnt(clnt_addr_t *mnt_server, int *msock)
773 {
774         struct sockaddr_in *mnt_saddr = &mnt_server->saddr;
775         struct pmap *mnt_pmap = &mnt_server->pmap;
776         CLIENT *clnt = NULL;
777
778         mnt_saddr->sin_port = htons((u_short)mnt_pmap->pm_port);
779         *msock = get_socket(mnt_saddr, mnt_pmap->pm_prot, MOUNT_TIMEOUT,
780                                 TRUE, FALSE);
781         if (*msock == RPC_ANYSOCK) {
782                 if (rpc_createerr.cf_error.re_errno == EADDRINUSE)
783                         /*
784                          * Probably in-use by a TIME_WAIT connection,
785                          * It is worth waiting a while and trying again.
786                          */
787                         rpc_createerr.cf_stat = RPC_TIMEDOUT;
788                 return NULL;
789         }
790
791         switch (mnt_pmap->pm_prot) {
792         case IPPROTO_UDP:
793                 clnt = clntudp_bufcreate(mnt_saddr,
794                                          mnt_pmap->pm_prog, mnt_pmap->pm_vers,
795                                          RETRY_TIMEOUT, msock,
796                                          MNT_SENDBUFSIZE, MNT_RECVBUFSIZE);
797                 break;
798         case IPPROTO_TCP:
799                 clnt = clnttcp_create(mnt_saddr,
800                                       mnt_pmap->pm_prog, mnt_pmap->pm_vers,
801                                       msock,
802                                       MNT_SENDBUFSIZE, MNT_RECVBUFSIZE);
803                 break;
804         }
805         if (clnt) {
806                 /* try to mount hostname:dirname */
807                 clnt->cl_auth = authunix_create_default();
808                 return clnt;
809         }
810         return NULL;
811 }
812
813 /**
814  * mnt_closeclnt - terminate a handle for a remote mountd service
815  * @clnt: pointer to an active handle for a remote mountd service
816  * @msock: file descriptor of the underlying transport socket
817  *
818  */
819 void mnt_closeclnt(CLIENT *clnt, int msock)
820 {
821         auth_destroy(clnt->cl_auth);
822         clnt_destroy(clnt);
823         close(msock);
824 }
825
826 /**
827  * clnt_ping - send an RPC ping to the remote RPC service endpoint
828  * @saddr: server's address
829  * @prog: target RPC program number
830  * @vers: target RPC version number
831  * @prot: target RPC protocol
832  * @caddr: filled in with our network address
833  *
834  * Sigh... GETPORT queries don't actually check the version number.
835  * In order to make sure that the server actually supports the service
836  * we're requesting, we open an RPC client, and fire off a NULL
837  * RPC call.
838  *
839  * caddr is the network address that the server will use to call us back.
840  * On multi-homed clients, this address depends on which NIC we use to
841  * route requests to the server.
842  *
843  * Returns one if successful, otherwise zero.
844  */
845 int clnt_ping(struct sockaddr_in *saddr, const unsigned long prog,
846                 const unsigned long vers, const unsigned int prot,
847                 struct sockaddr_in *caddr)
848 {
849         CLIENT *clnt = NULL;
850         int sock, stat;
851         static char clnt_res;
852         struct sockaddr dissolve;
853
854         rpc_createerr.cf_stat = stat = 0;
855         sock = get_socket(saddr, prot, CONNECT_TIMEOUT, FALSE, TRUE);
856         if (sock == RPC_ANYSOCK) {
857                 if (rpc_createerr.cf_error.re_errno == ETIMEDOUT) {
858                         /*
859                          * TCP timeout. Bubble up the error to see 
860                          * how it should be handled.
861                          */
862                         rpc_createerr.cf_stat = RPC_TIMEDOUT;
863                 }
864                 return 0;
865         }
866
867         if (caddr) {
868                 /* Get the address of our end of this connection */
869                 socklen_t len = sizeof(*caddr);
870                 if (getsockname(sock, caddr, &len) != 0)
871                         caddr->sin_family = 0;
872         }
873
874         switch(prot) {
875         case IPPROTO_UDP:
876                 /* The socket is connected (so we could getsockname successfully),
877                  * but some servers on multi-homed hosts reply from
878                  * the wrong address, so if we stay connected, we lose the reply.
879                  */
880                 dissolve.sa_family = AF_UNSPEC;
881                 connect(sock, &dissolve, sizeof(dissolve));
882
883                 clnt = clntudp_bufcreate(saddr, prog, vers,
884                                          RETRY_TIMEOUT, &sock,
885                                          RPCSMALLMSGSIZE, RPCSMALLMSGSIZE);
886                 break;
887         case IPPROTO_TCP:
888                 clnt = clnttcp_create(saddr, prog, vers, &sock,
889                                       RPCSMALLMSGSIZE, RPCSMALLMSGSIZE);
890                 break;
891         }
892         if (!clnt) {
893                 close(sock);
894                 return 0;
895         }
896         memset(&clnt_res, 0, sizeof(clnt_res));
897         stat = clnt_call(clnt, NULLPROC,
898                          (xdrproc_t)xdr_void, (caddr_t)NULL,
899                          (xdrproc_t)xdr_void, (caddr_t)&clnt_res,
900                          TIMEOUT);
901         if (stat) {
902                 clnt_geterr(clnt, &rpc_createerr.cf_error);
903                 rpc_createerr.cf_stat = stat;
904         }
905         clnt_destroy(clnt);
906         close(sock);
907
908         if (stat == RPC_SUCCESS)
909                 return 1;
910         else
911                 return 0;
912 }
913
914 /*
915  * Try a getsockname() on a connected datagram socket.
916  *
917  * Returns 1 and fills in @buf if successful; otherwise, zero.
918  *
919  * A connected datagram socket prevents leaving a socket in TIME_WAIT.
920  * This conserves the ephemeral port number space, helping reduce failed
921  * socket binds during mount storms.
922  */
923 static int nfs_ca_sockname(const struct sockaddr *sap, const socklen_t salen,
924                            struct sockaddr *buf, socklen_t *buflen)
925 {
926         struct sockaddr_in sin = {
927                 .sin_family             = AF_INET,
928                 .sin_addr.s_addr        = htonl(INADDR_ANY),
929         };
930         struct sockaddr_in6 sin6 = {
931                 .sin6_family            = AF_INET6,
932                 .sin6_addr              = IN6ADDR_ANY_INIT,
933         };
934         int sock;
935
936         sock = socket(sap->sa_family, SOCK_DGRAM, IPPROTO_UDP);
937         if (sock < 0)
938                 return 0;
939
940         switch (sap->sa_family) {
941         case AF_INET:
942                 if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
943                         close(sock);
944                         return 0;
945                 }
946                 break;
947         case AF_INET6:
948                 if (bind(sock, (struct sockaddr *)&sin6, sizeof(sin6)) < 0) {
949                         close(sock);
950                         return 0;
951                 }
952                 break;
953         default:
954                 errno = EAFNOSUPPORT;
955                 return 0;
956         }
957
958         if (connect(sock, sap, salen) < 0) {
959                 close(sock);
960                 return 0;
961         }
962
963         return !getsockname(sock, buf, buflen);
964 }
965
966 /*
967  * Try to generate an address that prevents the server from calling us.
968  *
969  * Returns 1 and fills in @buf if successful; otherwise, zero.
970  */
971 static int nfs_ca_gai(const struct sockaddr *sap, const socklen_t salen,
972                       struct sockaddr *buf, socklen_t *buflen)
973 {
974         struct addrinfo *gai_results;
975         struct addrinfo gai_hint = {
976                 .ai_family      = sap->sa_family,
977                 .ai_flags       = AI_PASSIVE,   /* ANYADDR */
978         };
979
980         if (getaddrinfo(NULL, "", &gai_hint, &gai_results))
981                 return 0;
982
983         *buflen = gai_results->ai_addrlen;
984         memcpy(buf, gai_results->ai_addr, *buflen);
985
986         freeaddrinfo(gai_results);
987
988         return 1;
989 }
990
991 /**
992  * nfs_callback_address - acquire our local network address
993  * @sap: pointer to address of remote
994  * @sap_len: length of address
995  * @buf: pointer to buffer to be filled in with local network address
996  * @buflen: IN: length of buffer to fill in; OUT: length of filled-in address
997  *
998  * Discover a network address that an NFSv4 server can use to call us back.
999  * On multi-homed clients, this address depends on which NIC we use to
1000  * route requests to the server.
1001  *
1002  * Returns 1 and fills in @buf if an unambiguous local address is
1003  * available; returns 1 and fills in an appropriate ANYADDR address
1004  * if a local address isn't available; otherwise, returns zero.
1005  */
1006 int nfs_callback_address(const struct sockaddr *sap, const socklen_t salen,
1007                          struct sockaddr *buf, socklen_t *buflen)
1008 {
1009         struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)buf;
1010
1011         if (nfs_ca_sockname(sap, salen, buf, buflen) == 0)
1012                 if (nfs_ca_gai(sap, salen, buf, buflen) == 0)
1013                         goto out_failed;
1014
1015         /*
1016          * The server can't use an interface ID that was generated
1017          * here on the client, so always clear sin6_scope_id.
1018          */
1019         if (sin6->sin6_family == AF_INET6)
1020                 sin6->sin6_scope_id = 0;
1021
1022         return 1;
1023
1024 out_failed:
1025         *buflen = 0;
1026         if (verbose)
1027                 nfs_error(_("%s: failed to construct callback address"));
1028         return 0;
1029
1030 }