mountd.c revision 192993
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: head/usr.sbin/mountd/mountd.c 192993 2009-05-28 20:28:13Z rmacklem $");
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			goto nextline;
1419
1420		/*
1421		 * Success. Update the data structures.
1422		 */
1423		if (has_host) {
1424			hang_dirp(dirhead, tgrp, ep, opt_flags);
1425			grp->gr_next = grphead;
1426			grphead = tgrp;
1427		} else {
1428			hang_dirp(dirhead, (struct grouplist *)NULL, ep,
1429				opt_flags);
1430			free_grp(grp);
1431		}
1432		dirhead = (struct dirlist *)NULL;
1433		if ((ep->ex_flag & EX_LINKED) == 0) {
1434			ep2 = exphead;
1435			epp = &exphead;
1436
1437			/*
1438			 * Insert in the list in alphabetical order.
1439			 */
1440			while (ep2 && strcmp(ep2->ex_fsdir, ep->ex_fsdir) < 0) {
1441				epp = &ep2->ex_next;
1442				ep2 = ep2->ex_next;
1443			}
1444			if (ep2)
1445				ep->ex_next = ep2;
1446			*epp = ep;
1447			ep->ex_flag |= EX_LINKED;
1448		}
1449nextline:
1450		v4root_phase = 0;
1451		if (dirhead) {
1452			free_dir(dirhead);
1453			dirhead = (struct dirlist *)NULL;
1454		}
1455	}
1456}
1457
1458/*
1459 * Get the export list from all specified files
1460 */
1461void
1462get_exportlist()
1463{
1464	struct exportlist *ep, *ep2;
1465	struct grouplist *grp, *tgrp;
1466	struct export_args export;
1467	struct iovec *iov;
1468	struct statfs *fsp, *mntbufp;
1469	struct xvfsconf vfc;
1470	char *dirp;
1471	char errmsg[255];
1472	int dirplen, num, i;
1473	int iovlen;
1474	int done;
1475	struct nfsex_args eargs;
1476
1477	v4root_dirpath[0] = '\0';
1478	bzero(&export, sizeof(export));
1479	export.ex_flags = MNT_DELEXPORT;
1480	dirp = NULL;
1481	dirplen = 0;
1482	iov = NULL;
1483	iovlen = 0;
1484	bzero(errmsg, sizeof(errmsg));
1485
1486	/*
1487	 * First, get rid of the old list
1488	 */
1489	ep = exphead;
1490	while (ep) {
1491		ep2 = ep;
1492		ep = ep->ex_next;
1493		free_exp(ep2);
1494	}
1495	exphead = (struct exportlist *)NULL;
1496
1497	grp = grphead;
1498	while (grp) {
1499		tgrp = grp;
1500		grp = grp->gr_next;
1501		free_grp(tgrp);
1502	}
1503	grphead = (struct grouplist *)NULL;
1504
1505	/*
1506	 * and the old V4 root dir.
1507	 */
1508	bzero(&eargs, sizeof (eargs));
1509	eargs.export.ex_flags = MNT_DELEXPORT;
1510	if (run_v4server > 0 &&
1511	    nfssvc(NFSSVC_V4ROOTEXPORT, (caddr_t)&eargs) < 0 &&
1512	    errno != ENOENT)
1513		syslog(LOG_ERR, "Can't delete exports for V4:");
1514
1515	/*
1516	 * and clear flag that notes if a public fh has been exported.
1517	 */
1518	has_publicfh = 0;
1519
1520	/*
1521	 * And delete exports that are in the kernel for all local
1522	 * filesystems.
1523	 * XXX: Should know how to handle all local exportable filesystems.
1524	 */
1525	num = getmntinfo(&mntbufp, MNT_NOWAIT);
1526
1527	if (num > 0) {
1528		build_iovec(&iov, &iovlen, "fstype", NULL, 0);
1529		build_iovec(&iov, &iovlen, "fspath", NULL, 0);
1530		build_iovec(&iov, &iovlen, "from", NULL, 0);
1531		build_iovec(&iov, &iovlen, "update", NULL, 0);
1532		build_iovec(&iov, &iovlen, "export", &export, sizeof(export));
1533		build_iovec(&iov, &iovlen, "errmsg", errmsg, sizeof(errmsg));
1534	}
1535
1536	for (i = 0; i < num; i++) {
1537		fsp = &mntbufp[i];
1538		if (getvfsbyname(fsp->f_fstypename, &vfc) != 0) {
1539			syslog(LOG_ERR, "getvfsbyname() failed for %s",
1540			    fsp->f_fstypename);
1541			continue;
1542		}
1543
1544		/*
1545		 * Do not delete export for network filesystem by
1546		 * passing "export" arg to nmount().
1547		 * It only makes sense to do this for local filesystems.
1548		 */
1549		if (vfc.vfc_flags & VFCF_NETWORK)
1550			continue;
1551
1552		iov[1].iov_base = fsp->f_fstypename;
1553		iov[1].iov_len = strlen(fsp->f_fstypename) + 1;
1554		iov[3].iov_base = fsp->f_mntonname;
1555		iov[3].iov_len = strlen(fsp->f_mntonname) + 1;
1556		iov[5].iov_base = fsp->f_mntfromname;
1557		iov[5].iov_len = strlen(fsp->f_mntfromname) + 1;
1558
1559		if (nmount(iov, iovlen, fsp->f_flags) < 0 &&
1560		    errno != ENOENT && errno != ENOTSUP) {
1561			syslog(LOG_ERR,
1562			    "can't delete exports for %s: %m %s",
1563			    fsp->f_mntonname, errmsg);
1564		}
1565	}
1566
1567	if (iov != NULL) {
1568		/* Free strings allocated by strdup() in getmntopts.c */
1569		free(iov[0].iov_base); /* fstype */
1570		free(iov[2].iov_base); /* fspath */
1571		free(iov[4].iov_base); /* from */
1572		free(iov[6].iov_base); /* update */
1573		free(iov[8].iov_base); /* export */
1574		free(iov[10].iov_base); /* errmsg */
1575
1576		/* free iov, allocated by realloc() */
1577		free(iov);
1578		iovlen = 0;
1579	}
1580
1581	/*
1582	 * Read in the exports file and build the list, calling
1583	 * nmount() as we go along to push the export rules into the kernel.
1584	 */
1585	done = 0;
1586	for (i = 0; exnames[i] != NULL; i++) {
1587		if (debug)
1588			warnx("reading exports from %s", exnames[i]);
1589		if ((exp_file = fopen(exnames[i], "r")) == NULL) {
1590			syslog(LOG_WARNING, "can't open %s", exnames[i]);
1591			continue;
1592		}
1593		get_exportlist_one();
1594		fclose(exp_file);
1595		done++;
1596	}
1597	if (done == 0) {
1598		syslog(LOG_ERR, "can't open any exports file");
1599		exit(2);
1600	}
1601
1602	/*
1603	 * If there was no public fh, clear any previous one set.
1604	 */
1605	if (run_v4server > 0 && has_publicfh == 0)
1606		(void) nfssvc(NFSSVC_NOPUBLICFH, NULL);
1607}
1608
1609/*
1610 * Allocate an export list element
1611 */
1612struct exportlist *
1613get_exp()
1614{
1615	struct exportlist *ep;
1616
1617	ep = (struct exportlist *)malloc(sizeof (struct exportlist));
1618	if (ep == (struct exportlist *)NULL)
1619		out_of_mem();
1620	memset(ep, 0, sizeof(struct exportlist));
1621	return (ep);
1622}
1623
1624/*
1625 * Allocate a group list element
1626 */
1627struct grouplist *
1628get_grp()
1629{
1630	struct grouplist *gp;
1631
1632	gp = (struct grouplist *)malloc(sizeof (struct grouplist));
1633	if (gp == (struct grouplist *)NULL)
1634		out_of_mem();
1635	memset(gp, 0, sizeof(struct grouplist));
1636	return (gp);
1637}
1638
1639/*
1640 * Clean up upon an error in get_exportlist().
1641 */
1642void
1643getexp_err(ep, grp)
1644	struct exportlist *ep;
1645	struct grouplist *grp;
1646{
1647	struct grouplist *tgrp;
1648
1649	if (!(opt_flags & OP_QUIET))
1650		syslog(LOG_ERR, "bad exports list line %s", line);
1651	if (ep && (ep->ex_flag & EX_LINKED) == 0)
1652		free_exp(ep);
1653	while (grp) {
1654		tgrp = grp;
1655		grp = grp->gr_next;
1656		free_grp(tgrp);
1657	}
1658}
1659
1660/*
1661 * Search the export list for a matching fs.
1662 */
1663struct exportlist *
1664ex_search(fsid)
1665	fsid_t *fsid;
1666{
1667	struct exportlist *ep;
1668
1669	ep = exphead;
1670	while (ep) {
1671		if (ep->ex_fs.val[0] == fsid->val[0] &&
1672		    ep->ex_fs.val[1] == fsid->val[1])
1673			return (ep);
1674		ep = ep->ex_next;
1675	}
1676	return (ep);
1677}
1678
1679/*
1680 * Add a directory path to the list.
1681 */
1682char *
1683add_expdir(dpp, cp, len)
1684	struct dirlist **dpp;
1685	char *cp;
1686	int len;
1687{
1688	struct dirlist *dp;
1689
1690	dp = (struct dirlist *)malloc(sizeof (struct dirlist) + len);
1691	if (dp == (struct dirlist *)NULL)
1692		out_of_mem();
1693	dp->dp_left = *dpp;
1694	dp->dp_right = (struct dirlist *)NULL;
1695	dp->dp_flag = 0;
1696	dp->dp_hosts = (struct hostlist *)NULL;
1697	strcpy(dp->dp_dirp, cp);
1698	*dpp = dp;
1699	return (dp->dp_dirp);
1700}
1701
1702/*
1703 * Hang the dir list element off the dirpath binary tree as required
1704 * and update the entry for host.
1705 */
1706void
1707hang_dirp(dp, grp, ep, flags)
1708	struct dirlist *dp;
1709	struct grouplist *grp;
1710	struct exportlist *ep;
1711	int flags;
1712{
1713	struct hostlist *hp;
1714	struct dirlist *dp2;
1715
1716	if (flags & OP_ALLDIRS) {
1717		if (ep->ex_defdir)
1718			free((caddr_t)dp);
1719		else
1720			ep->ex_defdir = dp;
1721		if (grp == (struct grouplist *)NULL) {
1722			ep->ex_defdir->dp_flag |= DP_DEFSET;
1723		} else while (grp) {
1724			hp = get_ht();
1725			hp->ht_grp = grp;
1726			hp->ht_next = ep->ex_defdir->dp_hosts;
1727			ep->ex_defdir->dp_hosts = hp;
1728			grp = grp->gr_next;
1729		}
1730	} else {
1731
1732		/*
1733		 * Loop through the directories adding them to the tree.
1734		 */
1735		while (dp) {
1736			dp2 = dp->dp_left;
1737			add_dlist(&ep->ex_dirl, dp, grp, flags);
1738			dp = dp2;
1739		}
1740	}
1741}
1742
1743/*
1744 * Traverse the binary tree either updating a node that is already there
1745 * for the new directory or adding the new node.
1746 */
1747void
1748add_dlist(dpp, newdp, grp, flags)
1749	struct dirlist **dpp;
1750	struct dirlist *newdp;
1751	struct grouplist *grp;
1752	int flags;
1753{
1754	struct dirlist *dp;
1755	struct hostlist *hp;
1756	int cmp;
1757
1758	dp = *dpp;
1759	if (dp) {
1760		cmp = strcmp(dp->dp_dirp, newdp->dp_dirp);
1761		if (cmp > 0) {
1762			add_dlist(&dp->dp_left, newdp, grp, flags);
1763			return;
1764		} else if (cmp < 0) {
1765			add_dlist(&dp->dp_right, newdp, grp, flags);
1766			return;
1767		} else
1768			free((caddr_t)newdp);
1769	} else {
1770		dp = newdp;
1771		dp->dp_left = (struct dirlist *)NULL;
1772		*dpp = dp;
1773	}
1774	if (grp) {
1775
1776		/*
1777		 * Hang all of the host(s) off of the directory point.
1778		 */
1779		do {
1780			hp = get_ht();
1781			hp->ht_grp = grp;
1782			hp->ht_next = dp->dp_hosts;
1783			dp->dp_hosts = hp;
1784			grp = grp->gr_next;
1785		} while (grp);
1786	} else {
1787		dp->dp_flag |= DP_DEFSET;
1788	}
1789}
1790
1791/*
1792 * Search for a dirpath on the export point.
1793 */
1794struct dirlist *
1795dirp_search(dp, dirp)
1796	struct dirlist *dp;
1797	char *dirp;
1798{
1799	int cmp;
1800
1801	if (dp) {
1802		cmp = strcmp(dp->dp_dirp, dirp);
1803		if (cmp > 0)
1804			return (dirp_search(dp->dp_left, dirp));
1805		else if (cmp < 0)
1806			return (dirp_search(dp->dp_right, dirp));
1807		else
1808			return (dp);
1809	}
1810	return (dp);
1811}
1812
1813/*
1814 * Scan for a host match in a directory tree.
1815 */
1816int
1817chk_host(dp, saddr, defsetp, hostsetp)
1818	struct dirlist *dp;
1819	struct sockaddr *saddr;
1820	int *defsetp;
1821	int *hostsetp;
1822{
1823	struct hostlist *hp;
1824	struct grouplist *grp;
1825	struct addrinfo *ai;
1826
1827	if (dp) {
1828		if (dp->dp_flag & DP_DEFSET)
1829			*defsetp = dp->dp_flag;
1830		hp = dp->dp_hosts;
1831		while (hp) {
1832			grp = hp->ht_grp;
1833			switch (grp->gr_type) {
1834			case GT_HOST:
1835				ai = grp->gr_ptr.gt_addrinfo;
1836				for (; ai; ai = ai->ai_next) {
1837					if (!sacmp(ai->ai_addr, saddr, NULL)) {
1838						*hostsetp =
1839						    (hp->ht_flag | DP_HOSTSET);
1840						return (1);
1841					}
1842				}
1843				break;
1844			case GT_NET:
1845				if (!sacmp(saddr, (struct sockaddr *)
1846				    &grp->gr_ptr.gt_net.nt_net,
1847				    (struct sockaddr *)
1848				    &grp->gr_ptr.gt_net.nt_mask)) {
1849					*hostsetp = (hp->ht_flag | DP_HOSTSET);
1850					return (1);
1851				}
1852				break;
1853			}
1854			hp = hp->ht_next;
1855		}
1856	}
1857	return (0);
1858}
1859
1860/*
1861 * Scan tree for a host that matches the address.
1862 */
1863int
1864scan_tree(dp, saddr)
1865	struct dirlist *dp;
1866	struct sockaddr *saddr;
1867{
1868	int defset, hostset;
1869
1870	if (dp) {
1871		if (scan_tree(dp->dp_left, saddr))
1872			return (1);
1873		if (chk_host(dp, saddr, &defset, &hostset))
1874			return (1);
1875		if (scan_tree(dp->dp_right, saddr))
1876			return (1);
1877	}
1878	return (0);
1879}
1880
1881/*
1882 * Traverse the dirlist tree and free it up.
1883 */
1884void
1885free_dir(dp)
1886	struct dirlist *dp;
1887{
1888
1889	if (dp) {
1890		free_dir(dp->dp_left);
1891		free_dir(dp->dp_right);
1892		free_host(dp->dp_hosts);
1893		free((caddr_t)dp);
1894	}
1895}
1896
1897/*
1898 * Parse a colon separated list of security flavors
1899 */
1900int
1901parsesec(seclist, ep)
1902	char *seclist;
1903	struct exportlist *ep;
1904{
1905	char *cp, savedc;
1906	int flavor;
1907
1908	ep->ex_numsecflavors = 0;
1909	for (;;) {
1910		cp = strchr(seclist, ':');
1911		if (cp) {
1912			savedc = *cp;
1913			*cp = '\0';
1914		}
1915
1916		if (!strcmp(seclist, "sys"))
1917			flavor = AUTH_SYS;
1918		else if (!strcmp(seclist, "krb5"))
1919			flavor = RPCSEC_GSS_KRB5;
1920		else if (!strcmp(seclist, "krb5i"))
1921			flavor = RPCSEC_GSS_KRB5I;
1922		else if (!strcmp(seclist, "krb5p"))
1923			flavor = RPCSEC_GSS_KRB5P;
1924		else {
1925			if (cp)
1926				*cp = savedc;
1927			syslog(LOG_ERR, "bad sec flavor: %s", seclist);
1928			return (1);
1929		}
1930		if (ep->ex_numsecflavors == MAXSECFLAVORS) {
1931			if (cp)
1932				*cp = savedc;
1933			syslog(LOG_ERR, "too many sec flavors: %s", seclist);
1934			return (1);
1935		}
1936		ep->ex_secflavors[ep->ex_numsecflavors] = flavor;
1937		ep->ex_numsecflavors++;
1938		if (cp) {
1939			*cp = savedc;
1940			seclist = cp + 1;
1941		} else {
1942			break;
1943		}
1944	}
1945	return (0);
1946}
1947
1948/*
1949 * Parse the option string and update fields.
1950 * Option arguments may either be -<option>=<value> or
1951 * -<option> <value>
1952 */
1953int
1954do_opt(cpp, endcpp, ep, grp, has_hostp, exflagsp, cr)
1955	char **cpp, **endcpp;
1956	struct exportlist *ep;
1957	struct grouplist *grp;
1958	int *has_hostp;
1959	int *exflagsp;
1960	struct xucred *cr;
1961{
1962	char *cpoptarg, *cpoptend;
1963	char *cp, *endcp, *cpopt, savedc, savedc2;
1964	int allflag, usedarg;
1965
1966	savedc2 = '\0';
1967	cpopt = *cpp;
1968	cpopt++;
1969	cp = *endcpp;
1970	savedc = *cp;
1971	*cp = '\0';
1972	while (cpopt && *cpopt) {
1973		allflag = 1;
1974		usedarg = -2;
1975		if ((cpoptend = strchr(cpopt, ','))) {
1976			*cpoptend++ = '\0';
1977			if ((cpoptarg = strchr(cpopt, '=')))
1978				*cpoptarg++ = '\0';
1979		} else {
1980			if ((cpoptarg = strchr(cpopt, '=')))
1981				*cpoptarg++ = '\0';
1982			else {
1983				*cp = savedc;
1984				nextfield(&cp, &endcp);
1985				**endcpp = '\0';
1986				if (endcp > cp && *cp != '-') {
1987					cpoptarg = cp;
1988					savedc2 = *endcp;
1989					*endcp = '\0';
1990					usedarg = 0;
1991				}
1992			}
1993		}
1994		if (!strcmp(cpopt, "ro") || !strcmp(cpopt, "o")) {
1995			*exflagsp |= MNT_EXRDONLY;
1996		} else if (cpoptarg && (!strcmp(cpopt, "maproot") ||
1997		    !(allflag = strcmp(cpopt, "mapall")) ||
1998		    !strcmp(cpopt, "root") || !strcmp(cpopt, "r"))) {
1999			usedarg++;
2000			parsecred(cpoptarg, cr);
2001			if (allflag == 0) {
2002				*exflagsp |= MNT_EXPORTANON;
2003				opt_flags |= OP_MAPALL;
2004			} else
2005				opt_flags |= OP_MAPROOT;
2006		} else if (cpoptarg && (!strcmp(cpopt, "mask") ||
2007		    !strcmp(cpopt, "m"))) {
2008			if (get_net(cpoptarg, &grp->gr_ptr.gt_net, 1)) {
2009				syslog(LOG_ERR, "bad mask: %s", cpoptarg);
2010				return (1);
2011			}
2012			usedarg++;
2013			opt_flags |= OP_MASK;
2014		} else if (cpoptarg && (!strcmp(cpopt, "network") ||
2015			!strcmp(cpopt, "n"))) {
2016			if (strchr(cpoptarg, '/') != NULL) {
2017				if (debug)
2018					fprintf(stderr, "setting OP_MASKLEN\n");
2019				opt_flags |= OP_MASKLEN;
2020			}
2021			if (grp->gr_type != GT_NULL) {
2022				syslog(LOG_ERR, "network/host conflict");
2023				return (1);
2024			} else if (get_net(cpoptarg, &grp->gr_ptr.gt_net, 0)) {
2025				syslog(LOG_ERR, "bad net: %s", cpoptarg);
2026				return (1);
2027			}
2028			grp->gr_type = GT_NET;
2029			*has_hostp = 1;
2030			usedarg++;
2031			opt_flags |= OP_NET;
2032		} else if (!strcmp(cpopt, "alldirs")) {
2033			opt_flags |= OP_ALLDIRS;
2034		} else if (!strcmp(cpopt, "public")) {
2035			*exflagsp |= MNT_EXPUBLIC;
2036		} else if (!strcmp(cpopt, "webnfs")) {
2037			*exflagsp |= (MNT_EXPUBLIC|MNT_EXRDONLY|MNT_EXPORTANON);
2038			opt_flags |= OP_MAPALL;
2039		} else if (cpoptarg && !strcmp(cpopt, "index")) {
2040			ep->ex_indexfile = strdup(cpoptarg);
2041		} else if (!strcmp(cpopt, "quiet")) {
2042			opt_flags |= OP_QUIET;
2043		} else if (!strcmp(cpopt, "sec")) {
2044			if (parsesec(cpoptarg, ep))
2045				return (1);
2046			opt_flags |= OP_SEC;
2047			usedarg++;
2048		} else {
2049			syslog(LOG_ERR, "bad opt %s", cpopt);
2050			return (1);
2051		}
2052		if (usedarg >= 0) {
2053			*endcp = savedc2;
2054			**endcpp = savedc;
2055			if (usedarg > 0) {
2056				*cpp = cp;
2057				*endcpp = endcp;
2058			}
2059			return (0);
2060		}
2061		cpopt = cpoptend;
2062	}
2063	**endcpp = savedc;
2064	return (0);
2065}
2066
2067/*
2068 * Translate a character string to the corresponding list of network
2069 * addresses for a hostname.
2070 */
2071int
2072get_host(cp, grp, tgrp)
2073	char *cp;
2074	struct grouplist *grp;
2075	struct grouplist *tgrp;
2076{
2077	struct grouplist *checkgrp;
2078	struct addrinfo *ai, *tai, hints;
2079	int ecode;
2080	char host[NI_MAXHOST];
2081
2082	if (grp->gr_type != GT_NULL) {
2083		syslog(LOG_ERR, "Bad netgroup type for ip host %s", cp);
2084		return (1);
2085	}
2086	memset(&hints, 0, sizeof hints);
2087	hints.ai_flags = AI_CANONNAME;
2088	hints.ai_protocol = IPPROTO_UDP;
2089	ecode = getaddrinfo(cp, NULL, &hints, &ai);
2090	if (ecode != 0) {
2091		syslog(LOG_ERR,"can't get address info for host %s", cp);
2092		return 1;
2093	}
2094	grp->gr_ptr.gt_addrinfo = ai;
2095	while (ai != NULL) {
2096		if (ai->ai_canonname == NULL) {
2097			if (getnameinfo(ai->ai_addr, ai->ai_addrlen, host,
2098			    sizeof host, NULL, 0, NI_NUMERICHOST) != 0)
2099				strlcpy(host, "?", sizeof(host));
2100			ai->ai_canonname = strdup(host);
2101			ai->ai_flags |= AI_CANONNAME;
2102		}
2103		if (debug)
2104			fprintf(stderr, "got host %s\n", ai->ai_canonname);
2105		/*
2106		 * Sanity check: make sure we don't already have an entry
2107		 * for this host in the grouplist.
2108		 */
2109		for (checkgrp = tgrp; checkgrp != NULL;
2110		    checkgrp = checkgrp->gr_next) {
2111			if (checkgrp->gr_type != GT_HOST)
2112				continue;
2113			for (tai = checkgrp->gr_ptr.gt_addrinfo; tai != NULL;
2114			    tai = tai->ai_next) {
2115				if (sacmp(tai->ai_addr, ai->ai_addr, NULL) != 0)
2116					continue;
2117				if (debug)
2118					fprintf(stderr,
2119					    "ignoring duplicate host %s\n",
2120					    ai->ai_canonname);
2121				grp->gr_type = GT_IGNORE;
2122				return (0);
2123			}
2124		}
2125		ai = ai->ai_next;
2126	}
2127	grp->gr_type = GT_HOST;
2128	return (0);
2129}
2130
2131/*
2132 * Free up an exports list component
2133 */
2134void
2135free_exp(ep)
2136	struct exportlist *ep;
2137{
2138
2139	if (ep->ex_defdir) {
2140		free_host(ep->ex_defdir->dp_hosts);
2141		free((caddr_t)ep->ex_defdir);
2142	}
2143	if (ep->ex_fsdir)
2144		free(ep->ex_fsdir);
2145	if (ep->ex_indexfile)
2146		free(ep->ex_indexfile);
2147	free_dir(ep->ex_dirl);
2148	free((caddr_t)ep);
2149}
2150
2151/*
2152 * Free hosts.
2153 */
2154void
2155free_host(hp)
2156	struct hostlist *hp;
2157{
2158	struct hostlist *hp2;
2159
2160	while (hp) {
2161		hp2 = hp;
2162		hp = hp->ht_next;
2163		free((caddr_t)hp2);
2164	}
2165}
2166
2167struct hostlist *
2168get_ht()
2169{
2170	struct hostlist *hp;
2171
2172	hp = (struct hostlist *)malloc(sizeof (struct hostlist));
2173	if (hp == (struct hostlist *)NULL)
2174		out_of_mem();
2175	hp->ht_next = (struct hostlist *)NULL;
2176	hp->ht_flag = 0;
2177	return (hp);
2178}
2179
2180/*
2181 * Out of memory, fatal
2182 */
2183void
2184out_of_mem()
2185{
2186
2187	syslog(LOG_ERR, "out of memory");
2188	exit(2);
2189}
2190
2191/*
2192 * Do the nmount() syscall with the update flag to push the export info into
2193 * the kernel.
2194 */
2195int
2196do_mount(struct exportlist *ep, struct grouplist *grp, int exflags,
2197    struct xucred *anoncrp, char *dirp, int dirplen, struct statfs *fsb)
2198{
2199	struct statfs fsb1;
2200	struct addrinfo *ai;
2201	struct export_args ea, *eap;
2202	char errmsg[255];
2203	char *cp;
2204	int done;
2205	char savedc;
2206	struct iovec *iov;
2207	int i, iovlen;
2208	int ret;
2209	struct nfsex_args nfsea;
2210
2211	if (run_v4server > 0)
2212		eap = &nfsea.export;
2213	else
2214		eap = &ea;
2215
2216	cp = NULL;
2217	savedc = '\0';
2218	iov = NULL;
2219	iovlen = 0;
2220	ret = 0;
2221
2222	bzero(eap, sizeof (struct export_args));
2223	bzero(errmsg, sizeof(errmsg));
2224	eap->ex_flags = exflags;
2225	eap->ex_anon = *anoncrp;
2226	eap->ex_indexfile = ep->ex_indexfile;
2227	if (grp->gr_type == GT_HOST)
2228		ai = grp->gr_ptr.gt_addrinfo;
2229	else
2230		ai = NULL;
2231	eap->ex_numsecflavors = ep->ex_numsecflavors;
2232	for (i = 0; i < eap->ex_numsecflavors; i++)
2233		eap->ex_secflavors[i] = ep->ex_secflavors[i];
2234	if (eap->ex_numsecflavors == 0) {
2235		eap->ex_numsecflavors = 1;
2236		eap->ex_secflavors[0] = AUTH_SYS;
2237	}
2238	done = FALSE;
2239
2240	if (v4root_phase == 0) {
2241		build_iovec(&iov, &iovlen, "fstype", NULL, 0);
2242		build_iovec(&iov, &iovlen, "fspath", NULL, 0);
2243		build_iovec(&iov, &iovlen, "from", NULL, 0);
2244		build_iovec(&iov, &iovlen, "update", NULL, 0);
2245		build_iovec(&iov, &iovlen, "export", eap,
2246		    sizeof (struct export_args));
2247		build_iovec(&iov, &iovlen, "errmsg", errmsg, sizeof(errmsg));
2248	}
2249
2250	while (!done) {
2251		switch (grp->gr_type) {
2252		case GT_HOST:
2253			if (ai->ai_addr->sa_family == AF_INET6 && have_v6 == 0)
2254				goto skip;
2255			eap->ex_addr = ai->ai_addr;
2256			eap->ex_addrlen = ai->ai_addrlen;
2257			eap->ex_masklen = 0;
2258			break;
2259		case GT_NET:
2260			if (grp->gr_ptr.gt_net.nt_net.ss_family == AF_INET6 &&
2261			    have_v6 == 0)
2262				goto skip;
2263			eap->ex_addr =
2264			    (struct sockaddr *)&grp->gr_ptr.gt_net.nt_net;
2265			eap->ex_addrlen =
2266			    ((struct sockaddr *)&grp->gr_ptr.gt_net.nt_net)->sa_len;
2267			eap->ex_mask =
2268			    (struct sockaddr *)&grp->gr_ptr.gt_net.nt_mask;
2269			eap->ex_masklen = ((struct sockaddr *)&grp->gr_ptr.gt_net.nt_mask)->sa_len;
2270			break;
2271		case GT_DEFAULT:
2272			eap->ex_addr = NULL;
2273			eap->ex_addrlen = 0;
2274			eap->ex_mask = NULL;
2275			eap->ex_masklen = 0;
2276			break;
2277		case GT_IGNORE:
2278			ret = 0;
2279			goto error_exit;
2280			break;
2281		default:
2282			syslog(LOG_ERR, "bad grouptype");
2283			if (cp)
2284				*cp = savedc;
2285			ret = 1;
2286			goto error_exit;
2287		};
2288
2289		/*
2290		 * For V4:, use the nfssvc() syscall, instead of mount().
2291		 */
2292		if (v4root_phase == 2) {
2293			nfsea.fspec = v4root_dirpath;
2294			if (run_v4server > 0 &&
2295			    nfssvc(NFSSVC_V4ROOTEXPORT, (caddr_t)&nfsea) < 0) {
2296				syslog(LOG_ERR, "Exporting V4: failed");
2297				return (2);
2298			}
2299		} else {
2300			/*
2301			 * XXX:
2302			 * Maybe I should just use the fsb->f_mntonname path
2303			 * instead of looping back up the dirp to the mount
2304			 * point??
2305			 * Also, needs to know how to export all types of local
2306			 * exportable filesystems and not just "ufs".
2307			 */
2308			iov[1].iov_base = fsb->f_fstypename; /* "fstype" */
2309			iov[1].iov_len = strlen(fsb->f_fstypename) + 1;
2310			iov[3].iov_base = fsb->f_mntonname; /* "fspath" */
2311			iov[3].iov_len = strlen(fsb->f_mntonname) + 1;
2312			iov[5].iov_base = fsb->f_mntfromname; /* "from" */
2313			iov[5].iov_len = strlen(fsb->f_mntfromname) + 1;
2314
2315			while (nmount(iov, iovlen, fsb->f_flags) < 0) {
2316				if (cp)
2317					*cp-- = savedc;
2318				else
2319					cp = dirp + dirplen - 1;
2320				if (opt_flags & OP_QUIET) {
2321					ret = 1;
2322					goto error_exit;
2323				}
2324				if (errno == EPERM) {
2325					if (debug)
2326						warnx("can't change attributes for %s",
2327						    dirp);
2328					syslog(LOG_ERR,
2329					   "can't change attributes for %s",
2330					    dirp);
2331					ret = 1;
2332					goto error_exit;
2333				}
2334				if (opt_flags & OP_ALLDIRS) {
2335					if (errno == EINVAL)
2336						syslog(LOG_ERR,
2337		"-alldirs requested but %s is not a filesystem mountpoint",
2338						    dirp);
2339					else
2340						syslog(LOG_ERR,
2341						    "could not remount %s: %m",
2342						    dirp);
2343					ret = 1;
2344					goto error_exit;
2345				}
2346				/* back up over the last component */
2347				while (*cp == '/' && cp > dirp)
2348					cp--;
2349				while (*(cp - 1) != '/' && cp > dirp)
2350					cp--;
2351				if (cp == dirp) {
2352					if (debug)
2353						warnx("mnt unsucc");
2354					syslog(LOG_ERR, "can't export %s %s",
2355					    dirp, errmsg);
2356					ret = 1;
2357					goto error_exit;
2358				}
2359				savedc = *cp;
2360				*cp = '\0';
2361				/*
2362				 * Check that we're still on the same
2363				 * filesystem.
2364				 */
2365				if (statfs(dirp, &fsb1) != 0 ||
2366				    bcmp(&fsb1.f_fsid, &fsb->f_fsid,
2367				    sizeof (fsb1.f_fsid)) != 0) {
2368					*cp = savedc;
2369					syslog(LOG_ERR,
2370					    "can't export %s %s", dirp,
2371					    errmsg);
2372					ret = 1;
2373					goto error_exit;
2374				}
2375			}
2376		}
2377
2378		/*
2379		 * For the experimental server:
2380		 * If this is the public directory, get the file handle
2381		 * and load it into the kernel via the nfssvc() syscall.
2382		 */
2383		if (run_v4server > 0 && (exflags & MNT_EXPUBLIC) != 0) {
2384			fhandle_t fh;
2385			char *public_name;
2386
2387			if (eap->ex_indexfile != NULL)
2388				public_name = eap->ex_indexfile;
2389			else
2390				public_name = dirp;
2391			if (getfh(public_name, &fh) < 0)
2392				syslog(LOG_ERR,
2393				    "Can't get public fh for %s", public_name);
2394			else if (nfssvc(NFSSVC_PUBLICFH, (caddr_t)&fh) < 0)
2395				syslog(LOG_ERR,
2396				    "Can't set public fh for %s", public_name);
2397			else
2398				has_publicfh = 1;
2399		}
2400skip:
2401		if (ai != NULL)
2402			ai = ai->ai_next;
2403		if (ai == NULL)
2404			done = TRUE;
2405	}
2406	if (cp)
2407		*cp = savedc;
2408error_exit:
2409	/* free strings allocated by strdup() in getmntopts.c */
2410	if (iov != NULL) {
2411		free(iov[0].iov_base); /* fstype */
2412		free(iov[2].iov_base); /* fspath */
2413		free(iov[4].iov_base); /* from */
2414		free(iov[6].iov_base); /* update */
2415		free(iov[8].iov_base); /* export */
2416		free(iov[10].iov_base); /* errmsg */
2417
2418		/* free iov, allocated by realloc() */
2419		free(iov);
2420	}
2421	return (ret);
2422}
2423
2424/*
2425 * Translate a net address.
2426 *
2427 * If `maskflg' is nonzero, then `cp' is a netmask, not a network address.
2428 */
2429int
2430get_net(cp, net, maskflg)
2431	char *cp;
2432	struct netmsk *net;
2433	int maskflg;
2434{
2435	struct netent *np = NULL;
2436	char *name, *p, *prefp;
2437	struct sockaddr_in sin;
2438	struct sockaddr *sa = NULL;
2439	struct addrinfo hints, *ai = NULL;
2440	char netname[NI_MAXHOST];
2441	long preflen;
2442
2443	p = prefp = NULL;
2444	if ((opt_flags & OP_MASKLEN) && !maskflg) {
2445		p = strchr(cp, '/');
2446		*p = '\0';
2447		prefp = p + 1;
2448	}
2449
2450	/*
2451	 * Check for a numeric address first. We wish to avoid
2452	 * possible DNS lookups in getnetbyname().
2453	 */
2454	if (isxdigit(*cp) || *cp == ':') {
2455		memset(&hints, 0, sizeof hints);
2456		/* Ensure the mask and the network have the same family. */
2457		if (maskflg && (opt_flags & OP_NET))
2458			hints.ai_family = net->nt_net.ss_family;
2459		else if (!maskflg && (opt_flags & OP_HAVEMASK))
2460			hints.ai_family = net->nt_mask.ss_family;
2461		else
2462			hints.ai_family = AF_UNSPEC;
2463		hints.ai_flags = AI_NUMERICHOST;
2464		if (getaddrinfo(cp, NULL, &hints, &ai) == 0)
2465			sa = ai->ai_addr;
2466		if (sa != NULL && ai->ai_family == AF_INET) {
2467			/*
2468			 * The address in `cp' is really a network address, so
2469			 * use inet_network() to re-interpret this correctly.
2470			 * e.g. "127.1" means 127.1.0.0, not 127.0.0.1.
2471			 */
2472			bzero(&sin, sizeof sin);
2473			sin.sin_family = AF_INET;
2474			sin.sin_len = sizeof sin;
2475			sin.sin_addr = inet_makeaddr(inet_network(cp), 0);
2476			if (debug)
2477				fprintf(stderr, "get_net: v4 addr %s\n",
2478				    inet_ntoa(sin.sin_addr));
2479			sa = (struct sockaddr *)&sin;
2480		}
2481	}
2482	if (sa == NULL && (np = getnetbyname(cp)) != NULL) {
2483		bzero(&sin, sizeof sin);
2484		sin.sin_family = AF_INET;
2485		sin.sin_len = sizeof sin;
2486		sin.sin_addr = inet_makeaddr(np->n_net, 0);
2487		sa = (struct sockaddr *)&sin;
2488	}
2489	if (sa == NULL)
2490		goto fail;
2491
2492	if (maskflg) {
2493		/* The specified sockaddr is a mask. */
2494		if (checkmask(sa) != 0)
2495			goto fail;
2496		bcopy(sa, &net->nt_mask, sa->sa_len);
2497		opt_flags |= OP_HAVEMASK;
2498	} else {
2499		/* The specified sockaddr is a network address. */
2500		bcopy(sa, &net->nt_net, sa->sa_len);
2501
2502		/* Get a network name for the export list. */
2503		if (np) {
2504			name = np->n_name;
2505		} else if (getnameinfo(sa, sa->sa_len, netname, sizeof netname,
2506		   NULL, 0, NI_NUMERICHOST) == 0) {
2507			name = netname;
2508		} else {
2509			goto fail;
2510		}
2511		if ((net->nt_name = strdup(name)) == NULL)
2512			out_of_mem();
2513
2514		/*
2515		 * Extract a mask from either a "/<masklen>" suffix, or
2516		 * from the class of an IPv4 address.
2517		 */
2518		if (opt_flags & OP_MASKLEN) {
2519			preflen = strtol(prefp, NULL, 10);
2520			if (preflen < 0L || preflen == LONG_MAX)
2521				goto fail;
2522			bcopy(sa, &net->nt_mask, sa->sa_len);
2523			if (makemask(&net->nt_mask, (int)preflen) != 0)
2524				goto fail;
2525			opt_flags |= OP_HAVEMASK;
2526			*p = '/';
2527		} else if (sa->sa_family == AF_INET &&
2528		    (opt_flags & OP_MASK) == 0) {
2529			in_addr_t addr;
2530
2531			addr = ((struct sockaddr_in *)sa)->sin_addr.s_addr;
2532			if (IN_CLASSA(addr))
2533				preflen = 8;
2534			else if (IN_CLASSB(addr))
2535				preflen = 16;
2536			else if (IN_CLASSC(addr))
2537				preflen = 24;
2538			else if (IN_CLASSD(addr))
2539				preflen = 28;
2540			else
2541				preflen = 32;	/* XXX */
2542
2543			bcopy(sa, &net->nt_mask, sa->sa_len);
2544			makemask(&net->nt_mask, (int)preflen);
2545			opt_flags |= OP_HAVEMASK;
2546		}
2547	}
2548
2549	if (ai)
2550		freeaddrinfo(ai);
2551	return 0;
2552
2553fail:
2554	if (ai)
2555		freeaddrinfo(ai);
2556	return 1;
2557}
2558
2559/*
2560 * Parse out the next white space separated field
2561 */
2562void
2563nextfield(cp, endcp)
2564	char **cp;
2565	char **endcp;
2566{
2567	char *p;
2568
2569	p = *cp;
2570	while (*p == ' ' || *p == '\t')
2571		p++;
2572	if (*p == '\n' || *p == '\0')
2573		*cp = *endcp = p;
2574	else {
2575		*cp = p++;
2576		while (*p != ' ' && *p != '\t' && *p != '\n' && *p != '\0')
2577			p++;
2578		*endcp = p;
2579	}
2580}
2581
2582/*
2583 * Get an exports file line. Skip over blank lines and handle line
2584 * continuations.
2585 */
2586int
2587get_line()
2588{
2589	char *p, *cp;
2590	size_t len;
2591	int totlen, cont_line;
2592
2593	/*
2594	 * Loop around ignoring blank lines and getting all continuation lines.
2595	 */
2596	p = line;
2597	totlen = 0;
2598	do {
2599		if ((p = fgetln(exp_file, &len)) == NULL)
2600			return (0);
2601		cp = p + len - 1;
2602		cont_line = 0;
2603		while (cp >= p &&
2604		    (*cp == ' ' || *cp == '\t' || *cp == '\n' || *cp == '\\')) {
2605			if (*cp == '\\')
2606				cont_line = 1;
2607			cp--;
2608			len--;
2609		}
2610		if (cont_line) {
2611			*++cp = ' ';
2612			len++;
2613		}
2614		if (linesize < len + totlen + 1) {
2615			linesize = len + totlen + 1;
2616			line = realloc(line, linesize);
2617			if (line == NULL)
2618				out_of_mem();
2619		}
2620		memcpy(line + totlen, p, len);
2621		totlen += len;
2622		line[totlen] = '\0';
2623	} while (totlen == 0 || cont_line);
2624	return (1);
2625}
2626
2627/*
2628 * Parse a description of a credential.
2629 */
2630void
2631parsecred(namelist, cr)
2632	char *namelist;
2633	struct xucred *cr;
2634{
2635	char *name;
2636	int cnt;
2637	char *names;
2638	struct passwd *pw;
2639	struct group *gr;
2640	gid_t groups[NGROUPS + 1];
2641	int ngroups;
2642
2643	cr->cr_version = XUCRED_VERSION;
2644	/*
2645	 * Set up the unprivileged user.
2646	 */
2647	cr->cr_uid = -2;
2648	cr->cr_groups[0] = -2;
2649	cr->cr_ngroups = 1;
2650	/*
2651	 * Get the user's password table entry.
2652	 */
2653	names = strsep(&namelist, " \t\n");
2654	name = strsep(&names, ":");
2655	if (isdigit(*name) || *name == '-')
2656		pw = getpwuid(atoi(name));
2657	else
2658		pw = getpwnam(name);
2659	/*
2660	 * Credentials specified as those of a user.
2661	 */
2662	if (names == NULL) {
2663		if (pw == NULL) {
2664			syslog(LOG_ERR, "unknown user: %s", name);
2665			return;
2666		}
2667		cr->cr_uid = pw->pw_uid;
2668		ngroups = NGROUPS + 1;
2669		if (getgrouplist(pw->pw_name, pw->pw_gid, groups, &ngroups))
2670			syslog(LOG_ERR, "too many groups");
2671		/*
2672		 * Compress out duplicate.
2673		 */
2674		cr->cr_ngroups = ngroups - 1;
2675		cr->cr_groups[0] = groups[0];
2676		for (cnt = 2; cnt < ngroups; cnt++)
2677			cr->cr_groups[cnt - 1] = groups[cnt];
2678		return;
2679	}
2680	/*
2681	 * Explicit credential specified as a colon separated list:
2682	 *	uid:gid:gid:...
2683	 */
2684	if (pw != NULL)
2685		cr->cr_uid = pw->pw_uid;
2686	else if (isdigit(*name) || *name == '-')
2687		cr->cr_uid = atoi(name);
2688	else {
2689		syslog(LOG_ERR, "unknown user: %s", name);
2690		return;
2691	}
2692	cr->cr_ngroups = 0;
2693	while (names != NULL && *names != '\0' && cr->cr_ngroups < NGROUPS) {
2694		name = strsep(&names, ":");
2695		if (isdigit(*name) || *name == '-') {
2696			cr->cr_groups[cr->cr_ngroups++] = atoi(name);
2697		} else {
2698			if ((gr = getgrnam(name)) == NULL) {
2699				syslog(LOG_ERR, "unknown group: %s", name);
2700				continue;
2701			}
2702			cr->cr_groups[cr->cr_ngroups++] = gr->gr_gid;
2703		}
2704	}
2705	if (names != NULL && *names != '\0' && cr->cr_ngroups == NGROUPS)
2706		syslog(LOG_ERR, "too many groups");
2707}
2708
2709#define	STRSIZ	(RPCMNT_NAMELEN+RPCMNT_PATHLEN+50)
2710/*
2711 * Routines that maintain the remote mounttab
2712 */
2713void
2714get_mountlist()
2715{
2716	struct mountlist *mlp, **mlpp;
2717	char *host, *dirp, *cp;
2718	char str[STRSIZ];
2719	FILE *mlfile;
2720
2721	if ((mlfile = fopen(_PATH_RMOUNTLIST, "r")) == NULL) {
2722		if (errno == ENOENT)
2723			return;
2724		else {
2725			syslog(LOG_ERR, "can't open %s", _PATH_RMOUNTLIST);
2726			return;
2727		}
2728	}
2729	mlpp = &mlhead;
2730	while (fgets(str, STRSIZ, mlfile) != NULL) {
2731		cp = str;
2732		host = strsep(&cp, " \t\n");
2733		dirp = strsep(&cp, " \t\n");
2734		if (host == NULL || dirp == NULL)
2735			continue;
2736		mlp = (struct mountlist *)malloc(sizeof (*mlp));
2737		if (mlp == (struct mountlist *)NULL)
2738			out_of_mem();
2739		strncpy(mlp->ml_host, host, RPCMNT_NAMELEN);
2740		mlp->ml_host[RPCMNT_NAMELEN] = '\0';
2741		strncpy(mlp->ml_dirp, dirp, RPCMNT_PATHLEN);
2742		mlp->ml_dirp[RPCMNT_PATHLEN] = '\0';
2743		mlp->ml_next = (struct mountlist *)NULL;
2744		*mlpp = mlp;
2745		mlpp = &mlp->ml_next;
2746	}
2747	fclose(mlfile);
2748}
2749
2750void
2751del_mlist(char *hostp, char *dirp)
2752{
2753	struct mountlist *mlp, **mlpp;
2754	struct mountlist *mlp2;
2755	FILE *mlfile;
2756	int fnd = 0;
2757
2758	mlpp = &mlhead;
2759	mlp = mlhead;
2760	while (mlp) {
2761		if (!strcmp(mlp->ml_host, hostp) &&
2762		    (!dirp || !strcmp(mlp->ml_dirp, dirp))) {
2763			fnd = 1;
2764			mlp2 = mlp;
2765			*mlpp = mlp = mlp->ml_next;
2766			free((caddr_t)mlp2);
2767		} else {
2768			mlpp = &mlp->ml_next;
2769			mlp = mlp->ml_next;
2770		}
2771	}
2772	if (fnd) {
2773		if ((mlfile = fopen(_PATH_RMOUNTLIST, "w")) == NULL) {
2774			syslog(LOG_ERR,"can't update %s", _PATH_RMOUNTLIST);
2775			return;
2776		}
2777		mlp = mlhead;
2778		while (mlp) {
2779			fprintf(mlfile, "%s %s\n", mlp->ml_host, mlp->ml_dirp);
2780			mlp = mlp->ml_next;
2781		}
2782		fclose(mlfile);
2783	}
2784}
2785
2786void
2787add_mlist(hostp, dirp)
2788	char *hostp, *dirp;
2789{
2790	struct mountlist *mlp, **mlpp;
2791	FILE *mlfile;
2792
2793	mlpp = &mlhead;
2794	mlp = mlhead;
2795	while (mlp) {
2796		if (!strcmp(mlp->ml_host, hostp) && !strcmp(mlp->ml_dirp, dirp))
2797			return;
2798		mlpp = &mlp->ml_next;
2799		mlp = mlp->ml_next;
2800	}
2801	mlp = (struct mountlist *)malloc(sizeof (*mlp));
2802	if (mlp == (struct mountlist *)NULL)
2803		out_of_mem();
2804	strncpy(mlp->ml_host, hostp, RPCMNT_NAMELEN);
2805	mlp->ml_host[RPCMNT_NAMELEN] = '\0';
2806	strncpy(mlp->ml_dirp, dirp, RPCMNT_PATHLEN);
2807	mlp->ml_dirp[RPCMNT_PATHLEN] = '\0';
2808	mlp->ml_next = (struct mountlist *)NULL;
2809	*mlpp = mlp;
2810	if ((mlfile = fopen(_PATH_RMOUNTLIST, "a")) == NULL) {
2811		syslog(LOG_ERR, "can't update %s", _PATH_RMOUNTLIST);
2812		return;
2813	}
2814	fprintf(mlfile, "%s %s\n", mlp->ml_host, mlp->ml_dirp);
2815	fclose(mlfile);
2816}
2817
2818/*
2819 * Free up a group list.
2820 */
2821void
2822free_grp(grp)
2823	struct grouplist *grp;
2824{
2825	if (grp->gr_type == GT_HOST) {
2826		if (grp->gr_ptr.gt_addrinfo != NULL)
2827			freeaddrinfo(grp->gr_ptr.gt_addrinfo);
2828	} else if (grp->gr_type == GT_NET) {
2829		if (grp->gr_ptr.gt_net.nt_name)
2830			free(grp->gr_ptr.gt_net.nt_name);
2831	}
2832	free((caddr_t)grp);
2833}
2834
2835#ifdef DEBUG
2836void
2837SYSLOG(int pri, const char *fmt, ...)
2838{
2839	va_list ap;
2840
2841	va_start(ap, fmt);
2842	vfprintf(stderr, fmt, ap);
2843	va_end(ap);
2844}
2845#endif /* DEBUG */
2846
2847/*
2848 * Check options for consistency.
2849 */
2850int
2851check_options(dp)
2852	struct dirlist *dp;
2853{
2854
2855	if (v4root_phase == 0 && dp == NULL)
2856	    return (1);
2857	if ((opt_flags & (OP_MAPROOT | OP_MAPALL)) == (OP_MAPROOT | OP_MAPALL)) {
2858	    syslog(LOG_ERR, "-mapall and -maproot mutually exclusive");
2859	    return (1);
2860	}
2861	if ((opt_flags & OP_MASK) && (opt_flags & OP_NET) == 0) {
2862		syslog(LOG_ERR, "-mask requires -network");
2863		return (1);
2864	}
2865	if ((opt_flags & OP_NET) && (opt_flags & OP_HAVEMASK) == 0) {
2866		syslog(LOG_ERR, "-network requires mask specification");
2867		return (1);
2868	}
2869	if ((opt_flags & OP_MASK) && (opt_flags & OP_MASKLEN)) {
2870		syslog(LOG_ERR, "-mask and /masklen are mutually exclusive");
2871		return (1);
2872	}
2873	if ((opt_flags & OP_ALLDIRS) && dp->dp_left) {
2874	    syslog(LOG_ERR, "-alldirs has multiple directories");
2875	    return (1);
2876	}
2877	if (v4root_phase > 0 &&
2878	    (opt_flags &
2879	     ~(OP_SEC | OP_MASK | OP_NET | OP_HAVEMASK | OP_MASKLEN)) != 0) {
2880	    syslog(LOG_ERR,"only -sec,-net,-mask options allowed on V4:");
2881	    return (1);
2882	}
2883	return (0);
2884}
2885
2886/*
2887 * Check an absolute directory path for any symbolic links. Return true
2888 */
2889int
2890check_dirpath(dirp)
2891	char *dirp;
2892{
2893	char *cp;
2894	int ret = 1;
2895	struct stat sb;
2896
2897	cp = dirp + 1;
2898	while (*cp && ret) {
2899		if (*cp == '/') {
2900			*cp = '\0';
2901			if (lstat(dirp, &sb) < 0 || !S_ISDIR(sb.st_mode))
2902				ret = 0;
2903			*cp = '/';
2904		}
2905		cp++;
2906	}
2907	if (lstat(dirp, &sb) < 0 || !S_ISDIR(sb.st_mode))
2908		ret = 0;
2909	return (ret);
2910}
2911
2912/*
2913 * Make a netmask according to the specified prefix length. The ss_family
2914 * and other non-address fields must be initialised before calling this.
2915 */
2916int
2917makemask(struct sockaddr_storage *ssp, int bitlen)
2918{
2919	u_char *p;
2920	int bits, i, len;
2921
2922	if ((p = sa_rawaddr((struct sockaddr *)ssp, &len)) == NULL)
2923		return (-1);
2924	if (bitlen > len * CHAR_BIT)
2925		return (-1);
2926
2927	for (i = 0; i < len; i++) {
2928		bits = (bitlen > CHAR_BIT) ? CHAR_BIT : bitlen;
2929		*p++ = (1 << bits) - 1;
2930		bitlen -= bits;
2931	}
2932	return 0;
2933}
2934
2935/*
2936 * Check that the sockaddr is a valid netmask. Returns 0 if the mask
2937 * is acceptable (i.e. of the form 1...10....0).
2938 */
2939int
2940checkmask(struct sockaddr *sa)
2941{
2942	u_char *mask;
2943	int i, len;
2944
2945	if ((mask = sa_rawaddr(sa, &len)) == NULL)
2946		return (-1);
2947
2948	for (i = 0; i < len; i++)
2949		if (mask[i] != 0xff)
2950			break;
2951	if (i < len) {
2952		if (~mask[i] & (u_char)(~mask[i] + 1))
2953			return (-1);
2954		i++;
2955	}
2956	for (; i < len; i++)
2957		if (mask[i] != 0)
2958			return (-1);
2959	return (0);
2960}
2961
2962/*
2963 * Compare two sockaddrs according to a specified mask. Return zero if
2964 * `sa1' matches `sa2' when filtered by the netmask in `samask'.
2965 * If samask is NULL, perform a full comparision.
2966 */
2967int
2968sacmp(struct sockaddr *sa1, struct sockaddr *sa2, struct sockaddr *samask)
2969{
2970	unsigned char *p1, *p2, *mask;
2971	int len, i;
2972
2973	if (sa1->sa_family != sa2->sa_family ||
2974	    (p1 = sa_rawaddr(sa1, &len)) == NULL ||
2975	    (p2 = sa_rawaddr(sa2, NULL)) == NULL)
2976		return (1);
2977
2978	switch (sa1->sa_family) {
2979	case AF_INET6:
2980		if (((struct sockaddr_in6 *)sa1)->sin6_scope_id !=
2981		    ((struct sockaddr_in6 *)sa2)->sin6_scope_id)
2982			return (1);
2983		break;
2984	}
2985
2986	/* Simple binary comparison if no mask specified. */
2987	if (samask == NULL)
2988		return (memcmp(p1, p2, len));
2989
2990	/* Set up the mask, and do a mask-based comparison. */
2991	if (sa1->sa_family != samask->sa_family ||
2992	    (mask = sa_rawaddr(samask, NULL)) == NULL)
2993		return (1);
2994
2995	for (i = 0; i < len; i++)
2996		if ((p1[i] & mask[i]) != (p2[i] & mask[i]))
2997			return (1);
2998	return (0);
2999}
3000
3001/*
3002 * Return a pointer to the part of the sockaddr that contains the
3003 * raw address, and set *nbytes to its length in bytes. Returns
3004 * NULL if the address family is unknown.
3005 */
3006void *
3007sa_rawaddr(struct sockaddr *sa, int *nbytes) {
3008	void *p;
3009	int len;
3010
3011	switch (sa->sa_family) {
3012	case AF_INET:
3013		len = sizeof(((struct sockaddr_in *)sa)->sin_addr);
3014		p = &((struct sockaddr_in *)sa)->sin_addr;
3015		break;
3016	case AF_INET6:
3017		len = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
3018		p = &((struct sockaddr_in6 *)sa)->sin6_addr;
3019		break;
3020	default:
3021		p = NULL;
3022		len = 0;
3023	}
3024
3025	if (nbytes != NULL)
3026		*nbytes = len;
3027	return (p);
3028}
3029
3030void
3031huphandler(int sig)
3032{
3033	got_sighup = 1;
3034}
3035
3036void terminate(sig)
3037int sig;
3038{
3039	pidfile_remove(pfh);
3040	rpcb_unset(RPCPROG_MNT, RPCMNT_VER1, NULL);
3041	rpcb_unset(RPCPROG_MNT, RPCMNT_VER3, NULL);
3042	exit (0);
3043}
3044
3045