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