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