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