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