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