mount_nfs.c revision 197298
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
35static 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
41static 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: head/sbin/mount_nfs/mount_nfs.c 197298 2009-09-17 19:08:15Z rmacklem $");
46
47#include <sys/param.h>
48#include <sys/linker.h>
49#include <sys/module.h>
50#include <sys/mount.h>
51#include <sys/socket.h>
52#include <sys/stat.h>
53#include <sys/syslog.h>
54#include <sys/uio.h>
55
56#include <rpc/rpc.h>
57#include <rpc/pmap_clnt.h>
58#include <rpc/pmap_prot.h>
59#include <rpcsvc/nfs_prot.h>
60#include <rpcsvc/mount.h>
61
62#include <nfsclient/nfs.h>
63
64#include <arpa/inet.h>
65
66#include <ctype.h>
67#include <err.h>
68#include <errno.h>
69#include <fcntl.h>
70#include <netdb.h>
71#include <stdio.h>
72#include <stdlib.h>
73#include <string.h>
74#include <strings.h>
75#include <sysexits.h>
76#include <unistd.h>
77
78#include "mntopts.h"
79#include "mounttab.h"
80
81/* Table for af,sotype -> netid conversions. */
82struct nc_protos {
83	const char *netid;
84	int af;
85	int sotype;
86} nc_protos[] = {
87	{"udp",		AF_INET,	SOCK_DGRAM},
88	{"tcp",		AF_INET,	SOCK_STREAM},
89	{"udp6",	AF_INET6,	SOCK_DGRAM},
90	{"tcp6",	AF_INET6,	SOCK_STREAM},
91	{NULL,		0,		0}
92};
93
94struct nfhret {
95	u_long		stat;
96	long		vers;
97	long		auth;
98	long		fhsize;
99	u_char		nfh[NFS3_FHSIZE];
100};
101#define	BGRND	1
102#define	ISBGRND	2
103#define	OF_NOINET4	4
104#define	OF_NOINET6	8
105int retrycnt = -1;
106int opflags = 0;
107int nfsproto = IPPROTO_TCP;
108int mnttcp_ok = 1;
109int noconn = 0;
110char *portspec = NULL;	/* Server nfs port; NULL means look up via rpcbind. */
111struct sockaddr *addr;
112int addrlen = 0;
113u_char *fh = NULL;
114int fhsize = 0;
115int secflavor = -1;
116int got_principal = 0;
117
118enum mountmode {
119	ANY,
120	V2,
121	V3,
122	V4
123} mountmode = ANY;
124
125/* Return codes for nfs_tryproto. */
126enum tryret {
127	TRYRET_SUCCESS,
128	TRYRET_TIMEOUT,		/* No response received. */
129	TRYRET_REMOTEERR,	/* Error received from remote server. */
130	TRYRET_LOCALERR		/* Local failure. */
131};
132
133int	fallback_mount(struct iovec *iov, int iovlen, int mntflags);
134int	sec_name_to_num(char *sec);
135char	*sec_num_to_name(int num);
136int	getnfsargs(char *, struct iovec **iov, int *iovlen);
137/* void	set_rpc_maxgrouplist(int); */
138struct netconfig *getnetconf_cached(const char *netid);
139const char	*netidbytype(int af, int sotype);
140void	usage(void) __dead2;
141int	xdr_dir(XDR *, char *);
142int	xdr_fh(XDR *, struct nfhret *);
143enum tryret nfs_tryproto(struct addrinfo *ai, char *hostp, char *spec,
144    char **errstr, struct iovec **iov, int *iovlen);
145enum tryret returncode(enum clnt_stat stat, struct rpc_err *rpcerr);
146extern int getosreldate(void);
147
148int
149main(int argc, char *argv[])
150{
151	int c;
152	struct iovec *iov;
153	int mntflags, num, iovlen;
154	int osversion;
155	char *name, *p, *spec, *fstype;
156	char mntpath[MAXPATHLEN], errmsg[255];
157	char hostname[MAXHOSTNAMELEN + 1], *gssname, gssn[MAXHOSTNAMELEN + 50];
158
159	mntflags = 0;
160	iov = NULL;
161	iovlen = 0;
162	memset(errmsg, 0, sizeof(errmsg));
163	gssname = NULL;
164
165	fstype = strrchr(argv[0], '_');
166	if (fstype == NULL)
167		errx(EX_USAGE, "argv[0] must end in _fstype");
168
169	++fstype;
170
171	while ((c = getopt(argc, argv,
172	    "23a:bcdD:g:I:iLlNo:PR:r:sTt:w:x:U")) != -1)
173		switch (c) {
174		case '2':
175			mountmode = V2;
176			break;
177		case '3':
178			mountmode = V3;
179			break;
180		case 'a':
181			printf("-a deprecated, use -o readhead=<value>\n");
182			build_iovec(&iov, &iovlen, "readahead", optarg, (size_t)-1);
183			break;
184		case 'b':
185			opflags |= BGRND;
186			break;
187		case 'c':
188			printf("-c deprecated, use -o noconn\n");
189			build_iovec(&iov, &iovlen, "noconn", NULL, 0);
190			noconn = 1;
191			break;
192		case 'D':
193			printf("-D deprecated, use -o deadthresh=<value>\n");
194			build_iovec(&iov, &iovlen, "deadthresh", optarg, (size_t)-1);
195			break;
196		case 'd':
197			printf("-d deprecated, use -o dumbtimer");
198			build_iovec(&iov, &iovlen, "dumbtimer", NULL, 0);
199			break;
200		case 'g':
201			printf("-g deprecated, use -o maxgroups");
202			num = strtol(optarg, &p, 10);
203			if (*p || num <= 0)
204				errx(1, "illegal -g value -- %s", optarg);
205			//set_rpc_maxgrouplist(num);
206			build_iovec(&iov, &iovlen, "maxgroups", optarg, (size_t)-1);
207			break;
208		case 'I':
209			printf("-I deprecated, use -o readdirsize=<value>\n");
210			build_iovec(&iov, &iovlen, "readdirsize", optarg, (size_t)-1);
211			break;
212		case 'i':
213			printf("-i deprecated, use -o intr\n");
214			build_iovec(&iov, &iovlen, "intr", NULL, 0);
215			break;
216		case 'L':
217			printf("-i deprecated, use -o nolockd\n");
218			build_iovec(&iov, &iovlen, "nolockd", NULL, 0);
219			break;
220		case 'l':
221			printf("-l deprecated, -o rdirplus\n");
222			build_iovec(&iov, &iovlen, "rdirplus", NULL, 0);
223			break;
224		case 'N':
225			printf("-N deprecated, do not specify -o resvport\n");
226			break;
227		case 'o': {
228			int pass_flag_to_nmount;
229			char *opt = optarg;
230			while (opt) {
231				char *pval = NULL;
232				char *pnextopt = NULL;
233				char *val = "";
234				pass_flag_to_nmount = 1;
235				pval = strchr(opt, '=');
236				pnextopt = strchr(opt, ',');
237				if (pval != NULL) {
238					*pval = '\0';
239					val = pval + 1;
240				}
241				if (pnextopt) {
242					*pnextopt = '\0';
243					pnextopt++;
244				}
245				if (strcmp(opt, "bg") == 0) {
246					opflags |= BGRND;
247					pass_flag_to_nmount=0;
248				} else if (strcmp(opt, "fg") == 0) {
249					/* same as not specifying -o bg */
250					pass_flag_to_nmount=0;
251				} else if (strcmp(opt, "gssname") == 0) {
252					pass_flag_to_nmount = 0;
253					gssname = val;
254				} else if (strcmp(opt, "mntudp") == 0) {
255					mnttcp_ok = 0;
256					nfsproto = IPPROTO_UDP;
257				} else if (strcmp(opt, "udp") == 0) {
258					nfsproto = IPPROTO_UDP;
259				} else if (strcmp(opt, "tcp") == 0) {
260					nfsproto = IPPROTO_TCP;
261				} else if (strcmp(opt, "noinet4") == 0) {
262					pass_flag_to_nmount=0;
263					opflags |= OF_NOINET4;
264				} else if (strcmp(opt, "noinet6") == 0) {
265					pass_flag_to_nmount=0;
266					opflags |= OF_NOINET6;
267				} else if (strcmp(opt, "noconn") == 0) {
268					noconn = 1;
269				} else if (strcmp(opt, "nfsv2") == 0) {
270					pass_flag_to_nmount=0;
271					mountmode = V2;
272				} else if (strcmp(opt, "nfsv3") == 0) {
273					mountmode = V3;
274				} else if (strcmp(opt, "nfsv4") == 0) {
275					pass_flag_to_nmount=0;
276					mountmode = V4;
277					fstype = "newnfs";
278					nfsproto = IPPROTO_TCP;
279					if (portspec == NULL)
280						portspec = "2049";
281				} else if (strcmp(opt, "port") == 0) {
282					pass_flag_to_nmount=0;
283					asprintf(&portspec, "%d",
284					    atoi(val));
285					if (portspec == NULL)
286						err(1, "asprintf");
287				} else if (strcmp(opt, "principal") == 0) {
288					got_principal = 1;
289				} else if (strcmp(opt, "sec") == 0) {
290					/*
291					 * Don't add this option to
292					 * the iovec yet - we will
293					 * negotiate which sec flavor
294					 * to use with the remote
295					 * mountd.
296					 */
297					pass_flag_to_nmount=0;
298					secflavor = sec_name_to_num(val);
299					if (secflavor < 0) {
300						errx(1,
301						    "illegal sec value -- %s",
302						    val);
303					}
304				} else if (strcmp(opt, "retrycnt") == 0) {
305					pass_flag_to_nmount=0;
306					num = strtol(val, &p, 10);
307					if (*p || num < 0)
308						errx(1, "illegal retrycnt value -- %s", val);
309					retrycnt = num;
310				} else if (strcmp(opt, "maxgroups") == 0) {
311					num = strtol(val, &p, 10);
312					if (*p || num <= 0)
313						errx(1, "illegal maxgroups value -- %s", val);
314					//set_rpc_maxgrouplist(num);
315				}
316				if (pass_flag_to_nmount)
317					build_iovec(&iov, &iovlen, opt, val,
318					    strlen(val) + 1);
319				opt = pnextopt;
320			}
321			}
322			break;
323		case 'P':
324			/* obsolete for -o noresvport now default */
325			printf("-P deprecated, use -o noresvport\n");
326			build_iovec(&iov, &iovlen, "noresvport", NULL, 0);
327			break;
328		case 'R':
329			printf("-R deprecated, use -o retrycnt=<retrycnt>\n");
330			num = strtol(optarg, &p, 10);
331			if (*p || num < 0)
332				errx(1, "illegal -R value -- %s", optarg);
333			retrycnt = num;
334			break;
335		case 'r':
336			printf("-r deprecated, use -o rsize=<rsize>\n");
337			build_iovec(&iov, &iovlen, "rsize", optarg, (size_t)-1);
338			break;
339		case 's':
340			printf("-s deprecated, use -o soft\n");
341			build_iovec(&iov, &iovlen, "soft", NULL, 0);
342			break;
343		case 'T':
344			nfsproto = IPPROTO_TCP;
345			printf("-T deprecated, use -o tcp\n");
346			break;
347		case 't':
348			printf("-t deprecated, use -o timeout=<value>\n");
349			build_iovec(&iov, &iovlen, "timeout", optarg, (size_t)-1);
350			break;
351		case 'w':
352			printf("-w deprecated, use -o wsize=<value>\n");
353			build_iovec(&iov, &iovlen, "wsize", optarg, (size_t)-1);
354			break;
355		case 'x':
356			printf("-x deprecated, use -o retrans=<value>\n");
357			build_iovec(&iov, &iovlen, "retrans", optarg, (size_t)-1);
358			break;
359		case 'U':
360			printf("-U deprecated, use -o mntudp\n");
361			mnttcp_ok = 0;
362			nfsproto = IPPROTO_UDP;
363			build_iovec(&iov, &iovlen, "mntudp", NULL, 0);
364			break;
365		default:
366			usage();
367			break;
368		}
369	argc -= optind;
370	argv += optind;
371
372	if (argc != 2) {
373		usage();
374		/* NOTREACHED */
375	}
376
377	spec = *argv++;
378	name = *argv;
379
380	if (retrycnt == -1)
381		/* The default is to keep retrying forever. */
382		retrycnt = 0;
383
384	/*
385	 * If the experimental nfs subsystem is loaded into the kernel
386	 * and the regular one is not, use it. Otherwise, use it if the
387	 * fstype is set to "newnfs", either via "mount -t newnfs ..."
388	 * or by specifying an nfsv4 mount.
389	 */
390	if (modfind("nfscl") >= 0 && modfind("nfs") < 0) {
391		fstype = "newnfs";
392	} else if (strcmp(fstype, "newnfs") == 0) {
393		if (modfind("nfscl") < 0) {
394			/* Not present in kernel, try loading it */
395			if (kldload("nfscl") < 0 ||
396			    modfind("nfscl") < 0)
397				errx(1, "nfscl is not available");
398		}
399	}
400
401	/*
402	 * Add the fqdn to the gssname, as required.
403	 */
404	if (gssname != NULL) {
405		if (strchr(gssname, '@') == NULL &&
406		    gethostname(hostname, MAXHOSTNAMELEN) == 0) {
407			snprintf(gssn, sizeof (gssn), "%s@%s", gssname,
408			    hostname);
409			gssname = gssn;
410		}
411		build_iovec(&iov, &iovlen, "gssname", gssname,
412		    strlen(gssname) + 1);
413	}
414
415	if (!getnfsargs(spec, &iov, &iovlen))
416		exit(1);
417
418	/* resolve the mountpoint with realpath(3) */
419	(void)checkpath(name, mntpath);
420
421	build_iovec(&iov, &iovlen, "fstype", fstype, (size_t)-1);
422	build_iovec(&iov, &iovlen, "fspath", mntpath, (size_t)-1);
423	build_iovec(&iov, &iovlen, "errmsg", errmsg, sizeof(errmsg));
424
425	/*
426	 * XXX:
427	 * Backwards compatibility routines for older kernels.
428	 * Remove this and fallback_mount() code when we do not need to support
429	 * NFS mounts against older kernels which still need
430	 * struct nfs_args to be passed in via nmount().
431	 */
432	osversion = getosreldate();
433	if (osversion >= 702100) {
434		if (nmount(iov, iovlen, mntflags))
435			err(1, "%s, %s", mntpath, errmsg);
436	} else {
437		if (fallback_mount(iov, iovlen, mntflags))
438			err(1, "%s, %s", mntpath, errmsg);
439	}
440
441	exit(0);
442}
443
444static int
445findopt(struct iovec *iov, int iovlen, const char *name,
446    char **valuep, int *lenp)
447{
448	int i;
449
450	for (i = 0; i < iovlen/2; i++, iov += 2) {
451		if (strcmp(name, iov[0].iov_base) == 0) {
452			if (valuep)
453				*valuep = iov[1].iov_base;
454			if (lenp)
455				*lenp = iov[1].iov_len;
456			return (0);
457		}
458	}
459	return (ENOENT);
460}
461
462static void
463copyopt(struct iovec **newiov, int *newiovlen,
464    struct iovec *iov, int iovlen, const char *name)
465{
466	char *value;
467	int len;
468
469	if (findopt(iov, iovlen, name, &value, &len) == 0)
470		build_iovec(newiov, newiovlen, name, value, len);
471}
472
473/*
474 * XXX: This function is provided for backwards
475 *      compatibility with older kernels which did not support
476 *      passing NFS mount options to nmount() as individual
477 *      parameters.  It should be eventually be removed.
478 */
479int
480fallback_mount(struct iovec *iov, int iovlen, int mntflags)
481{
482	struct nfs_args args = {
483	    .version = NFS_ARGSVERSION,
484	    .addr = NULL,
485	    .addrlen = sizeof (struct sockaddr_in),
486	    .sotype = SOCK_STREAM,
487	    .proto = 0,
488	    .fh = NULL,
489	    .fhsize = 0,
490	    .flags = NFSMNT_RESVPORT,
491	    .wsize = NFS_WSIZE,
492	    .rsize = NFS_RSIZE,
493	    .readdirsize = NFS_READDIRSIZE,
494	    .timeo = 10,
495	    .retrans = NFS_RETRANS,
496	    .maxgrouplist = NFS_MAXGRPS,
497	    .readahead = NFS_DEFRAHEAD,
498	    .wcommitsize = 0,			/* was: NQ_DEFLEASE */
499	    .deadthresh = NFS_MAXDEADTHRESH,	/* was: NQ_DEADTHRESH */
500	    .hostname = NULL,
501	    /* args version 4 */
502	    .acregmin = NFS_MINATTRTIMO,
503	    .acregmax = NFS_MAXATTRTIMO,
504	    .acdirmin = NFS_MINDIRATTRTIMO,
505	    .acdirmax = NFS_MAXDIRATTRTIMO,
506	};
507	int ret;
508	char *opt;
509	struct iovec *newiov;
510	int newiovlen;
511
512	if (findopt(iov, iovlen, "dumbtimer", NULL, NULL) == 0)
513		args.flags |= NFSMNT_DUMBTIMR;
514	if (findopt(iov, iovlen, "noconn", NULL, NULL) == 0)
515		args.flags |= NFSMNT_NOCONN;
516	if (findopt(iov, iovlen, "conn", NULL, NULL) == 0)
517		args.flags |= NFSMNT_NOCONN;
518	if (findopt(iov, iovlen, "nolockd", NULL, NULL) == 0)
519		args.flags |= NFSMNT_NOLOCKD;
520	if (findopt(iov, iovlen, "lockd", NULL, NULL) == 0)
521		args.flags &= ~NFSMNT_NOLOCKD;
522	if (findopt(iov, iovlen, "intr", NULL, NULL) == 0)
523		args.flags |= NFSMNT_INT;
524	if (findopt(iov, iovlen, "rdirplus", NULL, NULL) == 0)
525		args.flags |= NFSMNT_RDIRPLUS;
526	if (findopt(iov, iovlen, "resvport", NULL, NULL) == 0)
527		args.flags |= NFSMNT_RESVPORT;
528	if (findopt(iov, iovlen, "noresvport", NULL, NULL) == 0)
529		args.flags &= ~NFSMNT_RESVPORT;
530	if (findopt(iov, iovlen, "soft", NULL, NULL) == 0)
531		args.flags |= NFSMNT_SOFT;
532	if (findopt(iov, iovlen, "hard", NULL, NULL) == 0)
533		args.flags &= ~NFSMNT_SOFT;
534	if (findopt(iov, iovlen, "mntudp", NULL, NULL) == 0)
535		args.sotype = SOCK_DGRAM;
536	if (findopt(iov, iovlen, "udp", NULL, NULL) == 0)
537		args.sotype = SOCK_DGRAM;
538	if (findopt(iov, iovlen, "tcp", NULL, NULL) == 0)
539		args.sotype = SOCK_STREAM;
540	if (findopt(iov, iovlen, "nfsv3", NULL, NULL) == 0)
541		args.flags |= NFSMNT_NFSV3;
542	if (findopt(iov, iovlen, "readdirsize", &opt, NULL) == 0) {
543		if (opt == NULL) {
544			errx(1, "illegal readdirsize");
545		}
546		ret = sscanf(opt, "%d", &args.readdirsize);
547		if (ret != 1 || args.readdirsize <= 0) {
548			errx(1, "illegal readdirsize: %s", opt);
549		}
550		args.flags |= NFSMNT_READDIRSIZE;
551	}
552	if (findopt(iov, iovlen, "readahead", &opt, NULL) == 0) {
553		if (opt == NULL) {
554			errx(1, "illegal readahead");
555		}
556		ret = sscanf(opt, "%d", &args.readahead);
557		if (ret != 1 || args.readahead <= 0) {
558			errx(1, "illegal readahead: %s", opt);
559		}
560		args.flags |= NFSMNT_READAHEAD;
561	}
562	if (findopt(iov, iovlen, "wsize", &opt, NULL) == 0) {
563		if (opt == NULL) {
564			errx(1, "illegal wsize");
565		}
566		ret = sscanf(opt, "%d", &args.wsize);
567		if (ret != 1 || args.wsize <= 0) {
568			errx(1, "illegal wsize: %s", opt);
569		}
570		args.flags |= NFSMNT_WSIZE;
571	}
572	if (findopt(iov, iovlen, "rsize", &opt, NULL) == 0) {
573		if (opt == NULL) {
574			errx(1, "illegal rsize");
575		}
576		ret = sscanf(opt, "%d", &args.rsize);
577		if (ret != 1 || args.rsize <= 0) {
578			errx(1, "illegal wsize: %s", opt);
579		}
580		args.flags |= NFSMNT_RSIZE;
581	}
582	if (findopt(iov, iovlen, "retrans", &opt, NULL) == 0) {
583		if (opt == NULL) {
584			errx(1, "illegal retrans");
585		}
586		ret = sscanf(opt, "%d", &args.retrans);
587		if (ret != 1 || args.retrans <= 0) {
588			errx(1, "illegal retrans: %s", opt);
589		}
590		args.flags |= NFSMNT_RETRANS;
591	}
592	if (findopt(iov, iovlen, "acregmin", &opt, NULL) == 0) {
593		ret = sscanf(opt, "%d", &args.acregmin);
594		if (ret != 1 || args.acregmin < 0) {
595			errx(1, "illegal acregmin: %s", opt);
596		}
597		args.flags |= NFSMNT_ACREGMIN;
598	}
599	if (findopt(iov, iovlen, "acregmax", &opt, NULL) == 0) {
600		ret = sscanf(opt, "%d", &args.acregmax);
601		if (ret != 1 || args.acregmax < 0) {
602			errx(1, "illegal acregmax: %s", opt);
603		}
604		args.flags |= NFSMNT_ACREGMAX;
605	}
606	if (findopt(iov, iovlen, "acdirmin", &opt, NULL) == 0) {
607		ret = sscanf(opt, "%d", &args.acdirmin);
608		if (ret != 1 || args.acdirmin < 0) {
609			errx(1, "illegal acdirmin: %s", opt);
610		}
611		args.flags |= NFSMNT_ACDIRMIN;
612	}
613	if (findopt(iov, iovlen, "acdirmax", &opt, NULL) == 0) {
614		ret = sscanf(opt, "%d", &args.acdirmax);
615		if (ret != 1 || args.acdirmax < 0) {
616			errx(1, "illegal acdirmax: %s", opt);
617		}
618		args.flags |= NFSMNT_ACDIRMAX;
619	}
620	if (findopt(iov, iovlen, "deadthresh", &opt, NULL) == 0) {
621		ret = sscanf(opt, "%d", &args.deadthresh);
622		if (ret != 1 || args.deadthresh <= 0) {
623			errx(1, "illegal deadthresh: %s", opt);
624		}
625		args.flags |= NFSMNT_DEADTHRESH;
626	}
627	if (findopt(iov, iovlen, "timeout", &opt, NULL) == 0) {
628		ret = sscanf(opt, "%d", &args.timeo);
629		if (ret != 1 || args.timeo <= 0) {
630			errx(1, "illegal timeout: %s", opt);
631		}
632		args.flags |= NFSMNT_TIMEO;
633	}
634	if (findopt(iov, iovlen, "maxgroups", &opt, NULL) == 0) {
635		ret = sscanf(opt, "%d", &args.maxgrouplist);
636		if (ret != 1 || args.timeo <= 0) {
637			errx(1, "illegal maxgroups: %s", opt);
638		}
639		args.flags |= NFSMNT_MAXGRPS;
640	}
641	if (findopt(iov, iovlen, "addr", &opt,
642		&args.addrlen) == 0) {
643		args.addr = (struct sockaddr *) opt;
644	}
645	if (findopt(iov, iovlen, "fh", &opt, &args.fhsize) == 0) {
646		args.fh = opt;
647	}
648	if (findopt(iov, iovlen, "hostname", &args.hostname,
649		NULL) == 0) {
650	}
651	if (args.hostname == NULL) {
652		errx(1, "Invalid hostname");
653	}
654
655	newiov = NULL;
656	newiovlen = 0;
657
658	build_iovec(&newiov, &newiovlen, "nfs_args", &args, sizeof(args));
659	copyopt(&newiov, &newiovlen, iov, iovlen, "fstype");
660	copyopt(&newiov, &newiovlen, iov, iovlen, "fspath");
661	copyopt(&newiov, &newiovlen, iov, iovlen, "errmsg");
662
663	return nmount(newiov, newiovlen, mntflags);
664}
665
666int
667sec_name_to_num(char *sec)
668{
669	if (!strcmp(sec, "krb5"))
670		return (RPCSEC_GSS_KRB5);
671	if (!strcmp(sec, "krb5i"))
672		return (RPCSEC_GSS_KRB5I);
673	if (!strcmp(sec, "krb5p"))
674		return (RPCSEC_GSS_KRB5P);
675	if (!strcmp(sec, "sys"))
676		return (AUTH_SYS);
677	return (-1);
678}
679
680char *
681sec_num_to_name(int flavor)
682{
683	switch (flavor) {
684	case RPCSEC_GSS_KRB5:
685		return ("krb5");
686	case RPCSEC_GSS_KRB5I:
687		return ("krb5i");
688	case RPCSEC_GSS_KRB5P:
689		return ("krb5p");
690	case AUTH_SYS:
691		return ("sys");
692	}
693	return (NULL);
694}
695
696int
697getnfsargs(char *spec, struct iovec **iov, int *iovlen)
698{
699	struct addrinfo hints, *ai_nfs, *ai;
700	enum tryret ret;
701	int ecode, speclen, remoteerr;
702	char *hostp, *delimp, *errstr;
703	size_t len;
704	static char nam[MNAMELEN + 1], pname[MAXHOSTNAMELEN + 5];
705
706	if ((delimp = strrchr(spec, ':')) != NULL) {
707		hostp = spec;
708		spec = delimp + 1;
709	} else if ((delimp = strrchr(spec, '@')) != NULL) {
710		warnx("path@server syntax is deprecated, use server:path");
711		hostp = delimp + 1;
712	} else {
713		warnx("no <host>:<dirpath> nfs-name");
714		return (0);
715	}
716	*delimp = '\0';
717
718	/*
719	 * If there has been a trailing slash at mounttime it seems
720	 * that some mountd implementations fail to remove the mount
721	 * entries from their mountlist while unmounting.
722	 */
723	for (speclen = strlen(spec);
724		speclen > 1 && spec[speclen - 1] == '/';
725		speclen--)
726		spec[speclen - 1] = '\0';
727	if (strlen(hostp) + strlen(spec) + 1 > MNAMELEN) {
728		warnx("%s:%s: %s", hostp, spec, strerror(ENAMETOOLONG));
729		return (0);
730	}
731	/* Make both '@' and ':' notations equal */
732	if (*hostp != '\0') {
733		len = strlen(hostp);
734		memmove(nam, hostp, len);
735		nam[len] = ':';
736		memmove(nam + len + 1, spec, speclen);
737		nam[len + speclen + 1] = '\0';
738	}
739
740	/*
741	 * Handle an internet host address.
742	 */
743	memset(&hints, 0, sizeof hints);
744	hints.ai_flags = AI_NUMERICHOST;
745	if (nfsproto == IPPROTO_TCP)
746		hints.ai_socktype = SOCK_STREAM;
747	else if (nfsproto == IPPROTO_UDP)
748		hints.ai_socktype = SOCK_DGRAM;
749
750	if (getaddrinfo(hostp, portspec, &hints, &ai_nfs) != 0) {
751		hints.ai_flags = AI_CANONNAME;
752		if ((ecode = getaddrinfo(hostp, portspec, &hints, &ai_nfs))
753		    != 0) {
754			if (portspec == NULL)
755				errx(1, "%s: %s", hostp, gai_strerror(ecode));
756			else
757				errx(1, "%s:%s: %s", hostp, portspec,
758				    gai_strerror(ecode));
759			return (0);
760		}
761
762		/*
763		 * For a Kerberized nfs mount where the "principal"
764		 * argument has not been set, add it here.
765		 */
766		if (got_principal == 0 && secflavor >= 0 &&
767		    secflavor != AUTH_SYS && ai_nfs->ai_canonname != NULL) {
768			snprintf(pname, sizeof (pname), "nfs@%s",
769			    ai_nfs->ai_canonname);
770			build_iovec(iov, iovlen, "principal", pname,
771			    strlen(pname) + 1);
772		}
773	}
774
775	ret = TRYRET_LOCALERR;
776	for (;;) {
777		/*
778		 * Try each entry returned by getaddrinfo(). Note the
779		 * occurence of remote errors by setting `remoteerr'.
780		 */
781		remoteerr = 0;
782		for (ai = ai_nfs; ai != NULL; ai = ai->ai_next) {
783			if ((ai->ai_family == AF_INET6) &&
784			    (opflags & OF_NOINET6))
785				continue;
786			if ((ai->ai_family == AF_INET) &&
787			    (opflags & OF_NOINET4))
788				continue;
789			ret = nfs_tryproto(ai, hostp, spec, &errstr, iov,
790			    iovlen);
791			if (ret == TRYRET_SUCCESS)
792				break;
793			if (ret != TRYRET_LOCALERR)
794				remoteerr = 1;
795			if ((opflags & ISBGRND) == 0)
796				fprintf(stderr, "%s\n", errstr);
797		}
798		if (ret == TRYRET_SUCCESS)
799			break;
800
801		/* Exit if all errors were local. */
802		if (!remoteerr)
803			exit(1);
804
805		/*
806		 * If retrycnt == 0, we are to keep retrying forever.
807		 * Otherwise decrement it, and exit if it hits zero.
808		 */
809		if (retrycnt != 0 && --retrycnt == 0)
810			exit(1);
811
812		if ((opflags & (BGRND | ISBGRND)) == BGRND) {
813			warnx("Cannot immediately mount %s:%s, backgrounding",
814			    hostp, spec);
815			opflags |= ISBGRND;
816			if (daemon(0, 0) != 0)
817				err(1, "daemon");
818		}
819		sleep(60);
820	}
821	freeaddrinfo(ai_nfs);
822
823	build_iovec(iov, iovlen, "hostname", nam, (size_t)-1);
824	/* Add mounted file system to PATH_MOUNTTAB */
825	if (!add_mtab(hostp, spec))
826		warnx("can't update %s for %s:%s", PATH_MOUNTTAB, hostp, spec);
827	return (1);
828}
829
830/*
831 * Try to set up the NFS arguments according to the address
832 * family, protocol (and possibly port) specified in `ai'.
833 *
834 * Returns TRYRET_SUCCESS if successful, or:
835 *   TRYRET_TIMEOUT		The server did not respond.
836 *   TRYRET_REMOTEERR		The server reported an error.
837 *   TRYRET_LOCALERR		Local failure.
838 *
839 * In all error cases, *errstr will be set to a statically-allocated string
840 * describing the error.
841 */
842enum tryret
843nfs_tryproto(struct addrinfo *ai, char *hostp, char *spec, char **errstr,
844    struct iovec **iov, int *iovlen)
845{
846	static char errbuf[256];
847	struct sockaddr_storage nfs_ss;
848	struct netbuf nfs_nb;
849	struct nfhret nfhret;
850	struct timeval try;
851	struct rpc_err rpcerr;
852	CLIENT *clp;
853	struct netconfig *nconf, *nconf_mnt;
854	const char *netid, *netid_mnt;
855	char *secname;
856	int doconnect, nfsvers, mntvers, sotype;
857	enum clnt_stat stat;
858	enum mountmode trymntmode;
859
860	trymntmode = mountmode;
861	errbuf[0] = '\0';
862	*errstr = errbuf;
863
864	if (nfsproto == IPPROTO_TCP)
865		sotype = SOCK_STREAM;
866	else if (nfsproto == IPPROTO_UDP)
867		sotype = SOCK_DGRAM;
868
869	if ((netid = netidbytype(ai->ai_family, sotype)) == NULL) {
870		snprintf(errbuf, sizeof errbuf,
871		    "af %d sotype %d not supported", ai->ai_family, sotype);
872		return (TRYRET_LOCALERR);
873	}
874	if ((nconf = getnetconf_cached(netid)) == NULL) {
875		snprintf(errbuf, sizeof errbuf, "%s: %s", netid, nc_sperror());
876		return (TRYRET_LOCALERR);
877	}
878	/* The RPCPROG_MNT netid may be different. */
879	if (mnttcp_ok) {
880		netid_mnt = netid;
881		nconf_mnt = nconf;
882	} else {
883		if ((netid_mnt = netidbytype(ai->ai_family, SOCK_DGRAM))
884		     == NULL) {
885			snprintf(errbuf, sizeof errbuf,
886			    "af %d sotype SOCK_DGRAM not supported",
887			     ai->ai_family);
888			return (TRYRET_LOCALERR);
889		}
890		if ((nconf_mnt = getnetconf_cached(netid_mnt)) == NULL) {
891			snprintf(errbuf, sizeof errbuf, "%s: %s", netid_mnt,
892			    nc_sperror());
893			return (TRYRET_LOCALERR);
894		}
895	}
896
897tryagain:
898	if (trymntmode == V4) {
899		nfsvers = 4;
900	} else if (trymntmode == V2) {
901		nfsvers = 2;
902		mntvers = 1;
903	} else {
904		nfsvers = 3;
905		mntvers = 3;
906	}
907
908	if (portspec != NULL) {
909		/* `ai' contains the complete nfsd sockaddr. */
910		nfs_nb.buf = ai->ai_addr;
911		nfs_nb.len = nfs_nb.maxlen = ai->ai_addrlen;
912	} else {
913		/* Ask the remote rpcbind. */
914		nfs_nb.buf = &nfs_ss;
915		nfs_nb.len = nfs_nb.maxlen = sizeof nfs_ss;
916
917		if (!rpcb_getaddr(NFS_PROGRAM, nfsvers, nconf, &nfs_nb,
918		    hostp)) {
919			if (rpc_createerr.cf_stat == RPC_PROGVERSMISMATCH &&
920			    trymntmode == ANY) {
921				trymntmode = V2;
922				goto tryagain;
923			}
924			snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s",
925			    netid, hostp, spec,
926			    clnt_spcreateerror("RPCPROG_NFS"));
927			return (returncode(rpc_createerr.cf_stat,
928			    &rpc_createerr.cf_error));
929		}
930	}
931
932	/* Check that the server (nfsd) responds on the port we have chosen. */
933	clp = clnt_tli_create(RPC_ANYFD, nconf, &nfs_nb, NFS_PROGRAM, nfsvers,
934	    0, 0);
935	if (clp == NULL) {
936		snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s", netid,
937		    hostp, spec, clnt_spcreateerror("nfsd: RPCPROG_NFS"));
938		return (returncode(rpc_createerr.cf_stat,
939		    &rpc_createerr.cf_error));
940	}
941	if (sotype == SOCK_DGRAM && noconn == 0) {
942		/*
943		 * Use connect(), to match what the kernel does. This
944		 * catches cases where the server responds from the
945		 * wrong source address.
946		 */
947		doconnect = 1;
948		if (!clnt_control(clp, CLSET_CONNECT, (char *)&doconnect)) {
949			clnt_destroy(clp);
950			snprintf(errbuf, sizeof errbuf,
951			    "[%s] %s:%s: CLSET_CONNECT failed", netid, hostp,
952			    spec);
953			return (TRYRET_LOCALERR);
954		}
955	}
956
957	try.tv_sec = 10;
958	try.tv_usec = 0;
959	stat = clnt_call(clp, NFSPROC_NULL, (xdrproc_t)xdr_void, NULL,
960			 (xdrproc_t)xdr_void, NULL, try);
961	if (stat != RPC_SUCCESS) {
962		if (stat == RPC_PROGVERSMISMATCH && trymntmode == ANY) {
963			clnt_destroy(clp);
964			trymntmode = V2;
965			goto tryagain;
966		}
967		clnt_geterr(clp, &rpcerr);
968		snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s", netid,
969		    hostp, spec, clnt_sperror(clp, "NFSPROC_NULL"));
970		clnt_destroy(clp);
971		return (returncode(stat, &rpcerr));
972	}
973	clnt_destroy(clp);
974
975	/*
976	 * For NFSv4, there is no mount protocol.
977	 */
978	if (trymntmode == V4) {
979		/*
980		 * Store the server address in nfsargsp, making
981		 * sure to copy any locally allocated structures.
982		 */
983		addrlen = nfs_nb.len;
984		addr = malloc(addrlen);
985		if (addr == NULL)
986			err(1, "malloc");
987		bcopy(nfs_nb.buf, addr, addrlen);
988
989		build_iovec(iov, iovlen, "addr", addr, addrlen);
990		secname = sec_num_to_name(secflavor);
991		if (secname != NULL)
992			build_iovec(iov, iovlen, "sec", secname, (size_t)-1);
993		build_iovec(iov, iovlen, "nfsv4", NULL, 0);
994		build_iovec(iov, iovlen, "dirpath", spec, (size_t)-1);
995
996		return (TRYRET_SUCCESS);
997	}
998
999	/* Send the MOUNTPROC_MNT RPC to get the root filehandle. */
1000	try.tv_sec = 10;
1001	try.tv_usec = 0;
1002	clp = clnt_tp_create(hostp, MOUNTPROG, mntvers, nconf_mnt);
1003	if (clp == NULL) {
1004		snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s", netid_mnt,
1005		    hostp, spec, clnt_spcreateerror("RPCMNT: clnt_create"));
1006		return (returncode(rpc_createerr.cf_stat,
1007		    &rpc_createerr.cf_error));
1008	}
1009	clp->cl_auth = authsys_create_default();
1010	nfhret.auth = secflavor;
1011	nfhret.vers = mntvers;
1012	stat = clnt_call(clp, MOUNTPROC_MNT, (xdrproc_t)xdr_dir, spec,
1013			 (xdrproc_t)xdr_fh, &nfhret,
1014	    try);
1015	auth_destroy(clp->cl_auth);
1016	if (stat != RPC_SUCCESS) {
1017		if (stat == RPC_PROGVERSMISMATCH && trymntmode == ANY) {
1018			clnt_destroy(clp);
1019			trymntmode = V2;
1020			goto tryagain;
1021		}
1022		clnt_geterr(clp, &rpcerr);
1023		snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s", netid_mnt,
1024		    hostp, spec, clnt_sperror(clp, "RPCPROG_MNT"));
1025		clnt_destroy(clp);
1026		return (returncode(stat, &rpcerr));
1027	}
1028	clnt_destroy(clp);
1029
1030	if (nfhret.stat != 0) {
1031		snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s", netid_mnt,
1032		    hostp, spec, strerror(nfhret.stat));
1033		return (TRYRET_REMOTEERR);
1034	}
1035
1036	/*
1037	 * Store the filehandle and server address in nfsargsp, making
1038	 * sure to copy any locally allocated structures.
1039	 */
1040	addrlen = nfs_nb.len;
1041	addr = malloc(addrlen);
1042	fhsize = nfhret.fhsize;
1043	fh = malloc(fhsize);
1044	if (addr == NULL || fh == NULL)
1045		err(1, "malloc");
1046	bcopy(nfs_nb.buf, addr, addrlen);
1047	bcopy(nfhret.nfh, fh, fhsize);
1048
1049	build_iovec(iov, iovlen, "addr", addr, addrlen);
1050	build_iovec(iov, iovlen, "fh", fh, fhsize);
1051	secname = sec_num_to_name(nfhret.auth);
1052	if (secname)
1053		build_iovec(iov, iovlen, "sec", secname, (size_t)-1);
1054	if (nfsvers == 3)
1055		build_iovec(iov, iovlen, "nfsv3", NULL, 0);
1056
1057	return (TRYRET_SUCCESS);
1058}
1059
1060/*
1061 * Catagorise a RPC return status and error into an `enum tryret'
1062 * return code.
1063 */
1064enum tryret
1065returncode(enum clnt_stat stat, struct rpc_err *rpcerr)
1066{
1067	switch (stat) {
1068	case RPC_TIMEDOUT:
1069		return (TRYRET_TIMEOUT);
1070	case RPC_PMAPFAILURE:
1071	case RPC_PROGNOTREGISTERED:
1072	case RPC_PROGVERSMISMATCH:
1073	/* XXX, these can be local or remote. */
1074	case RPC_CANTSEND:
1075	case RPC_CANTRECV:
1076		return (TRYRET_REMOTEERR);
1077	case RPC_SYSTEMERROR:
1078		switch (rpcerr->re_errno) {
1079		case ETIMEDOUT:
1080			return (TRYRET_TIMEOUT);
1081		case ENOMEM:
1082			break;
1083		default:
1084			return (TRYRET_REMOTEERR);
1085		}
1086		/* FALLTHROUGH */
1087	default:
1088		break;
1089	}
1090	return (TRYRET_LOCALERR);
1091}
1092
1093/*
1094 * Look up a netid based on an address family and socket type.
1095 * `af' is the address family, and `sotype' is SOCK_DGRAM or SOCK_STREAM.
1096 *
1097 * XXX there should be a library function for this.
1098 */
1099const char *
1100netidbytype(int af, int sotype)
1101{
1102	struct nc_protos *p;
1103
1104	for (p = nc_protos; p->netid != NULL; p++) {
1105		if (af != p->af || sotype != p->sotype)
1106			continue;
1107		return (p->netid);
1108	}
1109	return (NULL);
1110}
1111
1112/*
1113 * Look up a netconfig entry based on a netid, and cache the result so
1114 * that we don't need to remember to call freenetconfigent().
1115 *
1116 * Otherwise it behaves just like getnetconfigent(), so nc_*error()
1117 * work on failure.
1118 */
1119struct netconfig *
1120getnetconf_cached(const char *netid)
1121{
1122	static struct nc_entry {
1123		struct netconfig *nconf;
1124		struct nc_entry *next;
1125	} *head;
1126	struct nc_entry *p;
1127	struct netconfig *nconf;
1128
1129	for (p = head; p != NULL; p = p->next)
1130		if (strcmp(netid, p->nconf->nc_netid) == 0)
1131			return (p->nconf);
1132
1133	if ((nconf = getnetconfigent(netid)) == NULL)
1134		return (NULL);
1135	if ((p = malloc(sizeof(*p))) == NULL)
1136		err(1, "malloc");
1137	p->nconf = nconf;
1138	p->next = head;
1139	head = p;
1140
1141	return (p->nconf);
1142}
1143
1144/*
1145 * xdr routines for mount rpc's
1146 */
1147int
1148xdr_dir(XDR *xdrsp, char *dirp)
1149{
1150	return (xdr_string(xdrsp, &dirp, MNTPATHLEN));
1151}
1152
1153int
1154xdr_fh(XDR *xdrsp, struct nfhret *np)
1155{
1156	int i;
1157	long auth, authcnt, authfnd = 0;
1158
1159	if (!xdr_u_long(xdrsp, &np->stat))
1160		return (0);
1161	if (np->stat)
1162		return (1);
1163	switch (np->vers) {
1164	case 1:
1165		np->fhsize = NFS_FHSIZE;
1166		return (xdr_opaque(xdrsp, (caddr_t)np->nfh, NFS_FHSIZE));
1167	case 3:
1168		if (!xdr_long(xdrsp, &np->fhsize))
1169			return (0);
1170		if (np->fhsize <= 0 || np->fhsize > NFS3_FHSIZE)
1171			return (0);
1172		if (!xdr_opaque(xdrsp, (caddr_t)np->nfh, np->fhsize))
1173			return (0);
1174		if (!xdr_long(xdrsp, &authcnt))
1175			return (0);
1176		for (i = 0; i < authcnt; i++) {
1177			if (!xdr_long(xdrsp, &auth))
1178				return (0);
1179			if (np->auth == -1) {
1180				np->auth = auth;
1181				authfnd++;
1182			} else if (auth == np->auth) {
1183				authfnd++;
1184			}
1185		}
1186		/*
1187		 * Some servers, such as DEC's OSF/1 return a nil authenticator
1188		 * list to indicate RPCAUTH_UNIX.
1189		 */
1190		if (authcnt == 0 && np->auth == -1)
1191			np->auth = AUTH_SYS;
1192		if (!authfnd && (authcnt > 0 || np->auth != AUTH_SYS))
1193			np->stat = EAUTH;
1194		return (1);
1195	};
1196	return (0);
1197}
1198
1199void
1200usage()
1201{
1202	(void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
1203"usage: mount_nfs [-23bcdiLlNPsTU] [-a maxreadahead] [-D deadthresh]",
1204"                 [-g maxgroups] [-I readdirsize] [-o options] [-R retrycnt]",
1205"                 [-r readsize] [-t timeout] [-w writesize] [-x retrans]",
1206"                 rhost:path node");
1207	exit(1);
1208}
1209