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