mount_nfs.c revision 75394
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 75394 2001-04-10 22:05:47Z iedowse $";
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#ifdef NFSKERB
62#include <kerberosIV/des.h>
63#include <kerberosIV/krb.h>
64#endif
65
66#include <nfs/rpcv2.h>
67#include <nfs/nfsproto.h>
68#include <nfs/nfs.h>
69#include <nfs/nqnfs.h>
70
71#include <arpa/inet.h>
72
73#include <ctype.h>
74#include <err.h>
75#include <errno.h>
76#include <fcntl.h>
77#include <netdb.h>
78#include <stdio.h>
79#include <stdlib.h>
80#include <strings.h>
81#include <sysexits.h>
82#include <unistd.h>
83
84#include "mntopts.h"
85#include "mounttab.h"
86
87#define	ALTF_BG		0x1
88#define ALTF_NOCONN	0x2
89#define ALTF_DUMBTIMR	0x4
90#define ALTF_INTR	0x8
91#define ALTF_KERB	0x10
92#define ALTF_NFSV3	0x20
93#define ALTF_RDIRPLUS	0x40
94#define	ALTF_MNTUDP	0x80
95#define ALTF_RESVPORT	0x100
96#define ALTF_SEQPACKET	0x200
97#define ALTF_NQNFS	0x400
98#define ALTF_SOFT	0x800
99#define ALTF_TCP	0x1000
100#define ALTF_PORT	0x2000
101#define ALTF_NFSV2	0x4000
102#define ALTF_ACREGMIN	0x8000
103#define ALTF_ACREGMAX	0x10000
104#define ALTF_ACDIRMIN	0x20000
105#define ALTF_ACDIRMAX	0x40000
106
107struct mntopt mopts[] = {
108	MOPT_STDOPTS,
109	MOPT_FORCE,
110	MOPT_UPDATE,
111	MOPT_ASYNC,
112	{ "bg", 0, ALTF_BG, 1 },
113	{ "conn", 1, ALTF_NOCONN, 1 },
114	{ "dumbtimer", 0, ALTF_DUMBTIMR, 1 },
115	{ "intr", 0, ALTF_INTR, 1 },
116#ifdef NFSKERB
117	{ "kerb", 0, ALTF_KERB, 1 },
118#endif
119	{ "nfsv3", 0, ALTF_NFSV3, 1 },
120	{ "rdirplus", 0, ALTF_RDIRPLUS, 1 },
121	{ "mntudp", 0, ALTF_MNTUDP, 1 },
122	{ "resvport", 0, ALTF_RESVPORT, 1 },
123	{ "nqnfs", 0, ALTF_NQNFS, 1 },
124	{ "soft", 0, ALTF_SOFT, 1 },
125	{ "tcp", 0, ALTF_TCP, 1 },
126	{ "port=", 0, ALTF_PORT, 1 },
127	{ "nfsv2", 0, ALTF_NFSV2, 1 },
128	{ "acregmin=", 0, ALTF_ACREGMIN, 1 },
129	{ "acregmax=", 0, ALTF_ACREGMAX, 1 },
130	{ "acdirmin=", 0, ALTF_ACDIRMIN, 1 },
131	{ "acdirmax=", 0, ALTF_ACDIRMAX, 1 },
132	{ NULL }
133};
134
135struct nfs_args nfsdefargs = {
136	NFS_ARGSVERSION,
137	(struct sockaddr *)0,
138	sizeof (struct sockaddr_in),
139	SOCK_DGRAM,
140	0,
141	(u_char *)0,
142	0,
143	NFSMNT_RESVPORT,
144	NFS_WSIZE,
145	NFS_RSIZE,
146	NFS_READDIRSIZE,
147	10,
148	NFS_RETRANS,
149	NFS_MAXGRPS,
150	NFS_DEFRAHEAD,
151	NQ_DEFLEASE,
152	NQ_DEADTHRESH,
153	(char *)0,
154	/* args version 4 */
155	NFS_MINATTRTIMO,
156	NFS_MAXATTRTIMO,
157	NFS_MINDIRATTRTIMO,
158	NFS_MAXDIRATTRTIMO,
159};
160
161struct nfhret {
162	u_long		stat;
163	long		vers;
164	long		auth;
165	long		fhsize;
166	u_char		nfh[NFSX_V3FHMAX];
167};
168#define	DEF_RETRY	10000
169#define	BGRND	1
170#define	ISBGRND	2
171int retrycnt = DEF_RETRY;
172int opflags = 0;
173int nfsproto = IPPROTO_UDP;
174int mnttcp_ok = 1;
175char *portspec = NULL;	/* Server nfs port; NULL means look up via rpcbind. */
176enum mountmode {
177	ANY,
178	V2,
179	V3
180} mountmode = ANY;
181
182#ifdef NFSKERB
183char inst[INST_SZ];
184char realm[REALM_SZ];
185struct {
186	u_long		kind;
187	KTEXT_ST	kt;
188} ktick;
189struct nfsrpc_nickverf kverf;
190struct nfsrpc_fullblock kin, kout;
191NFSKERBKEY_T kivec;
192CREDENTIALS kcr;
193struct timeval ktv;
194NFSKERBKEYSCHED_T kerb_keysched;
195#endif
196
197/* Return codes for nfs_tryproto. */
198enum tryret {
199	TRYRET_SUCCESS,
200	TRYRET_TIMEOUT,		/* No response received. */
201	TRYRET_REMOTEERR,	/* Error received from remote server. */
202	TRYRET_LOCALERR		/* Local failure. */
203};
204
205int	getnfsargs __P((char *, struct nfs_args *));
206/* void	set_rpc_maxgrouplist __P((int)); */
207void	usage __P((void)) __dead2;
208int	xdr_dir __P((XDR *, char *));
209int	xdr_fh __P((XDR *, struct nfhret *));
210enum tryret nfs_tryproto(struct nfs_args *nfsargsp, struct addrinfo *ai,
211    char *hostp, char *spec, char **errstr);
212enum tryret returncode(enum clnt_stat stat, struct rpc_err *rpcerr);
213
214/*
215 * Used to set mount flags with getmntopts.  Call with dir=TRUE to
216 * initialize altflags from the current mount flags.  Call with
217 * dir=FALSE to update mount flags with the new value of altflags after
218 * the call to getmntopts.
219 */
220static void
221set_flags(int* altflags, int* nfsflags, int dir)
222{
223#define F2(af, nf)					\
224	if (dir) {					\
225		if (*nfsflags & NFSMNT_##nf)		\
226			*altflags |= ALTF_##af;		\
227		else					\
228			*altflags &= ~ALTF_##af;	\
229	} else {					\
230		if (*altflags & ALTF_##af)		\
231			*nfsflags |= NFSMNT_##nf;	\
232		else					\
233			*nfsflags &= ~NFSMNT_##nf;	\
234	}
235#define F(f)	F2(f,f)
236
237	F(NOCONN);
238	F(DUMBTIMR);
239	F2(INTR, INT);
240#ifdef NFSKERB
241	F(KERB);
242#endif
243	F(RDIRPLUS);
244	F(RESVPORT);
245	F(NQNFS);
246	F(SOFT);
247
248#undef F
249#undef F2
250}
251
252int
253main(argc, argv)
254	int argc;
255	char *argv[];
256{
257	register int c;
258	register struct nfs_args *nfsargsp;
259	struct nfs_args nfsargs;
260	struct nfsd_cargs ncd;
261	int mntflags, altflags, nfssvc_flag, num;
262	char *name, *p, *spec;
263	char mntpath[MAXPATHLEN];
264	struct vfsconf vfc;
265	int error = 0;
266#ifdef NFSKERB
267	uid_t last_ruid;
268
269	last_ruid = -1;
270	(void)strcpy(realm, KRB_REALM);
271	if (sizeof (struct nfsrpc_nickverf) != RPCX_NICKVERF ||
272	    sizeof (struct nfsrpc_fullblock) != RPCX_FULLBLOCK ||
273	    ((char *)&ktick.kt) - ((char *)&ktick) != NFSX_UNSIGNED ||
274	    ((char *)ktick.kt.dat) - ((char *)&ktick) != 2 * NFSX_UNSIGNED)
275		fprintf(stderr, "Yikes! NFSKERB structs not packed!!\n");
276#endif /* NFSKERB */
277	retrycnt = DEF_RETRY;
278
279	mntflags = 0;
280	altflags = 0;
281	nfsargs = nfsdefargs;
282	nfsargsp = &nfsargs;
283	while ((c = getopt(argc, argv,
284	    "23a:bcdD:g:I:iKL:lm:No:PpqR:r:sTt:w:x:U")) != -1)
285		switch (c) {
286		case '2':
287			mountmode = V2;
288			break;
289		case '3':
290			mountmode = V3;
291			break;
292		case 'a':
293			num = strtol(optarg, &p, 10);
294			if (*p || num < 0)
295				errx(1, "illegal -a value -- %s", optarg);
296			nfsargsp->readahead = num;
297			nfsargsp->flags |= NFSMNT_READAHEAD;
298			break;
299		case 'b':
300			opflags |= BGRND;
301			break;
302		case 'c':
303			nfsargsp->flags |= NFSMNT_NOCONN;
304			break;
305		case 'D':
306			num = strtol(optarg, &p, 10);
307			if (*p || num <= 0)
308				errx(1, "illegal -D value -- %s", optarg);
309			nfsargsp->deadthresh = num;
310			nfsargsp->flags |= NFSMNT_DEADTHRESH;
311			break;
312		case 'd':
313			nfsargsp->flags |= NFSMNT_DUMBTIMR;
314			break;
315#if 0 /* XXXX */
316		case 'g':
317			num = strtol(optarg, &p, 10);
318			if (*p || num <= 0)
319				errx(1, "illegal -g value -- %s", optarg);
320			set_rpc_maxgrouplist(num);
321			nfsargsp->maxgrouplist = num;
322			nfsargsp->flags |= NFSMNT_MAXGRPS;
323			break;
324#endif
325		case 'I':
326			num = strtol(optarg, &p, 10);
327			if (*p || num <= 0)
328				errx(1, "illegal -I value -- %s", optarg);
329			nfsargsp->readdirsize = num;
330			nfsargsp->flags |= NFSMNT_READDIRSIZE;
331			break;
332		case 'i':
333			nfsargsp->flags |= NFSMNT_INT;
334			break;
335#ifdef NFSKERB
336		case 'K':
337			nfsargsp->flags |= NFSMNT_KERB;
338			break;
339#endif
340		case 'L':
341			num = strtol(optarg, &p, 10);
342			if (*p || num < 2)
343				errx(1, "illegal -L value -- %s", optarg);
344			nfsargsp->leaseterm = num;
345			nfsargsp->flags |= NFSMNT_LEASETERM;
346			break;
347		case 'l':
348			nfsargsp->flags |= NFSMNT_RDIRPLUS;
349			break;
350#ifdef NFSKERB
351		case 'm':
352			(void)strncpy(realm, optarg, REALM_SZ - 1);
353			realm[REALM_SZ - 1] = '\0';
354			break;
355#endif
356		case 'N':
357			nfsargsp->flags &= ~NFSMNT_RESVPORT;
358			break;
359		case 'o':
360			altflags = 0;
361			set_flags(&altflags, &nfsargsp->flags, TRUE);
362			if (mountmode == V2)
363				altflags |= ALTF_NFSV2;
364			else if (mountmode == V3)
365				altflags |= ALTF_NFSV3;
366			getmntopts(optarg, mopts, &mntflags, &altflags);
367			set_flags(&altflags, &nfsargsp->flags, FALSE);
368			/*
369			 * Handle altflags which don't map directly to
370			 * mount flags.
371			 */
372			if(altflags & ALTF_BG)
373				opflags |= BGRND;
374			if(altflags & ALTF_MNTUDP)
375				mnttcp_ok = 0;
376			if(altflags & ALTF_TCP) {
377				nfsargsp->sotype = SOCK_STREAM;
378				nfsproto = IPPROTO_TCP;
379			}
380			if(altflags & ALTF_PORT) {
381				/*
382				 * XXX Converting from a string to an int
383				 * and back again is silly, and we should
384				 * allow /etc/services names.
385				 */
386				asprintf(&portspec, "%d",
387				    atoi(strstr(optarg, "port=") + 5));
388				if (portspec == NULL)
389					err(1, "asprintf");
390			}
391			mountmode = ANY;
392			if(altflags & ALTF_NFSV2)
393				mountmode = V2;
394			if(altflags & ALTF_NFSV3)
395				mountmode = V3;
396			if(altflags & ALTF_ACREGMIN)
397				nfsargsp->acregmin = atoi(strstr(optarg,
398				    "acregmin=") + 9);
399			if(altflags & ALTF_ACREGMAX)
400				nfsargsp->acregmax = atoi(strstr(optarg,
401				    "acregmax=") + 9);
402			if(altflags & ALTF_ACDIRMIN)
403				nfsargsp->acdirmin = atoi(strstr(optarg,
404				    "acdirmin=") + 9);
405			if(altflags & ALTF_ACDIRMAX)
406				nfsargsp->acdirmax = atoi(strstr(optarg,
407				    "acdirmax=") + 9);
408			break;
409		case 'P':
410			/* obsolete for NFSMNT_RESVPORT, now default */
411			break;
412		case 'q':
413			mountmode = V3;
414			nfsargsp->flags |= NFSMNT_NQNFS;
415			break;
416		case 'R':
417			num = strtol(optarg, &p, 10);
418			if (*p || num <= 0)
419				errx(1, "illegal -R value -- %s", optarg);
420			retrycnt = num;
421			break;
422		case 'r':
423			num = strtol(optarg, &p, 10);
424			if (*p || num <= 0)
425				errx(1, "illegal -r value -- %s", optarg);
426			nfsargsp->rsize = num;
427			nfsargsp->flags |= NFSMNT_RSIZE;
428			break;
429		case 's':
430			nfsargsp->flags |= NFSMNT_SOFT;
431			break;
432		case 'T':
433			nfsargsp->sotype = SOCK_STREAM;
434			nfsproto = IPPROTO_TCP;
435			break;
436		case 't':
437			num = strtol(optarg, &p, 10);
438			if (*p || num <= 0)
439				errx(1, "illegal -t value -- %s", optarg);
440			nfsargsp->timeo = num;
441			nfsargsp->flags |= NFSMNT_TIMEO;
442			break;
443		case 'w':
444			num = strtol(optarg, &p, 10);
445			if (*p || num <= 0)
446				errx(1, "illegal -w value -- %s", optarg);
447			nfsargsp->wsize = num;
448			nfsargsp->flags |= NFSMNT_WSIZE;
449			break;
450		case 'x':
451			num = strtol(optarg, &p, 10);
452			if (*p || num <= 0)
453				errx(1, "illegal -x value -- %s", optarg);
454			nfsargsp->retrans = num;
455			nfsargsp->flags |= NFSMNT_RETRANS;
456			break;
457		case 'U':
458			mnttcp_ok = 0;
459			break;
460		default:
461			usage();
462			break;
463		}
464	argc -= optind;
465	argv += optind;
466
467	if (argc != 2) {
468		usage();
469		/* NOTREACHED */
470	}
471
472	spec = *argv++;
473	name = *argv;
474
475	if (!getnfsargs(spec, nfsargsp))
476		exit(1);
477
478	/* resolve the mountpoint with realpath(3) */
479	(void)checkpath(name, mntpath);
480
481	error = getvfsbyname("nfs", &vfc);
482	if (error && vfsisloadable("nfs")) {
483		if(vfsload("nfs"))
484			err(EX_OSERR, "vfsload(nfs)");
485		endvfsent();	/* clear cache */
486		error = getvfsbyname("nfs", &vfc);
487	}
488	if (error)
489		errx(EX_OSERR, "nfs filesystem is not available");
490
491	if (mount(vfc.vfc_name, mntpath, mntflags, nfsargsp))
492		err(1, "%s", mntpath);
493	if (nfsargsp->flags & (NFSMNT_NQNFS | NFSMNT_KERB)) {
494		if ((opflags & ISBGRND) == 0) {
495			if (daemon(0, 0) != 0)
496				err(1, "daemon");
497		}
498		openlog("mount_nfs", LOG_PID, LOG_DAEMON);
499		nfssvc_flag = NFSSVC_MNTD;
500		ncd.ncd_dirp = mntpath;
501		while (nfssvc(nfssvc_flag, (caddr_t)&ncd) < 0) {
502			if (errno != ENEEDAUTH) {
503				syslog(LOG_ERR, "nfssvc err %m");
504				continue;
505			}
506			nfssvc_flag =
507			    NFSSVC_MNTD | NFSSVC_GOTAUTH | NFSSVC_AUTHINFAIL;
508#ifdef NFSKERB
509			/*
510			 * Set up as ncd_authuid for the kerberos call.
511			 * Must set ruid to ncd_authuid and reset the
512			 * ticket name iff ncd_authuid is not the same
513			 * as last time, so that the right ticket file
514			 * is found.
515			 * Get the Kerberos credential structure so that
516			 * we have the session key and get a ticket for
517			 * this uid.
518			 * For more info see the IETF Draft "Authentication
519			 * in ONC RPC".
520			 */
521			if (ncd.ncd_authuid != last_ruid) {
522				char buf[512];
523				(void)sprintf(buf, "%s%d",
524					      TKT_ROOT, ncd.ncd_authuid);
525				krb_set_tkt_string(buf);
526				last_ruid = ncd.ncd_authuid;
527			}
528			setreuid(ncd.ncd_authuid, 0);
529			kret = krb_get_cred(NFS_KERBSRV, inst, realm, &kcr);
530			if (kret == RET_NOTKT) {
531		            kret = get_ad_tkt(NFS_KERBSRV, inst, realm,
532				DEFAULT_TKT_LIFE);
533			    if (kret == KSUCCESS)
534				kret = krb_get_cred(NFS_KERBSRV, inst, realm,
535				    &kcr);
536			}
537			if (kret == KSUCCESS)
538			    kret = krb_mk_req(&ktick.kt, NFS_KERBSRV, inst,
539				realm, 0);
540
541			/*
542			 * Fill in the AKN_FULLNAME authenticator and verifier.
543			 * Along with the Kerberos ticket, we need to build
544			 * the timestamp verifier and encrypt it in CBC mode.
545			 */
546			if (kret == KSUCCESS &&
547			    ktick.kt.length <= (RPCAUTH_MAXSIZ-3*NFSX_UNSIGNED)
548			    && gettimeofday(&ktv, (struct timezone *)0) == 0) {
549			    ncd.ncd_authtype = RPCAUTH_KERB4;
550			    ncd.ncd_authstr = (u_char *)&ktick;
551			    ncd.ncd_authlen = nfsm_rndup(ktick.kt.length) +
552				3 * NFSX_UNSIGNED;
553			    ncd.ncd_verfstr = (u_char *)&kverf;
554			    ncd.ncd_verflen = sizeof (kverf);
555			    memmove(ncd.ncd_key, kcr.session,
556				sizeof (kcr.session));
557			    kin.t1 = htonl(ktv.tv_sec);
558			    kin.t2 = htonl(ktv.tv_usec);
559			    kin.w1 = htonl(NFS_KERBTTL);
560			    kin.w2 = htonl(NFS_KERBTTL - 1);
561			    bzero((caddr_t)kivec, sizeof (kivec));
562
563			    /*
564			     * Encrypt kin in CBC mode using the session
565			     * key in kcr.
566			     */
567			    XXX
568
569			    /*
570			     * Finally, fill the timestamp verifier into the
571			     * authenticator and verifier.
572			     */
573			    ktick.kind = htonl(RPCAKN_FULLNAME);
574			    kverf.kind = htonl(RPCAKN_FULLNAME);
575			    NFS_KERBW1(ktick.kt) = kout.w1;
576			    ktick.kt.length = htonl(ktick.kt.length);
577			    kverf.verf.t1 = kout.t1;
578			    kverf.verf.t2 = kout.t2;
579			    kverf.verf.w2 = kout.w2;
580			    nfssvc_flag = NFSSVC_MNTD | NFSSVC_GOTAUTH;
581			}
582			setreuid(0, 0);
583#endif /* NFSKERB */
584		}
585	}
586	exit(0);
587}
588
589int
590getnfsargs(spec, nfsargsp)
591	char *spec;
592	struct nfs_args *nfsargsp;
593{
594	struct addrinfo hints, *ai_nfs, *ai;
595#ifdef NFSKERB
596	char host[NI_MAXHOST], serv[NI_MAXSERV];
597#endif
598	enum tryret ret;
599	int ecode, speclen, remoteerr;
600	char *hostp, *delimp, *errstr;
601#ifdef NFSKERB
602	char *cp;
603#endif
604	size_t len;
605	static char nam[MNAMELEN + 1];
606
607	if ((delimp = strrchr(spec, ':')) != NULL) {
608		hostp = spec;
609		spec = delimp + 1;
610	} else if ((delimp = strrchr(spec, '@')) != NULL) {
611		warnx("path@server syntax is deprecated, use server:path");
612		hostp = delimp + 1;
613	} else {
614		warnx("no <host>:<dirpath> nfs-name");
615		return (0);
616	}
617	*delimp = '\0';
618
619	/*
620	 * If there has been a trailing slash at mounttime it seems
621	 * that some mountd implementations fail to remove the mount
622	 * entries from their mountlist while unmounting.
623	 */
624	for (speclen = strlen(spec);
625		speclen > 1 && spec[speclen - 1] == '/';
626		speclen--)
627		spec[speclen - 1] = '\0';
628	if (strlen(hostp) + strlen(spec) + 1 > MNAMELEN) {
629		warnx("%s:%s: %s", hostp, spec, strerror(ENAMETOOLONG));
630		return (0);
631	}
632	/* Make both '@' and ':' notations equal */
633	if (*hostp != '\0') {
634		len = strlen(hostp);
635		memmove(nam, hostp, len);
636		nam[len] = ':';
637		memmove(nam + len + 1, spec, speclen);
638		nam[len + speclen + 1] = '\0';
639	}
640
641	/*
642	 * Handle an internet host address and reverse resolve it if
643	 * doing Kerberos.
644	 */
645	memset(&hints, 0, sizeof hints);
646	hints.ai_flags = AI_NUMERICHOST;
647	hints.ai_socktype = nfsargsp->sotype;
648	if (getaddrinfo(hostp, portspec, &hints, &ai_nfs) == 0) {
649#ifdef NFSKERB
650		if ((nfsargsp->flags & NFSMNT_KERB)) {
651			hints.ai_flags = 0;
652			if (getnameinfo(ai_nfs->ai_addr, ai_nfs->ai_addrlen,
653			    host, sizeof host, serv, sizeof serv, 0) != 0) {
654				warnx("can't reverse resolve net address");
655					return (0);
656				}
657			hostp = host;
658		}
659#endif /* NFSKERB */
660	} else {
661		hints.ai_flags = 0;
662		if ((ecode = getaddrinfo(hostp, portspec, &hints, &ai_nfs))
663		    != 0) {
664			if (portspec == NULL)
665				errx(1, "%s: %s", hostp, gai_strerror(ecode));
666			else
667				errx(1, "%s:%s: %s", hostp, portspec,
668				    gai_strerror(ecode));
669			return (0);
670		}
671	}
672#ifdef NFSKERB
673	if (nfsargsp->flags & NFSMNT_KERB) {
674		strncpy(inst, hp->h_name, INST_SZ);
675		inst[INST_SZ - 1] = '\0';
676		if (cp = strchr(inst, '.'))
677			*cp = '\0';
678	}
679#endif /* NFSKERB */
680
681	ret = TRYRET_LOCALERR;
682	while (retrycnt > 0) {
683		/*
684		 * Try each entry returned by getaddrinfo(). Note the
685		 * occurence of remote errors by setting `remoteerr'.
686		 */
687		remoteerr = 0;
688		for (ai = ai_nfs; ai != NULL; ai = ai->ai_next) {
689			ret = nfs_tryproto(nfsargsp, ai, hostp, spec, &errstr);
690			if (ret == TRYRET_SUCCESS)
691				break;
692			if (ret != TRYRET_LOCALERR)
693				remoteerr = 1;
694			if ((opflags & ISBGRND) == 0)
695				fprintf(stderr, "%s\n", errstr);
696		}
697		if (ret == TRYRET_SUCCESS)
698			break;
699
700		/*
701		 * Exit on failures if not BGRND mode, or if all errors
702		 * were local.
703		 */
704		if ((opflags & BGRND) == 0 || !remoteerr)
705			exit(1);
706
707		if (--retrycnt <= 0)
708			exit(1);
709
710		if ((opflags & (BGRND | ISBGRND)) == BGRND) {
711			warnx("Cannot immediately mount %s:%s, backgrounding",
712			    hostp, spec);
713			opflags |= ISBGRND;
714			if (daemon(0, 0) != 0)
715				err(1, "daemon");
716		}
717		sleep(60);
718	}
719	freeaddrinfo(ai_nfs);
720	nfsargsp->hostname = nam;
721	/* Add mounted filesystem to PATH_MOUNTTAB */
722	if (!add_mtab(hostp, spec))
723		warnx("can't update %s for %s:%s", PATH_MOUNTTAB, hostp, spec);
724	return (1);
725}
726
727/*
728 * Try to set up the NFS arguments according to the address
729 * family, protocol (and possibly port) specified in `ai'.
730 *
731 * Returns TRYRET_SUCCESS if successful, or:
732 *   TRYRET_TIMEOUT		The server did not respond.
733 *   TRYRET_REMOTEERR		The server reported an error.
734 *   TRYRET_LOCALERR		Local failure.
735 *
736 * In all error cases, *errstr will be set to a statically-allocated string
737 * describing the error.
738 */
739enum tryret
740nfs_tryproto(struct nfs_args *nfsargsp, struct addrinfo *ai, char *hostp,
741    char *spec, char **errstr)
742{
743	static char errbuf[256];
744	struct sockaddr_storage nfs_ss;
745	struct netbuf nfs_nb;
746	struct nfhret nfhret;
747	struct timeval try;
748	struct rpc_err rpcerr;
749	CLIENT *clp;
750	struct netconfig *nconf, *nconf_mnt;
751	char *netid, *netid_mnt;
752	int nfsvers, mntvers;
753	enum clnt_stat stat;
754	enum mountmode trymntmode;
755
756	trymntmode = mountmode;
757	errbuf[0] = '\0';
758	*errstr = errbuf;
759
760	/*
761	 * XXX. Nead a generic (family, type, proto) -> nconf interface.
762	 * __rpc_*2nconf exist, maybe they should be exported.
763	 */
764	if (nfsargsp->sotype == SOCK_STREAM)
765		netid = (ai->ai_family == AF_INET6) ? "tcp6" : "tcp";
766	else
767		netid = (ai->ai_family == AF_INET6) ? "udp6" : "udp";
768	if ((nconf = getnetconfigent(netid)) == NULL) {
769		snprintf(errbuf, sizeof errbuf, "%s: %s", netid, nc_sperror());
770		return (TRYRET_LOCALERR);
771	}
772	/* The RPCPROG_MNT netid may be different. */
773	if (mnttcp_ok) {
774		nconf_mnt = nconf;
775	} else {
776		netid_mnt = (ai->ai_family == AF_INET6) ? "udp6" : "udp";
777		if ((nconf_mnt = getnetconfigent(netid)) == NULL) {
778			snprintf(errbuf, sizeof errbuf, "%s: %s", netid,
779			    nc_sperror());
780			return (TRYRET_LOCALERR);
781		}
782	}
783
784tryagain:
785	if (trymntmode == V2) {
786		nfsvers = 2;
787		mntvers = 1;
788	} else {
789		nfsvers = 3;
790		mntvers = 3;
791	}
792
793	if (portspec != NULL) {
794		/* `ai' contains the complete nfsd sockaddr. */
795		nfs_nb.buf = ai->ai_addr;
796		nfs_nb.len = nfs_nb.maxlen = ai->ai_addrlen;
797	} else {
798		/* Ask the remote rpcbind. */
799		nfs_nb.buf = &nfs_ss;
800		nfs_nb.len = nfs_nb.maxlen = sizeof nfs_ss;
801
802		if (!rpcb_getaddr(RPCPROG_NFS, nfsvers, nconf, &nfs_nb,
803		    hostp)) {
804			if (rpc_createerr.cf_stat == RPC_PROGVERSMISMATCH &&
805			    trymntmode == ANY) {
806				trymntmode = V2;
807				goto tryagain;
808			}
809			snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s",
810			    netid, hostp, spec,
811			    clnt_spcreateerror("RPCPROG_NFS"));
812			return (returncode(rpc_createerr.cf_stat,
813			    &rpc_createerr.cf_error));
814		}
815	}
816
817	/* Check that the server (nfsd) responds on the port we have chosen. */
818	clp = clnt_tli_create(RPC_ANYFD, nconf, &nfs_nb, RPCPROG_NFS, nfsvers,
819	    0, 0);
820	if (clp == NULL) {
821		snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s", netid,
822		    hostp, spec, clnt_spcreateerror("nfsd: RPCPROG_NFS"));
823		return (returncode(rpc_createerr.cf_stat,
824		    &rpc_createerr.cf_error));
825	}
826	try.tv_sec = 10;
827	try.tv_usec = 0;
828	stat = clnt_call(clp, NFSPROC_NULL, xdr_void, NULL, xdr_void, NULL,
829	    try);
830	if (stat != RPC_SUCCESS) {
831		if (stat == RPC_PROGVERSMISMATCH && trymntmode == ANY) {
832			clnt_destroy(clp);
833			trymntmode = V2;
834			goto tryagain;
835		}
836		clnt_geterr(clp, &rpcerr);
837		snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s", netid,
838		    hostp, spec, clnt_sperror(clp, "NFSPROC_NULL"));
839		clnt_destroy(clp);
840		return (returncode(stat, &rpcerr));
841	}
842	clnt_destroy(clp);
843
844	/* Send the RPCMNT_MOUNT RPC to get the root filehandle. */
845	try.tv_sec = 10;
846	try.tv_usec = 0;
847	clp = clnt_tp_create(hostp, RPCPROG_MNT, mntvers, nconf_mnt);
848	if (clp == NULL) {
849		snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s", netid,
850		    hostp, spec, clnt_spcreateerror("RPCMNT: clnt_create"));
851		return (returncode(rpc_createerr.cf_stat,
852		    &rpc_createerr.cf_error));
853	}
854	clp->cl_auth = authsys_create_default();
855	if (nfsargsp->flags & NFSMNT_KERB)
856		nfhret.auth = RPCAUTH_KERB4;
857	else
858		nfhret.auth = RPCAUTH_UNIX;
859	nfhret.vers = mntvers;
860	stat = clnt_call(clp, RPCMNT_MOUNT, xdr_dir, spec, xdr_fh, &nfhret,
861	    try);
862	auth_destroy(clp->cl_auth);
863	if (stat != RPC_SUCCESS) {
864		if (stat == RPC_PROGVERSMISMATCH && trymntmode == ANY) {
865			clnt_destroy(clp);
866			trymntmode = V2;
867			goto tryagain;
868		}
869		clnt_geterr(clp, &rpcerr);
870		snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s", netid,
871		    hostp, spec, clnt_sperror(clp, "RPCPROG_MNT"));
872		clnt_destroy(clp);
873		return (returncode(stat, &rpcerr));
874	}
875	clnt_destroy(clp);
876
877	if (nfhret.stat != 0) {
878		snprintf(errbuf, sizeof errbuf, "[%s] %s:%s: %s", netid,
879		    hostp, spec, strerror(nfhret.stat));
880		return (TRYRET_REMOTEERR);
881	}
882
883	/*
884	 * Store the filehandle and server address in nfsargsp, making
885	 * sure to copy any locally allocated structures.
886	 */
887	nfsargsp->addrlen = nfs_nb.len;
888	nfsargsp->addr = malloc(nfsargsp->addrlen);
889	nfsargsp->fhsize = nfhret.fhsize;
890	nfsargsp->fh = malloc(nfsargsp->fhsize);
891	if (nfsargsp->addr == NULL || nfsargsp->fh == NULL)
892		err(1, "malloc");
893	bcopy(nfs_nb.buf, nfsargsp->addr, nfsargsp->addrlen);
894	bcopy(nfhret.nfh, nfsargsp->fh, nfsargsp->fhsize);
895
896	if (nfsvers == 3)
897		nfsargsp->flags |= NFSMNT_NFSV3;
898	else
899		nfsargsp->flags &= ~NFSMNT_NFSV3;
900
901	return (TRYRET_SUCCESS);
902}
903
904
905/*
906 * Catagorise a RPC return status and error into an `enum tryret'
907 * return code.
908 */
909enum tryret
910returncode(enum clnt_stat stat, struct rpc_err *rpcerr)
911{
912	switch (stat) {
913	case RPC_TIMEDOUT:
914		return (TRYRET_TIMEOUT);
915	case RPC_PMAPFAILURE:
916	case RPC_PROGNOTREGISTERED:
917	case RPC_PROGVERSMISMATCH:
918		return (TRYRET_REMOTEERR);
919	case RPC_SYSTEMERROR:
920		switch (rpcerr->re_errno) {
921		case ETIMEDOUT:
922			return (TRYRET_TIMEOUT);
923		case ENOMEM:
924			break;
925		default:
926			return (TRYRET_REMOTEERR);
927		}
928		/* FALLTHROUGH */
929	default:
930		break;
931	}
932	return (TRYRET_LOCALERR);
933}
934
935/*
936 * xdr routines for mount rpc's
937 */
938int
939xdr_dir(xdrsp, dirp)
940	XDR *xdrsp;
941	char *dirp;
942{
943	return (xdr_string(xdrsp, &dirp, RPCMNT_PATHLEN));
944}
945
946int
947xdr_fh(xdrsp, np)
948	XDR *xdrsp;
949	register struct nfhret *np;
950{
951	register int i;
952	long auth, authcnt, authfnd = 0;
953
954	if (!xdr_u_long(xdrsp, &np->stat))
955		return (0);
956	if (np->stat)
957		return (1);
958	switch (np->vers) {
959	case 1:
960		np->fhsize = NFSX_V2FH;
961		return (xdr_opaque(xdrsp, (caddr_t)np->nfh, NFSX_V2FH));
962	case 3:
963		if (!xdr_long(xdrsp, &np->fhsize))
964			return (0);
965		if (np->fhsize <= 0 || np->fhsize > NFSX_V3FHMAX)
966			return (0);
967		if (!xdr_opaque(xdrsp, (caddr_t)np->nfh, np->fhsize))
968			return (0);
969		if (!xdr_long(xdrsp, &authcnt))
970			return (0);
971		for (i = 0; i < authcnt; i++) {
972			if (!xdr_long(xdrsp, &auth))
973				return (0);
974			if (auth == np->auth)
975				authfnd++;
976		}
977		/*
978		 * Some servers, such as DEC's OSF/1 return a nil authenticator
979		 * list to indicate RPCAUTH_UNIX.
980		 */
981		if (!authfnd && (authcnt > 0 || np->auth != RPCAUTH_UNIX))
982			np->stat = EAUTH;
983		return (1);
984	};
985	return (0);
986}
987
988void
989usage()
990{
991	(void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
992"usage: mount_nfs [-23KNPTUbcdilqs] [-D deadthresh] [-I readdirsize]",
993"                 [-L leaseterm] [-R retrycnt] [-a maxreadahead]",
994"                 [-g maxgroups] [-m realm] [-o options] [-r readsize]",
995"                 [-t timeout] [-w writesize] [-x retrans] rhost:path node");
996	exit(1);
997}
998