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