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