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