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