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