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