#ifndef lint
static	char	*sccsid = "@(#)mountd.c	2.8	(ULTRIX)	2/9/90";
#endif lint
/************************************************************************
 *									*
 *			Copyright (c) 1986-1990 by			*
 *		Digital Equipment Corporation, Maynard, MA		*
 *			All rights reserved.				*
 *									*
 *   This software is furnished under a license and may be used and	*
 *   copied  only  in accordance with the terms of such license and	*
 *   with the  inclusion  of  the  above  copyright  notice.   This	*
 *   software  or  any  other copies thereof may not be provided or	*
 *   otherwise made available to any other person.  No title to and	*
 *   ownership of the software is hereby transferred.			*
 *									*
 *   This software is  derived  from  software  received  from  the	*
 *   University    of   California,   Berkeley,   and   from   Bell	*
 *   Laboratories.  Use, duplication, or disclosure is  subject  to	*
 *   restrictions  under  license  agreements  with  University  of	*
 *   California and with AT&T.						*
 *									*
 *   The information in this software is subject to change  without	*
 *   notice  and should not be construed as a commitment by Digital	*
 *   Equipment Corporation.						*
 *									*
 *   Digital assumes no responsibility for the use  or  reliability	*
 *   of its software on equipment which is not supplied by Digital.	*
 *									*
 ************************************************************************/

/*
 *	Portions of this software have been licensed to 
 *	Digital Equipment Company, Maynard, MA.
 *	Copyright (c) 1986 Sun Microsystems, Inc.  ALL RIGHTS RESERVED.
 */

/***********************************************************************
 *
 *		Modification History
 * 07/02/90 sue
 *		Made fix to have short host names in /etc/exports.
 *
 * 11/10/89 lebel
 *		Errors now go to syslog.  Showmounts can be done over tcp 
 *		(tcp can handle arbitrarily long exports lists).  The -d
 *		option implies the -i option and the -s option implies both
 *		-i and -d.  Mountd registers itself with the portmapper 
 *		before forking to prevent the case where nfsds start up
 *		before mountd has time to register itself.  Hostname 
 *		comparisons are case insensitive.  Duplicate detection
 *		is now done by inode # comparison (to detect links).
 *
 * 07/21/89 lebel
 *		Rewrite of mtd_mount() and set_exports() to allow options at
 *		the directory level.  The -n (no filehandle) exports option
 *		is no longer employed.  update_exportfsdata() keeps the new
 *		kernel exports list in sync with the mount daemon's.
 *
 * 05/25/89	Suzanne Logcher
 *		Removed code specific to /etc/svcorder.  File is now
 *		/etc/svc.conf.  Use libc version of bindup().
 *
 * 11/16/88	Suzanne Logcher
 *		Fixed de-referencing null pointer bugs in path_check()
 *		which caused mountd on PMAX to seg fault and core dump.
 *
 * 11/10/88	Suzanne Logcher
 *		Updated with V3.0 changes.
 *
 * 07/15/88	Suzanne Logcher
 *		Fixed QAR 64 bug to continue to parse a directory entry
 *		in /etc/exports after catching an improper setting of
 *		an option.  Force a showmount request to rebuild the
 *		export structure.  Changed usage of -i with bind.  The
 *		-d flag is for after checking the IP address, see if
 *		host is in the server domain.  The -s flag does the same
 *		check but checks if the host is in the server domain or
 *		a subdomain.
 *
 * 06/09/88	Suzanne Logcher
 *		Added v2.3 fix to not cleanup the export list of
 *		unexported filesystems and use that info to determine
 *		whether the getmount info on the filesystem has changed
 *		thus giving the mountd a "kick" to rebuild the export
 *		list.  This handles the case when the filesystems have
 *		changed and the /etc/exports file has NOT been modified
 *		thus causing the mountd's export list to be out-of-date.
 *		Upon a second failure with exit with EACESS.
 *
 * 04/24/88	Fred Glover
 *		Add BIND domain specification check for ipaddr_check 
 *
 * 03/01/88	Suzanne Logcher
 *		Rewrite of code.  Use getmountent to build exports
 *		list, and then read in /etc/exports and build matrix
 *		of exports with filesystems and directories.  Change
 *		code in mtd_mount() to parse new list structure.  Add a
 *		routine, flatten_exports(), to provide full information
 *		to an EXPORT request.  Linted as best as possible.
 *
 * 05/25/87	Joe Amato
 *		When looking to match the path requested to mount
 *		loop through exports list looking for an exact match
 *		if not found, loop through exports list again, but
 *		look for a match on a subset of the requested path
 *
 * 05/19/87	Joe Amato
 *		Moved some initialization code before fork.
 *		When looking for a machine in a long group list, only 
 *		call innetgr after searching complete list to avoid 
 *		unnecessary YP timeouts.
 *
 * 05/06/87	Suzanne Logcher
 *		Changed M_RONLY to M_EXRONLY
 *
 * 03/19/87	Suzanne Logcher
 *		Added code to setopt to parse options in /etc/exports
 *
 * 02/10/87	Suzanne Logcher
 *		Added code to allow exporting of directories
 *
 ***********************************************************************/

/* NFS mount server */

#include <ctype.h>
#include <sys/param.h>
#include <ufs/fs.h>
#include <rpc/rpc.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/file.h>
#include <sys/time.h>
#include <stdio.h>
#include <syslog.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <sys/errno.h>
#include <sys/dir.h>
#include <nfs/nfs.h>
#include <rpcsvc/mount.h>
#include <netdb.h>
#include <sys/mount.h>
#include <nfs/nfs_clnt.h>
#include <nfs/vfs.h>

#include <arpa/nameser.h>
#include <resolv.h>

#define M_EXFASCIST 0x8000
    
#ifdef KERBEROS
#define CREDFILE "/usr/etc/credentials"
#ifndef KRB_SLOP_TIME
#define KRB_SLOP_TIME 0
#endif
#include <nfs/nfs_mapctl.h>
#include "dbmcred.h"
#ifdef NDBM
#include <ndbm.h>
#else
#undef NULL
#include <dbm.h>
#include "dbmcompat.h"
#undef NULL
#define NULL 0
#endif /* NDBM */
#endif /* KERBEROS */

#define	EXPORTS	"/etc/exports"
#ifndef NORMTAB
#define RMTAB	"/etc/rmtab"
#endif
    
#define	MAXLINE	2048
#define GROUP_HOSTS	0
#define GROUP_YP	1
#define GROUP_ALL	2
#define MAX_LEVELS  10

extern int errno;

int mnt();
char *exmalloc();
struct exports *newex();
struct groups *newgroup();
char *goto_char();

static struct mountlist *mountlist;
char myname[BUFSIZ];
char mydomain[MAXNAMLEN+1];
char *pgmname;
char *exportfile = EXPORTS;
struct stat exportstat;
struct exports *exports = NULL;
struct exports *flatexports = NULL;
int nfs_portmon = 0;
int ipaddr_check = 0;
int domain_check = 0;
int subdomain_check = 0;

#ifdef DEBUG
int debug = 1;
#endif

#ifdef KERBEROS
DBM *dbmfile;
struct timeval timep;
struct timeval savetime;
#endif

main(argc, argv)
char	*argv[];
{
	struct sockaddr_in addr;
	int len = sizeof(struct sockaddr_in);
	SVCXPRT *transp;
	char *cp;
	char *strchr ();
#ifdef KERBEROS
	int sig_handler();
	struct itimerval itimer;
#endif

	pgmname = argv[0];

	/*
	 * must be superuser to run 
	 */
	if (geteuid() != 0){
		(void) fprintf(stderr, "%s:  must be super user\n", pgmname);
		(void) fflush(stderr);
		exit(1);
	}
	while (--argc > 0 ) {
		*++argv;
		if ((*argv)[0] != '-' || strlen(*argv) != 2) {
			usage();
		}

		switch ((*argv)[1]) {
		case 'i':
			ipaddr_check++;
			break;
		case 'd':
			ipaddr_check++;
			domain_check++;
			break;
		case 's':
			ipaddr_check++;
			subdomain_check++;
			break;
		default:
			usage();
		}
	}
	if (openlog("mountd", LOG_PID) < 0)
		printf("mountd: openlog failed\n");

	/*
	 * Initalize the world
	 */
	if(gethostname(myname, sizeof(myname)) < 0){            /* jaa */
		syslog(LOG_ERR, "gethostname: %m");
		exit(1);
	}
	if(getdomainname(mydomain, sizeof(mydomain)) < 0){      /* jaa */
		syslog(LOG_ERR, "getdomainname: %m");
		exit(1);
	}

	/*
	 * Read rmtab and exports files
	 */
	readfromfile();                                         /* jaa */
#ifdef DEBUG
	(void) fprintf(stderr, "*** loading export list ***\n");
#endif
	set_exports();                                          /* jaa */
#ifdef DEBUG
	(void) fprintf(stderr, "*** finished loading export list ***\n");
#endif

	/*
	 * Remove this chunk of code if we ever run under inetd.
	 * Also remove the mtd_abort() routine if running under inetd.
	 */
	{
		int s, t;
		struct sockaddr_in addr;
		int len = sizeof(struct sockaddr_in);
		int pid;

#ifndef DEBUG
		for (t = 0; t < 20; t++)
			(void) close(t);
	 	open("/", 0);
	 	dup2(0, 1);
	 	dup2(0, 2);
#endif
		if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
			syslog(LOG_ERR, "socket: %m");
			exit(1);
		}
		if (bind(s, &addr, sizeof(addr)) < 0) {
			syslog(LOG_ERR, "bind: %m");
			exit(1);
		}
		if (getsockname(s, &addr, &len) != 0) {
			syslog(LOG_ERR, "getsockname: %m");
			(void) close(s);
			exit(1);
		}
		pmap_unset(MOUNTPROG, MOUNTVERS);
		/* 
		 * register with portmapper if not started from inetd
		 */
		pmap_set(MOUNTPROG, MOUNTVERS, IPPROTO_UDP,
		    ntohs(addr.sin_port));
		if (dup2(s, 0) < 0) {
			syslog(LOG_ERR, "dup2: %m");
			exit(1);
		}
#ifndef DEBUG
		pid = fork();
		if (pid < 0) {
			syslog(LOG_ERR, "Cannot fork: %m");
			exit(1);
		}
		if (pid != 0)
			exit(0);
#endif
	}

	/* End chunk to remove if running under inetd. */

	/*
	 * Create UDP service
	 */
	if ((transp = svcudp_create(0)) == NULL) {
		syslog(LOG_ERR, "couldn't create UDP transport");
		exit(1);
	}
	if (!svc_register(transp, MOUNTPROG, MOUNTVERS, mnt, 0)) {
		syslog(LOG_ERR, "couldn't register MOUNTPROG");
		exit(1);
	}

	/*
	 * Create TCP service
	 */
	if ((transp = svctcp_create(RPC_ANYSOCK, 0, 0)) == NULL) {
		syslog(LOG_ERR, "couldn't create TCP transport");
		exit(1);
	}
	if (!svc_register(transp, MOUNTPROG, MOUNTVERS, mnt, IPPROTO_TCP)) {
		syslog(LOG_ERR, "couldn't register MOUNTPROG");
		exit(1);
	}

	/*
	 * Start serving
	 */

#ifdef KERBEROS
	dbmfile = dbm_open(CREDFILE, DBM_INSERT, 0600);
	(void) gettimeofday(&savetime, (struct timezone *)0);
	(void) signal(SIGALRM, sig_handler);

	itimer.it_value.tv_sec = 0;
	itimer.it_value.tv_usec = 1;
	itimer.it_interval.tv_sec = 1800;
	itimer.it_interval.tv_usec = 0;
	if (setitimer(ITIMER_REAL, &itimer, (struct itimerval *)NULL)) {
	    perror("rpc.mountd: setitimer");
	}
#endif
	while(1) {
		svc_run();
		syslog(LOG_ERR, "Error: svc_run shouldn't have returned");
		mtd_abort();
	}
}

/*
 * Restore saved mount state
 */
readfromfile()
{
#ifndef NORMTAB
	FILE *fp;
	struct mountlist *ml;
	char name[BUFSIZ];
	char *path, *index(), *rindex();
	
	fp = fopen(RMTAB, "r");
	if (fp == NULL)
		return;
	while (1) {
		if (fgets(name, sizeof(name), fp) == NULL)
			break;
		path = rindex(name, '\n');
		if (path == NULL)
			break;
		*path = 0;
		path = index(name, ':');
		if (path == NULL)
			break;
		*path++ = NULL;
		ml = (struct mountlist *) exmalloc(sizeof(struct mountlist));
		ml->ml_path = (char *)exmalloc(strlen(path) + 1);
		(void) strcpy(ml->ml_path, path);
		ml->ml_name = (char *)exmalloc(strlen(name) + 1);
		(void) strcpy(ml->ml_name, name);
		ml->ml_nxt = mountlist;
		mountlist = ml;
	}
	(void) fclose(fp);
#endif
}

/*
 * Server procedure switch routine
 */
mnt(rqstp, transp)
	struct svc_req *rqstp;
	SVCXPRT *transp;
{
#ifdef DEBUG
	char *machine;

	machine = ((struct authunix_parms *) rqstp->rq_clntcred)->aup_machname;
#endif
#ifdef KERBEROS
	gettimeofday(&timep, (struct timezone *)0);
	if (timep.tv_sec - savetime.tv_sec > 60*5) {
#ifdef DEBUG
		if (debug)
			fprintf(stdout, "Five minute cred. timer expired\n");
#endif
		if (dbmfile) dbm_close(dbmfile);
		dbmfile = dbm_open(CREDFILE, DBM_INSERT, 0600);
		savetime.tv_sec = timep.tv_sec;
	}
#endif KERBEROS
	switch(rqstp->rq_proc) {
		case NULLPROC:
			if (!svc_sendreply(transp, xdr_void, NULL)) {
				syslog(LOG_ERR, "couldn't reply to rpc call");
				mtd_abort();
			}
			return;
		case MOUNTPROC_MNT:
#ifdef DEBUG
			(void) fprintf(stderr, "about to do a mount from %s\n", machine);
#endif
			if (imposter(rqstp,transp)) {
				svcerr_weakauth(transp);
				return;
			}
			set_exports();
			(void) mtd_mount(rqstp, transp);
			return;
		case MOUNTPROC_DUMP:
#ifdef DEBUG
			(void) fprintf(stderr, "about to do a dump from %s\n", machine);
#endif
			if (!svc_sendreply(transp, xdr_mountlist, &mountlist)) {
				syslog(LOG_ERR, "couldn't reply to rpc call");
				mtd_abort();
			}
			return;
		case MOUNTPROC_UMNT:
#ifdef DEBUG
			(void) fprintf(stderr, "about to do an unmount from %s\n", machine);
#endif
			if (imposter(rqstp,transp)) {
				svcerr_weakauth(transp);
				return;
			}
			(void) mtd_umount(rqstp, transp);
			return;
		case MOUNTPROC_UMNTALL:
#ifdef DEBUG
			(void) fprintf(stderr, "about to do an unmountall from %s\n", machine);
#endif
#if 0
	/* commented out until clnt_broadcast problem is solved */
			if (imposter(rqstp,transp)) {
				svcerr_weakauth(transp);
				return;
			}
#endif
			mtd_umountall(rqstp, transp);
			return;
		case MOUNTPROC_EXPORT:
		case MOUNTPROC_EXPORTALL:
#ifdef DEBUG
			(void) fprintf(stderr, "about to do an export from %s\n", machine);
#endif
			/*
			 * Make saved /etc/exports time older to force
			 * a re-build of the in core structure.
			 */
			exportstat.st_mtime--;
			set_exports();
			mtd_export(transp);
			return;
#ifdef KERBEROS
#define KUID_SET 0
#define KUID_DELETE 1
#define KUID_PURGE 2
#define KUID_UPURGE 3

		case MOUNTPROC_KUIDMAP:
#ifdef DEBUG
			if (debug)
			    fprintf(stdout,"about to do a Kerberos UID map\n");
#endif
			kuidops(KUID_SET, rqstp, transp);
			return;
		case MOUNTPROC_KUIDUMAP:
#ifdef DEBUG
			if (debug)
			    fprintf(stdout, "about to do a Kerberos UID unmap\n");
#endif
			kuidops(KUID_DELETE, rqstp, transp);
			return;

		case MOUNTPROC_KUIDPURGE:
#ifdef DEBUG
			if (debug)
			    fprintf(stdout, "about to do a Kerberos UID purge\n");
#endif
			kuidops(KUID_PURGE, rqstp, transp);
			return;
		case MOUNTPROC_KUIDUPURGE:
#ifdef DEBUG
			if (debug)
			    fprintf(stdout, "about to do a Kerberos user purge\n");
#endif
			kuidops(KUID_UPURGE, rqstp, transp);
			return;
#endif
		default:
			svcerr_noproc(transp);
			return;
	}
}

imposter(rqstp,transp)
	struct svc_req *rqstp;
	SVCXPRT *transp;
{
	struct in_addr claim;
	struct sockaddr_in actual;
	struct hostent *hp;
	struct hostent *ap;
	char *machine;
	char *cp;
	char *strchr ();
		
#ifdef DEBUG
	(void) fprintf(stderr, "%s: AUTH %d\n", pgmname, rqstp->rq_cred.oa_flavor);
#endif
	if (rqstp->rq_cred.oa_flavor != AUTH_UNIX) {
		svcerr_weakauth(transp);
		return(1);
	}
	actual = *svc_getcaller(transp);
	if (nfs_portmon) {
		if (ntohs(actual.sin_port) >= IPPORT_RESERVED) {
			return(1);
		}
	}
	if (ipaddr_check) {
		/* 
		 * check for imposters (unfortunately, this may not
		 * work if the request comes from a gateway)
	 	 * The 'verifier' is the source IP address.
		 */
#ifdef DEBUG
		(void) fprintf(stderr, "%s: begin ipaddr_check\n", pgmname);
#endif
		machine = ((struct authunix_parms *)
			rqstp->rq_clntcred)->aup_machname;
#ifdef DEBUG
	(void) fprintf(stderr, "%s: machine %s\n", pgmname, machine);
#endif
		hp = gethostbyname(machine);
		if (hp == NULL) { 
			svcerr_auth(transp,AUTH_BADCRED);
			return(1);
		}
		bcopy(hp->h_addr, &claim, sizeof(struct in_addr));
		if (actual.sin_addr.s_addr != claim.s_addr) {;
			svcerr_weakauth(transp);
			return(1);
		}

		/*
		 *	If domain_check or subdomain_check is set and
		 *	if BIND enabled, check the requester's domain spec
		 *	to be sure it is local.  Obtain hostname based upon
		 *	host address, and then check if:
		 *		1) domain spec matches that of local host or
		 *		2) host name is unqualified (local)
		 */

		if ((domain_check || subdomain_check) && (bindup()) != NULL) {
			if ((ap = gethostbyaddr ((char *)&claim.s_addr, 
					4, AF_INET)) == NULL) {
# ifdef DEBUG
				(void) fprintf(stderr,"mountd: can't convert addr: x%x\n", claim.s_addr);
# endif

				return (1);
			}

			if ((cp = strchr (ap->h_name, '.')) != NULL) {
	
				/* qualified name */

				if (strcmp (cp+1, _res.defdname) != NULL) {
					/*
					 * Not in local domain and flag
					 * subdomain_check is set, check
					 * if in subdomain
					 */
					if (subdomain_check) {
#ifdef DEBUG
						(void) fprintf (stderr, "mountd: client, %s not local domain member, check if %s is a subdomain of %s\n", ap->h_name, cp+1, _res.defdname);
#endif
						if ((strfind (cp+1, _res.defdname)) == NULL) {
							syslog(LOG_ERR, "client %s is not a local subdomain member", ap->h_name);
							return (1);
						}
					}
					else {
						syslog(LOG_ERR, "client %s is not a local domain member", ap->h_name);
						return(1);
					}
				}
			}
		}

#ifdef DEBUG
		(void) fprintf(stderr, "%s: end ipaddr_check successful\n", pgmname);
#endif
	}
	return(0);
}

/*
 * Check mount requests, add to mounted list if ok
 */
mtd_mount(rqstp, transp)
	struct svc_req *rqstp;
	SVCXPRT *transp;
{
	fhandle_t fh;
	struct fhstatus fhs;
	char *path, *machine;
	int fd, anc_fd;
	struct mountlist *ml;
	struct stat statbuf;
	struct exports *ex, *ex2, *ancestors[MAX_LEVELS];
	struct exports *saveex = NULL;
	int found=0, success=0, bestposs=1, index, i;
	int first = 1;

	path = NULL;
	if (!svc_getargs(transp, xdr_path, &path)) {
		svcerr_decode(transp);
		mtd_abort();
		return;
	}
#ifdef DEBUG
	(void) fprintf(stderr, "path is %s\n", path);
#endif
	machine =
	  ((struct authunix_parms *)rqstp->rq_clntcred)->aup_machname;

	if ((fd = open(path, O_RDONLY, 0)) < 0) {
		fhs.fhs_status = errno;
		perror("mountd: open");
		goto fail;
	}
	if (fstat(fd, &statbuf) < 0) {
		fhs.fhs_status = errno;
		perror("mountd: stat");
		(void) close(fd);
		goto fail;
	}

	/*
	 * Search exports list for a directory with an entry with the
	 * same dev_t number.  Search down that dev's list looking for 
	 * an exact match.  If none found, look for entries that are
	 * an ancestor of the requested path.  Check the access on the
	 * closest match.  If access is not allowed, check the next
	 * closest, ... until either no more exported ancestors exist
	 * or an ancestor is found with allowable access for the client.
	 * The export options used will be those on the ancestor found.
	 */
loop_search:
	for (ex = exports; ex != NULL; ex = ex->ex_devptr) {
#ifdef DEBUG
		(void) fprintf(stderr, "checking %o for %o\n", ex->ex_dev, statbuf.st_dev);
#endif
		if (ex->ex_dev == statbuf.st_dev) {
			for (ex2=ex; ex2 != NULL; ex2 = ex2->ex_next) {
#ifdef DEBUG
				(void) fprintf(stderr, "checking %s with %s for exact match dir\n", ex2->ex_name, path);
#endif
				if (strcmp(ex2->ex_name, path) == NULL) {
#ifdef DEBUG
					(void) fprintf(stderr, "got exact match dir\n");
#endif
					if (check_client(ex2, rqstp, transp)) {
					    success = 1;
					    break;
					}
					else {
					    /*
					     * Exact match found but requester
					     * is not an allowable host.  Break
					     * to search for an ancestor match.
					     */
					    saveex = ex;
					    break;
					}
				}
			}
			if (success) {
				if ((anc_fd = open(ex2->ex_name, O_RDONLY, 0)) < 0) {
					fhs.fhs_status = errno;
					perror("mountd: open");
					goto fail;
				}
				goto hit;
			}
			if (saveex != NULL)
				break;
			if (ex2 == NULL) {
				/*
				 * Exact matches failed.  
				 * Break to best match search.
				 */
#ifdef DEBUG
				(void) fprintf(stderr,"exact match for %s failed\n", path);
#endif
				saveex = ex;
				break;
			}
		}
	}
	if (!saveex) {
		if (first) {
			first = 0;
			exportstat.st_mtime--;
			set_exports();
			goto loop_search;
		}
		else {
#ifdef DEBUG
			(void) fprintf(stderr, "%s: filesystem %s not found\n", pgmname, path);
#endif
			fhs.fhs_status = EACCES;
			goto fail;
		}
	}

	/*
	 * Using pointer to directory exports record with same
	 * dev_t number, try to find best match.
	 */
	ex = saveex;
	if (ex->ex_dev == statbuf.st_dev) {
		/*
		 *  initialize ancestors
		 */
		for (i=0; i< MAX_LEVELS; i++)
			ancestors[i] = NULL;
		for (ex2 = ex; ex2 != NULL; ex2 = ex2->ex_next) {
			if ((strcmp(ex2->ex_name, path) != NULL) && (index = path_check(ex2->ex_name, path)) > bestposs) {
#ifdef DEBUG
				(void) fprintf(stderr, "ancestor: %s found, level:%d is > bestposs\n", ex2->ex_name, index);
#endif
				found = 1;
				ancestors[index-2] = ex2;
			}
			else if (index == bestposs) {
#ifdef DEBUG
				(void) fprintf(stderr, "best match %s found, checking access\n", ex2->ex_name);
#endif
				if (check_client(ex2, rqstp, transp)) {
				    success = 1;
				    break;
				}
				else
				    ++bestposs;
			}
		}
		if (success) {
			if ((anc_fd = open(ex2->ex_name, O_RDONLY, 0)) < 0) {
				fhs.fhs_status = errno;
				perror("mountd: open");
				goto fail;
			}
			goto hit;
		}
		if (found) {
			for (i= ((bestposs==1)? 0:bestposs-2); i< MAX_LEVELS-1; i++)
				if (ancestors[i] != NULL) {
#ifdef DEBUG
					(void) fprintf(stderr, "Checking ancestor: %s for allowable access\n", ancestors[i]->ex_name);
#endif
					if (check_client(ancestors[i], rqstp, transp)) {
						success = 1;
						break;
					}
				}
			if (success) {
				if ((anc_fd = open(ancestors[i]->ex_name, O_RDONLY, 0)) < 0) {
					fhs.fhs_status = errno;
					perror("mountd: open");
					goto fail;
				}
				goto hit;
			}
		}
	}
	fhs.fhs_status = EACCES;
	goto fail;
  hit:
	if (nfs_getfh(fd, anc_fd, &fh) < 0) {
		fhs.fhs_status = errno;
		perror("mountd: nfs_getfh");
		goto fail;
	}
	fhs.fhs_status = 0;
	fhs.fhs_fh = fh;
	(void)close(anc_fd);
	for (ml = mountlist; ml != NULL; ml = ml->ml_nxt) {
		if (strcmp(ml->ml_path, path) == 0 &&
		    strcmp(ml->ml_name, machine) == 0)
			break;
	}
	if (ml == NULL) {
		ml = (struct mountlist *)exmalloc(sizeof(struct mountlist));
		ml->ml_path = (char *)exmalloc(strlen(path) + 1);
		(void) strcpy(ml->ml_path, path);
		ml->ml_name = (char *)exmalloc(strlen(machine) + 1);
		(void) strcpy(ml->ml_name, machine);
		ml->ml_nxt = mountlist;
		mountlist = ml;
	}
fail:
	(void) close(fd);
	if (!svc_sendreply(transp, xdr_fhstatus, &fhs)) {
		syslog(LOG_ERR, "couldn't reply to rpc call");
		mtd_abort();
	} else {
		dumptofile();
	}
	svc_freeargs(transp, xdr_path, &path);
}

check_client(ex, rqstp, transp)
    struct exports *ex;
    struct svc_req *rqstp;
    SVCXPRT *transp;
{
    struct sockaddr_in sin;
    register struct authunix_parms *credp =
	(struct authunix_parms *)rqstp->rq_clntcred;
    char *machine = credp->aup_machname;
    rpc_uid_t uid = credp->aup_uid;
    struct authunix_parms acred;

    if (ex->ex_flags & M_EXFASCIST)
    {
	acred = *credp;
	sin = transp->xp_raddr;
	if (nfsmapctl(NFSMC_GET, (char *)&sin, sizeof(sin), uid, &acred) < 0)
	{
#if 0
	    syslog(LOG_ERR, "check_client: check for client %s:%d failed (%d)",
		   inet_ntoa(sin.sin_addr), uid, errno);
#endif
	    return 0;
	}
    }
    return (ex->ex_groups ? check_groups(ex->ex_groups, machine) : 1);
}

/*
 * Check if machine is in groups structure.  If not, call YP.
 */
check_groups(headgl, mach)
	struct groups *headgl;
	char *mach;
{
	struct groups *gl;
	int length;

	/* 
	 * first check for exact match on machine name
	 */
	for (gl = headgl; gl != NULL; gl = gl->g_next){ 
#ifdef DEBUG
		(void) fprintf(stderr, "checking machines: %s for %s\n", gl->g_name, mach);
#endif
		if (strcasecmp(gl->g_name, mach) == 0)
			return(TRUE);
		else if (((length = local_hostname_length(mach)) != NULL) && (strncasecmp(gl->g_name, mach, length) == 0))
			return(TRUE);
	}
	/*
	 * now check netgroups, if not here fail it
	 */
	for (gl = headgl; gl != NULL; gl = gl->g_next){ 
#ifdef DEBUG
		(void) fprintf(stderr, "checking innetgr: %s for %s\n", gl->g_name, mach);
#endif
		if (innetgr(gl->g_name, mach, NULL, mydomain)){
			return(TRUE);
		}
	}
	return(FALSE);
}

/*
 * Check the pathnames of the export name and the desired mount
 * pathname.
 */
path_check(list_name, name)
 	char *list_name, *name;
{
 	char *ch1, *ch2;
 	char *ch11, *ch22;
 	char s1, s2;
 	int done, level=0;
 	char *index(); 
 
#ifdef DEBUG
	(void) fprintf(stderr, "path_check %s with %s\n", list_name, name);
#endif
 	if (!strcmp(list_name, "/"))
 		return(TRUE);
 	ch1 = list_name;
 	ch2 = name;
 	done = 0;
 	while (!done) {
 		if ((ch1 = goto_char(ch1)) != NULL)
 			ch11 = index(ch1, '/');
 		if ((ch2 = goto_char(ch2)) != NULL)
 			ch22 = index(ch2, '/');
 		if (ch11 && *ch11 != '\0') {
 			s1 = *ch11;
 			*ch11 = '\0';
 			ch11++;
 		}
 		if (ch22 && *ch22 != '\0') {
 			s2 = *ch22;
 			*ch22 = '\0';
 			ch22++;
 		}
 		if ((ch1 && ch2) && !strcmp(ch1, ch2)) {
 			if (ch11 && *ch11 != '\0') {
 				*--ch11 = s1;
 				ch11++;
 			}
 			if (ch22 && *ch22 != '\0') {
 				*--ch22 = s2;
 				ch22++;
 			}
 			ch1 = ch11;
 			ch2 = ch22;
 			if ((ch11 && *ch11 == '\0') || !ch11) {
				/*
				 * count number of slashes remaining in ancestor
				 */
				if (ch2) {
					for (--ch2; ch2 && *ch2!='\0'; ch2++)
						if (*ch2 == '/') level++;
					if (*--ch2 == '/')
						level--;
				}
 				return(level);
			}
 			if ((ch11 && *ch11 != '\0') && ((ch22 && *ch22 == '\0') || !ch22))
 				done = 1;
 		}
 		else {
 			if (ch11 && *ch11 != '\0')
 				*--ch11 = s1;
 			if (ch22 && *ch22 != '\0')
 				*--ch22 = s2;
 			done = 1;
 		}
 	}
	return(level);
}

/*
 * Skip over slashes (/) and go to first character
 */
char *
goto_char(ch)
 	char *ch;
{
 	for (;ch && *ch == '/'; ch++)
 		;
	if (ch)
 		return(ch);
	else
		return(NULL);
}
 
/*
 * Remove an entry from mounted list
 */
mtd_umount(rqstp, transp)
	struct svc_req *rqstp;
	SVCXPRT *transp;
{
	char *path, *machine;
	struct mountlist *ml, *oldml;

	path = NULL;
	if (!svc_getargs(transp, xdr_path, &path)) {
		svcerr_decode(transp);
		mtd_abort();
		return;
	}
	if (rqstp->rq_cred.oa_flavor == AUTH_UNIX) {
		machine =
		  ((struct authunix_parms *)rqstp->rq_clntcred)->aup_machname;
	}
	else
		return;
#ifdef DEBUG
	(void) fprintf(stderr, "umounting %s for %s\n", path, machine);
#endif
	oldml = mountlist;
	for (ml = mountlist; ml != NULL;
	    oldml = ml, ml = ml->ml_nxt) {
		if (strcmp(ml->ml_path, path) == 0 &&
		    strcmp(ml->ml_name, machine) == 0) {
			if (ml == mountlist)
				mountlist = ml->ml_nxt;
			else
				oldml->ml_nxt = ml->ml_nxt;
#ifdef DEBUG
			(void) fprintf(stderr, "freeing %s\n", path);
#endif
			free(ml->ml_path);
			free(ml->ml_name);
			free((char *)ml);
			break;
		    }
	}
	if (!svc_sendreply(transp,xdr_void, NULL)) {
		syslog(LOG_ERR, "couldn't reply to rpc call");
		mtd_abort();
	} else {
		dumptofile();
	}
	svc_freeargs(transp, xdr_path, &path);
}

/*
 * Remove all entries for one machine from mounted list
 */
mtd_umountall(rqstp, transp)
	struct svc_req *rqstp;
	SVCXPRT *transp;
{
	char *machine;
	struct mountlist *ml, *oldml;

	if (!svc_getargs(transp, xdr_void, NULL)) {
		svcerr_decode(transp);
		return;
	}
	/*
	 * We assume that this call is asynchronous and made via the 
	 * portmapper callit routine.  Therefore return control immediately.
	 * The error causes the portmapper to remain silent, as opposed to
	 * every machine on the net blasting the requester with a response.
	 */
	svcerr_systemerr(transp);
	if (rqstp->rq_cred.oa_flavor == AUTH_UNIX) {
		machine =
		   ((struct authunix_parms *)rqstp->rq_clntcred)->aup_machname;
	}
	else
		return;
	oldml = mountlist;
	for (ml = mountlist; ml != NULL; ml = ml->ml_nxt) {
		if (strcmp(ml->ml_name, machine) == 0) {
#ifdef DEBUG
			(void) fprintf(stderr, "got a hit\n");
#endif
			if (ml == mountlist) {
				mountlist = ml->ml_nxt;
				oldml = mountlist;
			}
			else
				oldml->ml_nxt = ml->ml_nxt;
			free(ml->ml_path);
			free(ml->ml_name);
			free((char *)ml);
		}
		else
			oldml = ml;
	}
	dumptofile();
	svc_freeargs(transp, xdr_void, NULL);
}

/*
 * Save current mount state info so we
 * can attempt to recover in case of a crash.
 */
dumptofile()
{
#ifndef NORMTAB
	static char *t1 = "/etc/zzXXXXXX";
	static char *t2 = "/etc/zzXXXXXX";
	FILE *fp;
	struct mountlist *ml;
	char *mktemp();
	int mf;
	
	(void) strcpy(t2, t1);
	t2 = mktemp(t2);
	if ((mf = creat(t2, 0644)) < 0) {
		syslog(LOG_ERR, "creat: %m, cannot dump mountlist to %s", RMTAB);
		return;
	}
	if ((fp = fdopen(mf, "w")) == NULL) {
		syslog(LOG_ERR, "fdopen: Cannot dump mountlist to %s", RMTAB);
		return;
	}
	for (ml = mountlist; ml != NULL; ml = ml->ml_nxt)
		(void) fprintf(fp, "%s:%s\n", ml->ml_name, ml->ml_path);
	if (rename(t2, RMTAB) < 0) 
		syslog(LOG_ERR, "rename: %m, cannot dump mountlist to %s", RMTAB);
	(void) fclose(fp);
#endif
}

/*
 * send current export list
 */
mtd_export(transp)
	SVCXPRT *transp;
{
	struct exports *ex;

	if (!svc_getargs(transp, xdr_void, NULL)) {
		svcerr_decode(transp);
		mtd_abort();
	} else {
		/*
		 * Send exported request the list of flattened exports
		 * to conform with other os's.  Otherwise, all 
		 * exported directories would not be seen.
		 */
		ex = flatexports;
		if (!svc_sendreply(transp, xdr_exports, &ex)) {
			syslog(LOG_ERR, "couldn't reply to rpc call");
			mtd_abort();
		}
		svc_freeargs(transp, xdr_void, NULL);
	}
}

/*
 * Parse exports file.  If this is the first call or the file exportfile
 * has changed, it is opened and parsed to create an exports list.
 * File should look like:
 *
 * pathname [-r=#] [-o] [name1 name2 ... namen]
 *   or
 * #anything
 *
 * pathname:	name of a mounted local file system
 *		name of a directory of a mounted local filesystem
 * optional options
 *	 -r=#	for entire filesystem, root maps to #
 *	 -o	entire filesystem exported readonly
 * name:	netgroup or host name or a list of whitespace separated
 *			names (optional, no names implies everyone)
 *
 * A '#' anywhere in the line marks a comment to the end of that line
 *
 * NOTE: a non-white character in column 1 indicates a new export
 *	specification.
 */
set_exports()
{
	int bol;	/* begining of line */
	int eof;	/* end of file */
	int opt;	/* beginning of option */
	struct exports *ex, *ex2;
	int newdev();
	char ch;
	char *str;
	char *l;
	char line[MAXLINE];	/* current line */
	struct stat statb;
	FILE *fp;
	int isdev;
	int found;

	if (stat(exportfile, &statb) < 0) {
#ifdef DEBUG
		(void) fprintf(stdout, "%s: stat failed", pgmname);
		perror("mountd: exportfile");
#endif
		freeex(exports);
		exports=NULL;
		freeex(flatexports);
		flatexports=NULL;
		exports = NULL;
		return;
	}
	if (exportstat.st_mtime == statb.st_mtime) {
		return;
	}
	exportstat = statb;

	if ((fp = fopen(exportfile, "r")) == NULL) {
		syslog(LOG_ERR, "fopen: %m");
		freeex(exports);
		exports=NULL;
		freeex(flatexports);
		flatexports=NULL;
		exports = NULL;
		return;
	}

	freeex(exports);
	exports=NULL;
	freeex(flatexports);
	flatexports=NULL;
	eof = 0;

	l = line;
	*l = '\0';
	while (!eof) {
		switch (*l) {
		case '\0':
		case '\n':
			/*
			 * End of line, read next line and set state vars
			 */
			if (fgets(line, MAXLINE, fp) == NULL) {
				eof = 1;
			} else {
				bol = 1;
				opt = 0;
				l = line;
			}
			break;
		case ' ':
		case '	':
			/*
			 * White space, skip to first non-white
			 */
			while (*l == ' ' || *l == '	') {
				l++;
			}
			bol = 0;
			break;
		case '#':
			/*
			 * Comment, skip to end of line.
			 */
			*l = '\0';
			break;
		case '-':
			/*
			 * option of the form: -option=value or -option
			 */
			if (bol) {
				syslog(LOG_ERR, "Cannot parse '%s'", l);
				*l = '\0';
				break;
			}
			opt = 1;
			l++;
			break;
		default:
			/*
			 * normal character: if col one get dir else name or opt
			 */
			str = l;
			while (*l != ' ' && *l != '	' &&
			     *l != '\0' && *l != '\n') {
				l++;
			}
			ch = *l;
			*l = '\0';
			if (bol) {
				/*
				 * Logic for building export list:
				 *  The list is organized by dev horizontally,
				 *  all entries of the same dev hang off vertically.
				 *  The top dev entry is just the first one read.
				 *
				 *  Try to find an exports list entry with the
				 *  same dev number.  If not found, this entry
				 *  represents a new top entry.  Connect its
				 *  devptr to the front of the exports list.
				 *  If a dev match was found, tack this entry on
				 *  to the "next" pointer of the top entry for this 
				 *  dev.  Always check if this is a duplicate entry.
				 */
#ifdef DEBUG_FULL
				(void) fprintf(stderr, "--- next /etc/exports entry to add is %s ---\n", str);
#endif
				if (stat(str, &statb) < 0) {
					syslog(LOG_ERR, "stat: %m, Cannot stat %s", str);
					break;
				}
				for (ex = exports; ex != NULL; ex = ex->ex_devptr) 
					if (ex->ex_dev == statb.st_dev) break;

				if (ex == NULL) {
					isdev = TRUE;
#ifdef DEBUG_FULL
					(void) fprintf(stderr, "adding new export %s\n", str);
#endif
					newdev(str, statb.st_dev, statb.st_ino, statb.st_gennum);
					ex = exports;
				}
				else {
					found = FALSE;
					for (ex2=ex; ex2 != NULL; ex2 = ex2->ex_next)
						if (ex2->ex_ino == statb.st_ino) {
							syslog(LOG_ERR, "Duplicate directory entry for %s - duplicate ignored", str); 
							found = TRUE;
							break;
						}
					if (!found) {
						isdev = FALSE;
						/*
					  	   initialize rootmap to nobody and flags to 0
						*/
#ifdef DEBUG_FULL
						(void) fprintf(stderr, "adding new export %s\n", str);
#endif
						ex->ex_next = newex(str, ex->ex_next, statb.st_dev, statb.st_ino, statb.st_gennum, -2, 0);
					}
				}
			}
			else {
				if (opt) {
					opt = 0;
					if (isdev) 
						setopt(str, ex);
					else 
						setopt(str, ex->ex_next);
				}
				else {
					if (!isdev) {
#ifdef DEBUG_FULL
						(void) fprintf(stderr, "adding new groups %s to %s\n", str, ex->ex_next->ex_name);
#endif
						ex->ex_next->ex_groups = newgroup(str, ex->ex_next->ex_groups);
					}
					else {
#ifdef DEBUG_FULL
						(void) fprintf(stderr, "adding new groups %s to %s\n", str, ex->ex_name);
#endif
						ex->ex_groups = newgroup(str, ex->ex_groups);
					}
				}
			}
			*l = ch;
			bol = 0;
			break;
		}
	}
	(void) fclose(fp);
#ifdef DEBUG
	(void) fprintf(stderr, "*** export list final results ***\n");
	print_exports(exports);
#endif

	/*
	 * Update the kernel's exportfsdata list so that it is in sync with
	 * the exports file and the mountd's list.
	 */

	update_exportfsdata();
	flatten_exports();
#ifdef DEBUG_FULL
	(void) fprintf(stderr, "*** export list final results flattened ***\n");
	print_exports(flatexports);
#endif
	return;
}

/*
 * Make exportfs calls necessary to update kernel's view of exports.
 */
update_exportfsdata()
{
	struct exports *ex, *ex2, *k_ex=NULL, *k_ptr;
	struct exportfsdata *kbuf=NULL;
	struct exportfsdata *extokex();
	struct stat statb;
	u_int cookie=0;

	/*
	 * Build a list equivalent to kernel's list.
	 */
	if ((kbuf = (struct exportfsdata *) malloc(sizeof(struct exportfsdata))) == NULL) {
		syslog(LOG_ERR, "Memory allocation failed: %m");
		exit(1);
	}
	for (;;) {
		if ((exportfs (EXPORTFS_READ, &cookie, kbuf)) < 0) {
			if (errno == ENOENT) break;
			syslog(LOG_ERR, "exportfs READ: %m");
			exit (1);
		}
		k_ex = newex(kbuf->e_path, k_ex, kbuf->e_fsid, kbuf->e_gnum, kbuf->e_gen, kbuf->e_rootmap, kbuf->e_flags);
		if (kbuf->e_more == 0) break;
	}
#ifdef DEBUG_FULL 
	(void) fprintf (stderr, "*** Kernel exportfsdata before changes ***\n");
	print_exports(k_ex);
#endif

	/*
	 * Loop through mountd's export list.  Find matching entry in
	 * local view of kernel's exportfsdata list.  If one is not found,
	 * add this export to kernel's list.  If they are different,
	 * update the kernel's data.  Mark the k_ex entry that has 
	 * been looked at so that we know what hasn't been checked yet.
	 */

	 for (ex=exports; ex!=NULL; ex=ex->ex_devptr)
		for (ex2=ex; ex2!=NULL; ex2=ex2->ex_next) {

			/*
			   find matching kernel entry
			*/
			for (k_ptr=k_ex; k_ptr!=NULL; k_ptr=k_ptr->ex_next)
				if ((strcmp(k_ptr->ex_name, ex2->ex_name))==0) break;

			/*
			   if export is not in kernel's exportfsdata, add it 
			*/
			if (k_ptr == NULL) {
#ifdef DEBUG_FULL
				(void) fprintf(stderr, "Adding new export %s to kernel\n", ex2->ex_name);
#endif
				kbuf = extokex(ex2->ex_name, ex2->ex_dev, ex2->ex_ino, 
						ex2->ex_gen, ex2->ex_rootmap, ex2->ex_flags);
				if ((exportfs(EXPORTFS_CREATE, NULL, kbuf)) < 0) {
					syslog(LOG_ERR, "exportfs CREATE of %s: %m", kbuf->e_path);
					exit (1);
				}
			}
			/*
			 * if kernel's exportfsdata struct is not uptodate, replace it 
			 */
			else if (!(ex_same(k_ptr, ex2))) {
#ifdef DEBUG_FULL
				(void) fprintf(stderr, "Fixing kernel export %s\n", ex2->ex_name);
#endif
				kbuf = extokex(k_ptr->ex_name, k_ptr->ex_dev, k_ptr->ex_ino, 
						k_ptr->ex_gen, k_ptr->ex_rootmap, k_ptr->ex_flags);
				if ((exportfs (EXPORTFS_REMOVE, NULL, kbuf))< 0) {
					syslog(LOG_ERR, "exportfs REMOVE of %s: %m", kbuf->e_path);
					exit (1);
				}
				kbuf = extokex(ex2->ex_name, ex2->ex_dev, ex2->ex_ino, 
						ex2->ex_gen, ex2->ex_rootmap, ex2->ex_flags);
				if ((exportfs(EXPORTFS_CREATE, NULL, kbuf)) < 0) {
					syslog(LOG_ERR, "exportfs CREATE(2) of %s: %m", kbuf->e_path);
					exit (1);
				}
				k_ptr->ex_name= "CHECKED";
			}
			else k_ptr->ex_name= "CHECKED";
		}

	/*
	 * Loop through k_ex list looking for entries that need to be 
	 * removed from kernel's exportfsdata list.
	 */

	for (k_ptr=k_ex; k_ptr!=NULL; k_ptr=k_ptr->ex_next)
		if (strcmp(k_ptr->ex_name, "CHECKED") != 0) {
#ifdef DEBUG_FULL
			(void)fprintf(stderr,"Removing kernel export %s\n", k_ptr->ex_name);
#endif
			kbuf = extokex(k_ptr->ex_name, k_ptr->ex_dev, k_ptr->ex_ino, 
					k_ptr->ex_gen, k_ptr->ex_rootmap, k_ptr->ex_flags);
			if ((exportfs (EXPORTFS_REMOVE, NULL, kbuf)) < 0) {
				syslog(LOG_ERR, "exportfs REMOVE(2) of %s: %m", kbuf->e_path);
				exit (1);
			}
		}
#ifdef DEBUG 
	(void) fprintf (stderr, "*** Kernel exportfsdata after changes ***\n");
	cookie = 0;
	for (;;) {
		if ((exportfs (EXPORTFS_READ, &cookie, kbuf)) < 0) {
			syslog(LOG_ERR, "exportfs READ(2): %m");
			exit (1);
		}
		(void)fprintf(stderr,"export name %s", kbuf->e_path);
		(void)fprintf(stderr,"-r=%d  dev: %d  ino: %d", kbuf->e_rootmap, kbuf->e_fsid, kbuf->e_gnum);
		if (kbuf->e_flags & M_EXRONLY)
			(void)fprintf(stderr," (M_EXRONLY)");
		(void)fprintf(stderr, "\n");
		if (kbuf->e_more == 0) break;
	}
	(void)fprintf(stderr, "\n");
#endif
}

/*
 * Compare kernel's export entry to mountd's
 */

ex_same (k_ex, ex)
	struct exports *k_ex, *ex;
{
	if ((k_ex->ex_rootmap!=ex->ex_rootmap) || (k_ex->ex_flags!=ex->ex_flags) ||
		(k_ex->ex_ino != ex->ex_ino) || (k_ex->ex_gen != ex->ex_gen) || 
		(k_ex->ex_dev != ex->ex_dev))
		return (FALSE);
	return (TRUE);
}


newdev (name, dev, ino, gen)
	char *name;
	dev_t dev;
	ino_t ino;
	u_long gen;
{
	struct exports *new;
	char *newname;

	new = (struct exports *)exmalloc(sizeof(*new));
	newname = (char *)exmalloc(strlen(name) + 1);
	(void) strcpy(newname, name);

	new->ex_name = newname;
	new->ex_dev = dev;
	new->ex_ino = ino;
	new->ex_gen = gen;
	new->ex_next = NULL;
	new->ex_rootmap = -2;		/* Initialize to nobody */
	new->ex_flags = 0;
	new->ex_groups = NULL;		/* Groups ptr */
	new->ex_devptr = exports;
	exports = new;
}

struct exports *
newex(name, next, dev, ino, gen, rootmap, flags)
	char *name;
	struct exports *next;
	dev_t dev;
	ino_t ino;
	u_long gen;
	short rootmap;
	u_int flags;
{
	struct exports *new;
	char *newname;

	new = (struct exports *)exmalloc(sizeof(*new));
	newname = (char *)exmalloc(strlen(name) + 1);
	(void) strcpy(newname, name);

	new->ex_name = newname;
	new->ex_dev = dev;
	new->ex_ino = ino;
	new->ex_gen = gen;
	new->ex_rootmap = rootmap;
	new->ex_flags = flags;
	new->ex_next = next;
	new->ex_groups = NULL;		/* Groups ptr */
	new->ex_devptr = NULL;
	return (new);
}

struct exportfsdata *
extokex(name, dev, ino, gen, rootmap, flags)
	char *name;
	dev_t dev;
	ino_t ino;
	u_long gen;
	short rootmap;
	u_int flags;
{
	struct exportfsdata *new;
	char *newname;

	new = (struct exportfsdata *)exmalloc(sizeof(*new));

	(void)strcpy (new->e_path, name);
	new->e_fsid = dev;
	new->e_gnum = ino;
	new->e_gen = gen;
	new->e_rootmap = rootmap;
	new->e_flags = flags;
	new->e_more = 0;
	return(new);
}

struct groups *
newgroup(name, next)
	char *name;
	struct groups *next;
{
	struct groups *new;
	char *newname;

	new = (struct groups *)exmalloc(sizeof(*new));
	newname = (char *)exmalloc(strlen(name) + 1);
	(void) strcpy(newname, name);

	new->g_name = newname;
	new->g_next = next;
	return (new);
}

setopt(str, ex)
	char *str;
	struct exports *ex;
{
	char *m, *n;

	/*
	 * Parse options
	 */

	switch (str[0]) {
	case 'r':
		/*
		 * If r, then set root mapping field
		 */
		m = str;
		m++;
		if (*m != '=') {
			syslog(LOG_ERR, "%s bad export option format in %s", str, EXPORTS);
			return;
		}
		else {
			m++;
			if (*m == '-')
				n = ++m;
			else
				n = m;
			for (; !n ; n++)
				if (!isdigit(*n)) {
					/*
		 		 	 * Bad string
		 		 	 */
					syslog(LOG_ERR, "%c unknown root mapping integer in %s", *m, EXPORTS);
					return;
				}
			ex->ex_rootmap = atoi(m);
		}
		break;
	case 'n':
		/*
		 * if n, ignore (no filehandle obsolete)
		 */
		break;
	case 'o':
		/*
		 * if o, set flags field for readonly
		 */
		ex->ex_flags |= M_EXRONLY;
		break;
	case 'x':
		/*
		 * if x, set flags field for fascist
		 */
		ex->ex_flags |= M_EXFASCIST;
		break;
	default:
		/*
		 * Bad option
		 */
		syslog(LOG_ERR, "%c unknown export option in %s", str[0], EXPORTS);
		break;
	}
	return;
}


/*
 * Flatten exports list to show directory entries.
 */
flatten_exports()
{
	struct exports *ex, *ex2;
	struct exports *exnew = NULL;
	struct groups *groups;
	struct groups *groupsnew = NULL;

#ifdef DEBUG_FULL
	(void) fprintf(stderr, "\n******* Flattening exports: *******\n");
#endif
	for (ex = exports; ex != NULL; ex = ex->ex_devptr) {
		for (ex2 = ex; ex2 != NULL; ex2 = ex2->ex_next) {
#ifdef DEBUG_FULL
			(void) fprintf(stderr, "making newex for %s\n", ex2->ex_name);
#endif
			exnew = newex(ex2->ex_name, exnew, NULL, NULL, NULL, NULL, NULL);
			for (groups = ex2->ex_groups, groupsnew = NULL; groups != NULL; groups = groups->g_next) {
#ifdef DEBUG_FULL
				(void) fprintf(stderr, "making newgroup for %s\n", groups->g_name);
#endif
				groupsnew = newgroup(groups->g_name, groupsnew);
			}
			exnew->ex_groups = groupsnew;
		}
	}
	flatexports = exnew;
}

char *
exmalloc(size)
	int size;
{
	char *ret;

	if ((ret = (char *)malloc((unsigned) size)) == 0) {
		syslog(LOG_ERR, "Memory allocation failed in exmalloc: %m");
		exit(1);
	}
	return (ret);
}

/*
 * Free entire ex list
 */
freeex(ex)
	struct exports *ex;
{
	struct exports *tmpex, *ex2, *tmpex2;
	struct groups *groups, *tmpgroups;

	while (ex) {
		ex2 = ex->ex_next;
		while (ex2) {
			groups = ex2->ex_groups;
			while (groups) {
				tmpgroups = groups->g_next;
#ifdef DEBUG_FULL
				fprintf(stderr, "freeing group of ex2\n");
#endif
				free ((char *)groups);
				groups = tmpgroups;
			}
			tmpex2 = ex2->ex_next;
#ifdef DEBUG_FULL
				fprintf(stderr, "freeing export ex2\n");
#endif
			free ((char *)ex2);
			ex2 = tmpex2;
		}
		groups = ex->ex_groups;
		while (groups) {
			tmpgroups = groups->g_next;
#ifdef DEBUG_FULL
				fprintf(stderr, "freeing group of ex\n");
#endif
			free ((char *)groups);
			groups = tmpgroups;
		}
		tmpex = ex->ex_devptr;
#ifdef DEBUG_FULL
				fprintf(stderr, "freeing export ex\n");
#endif
		free ((char *)ex);
		ex = tmpex;
	}
}


#ifdef DEBUG
print_exports(ex)
	struct exports *ex;
{
	struct groups *groups;
	struct exports *ex2;

	(void) fprintf(stderr, "\nexport list begin:\n");
	for (; ex != NULL; ex = ex->ex_devptr) {
		for (ex2 = ex; ex2 != NULL; ex2 = ex2->ex_next) {
			(void) fprintf(stderr, "fs or dir: %s", ex2->ex_name);
			(void) fprintf(stderr, " -r=%d ", ex2->ex_rootmap);
			if (ex2->ex_flags & M_EXRONLY)
				(void) fprintf(stderr, " ( M_EXRONLY )");
			(void) fprintf(stderr, "\n\tdev: %d, ino: %d", ex2->ex_dev, ex2->ex_ino);
			for (groups= ex2->ex_groups; groups!= NULL; groups= groups->g_next)
				(void) fprintf(stderr, " %s", groups->g_name);
			(void) fprintf(stderr, "\n");
		}
		(void) fprintf(stderr, "finish exports for this dev\n");
	}
	(void) fprintf(stderr, "export list end:\n\n");
}
#endif

usage()
{
	(void) fprintf(stderr,"usage: mountd [-i]\n");
	(void) fflush(stderr);
	exit(1);
}

mtd_abort()
{
	/*
	 * This routine is a do-nothing to replace the libc abort, to prevent
	 * mountd from crashing all the time.  It is safe to remove this stub
	 * if running under inetd, since inetd will just restart us when we
	 * crash and the core dumps may be useful.
	 */
}

#ifdef KERBEROS
#include <krb.h>
#include <pwd.h>
#include <grp.h>

char *auth_to_user();

kuidops(kop, rqstp, transp)
	int kop;
	struct svc_req *rqstp;
	SVCXPRT *transp;
{
	KTEXT_ST kauth;
	AUTH_DAT *kdata;
	char *user;
	struct sockaddr_in client_addr;
  	register struct authunix_parms *credp = 
		(struct authunix_parms *) rqstp->rq_clntcred;
	struct authunix_parms ncred, *np = &ncred;
	struct passwd *pw, pwbuf;
	static char thishost[255];
	rpc_uid_t uid;
	gid_t *initgroups();
	bool_t xdr_krbtkt();
	datum d, k;
	struct dbmcred up;
	long time();

	if (thishost[0] == '\0')
		gethostname(thishost, 255);
	if (!svc_getargs(transp, xdr_krbtkt, &kauth)) {
		svcerr_decode(transp);
		mtd_abort();
		return;
	}
	client_addr = *svc_getcaller(transp);
	client_addr.sin_port = 0; /* kernel checks pno, too! */
	switch(kop) {
	case KUID_SET:
		/*
		 * Unmapping does not require a Kerberos ticket
		 * (a logout-induced detach may occur after a
		 * ticket has expired.)
		 * Purging does not require a Kerberos ticket
		 * (usually done at boot time when no tickets
		 * are available.)  This leaves lots of interesting
		 * opportunities for sending a purge on a multi-user
		 * system, but we'll not worry about that now.
		 */
		user = auth_to_user(&kauth, client_addr.sin_addr, &kdata);
		if (user == NULL) {
			svc_freeargs(transp, xdr_krbtkt, &kauth);
			svcerr_weakauth(transp);
			return;
		}
		k.dptr = user; k.dsize = strlen(user);
		if(dbmfile) d = dbm_fetch(dbmfile,k);
		if (!(dbmfile) || d.dptr == NULL) {
#ifdef OLDFASCIST
			if (fascist) break;
#endif
			svc_freeargs(transp, xdr_krbtkt, &kauth);
			svcerr_weakauth(transp);
			return;
		}
		bcopy(d.dptr,(char *)&up,sizeof(up));
		uid = credp->aup_uid;
		/* Set the expiration time.
		 * The lifetime of mappings is approximately twice the
		 * Kerberos ticket lifetime.  This is to avoid confusion
		 * and reduce the impact for the Athena user community.
		 */
		np->aup_time = kdata->time_sec+kdata->life*300 + KRB_SLOP_TIME;
		np->aup_machname = thishost;
		np->aup_uid = up.uid;
		np->aup_gid = up.gid;
		np->aup_len = up.glen;
		np->aup_gids = up.gids;

#ifdef DEBUG
		if (debug) {
		    fprintf(stdout,
			    "Mapping user \"%s\", uid %d on %s to uid %d\n",
			    user, uid, inet_ntoa(client_addr.sin_addr),
			    up.uid);
		    fflush(stdout);
		    disp_cred(np);
		}
#endif
		errno = 0;
		if (nfsmapctl(NFSMC_SET, &client_addr,
				sizeof(struct sockaddr_in), uid, np) < 0) {
			perror("nfs_mapctl(NFSMC_SET)");
			fprintf(stdout, "Errno = %d\n", errno);
		}
		break;

	case KUID_DELETE:
		uid = credp->aup_uid;
		if (nfsmapctl (NFSMC_DELETE, &client_addr,
			sizeof(struct sockaddr_in), uid, NULL) < 0) {
			perror("nfs_mapctl(NFSMC_DELETE)");
			fprintf(stdout, "Errno = %d\n", errno);
		}
		break;

	case KUID_PURGE:
		uid = credp->aup_uid;
		if (nfsmapctl (NFSMC_FLUSH, &client_addr,
			sizeof(struct sockaddr_in), uid, NULL) < 0) {
			perror("nfs_mapctl(NFSMC_FLUSH)");
			fprintf(stdout, "Errno = %d\n", errno);
		}
		break;
	case KUID_UPURGE:
		user = auth_to_user(&kauth, client_addr.sin_addr, &kdata);
		if (user == NULL) {
			svc_freeargs(transp, xdr_krbtkt, &kauth);
			svcerr_weakauth(transp);
			return;
		}
		k.dptr = user; k.dsize = strlen(user);
		if (dbmfile) d = dbm_fetch(dbmfile,k);
		if (! (dbmfile) || d.dptr == NULL) {
			svc_freeargs(transp, xdr_krbtkt, &kauth);
			svcerr_weakauth(transp);
			return;
		}
		bcopy(d.dptr,(char *)&up,sizeof(up));
		uid = up.uid;

#ifdef DEBUG
		if (debug) {
		    fprintf(stdout,
			"Purging user \"%s\", mapped to %d from %s\n", user,
			uid, inet_ntoa(client_addr.sin_addr));
		    fflush(stdout);
		}
#endif		
		if (nfsmapctl(NFSMC_UFLUSH, &client_addr,
				sizeof(struct sockaddr_in), uid, NULL) < 0) {
			perror("nfs_mapctl(NFSMC_UFLUSH)");
			fprintf(stdout, "Errno = %d\n", errno);
		}
		break;
	default:
		fprintf(stdout, "Bad kop %d\n", kop);
		break;
	}
	if (!svc_sendreply(transp,xdr_void, NULL)) {
	    	fprintf(stdout, "kuidop: couldn't reply to rpc call\n");
		mtd_abort();
	}
	svc_freeargs(transp, xdr_krbtkt, &kauth);
}


/*
struct authunix_parms {
	u_long		 aup_time;
	char		*aup_machname;
	rpc_uid_t	 aup_uid;
	rpc_gid_t	 aup_gid;
	u_int		 aup_len;
	rpc_gid_t	*aup_gids;
};
*/

disp_cred(credp)
  register struct authunix_parms *credp;
{
	register int i;

	printf("Authenticator passed to nfs_mapctl is:\n");
	printf("time: %s", ctime(&credp->aup_time));
	printf("machine: %s\n", credp->aup_machname);
	printf("uid: %d\n", credp->aup_uid);
	printf("gid: %d\n", credp->aup_gid);
	printf("length of group list: %d\n", credp->aup_len);
	for(i=0; i< credp->aup_len; i++)
		printf("%d ", credp->aup_gids[i]);
	printf("\n");
	fflush(stdout);
}

sig_handler(sig, code, scp)
int sig, code;
struct sigcontext *scp;
{
    switch(sig) {
    case SIGALRM:

#ifdef DEBUG
	if (debug) {
	    fprintf(stdout, "About to expire old mappings\n");
	    fflush(stdout);
	}
#endif
	if (nfsmapctl(NFSMC_EXPIRE,
		      (struct sockaddr_in *)NULL, sizeof(struct sockaddr_in),
		      0, (struct authunix_parms *)NULL) < 0) {
	    perror("nfs_mapctl(NFSMC_EXPIRE)");
	    fprintf(stderr, "Errno = %d\n", errno);
	}

	break;

    default:
	break;
    }
    return;
}
#endif
