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