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