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