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