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