xref: /freebsd/sbin/mount_nfs/mount_nfs.c (revision c4f6a2a9e1b1879b618c436ab4f56ff75c73a0f5)
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 				asprintf(&portspec, "%d",
348 				    atoi(strstr(optarg, "port=") + 5));
349 				if (portspec == NULL)
350 					err(1, "asprintf");
351 			}
352 			mountmode = ANY;
353 			if(altflags & ALTF_NFSV2)
354 				mountmode = V2;
355 			if(altflags & ALTF_NFSV3)
356 				mountmode = V3;
357 			if(altflags & ALTF_ACREGMIN)
358 				nfsargsp->acregmin = atoi(strstr(optarg,
359 				    "acregmin=") + 9);
360 			if(altflags & ALTF_ACREGMAX)
361 				nfsargsp->acregmax = atoi(strstr(optarg,
362 				    "acregmax=") + 9);
363 			if(altflags & ALTF_ACDIRMIN)
364 				nfsargsp->acdirmin = atoi(strstr(optarg,
365 				    "acdirmin=") + 9);
366 			if(altflags & ALTF_ACDIRMAX)
367 				nfsargsp->acdirmax = atoi(strstr(optarg,
368 				    "acdirmax=") + 9);
369 			break;
370 		case 'P':
371 			/* obsolete for NFSMNT_RESVPORT, now default */
372 			break;
373 		case 'R':
374 			num = strtol(optarg, &p, 10);
375 			if (*p || num < 0)
376 				errx(1, "illegal -R value -- %s", optarg);
377 			retrycnt = num;
378 			break;
379 		case 'r':
380 			num = strtol(optarg, &p, 10);
381 			if (*p || num <= 0)
382 				errx(1, "illegal -r value -- %s", optarg);
383 			nfsargsp->rsize = num;
384 			nfsargsp->flags |= NFSMNT_RSIZE;
385 			break;
386 		case 's':
387 			nfsargsp->flags |= NFSMNT_SOFT;
388 			break;
389 		case 'T':
390 			nfsargsp->sotype = SOCK_STREAM;
391 			nfsproto = IPPROTO_TCP;
392 			break;
393 		case 't':
394 			num = strtol(optarg, &p, 10);
395 			if (*p || num <= 0)
396 				errx(1, "illegal -t value -- %s", optarg);
397 			nfsargsp->timeo = num;
398 			nfsargsp->flags |= NFSMNT_TIMEO;
399 			break;
400 		case 'w':
401 			num = strtol(optarg, &p, 10);
402 			if (*p || num <= 0)
403 				errx(1, "illegal -w value -- %s", optarg);
404 			nfsargsp->wsize = num;
405 			nfsargsp->flags |= NFSMNT_WSIZE;
406 			break;
407 		case 'x':
408 			num = strtol(optarg, &p, 10);
409 			if (*p || num <= 0)
410 				errx(1, "illegal -x value -- %s", optarg);
411 			nfsargsp->retrans = num;
412 			nfsargsp->flags |= NFSMNT_RETRANS;
413 			break;
414 		case 'U':
415 			mnttcp_ok = 0;
416 			break;
417 		default:
418 			usage();
419 			break;
420 		}
421 	argc -= optind;
422 	argv += optind;
423 
424 	if (argc != 2) {
425 		usage();
426 		/* NOTREACHED */
427 	}
428 
429 	spec = *argv++;
430 	name = *argv;
431 
432 	if (retrycnt == -1)
433 		/* The default is to keep retrying forever. */
434 		retrycnt = 0;
435 	if (!getnfsargs(spec, nfsargsp))
436 		exit(1);
437 
438 	/* resolve the mountpoint with realpath(3) */
439 	(void)checkpath(name, mntpath);
440 
441 	if (mount("nfs", mntpath, mntflags, nfsargsp))
442 		err(1, "%s", mntpath);
443 
444 	exit(0);
445 }
446 
447 int
448 getnfsargs(spec, nfsargsp)
449 	char *spec;
450 	struct nfs_args *nfsargsp;
451 {
452 	struct addrinfo hints, *ai_nfs, *ai;
453 	enum tryret ret;
454 	int ecode, speclen, remoteerr;
455 	char *hostp, *delimp, *errstr;
456 	size_t len;
457 	static char nam[MNAMELEN + 1];
458 
459 	if ((delimp = strrchr(spec, ':')) != NULL) {
460 		hostp = spec;
461 		spec = delimp + 1;
462 	} else if ((delimp = strrchr(spec, '@')) != NULL) {
463 		warnx("path@server syntax is deprecated, use server:path");
464 		hostp = delimp + 1;
465 	} else {
466 		warnx("no <host>:<dirpath> nfs-name");
467 		return (0);
468 	}
469 	*delimp = '\0';
470 
471 	/*
472 	 * If there has been a trailing slash at mounttime it seems
473 	 * that some mountd implementations fail to remove the mount
474 	 * entries from their mountlist while unmounting.
475 	 */
476 	for (speclen = strlen(spec);
477 		speclen > 1 && spec[speclen - 1] == '/';
478 		speclen--)
479 		spec[speclen - 1] = '\0';
480 	if (strlen(hostp) + strlen(spec) + 1 > MNAMELEN) {
481 		warnx("%s:%s: %s", hostp, spec, strerror(ENAMETOOLONG));
482 		return (0);
483 	}
484 	/* Make both '@' and ':' notations equal */
485 	if (*hostp != '\0') {
486 		len = strlen(hostp);
487 		memmove(nam, hostp, len);
488 		nam[len] = ':';
489 		memmove(nam + len + 1, spec, speclen);
490 		nam[len + speclen + 1] = '\0';
491 	}
492 
493 	/*
494 	 * Handle an internet host address.
495 	 */
496 	memset(&hints, 0, sizeof hints);
497 	hints.ai_flags = AI_NUMERICHOST;
498 	hints.ai_socktype = nfsargsp->sotype;
499 	if (getaddrinfo(hostp, portspec, &hints, &ai_nfs) != 0) {
500 		hints.ai_flags = 0;
501 		if ((ecode = getaddrinfo(hostp, portspec, &hints, &ai_nfs))
502 		    != 0) {
503 			if (portspec == NULL)
504 				errx(1, "%s: %s", hostp, gai_strerror(ecode));
505 			else
506 				errx(1, "%s:%s: %s", hostp, portspec,
507 				    gai_strerror(ecode));
508 			return (0);
509 		}
510 	}
511 
512 	ret = TRYRET_LOCALERR;
513 	for (;;) {
514 		/*
515 		 * Try each entry returned by getaddrinfo(). Note the
516 		 * occurence of remote errors by setting `remoteerr'.
517 		 */
518 		remoteerr = 0;
519 		for (ai = ai_nfs; ai != NULL; ai = ai->ai_next) {
520 			ret = nfs_tryproto(nfsargsp, ai, hostp, spec, &errstr);
521 			if (ret == TRYRET_SUCCESS)
522 				break;
523 			if (ret != TRYRET_LOCALERR)
524 				remoteerr = 1;
525 			if ((opflags & ISBGRND) == 0)
526 				fprintf(stderr, "%s\n", errstr);
527 		}
528 		if (ret == TRYRET_SUCCESS)
529 			break;
530 
531 		/* Exit if all errors were local. */
532 		if (!remoteerr)
533 			exit(1);
534 
535 		/*
536 		 * If retrycnt == 0, we are to keep retrying forever.
537 		 * Otherwise decrement it, and exit if it hits zero.
538 		 */
539 		if (retrycnt != 0 && --retrycnt == 0)
540 			exit(1);
541 
542 		if ((opflags & (BGRND | ISBGRND)) == BGRND) {
543 			warnx("Cannot immediately mount %s:%s, backgrounding",
544 			    hostp, spec);
545 			opflags |= ISBGRND;
546 			if (daemon(0, 0) != 0)
547 				err(1, "daemon");
548 		}
549 		sleep(60);
550 	}
551 	freeaddrinfo(ai_nfs);
552 	nfsargsp->hostname = nam;
553 	/* Add mounted file system to PATH_MOUNTTAB */
554 	if (!add_mtab(hostp, spec))
555 		warnx("can't update %s for %s:%s", PATH_MOUNTTAB, hostp, spec);
556 	return (1);
557 }
558 
559 /*
560  * Try to set up the NFS arguments according to the address
561  * family, protocol (and possibly port) specified in `ai'.
562  *
563  * Returns TRYRET_SUCCESS if successful, or:
564  *   TRYRET_TIMEOUT		The server did not respond.
565  *   TRYRET_REMOTEERR		The server reported an error.
566  *   TRYRET_LOCALERR		Local failure.
567  *
568  * In all error cases, *errstr will be set to a statically-allocated string
569  * describing the error.
570  */
571 enum tryret
572 nfs_tryproto(struct nfs_args *nfsargsp, struct addrinfo *ai, char *hostp,
573     char *spec, char **errstr)
574 {
575 	static char errbuf[256];
576 	struct sockaddr_storage nfs_ss;
577 	struct netbuf nfs_nb;
578 	struct nfhret nfhret;
579 	struct timeval try;
580 	struct rpc_err rpcerr;
581 	CLIENT *clp;
582 	struct netconfig *nconf, *nconf_mnt;
583 	char *netid, *netid_mnt;
584 	int doconnect, nfsvers, mntvers;
585 	enum clnt_stat stat;
586 	enum mountmode trymntmode;
587 
588 	trymntmode = mountmode;
589 	errbuf[0] = '\0';
590 	*errstr = errbuf;
591 
592 	if ((netid = netidbytype(ai->ai_family, nfsargsp->sotype)) == NULL) {
593 		snprintf(errbuf, sizeof errbuf,
594 		    "af %d sotype %d not supported", ai->ai_family,
595 		    nfsargsp->sotype);
596 		return (TRYRET_LOCALERR);
597 	}
598 	if ((nconf = getnetconf_cached(netid)) == NULL) {
599 		snprintf(errbuf, sizeof errbuf, "%s: %s", netid, nc_sperror());
600 		return (TRYRET_LOCALERR);
601 	}
602 	/* The RPCPROG_MNT netid may be different. */
603 	if (mnttcp_ok) {
604 		netid_mnt = netid;
605 		nconf_mnt = nconf;
606 	} else {
607 		if ((netid_mnt = netidbytype(ai->ai_family, SOCK_DGRAM))
608 		     == NULL) {
609 			snprintf(errbuf, sizeof errbuf,
610 			    "af %d sotype SOCK_DGRAM not supported",
611 			     ai->ai_family);
612 			return (TRYRET_LOCALERR);
613 		}
614 		if ((nconf_mnt = getnetconf_cached(netid_mnt)) == NULL) {
615 			snprintf(errbuf, sizeof errbuf, "%s: %s", netid_mnt,
616 			    nc_sperror());
617 			return (TRYRET_LOCALERR);
618 		}
619 	}
620 
621 tryagain:
622 	if (trymntmode == V2) {
623 		nfsvers = 2;
624 		mntvers = 1;
625 	} else {
626 		nfsvers = 3;
627 		mntvers = 3;
628 	}
629 
630 	if (portspec != NULL) {
631 		/* `ai' contains the complete nfsd sockaddr. */
632 		nfs_nb.buf = ai->ai_addr;
633 		nfs_nb.len = nfs_nb.maxlen = ai->ai_addrlen;
634 	} else {
635 		/* Ask the remote rpcbind. */
636 		nfs_nb.buf = &nfs_ss;
637 		nfs_nb.len = nfs_nb.maxlen = sizeof nfs_ss;
638 
639 		if (!rpcb_getaddr(RPCPROG_NFS, nfsvers, nconf, &nfs_nb,
640 		    hostp)) {
641 			if (rpc_createerr.cf_stat == RPC_PROGVERSMISMATCH &&
642 			    trymntmode == ANY) {
643 				trymntmode = V2;
644 				goto tryagain;
645 			}
646 			snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s",
647 			    netid, hostp, spec,
648 			    clnt_spcreateerror("RPCPROG_NFS"));
649 			return (returncode(rpc_createerr.cf_stat,
650 			    &rpc_createerr.cf_error));
651 		}
652 	}
653 
654 	/* Check that the server (nfsd) responds on the port we have chosen. */
655 	clp = clnt_tli_create(RPC_ANYFD, nconf, &nfs_nb, RPCPROG_NFS, nfsvers,
656 	    0, 0);
657 	if (clp == NULL) {
658 		snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s", netid,
659 		    hostp, spec, clnt_spcreateerror("nfsd: RPCPROG_NFS"));
660 		return (returncode(rpc_createerr.cf_stat,
661 		    &rpc_createerr.cf_error));
662 	}
663 	if (nfsargsp->sotype == SOCK_DGRAM) {
664 		/*
665 		 * Use connect(), to match what the kernel does. This
666 		 * catches cases where the server responds from the
667 		 * wrong source address.
668 		 */
669 		doconnect = 1;
670 		if (!clnt_control(clp, CLSET_CONNECT, (char *)&doconnect)) {
671 			clnt_destroy(clp);
672 			snprintf(errbuf, sizeof errbuf,
673 			    "[%s] %s:%s: CLSET_CONNECT failed", netid, hostp,
674 			    spec);
675 			return (TRYRET_LOCALERR);
676 		}
677 	}
678 
679 	try.tv_sec = 10;
680 	try.tv_usec = 0;
681 	stat = clnt_call(clp, NFSPROC_NULL, xdr_void, NULL, xdr_void, NULL,
682 	    try);
683 	if (stat != RPC_SUCCESS) {
684 		if (stat == RPC_PROGVERSMISMATCH && trymntmode == ANY) {
685 			clnt_destroy(clp);
686 			trymntmode = V2;
687 			goto tryagain;
688 		}
689 		clnt_geterr(clp, &rpcerr);
690 		snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s", netid,
691 		    hostp, spec, clnt_sperror(clp, "NFSPROC_NULL"));
692 		clnt_destroy(clp);
693 		return (returncode(stat, &rpcerr));
694 	}
695 	clnt_destroy(clp);
696 
697 	/* Send the RPCMNT_MOUNT RPC to get the root filehandle. */
698 	try.tv_sec = 10;
699 	try.tv_usec = 0;
700 	clp = clnt_tp_create(hostp, RPCPROG_MNT, mntvers, nconf_mnt);
701 	if (clp == NULL) {
702 		snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s", netid_mnt,
703 		    hostp, spec, clnt_spcreateerror("RPCMNT: clnt_create"));
704 		return (returncode(rpc_createerr.cf_stat,
705 		    &rpc_createerr.cf_error));
706 	}
707 	clp->cl_auth = authsys_create_default();
708 	nfhret.auth = RPCAUTH_UNIX;
709 	nfhret.vers = mntvers;
710 	stat = clnt_call(clp, RPCMNT_MOUNT, xdr_dir, spec, xdr_fh, &nfhret,
711 	    try);
712 	auth_destroy(clp->cl_auth);
713 	if (stat != RPC_SUCCESS) {
714 		if (stat == RPC_PROGVERSMISMATCH && trymntmode == ANY) {
715 			clnt_destroy(clp);
716 			trymntmode = V2;
717 			goto tryagain;
718 		}
719 		clnt_geterr(clp, &rpcerr);
720 		snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s", netid_mnt,
721 		    hostp, spec, clnt_sperror(clp, "RPCPROG_MNT"));
722 		clnt_destroy(clp);
723 		return (returncode(stat, &rpcerr));
724 	}
725 	clnt_destroy(clp);
726 
727 	if (nfhret.stat != 0) {
728 		snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s", netid_mnt,
729 		    hostp, spec, strerror(nfhret.stat));
730 		return (TRYRET_REMOTEERR);
731 	}
732 
733 	/*
734 	 * Store the filehandle and server address in nfsargsp, making
735 	 * sure to copy any locally allocated structures.
736 	 */
737 	nfsargsp->addrlen = nfs_nb.len;
738 	nfsargsp->addr = malloc(nfsargsp->addrlen);
739 	nfsargsp->fhsize = nfhret.fhsize;
740 	nfsargsp->fh = malloc(nfsargsp->fhsize);
741 	if (nfsargsp->addr == NULL || nfsargsp->fh == NULL)
742 		err(1, "malloc");
743 	bcopy(nfs_nb.buf, nfsargsp->addr, nfsargsp->addrlen);
744 	bcopy(nfhret.nfh, nfsargsp->fh, nfsargsp->fhsize);
745 
746 	if (nfsvers == 3)
747 		nfsargsp->flags |= NFSMNT_NFSV3;
748 	else
749 		nfsargsp->flags &= ~NFSMNT_NFSV3;
750 
751 	return (TRYRET_SUCCESS);
752 }
753 
754 
755 /*
756  * Catagorise a RPC return status and error into an `enum tryret'
757  * return code.
758  */
759 enum tryret
760 returncode(enum clnt_stat stat, struct rpc_err *rpcerr)
761 {
762 	switch (stat) {
763 	case RPC_TIMEDOUT:
764 		return (TRYRET_TIMEOUT);
765 	case RPC_PMAPFAILURE:
766 	case RPC_PROGNOTREGISTERED:
767 	case RPC_PROGVERSMISMATCH:
768 	/* XXX, these can be local or remote. */
769 	case RPC_CANTSEND:
770 	case RPC_CANTRECV:
771 		return (TRYRET_REMOTEERR);
772 	case RPC_SYSTEMERROR:
773 		switch (rpcerr->re_errno) {
774 		case ETIMEDOUT:
775 			return (TRYRET_TIMEOUT);
776 		case ENOMEM:
777 			break;
778 		default:
779 			return (TRYRET_REMOTEERR);
780 		}
781 		/* FALLTHROUGH */
782 	default:
783 		break;
784 	}
785 	return (TRYRET_LOCALERR);
786 }
787 
788 /*
789  * Look up a netid based on an address family and socket type.
790  * `af' is the address family, and `sotype' is SOCK_DGRAM or SOCK_STREAM.
791  *
792  * XXX there should be a library function for this.
793  */
794 char *
795 netidbytype(int af, int sotype) {
796 	struct nc_protos *p;
797 
798 	for (p = nc_protos; p->netid != NULL; p++) {
799 		if (af != p->af || sotype != p->sotype)
800 			continue;
801 		return (p->netid);
802 	}
803 	return (NULL);
804 }
805 
806 /*
807  * Look up a netconfig entry based on a netid, and cache the result so
808  * that we don't need to remember to call freenetconfigent().
809  *
810  * Otherwise it behaves just like getnetconfigent(), so nc_*error()
811  * work on failure.
812  */
813 struct netconfig *
814 getnetconf_cached(const char *netid) {
815 	static struct nc_entry {
816 		struct netconfig *nconf;
817 		struct nc_entry *next;
818 	} *head;
819 	struct nc_entry *p;
820 	struct netconfig *nconf;
821 
822 	for (p = head; p != NULL; p = p->next)
823 		if (strcmp(netid, p->nconf->nc_netid) == 0)
824 			return (p->nconf);
825 
826 	if ((nconf = getnetconfigent(netid)) == NULL)
827 		return (NULL);
828 	if ((p = malloc(sizeof(*p))) == NULL)
829 		err(1, "malloc");
830 	p->nconf = nconf;
831 	p->next = head;
832 	head = p;
833 
834 	return (p->nconf);
835 }
836 
837 /*
838  * xdr routines for mount rpc's
839  */
840 int
841 xdr_dir(xdrsp, dirp)
842 	XDR *xdrsp;
843 	char *dirp;
844 {
845 	return (xdr_string(xdrsp, &dirp, RPCMNT_PATHLEN));
846 }
847 
848 int
849 xdr_fh(xdrsp, np)
850 	XDR *xdrsp;
851 	struct nfhret *np;
852 {
853 	int i;
854 	long auth, authcnt, authfnd = 0;
855 
856 	if (!xdr_u_long(xdrsp, &np->stat))
857 		return (0);
858 	if (np->stat)
859 		return (1);
860 	switch (np->vers) {
861 	case 1:
862 		np->fhsize = NFSX_V2FH;
863 		return (xdr_opaque(xdrsp, (caddr_t)np->nfh, NFSX_V2FH));
864 	case 3:
865 		if (!xdr_long(xdrsp, &np->fhsize))
866 			return (0);
867 		if (np->fhsize <= 0 || np->fhsize > NFSX_V3FHMAX)
868 			return (0);
869 		if (!xdr_opaque(xdrsp, (caddr_t)np->nfh, np->fhsize))
870 			return (0);
871 		if (!xdr_long(xdrsp, &authcnt))
872 			return (0);
873 		for (i = 0; i < authcnt; i++) {
874 			if (!xdr_long(xdrsp, &auth))
875 				return (0);
876 			if (auth == np->auth)
877 				authfnd++;
878 		}
879 		/*
880 		 * Some servers, such as DEC's OSF/1 return a nil authenticator
881 		 * list to indicate RPCAUTH_UNIX.
882 		 */
883 		if (!authfnd && (authcnt > 0 || np->auth != RPCAUTH_UNIX))
884 			np->stat = EAUTH;
885 		return (1);
886 	};
887 	return (0);
888 }
889 
890 void
891 usage()
892 {
893 	(void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
894 "usage: mount_nfs [-23KNPTUbcdilqs] [-D deadthresh] [-I readdirsize]",
895 "                 [-R retrycnt] [-a maxreadahead]",
896 "                 [-g maxgroups] [-m realm] [-o options] [-r readsize]",
897 "                 [-t timeout] [-w writesize] [-x retrans] rhost:path node");
898 	exit(1);
899 }
900