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