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