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