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