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