]> git.decadent.org.uk Git - nfs-utils.git/blob - utils/mount/network.c
getport: Clear shared error fields before trying rpcbind queries
[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 "parse_opt.h"
52 #include "network.h"
53
54 #define PMAP_TIMEOUT    (10)
55 #define CONNECT_TIMEOUT (20)
56 #define MOUNT_TIMEOUT   (30)
57
58 #if SIZEOF_SOCKLEN_T - 0 == 0
59 #define socklen_t unsigned int
60 #endif
61
62 extern int nfs_mount_data_version;
63 extern char *progname;
64 extern int verbose;
65
66 static const char *nfs_ns_pgmtbl[] = {
67         "status",
68         NULL,
69 };
70
71 static const char *nfs_mnt_pgmtbl[] = {
72         "mount",
73         "mountd",
74         NULL,
75 };
76
77 static const char *nfs_nfs_pgmtbl[] = {
78         "nfs",
79         "nfsprog",
80         NULL,
81 };
82
83 static const char *nfs_transport_opttbl[] = {
84         "udp",
85         "tcp",
86         "proto",
87         NULL,
88 };
89
90 static const char *nfs_version_opttbl[] = {
91         "v2",
92         "v3",
93         "vers",
94         "nfsvers",
95         NULL,
96 };
97
98 static const unsigned long nfs_to_mnt[] = {
99         0,
100         0,
101         1,
102         3,
103 };
104
105 static const unsigned long mnt_to_nfs[] = {
106         0,
107         2,
108         2,
109         3,
110 };
111
112 /*
113  * Map an NFS version into the corresponding Mountd version
114  */
115 unsigned long nfsvers_to_mnt(const unsigned long vers)
116 {
117         if (vers <= 3)
118                 return nfs_to_mnt[vers];
119         return 0;
120 }
121
122 /*
123  * Map a Mountd version into the corresponding NFS version
124  */
125 static unsigned long mntvers_to_nfs(const unsigned long vers)
126 {
127         if (vers <= 3)
128                 return mnt_to_nfs[vers];
129         return 0;
130 }
131
132 static const unsigned int probe_udp_only[] = {
133         IPPROTO_UDP,
134         0,
135 };
136
137 static const unsigned int probe_udp_first[] = {
138         IPPROTO_UDP,
139         IPPROTO_TCP,
140         0,
141 };
142
143 static const unsigned int probe_tcp_first[] = {
144         IPPROTO_TCP,
145         IPPROTO_UDP,
146         0,
147 };
148
149 static const unsigned long probe_nfs2_only[] = {
150         2,
151         0,
152 };
153
154 static const unsigned long probe_nfs3_first[] = {
155         3,
156         2,
157         0,
158 };
159
160 static const unsigned long probe_mnt1_first[] = {
161         1,
162         2,
163         0,
164 };
165
166 static const unsigned long probe_mnt3_first[] = {
167         3,
168         1,
169         2,
170         0,
171 };
172
173 static void nfs_set_port(struct sockaddr *sap, const unsigned short port)
174 {
175         switch (sap->sa_family) {
176         case AF_INET:
177                 ((struct sockaddr_in *)sap)->sin_port = htons(port);
178                 break;
179         case AF_INET6:
180                 ((struct sockaddr_in6 *)sap)->sin6_port = htons(port);
181                 break;
182         default:
183                 nfs_error(_("%s: unrecognized address family in %s"),
184                         progname, __func__);
185         }
186 }
187
188 static int nfs_lookup(const char *hostname, const sa_family_t family,
189                       struct sockaddr *sap, socklen_t *salen)
190 {
191         struct addrinfo *gai_results;
192         struct addrinfo gai_hint = {
193 #ifdef HAVE_DECL_AI_ADDRCONFIG
194                 .ai_flags       = AI_ADDRCONFIG,
195 #endif  /* HAVE_DECL_AI_ADDRCONFIG */
196                 .ai_family      = family,
197         };
198         socklen_t len = *salen;
199         int error, ret = 0;
200
201         *salen = 0;
202
203         error = getaddrinfo(hostname, NULL, &gai_hint, &gai_results);
204         switch (error) {
205         case 0:
206                 break;
207         case EAI_SYSTEM:
208                 nfs_error(_("%s: DNS resolution failed for %s: %s"),
209                         progname, hostname, strerror(errno));
210                 return ret;
211         default:
212                 nfs_error(_("%s: DNS resolution failed for %s: %s"),
213                         progname, hostname, gai_strerror(error));
214                 return ret;
215         }
216
217         switch (gai_results->ai_addr->sa_family) {
218         case AF_INET:
219         case AF_INET6:
220                 if (len >= gai_results->ai_addrlen) {
221                         *salen = gai_results->ai_addrlen;
222                         memcpy(sap, gai_results->ai_addr, *salen);
223                         ret = 1;
224                 }
225                 break;
226         default:
227                 /* things are really broken if we get here, so warn */
228                 nfs_error(_("%s: unrecognized DNS resolution results for %s"),
229                                 progname, hostname);
230                 break;
231         }
232
233         freeaddrinfo(gai_results);
234         return ret;
235 }
236
237 /**
238  * nfs_name_to_address - resolve hostname to an IPv4 or IPv6 socket address
239  * @hostname: pointer to C string containing DNS hostname to resolve
240  * @sap: pointer to buffer to fill with socket address
241  * @len: IN: size of buffer to fill; OUT: size of socket address
242  *
243  * Returns 1 and places a socket address at @sap if successful;
244  * otherwise zero.
245  */
246 int nfs_name_to_address(const char *hostname,
247                         struct sockaddr *sap, socklen_t *salen)
248 {
249 #ifdef IPV6_SUPPORTED
250         return nfs_lookup(hostname, AF_UNSPEC, sap, salen);
251 #else   /* !IPV6_SUPPORTED */
252         return nfs_lookup(hostname, AF_INET, sap, salen);
253 #endif  /* !IPV6_SUPPORTED */
254 }
255
256 /**
257  * nfs_gethostbyname - resolve a hostname to an IPv4 address
258  * @hostname: pointer to a C string containing a DNS hostname
259  * @sin: returns an IPv4 address 
260  *
261  * Returns 1 if successful, otherwise zero.
262  */
263 int nfs_gethostbyname(const char *hostname, struct sockaddr_in *sin)
264 {
265         socklen_t len = sizeof(*sin);
266
267         return nfs_lookup(hostname, AF_INET, (struct sockaddr *)sin, &len);
268 }
269
270 /**
271  * nfs_string_to_sockaddr - convert string address to sockaddr
272  * @address:    pointer to presentation format address to convert
273  * @addrlen:    length of presentation address
274  * @sap:        pointer to socket address buffer to fill in
275  * @salen:      IN: length of address buffer
276  *              OUT: length of converted socket address
277  *
278  * Convert a presentation format address string to a socket address.
279  * Similar to nfs_name_to_address(), but the DNS query is squelched,
280  * and won't make any noise if the getaddrinfo() call fails.
281  *
282  * Returns 1 and fills in @sap and @salen if successful; otherwise zero.
283  *
284  * See RFC 4038 section 5.1 or RFC 3513 section 2.2 for more details
285  * on presenting IPv6 addresses as text strings.
286  */
287 int nfs_string_to_sockaddr(const char *address, const size_t addrlen,
288                            struct sockaddr *sap, socklen_t *salen)
289 {
290         struct addrinfo *gai_results;
291         struct addrinfo gai_hint = {
292                 .ai_flags       = AI_NUMERICHOST,
293         };
294         socklen_t len = *salen;
295         int ret = 0;
296
297         *salen = 0;
298
299         if (getaddrinfo(address, NULL, &gai_hint, &gai_results) == 0) {
300                 switch (gai_results->ai_addr->sa_family) {
301                 case AF_INET:
302                 case AF_INET6:
303                         if (len >= gai_results->ai_addrlen) {
304                                 *salen = gai_results->ai_addrlen;
305                                 memcpy(sap, gai_results->ai_addr, *salen);
306                                 ret = 1;
307                         }
308                         break;
309                 }
310                 freeaddrinfo(gai_results);
311         }
312
313         return ret;
314 }
315
316 /**
317  * nfs_present_sockaddr - convert sockaddr to string
318  * @sap: pointer to socket address to convert
319  * @salen: length of socket address
320  * @buf: pointer to buffer to fill in
321  * @buflen: length of buffer
322  *
323  * Convert the passed-in sockaddr-style address to presentation format.
324  * The presentation format address is placed in @buf and is
325  * '\0'-terminated.
326  *
327  * Returns 1 if successful; otherwise zero.
328  *
329  * See RFC 4038 section 5.1 or RFC 3513 section 2.2 for more details
330  * on presenting IPv6 addresses as text strings.
331  */
332 int nfs_present_sockaddr(const struct sockaddr *sap, const socklen_t salen,
333                          char *buf, const size_t buflen)
334 {
335 #ifdef HAVE_GETNAMEINFO
336         int result;
337
338         result = getnameinfo(sap, salen, buf, buflen,
339                                         NULL, 0, NI_NUMERICHOST);
340         if (!result)
341                 return 1;
342
343         nfs_error(_("%s: invalid server address: %s"), progname,
344                         gai_strerror(result));
345         return 0;
346 #else   /* HAVE_GETNAMEINFO */
347         char *addr;
348
349         if (sap->sa_family == AF_INET) {
350                 addr = inet_ntoa(((struct sockaddr_in *)sap)->sin_addr);
351                 if (addr && strlen(addr) < buflen) {
352                         strcpy(buf, addr);
353                         return 1;
354                 }
355         }
356
357         nfs_error(_("%s: invalid server address"), progname);
358         return 0;
359 #endif  /* HAVE_GETNAMEINFO */
360 }
361
362 /*
363  * Attempt to connect a socket, but time out after "timeout" seconds.
364  *
365  * On error return, caller closes the socket.
366  */
367 static int connect_to(int fd, struct sockaddr *addr,
368                         socklen_t addrlen, int timeout)
369 {
370         int ret, saved;
371         fd_set rset, wset;
372         struct timeval tv = {
373                 .tv_sec = timeout,
374         };
375
376         saved = fcntl(fd, F_GETFL, 0);
377         fcntl(fd, F_SETFL, saved | O_NONBLOCK);
378
379         ret = connect(fd, addr, addrlen);
380         if (ret < 0 && errno != EINPROGRESS)
381                 return -1;
382         if (ret == 0)
383                 goto out;
384
385         FD_ZERO(&rset);
386         FD_SET(fd, &rset);
387         wset = rset;
388         ret = select(fd + 1, &rset, &wset, NULL, &tv);
389         if (ret == 0) {
390                 errno = ETIMEDOUT;
391                 return -1;
392         }
393         if (FD_ISSET(fd, &rset) || FD_ISSET(fd, &wset)) {
394                 int error;
395                 socklen_t len = sizeof(error);
396                 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &len) < 0)
397                         return -1;
398                 if (error) {
399                         errno = error;
400                         return -1;
401                 }
402         } else
403                 return -1;
404
405 out:
406         fcntl(fd, F_SETFL, saved);
407         return 0;
408 }
409
410 /*
411  * Create a socket that is locally bound to a reserved or non-reserved port.
412  *
413  * The caller should check rpc_createerr to determine the cause of any error.
414  */
415 static int get_socket(struct sockaddr_in *saddr, unsigned int p_prot,
416                         unsigned int timeout, int resvp, int conn)
417 {
418         int so, cc, type;
419         struct sockaddr_in laddr;
420         socklen_t namelen = sizeof(laddr);
421
422         type = (p_prot == IPPROTO_UDP ? SOCK_DGRAM : SOCK_STREAM);
423         if ((so = socket (AF_INET, type, p_prot)) < 0)
424                 goto err_socket;
425
426         laddr.sin_family = AF_INET;
427         laddr.sin_port = 0;
428         laddr.sin_addr.s_addr = htonl(INADDR_ANY);
429         if (resvp) {
430                 if (bindresvport(so, &laddr) < 0)
431                         goto err_bindresvport;
432         } else {
433                 cc = bind(so, (struct sockaddr *)&laddr, namelen);
434                 if (cc < 0)
435                         goto err_bind;
436         }
437         if (type == SOCK_STREAM || (conn && type == SOCK_DGRAM)) {
438                 cc = connect_to(so, (struct sockaddr *)saddr, namelen,
439                                 timeout);
440                 if (cc < 0)
441                         goto err_connect;
442         }
443         return so;
444
445 err_socket:
446         rpc_createerr.cf_stat = RPC_SYSTEMERROR;
447         rpc_createerr.cf_error.re_errno = errno;
448         if (verbose) {
449                 nfs_error(_("%s: Unable to create %s socket: errno %d (%s)\n"),
450                         progname, p_prot == IPPROTO_UDP ? _("UDP") : _("TCP"),
451                         errno, strerror(errno));
452         }
453         return RPC_ANYSOCK;
454
455 err_bindresvport:
456         rpc_createerr.cf_stat = RPC_SYSTEMERROR;
457         rpc_createerr.cf_error.re_errno = errno;
458         if (verbose) {
459                 nfs_error(_("%s: Unable to bindresvport %s socket: errno %d"
460                                 " (%s)\n"),
461                         progname, p_prot == IPPROTO_UDP ? _("UDP") : _("TCP"),
462                         errno, strerror(errno));
463         }
464         close(so);
465         return RPC_ANYSOCK;
466
467 err_bind:
468         rpc_createerr.cf_stat = RPC_SYSTEMERROR;
469         rpc_createerr.cf_error.re_errno = errno;
470         if (verbose) {
471                 nfs_error(_("%s: Unable to bind to %s socket: errno %d (%s)\n"),
472                         progname, p_prot == IPPROTO_UDP ? _("UDP") : _("TCP"),
473                         errno, strerror(errno));
474         }
475         close(so);
476         return RPC_ANYSOCK;
477
478 err_connect:
479         rpc_createerr.cf_stat = RPC_SYSTEMERROR;
480         rpc_createerr.cf_error.re_errno = errno;
481         if (verbose) {
482                 nfs_error(_("%s: Unable to connect to %s:%d, errno %d (%s)\n"),
483                         progname, inet_ntoa(saddr->sin_addr),
484                         ntohs(saddr->sin_port), errno, strerror(errno));
485         }
486         close(so);
487         return RPC_ANYSOCK;
488 }
489
490 static void nfs_pp_debug(const struct sockaddr *sap, const socklen_t salen,
491                          const rpcprog_t program, const rpcvers_t version,
492                          const unsigned short protocol,
493                          const unsigned short port)
494 {
495         char buf[NI_MAXHOST];
496
497         if (!verbose)
498                 return;
499
500         if (nfs_present_sockaddr(sap, salen, buf, sizeof(buf)) == 0) {
501                 buf[0] = '\0';
502                 strcat(buf, "unknown host");
503         }
504
505         fprintf(stderr, _("%s: trying %s prog %lu vers %lu prot %s port %d\n"),
506                         progname, buf, (unsigned long)program,
507                         (unsigned long)version,
508                         (protocol == IPPROTO_UDP ? _("UDP") : _("TCP")),
509                         port);
510 }
511
512 /*
513  * Use the portmapper to discover whether or not the service we want is
514  * available. The lists 'versions' and 'protos' define ordered sequences
515  * of service versions and udp/tcp protocols to probe for.
516  *
517  * Returns 1 if the requested service port is unambiguous and pingable;
518  * @pmap is filled in with the version, port, and transport protocol used
519  * during the successful ping.  Note that if a port is already specified
520  * in @pmap and it matches the rpcbind query result, nfs_probe_port() does
521  * not perform an RPC ping.
522  * 
523  * If an error occurs or the requested service isn't available, zero is
524  * returned; rpccreateerr.cf_stat is set to reflect the nature of the error.
525  */
526 static int nfs_probe_port(const struct sockaddr *sap, const socklen_t salen,
527                           struct pmap *pmap, const unsigned long *versions,
528                           const unsigned int *protos)
529 {
530         struct sockaddr_storage address;
531         struct sockaddr *saddr = (struct sockaddr *)&address;
532         const unsigned long prog = pmap->pm_prog, *p_vers;
533         const unsigned int prot = (u_int)pmap->pm_prot, *p_prot;
534         const u_short port = (u_short) pmap->pm_port;
535         unsigned long vers = pmap->pm_vers;
536         unsigned short p_port;
537
538         memcpy(saddr, sap, salen);
539         p_prot = prot ? &prot : protos;
540         p_vers = vers ? &vers : versions;
541
542         for (;;) {
543                 p_port = nfs_getport(saddr, salen, prog, *p_vers, *p_prot);
544                 if (p_port) {
545                         if (!port || port == p_port) {
546                                 nfs_set_port(saddr, p_port);
547                                 nfs_pp_debug(saddr, salen, prog, *p_vers,
548                                                 *p_prot, p_port);
549                                 if (nfs_rpc_ping(saddr, salen, prog,
550                                                         *p_vers, *p_prot, NULL))
551                                         goto out_ok;
552                         }
553                 }
554                 if (rpc_createerr.cf_stat != RPC_PROGNOTREGISTERED &&
555                     rpc_createerr.cf_stat != RPC_TIMEDOUT &&
556                     rpc_createerr.cf_stat != RPC_CANTRECV &&
557                     rpc_createerr.cf_stat != RPC_PROGVERSMISMATCH)
558                         goto out_bad;
559
560                 if (!prot) {
561                         if (*++p_prot)
562                                 continue;
563                         p_prot = protos;
564                 }
565                 if (rpc_createerr.cf_stat == RPC_TIMEDOUT ||
566                     rpc_createerr.cf_stat == RPC_CANTRECV)
567                         goto out_bad;
568
569                 if (vers || !*++p_vers)
570                         break;
571         }
572
573 out_bad:
574         return 0;
575
576 out_ok:
577         if (!vers)
578                 pmap->pm_vers = *p_vers;
579         if (!prot)
580                 pmap->pm_prot = *p_prot;
581         if (!port)
582                 pmap->pm_port = p_port;
583         nfs_clear_rpc_createerr();
584         return 1;
585 }
586
587 /*
588  * Probe a server's NFS service to determine which versions and
589  * transport protocols are supported.
590  *
591  * Returns 1 if the requested service port is unambiguous and pingable;
592  * @pmap is filled in with the version, port, and transport protocol used
593  * during the successful ping.  If all three are already specified, simply
594  * return success without an rpcbind query or RPC ping (we may be trying
595  * to mount an NFS service that is not advertised via rpcbind).
596  *
597  * If an error occurs or the requested service isn't available, zero is
598  * returned; rpccreateerr.cf_stat is set to reflect the nature of the error.
599  */
600 static int nfs_probe_nfsport(const struct sockaddr *sap, const socklen_t salen,
601                                 struct pmap *pmap)
602 {
603         if (pmap->pm_vers && pmap->pm_prot && pmap->pm_port)
604                 return 1;
605
606         if (nfs_mount_data_version >= 4)
607                 return nfs_probe_port(sap, salen, pmap,
608                                         probe_nfs3_first, probe_tcp_first);
609         else
610                 return nfs_probe_port(sap, salen, pmap,
611                                         probe_nfs2_only, probe_udp_only);
612 }
613
614 /*
615  * Probe a server's mountd service to determine which versions and
616  * transport protocols are supported.
617  *
618  * Returns 1 if the requested service port is unambiguous and pingable;
619  * @pmap is filled in with the version, port, and transport protocol used
620  * during the successful ping.  If all three are already specified, simply
621  * return success without an rpcbind query or RPC ping (we may be trying
622  * to mount an NFS service that is not advertised via rpcbind).
623  * 
624  * If an error occurs or the requested service isn't available, zero is
625  * returned; rpccreateerr.cf_stat is set to reflect the nature of the error.
626  */
627 static int nfs_probe_mntport(const struct sockaddr *sap, const socklen_t salen,
628                                 struct pmap *pmap)
629 {
630         if (pmap->pm_vers && pmap->pm_prot && pmap->pm_port)
631                 return 1;
632
633         if (nfs_mount_data_version >= 4)
634                 return nfs_probe_port(sap, salen, pmap,
635                                         probe_mnt3_first, probe_udp_first);
636         else
637                 return nfs_probe_port(sap, salen, pmap,
638                                         probe_mnt1_first, probe_udp_only);
639 }
640
641 /*
642  * Probe a server's mountd service to determine which versions and
643  * transport protocols are supported.  Invoked when the protocol
644  * version is already known for both the NFS and mountd service.
645  *
646  * Returns 1 and fills in both @pmap structs if the requested service
647  * ports are unambiguous and pingable.  Otherwise zero is returned;
648  * rpccreateerr.cf_stat is set to reflect the nature of the error.
649  */
650 static int nfs_probe_version_fixed(const struct sockaddr *mnt_saddr,
651                         const socklen_t mnt_salen,
652                         struct pmap *mnt_pmap,
653                         const struct sockaddr *nfs_saddr,
654                         const socklen_t nfs_salen,
655                         struct pmap *nfs_pmap)
656 {
657         if (!nfs_probe_nfsport(nfs_saddr, nfs_salen, nfs_pmap))
658                 return 0;
659         return nfs_probe_mntport(mnt_saddr, mnt_salen, mnt_pmap);
660 }
661
662 /**
663  * nfs_probe_bothports - discover the RPC endpoints of mountd and NFS server
664  * @mnt_saddr:  pointer to socket address of mountd server
665  * @mnt_salen:  length of mountd server's address
666  * @mnt_pmap:   IN: partially filled-in mountd RPC service tuple;
667  *              OUT: fully filled-in mountd RPC service tuple
668  * @nfs_saddr:  pointer to socket address of NFS server
669  * @nfs_salen:  length of NFS server's address
670  * @nfs_pmap:   IN: partially filled-in NFS RPC service tuple;
671  *              OUT: fully filled-in NFS RPC service tuple
672  *
673  * Returns 1 and fills in both @pmap structs if the requested service
674  * ports are unambiguous and pingable.  Otherwise zero is returned;
675  * rpccreateerr.cf_stat is set to reflect the nature of the error.
676  */
677 int nfs_probe_bothports(const struct sockaddr *mnt_saddr,
678                         const socklen_t mnt_salen,
679                         struct pmap *mnt_pmap,
680                         const struct sockaddr *nfs_saddr,
681                         const socklen_t nfs_salen,
682                         struct pmap *nfs_pmap)
683 {
684         struct pmap save_nfs, save_mnt;
685         const unsigned long *probe_vers;
686
687         if (mnt_pmap->pm_vers && !nfs_pmap->pm_vers)
688                 nfs_pmap->pm_vers = mntvers_to_nfs(mnt_pmap->pm_vers);
689         else if (nfs_pmap->pm_vers && !mnt_pmap->pm_vers)
690                 mnt_pmap->pm_vers = nfsvers_to_mnt(nfs_pmap->pm_vers);
691
692         if (nfs_pmap->pm_vers)
693                 return nfs_probe_version_fixed(mnt_saddr, mnt_salen, mnt_pmap,
694                                                nfs_saddr, nfs_salen, nfs_pmap);
695
696         memcpy(&save_nfs, nfs_pmap, sizeof(save_nfs));
697         memcpy(&save_mnt, mnt_pmap, sizeof(save_mnt));
698         probe_vers = (nfs_mount_data_version >= 4) ?
699                         probe_mnt3_first : probe_mnt1_first;
700
701         for (; *probe_vers; probe_vers++) {
702                 nfs_pmap->pm_vers = mntvers_to_nfs(*probe_vers);
703                 if (nfs_probe_nfsport(nfs_saddr, nfs_salen, nfs_pmap) != 0) {
704                         mnt_pmap->pm_vers = *probe_vers;
705                         if (nfs_probe_mntport(mnt_saddr, mnt_salen, mnt_pmap) != 0)
706                                 return 1;
707                         memcpy(mnt_pmap, &save_mnt, sizeof(*mnt_pmap));
708                 }
709                 switch (rpc_createerr.cf_stat) {
710                 case RPC_PROGVERSMISMATCH:
711                 case RPC_PROGNOTREGISTERED:
712                         break;
713                 default:
714                         return 0;
715                 }
716                 memcpy(nfs_pmap, &save_nfs, sizeof(*nfs_pmap));
717         }
718
719         return 0;
720 }
721
722 /**
723  * probe_bothports - discover the RPC endpoints of mountd and NFS server
724  * @mnt_server: pointer to address and pmap argument for mountd results
725  * @nfs_server: pointer to address and pmap argument for NFS server
726  *
727  * This is the legacy API that takes "clnt_addr_t" for both servers,
728  * but supports only AF_INET addresses.
729  *
730  * Returns 1 and fills in the pmap field in both clnt_addr_t structs
731  * if the requested service ports are unambiguous and pingable.
732  * Otherwise zero is returned; rpccreateerr.cf_stat is set to reflect
733  * the nature of the error.
734  */
735 int probe_bothports(clnt_addr_t *mnt_server, clnt_addr_t *nfs_server)
736 {
737         return nfs_probe_bothports((struct sockaddr *)&mnt_server->saddr,
738                                         sizeof(mnt_server->saddr),
739                                         &mnt_server->pmap,
740                                         (struct sockaddr *)&nfs_server->saddr,
741                                         sizeof(nfs_server->saddr),
742                                         &nfs_server->pmap);
743 }
744
745 static int nfs_probe_statd(void)
746 {
747         struct sockaddr_in addr = {
748                 .sin_family             = AF_INET,
749                 .sin_addr.s_addr        = htonl(INADDR_LOOPBACK),
750         };
751         rpcprog_t program = nfs_getrpcbyname(NSMPROG, nfs_ns_pgmtbl);
752
753         return nfs_getport_ping((struct sockaddr *)&addr, sizeof(addr),
754                                 program, (rpcvers_t)1, IPPROTO_UDP);
755 }
756
757 /**
758  * start_statd - attempt to start rpc.statd
759  *
760  * Returns 1 if statd is running; otherwise zero.
761  */
762 int start_statd(void)
763 {
764 #ifdef START_STATD
765         struct stat stb;
766 #endif
767
768         if (nfs_probe_statd())
769                 return 1;
770
771 #ifdef START_STATD
772         if (stat(START_STATD, &stb) == 0) {
773                 if (S_ISREG(stb.st_mode) && (stb.st_mode & S_IXUSR)) {
774                         pid_t pid = fork();
775                         switch (pid) {
776                         case 0: /* child */
777                                 execl(START_STATD, START_STATD, NULL);
778                                 exit(1);
779                         case -1: /* error */
780                                 nfs_error(_("fork failed: %s"),
781                                                         strerror(errno));
782                                 break;
783                         default: /* parent */
784                                 waitpid(pid, NULL,0);
785                                 break;
786                         }
787                         if (nfs_probe_statd())
788                                 return 1;
789                 }
790         }
791 #endif
792
793         return 0;
794 }
795
796 /**
797  * nfs_advise_umount - ask the server to remove a share from it's rmtab
798  * @sap: pointer to IP address of server to call
799  * @salen: length of server address
800  * @pmap: partially filled-in mountd RPC service tuple
801  * @argp: directory path of share to "unmount"
802  *
803  * Returns one if the unmount call succeeded; zero if the unmount
804  * failed for any reason;  rpccreateerr.cf_stat is set to reflect
805  * the nature of the error.
806  *
807  * We use a fast timeout since this call is advisory only.
808  */
809 int nfs_advise_umount(const struct sockaddr *sap, const socklen_t salen,
810                       const struct pmap *pmap, const dirpath *argp)
811 {
812         struct sockaddr_storage address;
813         struct sockaddr *saddr = (struct sockaddr *)&address;
814         struct pmap mnt_pmap = *pmap;
815         struct timeval timeout = {
816                 .tv_sec         = MOUNT_TIMEOUT >> 3,
817         };
818         CLIENT *client;
819         enum clnt_stat res = 0;
820
821         memcpy(saddr, sap, salen);
822         if (nfs_probe_mntport(saddr, salen, &mnt_pmap) == 0) {
823                 if (verbose)
824                         nfs_error(_("%s: Failed to discover mountd port%s"),
825                                 progname, clnt_spcreateerror(""));
826                 return 0;
827         }
828         nfs_set_port(saddr, mnt_pmap.pm_port);
829
830         client = nfs_get_priv_rpcclient(saddr, salen, mnt_pmap.pm_prot,
831                                         mnt_pmap.pm_prog, mnt_pmap.pm_vers,
832                                         &timeout);
833         if (client == NULL) {
834                 if (verbose)
835                         nfs_error(_("%s: Failed to create RPC client%s"),
836                                 progname, clnt_spcreateerror(""));
837                 return 0;
838         }
839
840         client->cl_auth = authunix_create_default();
841
842         res = CLNT_CALL(client, MOUNTPROC_UMNT,
843                         (xdrproc_t)xdr_dirpath, (caddr_t)argp,
844                         (xdrproc_t)xdr_void, NULL,
845                         timeout);
846         if (verbose && res != RPC_SUCCESS)
847                 nfs_error(_("%s: UMNT call failed: %s"),
848                         progname, clnt_sperrno(res));
849
850         auth_destroy(client->cl_auth);
851         CLNT_DESTROY(client);
852
853         if (res != RPC_SUCCESS)
854                 return 0;
855         return 1;
856 }
857
858 /**
859  * nfs_call_umount - ask the server to remove a share from it's rmtab
860  * @mnt_server: address of RPC MNT program server
861  * @argp: directory path of share to "unmount"
862  *
863  * Returns one if the unmount call succeeded; zero if the unmount
864  * failed for any reason.
865  *
866  * Note that a side effect of calling this function is that rpccreateerr
867  * is set.
868  */
869 int nfs_call_umount(clnt_addr_t *mnt_server, dirpath *argp)
870 {
871         struct sockaddr *sap = (struct sockaddr *)&mnt_server->saddr;
872         socklen_t salen = sizeof(mnt_server->saddr);
873         struct pmap *pmap = &mnt_server->pmap;
874         CLIENT *clnt;
875         enum clnt_stat res = 0;
876         int msock;
877
878         if (!nfs_probe_mntport(sap, salen, pmap))
879                 return 0;
880         clnt = mnt_openclnt(mnt_server, &msock);
881         if (!clnt)
882                 return 0;
883         res = clnt_call(clnt, MOUNTPROC_UMNT,
884                         (xdrproc_t)xdr_dirpath, (caddr_t)argp,
885                         (xdrproc_t)xdr_void, NULL,
886                         TIMEOUT);
887         mnt_closeclnt(clnt, msock);
888
889         if (res == RPC_SUCCESS)
890                 return 1;
891         return 0;
892 }
893
894 /**
895  * mnt_openclnt - get a handle for a remote mountd service
896  * @mnt_server: address and pmap arguments of mountd service
897  * @msock: returns a file descriptor of the underlying transport socket
898  *
899  * Returns an active handle for the remote's mountd service
900  */
901 CLIENT *mnt_openclnt(clnt_addr_t *mnt_server, int *msock)
902 {
903         struct sockaddr_in *mnt_saddr = &mnt_server->saddr;
904         struct pmap *mnt_pmap = &mnt_server->pmap;
905         CLIENT *clnt = NULL;
906
907         mnt_saddr->sin_port = htons((u_short)mnt_pmap->pm_port);
908         *msock = get_socket(mnt_saddr, mnt_pmap->pm_prot, MOUNT_TIMEOUT,
909                                 TRUE, FALSE);
910         if (*msock == RPC_ANYSOCK) {
911                 if (rpc_createerr.cf_error.re_errno == EADDRINUSE)
912                         /*
913                          * Probably in-use by a TIME_WAIT connection,
914                          * It is worth waiting a while and trying again.
915                          */
916                         rpc_createerr.cf_stat = RPC_TIMEDOUT;
917                 return NULL;
918         }
919
920         switch (mnt_pmap->pm_prot) {
921         case IPPROTO_UDP:
922                 clnt = clntudp_bufcreate(mnt_saddr,
923                                          mnt_pmap->pm_prog, mnt_pmap->pm_vers,
924                                          RETRY_TIMEOUT, msock,
925                                          MNT_SENDBUFSIZE, MNT_RECVBUFSIZE);
926                 break;
927         case IPPROTO_TCP:
928                 clnt = clnttcp_create(mnt_saddr,
929                                       mnt_pmap->pm_prog, mnt_pmap->pm_vers,
930                                       msock,
931                                       MNT_SENDBUFSIZE, MNT_RECVBUFSIZE);
932                 break;
933         }
934         if (clnt) {
935                 /* try to mount hostname:dirname */
936                 clnt->cl_auth = authunix_create_default();
937                 return clnt;
938         }
939         return NULL;
940 }
941
942 /**
943  * mnt_closeclnt - terminate a handle for a remote mountd service
944  * @clnt: pointer to an active handle for a remote mountd service
945  * @msock: file descriptor of the underlying transport socket
946  *
947  */
948 void mnt_closeclnt(CLIENT *clnt, int msock)
949 {
950         auth_destroy(clnt->cl_auth);
951         clnt_destroy(clnt);
952         close(msock);
953 }
954
955 /**
956  * clnt_ping - send an RPC ping to the remote RPC service endpoint
957  * @saddr: server's address
958  * @prog: target RPC program number
959  * @vers: target RPC version number
960  * @prot: target RPC protocol
961  * @caddr: filled in with our network address
962  *
963  * Sigh... GETPORT queries don't actually check the version number.
964  * In order to make sure that the server actually supports the service
965  * we're requesting, we open an RPC client, and fire off a NULL
966  * RPC call.
967  *
968  * caddr is the network address that the server will use to call us back.
969  * On multi-homed clients, this address depends on which NIC we use to
970  * route requests to the server.
971  *
972  * Returns one if successful, otherwise zero.
973  */
974 int clnt_ping(struct sockaddr_in *saddr, const unsigned long prog,
975                 const unsigned long vers, const unsigned int prot,
976                 struct sockaddr_in *caddr)
977 {
978         CLIENT *clnt = NULL;
979         int sock, stat;
980         static char clnt_res;
981         struct sockaddr dissolve;
982
983         rpc_createerr.cf_stat = stat = 0;
984         sock = get_socket(saddr, prot, CONNECT_TIMEOUT, FALSE, TRUE);
985         if (sock == RPC_ANYSOCK) {
986                 if (rpc_createerr.cf_error.re_errno == ETIMEDOUT) {
987                         /*
988                          * TCP timeout. Bubble up the error to see 
989                          * how it should be handled.
990                          */
991                         rpc_createerr.cf_stat = RPC_TIMEDOUT;
992                 }
993                 return 0;
994         }
995
996         if (caddr) {
997                 /* Get the address of our end of this connection */
998                 socklen_t len = sizeof(*caddr);
999                 if (getsockname(sock, caddr, &len) != 0)
1000                         caddr->sin_family = 0;
1001         }
1002
1003         switch(prot) {
1004         case IPPROTO_UDP:
1005                 /* The socket is connected (so we could getsockname successfully),
1006                  * but some servers on multi-homed hosts reply from
1007                  * the wrong address, so if we stay connected, we lose the reply.
1008                  */
1009                 dissolve.sa_family = AF_UNSPEC;
1010                 connect(sock, &dissolve, sizeof(dissolve));
1011
1012                 clnt = clntudp_bufcreate(saddr, prog, vers,
1013                                          RETRY_TIMEOUT, &sock,
1014                                          RPCSMALLMSGSIZE, RPCSMALLMSGSIZE);
1015                 break;
1016         case IPPROTO_TCP:
1017                 clnt = clnttcp_create(saddr, prog, vers, &sock,
1018                                       RPCSMALLMSGSIZE, RPCSMALLMSGSIZE);
1019                 break;
1020         }
1021         if (!clnt) {
1022                 close(sock);
1023                 return 0;
1024         }
1025         memset(&clnt_res, 0, sizeof(clnt_res));
1026         stat = clnt_call(clnt, NULLPROC,
1027                          (xdrproc_t)xdr_void, (caddr_t)NULL,
1028                          (xdrproc_t)xdr_void, (caddr_t)&clnt_res,
1029                          TIMEOUT);
1030         if (stat) {
1031                 clnt_geterr(clnt, &rpc_createerr.cf_error);
1032                 rpc_createerr.cf_stat = stat;
1033         }
1034         clnt_destroy(clnt);
1035         close(sock);
1036
1037         if (stat == RPC_SUCCESS)
1038                 return 1;
1039         else
1040                 return 0;
1041 }
1042
1043 /*
1044  * Try a getsockname() on a connected datagram socket.
1045  *
1046  * Returns 1 and fills in @buf if successful; otherwise, zero.
1047  *
1048  * A connected datagram socket prevents leaving a socket in TIME_WAIT.
1049  * This conserves the ephemeral port number space, helping reduce failed
1050  * socket binds during mount storms.
1051  */
1052 static int nfs_ca_sockname(const struct sockaddr *sap, const socklen_t salen,
1053                            struct sockaddr *buf, socklen_t *buflen)
1054 {
1055         struct sockaddr_in sin = {
1056                 .sin_family             = AF_INET,
1057                 .sin_addr.s_addr        = htonl(INADDR_ANY),
1058         };
1059         struct sockaddr_in6 sin6 = {
1060                 .sin6_family            = AF_INET6,
1061                 .sin6_addr              = IN6ADDR_ANY_INIT,
1062         };
1063         int sock;
1064
1065         sock = socket(sap->sa_family, SOCK_DGRAM, IPPROTO_UDP);
1066         if (sock < 0)
1067                 return 0;
1068
1069         switch (sap->sa_family) {
1070         case AF_INET:
1071                 if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
1072                         close(sock);
1073                         return 0;
1074                 }
1075                 break;
1076         case AF_INET6:
1077                 if (bind(sock, (struct sockaddr *)&sin6, sizeof(sin6)) < 0) {
1078                         close(sock);
1079                         return 0;
1080                 }
1081                 break;
1082         default:
1083                 errno = EAFNOSUPPORT;
1084                 return 0;
1085         }
1086
1087         if (connect(sock, sap, salen) < 0) {
1088                 close(sock);
1089                 return 0;
1090         }
1091
1092         return !getsockname(sock, buf, buflen);
1093 }
1094
1095 /*
1096  * Try to generate an address that prevents the server from calling us.
1097  *
1098  * Returns 1 and fills in @buf if successful; otherwise, zero.
1099  */
1100 static int nfs_ca_gai(const struct sockaddr *sap, const socklen_t salen,
1101                       struct sockaddr *buf, socklen_t *buflen)
1102 {
1103         struct addrinfo *gai_results;
1104         struct addrinfo gai_hint = {
1105                 .ai_family      = sap->sa_family,
1106                 .ai_flags       = AI_PASSIVE,   /* ANYADDR */
1107         };
1108
1109         if (getaddrinfo(NULL, "", &gai_hint, &gai_results))
1110                 return 0;
1111
1112         *buflen = gai_results->ai_addrlen;
1113         memcpy(buf, gai_results->ai_addr, *buflen);
1114
1115         freeaddrinfo(gai_results);
1116
1117         return 1;
1118 }
1119
1120 /**
1121  * nfs_callback_address - acquire our local network address
1122  * @sap: pointer to address of remote
1123  * @sap_len: length of address
1124  * @buf: pointer to buffer to be filled in with local network address
1125  * @buflen: IN: length of buffer to fill in; OUT: length of filled-in address
1126  *
1127  * Discover a network address that an NFSv4 server can use to call us back.
1128  * On multi-homed clients, this address depends on which NIC we use to
1129  * route requests to the server.
1130  *
1131  * Returns 1 and fills in @buf if an unambiguous local address is
1132  * available; returns 1 and fills in an appropriate ANYADDR address
1133  * if a local address isn't available; otherwise, returns zero.
1134  */
1135 int nfs_callback_address(const struct sockaddr *sap, const socklen_t salen,
1136                          struct sockaddr *buf, socklen_t *buflen)
1137 {
1138         struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)buf;
1139
1140         if (nfs_ca_sockname(sap, salen, buf, buflen) == 0)
1141                 if (nfs_ca_gai(sap, salen, buf, buflen) == 0)
1142                         goto out_failed;
1143
1144         /*
1145          * The server can't use an interface ID that was generated
1146          * here on the client, so always clear sin6_scope_id.
1147          */
1148         if (sin6->sin6_family == AF_INET6)
1149                 sin6->sin6_scope_id = 0;
1150
1151         return 1;
1152
1153 out_failed:
1154         *buflen = 0;
1155         if (verbose)
1156                 nfs_error(_("%s: failed to construct callback address"));
1157         return 0;
1158
1159 }
1160
1161 /*
1162  * "nfsprog" is only supported by the legacy mount command.  The
1163  * kernel mount client does not support this option.
1164  *
1165  * Returns the value set by the nfsprog= option, the value of
1166  * the RPC NFS program specified in /etc/rpc, or a baked-in
1167  * default program number, if all fails.
1168  */
1169 static rpcprog_t nfs_nfs_program(struct mount_options *options)
1170 {
1171         long tmp;
1172
1173         if (po_get_numeric(options, "nfsprog", &tmp) == PO_FOUND)
1174                 if (tmp >= 0)
1175                         return tmp;
1176         return nfs_getrpcbyname(NFSPROG, nfs_nfs_pgmtbl);
1177 }
1178
1179
1180 /*
1181  * Returns the RPC version number specified by the given mount
1182  * options for the NFS service, or zero if all fails.
1183  */
1184 static rpcvers_t nfs_nfs_version(struct mount_options *options)
1185 {
1186         long tmp;
1187
1188         switch (po_rightmost(options, nfs_version_opttbl)) {
1189         case 0: /* v2 */
1190                 return 2;
1191         case 1: /* v3 */
1192                 return 3;
1193         case 2: /* vers */
1194                 if (po_get_numeric(options, "vers", &tmp) == PO_FOUND)
1195                         if (tmp >= 2 && tmp <= 3)
1196                                 return tmp;
1197                 break;
1198         case 3: /* nfsvers */
1199                 if (po_get_numeric(options, "nfsvers", &tmp) == PO_FOUND)
1200                         if (tmp >= 2 && tmp <= 3)
1201                                 return tmp;
1202                 break;
1203         }
1204
1205         return 0;
1206 }
1207
1208 /*
1209  * Returns the NFS transport protocol specified by the given mount options
1210  *
1211  * Returns the IPPROTO_ value specified by the given mount options, or
1212  * IPPROTO_UDP if all fails.
1213  */
1214 static unsigned short nfs_nfs_protocol(struct mount_options *options)
1215 {
1216         char *option;
1217
1218         switch (po_rightmost(options, nfs_transport_opttbl)) {
1219         case 1: /* tcp */
1220                 return IPPROTO_TCP;
1221         case 2: /* proto */
1222                 option = po_get(options, "proto");
1223                 if (option) {
1224                         if (strcmp(option, "tcp") == 0)
1225                                 return IPPROTO_TCP;
1226                         if (strcmp(option, "udp") == 0)
1227                                 return IPPROTO_UDP;
1228                 }
1229         }
1230
1231         return IPPROTO_UDP;
1232 }
1233
1234 /*
1235  * Returns the NFS server's port number specified by the given
1236  * mount options, or zero if all fails.  Zero results in a portmap
1237  * query to discover the server's mountd service port.
1238  *
1239  * port=0 will guarantee an rpcbind request precedes the first
1240  * NFS RPC so the client can determine the server's port number.
1241  */
1242 static unsigned short nfs_nfs_port(struct mount_options *options)
1243 {
1244         long tmp;
1245
1246         if (po_get_numeric(options, "port", &tmp) == PO_FOUND)
1247                 if (tmp >= 0 && tmp <= 65535)
1248                         return tmp;
1249         return 0;
1250 }
1251
1252 /*
1253  * "mountprog" is only supported by the legacy mount command.  The
1254  * kernel mount client does not support this option.
1255  *
1256  * Returns the value set by the mountprog= option, the value of
1257  * the RPC mount program specified in /etc/rpc, or a baked-in
1258  * default program number, if all fails.
1259  */
1260 static rpcprog_t nfs_mount_program(struct mount_options *options)
1261 {
1262         long tmp;
1263
1264         if (po_get_numeric(options, "mountprog", &tmp) == PO_FOUND)
1265                 if (tmp >= 0)
1266                         return tmp;
1267         return nfs_getrpcbyname(MOUNTPROG, nfs_mnt_pgmtbl);
1268 }
1269
1270 /*
1271  * Returns the RPC version number specified by the given mount options,
1272  * or the version "3" if all fails.
1273  */
1274 static rpcvers_t nfs_mount_version(struct mount_options *options)
1275 {
1276         long tmp;
1277
1278         if (po_get_numeric(options, "mountvers", &tmp) == PO_FOUND)
1279                 if (tmp >= 1 && tmp <= 4)
1280                         return tmp;
1281
1282         return nfsvers_to_mnt(nfs_nfs_version(options));
1283 }
1284
1285 /*
1286  * Returns the transport protocol to use for the mount service
1287  *
1288  * Returns the IPPROTO_ value specified by the mountproto option, or
1289  * if that doesn't exist, the IPPROTO_ value specified for NFS
1290  * itself.
1291  */
1292 static unsigned short nfs_mount_protocol(struct mount_options *options)
1293 {
1294         char *option;
1295
1296         option = po_get(options, "mountproto");
1297         if (option) {
1298                 if (strcmp(option, "tcp") == 0)
1299                         return IPPROTO_TCP;
1300                 if (strcmp(option, "udp") == 0)
1301                         return IPPROTO_UDP;
1302         }
1303
1304         return nfs_nfs_protocol(options);
1305 }
1306
1307 /*
1308  * Returns the mountd server's port number specified by the given
1309  * mount options, or zero if all fails.  Zero results in a portmap
1310  * query to discover the server's mountd service port.
1311  *
1312  * port=0 will guarantee an rpcbind request precedes the mount
1313  * RPC so the client can determine the server's port number.
1314  */
1315 static unsigned short nfs_mount_port(struct mount_options *options)
1316 {
1317         long tmp;
1318
1319         if (po_get_numeric(options, "mountport", &tmp) == PO_FOUND)
1320                 if (tmp >= 0 && tmp <= 65535)
1321                         return tmp;
1322         return 0;
1323 }
1324
1325 /**
1326  * nfs_options2pmap - set up pmap structs based on mount options
1327  * @options: pointer to mount options
1328  * @nfs_pmap: OUT: pointer to pmap arguments for NFS server
1329  * @mnt_pmap: OUT: pointer to pmap arguments for mountd server
1330  *
1331  */
1332 void nfs_options2pmap(struct mount_options *options,
1333                       struct pmap *nfs_pmap, struct pmap *mnt_pmap)
1334 {
1335         nfs_pmap->pm_prog = nfs_nfs_program(options);
1336         nfs_pmap->pm_vers = nfs_nfs_version(options);
1337         nfs_pmap->pm_prot = nfs_nfs_protocol(options);
1338         nfs_pmap->pm_port = nfs_nfs_port(options);
1339
1340         mnt_pmap->pm_prog = nfs_mount_program(options);
1341         mnt_pmap->pm_vers = nfs_mount_version(options);
1342         mnt_pmap->pm_prot = nfs_mount_protocol(options);
1343         mnt_pmap->pm_port = nfs_mount_port(options);
1344 }