]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/mountd/mountd.c
MFV r319743: 8108 zdb -l fails to read labels 2 and 3
[FreeBSD/FreeBSD.git] / usr.sbin / mountd / mountd.c
1 /*
2  * Copyright (c) 1989, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Herb Hasler and 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
33 #ifndef lint
34 static const char copyright[] =
35 "@(#) Copyright (c) 1989, 1993\n\
36         The Regents of the University of California.  All rights reserved.\n";
37 #endif /*not lint*/
38
39 #if 0
40 #ifndef lint
41 static char sccsid[] = "@(#)mountd.c    8.15 (Berkeley) 5/1/95";
42 #endif /*not lint*/
43 #endif
44
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
47
48 #include <sys/param.h>
49 #include <sys/fcntl.h>
50 #include <sys/linker.h>
51 #include <sys/module.h>
52 #include <sys/mount.h>
53 #include <sys/stat.h>
54 #include <sys/sysctl.h>
55 #include <sys/syslog.h>
56
57 #include <rpc/rpc.h>
58 #include <rpc/rpc_com.h>
59 #include <rpc/pmap_clnt.h>
60 #include <rpc/pmap_prot.h>
61 #include <rpcsvc/mount.h>
62 #include <nfs/nfsproto.h>
63 #include <nfs/nfssvc.h>
64 #include <nfsserver/nfs.h>
65
66 #include <fs/nfs/nfsport.h>
67
68 #include <arpa/inet.h>
69
70 #include <ctype.h>
71 #include <err.h>
72 #include <errno.h>
73 #include <grp.h>
74 #include <libutil.h>
75 #include <limits.h>
76 #include <netdb.h>
77 #include <pwd.h>
78 #include <signal.h>
79 #include <stdio.h>
80 #include <stdlib.h>
81 #include <string.h>
82 #include <unistd.h>
83 #include "pathnames.h"
84 #include "mntopts.h"
85
86 #ifdef DEBUG
87 #include <stdarg.h>
88 #endif
89
90 /*
91  * Structures for keeping the mount list and export list
92  */
93 struct mountlist {
94         struct mountlist *ml_next;
95         char    ml_host[MNTNAMLEN+1];
96         char    ml_dirp[MNTPATHLEN+1];
97 };
98
99 struct dirlist {
100         struct dirlist  *dp_left;
101         struct dirlist  *dp_right;
102         int             dp_flag;
103         struct hostlist *dp_hosts;      /* List of hosts this dir exported to */
104         char            *dp_dirp;
105 };
106 /* dp_flag bits */
107 #define DP_DEFSET       0x1
108 #define DP_HOSTSET      0x2
109
110 struct exportlist {
111         struct exportlist *ex_next;
112         struct dirlist  *ex_dirl;
113         struct dirlist  *ex_defdir;
114         int             ex_flag;
115         fsid_t          ex_fs;
116         char            *ex_fsdir;
117         char            *ex_indexfile;
118         int             ex_numsecflavors;
119         int             ex_secflavors[MAXSECFLAVORS];
120         int             ex_defnumsecflavors;
121         int             ex_defsecflavors[MAXSECFLAVORS];
122 };
123 /* ex_flag bits */
124 #define EX_LINKED       0x1
125
126 struct netmsk {
127         struct sockaddr_storage nt_net;
128         struct sockaddr_storage nt_mask;
129         char            *nt_name;
130 };
131
132 union grouptypes {
133         struct addrinfo *gt_addrinfo;
134         struct netmsk   gt_net;
135 };
136
137 struct grouplist {
138         int gr_type;
139         union grouptypes gr_ptr;
140         struct grouplist *gr_next;
141         int gr_numsecflavors;
142         int gr_secflavors[MAXSECFLAVORS];
143 };
144 /* Group types */
145 #define GT_NULL         0x0
146 #define GT_HOST         0x1
147 #define GT_NET          0x2
148 #define GT_DEFAULT      0x3
149 #define GT_IGNORE       0x5
150
151 struct hostlist {
152         int              ht_flag;       /* Uses DP_xx bits */
153         struct grouplist *ht_grp;
154         struct hostlist  *ht_next;
155 };
156
157 struct fhreturn {
158         int     fhr_flag;
159         int     fhr_vers;
160         nfsfh_t fhr_fh;
161         int     fhr_numsecflavors;
162         int     *fhr_secflavors;
163 };
164
165 #define GETPORT_MAXTRY  20      /* Max tries to get a port # */
166
167 /* Global defs */
168 static char     *add_expdir(struct dirlist **, char *, int);
169 static void     add_dlist(struct dirlist **, struct dirlist *,
170                     struct grouplist *, int, struct exportlist *);
171 static void     add_mlist(char *, char *);
172 static int      check_dirpath(char *);
173 static int      check_options(struct dirlist *);
174 static int      checkmask(struct sockaddr *sa);
175 static int      chk_host(struct dirlist *, struct sockaddr *, int *, int *,
176                     int *, int **);
177 static char     *strsep_quote(char **stringp, const char *delim);
178 static int      create_service(struct netconfig *nconf);
179 static void     complete_service(struct netconfig *nconf, char *port_str);
180 static void     clearout_service(void);
181 static void     del_mlist(char *hostp, char *dirp);
182 static struct dirlist   *dirp_search(struct dirlist *, char *);
183 static int      do_mount(struct exportlist *, struct grouplist *, int,
184                     struct xucred *, char *, int, struct statfs *);
185 static int      do_opt(char **, char **, struct exportlist *,
186                     struct grouplist *, int *, int *, struct xucred *);
187 static struct exportlist        *ex_search(fsid_t *);
188 static struct exportlist        *get_exp(void);
189 static void     free_dir(struct dirlist *);
190 static void     free_exp(struct exportlist *);
191 static void     free_grp(struct grouplist *);
192 static void     free_host(struct hostlist *);
193 static void     get_exportlist(void);
194 static int      get_host(char *, struct grouplist *, struct grouplist *);
195 static struct hostlist *get_ht(void);
196 static int      get_line(void);
197 static void     get_mountlist(void);
198 static int      get_net(char *, struct netmsk *, int);
199 static void     getexp_err(struct exportlist *, struct grouplist *);
200 static struct grouplist *get_grp(void);
201 static void     hang_dirp(struct dirlist *, struct grouplist *,
202                                 struct exportlist *, int);
203 static void     huphandler(int sig);
204 static int      makemask(struct sockaddr_storage *ssp, int bitlen);
205 static void     mntsrv(struct svc_req *, SVCXPRT *);
206 static void     nextfield(char **, char **);
207 static void     out_of_mem(void);
208 static void     parsecred(char *, struct xucred *);
209 static int      parsesec(char *, struct exportlist *);
210 static int      put_exlist(struct dirlist *, XDR *, struct dirlist *,
211                     int *, int);
212 static void     *sa_rawaddr(struct sockaddr *sa, int *nbytes);
213 static int      sacmp(struct sockaddr *sa1, struct sockaddr *sa2,
214                     struct sockaddr *samask);
215 static int      scan_tree(struct dirlist *, struct sockaddr *);
216 static void     usage(void);
217 static int      xdr_dir(XDR *, char *);
218 static int      xdr_explist(XDR *, caddr_t);
219 static int      xdr_explist_brief(XDR *, caddr_t);
220 static int      xdr_explist_common(XDR *, caddr_t, int);
221 static int      xdr_fhs(XDR *, caddr_t);
222 static int      xdr_mlist(XDR *, caddr_t);
223 static void     terminate(int);
224
225 static struct exportlist *exphead;
226 static struct mountlist *mlhead;
227 static struct grouplist *grphead;
228 static char *exnames_default[2] = { _PATH_EXPORTS, NULL };
229 static char **exnames;
230 static char **hosts = NULL;
231 static struct xucred def_anon = {
232         XUCRED_VERSION,
233         (uid_t)65534,
234         1,
235         { (gid_t)65533 },
236         NULL
237 };
238 static int force_v2 = 0;
239 static int resvport_only = 1;
240 static int nhosts = 0;
241 static int dir_only = 1;
242 static int dolog = 0;
243 static int got_sighup = 0;
244 static int xcreated = 0;
245
246 static char *svcport_str = NULL;
247 static int mallocd_svcport = 0;
248 static int *sock_fd;
249 static int sock_fdcnt;
250 static int sock_fdpos;
251 static int suspend_nfsd = 0;
252
253 static int opt_flags;
254 static int have_v6 = 1;
255
256 static int v4root_phase = 0;
257 static char v4root_dirpath[PATH_MAX + 1];
258 static int has_publicfh = 0;
259
260 static struct pidfh *pfh = NULL;
261 /* Bits for opt_flags above */
262 #define OP_MAPROOT      0x01
263 #define OP_MAPALL       0x02
264 /* 0x4 free */
265 #define OP_MASK         0x08
266 #define OP_NET          0x10
267 #define OP_ALLDIRS      0x40
268 #define OP_HAVEMASK     0x80    /* A mask was specified or inferred. */
269 #define OP_QUIET        0x100
270 #define OP_MASKLEN      0x200
271 #define OP_SEC          0x400
272
273 #ifdef DEBUG
274 static int debug = 1;
275 static void     SYSLOG(int, const char *, ...) __printflike(2, 3);
276 #define syslog SYSLOG
277 #else
278 static int debug = 0;
279 #endif
280
281 /*
282  * Similar to strsep(), but it allows for quoted strings
283  * and escaped characters.
284  *
285  * It returns the string (or NULL, if *stringp is NULL),
286  * which is a de-quoted version of the string if necessary.
287  *
288  * It modifies *stringp in place.
289  */
290 static char *
291 strsep_quote(char **stringp, const char *delim)
292 {
293         char *srcptr, *dstptr, *retval;
294         char quot = 0;
295         
296         if (stringp == NULL || *stringp == NULL)
297                 return (NULL);
298
299         srcptr = dstptr = retval = *stringp;
300
301         while (*srcptr) {
302                 /*
303                  * We're looking for several edge cases here.
304                  * First:  if we're in quote state (quot != 0),
305                  * then we ignore the delim characters, but otherwise
306                  * process as normal, unless it is the quote character.
307                  * Second:  if the current character is a backslash,
308                  * we take the next character as-is, without checking
309                  * for delim, quote, or backslash.  Exception:  if the
310                  * next character is a NUL, that's the end of the string.
311                  * Third:  if the character is a quote character, we toggle
312                  * quote state.
313                  * Otherwise:  check the current character for NUL, or
314                  * being in delim, and end the string if either is true.
315                  */
316                 if (*srcptr == '\\') {
317                         srcptr++;
318                         /*
319                          * The edge case here is if the next character
320                          * is NUL, we want to stop processing.  But if
321                          * it's not NUL, then we simply want to copy it.
322                          */
323                         if (*srcptr) {
324                                 *dstptr++ = *srcptr++;
325                         }
326                         continue;
327                 }
328                 if (quot == 0 && (*srcptr == '\'' || *srcptr == '"')) {
329                         quot = *srcptr++;
330                         continue;
331                 }
332                 if (quot && *srcptr == quot) {
333                         /* End of the quoted part */
334                         quot = 0;
335                         srcptr++;
336                         continue;
337                 }
338                 if (!quot && strchr(delim, *srcptr))
339                         break;
340                 *dstptr++ = *srcptr++;
341         }
342
343         *dstptr = 0; /* Terminate the string */
344         *stringp = (*srcptr == '\0') ? NULL : srcptr + 1;
345         return (retval);
346 }
347
348 /*
349  * Mountd server for NFS mount protocol as described in:
350  * NFS: Network File System Protocol Specification, RFC1094, Appendix A
351  * The optional arguments are the exports file name
352  * default: _PATH_EXPORTS
353  * and "-n" to allow nonroot mount.
354  */
355 int
356 main(int argc, char **argv)
357 {
358         fd_set readfds;
359         struct netconfig *nconf;
360         char *endptr, **hosts_bak;
361         void *nc_handle;
362         pid_t otherpid;
363         in_port_t svcport;
364         int c, k, s;
365         int maxrec = RPC_MAXDATASIZE;
366         int attempt_cnt, port_len, port_pos, ret;
367         char **port_list;
368
369         /* Check that another mountd isn't already running. */
370         pfh = pidfile_open(_PATH_MOUNTDPID, 0600, &otherpid);
371         if (pfh == NULL) {
372                 if (errno == EEXIST)
373                         errx(1, "mountd already running, pid: %d.", otherpid);
374                 warn("cannot open or create pidfile");
375         }
376
377         s = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
378         if (s < 0)
379                 have_v6 = 0;
380         else
381                 close(s);
382
383         while ((c = getopt(argc, argv, "2deh:lnp:rS")) != -1)
384                 switch (c) {
385                 case '2':
386                         force_v2 = 1;
387                         break;
388                 case 'e':
389                         /* now a no-op, since this is the default */
390                         break;
391                 case 'n':
392                         resvport_only = 0;
393                         break;
394                 case 'r':
395                         dir_only = 0;
396                         break;
397                 case 'd':
398                         debug = debug ? 0 : 1;
399                         break;
400                 case 'l':
401                         dolog = 1;
402                         break;
403                 case 'p':
404                         endptr = NULL;
405                         svcport = (in_port_t)strtoul(optarg, &endptr, 10);
406                         if (endptr == NULL || *endptr != '\0' ||
407                             svcport == 0 || svcport >= IPPORT_MAX)
408                                 usage();
409                         svcport_str = strdup(optarg);
410                         break;
411                 case 'h':
412                         ++nhosts;
413                         hosts_bak = hosts;
414                         hosts_bak = realloc(hosts, nhosts * sizeof(char *));
415                         if (hosts_bak == NULL) {
416                                 if (hosts != NULL) {
417                                         for (k = 0; k < nhosts; k++) 
418                                                 free(hosts[k]);
419                                         free(hosts);
420                                         out_of_mem();
421                                 }
422                         }
423                         hosts = hosts_bak;
424                         hosts[nhosts - 1] = strdup(optarg);
425                         if (hosts[nhosts - 1] == NULL) {
426                                 for (k = 0; k < (nhosts - 1); k++) 
427                                         free(hosts[k]);
428                                 free(hosts);
429                                 out_of_mem();
430                         }
431                         break;
432                 case 'S':
433                         suspend_nfsd = 1;
434                         break;
435                 default:
436                         usage();
437                 }
438
439         if (modfind("nfsd") < 0) {
440                 /* Not present in kernel, try loading it */
441                 if (kldload("nfsd") < 0 || modfind("nfsd") < 0)
442                         errx(1, "NFS server is not available");
443         }
444
445         argc -= optind;
446         argv += optind;
447         grphead = (struct grouplist *)NULL;
448         exphead = (struct exportlist *)NULL;
449         mlhead = (struct mountlist *)NULL;
450         if (argc > 0)
451                 exnames = argv;
452         else
453                 exnames = exnames_default;
454         openlog("mountd", LOG_PID, LOG_DAEMON);
455         if (debug)
456                 warnx("getting export list");
457         get_exportlist();
458         if (debug)
459                 warnx("getting mount list");
460         get_mountlist();
461         if (debug)
462                 warnx("here we go");
463         if (debug == 0) {
464                 daemon(0, 0);
465                 signal(SIGINT, SIG_IGN);
466                 signal(SIGQUIT, SIG_IGN);
467         }
468         signal(SIGHUP, huphandler);
469         signal(SIGTERM, terminate);
470         signal(SIGPIPE, SIG_IGN);
471
472         pidfile_write(pfh);
473
474         rpcb_unset(MOUNTPROG, MOUNTVERS, NULL);
475         rpcb_unset(MOUNTPROG, MOUNTVERS3, NULL);
476         rpc_control(RPC_SVC_CONNMAXREC_SET, &maxrec);
477
478         if (!resvport_only) {
479                 if (sysctlbyname("vfs.nfsd.nfs_privport", NULL, NULL,
480                     &resvport_only, sizeof(resvport_only)) != 0 &&
481                     errno != ENOENT) {
482                         syslog(LOG_ERR, "sysctl: %m");
483                         exit(1);
484                 }
485         }
486
487         /*
488          * If no hosts were specified, add a wildcard entry to bind to
489          * INADDR_ANY. Otherwise make sure 127.0.0.1 and ::1 are added to the
490          * list.
491          */
492         if (nhosts == 0) {
493                 hosts = malloc(sizeof(char *));
494                 if (hosts == NULL)
495                         out_of_mem();
496                 hosts[0] = "*";
497                 nhosts = 1;
498         } else {
499                 hosts_bak = hosts;
500                 if (have_v6) {
501                         hosts_bak = realloc(hosts, (nhosts + 2) *
502                             sizeof(char *));
503                         if (hosts_bak == NULL) {
504                                 for (k = 0; k < nhosts; k++)
505                                         free(hosts[k]);
506                                 free(hosts);
507                                 out_of_mem();
508                         } else
509                                 hosts = hosts_bak;
510                         nhosts += 2;
511                         hosts[nhosts - 2] = "::1";
512                 } else {
513                         hosts_bak = realloc(hosts, (nhosts + 1) * sizeof(char *));
514                         if (hosts_bak == NULL) {
515                                 for (k = 0; k < nhosts; k++)
516                                         free(hosts[k]);
517                                 free(hosts);
518                                 out_of_mem();
519                         } else {
520                                 nhosts += 1;
521                                 hosts = hosts_bak;
522                         }
523                 }
524
525                 hosts[nhosts - 1] = "127.0.0.1";
526         }
527
528         attempt_cnt = 1;
529         sock_fdcnt = 0;
530         sock_fd = NULL;
531         port_list = NULL;
532         port_len = 0;
533         nc_handle = setnetconfig();
534         while ((nconf = getnetconfig(nc_handle))) {
535                 if (nconf->nc_flag & NC_VISIBLE) {
536                         if (have_v6 == 0 && strcmp(nconf->nc_protofmly,
537                             "inet6") == 0) {
538                                 /* DO NOTHING */
539                         } else {
540                                 ret = create_service(nconf);
541                                 if (ret == 1)
542                                         /* Ignore this call */
543                                         continue;
544                                 if (ret < 0) {
545                                         /*
546                                          * Failed to bind port, so close off
547                                          * all sockets created and try again
548                                          * if the port# was dynamically
549                                          * assigned via bind(2).
550                                          */
551                                         clearout_service();
552                                         if (mallocd_svcport != 0 &&
553                                             attempt_cnt < GETPORT_MAXTRY) {
554                                                 free(svcport_str);
555                                                 svcport_str = NULL;
556                                                 mallocd_svcport = 0;
557                                         } else {
558                                                 errno = EADDRINUSE;
559                                                 syslog(LOG_ERR,
560                                                     "bindresvport_sa: %m");
561                                                 exit(1);
562                                         }
563
564                                         /* Start over at the first service. */
565                                         free(sock_fd);
566                                         sock_fdcnt = 0;
567                                         sock_fd = NULL;
568                                         nc_handle = setnetconfig();
569                                         attempt_cnt++;
570                                 } else if (mallocd_svcport != 0 &&
571                                     attempt_cnt == GETPORT_MAXTRY) {
572                                         /*
573                                          * For the last attempt, allow
574                                          * different port #s for each nconf
575                                          * by saving the svcport_str and
576                                          * setting it back to NULL.
577                                          */
578                                         port_list = realloc(port_list,
579                                             (port_len + 1) * sizeof(char *));
580                                         if (port_list == NULL)
581                                                 out_of_mem();
582                                         port_list[port_len++] = svcport_str;
583                                         svcport_str = NULL;
584                                         mallocd_svcport = 0;
585                                 }
586                         }
587                 }
588         }
589
590         /*
591          * Successfully bound the ports, so call complete_service() to
592          * do the rest of the setup on the service(s).
593          */
594         sock_fdpos = 0;
595         port_pos = 0;
596         nc_handle = setnetconfig();
597         while ((nconf = getnetconfig(nc_handle))) {
598                 if (nconf->nc_flag & NC_VISIBLE) {
599                         if (have_v6 == 0 && strcmp(nconf->nc_protofmly,
600                             "inet6") == 0) {
601                                 /* DO NOTHING */
602                         } else if (port_list != NULL) {
603                                 if (port_pos >= port_len) {
604                                         syslog(LOG_ERR, "too many port#s");
605                                         exit(1);
606                                 }
607                                 complete_service(nconf, port_list[port_pos++]);
608                         } else
609                                 complete_service(nconf, svcport_str);
610                 }
611         }
612         endnetconfig(nc_handle);
613         free(sock_fd);
614         if (port_list != NULL) {
615                 for (port_pos = 0; port_pos < port_len; port_pos++)
616                         free(port_list[port_pos]);
617                 free(port_list);
618         }
619
620         if (xcreated == 0) {
621                 syslog(LOG_ERR, "could not create any services");
622                 exit(1);
623         }
624
625         /* Expand svc_run() here so that we can call get_exportlist(). */
626         for (;;) {
627                 if (got_sighup) {
628                         get_exportlist();
629                         got_sighup = 0;
630                 }
631                 readfds = svc_fdset;
632                 switch (select(svc_maxfd + 1, &readfds, NULL, NULL, NULL)) {
633                 case -1:
634                         if (errno == EINTR)
635                                 continue;
636                         syslog(LOG_ERR, "mountd died: select: %m");
637                         exit(1);
638                 case 0:
639                         continue;
640                 default:
641                         svc_getreqset(&readfds);
642                 }
643         }
644
645
646 /*
647  * This routine creates and binds sockets on the appropriate
648  * addresses. It gets called one time for each transport.
649  * It returns 0 upon success, 1 for ingore the call and -1 to indicate
650  * bind failed with EADDRINUSE.
651  * Any file descriptors that have been created are stored in sock_fd and
652  * the total count of them is maintained in sock_fdcnt.
653  */
654 static int
655 create_service(struct netconfig *nconf)
656 {
657         struct addrinfo hints, *res = NULL;
658         struct sockaddr_in *sin;
659         struct sockaddr_in6 *sin6;
660         struct __rpc_sockinfo si;
661         int aicode;
662         int fd;
663         int nhostsbak;
664         int one = 1;
665         int r;
666         u_int32_t host_addr[4];  /* IPv4 or IPv6 */
667         int mallocd_res;
668
669         if ((nconf->nc_semantics != NC_TPI_CLTS) &&
670             (nconf->nc_semantics != NC_TPI_COTS) &&
671             (nconf->nc_semantics != NC_TPI_COTS_ORD))
672                 return (1);     /* not my type */
673
674         /*
675          * XXX - using RPC library internal functions.
676          */
677         if (!__rpc_nconf2sockinfo(nconf, &si)) {
678                 syslog(LOG_ERR, "cannot get information for %s",
679                     nconf->nc_netid);
680                 return (1);
681         }
682
683         /* Get mountd's address on this transport */
684         memset(&hints, 0, sizeof hints);
685         hints.ai_family = si.si_af;
686         hints.ai_socktype = si.si_socktype;
687         hints.ai_protocol = si.si_proto;
688
689         /*
690          * Bind to specific IPs if asked to
691          */
692         nhostsbak = nhosts;
693         while (nhostsbak > 0) {
694                 --nhostsbak;
695                 sock_fd = realloc(sock_fd, (sock_fdcnt + 1) * sizeof(int));
696                 if (sock_fd == NULL)
697                         out_of_mem();
698                 sock_fd[sock_fdcnt++] = -1;     /* Set invalid for now. */
699                 mallocd_res = 0;
700
701                 hints.ai_flags = AI_PASSIVE;
702
703                 /*      
704                  * XXX - using RPC library internal functions.
705                  */
706                 if ((fd = __rpc_nconf2fd(nconf)) < 0) {
707                         int non_fatal = 0;
708                         if (errno == EAFNOSUPPORT &&
709                             nconf->nc_semantics != NC_TPI_CLTS) 
710                                 non_fatal = 1;
711                                 
712                         syslog(non_fatal ? LOG_DEBUG : LOG_ERR, 
713                             "cannot create socket for %s", nconf->nc_netid);
714                         if (non_fatal != 0)
715                                 continue;
716                         exit(1);
717                 }
718
719                 switch (hints.ai_family) {
720                 case AF_INET:
721                         if (inet_pton(AF_INET, hosts[nhostsbak],
722                             host_addr) == 1) {
723                                 hints.ai_flags |= AI_NUMERICHOST;
724                         } else {
725                                 /*
726                                  * Skip if we have an AF_INET6 address.
727                                  */
728                                 if (inet_pton(AF_INET6, hosts[nhostsbak],
729                                     host_addr) == 1) {
730                                         close(fd);
731                                         continue;
732                                 }
733                         }
734                         break;
735                 case AF_INET6:
736                         if (inet_pton(AF_INET6, hosts[nhostsbak],
737                             host_addr) == 1) {
738                                 hints.ai_flags |= AI_NUMERICHOST;
739                         } else {
740                                 /*
741                                  * Skip if we have an AF_INET address.
742                                  */
743                                 if (inet_pton(AF_INET, hosts[nhostsbak],
744                                     host_addr) == 1) {
745                                         close(fd);
746                                         continue;
747                                 }
748                         }
749
750                         /*
751                          * We're doing host-based access checks here, so don't
752                          * allow v4-in-v6 to confuse things. The kernel will
753                          * disable it by default on NFS sockets too.
754                          */
755                         if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &one,
756                             sizeof one) < 0) {
757                                 syslog(LOG_ERR,
758                                     "can't disable v4-in-v6 on IPv6 socket");
759                                 exit(1);
760                         }
761                         break;
762                 default:
763                         break;
764                 }
765
766                 /*
767                  * If no hosts were specified, just bind to INADDR_ANY
768                  */
769                 if (strcmp("*", hosts[nhostsbak]) == 0) {
770                         if (svcport_str == NULL) {
771                                 res = malloc(sizeof(struct addrinfo));
772                                 if (res == NULL) 
773                                         out_of_mem();
774                                 mallocd_res = 1;
775                                 res->ai_flags = hints.ai_flags;
776                                 res->ai_family = hints.ai_family;
777                                 res->ai_protocol = hints.ai_protocol;
778                                 switch (res->ai_family) {
779                                 case AF_INET:
780                                         sin = malloc(sizeof(struct sockaddr_in));
781                                         if (sin == NULL) 
782                                                 out_of_mem();
783                                         sin->sin_family = AF_INET;
784                                         sin->sin_port = htons(0);
785                                         sin->sin_addr.s_addr = htonl(INADDR_ANY);
786                                         res->ai_addr = (struct sockaddr*) sin;
787                                         res->ai_addrlen = (socklen_t)
788                                             sizeof(struct sockaddr_in);
789                                         break;
790                                 case AF_INET6:
791                                         sin6 = malloc(sizeof(struct sockaddr_in6));
792                                         if (sin6 == NULL)
793                                                 out_of_mem();
794                                         sin6->sin6_family = AF_INET6;
795                                         sin6->sin6_port = htons(0);
796                                         sin6->sin6_addr = in6addr_any;
797                                         res->ai_addr = (struct sockaddr*) sin6;
798                                         res->ai_addrlen = (socklen_t)
799                                             sizeof(struct sockaddr_in6);
800                                         break;
801                                 default:
802                                         syslog(LOG_ERR, "bad addr fam %d",
803                                             res->ai_family);
804                                         exit(1);
805                                 }
806                         } else { 
807                                 if ((aicode = getaddrinfo(NULL, svcport_str,
808                                     &hints, &res)) != 0) {
809                                         syslog(LOG_ERR,
810                                             "cannot get local address for %s: %s",
811                                             nconf->nc_netid,
812                                             gai_strerror(aicode));
813                                         close(fd);
814                                         continue;
815                                 }
816                         }
817                 } else {
818                         if ((aicode = getaddrinfo(hosts[nhostsbak], svcport_str,
819                             &hints, &res)) != 0) {
820                                 syslog(LOG_ERR,
821                                     "cannot get local address for %s: %s",
822                                     nconf->nc_netid, gai_strerror(aicode));
823                                 close(fd);
824                                 continue;
825                         }
826                 }
827
828                 /* Store the fd. */
829                 sock_fd[sock_fdcnt - 1] = fd;
830
831                 /* Now, attempt the bind. */
832                 r = bindresvport_sa(fd, res->ai_addr);
833                 if (r != 0) {
834                         if (errno == EADDRINUSE && mallocd_svcport != 0) {
835                                 if (mallocd_res != 0) {
836                                         free(res->ai_addr);
837                                         free(res);
838                                 } else
839                                         freeaddrinfo(res);
840                                 return (-1);
841                         }
842                         syslog(LOG_ERR, "bindresvport_sa: %m");
843                         exit(1);
844                 }
845
846                 if (svcport_str == NULL) {
847                         svcport_str = malloc(NI_MAXSERV * sizeof(char));
848                         if (svcport_str == NULL)
849                                 out_of_mem();
850                         mallocd_svcport = 1;
851
852                         if (getnameinfo(res->ai_addr,
853                             res->ai_addr->sa_len, NULL, NI_MAXHOST,
854                             svcport_str, NI_MAXSERV * sizeof(char),
855                             NI_NUMERICHOST | NI_NUMERICSERV))
856                                 errx(1, "Cannot get port number");
857                 }
858                 if (mallocd_res != 0) {
859                         free(res->ai_addr);
860                         free(res);
861                 } else
862                         freeaddrinfo(res);
863                 res = NULL;
864         }
865         return (0);
866 }
867
868 /*
869  * Called after all the create_service() calls have succeeded, to complete
870  * the setup and registration.
871  */
872 static void
873 complete_service(struct netconfig *nconf, char *port_str)
874 {
875         struct addrinfo hints, *res = NULL;
876         struct __rpc_sockinfo si;
877         struct netbuf servaddr;
878         SVCXPRT *transp = NULL;
879         int aicode, fd, nhostsbak;
880         int registered = 0;
881
882         if ((nconf->nc_semantics != NC_TPI_CLTS) &&
883             (nconf->nc_semantics != NC_TPI_COTS) &&
884             (nconf->nc_semantics != NC_TPI_COTS_ORD))
885                 return; /* not my type */
886
887         /*
888          * XXX - using RPC library internal functions.
889          */
890         if (!__rpc_nconf2sockinfo(nconf, &si)) {
891                 syslog(LOG_ERR, "cannot get information for %s",
892                     nconf->nc_netid);
893                 return;
894         }
895
896         nhostsbak = nhosts;
897         while (nhostsbak > 0) {
898                 --nhostsbak;
899                 if (sock_fdpos >= sock_fdcnt) {
900                         /* Should never happen. */
901                         syslog(LOG_ERR, "Ran out of socket fd's");
902                         return;
903                 }
904                 fd = sock_fd[sock_fdpos++];
905                 if (fd < 0)
906                         continue;
907
908                 if (nconf->nc_semantics != NC_TPI_CLTS)
909                         listen(fd, SOMAXCONN);
910
911                 if (nconf->nc_semantics == NC_TPI_CLTS )
912                         transp = svc_dg_create(fd, 0, 0);
913                 else 
914                         transp = svc_vc_create(fd, RPC_MAXDATASIZE,
915                             RPC_MAXDATASIZE);
916
917                 if (transp != (SVCXPRT *) NULL) {
918                         if (!svc_reg(transp, MOUNTPROG, MOUNTVERS, mntsrv,
919                             NULL)) 
920                                 syslog(LOG_ERR,
921                                     "can't register %s MOUNTVERS service",
922                                     nconf->nc_netid);
923                         if (!force_v2) {
924                                 if (!svc_reg(transp, MOUNTPROG, MOUNTVERS3,
925                                     mntsrv, NULL)) 
926                                         syslog(LOG_ERR,
927                                             "can't register %s MOUNTVERS3 service",
928                                             nconf->nc_netid);
929                         }
930                 } else 
931                         syslog(LOG_WARNING, "can't create %s services",
932                             nconf->nc_netid);
933
934                 if (registered == 0) {
935                         registered = 1;
936                         memset(&hints, 0, sizeof hints);
937                         hints.ai_flags = AI_PASSIVE;
938                         hints.ai_family = si.si_af;
939                         hints.ai_socktype = si.si_socktype;
940                         hints.ai_protocol = si.si_proto;
941
942                         if ((aicode = getaddrinfo(NULL, port_str, &hints,
943                             &res)) != 0) {
944                                 syslog(LOG_ERR, "cannot get local address: %s",
945                                     gai_strerror(aicode));
946                                 exit(1);
947                         }
948
949                         servaddr.buf = malloc(res->ai_addrlen);
950                         memcpy(servaddr.buf, res->ai_addr, res->ai_addrlen);
951                         servaddr.len = res->ai_addrlen;
952
953                         rpcb_set(MOUNTPROG, MOUNTVERS, nconf, &servaddr);
954                         rpcb_set(MOUNTPROG, MOUNTVERS3, nconf, &servaddr);
955
956                         xcreated++;
957                         freeaddrinfo(res);
958                 }
959         } /* end while */
960 }
961
962 /*
963  * Clear out sockets after a failure to bind one of them, so that the
964  * cycle of socket creation/binding can start anew.
965  */
966 static void
967 clearout_service(void)
968 {
969         int i;
970
971         for (i = 0; i < sock_fdcnt; i++) {
972                 if (sock_fd[i] >= 0) {
973                         shutdown(sock_fd[i], SHUT_RDWR);
974                         close(sock_fd[i]);
975                 }
976         }
977 }
978
979 static void
980 usage(void)
981 {
982         fprintf(stderr,
983                 "usage: mountd [-2] [-d] [-e] [-l] [-n] [-p <port>] [-r] "
984                 "[-S] [-h <bindip>] [export_file ...]\n");
985         exit(1);
986 }
987
988 /*
989  * The mount rpc service
990  */
991 void
992 mntsrv(struct svc_req *rqstp, SVCXPRT *transp)
993 {
994         struct exportlist *ep;
995         struct dirlist *dp;
996         struct fhreturn fhr;
997         struct stat stb;
998         struct statfs fsb;
999         char host[NI_MAXHOST], numerichost[NI_MAXHOST];
1000         int lookup_failed = 1;
1001         struct sockaddr *saddr;
1002         u_short sport;
1003         char rpcpath[MNTPATHLEN + 1], dirpath[MAXPATHLEN];
1004         int bad = 0, defset, hostset;
1005         sigset_t sighup_mask;
1006         int numsecflavors, *secflavorsp;
1007
1008         sigemptyset(&sighup_mask);
1009         sigaddset(&sighup_mask, SIGHUP);
1010         saddr = svc_getrpccaller(transp)->buf;
1011         switch (saddr->sa_family) {
1012         case AF_INET6:
1013                 sport = ntohs(((struct sockaddr_in6 *)saddr)->sin6_port);
1014                 break;
1015         case AF_INET:
1016                 sport = ntohs(((struct sockaddr_in *)saddr)->sin_port);
1017                 break;
1018         default:
1019                 syslog(LOG_ERR, "request from unknown address family");
1020                 return;
1021         }
1022         lookup_failed = getnameinfo(saddr, saddr->sa_len, host, sizeof host, 
1023             NULL, 0, 0);
1024         getnameinfo(saddr, saddr->sa_len, numerichost,
1025             sizeof numerichost, NULL, 0, NI_NUMERICHOST);
1026         switch (rqstp->rq_proc) {
1027         case NULLPROC:
1028                 if (!svc_sendreply(transp, (xdrproc_t)xdr_void, NULL))
1029                         syslog(LOG_ERR, "can't send reply");
1030                 return;
1031         case MOUNTPROC_MNT:
1032                 if (sport >= IPPORT_RESERVED && resvport_only) {
1033                         syslog(LOG_NOTICE,
1034                             "mount request from %s from unprivileged port",
1035                             numerichost);
1036                         svcerr_weakauth(transp);
1037                         return;
1038                 }
1039                 if (!svc_getargs(transp, (xdrproc_t)xdr_dir, rpcpath)) {
1040                         syslog(LOG_NOTICE, "undecodable mount request from %s",
1041                             numerichost);
1042                         svcerr_decode(transp);
1043                         return;
1044                 }
1045
1046                 /*
1047                  * Get the real pathname and make sure it is a directory
1048                  * or a regular file if the -r option was specified
1049                  * and it exists.
1050                  */
1051                 if (realpath(rpcpath, dirpath) == NULL ||
1052                     stat(dirpath, &stb) < 0 ||
1053                     (!S_ISDIR(stb.st_mode) &&
1054                     (dir_only || !S_ISREG(stb.st_mode))) ||
1055                     statfs(dirpath, &fsb) < 0) {
1056                         chdir("/");     /* Just in case realpath doesn't */
1057                         syslog(LOG_NOTICE,
1058                             "mount request from %s for non existent path %s",
1059                             numerichost, dirpath);
1060                         if (debug)
1061                                 warnx("stat failed on %s", dirpath);
1062                         bad = ENOENT;   /* We will send error reply later */
1063                 }
1064
1065                 /* Check in the exports list */
1066                 sigprocmask(SIG_BLOCK, &sighup_mask, NULL);
1067                 ep = ex_search(&fsb.f_fsid);
1068                 hostset = defset = 0;
1069                 if (ep && (chk_host(ep->ex_defdir, saddr, &defset, &hostset,
1070                     &numsecflavors, &secflavorsp) ||
1071                     ((dp = dirp_search(ep->ex_dirl, dirpath)) &&
1072                       chk_host(dp, saddr, &defset, &hostset, &numsecflavors,
1073                        &secflavorsp)) ||
1074                     (defset && scan_tree(ep->ex_defdir, saddr) == 0 &&
1075                      scan_tree(ep->ex_dirl, saddr) == 0))) {
1076                         if (bad) {
1077                                 if (!svc_sendreply(transp, (xdrproc_t)xdr_long,
1078                                     (caddr_t)&bad))
1079                                         syslog(LOG_ERR, "can't send reply");
1080                                 sigprocmask(SIG_UNBLOCK, &sighup_mask, NULL);
1081                                 return;
1082                         }
1083                         if (hostset & DP_HOSTSET) {
1084                                 fhr.fhr_flag = hostset;
1085                                 fhr.fhr_numsecflavors = numsecflavors;
1086                                 fhr.fhr_secflavors = secflavorsp;
1087                         } else {
1088                                 fhr.fhr_flag = defset;
1089                                 fhr.fhr_numsecflavors = ep->ex_defnumsecflavors;
1090                                 fhr.fhr_secflavors = ep->ex_defsecflavors;
1091                         }
1092                         fhr.fhr_vers = rqstp->rq_vers;
1093                         /* Get the file handle */
1094                         memset(&fhr.fhr_fh, 0, sizeof(nfsfh_t));
1095                         if (getfh(dirpath, (fhandle_t *)&fhr.fhr_fh) < 0) {
1096                                 bad = errno;
1097                                 syslog(LOG_ERR, "can't get fh for %s", dirpath);
1098                                 if (!svc_sendreply(transp, (xdrproc_t)xdr_long,
1099                                     (caddr_t)&bad))
1100                                         syslog(LOG_ERR, "can't send reply");
1101                                 sigprocmask(SIG_UNBLOCK, &sighup_mask, NULL);
1102                                 return;
1103                         }
1104                         if (!svc_sendreply(transp, (xdrproc_t)xdr_fhs,
1105                             (caddr_t)&fhr))
1106                                 syslog(LOG_ERR, "can't send reply");
1107                         if (!lookup_failed)
1108                                 add_mlist(host, dirpath);
1109                         else
1110                                 add_mlist(numerichost, dirpath);
1111                         if (debug)
1112                                 warnx("mount successful");
1113                         if (dolog)
1114                                 syslog(LOG_NOTICE,
1115                                     "mount request succeeded from %s for %s",
1116                                     numerichost, dirpath);
1117                 } else {
1118                         bad = EACCES;
1119                         syslog(LOG_NOTICE,
1120                             "mount request denied from %s for %s",
1121                             numerichost, dirpath);
1122                 }
1123
1124                 if (bad && !svc_sendreply(transp, (xdrproc_t)xdr_long,
1125                     (caddr_t)&bad))
1126                         syslog(LOG_ERR, "can't send reply");
1127                 sigprocmask(SIG_UNBLOCK, &sighup_mask, NULL);
1128                 return;
1129         case MOUNTPROC_DUMP:
1130                 if (!svc_sendreply(transp, (xdrproc_t)xdr_mlist, (caddr_t)NULL))
1131                         syslog(LOG_ERR, "can't send reply");
1132                 else if (dolog)
1133                         syslog(LOG_NOTICE,
1134                             "dump request succeeded from %s",
1135                             numerichost);
1136                 return;
1137         case MOUNTPROC_UMNT:
1138                 if (sport >= IPPORT_RESERVED && resvport_only) {
1139                         syslog(LOG_NOTICE,
1140                             "umount request from %s from unprivileged port",
1141                             numerichost);
1142                         svcerr_weakauth(transp);
1143                         return;
1144                 }
1145                 if (!svc_getargs(transp, (xdrproc_t)xdr_dir, rpcpath)) {
1146                         syslog(LOG_NOTICE, "undecodable umount request from %s",
1147                             numerichost);
1148                         svcerr_decode(transp);
1149                         return;
1150                 }
1151                 if (realpath(rpcpath, dirpath) == NULL) {
1152                         syslog(LOG_NOTICE, "umount request from %s "
1153                             "for non existent path %s",
1154                             numerichost, dirpath);
1155                 }
1156                 if (!svc_sendreply(transp, (xdrproc_t)xdr_void, (caddr_t)NULL))
1157                         syslog(LOG_ERR, "can't send reply");
1158                 if (!lookup_failed)
1159                         del_mlist(host, dirpath);
1160                 del_mlist(numerichost, dirpath);
1161                 if (dolog)
1162                         syslog(LOG_NOTICE,
1163                             "umount request succeeded from %s for %s",
1164                             numerichost, dirpath);
1165                 return;
1166         case MOUNTPROC_UMNTALL:
1167                 if (sport >= IPPORT_RESERVED && resvport_only) {
1168                         syslog(LOG_NOTICE,
1169                             "umountall request from %s from unprivileged port",
1170                             numerichost);
1171                         svcerr_weakauth(transp);
1172                         return;
1173                 }
1174                 if (!svc_sendreply(transp, (xdrproc_t)xdr_void, (caddr_t)NULL))
1175                         syslog(LOG_ERR, "can't send reply");
1176                 if (!lookup_failed)
1177                         del_mlist(host, NULL);
1178                 del_mlist(numerichost, NULL);
1179                 if (dolog)
1180                         syslog(LOG_NOTICE,
1181                             "umountall request succeeded from %s",
1182                             numerichost);
1183                 return;
1184         case MOUNTPROC_EXPORT:
1185                 if (!svc_sendreply(transp, (xdrproc_t)xdr_explist, (caddr_t)NULL))
1186                         if (!svc_sendreply(transp, (xdrproc_t)xdr_explist_brief,
1187                             (caddr_t)NULL))
1188                                 syslog(LOG_ERR, "can't send reply");
1189                 if (dolog)
1190                         syslog(LOG_NOTICE,
1191                             "export request succeeded from %s",
1192                             numerichost);
1193                 return;
1194         default:
1195                 svcerr_noproc(transp);
1196                 return;
1197         }
1198 }
1199
1200 /*
1201  * Xdr conversion for a dirpath string
1202  */
1203 static int
1204 xdr_dir(XDR *xdrsp, char *dirp)
1205 {
1206         return (xdr_string(xdrsp, &dirp, MNTPATHLEN));
1207 }
1208
1209 /*
1210  * Xdr routine to generate file handle reply
1211  */
1212 static int
1213 xdr_fhs(XDR *xdrsp, caddr_t cp)
1214 {
1215         struct fhreturn *fhrp = (struct fhreturn *)cp;
1216         u_long ok = 0, len, auth;
1217         int i;
1218
1219         if (!xdr_long(xdrsp, &ok))
1220                 return (0);
1221         switch (fhrp->fhr_vers) {
1222         case 1:
1223                 return (xdr_opaque(xdrsp, (caddr_t)&fhrp->fhr_fh, NFSX_V2FH));
1224         case 3:
1225                 len = NFSX_V3FH;
1226                 if (!xdr_long(xdrsp, &len))
1227                         return (0);
1228                 if (!xdr_opaque(xdrsp, (caddr_t)&fhrp->fhr_fh, len))
1229                         return (0);
1230                 if (fhrp->fhr_numsecflavors) {
1231                         if (!xdr_int(xdrsp, &fhrp->fhr_numsecflavors))
1232                                 return (0);
1233                         for (i = 0; i < fhrp->fhr_numsecflavors; i++)
1234                                 if (!xdr_int(xdrsp, &fhrp->fhr_secflavors[i]))
1235                                         return (0);
1236                         return (1);
1237                 } else {
1238                         auth = AUTH_SYS;
1239                         len = 1;
1240                         if (!xdr_long(xdrsp, &len))
1241                                 return (0);
1242                         return (xdr_long(xdrsp, &auth));
1243                 }
1244         }
1245         return (0);
1246 }
1247
1248 static int
1249 xdr_mlist(XDR *xdrsp, caddr_t cp __unused)
1250 {
1251         struct mountlist *mlp;
1252         int true = 1;
1253         int false = 0;
1254         char *strp;
1255
1256         mlp = mlhead;
1257         while (mlp) {
1258                 if (!xdr_bool(xdrsp, &true))
1259                         return (0);
1260                 strp = &mlp->ml_host[0];
1261                 if (!xdr_string(xdrsp, &strp, MNTNAMLEN))
1262                         return (0);
1263                 strp = &mlp->ml_dirp[0];
1264                 if (!xdr_string(xdrsp, &strp, MNTPATHLEN))
1265                         return (0);
1266                 mlp = mlp->ml_next;
1267         }
1268         if (!xdr_bool(xdrsp, &false))
1269                 return (0);
1270         return (1);
1271 }
1272
1273 /*
1274  * Xdr conversion for export list
1275  */
1276 static int
1277 xdr_explist_common(XDR *xdrsp, caddr_t cp __unused, int brief)
1278 {
1279         struct exportlist *ep;
1280         int false = 0;
1281         int putdef;
1282         sigset_t sighup_mask;
1283
1284         sigemptyset(&sighup_mask);
1285         sigaddset(&sighup_mask, SIGHUP);
1286         sigprocmask(SIG_BLOCK, &sighup_mask, NULL);
1287         ep = exphead;
1288         while (ep) {
1289                 putdef = 0;
1290                 if (put_exlist(ep->ex_dirl, xdrsp, ep->ex_defdir,
1291                                &putdef, brief))
1292                         goto errout;
1293                 if (ep->ex_defdir && putdef == 0 &&
1294                         put_exlist(ep->ex_defdir, xdrsp, (struct dirlist *)NULL,
1295                         &putdef, brief))
1296                         goto errout;
1297                 ep = ep->ex_next;
1298         }
1299         sigprocmask(SIG_UNBLOCK, &sighup_mask, NULL);
1300         if (!xdr_bool(xdrsp, &false))
1301                 return (0);
1302         return (1);
1303 errout:
1304         sigprocmask(SIG_UNBLOCK, &sighup_mask, NULL);
1305         return (0);
1306 }
1307
1308 /*
1309  * Called from xdr_explist() to traverse the tree and export the
1310  * directory paths.
1311  */
1312 static int
1313 put_exlist(struct dirlist *dp, XDR *xdrsp, struct dirlist *adp, int *putdefp,
1314         int brief)
1315 {
1316         struct grouplist *grp;
1317         struct hostlist *hp;
1318         int true = 1;
1319         int false = 0;
1320         int gotalldir = 0;
1321         char *strp;
1322
1323         if (dp) {
1324                 if (put_exlist(dp->dp_left, xdrsp, adp, putdefp, brief))
1325                         return (1);
1326                 if (!xdr_bool(xdrsp, &true))
1327                         return (1);
1328                 strp = dp->dp_dirp;
1329                 if (!xdr_string(xdrsp, &strp, MNTPATHLEN))
1330                         return (1);
1331                 if (adp && !strcmp(dp->dp_dirp, adp->dp_dirp)) {
1332                         gotalldir = 1;
1333                         *putdefp = 1;
1334                 }
1335                 if (brief) {
1336                         if (!xdr_bool(xdrsp, &true))
1337                                 return (1);
1338                         strp = "(...)";
1339                         if (!xdr_string(xdrsp, &strp, MNTPATHLEN))
1340                                 return (1);
1341                 } else if ((dp->dp_flag & DP_DEFSET) == 0 &&
1342                     (gotalldir == 0 || (adp->dp_flag & DP_DEFSET) == 0)) {
1343                         hp = dp->dp_hosts;
1344                         while (hp) {
1345                                 grp = hp->ht_grp;
1346                                 if (grp->gr_type == GT_HOST) {
1347                                         if (!xdr_bool(xdrsp, &true))
1348                                                 return (1);
1349                                         strp = grp->gr_ptr.gt_addrinfo->ai_canonname;
1350                                         if (!xdr_string(xdrsp, &strp,
1351                                             MNTNAMLEN))
1352                                                 return (1);
1353                                 } else if (grp->gr_type == GT_NET) {
1354                                         if (!xdr_bool(xdrsp, &true))
1355                                                 return (1);
1356                                         strp = grp->gr_ptr.gt_net.nt_name;
1357                                         if (!xdr_string(xdrsp, &strp,
1358                                             MNTNAMLEN))
1359                                                 return (1);
1360                                 }
1361                                 hp = hp->ht_next;
1362                                 if (gotalldir && hp == (struct hostlist *)NULL) {
1363                                         hp = adp->dp_hosts;
1364                                         gotalldir = 0;
1365                                 }
1366                         }
1367                 }
1368                 if (!xdr_bool(xdrsp, &false))
1369                         return (1);
1370                 if (put_exlist(dp->dp_right, xdrsp, adp, putdefp, brief))
1371                         return (1);
1372         }
1373         return (0);
1374 }
1375
1376 static int
1377 xdr_explist(XDR *xdrsp, caddr_t cp)
1378 {
1379
1380         return xdr_explist_common(xdrsp, cp, 0);
1381 }
1382
1383 static int
1384 xdr_explist_brief(XDR *xdrsp, caddr_t cp)
1385 {
1386
1387         return xdr_explist_common(xdrsp, cp, 1);
1388 }
1389
1390 static char *line;
1391 static size_t linesize;
1392 static FILE *exp_file;
1393
1394 /*
1395  * Get the export list from one, currently open file
1396  */
1397 static void
1398 get_exportlist_one(void)
1399 {
1400         struct exportlist *ep, *ep2;
1401         struct grouplist *grp, *tgrp;
1402         struct exportlist **epp;
1403         struct dirlist *dirhead;
1404         struct statfs fsb;
1405         struct xucred anon;
1406         char *cp, *endcp, *dirp, *hst, *usr, *dom, savedc;
1407         int len, has_host, exflags, got_nondir, dirplen, netgrp;
1408
1409         v4root_phase = 0;
1410         dirhead = (struct dirlist *)NULL;
1411         while (get_line()) {
1412                 if (debug)
1413                         warnx("got line %s", line);
1414                 cp = line;
1415                 nextfield(&cp, &endcp);
1416                 if (*cp == '#')
1417                         goto nextline;
1418
1419                 /*
1420                  * Set defaults.
1421                  */
1422                 has_host = FALSE;
1423                 anon = def_anon;
1424                 exflags = MNT_EXPORTED;
1425                 got_nondir = 0;
1426                 opt_flags = 0;
1427                 ep = (struct exportlist *)NULL;
1428                 dirp = NULL;
1429
1430                 /*
1431                  * Handle the V4 root dir.
1432                  */
1433                 if (*cp == 'V' && *(cp + 1) == '4' && *(cp + 2) == ':') {
1434                         /*
1435                          * V4: just indicates that it is the v4 root point,
1436                          * so skip over that and set v4root_phase.
1437                          */
1438                         if (v4root_phase > 0) {
1439                                 syslog(LOG_ERR, "V4:duplicate line, ignored");
1440                                 goto nextline;
1441                         }
1442                         v4root_phase = 1;
1443                         cp += 3;
1444                         nextfield(&cp, &endcp);
1445                 }
1446
1447                 /*
1448                  * Create new exports list entry
1449                  */
1450                 len = endcp-cp;
1451                 tgrp = grp = get_grp();
1452                 while (len > 0) {
1453                         if (len > MNTNAMLEN) {
1454                             getexp_err(ep, tgrp);
1455                             goto nextline;
1456                         }
1457                         if (*cp == '-') {
1458                             if (ep == (struct exportlist *)NULL) {
1459                                 getexp_err(ep, tgrp);
1460                                 goto nextline;
1461                             }
1462                             if (debug)
1463                                 warnx("doing opt %s", cp);
1464                             got_nondir = 1;
1465                             if (do_opt(&cp, &endcp, ep, grp, &has_host,
1466                                 &exflags, &anon)) {
1467                                 getexp_err(ep, tgrp);
1468                                 goto nextline;
1469                             }
1470                         } else if (*cp == '/') {
1471                             savedc = *endcp;
1472                             *endcp = '\0';
1473                             if (v4root_phase > 1) {
1474                                     if (dirp != NULL) {
1475                                         syslog(LOG_ERR, "Multiple V4 dirs");
1476                                         getexp_err(ep, tgrp);
1477                                         goto nextline;
1478                                     }
1479                             }
1480                             if (check_dirpath(cp) &&
1481                                 statfs(cp, &fsb) >= 0) {
1482                                 if ((fsb.f_flags & MNT_AUTOMOUNTED) != 0)
1483                                     syslog(LOG_ERR, "Warning: exporting of "
1484                                         "automounted fs %s not supported", cp);
1485                                 if (got_nondir) {
1486                                     syslog(LOG_ERR, "dirs must be first");
1487                                     getexp_err(ep, tgrp);
1488                                     goto nextline;
1489                                 }
1490                                 if (v4root_phase == 1) {
1491                                     if (dirp != NULL) {
1492                                         syslog(LOG_ERR, "Multiple V4 dirs");
1493                                         getexp_err(ep, tgrp);
1494                                         goto nextline;
1495                                     }
1496                                     if (strlen(v4root_dirpath) == 0) {
1497                                         strlcpy(v4root_dirpath, cp,
1498                                             sizeof (v4root_dirpath));
1499                                     } else if (strcmp(v4root_dirpath, cp)
1500                                         != 0) {
1501                                         syslog(LOG_ERR,
1502                                             "different V4 dirpath %s", cp);
1503                                         getexp_err(ep, tgrp);
1504                                         goto nextline;
1505                                     }
1506                                     dirp = cp;
1507                                     v4root_phase = 2;
1508                                     got_nondir = 1;
1509                                     ep = get_exp();
1510                                 } else {
1511                                     if (ep) {
1512                                         if (ep->ex_fs.val[0] !=
1513                                             fsb.f_fsid.val[0] ||
1514                                             ep->ex_fs.val[1] !=
1515                                             fsb.f_fsid.val[1]) {
1516                                                 getexp_err(ep, tgrp);
1517                                                 goto nextline;
1518                                         }
1519                                     } else {
1520                                         /*
1521                                          * See if this directory is already
1522                                          * in the list.
1523                                          */
1524                                         ep = ex_search(&fsb.f_fsid);
1525                                         if (ep == (struct exportlist *)NULL) {
1526                                             ep = get_exp();
1527                                             ep->ex_fs = fsb.f_fsid;
1528                                             ep->ex_fsdir = strdup(fsb.f_mntonname);
1529                                             if (ep->ex_fsdir == NULL)
1530                                                 out_of_mem();
1531                                             if (debug)
1532                                                 warnx(
1533                                                   "making new ep fs=0x%x,0x%x",
1534                                                   fsb.f_fsid.val[0],
1535                                                   fsb.f_fsid.val[1]);
1536                                         } else if (debug)
1537                                             warnx("found ep fs=0x%x,0x%x",
1538                                                 fsb.f_fsid.val[0],
1539                                                 fsb.f_fsid.val[1]);
1540                                     }
1541
1542                                     /*
1543                                      * Add dirpath to export mount point.
1544                                      */
1545                                     dirp = add_expdir(&dirhead, cp, len);
1546                                     dirplen = len;
1547                                 }
1548                             } else {
1549                                 getexp_err(ep, tgrp);
1550                                 goto nextline;
1551                             }
1552                             *endcp = savedc;
1553                         } else {
1554                             savedc = *endcp;
1555                             *endcp = '\0';
1556                             got_nondir = 1;
1557                             if (ep == (struct exportlist *)NULL) {
1558                                 getexp_err(ep, tgrp);
1559                                 goto nextline;
1560                             }
1561
1562                             /*
1563                              * Get the host or netgroup.
1564                              */
1565                             setnetgrent(cp);
1566                             netgrp = getnetgrent(&hst, &usr, &dom);
1567                             do {
1568                                 if (has_host) {
1569                                     grp->gr_next = get_grp();
1570                                     grp = grp->gr_next;
1571                                 }
1572                                 if (netgrp) {
1573                                     if (hst == 0) {
1574                                         syslog(LOG_ERR,
1575                                 "null hostname in netgroup %s, skipping", cp);
1576                                         grp->gr_type = GT_IGNORE;
1577                                     } else if (get_host(hst, grp, tgrp)) {
1578                                         syslog(LOG_ERR,
1579                         "bad host %s in netgroup %s, skipping", hst, cp);
1580                                         grp->gr_type = GT_IGNORE;
1581                                     }
1582                                 } else if (get_host(cp, grp, tgrp)) {
1583                                     syslog(LOG_ERR, "bad host %s, skipping", cp);
1584                                     grp->gr_type = GT_IGNORE;
1585                                 }
1586                                 has_host = TRUE;
1587                             } while (netgrp && getnetgrent(&hst, &usr, &dom));
1588                             endnetgrent();
1589                             *endcp = savedc;
1590                         }
1591                         cp = endcp;
1592                         nextfield(&cp, &endcp);
1593                         len = endcp - cp;
1594                 }
1595                 if (check_options(dirhead)) {
1596                         getexp_err(ep, tgrp);
1597                         goto nextline;
1598                 }
1599                 if (!has_host) {
1600                         grp->gr_type = GT_DEFAULT;
1601                         if (debug)
1602                                 warnx("adding a default entry");
1603
1604                 /*
1605                  * Don't allow a network export coincide with a list of
1606                  * host(s) on the same line.
1607                  */
1608                 } else if ((opt_flags & OP_NET) && tgrp->gr_next) {
1609                         syslog(LOG_ERR, "network/host conflict");
1610                         getexp_err(ep, tgrp);
1611                         goto nextline;
1612
1613                 /*
1614                  * If an export list was specified on this line, make sure
1615                  * that we have at least one valid entry, otherwise skip it.
1616                  */
1617                 } else {
1618                         grp = tgrp;
1619                         while (grp && grp->gr_type == GT_IGNORE)
1620                                 grp = grp->gr_next;
1621                         if (! grp) {
1622                             getexp_err(ep, tgrp);
1623                             goto nextline;
1624                         }
1625                 }
1626
1627                 if (v4root_phase == 1) {
1628                         syslog(LOG_ERR, "V4:root, no dirp, ignored");
1629                         getexp_err(ep, tgrp);
1630                         goto nextline;
1631                 }
1632
1633                 /*
1634                  * Loop through hosts, pushing the exports into the kernel.
1635                  * After loop, tgrp points to the start of the list and
1636                  * grp points to the last entry in the list.
1637                  */
1638                 grp = tgrp;
1639                 do {
1640                         if (do_mount(ep, grp, exflags, &anon, dirp, dirplen,
1641                             &fsb)) {
1642                                 getexp_err(ep, tgrp);
1643                                 goto nextline;
1644                         }
1645                 } while (grp->gr_next && (grp = grp->gr_next));
1646
1647                 /*
1648                  * For V4: don't enter in mount lists.
1649                  */
1650                 if (v4root_phase > 0 && v4root_phase <= 2) {
1651                         /*
1652                          * Since these structures aren't used by mountd,
1653                          * free them up now.
1654                          */
1655                         if (ep != NULL)
1656                                 free_exp(ep);
1657                         while (tgrp != NULL) {
1658                                 grp = tgrp;
1659                                 tgrp = tgrp->gr_next;
1660                                 free_grp(grp);
1661                         }
1662                         goto nextline;
1663                 }
1664
1665                 /*
1666                  * Success. Update the data structures.
1667                  */
1668                 if (has_host) {
1669                         hang_dirp(dirhead, tgrp, ep, opt_flags);
1670                         grp->gr_next = grphead;
1671                         grphead = tgrp;
1672                 } else {
1673                         hang_dirp(dirhead, (struct grouplist *)NULL, ep,
1674                                 opt_flags);
1675                         free_grp(grp);
1676                 }
1677                 dirhead = (struct dirlist *)NULL;
1678                 if ((ep->ex_flag & EX_LINKED) == 0) {
1679                         ep2 = exphead;
1680                         epp = &exphead;
1681
1682                         /*
1683                          * Insert in the list in alphabetical order.
1684                          */
1685                         while (ep2 && strcmp(ep2->ex_fsdir, ep->ex_fsdir) < 0) {
1686                                 epp = &ep2->ex_next;
1687                                 ep2 = ep2->ex_next;
1688                         }
1689                         if (ep2)
1690                                 ep->ex_next = ep2;
1691                         *epp = ep;
1692                         ep->ex_flag |= EX_LINKED;
1693                 }
1694 nextline:
1695                 v4root_phase = 0;
1696                 if (dirhead) {
1697                         free_dir(dirhead);
1698                         dirhead = (struct dirlist *)NULL;
1699                 }
1700         }
1701 }
1702
1703 /*
1704  * Get the export list from all specified files
1705  */
1706 static void
1707 get_exportlist(void)
1708 {
1709         struct exportlist *ep, *ep2;
1710         struct grouplist *grp, *tgrp;
1711         struct export_args export;
1712         struct iovec *iov;
1713         struct statfs *fsp, *mntbufp;
1714         struct xvfsconf vfc;
1715         char errmsg[255];
1716         int num, i;
1717         int iovlen;
1718         int done;
1719         struct nfsex_args eargs;
1720
1721         if (suspend_nfsd != 0)
1722                 (void)nfssvc(NFSSVC_SUSPENDNFSD, NULL);
1723         v4root_dirpath[0] = '\0';
1724         bzero(&export, sizeof(export));
1725         export.ex_flags = MNT_DELEXPORT;
1726         iov = NULL;
1727         iovlen = 0;
1728         bzero(errmsg, sizeof(errmsg));
1729
1730         /*
1731          * First, get rid of the old list
1732          */
1733         ep = exphead;
1734         while (ep) {
1735                 ep2 = ep;
1736                 ep = ep->ex_next;
1737                 free_exp(ep2);
1738         }
1739         exphead = (struct exportlist *)NULL;
1740
1741         grp = grphead;
1742         while (grp) {
1743                 tgrp = grp;
1744                 grp = grp->gr_next;
1745                 free_grp(tgrp);
1746         }
1747         grphead = (struct grouplist *)NULL;
1748
1749         /*
1750          * and the old V4 root dir.
1751          */
1752         bzero(&eargs, sizeof (eargs));
1753         eargs.export.ex_flags = MNT_DELEXPORT;
1754         if (nfssvc(NFSSVC_V4ROOTEXPORT, (caddr_t)&eargs) < 0 &&
1755             errno != ENOENT)
1756                 syslog(LOG_ERR, "Can't delete exports for V4:");
1757
1758         /*
1759          * and clear flag that notes if a public fh has been exported.
1760          */
1761         has_publicfh = 0;
1762
1763         /*
1764          * And delete exports that are in the kernel for all local
1765          * filesystems.
1766          * XXX: Should know how to handle all local exportable filesystems.
1767          */
1768         num = getmntinfo(&mntbufp, MNT_NOWAIT);
1769
1770         if (num > 0) {
1771                 build_iovec(&iov, &iovlen, "fstype", NULL, 0);
1772                 build_iovec(&iov, &iovlen, "fspath", NULL, 0);
1773                 build_iovec(&iov, &iovlen, "from", NULL, 0);
1774                 build_iovec(&iov, &iovlen, "update", NULL, 0);
1775                 build_iovec(&iov, &iovlen, "export", &export, sizeof(export));
1776                 build_iovec(&iov, &iovlen, "errmsg", errmsg, sizeof(errmsg));
1777         }
1778
1779         for (i = 0; i < num; i++) {
1780                 fsp = &mntbufp[i];
1781                 if (getvfsbyname(fsp->f_fstypename, &vfc) != 0) {
1782                         syslog(LOG_ERR, "getvfsbyname() failed for %s",
1783                             fsp->f_fstypename);
1784                         continue;
1785                 }
1786
1787                 /*
1788                  * We do not need to delete "export" flag from
1789                  * filesystems that do not have it set.
1790                  */
1791                 if (!(fsp->f_flags & MNT_EXPORTED))
1792                     continue;
1793                 /*
1794                  * Do not delete export for network filesystem by
1795                  * passing "export" arg to nmount().
1796                  * It only makes sense to do this for local filesystems.
1797                  */
1798                 if (vfc.vfc_flags & VFCF_NETWORK)
1799                         continue;
1800
1801                 iov[1].iov_base = fsp->f_fstypename;
1802                 iov[1].iov_len = strlen(fsp->f_fstypename) + 1;
1803                 iov[3].iov_base = fsp->f_mntonname;
1804                 iov[3].iov_len = strlen(fsp->f_mntonname) + 1;
1805                 iov[5].iov_base = fsp->f_mntfromname;
1806                 iov[5].iov_len = strlen(fsp->f_mntfromname) + 1;
1807                 errmsg[0] = '\0';
1808
1809                 /*
1810                  * EXDEV is returned when path exists but is not a
1811                  * mount point.  May happens if raced with unmount.
1812                  */
1813                 if (nmount(iov, iovlen, fsp->f_flags) < 0 &&
1814                     errno != ENOENT && errno != ENOTSUP && errno != EXDEV) {
1815                         syslog(LOG_ERR,
1816                             "can't delete exports for %s: %m %s",
1817                             fsp->f_mntonname, errmsg);
1818                 }
1819         }
1820
1821         if (iov != NULL) {
1822                 /* Free strings allocated by strdup() in getmntopts.c */
1823                 free(iov[0].iov_base); /* fstype */
1824                 free(iov[2].iov_base); /* fspath */
1825                 free(iov[4].iov_base); /* from */
1826                 free(iov[6].iov_base); /* update */
1827                 free(iov[8].iov_base); /* export */
1828                 free(iov[10].iov_base); /* errmsg */
1829
1830                 /* free iov, allocated by realloc() */
1831                 free(iov);
1832                 iovlen = 0;
1833         }
1834
1835         /*
1836          * Read in the exports file and build the list, calling
1837          * nmount() as we go along to push the export rules into the kernel.
1838          */
1839         done = 0;
1840         for (i = 0; exnames[i] != NULL; i++) {
1841                 if (debug)
1842                         warnx("reading exports from %s", exnames[i]);
1843                 if ((exp_file = fopen(exnames[i], "r")) == NULL) {
1844                         syslog(LOG_WARNING, "can't open %s", exnames[i]);
1845                         continue;
1846                 }
1847                 get_exportlist_one();
1848                 fclose(exp_file);
1849                 done++;
1850         }
1851         if (done == 0) {
1852                 syslog(LOG_ERR, "can't open any exports file");
1853                 exit(2);
1854         }
1855
1856         /*
1857          * If there was no public fh, clear any previous one set.
1858          */
1859         if (has_publicfh == 0)
1860                 (void) nfssvc(NFSSVC_NOPUBLICFH, NULL);
1861
1862         /* Resume the nfsd. If they weren't suspended, this is harmless. */
1863         (void)nfssvc(NFSSVC_RESUMENFSD, NULL);
1864 }
1865
1866 /*
1867  * Allocate an export list element
1868  */
1869 static struct exportlist *
1870 get_exp(void)
1871 {
1872         struct exportlist *ep;
1873
1874         ep = (struct exportlist *)calloc(1, sizeof (struct exportlist));
1875         if (ep == (struct exportlist *)NULL)
1876                 out_of_mem();
1877         return (ep);
1878 }
1879
1880 /*
1881  * Allocate a group list element
1882  */
1883 static struct grouplist *
1884 get_grp(void)
1885 {
1886         struct grouplist *gp;
1887
1888         gp = (struct grouplist *)calloc(1, sizeof (struct grouplist));
1889         if (gp == (struct grouplist *)NULL)
1890                 out_of_mem();
1891         return (gp);
1892 }
1893
1894 /*
1895  * Clean up upon an error in get_exportlist().
1896  */
1897 static void
1898 getexp_err(struct exportlist *ep, struct grouplist *grp)
1899 {
1900         struct grouplist *tgrp;
1901
1902         if (!(opt_flags & OP_QUIET))
1903                 syslog(LOG_ERR, "bad exports list line %s", line);
1904         if (ep && (ep->ex_flag & EX_LINKED) == 0)
1905                 free_exp(ep);
1906         while (grp) {
1907                 tgrp = grp;
1908                 grp = grp->gr_next;
1909                 free_grp(tgrp);
1910         }
1911 }
1912
1913 /*
1914  * Search the export list for a matching fs.
1915  */
1916 static struct exportlist *
1917 ex_search(fsid_t *fsid)
1918 {
1919         struct exportlist *ep;
1920
1921         ep = exphead;
1922         while (ep) {
1923                 if (ep->ex_fs.val[0] == fsid->val[0] &&
1924                     ep->ex_fs.val[1] == fsid->val[1])
1925                         return (ep);
1926                 ep = ep->ex_next;
1927         }
1928         return (ep);
1929 }
1930
1931 /*
1932  * Add a directory path to the list.
1933  */
1934 static char *
1935 add_expdir(struct dirlist **dpp, char *cp, int len)
1936 {
1937         struct dirlist *dp;
1938
1939         dp = malloc(sizeof (struct dirlist));
1940         if (dp == (struct dirlist *)NULL)
1941                 out_of_mem();
1942         dp->dp_left = *dpp;
1943         dp->dp_right = (struct dirlist *)NULL;
1944         dp->dp_flag = 0;
1945         dp->dp_hosts = (struct hostlist *)NULL;
1946         dp->dp_dirp = strndup(cp, len);
1947         if (dp->dp_dirp == NULL)
1948                 out_of_mem();
1949         *dpp = dp;
1950         return (dp->dp_dirp);
1951 }
1952
1953 /*
1954  * Hang the dir list element off the dirpath binary tree as required
1955  * and update the entry for host.
1956  */
1957 static void
1958 hang_dirp(struct dirlist *dp, struct grouplist *grp, struct exportlist *ep,
1959         int flags)
1960 {
1961         struct hostlist *hp;
1962         struct dirlist *dp2;
1963
1964         if (flags & OP_ALLDIRS) {
1965                 if (ep->ex_defdir)
1966                         free((caddr_t)dp);
1967                 else
1968                         ep->ex_defdir = dp;
1969                 if (grp == (struct grouplist *)NULL) {
1970                         ep->ex_defdir->dp_flag |= DP_DEFSET;
1971                         /* Save the default security flavors list. */
1972                         ep->ex_defnumsecflavors = ep->ex_numsecflavors;
1973                         if (ep->ex_numsecflavors > 0)
1974                                 memcpy(ep->ex_defsecflavors, ep->ex_secflavors,
1975                                     sizeof(ep->ex_secflavors));
1976                 } else while (grp) {
1977                         hp = get_ht();
1978                         hp->ht_grp = grp;
1979                         hp->ht_next = ep->ex_defdir->dp_hosts;
1980                         ep->ex_defdir->dp_hosts = hp;
1981                         /* Save the security flavors list for this host set. */
1982                         grp->gr_numsecflavors = ep->ex_numsecflavors;
1983                         if (ep->ex_numsecflavors > 0)
1984                                 memcpy(grp->gr_secflavors, ep->ex_secflavors,
1985                                     sizeof(ep->ex_secflavors));
1986                         grp = grp->gr_next;
1987                 }
1988         } else {
1989
1990                 /*
1991                  * Loop through the directories adding them to the tree.
1992                  */
1993                 while (dp) {
1994                         dp2 = dp->dp_left;
1995                         add_dlist(&ep->ex_dirl, dp, grp, flags, ep);
1996                         dp = dp2;
1997                 }
1998         }
1999 }
2000
2001 /*
2002  * Traverse the binary tree either updating a node that is already there
2003  * for the new directory or adding the new node.
2004  */
2005 static void
2006 add_dlist(struct dirlist **dpp, struct dirlist *newdp, struct grouplist *grp,
2007         int flags, struct exportlist *ep)
2008 {
2009         struct dirlist *dp;
2010         struct hostlist *hp;
2011         int cmp;
2012
2013         dp = *dpp;
2014         if (dp) {
2015                 cmp = strcmp(dp->dp_dirp, newdp->dp_dirp);
2016                 if (cmp > 0) {
2017                         add_dlist(&dp->dp_left, newdp, grp, flags, ep);
2018                         return;
2019                 } else if (cmp < 0) {
2020                         add_dlist(&dp->dp_right, newdp, grp, flags, ep);
2021                         return;
2022                 } else
2023                         free((caddr_t)newdp);
2024         } else {
2025                 dp = newdp;
2026                 dp->dp_left = (struct dirlist *)NULL;
2027                 *dpp = dp;
2028         }
2029         if (grp) {
2030
2031                 /*
2032                  * Hang all of the host(s) off of the directory point.
2033                  */
2034                 do {
2035                         hp = get_ht();
2036                         hp->ht_grp = grp;
2037                         hp->ht_next = dp->dp_hosts;
2038                         dp->dp_hosts = hp;
2039                         /* Save the security flavors list for this host set. */
2040                         grp->gr_numsecflavors = ep->ex_numsecflavors;
2041                         if (ep->ex_numsecflavors > 0)
2042                                 memcpy(grp->gr_secflavors, ep->ex_secflavors,
2043                                     sizeof(ep->ex_secflavors));
2044                         grp = grp->gr_next;
2045                 } while (grp);
2046         } else {
2047                 dp->dp_flag |= DP_DEFSET;
2048                 /* Save the default security flavors list. */
2049                 ep->ex_defnumsecflavors = ep->ex_numsecflavors;
2050                 if (ep->ex_numsecflavors > 0)
2051                         memcpy(ep->ex_defsecflavors, ep->ex_secflavors,
2052                             sizeof(ep->ex_secflavors));
2053         }
2054 }
2055
2056 /*
2057  * Search for a dirpath on the export point.
2058  */
2059 static struct dirlist *
2060 dirp_search(struct dirlist *dp, char *dirp)
2061 {
2062         int cmp;
2063
2064         if (dp) {
2065                 cmp = strcmp(dp->dp_dirp, dirp);
2066                 if (cmp > 0)
2067                         return (dirp_search(dp->dp_left, dirp));
2068                 else if (cmp < 0)
2069                         return (dirp_search(dp->dp_right, dirp));
2070                 else
2071                         return (dp);
2072         }
2073         return (dp);
2074 }
2075
2076 /*
2077  * Scan for a host match in a directory tree.
2078  */
2079 static int
2080 chk_host(struct dirlist *dp, struct sockaddr *saddr, int *defsetp,
2081         int *hostsetp, int *numsecflavors, int **secflavorsp)
2082 {
2083         struct hostlist *hp;
2084         struct grouplist *grp;
2085         struct addrinfo *ai;
2086
2087         if (dp) {
2088                 if (dp->dp_flag & DP_DEFSET)
2089                         *defsetp = dp->dp_flag;
2090                 hp = dp->dp_hosts;
2091                 while (hp) {
2092                         grp = hp->ht_grp;
2093                         switch (grp->gr_type) {
2094                         case GT_HOST:
2095                                 ai = grp->gr_ptr.gt_addrinfo;
2096                                 for (; ai; ai = ai->ai_next) {
2097                                         if (!sacmp(ai->ai_addr, saddr, NULL)) {
2098                                                 *hostsetp =
2099                                                     (hp->ht_flag | DP_HOSTSET);
2100                                                 if (numsecflavors != NULL) {
2101                                                         *numsecflavors =
2102                                                             grp->gr_numsecflavors;
2103                                                         *secflavorsp =
2104                                                             grp->gr_secflavors;
2105                                                 }
2106                                                 return (1);
2107                                         }
2108                                 }
2109                                 break;
2110                         case GT_NET:
2111                                 if (!sacmp(saddr, (struct sockaddr *)
2112                                     &grp->gr_ptr.gt_net.nt_net,
2113                                     (struct sockaddr *)
2114                                     &grp->gr_ptr.gt_net.nt_mask)) {
2115                                         *hostsetp = (hp->ht_flag | DP_HOSTSET);
2116                                         if (numsecflavors != NULL) {
2117                                                 *numsecflavors =
2118                                                     grp->gr_numsecflavors;
2119                                                 *secflavorsp =
2120                                                     grp->gr_secflavors;
2121                                         }
2122                                         return (1);
2123                                 }
2124                                 break;
2125                         }
2126                         hp = hp->ht_next;
2127                 }
2128         }
2129         return (0);
2130 }
2131
2132 /*
2133  * Scan tree for a host that matches the address.
2134  */
2135 static int
2136 scan_tree(struct dirlist *dp, struct sockaddr *saddr)
2137 {
2138         int defset, hostset;
2139
2140         if (dp) {
2141                 if (scan_tree(dp->dp_left, saddr))
2142                         return (1);
2143                 if (chk_host(dp, saddr, &defset, &hostset, NULL, NULL))
2144                         return (1);
2145                 if (scan_tree(dp->dp_right, saddr))
2146                         return (1);
2147         }
2148         return (0);
2149 }
2150
2151 /*
2152  * Traverse the dirlist tree and free it up.
2153  */
2154 static void
2155 free_dir(struct dirlist *dp)
2156 {
2157
2158         if (dp) {
2159                 free_dir(dp->dp_left);
2160                 free_dir(dp->dp_right);
2161                 free_host(dp->dp_hosts);
2162                 free(dp->dp_dirp);
2163                 free(dp);
2164         }
2165 }
2166
2167 /*
2168  * Parse a colon separated list of security flavors
2169  */
2170 static int
2171 parsesec(char *seclist, struct exportlist *ep)
2172 {
2173         char *cp, savedc;
2174         int flavor;
2175
2176         ep->ex_numsecflavors = 0;
2177         for (;;) {
2178                 cp = strchr(seclist, ':');
2179                 if (cp) {
2180                         savedc = *cp;
2181                         *cp = '\0';
2182                 }
2183
2184                 if (!strcmp(seclist, "sys"))
2185                         flavor = AUTH_SYS;
2186                 else if (!strcmp(seclist, "krb5"))
2187                         flavor = RPCSEC_GSS_KRB5;
2188                 else if (!strcmp(seclist, "krb5i"))
2189                         flavor = RPCSEC_GSS_KRB5I;
2190                 else if (!strcmp(seclist, "krb5p"))
2191                         flavor = RPCSEC_GSS_KRB5P;
2192                 else {
2193                         if (cp)
2194                                 *cp = savedc;
2195                         syslog(LOG_ERR, "bad sec flavor: %s", seclist);
2196                         return (1);
2197                 }
2198                 if (ep->ex_numsecflavors == MAXSECFLAVORS) {
2199                         if (cp)
2200                                 *cp = savedc;
2201                         syslog(LOG_ERR, "too many sec flavors: %s", seclist);
2202                         return (1);
2203                 }
2204                 ep->ex_secflavors[ep->ex_numsecflavors] = flavor;
2205                 ep->ex_numsecflavors++;
2206                 if (cp) {
2207                         *cp = savedc;
2208                         seclist = cp + 1;
2209                 } else {
2210                         break;
2211                 }
2212         }
2213         return (0);
2214 }
2215
2216 /*
2217  * Parse the option string and update fields.
2218  * Option arguments may either be -<option>=<value> or
2219  * -<option> <value>
2220  */
2221 static int
2222 do_opt(char **cpp, char **endcpp, struct exportlist *ep, struct grouplist *grp,
2223         int *has_hostp, int *exflagsp, struct xucred *cr)
2224 {
2225         char *cpoptarg, *cpoptend;
2226         char *cp, *endcp, *cpopt, savedc, savedc2;
2227         int allflag, usedarg;
2228
2229         savedc2 = '\0';
2230         cpopt = *cpp;
2231         cpopt++;
2232         cp = *endcpp;
2233         savedc = *cp;
2234         *cp = '\0';
2235         while (cpopt && *cpopt) {
2236                 allflag = 1;
2237                 usedarg = -2;
2238                 if ((cpoptend = strchr(cpopt, ','))) {
2239                         *cpoptend++ = '\0';
2240                         if ((cpoptarg = strchr(cpopt, '=')))
2241                                 *cpoptarg++ = '\0';
2242                 } else {
2243                         if ((cpoptarg = strchr(cpopt, '=')))
2244                                 *cpoptarg++ = '\0';
2245                         else {
2246                                 *cp = savedc;
2247                                 nextfield(&cp, &endcp);
2248                                 **endcpp = '\0';
2249                                 if (endcp > cp && *cp != '-') {
2250                                         cpoptarg = cp;
2251                                         savedc2 = *endcp;
2252                                         *endcp = '\0';
2253                                         usedarg = 0;
2254                                 }
2255                         }
2256                 }
2257                 if (!strcmp(cpopt, "ro") || !strcmp(cpopt, "o")) {
2258                         *exflagsp |= MNT_EXRDONLY;
2259                 } else if (cpoptarg && (!strcmp(cpopt, "maproot") ||
2260                     !(allflag = strcmp(cpopt, "mapall")) ||
2261                     !strcmp(cpopt, "root") || !strcmp(cpopt, "r"))) {
2262                         usedarg++;
2263                         parsecred(cpoptarg, cr);
2264                         if (allflag == 0) {
2265                                 *exflagsp |= MNT_EXPORTANON;
2266                                 opt_flags |= OP_MAPALL;
2267                         } else
2268                                 opt_flags |= OP_MAPROOT;
2269                 } else if (cpoptarg && (!strcmp(cpopt, "mask") ||
2270                     !strcmp(cpopt, "m"))) {
2271                         if (get_net(cpoptarg, &grp->gr_ptr.gt_net, 1)) {
2272                                 syslog(LOG_ERR, "bad mask: %s", cpoptarg);
2273                                 return (1);
2274                         }
2275                         usedarg++;
2276                         opt_flags |= OP_MASK;
2277                 } else if (cpoptarg && (!strcmp(cpopt, "network") ||
2278                         !strcmp(cpopt, "n"))) {
2279                         if (strchr(cpoptarg, '/') != NULL) {
2280                                 if (debug)
2281                                         fprintf(stderr, "setting OP_MASKLEN\n");
2282                                 opt_flags |= OP_MASKLEN;
2283                         }
2284                         if (grp->gr_type != GT_NULL) {
2285                                 syslog(LOG_ERR, "network/host conflict");
2286                                 return (1);
2287                         } else if (get_net(cpoptarg, &grp->gr_ptr.gt_net, 0)) {
2288                                 syslog(LOG_ERR, "bad net: %s", cpoptarg);
2289                                 return (1);
2290                         }
2291                         grp->gr_type = GT_NET;
2292                         *has_hostp = 1;
2293                         usedarg++;
2294                         opt_flags |= OP_NET;
2295                 } else if (!strcmp(cpopt, "alldirs")) {
2296                         opt_flags |= OP_ALLDIRS;
2297                 } else if (!strcmp(cpopt, "public")) {
2298                         *exflagsp |= MNT_EXPUBLIC;
2299                 } else if (!strcmp(cpopt, "webnfs")) {
2300                         *exflagsp |= (MNT_EXPUBLIC|MNT_EXRDONLY|MNT_EXPORTANON);
2301                         opt_flags |= OP_MAPALL;
2302                 } else if (cpoptarg && !strcmp(cpopt, "index")) {
2303                         ep->ex_indexfile = strdup(cpoptarg);
2304                 } else if (!strcmp(cpopt, "quiet")) {
2305                         opt_flags |= OP_QUIET;
2306                 } else if (cpoptarg && !strcmp(cpopt, "sec")) {
2307                         if (parsesec(cpoptarg, ep))
2308                                 return (1);
2309                         opt_flags |= OP_SEC;
2310                         usedarg++;
2311                 } else {
2312                         syslog(LOG_ERR, "bad opt %s", cpopt);
2313                         return (1);
2314                 }
2315                 if (usedarg >= 0) {
2316                         *endcp = savedc2;
2317                         **endcpp = savedc;
2318                         if (usedarg > 0) {
2319                                 *cpp = cp;
2320                                 *endcpp = endcp;
2321                         }
2322                         return (0);
2323                 }
2324                 cpopt = cpoptend;
2325         }
2326         **endcpp = savedc;
2327         return (0);
2328 }
2329
2330 /*
2331  * Translate a character string to the corresponding list of network
2332  * addresses for a hostname.
2333  */
2334 static int
2335 get_host(char *cp, struct grouplist *grp, struct grouplist *tgrp)
2336 {
2337         struct grouplist *checkgrp;
2338         struct addrinfo *ai, *tai, hints;
2339         int ecode;
2340         char host[NI_MAXHOST];
2341
2342         if (grp->gr_type != GT_NULL) {
2343                 syslog(LOG_ERR, "Bad netgroup type for ip host %s", cp);
2344                 return (1);
2345         }
2346         memset(&hints, 0, sizeof hints);
2347         hints.ai_flags = AI_CANONNAME;
2348         hints.ai_protocol = IPPROTO_UDP;
2349         ecode = getaddrinfo(cp, NULL, &hints, &ai);
2350         if (ecode != 0) {
2351                 syslog(LOG_ERR,"can't get address info for host %s", cp);
2352                 return 1;
2353         }
2354         grp->gr_ptr.gt_addrinfo = ai;
2355         while (ai != NULL) {
2356                 if (ai->ai_canonname == NULL) {
2357                         if (getnameinfo(ai->ai_addr, ai->ai_addrlen, host,
2358                             sizeof host, NULL, 0, NI_NUMERICHOST) != 0)
2359                                 strlcpy(host, "?", sizeof(host));
2360                         ai->ai_canonname = strdup(host);
2361                         ai->ai_flags |= AI_CANONNAME;
2362                 }
2363                 if (debug)
2364                         fprintf(stderr, "got host %s\n", ai->ai_canonname);
2365                 /*
2366                  * Sanity check: make sure we don't already have an entry
2367                  * for this host in the grouplist.
2368                  */
2369                 for (checkgrp = tgrp; checkgrp != NULL;
2370                     checkgrp = checkgrp->gr_next) {
2371                         if (checkgrp->gr_type != GT_HOST)
2372                                 continue;
2373                         for (tai = checkgrp->gr_ptr.gt_addrinfo; tai != NULL;
2374                             tai = tai->ai_next) {
2375                                 if (sacmp(tai->ai_addr, ai->ai_addr, NULL) != 0)
2376                                         continue;
2377                                 if (debug)
2378                                         fprintf(stderr,
2379                                             "ignoring duplicate host %s\n",
2380                                             ai->ai_canonname);
2381                                 grp->gr_type = GT_IGNORE;
2382                                 return (0);
2383                         }
2384                 }
2385                 ai = ai->ai_next;
2386         }
2387         grp->gr_type = GT_HOST;
2388         return (0);
2389 }
2390
2391 /*
2392  * Free up an exports list component
2393  */
2394 static void
2395 free_exp(struct exportlist *ep)
2396 {
2397
2398         if (ep->ex_defdir) {
2399                 free_host(ep->ex_defdir->dp_hosts);
2400                 free((caddr_t)ep->ex_defdir);
2401         }
2402         if (ep->ex_fsdir)
2403                 free(ep->ex_fsdir);
2404         if (ep->ex_indexfile)
2405                 free(ep->ex_indexfile);
2406         free_dir(ep->ex_dirl);
2407         free((caddr_t)ep);
2408 }
2409
2410 /*
2411  * Free hosts.
2412  */
2413 static void
2414 free_host(struct hostlist *hp)
2415 {
2416         struct hostlist *hp2;
2417
2418         while (hp) {
2419                 hp2 = hp;
2420                 hp = hp->ht_next;
2421                 free((caddr_t)hp2);
2422         }
2423 }
2424
2425 static struct hostlist *
2426 get_ht(void)
2427 {
2428         struct hostlist *hp;
2429
2430         hp = (struct hostlist *)malloc(sizeof (struct hostlist));
2431         if (hp == (struct hostlist *)NULL)
2432                 out_of_mem();
2433         hp->ht_next = (struct hostlist *)NULL;
2434         hp->ht_flag = 0;
2435         return (hp);
2436 }
2437
2438 /*
2439  * Out of memory, fatal
2440  */
2441 static void
2442 out_of_mem(void)
2443 {
2444
2445         syslog(LOG_ERR, "out of memory");
2446         exit(2);
2447 }
2448
2449 /*
2450  * Do the nmount() syscall with the update flag to push the export info into
2451  * the kernel.
2452  */
2453 static int
2454 do_mount(struct exportlist *ep, struct grouplist *grp, int exflags,
2455     struct xucred *anoncrp, char *dirp, int dirplen, struct statfs *fsb)
2456 {
2457         struct statfs fsb1;
2458         struct addrinfo *ai;
2459         struct export_args *eap;
2460         char errmsg[255];
2461         char *cp;
2462         int done;
2463         char savedc;
2464         struct iovec *iov;
2465         int i, iovlen;
2466         int ret;
2467         struct nfsex_args nfsea;
2468
2469         eap = &nfsea.export;
2470
2471         cp = NULL;
2472         savedc = '\0';
2473         iov = NULL;
2474         iovlen = 0;
2475         ret = 0;
2476
2477         bzero(eap, sizeof (struct export_args));
2478         bzero(errmsg, sizeof(errmsg));
2479         eap->ex_flags = exflags;
2480         eap->ex_anon = *anoncrp;
2481         eap->ex_indexfile = ep->ex_indexfile;
2482         if (grp->gr_type == GT_HOST)
2483                 ai = grp->gr_ptr.gt_addrinfo;
2484         else
2485                 ai = NULL;
2486         eap->ex_numsecflavors = ep->ex_numsecflavors;
2487         for (i = 0; i < eap->ex_numsecflavors; i++)
2488                 eap->ex_secflavors[i] = ep->ex_secflavors[i];
2489         if (eap->ex_numsecflavors == 0) {
2490                 eap->ex_numsecflavors = 1;
2491                 eap->ex_secflavors[0] = AUTH_SYS;
2492         }
2493         done = FALSE;
2494
2495         if (v4root_phase == 0) {
2496                 build_iovec(&iov, &iovlen, "fstype", NULL, 0);
2497                 build_iovec(&iov, &iovlen, "fspath", NULL, 0);
2498                 build_iovec(&iov, &iovlen, "from", NULL, 0);
2499                 build_iovec(&iov, &iovlen, "update", NULL, 0);
2500                 build_iovec(&iov, &iovlen, "export", eap,
2501                     sizeof (struct export_args));
2502                 build_iovec(&iov, &iovlen, "errmsg", errmsg, sizeof(errmsg));
2503         }
2504
2505         while (!done) {
2506                 switch (grp->gr_type) {
2507                 case GT_HOST:
2508                         if (ai->ai_addr->sa_family == AF_INET6 && have_v6 == 0)
2509                                 goto skip;
2510                         eap->ex_addr = ai->ai_addr;
2511                         eap->ex_addrlen = ai->ai_addrlen;
2512                         eap->ex_masklen = 0;
2513                         break;
2514                 case GT_NET:
2515                         if (grp->gr_ptr.gt_net.nt_net.ss_family == AF_INET6 &&
2516                             have_v6 == 0)
2517                                 goto skip;
2518                         eap->ex_addr =
2519                             (struct sockaddr *)&grp->gr_ptr.gt_net.nt_net;
2520                         eap->ex_addrlen =
2521                             ((struct sockaddr *)&grp->gr_ptr.gt_net.nt_net)->sa_len;
2522                         eap->ex_mask =
2523                             (struct sockaddr *)&grp->gr_ptr.gt_net.nt_mask;
2524                         eap->ex_masklen = ((struct sockaddr *)&grp->gr_ptr.gt_net.nt_mask)->sa_len;
2525                         break;
2526                 case GT_DEFAULT:
2527                         eap->ex_addr = NULL;
2528                         eap->ex_addrlen = 0;
2529                         eap->ex_mask = NULL;
2530                         eap->ex_masklen = 0;
2531                         break;
2532                 case GT_IGNORE:
2533                         ret = 0;
2534                         goto error_exit;
2535                         break;
2536                 default:
2537                         syslog(LOG_ERR, "bad grouptype");
2538                         if (cp)
2539                                 *cp = savedc;
2540                         ret = 1;
2541                         goto error_exit;
2542                 }
2543
2544                 /*
2545                  * For V4:, use the nfssvc() syscall, instead of mount().
2546                  */
2547                 if (v4root_phase == 2) {
2548                         nfsea.fspec = v4root_dirpath;
2549                         if (nfssvc(NFSSVC_V4ROOTEXPORT, (caddr_t)&nfsea) < 0) {
2550                                 syslog(LOG_ERR, "Exporting V4: failed");
2551                                 return (2);
2552                         }
2553                 } else {
2554                         /*
2555                          * XXX:
2556                          * Maybe I should just use the fsb->f_mntonname path
2557                          * instead of looping back up the dirp to the mount
2558                          * point??
2559                          * Also, needs to know how to export all types of local
2560                          * exportable filesystems and not just "ufs".
2561                          */
2562                         iov[1].iov_base = fsb->f_fstypename; /* "fstype" */
2563                         iov[1].iov_len = strlen(fsb->f_fstypename) + 1;
2564                         iov[3].iov_base = fsb->f_mntonname; /* "fspath" */
2565                         iov[3].iov_len = strlen(fsb->f_mntonname) + 1;
2566                         iov[5].iov_base = fsb->f_mntfromname; /* "from" */
2567                         iov[5].iov_len = strlen(fsb->f_mntfromname) + 1;
2568                         errmsg[0] = '\0';
2569         
2570                         while (nmount(iov, iovlen, fsb->f_flags) < 0) {
2571                                 if (cp)
2572                                         *cp-- = savedc;
2573                                 else
2574                                         cp = dirp + dirplen - 1;
2575                                 if (opt_flags & OP_QUIET) {
2576                                         ret = 1;
2577                                         goto error_exit;
2578                                 }
2579                                 if (errno == EPERM) {
2580                                         if (debug)
2581                                                 warnx("can't change attributes for %s: %s",
2582                                                     dirp, errmsg);
2583                                         syslog(LOG_ERR,
2584                                            "can't change attributes for %s: %s",
2585                                             dirp, errmsg);
2586                                         ret = 1;
2587                                         goto error_exit;
2588                                 }
2589                                 if (opt_flags & OP_ALLDIRS) {
2590                                         if (errno == EINVAL)
2591                                                 syslog(LOG_ERR,
2592                 "-alldirs requested but %s is not a filesystem mountpoint",
2593                                                     dirp);
2594                                         else
2595                                                 syslog(LOG_ERR,
2596                                                     "could not remount %s: %m",
2597                                                     dirp);
2598                                         ret = 1;
2599                                         goto error_exit;
2600                                 }
2601                                 /* back up over the last component */
2602                                 while (*cp == '/' && cp > dirp)
2603                                         cp--;
2604                                 while (*(cp - 1) != '/' && cp > dirp)
2605                                         cp--;
2606                                 if (cp == dirp) {
2607                                         if (debug)
2608                                                 warnx("mnt unsucc");
2609                                         syslog(LOG_ERR, "can't export %s %s",
2610                                             dirp, errmsg);
2611                                         ret = 1;
2612                                         goto error_exit;
2613                                 }
2614                                 savedc = *cp;
2615                                 *cp = '\0';
2616                                 /*
2617                                  * Check that we're still on the same
2618                                  * filesystem.
2619                                  */
2620                                 if (statfs(dirp, &fsb1) != 0 ||
2621                                     bcmp(&fsb1.f_fsid, &fsb->f_fsid,
2622                                     sizeof (fsb1.f_fsid)) != 0) {
2623                                         *cp = savedc;
2624                                         syslog(LOG_ERR,
2625                                             "can't export %s %s", dirp,
2626                                             errmsg);
2627                                         ret = 1;
2628                                         goto error_exit;
2629                                 }
2630                         }
2631                 }
2632
2633                 /*
2634                  * For the experimental server:
2635                  * If this is the public directory, get the file handle
2636                  * and load it into the kernel via the nfssvc() syscall.
2637                  */
2638                 if ((exflags & MNT_EXPUBLIC) != 0) {
2639                         fhandle_t fh;
2640                         char *public_name;
2641
2642                         if (eap->ex_indexfile != NULL)
2643                                 public_name = eap->ex_indexfile;
2644                         else
2645                                 public_name = dirp;
2646                         if (getfh(public_name, &fh) < 0)
2647                                 syslog(LOG_ERR,
2648                                     "Can't get public fh for %s", public_name);
2649                         else if (nfssvc(NFSSVC_PUBLICFH, (caddr_t)&fh) < 0)
2650                                 syslog(LOG_ERR,
2651                                     "Can't set public fh for %s", public_name);
2652                         else
2653                                 has_publicfh = 1;
2654                 }
2655 skip:
2656                 if (ai != NULL)
2657                         ai = ai->ai_next;
2658                 if (ai == NULL)
2659                         done = TRUE;
2660         }
2661         if (cp)
2662                 *cp = savedc;
2663 error_exit:
2664         /* free strings allocated by strdup() in getmntopts.c */
2665         if (iov != NULL) {
2666                 free(iov[0].iov_base); /* fstype */
2667                 free(iov[2].iov_base); /* fspath */
2668                 free(iov[4].iov_base); /* from */
2669                 free(iov[6].iov_base); /* update */
2670                 free(iov[8].iov_base); /* export */
2671                 free(iov[10].iov_base); /* errmsg */
2672
2673                 /* free iov, allocated by realloc() */
2674                 free(iov);
2675         }
2676         return (ret);
2677 }
2678
2679 /*
2680  * Translate a net address.
2681  *
2682  * If `maskflg' is nonzero, then `cp' is a netmask, not a network address.
2683  */
2684 static int
2685 get_net(char *cp, struct netmsk *net, int maskflg)
2686 {
2687         struct netent *np = NULL;
2688         char *name, *p, *prefp;
2689         struct sockaddr_in sin;
2690         struct sockaddr *sa = NULL;
2691         struct addrinfo hints, *ai = NULL;
2692         char netname[NI_MAXHOST];
2693         long preflen;
2694
2695         p = prefp = NULL;
2696         if ((opt_flags & OP_MASKLEN) && !maskflg) {
2697                 p = strchr(cp, '/');
2698                 *p = '\0';
2699                 prefp = p + 1;
2700         }
2701
2702         /*
2703          * Check for a numeric address first. We wish to avoid
2704          * possible DNS lookups in getnetbyname().
2705          */
2706         if (isxdigit(*cp) || *cp == ':') {
2707                 memset(&hints, 0, sizeof hints);
2708                 /* Ensure the mask and the network have the same family. */
2709                 if (maskflg && (opt_flags & OP_NET))
2710                         hints.ai_family = net->nt_net.ss_family;
2711                 else if (!maskflg && (opt_flags & OP_HAVEMASK))
2712                         hints.ai_family = net->nt_mask.ss_family;
2713                 else
2714                         hints.ai_family = AF_UNSPEC;
2715                 hints.ai_flags = AI_NUMERICHOST;
2716                 if (getaddrinfo(cp, NULL, &hints, &ai) == 0)
2717                         sa = ai->ai_addr;
2718                 if (sa != NULL && ai->ai_family == AF_INET) {
2719                         /*
2720                          * The address in `cp' is really a network address, so
2721                          * use inet_network() to re-interpret this correctly.
2722                          * e.g. "127.1" means 127.1.0.0, not 127.0.0.1.
2723                          */
2724                         bzero(&sin, sizeof sin);
2725                         sin.sin_family = AF_INET;
2726                         sin.sin_len = sizeof sin;
2727                         sin.sin_addr = inet_makeaddr(inet_network(cp), 0);
2728                         if (debug)
2729                                 fprintf(stderr, "get_net: v4 addr %s\n",
2730                                     inet_ntoa(sin.sin_addr));
2731                         sa = (struct sockaddr *)&sin;
2732                 }
2733         }
2734         if (sa == NULL && (np = getnetbyname(cp)) != NULL) {
2735                 bzero(&sin, sizeof sin);
2736                 sin.sin_family = AF_INET;
2737                 sin.sin_len = sizeof sin;
2738                 sin.sin_addr = inet_makeaddr(np->n_net, 0);
2739                 sa = (struct sockaddr *)&sin;
2740         }
2741         if (sa == NULL)
2742                 goto fail;
2743
2744         if (maskflg) {
2745                 /* The specified sockaddr is a mask. */
2746                 if (checkmask(sa) != 0)
2747                         goto fail;
2748                 bcopy(sa, &net->nt_mask, sa->sa_len);
2749                 opt_flags |= OP_HAVEMASK;
2750         } else {
2751                 /* The specified sockaddr is a network address. */
2752                 bcopy(sa, &net->nt_net, sa->sa_len);
2753
2754                 /* Get a network name for the export list. */
2755                 if (np) {
2756                         name = np->n_name;
2757                 } else if (getnameinfo(sa, sa->sa_len, netname, sizeof netname,
2758                    NULL, 0, NI_NUMERICHOST) == 0) {
2759                         name = netname;
2760                 } else {
2761                         goto fail;
2762                 }
2763                 if ((net->nt_name = strdup(name)) == NULL)
2764                         out_of_mem();
2765
2766                 /*
2767                  * Extract a mask from either a "/<masklen>" suffix, or
2768                  * from the class of an IPv4 address.
2769                  */
2770                 if (opt_flags & OP_MASKLEN) {
2771                         preflen = strtol(prefp, NULL, 10);
2772                         if (preflen < 0L || preflen == LONG_MAX)
2773                                 goto fail;
2774                         bcopy(sa, &net->nt_mask, sa->sa_len);
2775                         if (makemask(&net->nt_mask, (int)preflen) != 0)
2776                                 goto fail;
2777                         opt_flags |= OP_HAVEMASK;
2778                         *p = '/';
2779                 } else if (sa->sa_family == AF_INET &&
2780                     (opt_flags & OP_MASK) == 0) {
2781                         in_addr_t addr;
2782
2783                         addr = ((struct sockaddr_in *)sa)->sin_addr.s_addr;
2784                         if (IN_CLASSA(addr))
2785                                 preflen = 8;
2786                         else if (IN_CLASSB(addr))
2787                                 preflen = 16;
2788                         else if (IN_CLASSC(addr))
2789                                 preflen = 24;
2790                         else if (IN_CLASSD(addr))
2791                                 preflen = 28;
2792                         else
2793                                 preflen = 32;   /* XXX */
2794
2795                         bcopy(sa, &net->nt_mask, sa->sa_len);
2796                         makemask(&net->nt_mask, (int)preflen);
2797                         opt_flags |= OP_HAVEMASK;
2798                 }
2799         }
2800
2801         if (ai)
2802                 freeaddrinfo(ai);
2803         return 0;
2804
2805 fail:
2806         if (ai)
2807                 freeaddrinfo(ai);
2808         return 1;
2809 }
2810
2811 /*
2812  * Parse out the next white space separated field
2813  */
2814 static void
2815 nextfield(char **cp, char **endcp)
2816 {
2817         char *p;
2818
2819         p = *cp;
2820         while (*p == ' ' || *p == '\t')
2821                 p++;
2822         if (*p == '\n' || *p == '\0')
2823                 *cp = *endcp = p;
2824         else {
2825                 *cp = p++;
2826                 while (*p != ' ' && *p != '\t' && *p != '\n' && *p != '\0')
2827                         p++;
2828                 *endcp = p;
2829         }
2830 }
2831
2832 /*
2833  * Get an exports file line. Skip over blank lines and handle line
2834  * continuations.
2835  */
2836 static int
2837 get_line(void)
2838 {
2839         char *p, *cp;
2840         size_t len;
2841         int totlen, cont_line;
2842
2843         /*
2844          * Loop around ignoring blank lines and getting all continuation lines.
2845          */
2846         p = line;
2847         totlen = 0;
2848         do {
2849                 if ((p = fgetln(exp_file, &len)) == NULL)
2850                         return (0);
2851                 cp = p + len - 1;
2852                 cont_line = 0;
2853                 while (cp >= p &&
2854                     (*cp == ' ' || *cp == '\t' || *cp == '\n' || *cp == '\\')) {
2855                         if (*cp == '\\')
2856                                 cont_line = 1;
2857                         cp--;
2858                         len--;
2859                 }
2860                 if (cont_line) {
2861                         *++cp = ' ';
2862                         len++;
2863                 }
2864                 if (linesize < len + totlen + 1) {
2865                         linesize = len + totlen + 1;
2866                         line = realloc(line, linesize);
2867                         if (line == NULL)
2868                                 out_of_mem();
2869                 }
2870                 memcpy(line + totlen, p, len);
2871                 totlen += len;
2872                 line[totlen] = '\0';
2873         } while (totlen == 0 || cont_line);
2874         return (1);
2875 }
2876
2877 /*
2878  * Parse a description of a credential.
2879  */
2880 static void
2881 parsecred(char *namelist, struct xucred *cr)
2882 {
2883         char *name;
2884         int cnt;
2885         char *names;
2886         struct passwd *pw;
2887         struct group *gr;
2888         gid_t groups[XU_NGROUPS + 1];
2889         int ngroups;
2890
2891         cr->cr_version = XUCRED_VERSION;
2892         /*
2893          * Set up the unprivileged user.
2894          */
2895         cr->cr_uid = 65534;
2896         cr->cr_groups[0] = 65533;
2897         cr->cr_ngroups = 1;
2898         /*
2899          * Get the user's password table entry.
2900          */
2901         names = strsep_quote(&namelist, " \t\n");
2902         name = strsep(&names, ":");
2903         /* Bug?  name could be NULL here */
2904         if (isdigit(*name) || *name == '-')
2905                 pw = getpwuid(atoi(name));
2906         else
2907                 pw = getpwnam(name);
2908         /*
2909          * Credentials specified as those of a user.
2910          */
2911         if (names == NULL) {
2912                 if (pw == NULL) {
2913                         syslog(LOG_ERR, "unknown user: %s", name);
2914                         return;
2915                 }
2916                 cr->cr_uid = pw->pw_uid;
2917                 ngroups = XU_NGROUPS + 1;
2918                 if (getgrouplist(pw->pw_name, pw->pw_gid, groups, &ngroups))
2919                         syslog(LOG_ERR, "too many groups");
2920                 /*
2921                  * Compress out duplicate.
2922                  */
2923                 cr->cr_ngroups = ngroups - 1;
2924                 cr->cr_groups[0] = groups[0];
2925                 for (cnt = 2; cnt < ngroups; cnt++)
2926                         cr->cr_groups[cnt - 1] = groups[cnt];
2927                 return;
2928         }
2929         /*
2930          * Explicit credential specified as a colon separated list:
2931          *      uid:gid:gid:...
2932          */
2933         if (pw != NULL)
2934                 cr->cr_uid = pw->pw_uid;
2935         else if (isdigit(*name) || *name == '-')
2936                 cr->cr_uid = atoi(name);
2937         else {
2938                 syslog(LOG_ERR, "unknown user: %s", name);
2939                 return;
2940         }
2941         cr->cr_ngroups = 0;
2942         while (names != NULL && *names != '\0' && cr->cr_ngroups < XU_NGROUPS) {
2943                 name = strsep(&names, ":");
2944                 if (isdigit(*name) || *name == '-') {
2945                         cr->cr_groups[cr->cr_ngroups++] = atoi(name);
2946                 } else {
2947                         if ((gr = getgrnam(name)) == NULL) {
2948                                 syslog(LOG_ERR, "unknown group: %s", name);
2949                                 continue;
2950                         }
2951                         cr->cr_groups[cr->cr_ngroups++] = gr->gr_gid;
2952                 }
2953         }
2954         if (names != NULL && *names != '\0' && cr->cr_ngroups == XU_NGROUPS)
2955                 syslog(LOG_ERR, "too many groups");
2956 }
2957
2958 #define STRSIZ  (MNTNAMLEN+MNTPATHLEN+50)
2959 /*
2960  * Routines that maintain the remote mounttab
2961  */
2962 static void
2963 get_mountlist(void)
2964 {
2965         struct mountlist *mlp, **mlpp;
2966         char *host, *dirp, *cp;
2967         char str[STRSIZ];
2968         FILE *mlfile;
2969
2970         if ((mlfile = fopen(_PATH_RMOUNTLIST, "r")) == NULL) {
2971                 if (errno == ENOENT)
2972                         return;
2973                 else {
2974                         syslog(LOG_ERR, "can't open %s", _PATH_RMOUNTLIST);
2975                         return;
2976                 }
2977         }
2978         mlpp = &mlhead;
2979         while (fgets(str, STRSIZ, mlfile) != NULL) {
2980                 cp = str;
2981                 host = strsep(&cp, " \t\n");
2982                 dirp = strsep(&cp, " \t\n");
2983                 if (host == NULL || dirp == NULL)
2984                         continue;
2985                 mlp = (struct mountlist *)malloc(sizeof (*mlp));
2986                 if (mlp == (struct mountlist *)NULL)
2987                         out_of_mem();
2988                 strncpy(mlp->ml_host, host, MNTNAMLEN);
2989                 mlp->ml_host[MNTNAMLEN] = '\0';
2990                 strncpy(mlp->ml_dirp, dirp, MNTPATHLEN);
2991                 mlp->ml_dirp[MNTPATHLEN] = '\0';
2992                 mlp->ml_next = (struct mountlist *)NULL;
2993                 *mlpp = mlp;
2994                 mlpp = &mlp->ml_next;
2995         }
2996         fclose(mlfile);
2997 }
2998
2999 static void
3000 del_mlist(char *hostp, char *dirp)
3001 {
3002         struct mountlist *mlp, **mlpp;
3003         struct mountlist *mlp2;
3004         FILE *mlfile;
3005         int fnd = 0;
3006
3007         mlpp = &mlhead;
3008         mlp = mlhead;
3009         while (mlp) {
3010                 if (!strcmp(mlp->ml_host, hostp) &&
3011                     (!dirp || !strcmp(mlp->ml_dirp, dirp))) {
3012                         fnd = 1;
3013                         mlp2 = mlp;
3014                         *mlpp = mlp = mlp->ml_next;
3015                         free((caddr_t)mlp2);
3016                 } else {
3017                         mlpp = &mlp->ml_next;
3018                         mlp = mlp->ml_next;
3019                 }
3020         }
3021         if (fnd) {
3022                 if ((mlfile = fopen(_PATH_RMOUNTLIST, "w")) == NULL) {
3023                         syslog(LOG_ERR,"can't update %s", _PATH_RMOUNTLIST);
3024                         return;
3025                 }
3026                 mlp = mlhead;
3027                 while (mlp) {
3028                         fprintf(mlfile, "%s %s\n", mlp->ml_host, mlp->ml_dirp);
3029                         mlp = mlp->ml_next;
3030                 }
3031                 fclose(mlfile);
3032         }
3033 }
3034
3035 static void
3036 add_mlist(char *hostp, char *dirp)
3037 {
3038         struct mountlist *mlp, **mlpp;
3039         FILE *mlfile;
3040
3041         mlpp = &mlhead;
3042         mlp = mlhead;
3043         while (mlp) {
3044                 if (!strcmp(mlp->ml_host, hostp) && !strcmp(mlp->ml_dirp, dirp))
3045                         return;
3046                 mlpp = &mlp->ml_next;
3047                 mlp = mlp->ml_next;
3048         }
3049         mlp = (struct mountlist *)malloc(sizeof (*mlp));
3050         if (mlp == (struct mountlist *)NULL)
3051                 out_of_mem();
3052         strncpy(mlp->ml_host, hostp, MNTNAMLEN);
3053         mlp->ml_host[MNTNAMLEN] = '\0';
3054         strncpy(mlp->ml_dirp, dirp, MNTPATHLEN);
3055         mlp->ml_dirp[MNTPATHLEN] = '\0';
3056         mlp->ml_next = (struct mountlist *)NULL;
3057         *mlpp = mlp;
3058         if ((mlfile = fopen(_PATH_RMOUNTLIST, "a")) == NULL) {
3059                 syslog(LOG_ERR, "can't update %s", _PATH_RMOUNTLIST);
3060                 return;
3061         }
3062         fprintf(mlfile, "%s %s\n", mlp->ml_host, mlp->ml_dirp);
3063         fclose(mlfile);
3064 }
3065
3066 /*
3067  * Free up a group list.
3068  */
3069 static void
3070 free_grp(struct grouplist *grp)
3071 {
3072         if (grp->gr_type == GT_HOST) {
3073                 if (grp->gr_ptr.gt_addrinfo != NULL)
3074                         freeaddrinfo(grp->gr_ptr.gt_addrinfo);
3075         } else if (grp->gr_type == GT_NET) {
3076                 if (grp->gr_ptr.gt_net.nt_name)
3077                         free(grp->gr_ptr.gt_net.nt_name);
3078         }
3079         free((caddr_t)grp);
3080 }
3081
3082 #ifdef DEBUG
3083 static void
3084 SYSLOG(int pri, const char *fmt, ...)
3085 {
3086         va_list ap;
3087
3088         va_start(ap, fmt);
3089         vfprintf(stderr, fmt, ap);
3090         va_end(ap);
3091 }
3092 #endif /* DEBUG */
3093
3094 /*
3095  * Check options for consistency.
3096  */
3097 static int
3098 check_options(struct dirlist *dp)
3099 {
3100
3101         if (v4root_phase == 0 && dp == NULL)
3102             return (1);
3103         if ((opt_flags & (OP_MAPROOT | OP_MAPALL)) == (OP_MAPROOT | OP_MAPALL)) {
3104             syslog(LOG_ERR, "-mapall and -maproot mutually exclusive");
3105             return (1);
3106         }
3107         if ((opt_flags & OP_MASK) && (opt_flags & OP_NET) == 0) {
3108                 syslog(LOG_ERR, "-mask requires -network");
3109                 return (1);
3110         }
3111         if ((opt_flags & OP_NET) && (opt_flags & OP_HAVEMASK) == 0) {
3112                 syslog(LOG_ERR, "-network requires mask specification");
3113                 return (1);
3114         }
3115         if ((opt_flags & OP_MASK) && (opt_flags & OP_MASKLEN)) {
3116                 syslog(LOG_ERR, "-mask and /masklen are mutually exclusive");
3117                 return (1);
3118         }
3119         if (v4root_phase > 0 &&
3120             (opt_flags &
3121              ~(OP_SEC | OP_MASK | OP_NET | OP_HAVEMASK | OP_MASKLEN)) != 0) {
3122             syslog(LOG_ERR,"only -sec,-net,-mask options allowed on V4:");
3123             return (1);
3124         }
3125         if ((opt_flags & OP_ALLDIRS) && dp->dp_left) {
3126             syslog(LOG_ERR, "-alldirs has multiple directories");
3127             return (1);
3128         }
3129         return (0);
3130 }
3131
3132 /*
3133  * Check an absolute directory path for any symbolic links. Return true
3134  */
3135 static int
3136 check_dirpath(char *dirp)
3137 {
3138         char *cp;
3139         int ret = 1;
3140         struct stat sb;
3141
3142         cp = dirp + 1;
3143         while (*cp && ret) {
3144                 if (*cp == '/') {
3145                         *cp = '\0';
3146                         if (lstat(dirp, &sb) < 0 || !S_ISDIR(sb.st_mode))
3147                                 ret = 0;
3148                         *cp = '/';
3149                 }
3150                 cp++;
3151         }
3152         if (lstat(dirp, &sb) < 0 || !S_ISDIR(sb.st_mode))
3153                 ret = 0;
3154         return (ret);
3155 }
3156
3157 /*
3158  * Make a netmask according to the specified prefix length. The ss_family
3159  * and other non-address fields must be initialised before calling this.
3160  */
3161 static int
3162 makemask(struct sockaddr_storage *ssp, int bitlen)
3163 {
3164         u_char *p;
3165         int bits, i, len;
3166
3167         if ((p = sa_rawaddr((struct sockaddr *)ssp, &len)) == NULL)
3168                 return (-1);
3169         if (bitlen > len * CHAR_BIT)
3170                 return (-1);
3171
3172         for (i = 0; i < len; i++) {
3173                 bits = MIN(CHAR_BIT, bitlen);
3174                 *p++ = (u_char)~0 << (CHAR_BIT - bits);
3175                 bitlen -= bits;
3176         }
3177         return 0;
3178 }
3179
3180 /*
3181  * Check that the sockaddr is a valid netmask. Returns 0 if the mask
3182  * is acceptable (i.e. of the form 1...10....0).
3183  */
3184 static int
3185 checkmask(struct sockaddr *sa)
3186 {
3187         u_char *mask;
3188         int i, len;
3189
3190         if ((mask = sa_rawaddr(sa, &len)) == NULL)
3191                 return (-1);
3192
3193         for (i = 0; i < len; i++)
3194                 if (mask[i] != 0xff)
3195                         break;
3196         if (i < len) {
3197                 if (~mask[i] & (u_char)(~mask[i] + 1))
3198                         return (-1);
3199                 i++;
3200         }
3201         for (; i < len; i++)
3202                 if (mask[i] != 0)
3203                         return (-1);
3204         return (0);
3205 }
3206
3207 /*
3208  * Compare two sockaddrs according to a specified mask. Return zero if
3209  * `sa1' matches `sa2' when filtered by the netmask in `samask'.
3210  * If samask is NULL, perform a full comparison.
3211  */
3212 static int
3213 sacmp(struct sockaddr *sa1, struct sockaddr *sa2, struct sockaddr *samask)
3214 {
3215         unsigned char *p1, *p2, *mask;
3216         int len, i;
3217
3218         if (sa1->sa_family != sa2->sa_family ||
3219             (p1 = sa_rawaddr(sa1, &len)) == NULL ||
3220             (p2 = sa_rawaddr(sa2, NULL)) == NULL)
3221                 return (1);
3222
3223         switch (sa1->sa_family) {
3224         case AF_INET6:
3225                 if (((struct sockaddr_in6 *)sa1)->sin6_scope_id !=
3226                     ((struct sockaddr_in6 *)sa2)->sin6_scope_id)
3227                         return (1);
3228                 break;
3229         }
3230
3231         /* Simple binary comparison if no mask specified. */
3232         if (samask == NULL)
3233                 return (memcmp(p1, p2, len));
3234
3235         /* Set up the mask, and do a mask-based comparison. */
3236         if (sa1->sa_family != samask->sa_family ||
3237             (mask = sa_rawaddr(samask, NULL)) == NULL)
3238                 return (1);
3239
3240         for (i = 0; i < len; i++)
3241                 if ((p1[i] & mask[i]) != (p2[i] & mask[i]))
3242                         return (1);
3243         return (0);
3244 }
3245
3246 /*
3247  * Return a pointer to the part of the sockaddr that contains the
3248  * raw address, and set *nbytes to its length in bytes. Returns
3249  * NULL if the address family is unknown.
3250  */
3251 static void *
3252 sa_rawaddr(struct sockaddr *sa, int *nbytes) {
3253         void *p;
3254         int len;
3255
3256         switch (sa->sa_family) {
3257         case AF_INET:
3258                 len = sizeof(((struct sockaddr_in *)sa)->sin_addr);
3259                 p = &((struct sockaddr_in *)sa)->sin_addr;
3260                 break;
3261         case AF_INET6:
3262                 len = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
3263                 p = &((struct sockaddr_in6 *)sa)->sin6_addr;
3264                 break;
3265         default:
3266                 p = NULL;
3267                 len = 0;
3268         }
3269
3270         if (nbytes != NULL)
3271                 *nbytes = len;
3272         return (p);
3273 }
3274
3275 static void
3276 huphandler(int sig __unused)
3277 {
3278
3279         got_sighup = 1;
3280 }
3281
3282 static void
3283 terminate(int sig __unused)
3284 {
3285         pidfile_remove(pfh);
3286         rpcb_unset(MOUNTPROG, MOUNTVERS, NULL);
3287         rpcb_unset(MOUNTPROG, MOUNTVERS3, NULL);
3288         exit (0);
3289 }