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