]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sbin/mount_nfs/mount_nfs.c
merge fix for boot-time hang on centos' xen
[FreeBSD/FreeBSD.git] / sbin / mount_nfs / mount_nfs.c
1 /*
2  * Copyright (c) 1992, 1993, 1994
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Rick Macklem at The University of Guelph.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 #if 0
34 #ifndef lint
35 static const char copyright[] =
36 "@(#) Copyright (c) 1992, 1993, 1994\n\
37         The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39
40 #ifndef lint
41 static char sccsid[] = "@(#)mount_nfs.c 8.11 (Berkeley) 5/4/95";
42 #endif /* not lint */
43 #endif
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46
47 #include <sys/param.h>
48 #include <sys/mount.h>
49 #include <sys/socket.h>
50 #include <sys/stat.h>
51 #include <sys/syslog.h>
52
53 #include <rpc/rpc.h>
54 #include <rpc/pmap_clnt.h>
55 #include <rpc/pmap_prot.h>
56
57 #include <nfs/rpcv2.h>
58 #include <nfs/nfsproto.h>
59 #include <nfsclient/nfs.h>
60 #include <nfsclient/nfsargs.h>
61
62 #include <arpa/inet.h>
63
64 #include <ctype.h>
65 #include <err.h>
66 #include <errno.h>
67 #include <fcntl.h>
68 #include <netdb.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #include <string.h>
72 #include <strings.h>
73 #include <sysexits.h>
74 #include <unistd.h>
75
76 #include "mntopts.h"
77 #include "mounttab.h"
78
79 #define ALTF_BG         0x1
80 #define ALTF_NOCONN     0x2
81 #define ALTF_DUMBTIMR   0x4
82 #define ALTF_INTR       0x8
83 #define ALTF_NFSV3      0x20
84 #define ALTF_RDIRPLUS   0x40
85 #define ALTF_MNTUDP     0x80
86 #define ALTF_RESVPORT   0x100
87 #define ALTF_SEQPACKET  0x200
88 #define ALTF_SOFT       0x800
89 #define ALTF_TCP        0x1000
90 #define ALTF_PORT       0x2000
91 #define ALTF_NFSV2      0x4000
92 #define ALTF_ACREGMIN   0x8000
93 #define ALTF_ACREGMAX   0x10000
94 #define ALTF_ACDIRMIN   0x20000
95 #define ALTF_ACDIRMAX   0x40000
96 #define ALTF_NOLOCKD    0x80000
97 #define ALTF_NOINET4    0x100000
98 #define ALTF_NOINET6    0x200000
99
100 struct mntopt mopts[] = {
101         MOPT_STDOPTS,
102         MOPT_FORCE,
103         MOPT_UPDATE,
104         MOPT_ASYNC,
105         { "bg", 0, ALTF_BG, 1 },
106         { "fg", 1, ALTF_BG, 1 },
107         { "conn", 1, ALTF_NOCONN, 1 },
108         { "dumbtimer", 0, ALTF_DUMBTIMR, 1 },
109         { "intr", 0, ALTF_INTR, 1 },
110         { "nfsv3", 0, ALTF_NFSV3, 1 },
111         { "rdirplus", 0, ALTF_RDIRPLUS, 1 },
112         { "mntudp", 0, ALTF_MNTUDP, 1 },
113         { "resvport", 0, ALTF_RESVPORT, 1 },
114         { "soft", 0, ALTF_SOFT, 1 },
115         { "hard", 1, ALTF_SOFT, 1 },
116         { "tcp", 0, ALTF_TCP, 1 },
117         { "port=", 0, ALTF_PORT, 1 },
118         { "nfsv2", 0, ALTF_NFSV2, 1 },
119         { "acregmin=", 0, ALTF_ACREGMIN, 1 },
120         { "acregmax=", 0, ALTF_ACREGMAX, 1 },
121         { "acdirmin=", 0, ALTF_ACDIRMIN, 1 },
122         { "acdirmax=", 0, ALTF_ACDIRMAX, 1 },
123         { "lockd", 1, ALTF_NOLOCKD, 1 },
124         { "inet4", 1, ALTF_NOINET4, 1 },
125         { "inet6", 1, ALTF_NOINET6, 1 },
126         MOPT_END
127 };
128
129 struct nfs_args nfsdefargs = {
130         NFS_ARGSVERSION,
131         NULL,
132         sizeof (struct sockaddr_in),
133         SOCK_DGRAM,
134         0,
135         NULL,
136         0,
137         NFSMNT_RESVPORT,
138         NFS_WSIZE,
139         NFS_RSIZE,
140         NFS_READDIRSIZE,
141         10,
142         NFS_RETRANS,
143         NFS_MAXGRPS,
144         NFS_DEFRAHEAD,
145         0,                      /* was: NQ_DEFLEASE */
146         NFS_MAXDEADTHRESH,      /* was: NQ_DEADTHRESH */
147         NULL,
148         /* args version 4 */
149         NFS_MINATTRTIMO,
150         NFS_MAXATTRTIMO,
151         NFS_MINDIRATTRTIMO,
152         NFS_MAXDIRATTRTIMO,
153 };
154
155 /* Table for af,sotype -> netid conversions. */
156 struct nc_protos {
157         char *netid;
158         int af;
159         int sotype;
160 } nc_protos[] = {
161         {"udp",         AF_INET,        SOCK_DGRAM},
162         {"tcp",         AF_INET,        SOCK_STREAM},
163         {"udp6",        AF_INET6,       SOCK_DGRAM},
164         {"tcp6",        AF_INET6,       SOCK_STREAM},
165         {NULL}
166 };
167
168 struct nfhret {
169         u_long          stat;
170         long            vers;
171         long            auth;
172         long            fhsize;
173         u_char          nfh[NFSX_V3FHMAX];
174 };
175 #define BGRND   1
176 #define ISBGRND 2
177 #define OF_NOINET4      4
178 #define OF_NOINET6      8
179 int retrycnt = -1;
180 int opflags = 0;
181 int nfsproto = IPPROTO_UDP;
182 int mnttcp_ok = 1;
183 char *portspec = NULL;  /* Server nfs port; NULL means look up via rpcbind. */
184 enum mountmode {
185         ANY,
186         V2,
187         V3
188 } mountmode = ANY;
189
190 /* Return codes for nfs_tryproto. */
191 enum tryret {
192         TRYRET_SUCCESS,
193         TRYRET_TIMEOUT,         /* No response received. */
194         TRYRET_REMOTEERR,       /* Error received from remote server. */
195         TRYRET_LOCALERR         /* Local failure. */
196 };
197
198 int     getnfsargs(char *, struct nfs_args *);
199 /* void set_rpc_maxgrouplist(int); */
200 struct netconfig *getnetconf_cached(const char *netid);
201 char    *netidbytype(int af, int sotype);
202 void    usage(void) __dead2;
203 int     xdr_dir(XDR *, char *);
204 int     xdr_fh(XDR *, struct nfhret *);
205 enum tryret nfs_tryproto(struct nfs_args *nfsargsp, struct addrinfo *ai,
206     char *hostp, char *spec, char **errstr);
207 enum tryret returncode(enum clnt_stat stat, struct rpc_err *rpcerr);
208
209 /*
210  * Used to set mount flags with getmntopts.  Call with dir=TRUE to
211  * initialize altflags from the current mount flags.  Call with
212  * dir=FALSE to update mount flags with the new value of altflags after
213  * the call to getmntopts.
214  */
215 static void
216 set_flags(int* altflags, int* nfsflags, int dir)
217 {
218 #define F2(af, nf)                                      \
219         if (dir) {                                      \
220                 if (*nfsflags & NFSMNT_##nf)            \
221                         *altflags |= ALTF_##af;         \
222                 else                                    \
223                         *altflags &= ~ALTF_##af;        \
224         } else {                                        \
225                 if (*altflags & ALTF_##af)              \
226                         *nfsflags |= NFSMNT_##nf;       \
227                 else                                    \
228                         *nfsflags &= ~NFSMNT_##nf;      \
229         }
230 #define F(f)    F2(f,f)
231
232         F(NOCONN);
233         F(DUMBTIMR);
234         F2(INTR, INT);
235         F(RDIRPLUS);
236         F(RESVPORT);
237         F(SOFT);
238         F(ACREGMIN);
239         F(ACREGMAX);
240         F(ACDIRMIN);
241         F(ACDIRMAX);
242         F(NOLOCKD);
243
244 #undef F
245 #undef F2
246 }
247
248 int
249 main(argc, argv)
250         int argc;
251         char *argv[];
252 {
253         int c;
254         struct nfs_args *nfsargsp;
255         struct nfs_args nfsargs;
256         int mntflags, altflags, num;
257         char *name, *p, *spec;
258         char mntpath[MAXPATHLEN];
259
260         mntflags = 0;
261         altflags = 0;
262         nfsargs = nfsdefargs;
263         nfsargsp = &nfsargs;
264         while ((c = getopt(argc, argv,
265             "23a:bcdD:g:I:iLlNo:PR:r:sTt:w:x:U")) != -1)
266                 switch (c) {
267                 case '2':
268                         mountmode = V2;
269                         break;
270                 case '3':
271                         mountmode = V3;
272                         break;
273                 case 'a':
274                         num = strtol(optarg, &p, 10);
275                         if (*p || num < 0)
276                                 errx(1, "illegal -a value -- %s", optarg);
277                         nfsargsp->readahead = num;
278                         nfsargsp->flags |= NFSMNT_READAHEAD;
279                         break;
280                 case 'b':
281                         opflags |= BGRND;
282                         break;
283                 case 'c':
284                         nfsargsp->flags |= NFSMNT_NOCONN;
285                         break;
286                 case 'D':
287                         num = strtol(optarg, &p, 10);
288                         if (*p || num <= 0)
289                                 errx(1, "illegal -D value -- %s", optarg);
290                         nfsargsp->deadthresh = num;
291                         nfsargsp->flags |= NFSMNT_DEADTHRESH;
292                         break;
293                 case 'd':
294                         nfsargsp->flags |= NFSMNT_DUMBTIMR;
295                         break;
296 #if 0 /* XXXX */
297                 case 'g':
298                         num = strtol(optarg, &p, 10);
299                         if (*p || num <= 0)
300                                 errx(1, "illegal -g value -- %s", optarg);
301                         set_rpc_maxgrouplist(num);
302                         nfsargsp->maxgrouplist = num;
303                         nfsargsp->flags |= NFSMNT_MAXGRPS;
304                         break;
305 #endif
306                 case 'I':
307                         num = strtol(optarg, &p, 10);
308                         if (*p || num <= 0)
309                                 errx(1, "illegal -I value -- %s", optarg);
310                         nfsargsp->readdirsize = num;
311                         nfsargsp->flags |= NFSMNT_READDIRSIZE;
312                         break;
313                 case 'i':
314                         nfsargsp->flags |= NFSMNT_INT;
315                         break;
316                 case 'L':
317                         nfsargsp->flags |= NFSMNT_NOLOCKD;
318                         break;
319                 case 'l':
320                         nfsargsp->flags |= NFSMNT_RDIRPLUS;
321                         break;
322                 case 'N':
323                         nfsargsp->flags &= ~NFSMNT_RESVPORT;
324                         break;
325                 case 'o':
326                         altflags = 0;
327                         set_flags(&altflags, &nfsargsp->flags, TRUE);
328                         if (mountmode == V2)
329                                 altflags |= ALTF_NFSV2;
330                         else if (mountmode == V3)
331                                 altflags |= ALTF_NFSV3;
332                         getmntopts(optarg, mopts, &mntflags, &altflags);
333                         set_flags(&altflags, &nfsargsp->flags, FALSE);
334                         /*
335                          * Handle altflags which don't map directly to
336                          * mount flags.
337                          */
338                         if (altflags & ALTF_BG)
339                                 opflags |= BGRND;
340                         if (altflags & ALTF_NOINET4)
341                                 opflags |= OF_NOINET4;
342                         if (altflags & ALTF_NOINET6)
343                                 opflags |= OF_NOINET6;
344                         if (altflags & ALTF_MNTUDP)
345                                 mnttcp_ok = 0;
346                         if (altflags & ALTF_TCP) {
347                                 nfsargsp->sotype = SOCK_STREAM;
348                                 nfsproto = IPPROTO_TCP;
349                         }
350                         if (altflags & ALTF_PORT) {
351                                 /*
352                                  * XXX Converting from a string to an int
353                                  * and back again is silly, and we should
354                                  * allow /etc/services names.
355                                  */
356                                 p = strstr(optarg, "port=");
357                                 if (p) {
358                                         asprintf(&portspec, "%d",
359                                             atoi(p + 5));
360                                         if (portspec == NULL)
361                                                 err(1, "asprintf");
362                                 }
363                         }
364                         mountmode = ANY;
365                         if (altflags & ALTF_NFSV2)
366                                 mountmode = V2;
367                         if (altflags & ALTF_NFSV3)
368                                 mountmode = V3;
369                         if (altflags & ALTF_ACREGMIN) {
370                                 p = strstr(optarg, "acregmin=");
371                                 if (p)
372                                         nfsargsp->acregmin = atoi(p + 9);
373                         }
374                         if (altflags & ALTF_ACREGMAX) {
375                                 p = strstr(optarg, "acregmax=");
376                                 if (p)
377                                         nfsargsp->acregmax = atoi(p + 9);
378                         }
379                         if (altflags & ALTF_ACDIRMIN) {
380                                 p = strstr(optarg, "acdirmin=");
381                                 if (p)
382                                         nfsargsp->acdirmin = atoi(p + 9);
383                         }
384                         if (altflags & ALTF_ACDIRMAX) {
385                                 p = strstr(optarg, "acdirmax=");
386                                 if (p)
387                                         nfsargsp->acdirmax = atoi(p + 9);
388                         }
389                         break;
390                 case 'P':
391                         /* obsolete for NFSMNT_RESVPORT, now default */
392                         break;
393                 case 'R':
394                         num = strtol(optarg, &p, 10);
395                         if (*p || num < 0)
396                                 errx(1, "illegal -R value -- %s", optarg);
397                         retrycnt = num;
398                         break;
399                 case 'r':
400                         num = strtol(optarg, &p, 10);
401                         if (*p || num <= 0)
402                                 errx(1, "illegal -r value -- %s", optarg);
403                         nfsargsp->rsize = num;
404                         nfsargsp->flags |= NFSMNT_RSIZE;
405                         break;
406                 case 's':
407                         nfsargsp->flags |= NFSMNT_SOFT;
408                         break;
409                 case 'T':
410                         nfsargsp->sotype = SOCK_STREAM;
411                         nfsproto = IPPROTO_TCP;
412                         break;
413                 case 't':
414                         num = strtol(optarg, &p, 10);
415                         if (*p || num <= 0)
416                                 errx(1, "illegal -t value -- %s", optarg);
417                         nfsargsp->timeo = num;
418                         nfsargsp->flags |= NFSMNT_TIMEO;
419                         break;
420                 case 'w':
421                         num = strtol(optarg, &p, 10);
422                         if (*p || num <= 0)
423                                 errx(1, "illegal -w value -- %s", optarg);
424                         nfsargsp->wsize = num;
425                         nfsargsp->flags |= NFSMNT_WSIZE;
426                         break;
427                 case 'x':
428                         num = strtol(optarg, &p, 10);
429                         if (*p || num <= 0)
430                                 errx(1, "illegal -x value -- %s", optarg);
431                         nfsargsp->retrans = num;
432                         nfsargsp->flags |= NFSMNT_RETRANS;
433                         break;
434                 case 'U':
435                         mnttcp_ok = 0;
436                         break;
437                 default:
438                         usage();
439                         break;
440                 }
441         argc -= optind;
442         argv += optind;
443
444         if (argc != 2) {
445                 usage();
446                 /* NOTREACHED */
447         }
448
449         spec = *argv++;
450         name = *argv;
451
452         if (retrycnt == -1)
453                 /* The default is to keep retrying forever. */
454                 retrycnt = 0;
455         if (!getnfsargs(spec, nfsargsp))
456                 exit(1);
457
458         /* resolve the mountpoint with realpath(3) */
459         (void)checkpath(name, mntpath);
460
461         if (mount("nfs", mntpath, mntflags, nfsargsp))
462                 err(1, "%s", mntpath);
463
464         exit(0);
465 }
466
467 int
468 getnfsargs(spec, nfsargsp)
469         char *spec;
470         struct nfs_args *nfsargsp;
471 {
472         struct addrinfo hints, *ai_nfs, *ai;
473         enum tryret ret;
474         int ecode, speclen, remoteerr;
475         char *hostp, *delimp, *errstr;
476         size_t len;
477         static char nam[MNAMELEN + 1];
478
479         if ((delimp = strrchr(spec, ':')) != NULL) {
480                 hostp = spec;
481                 spec = delimp + 1;
482         } else if ((delimp = strrchr(spec, '@')) != NULL) {
483                 warnx("path@server syntax is deprecated, use server:path");
484                 hostp = delimp + 1;
485         } else {
486                 warnx("no <host>:<dirpath> nfs-name");
487                 return (0);
488         }
489         *delimp = '\0';
490
491         /*
492          * If there has been a trailing slash at mounttime it seems
493          * that some mountd implementations fail to remove the mount
494          * entries from their mountlist while unmounting.
495          */
496         for (speclen = strlen(spec); 
497                 speclen > 1 && spec[speclen - 1] == '/';
498                 speclen--)
499                 spec[speclen - 1] = '\0';
500         if (strlen(hostp) + strlen(spec) + 1 > MNAMELEN) {
501                 warnx("%s:%s: %s", hostp, spec, strerror(ENAMETOOLONG));
502                 return (0);
503         }
504         /* Make both '@' and ':' notations equal */
505         if (*hostp != '\0') {
506                 len = strlen(hostp);
507                 memmove(nam, hostp, len);
508                 nam[len] = ':';
509                 memmove(nam + len + 1, spec, speclen);
510                 nam[len + speclen + 1] = '\0';
511         }
512
513         /*
514          * Handle an internet host address.
515          */
516         memset(&hints, 0, sizeof hints);
517         hints.ai_flags = AI_NUMERICHOST;
518         hints.ai_socktype = nfsargsp->sotype;
519         if (getaddrinfo(hostp, portspec, &hints, &ai_nfs) != 0) {
520                 hints.ai_flags = 0;
521                 if ((ecode = getaddrinfo(hostp, portspec, &hints, &ai_nfs))
522                     != 0) {
523                         if (portspec == NULL)
524                                 errx(1, "%s: %s", hostp, gai_strerror(ecode));
525                         else
526                                 errx(1, "%s:%s: %s", hostp, portspec,
527                                     gai_strerror(ecode));
528                         return (0);
529                 }
530         }
531
532         ret = TRYRET_LOCALERR;
533         for (;;) {
534                 /*
535                  * Try each entry returned by getaddrinfo(). Note the
536                  * occurence of remote errors by setting `remoteerr'.
537                  */
538                 remoteerr = 0;
539                 for (ai = ai_nfs; ai != NULL; ai = ai->ai_next) {
540                         if ((ai->ai_family == AF_INET6) &&
541                             (opflags & OF_NOINET6))
542                                 continue;
543                         if ((ai->ai_family == AF_INET) && 
544                             (opflags & OF_NOINET4))
545                                 continue;
546                         ret = nfs_tryproto(nfsargsp, ai, hostp, spec, &errstr);
547                         if (ret == TRYRET_SUCCESS)
548                                 break;
549                         if (ret != TRYRET_LOCALERR)
550                                 remoteerr = 1;
551                         if ((opflags & ISBGRND) == 0)
552                                 fprintf(stderr, "%s\n", errstr);
553                 }
554                 if (ret == TRYRET_SUCCESS)
555                         break;
556
557                 /* Exit if all errors were local. */
558                 if (!remoteerr)
559                         exit(1);
560
561                 /*
562                  * If retrycnt == 0, we are to keep retrying forever.
563                  * Otherwise decrement it, and exit if it hits zero.
564                  */
565                 if (retrycnt != 0 && --retrycnt == 0)
566                         exit(1);
567
568                 if ((opflags & (BGRND | ISBGRND)) == BGRND) {
569                         warnx("Cannot immediately mount %s:%s, backgrounding",
570                             hostp, spec);
571                         opflags |= ISBGRND;
572                         if (daemon(0, 0) != 0)
573                                 err(1, "daemon");
574                 }
575                 sleep(60);
576         }
577         freeaddrinfo(ai_nfs);
578         nfsargsp->hostname = nam;
579         /* Add mounted file system to PATH_MOUNTTAB */
580         if (!add_mtab(hostp, spec))
581                 warnx("can't update %s for %s:%s", PATH_MOUNTTAB, hostp, spec);
582         return (1);
583 }
584
585 /*
586  * Try to set up the NFS arguments according to the address
587  * family, protocol (and possibly port) specified in `ai'.
588  *
589  * Returns TRYRET_SUCCESS if successful, or:
590  *   TRYRET_TIMEOUT             The server did not respond.
591  *   TRYRET_REMOTEERR           The server reported an error.
592  *   TRYRET_LOCALERR            Local failure.
593  *
594  * In all error cases, *errstr will be set to a statically-allocated string
595  * describing the error.
596  */
597 enum tryret
598 nfs_tryproto(struct nfs_args *nfsargsp, struct addrinfo *ai, char *hostp,
599     char *spec, char **errstr)
600 {
601         static char errbuf[256];
602         struct sockaddr_storage nfs_ss;
603         struct netbuf nfs_nb;
604         struct nfhret nfhret;
605         struct timeval try;
606         struct rpc_err rpcerr;
607         CLIENT *clp;
608         struct netconfig *nconf, *nconf_mnt;
609         char *netid, *netid_mnt;
610         int doconnect, nfsvers, mntvers;
611         enum clnt_stat stat;
612         enum mountmode trymntmode;
613
614         trymntmode = mountmode;
615         errbuf[0] = '\0';
616         *errstr = errbuf;
617
618         if ((netid = netidbytype(ai->ai_family, nfsargsp->sotype)) == NULL) {
619                 snprintf(errbuf, sizeof errbuf,
620                     "af %d sotype %d not supported", ai->ai_family,
621                     nfsargsp->sotype);
622                 return (TRYRET_LOCALERR);
623         }
624         if ((nconf = getnetconf_cached(netid)) == NULL) {
625                 snprintf(errbuf, sizeof errbuf, "%s: %s", netid, nc_sperror());
626                 return (TRYRET_LOCALERR);
627         }
628         /* The RPCPROG_MNT netid may be different. */
629         if (mnttcp_ok) {
630                 netid_mnt = netid;
631                 nconf_mnt = nconf;
632         } else {
633                 if ((netid_mnt = netidbytype(ai->ai_family, SOCK_DGRAM))
634                      == NULL) {
635                         snprintf(errbuf, sizeof errbuf,
636                             "af %d sotype SOCK_DGRAM not supported",
637                              ai->ai_family);
638                         return (TRYRET_LOCALERR);
639                 }
640                 if ((nconf_mnt = getnetconf_cached(netid_mnt)) == NULL) {
641                         snprintf(errbuf, sizeof errbuf, "%s: %s", netid_mnt,
642                             nc_sperror());
643                         return (TRYRET_LOCALERR);
644                 }
645         }
646
647 tryagain:
648         if (trymntmode == V2) {
649                 nfsvers = 2;
650                 mntvers = 1;
651         } else {
652                 nfsvers = 3;
653                 mntvers = 3;
654         }
655
656         if (portspec != NULL) {
657                 /* `ai' contains the complete nfsd sockaddr. */
658                 nfs_nb.buf = ai->ai_addr;
659                 nfs_nb.len = nfs_nb.maxlen = ai->ai_addrlen;
660         } else {
661                 /* Ask the remote rpcbind. */
662                 nfs_nb.buf = &nfs_ss;
663                 nfs_nb.len = nfs_nb.maxlen = sizeof nfs_ss;
664
665                 if (!rpcb_getaddr(RPCPROG_NFS, nfsvers, nconf, &nfs_nb,
666                     hostp)) {
667                         if (rpc_createerr.cf_stat == RPC_PROGVERSMISMATCH &&
668                             trymntmode == ANY) {
669                                 trymntmode = V2;
670                                 goto tryagain;
671                         }
672                         snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s",
673                             netid, hostp, spec,
674                             clnt_spcreateerror("RPCPROG_NFS"));
675                         return (returncode(rpc_createerr.cf_stat,
676                             &rpc_createerr.cf_error));
677                 }
678         }
679
680         /* Check that the server (nfsd) responds on the port we have chosen. */
681         clp = clnt_tli_create(RPC_ANYFD, nconf, &nfs_nb, RPCPROG_NFS, nfsvers,
682             0, 0);
683         if (clp == NULL) {
684                 snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s", netid,
685                     hostp, spec, clnt_spcreateerror("nfsd: RPCPROG_NFS"));
686                 return (returncode(rpc_createerr.cf_stat,
687                     &rpc_createerr.cf_error));
688         }
689         if (nfsargsp->sotype == SOCK_DGRAM &&
690             !(nfsargsp->flags & NFSMNT_NOCONN)) {
691                 /*
692                  * Use connect(), to match what the kernel does. This
693                  * catches cases where the server responds from the
694                  * wrong source address.
695                  */
696                 doconnect = 1;
697                 if (!clnt_control(clp, CLSET_CONNECT, (char *)&doconnect)) {
698                         clnt_destroy(clp);
699                         snprintf(errbuf, sizeof errbuf,
700                             "[%s] %s:%s: CLSET_CONNECT failed", netid, hostp,
701                             spec);
702                         return (TRYRET_LOCALERR);
703                 }
704         }
705
706         try.tv_sec = 10;
707         try.tv_usec = 0;
708         stat = clnt_call(clp, NFSPROC_NULL, (xdrproc_t)xdr_void, NULL,
709                          (xdrproc_t)xdr_void, NULL,
710             try);
711         if (stat != RPC_SUCCESS) {
712                 if (stat == RPC_PROGVERSMISMATCH && trymntmode == ANY) {
713                         clnt_destroy(clp);
714                         trymntmode = V2;
715                         goto tryagain;
716                 }
717                 clnt_geterr(clp, &rpcerr);
718                 snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s", netid,
719                     hostp, spec, clnt_sperror(clp, "NFSPROC_NULL"));
720                 clnt_destroy(clp);
721                 return (returncode(stat, &rpcerr));
722         }
723         clnt_destroy(clp);
724
725         /* Send the RPCMNT_MOUNT RPC to get the root filehandle. */
726         try.tv_sec = 10;
727         try.tv_usec = 0;
728         clp = clnt_tp_create(hostp, RPCPROG_MNT, mntvers, nconf_mnt);
729         if (clp == NULL) {
730                 snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s", netid_mnt,
731                     hostp, spec, clnt_spcreateerror("RPCMNT: clnt_create"));
732                 return (returncode(rpc_createerr.cf_stat,
733                     &rpc_createerr.cf_error));
734         }
735         clp->cl_auth = authsys_create_default();
736         nfhret.auth = RPCAUTH_UNIX;
737         nfhret.vers = mntvers;
738         stat = clnt_call(clp, RPCMNT_MOUNT, (xdrproc_t)xdr_dir, spec, 
739                          (xdrproc_t)xdr_fh, &nfhret,
740             try);
741         auth_destroy(clp->cl_auth);
742         if (stat != RPC_SUCCESS) {
743                 if (stat == RPC_PROGVERSMISMATCH && trymntmode == ANY) {
744                         clnt_destroy(clp);
745                         trymntmode = V2;
746                         goto tryagain;
747                 }
748                 clnt_geterr(clp, &rpcerr);
749                 snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s", netid_mnt,
750                     hostp, spec, clnt_sperror(clp, "RPCPROG_MNT"));
751                 clnt_destroy(clp);
752                 return (returncode(stat, &rpcerr));
753         }
754         clnt_destroy(clp);
755
756         if (nfhret.stat != 0) {
757                 snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s", netid_mnt,
758                     hostp, spec, strerror(nfhret.stat));
759                 return (TRYRET_REMOTEERR);
760         }
761
762         /*
763          * Store the filehandle and server address in nfsargsp, making
764          * sure to copy any locally allocated structures.
765          */
766         nfsargsp->addrlen = nfs_nb.len;
767         nfsargsp->addr = malloc(nfsargsp->addrlen);
768         nfsargsp->fhsize = nfhret.fhsize;
769         nfsargsp->fh = malloc(nfsargsp->fhsize);
770         if (nfsargsp->addr == NULL || nfsargsp->fh == NULL)
771                 err(1, "malloc");
772         bcopy(nfs_nb.buf, nfsargsp->addr, nfsargsp->addrlen);
773         bcopy(nfhret.nfh, nfsargsp->fh, nfsargsp->fhsize);
774
775         if (nfsvers == 3)
776                 nfsargsp->flags |= NFSMNT_NFSV3;
777         else
778                 nfsargsp->flags &= ~NFSMNT_NFSV3;
779
780         return (TRYRET_SUCCESS);
781 }
782
783
784 /*
785  * Catagorise a RPC return status and error into an `enum tryret'
786  * return code.
787  */
788 enum tryret
789 returncode(enum clnt_stat stat, struct rpc_err *rpcerr)
790 {
791         switch (stat) {
792         case RPC_TIMEDOUT:
793                 return (TRYRET_TIMEOUT);
794         case RPC_PMAPFAILURE:
795         case RPC_PROGNOTREGISTERED:
796         case RPC_PROGVERSMISMATCH:
797         /* XXX, these can be local or remote. */
798         case RPC_CANTSEND:
799         case RPC_CANTRECV:
800                 return (TRYRET_REMOTEERR);
801         case RPC_SYSTEMERROR:
802                 switch (rpcerr->re_errno) {
803                 case ETIMEDOUT:
804                         return (TRYRET_TIMEOUT);
805                 case ENOMEM:
806                         break;
807                 default:
808                         return (TRYRET_REMOTEERR);
809                 }
810                 /* FALLTHROUGH */
811         default:
812                 break;
813         }
814         return (TRYRET_LOCALERR);
815 }
816
817 /*
818  * Look up a netid based on an address family and socket type.
819  * `af' is the address family, and `sotype' is SOCK_DGRAM or SOCK_STREAM.
820  *
821  * XXX there should be a library function for this.
822  */
823 char *
824 netidbytype(int af, int sotype) {
825         struct nc_protos *p;
826
827         for (p = nc_protos; p->netid != NULL; p++) {
828                 if (af != p->af || sotype != p->sotype)
829                         continue;
830                 return (p->netid);
831         }
832         return (NULL);
833 }
834
835 /*
836  * Look up a netconfig entry based on a netid, and cache the result so
837  * that we don't need to remember to call freenetconfigent().
838  *
839  * Otherwise it behaves just like getnetconfigent(), so nc_*error()
840  * work on failure.
841  */
842 struct netconfig *
843 getnetconf_cached(const char *netid) {
844         static struct nc_entry {
845                 struct netconfig *nconf;
846                 struct nc_entry *next;
847         } *head;
848         struct nc_entry *p;
849         struct netconfig *nconf;
850
851         for (p = head; p != NULL; p = p->next)
852                 if (strcmp(netid, p->nconf->nc_netid) == 0)
853                         return (p->nconf);
854
855         if ((nconf = getnetconfigent(netid)) == NULL)
856                 return (NULL);
857         if ((p = malloc(sizeof(*p))) == NULL)
858                 err(1, "malloc");
859         p->nconf = nconf;
860         p->next = head;
861         head = p;
862
863         return (p->nconf);
864 }
865
866 /*
867  * xdr routines for mount rpc's
868  */
869 int
870 xdr_dir(xdrsp, dirp)
871         XDR *xdrsp;
872         char *dirp;
873 {
874         return (xdr_string(xdrsp, &dirp, RPCMNT_PATHLEN));
875 }
876
877 int
878 xdr_fh(xdrsp, np)
879         XDR *xdrsp;
880         struct nfhret *np;
881 {
882         int i;
883         long auth, authcnt, authfnd = 0;
884
885         if (!xdr_u_long(xdrsp, &np->stat))
886                 return (0);
887         if (np->stat)
888                 return (1);
889         switch (np->vers) {
890         case 1:
891                 np->fhsize = NFSX_V2FH;
892                 return (xdr_opaque(xdrsp, (caddr_t)np->nfh, NFSX_V2FH));
893         case 3:
894                 if (!xdr_long(xdrsp, &np->fhsize))
895                         return (0);
896                 if (np->fhsize <= 0 || np->fhsize > NFSX_V3FHMAX)
897                         return (0);
898                 if (!xdr_opaque(xdrsp, (caddr_t)np->nfh, np->fhsize))
899                         return (0);
900                 if (!xdr_long(xdrsp, &authcnt))
901                         return (0);
902                 for (i = 0; i < authcnt; i++) {
903                         if (!xdr_long(xdrsp, &auth))
904                                 return (0);
905                         if (auth == np->auth)
906                                 authfnd++;
907                 }
908                 /*
909                  * Some servers, such as DEC's OSF/1 return a nil authenticator
910                  * list to indicate RPCAUTH_UNIX.
911                  */
912                 if (!authfnd && (authcnt > 0 || np->auth != RPCAUTH_UNIX))
913                         np->stat = EAUTH;
914                 return (1);
915         };
916         return (0);
917 }
918
919 void
920 usage()
921 {
922         (void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
923 "usage: mount_nfs [-23bcdiLlNPsTU] [-a maxreadahead] [-D deadthresh]",
924 "                 [-g maxgroups] [-I readdirsize] [-o options] [-R retrycnt]",
925 "                 [-r readsize] [-t timeout] [-w writesize] [-x retrans]",
926 "                 rhost:path node");
927         exit(1);
928 }