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