/*
 * Copyright (c) 1983 Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms are permitted
 * provided that: (1) source distributions retain this entire copyright
 * notice and comment, and (2) distributions including binaries display
 * the following acknowledgement:  ``This product includes software
 * developed by the University of California, Berkeley and its contributors''
 * in the documentation or other materials provided with the distribution
 * and in all advertising materials mentioning features or use of this
 * software. Neither the name of the University nor the names of its
 * contributors may be used to endorse or promote products derived
 * from this software without specific prior written permission.
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#ifndef lint
char copyright[] =
"@(#) Copyright (c) 1983 Regents of the University of California.\n\
 All rights reserved.\n";
#endif /* not lint */

#ifndef lint
static char sccsid[] = "@(#)tftpd.c	5.12 (Berkeley) 6/1/90";
#endif /* not lint */

/*
 * Trivial file transfer protocol server.
 *
 * This version includes many modifications by Jim Guyton <guyton@rand-unix>
 *
 * Even more changes by Alan S. Watt <Watt-Alan@.Yale.Edu>
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/signal.h>
#include <sys/time.h>
#include <sys/param.h>

#include <netinet/in.h>

#include <arpa/tftp.h>

#include <netdb.h>
#include <setjmp.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <syslog.h>
#include <string.h>

#define	TIMEOUT		5

extern	int errno;
struct	sockaddr_in sock_in = { AF_INET };
int	peer;
int	rexmtval = TIMEOUT;
int	maxtimeout = 5*TIMEOUT;

#define	PKTSIZE	SEGSIZE+4
char	buf[PKTSIZE];
char	ackbuf[PKTSIZE];
struct	sockaddr_in from;
int	fromlen;

extern int	tftpDebugLevel;
extern char*	tftpDefaultDirectory;
extern char*	tftpRootDirectory;
static void	sigChildHandler();
static int	childExited;

#if !(defined(BSD) && (BSD >= 199306)) && !defined(HAVE_STRERROR)
/*
 * strerror is here if you need it,  but you shouldn't unless your UNIX
 * flavor is quite ancient.
 */
char *
strerror(n)
int	n;
{
	extern char *sys_errlist[];
	extern int   sys_nerr;

	return n > sys_nerr ? "unknown error" : sys_errlist[n];
}
#endif

main(argc, argv)
int	argc;
char	**argv;
{
	register int n;
	int on = 1;

	openlog("tftpd", LOG_PID, LOG_DAEMON);
	if (tftpDebugLevel > 0)
		syslog (LOG_INFO, "tftpd started");

	if (argc > 1 && strcmp (argv[1], "-d") == 0) {
		setUpForDebugging();
	}
	if (ioctl(0, FIONBIO, &on) < 0) {
		syslog(LOG_ERR, "ioctl(FIONBIO): %m\n");
		exit(1);
	}

	/* wait up to 5 minutes for a request packet.  This
	 * means the parent daemon hangs around for requests
	 * spaced closely together, but doesn't run all the
	 * time when there's no need.
	 */
	signal (SIGCHLD, sigChildHandler);
	for (;;) {
		int pid;

		reapChildren();
		n = awaitInput(0);
		if (n < 0) {
			if (childExited || errno == EINTR)
				continue;
			syslog(LOG_ERR, "no input");
			exit (1);
		}
		if (n == 0) {
			syslog(LOG_INFO, "input timeout exceeded; normal exit");
			exit (0);
		}
		fromlen = sizeof (from);
		n = recvfrom(0, buf, sizeof (buf), 0, (struct sockaddr *) &from,
			     &fromlen);
		if (n < 0) {
			syslog(LOG_ERR, "recvfrom: %m\n");
			exit(1);
		}
		readConfigFile(argc, argv);

		/*
		 * Now that we have read the message out of the UDP
		 * socket, we fork and exit.  Thus, inetd will go back
		 * to listening to the tftp port, and the next request
		 * to come in will start up a new instance of tftpd.
		 *
		 * We do this so that inetd can run tftpd in "wait" mode.
		 * The problem with tftpd running in "nowait" mode is that
		 * inetd may get one or more successful "selects" on the
		 * tftp port before we do our receive, so more than one
		 * instance of tftpd may be started up.  Worse, if tftpd
		 * break before doing the above "recvfrom", inetd would
		 * spawn endless instances, clogging the system.
		 */
		pid = createChild();
		if (pid == 0) {
			runChild((struct tftphdr*)buf, n);
			exit (1);
		}
	}
}

/* Run directly, rather than called from inetd.
 */
setUpForDebugging()
{
	int peer;
	struct	sockaddr_in listenSock;
	struct  servent *serv;

	close(0); close(1); close(2);

	/* must be 0 */
	peer = socket(AF_INET, SOCK_DGRAM, 0);
	if (peer < 0) {
		syslog(LOG_ERR, "socket: %m\n");
		exit(1);
	}

	listenSock.sin_family = AF_INET;
	listenSock.sin_addr.s_addr = htonl(INADDR_ANY);
	if (serv = getservbyname("tftpd", "udp"))
		listenSock.sin_port = serv->s_port;
	else
		listenSock.sin_port = htons(69);

	if (bind(peer, (struct sockaddr *)&listenSock, sizeof (listenSock)) < 0) {
		syslog(LOG_ERR, "bind: %m\n");
		perror ("bind");
		exit(1);
	}
	listen (peer, 0);
}

/* Wait for input on specified channel (socket)
 * wait for <maxInputWait> seconds, or a default
 * of 5 minutes if that is not set.
 */
awaitInput(chan)
int	chan;
{
	int imask;
	int nready;
	struct timeval tv;
	extern int maxInputWait;

	if (maxInputWait > 0)
		tv.tv_sec = maxInputWait;
	else
		tv.tv_sec = 5*60;	/* default: wait for 5 minutes */
	tv.tv_usec = 0;
	imask = 1<<chan;
	nready = select (sizeof(imask)*8, &imask, (int*)0, (int*)0, &tv);
	return nready;
}

/* Just set a flag saying there are children to
 * reap.
 */
static void
sigChildHandler(signum)
int	signum;
{ 
	childExited = 1;
}

/* Create a child process */
createChild()
{
	int i, pid;

	for (i = 1; i < 20; i++) {
		pid = fork();
		if (pid < 0)
			sleep(i);
		else
			return pid;
	}
	if (pid < 0) {
		syslog(LOG_ERR, "fork: %m\n");
		exit(1);
	}
	return pid;
}

/* check for any terminated child processes */
reapChildren()
{
	int p;
	int uw;

	/* just lay to rest all children */
	while ((p = wait3(&uw, WNOHANG, (struct rusage*)0)) > 0)
		continue;
	childExited = 0;
}

/* Run the actual TFTP request in the child process
 * Get a connected socket to the client and process
 * the request.
 */
runChild(tp, n)
register struct tftphdr *tp;
int n;
{

	from.sin_family = AF_INET;
	alarm(0);
	close(0);
	close(1);
	peer = socket(AF_INET, SOCK_DGRAM, 0);
	if (peer < 0) {
		syslog(LOG_ERR, "socket: %m\n");
		exit(1);
	}
	if (bind(peer, (struct sockaddr *)&sock_in, sizeof (sock_in)) < 0) {
		syslog(LOG_ERR, "bind: %m\n");
		exit(1);
	}
	if (connect(peer, (struct sockaddr *)&from, sizeof(from)) < 0) {
		syslog(LOG_ERR, "connect: %m\n");
		exit(1);
	}
	tp->th_opcode = ntohs(tp->th_opcode);
	if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
		tftp(tp, n);

	/* error */
	syslog (LOG_ERR, "illegal opcode: %d\n", tp->th_opcode);
	exit(1);
}

int	validate_access();

struct formats;
int	tftpsendfile(struct formats *);
int	tftprecvfile(struct formats *);

struct formats {
	char	*f_mode;
	int	(*f_validate)();
	int	(*f_send)();
	int	(*f_recv)();
	int	f_convert;
} formats[] = {
	{ "netascii",	validate_access,	tftpsendfile,	tftprecvfile, 1 },
	{ "octet",	validate_access,	tftpsendfile,	tftprecvfile, 0 },
#ifdef notdef
	{ "mail",	validate_user,		sendmail,	recvmail, 1 },
#endif
	{ 0 }
};

/*
 * Handle initial connection protocol.
 */
tftp(tp, size)
	struct tftphdr *tp;
	int size;
{
	register char *cp;
	int first = 1, ecode;
	register struct formats *pf;
	char *filename, *mode;

#ifdef	BROKEN_TH_STUFF		/* solaris 2.3 redefiened th_stuff */
	filename = cp = (char *) &tp->th_stuff;
#else
	filename = cp = tp->th_stuff;
#endif

again:
	while (cp < buf + size) {
		if (*cp == '\0')
			break;
		cp++;
	}
	if (*cp != '\0') {
		nak(EBADOP);
		exit(1);
	}
	if (first) {
		mode = ++cp;
		first = 0;
		goto again;
	}
	for (cp = mode; *cp; cp++)
		if (isupper(*cp))
			*cp = tolower(*cp);
	for (pf = formats; pf->f_mode; pf++)
		if (strcmp(pf->f_mode, mode) == 0)
			break;
	if (pf->f_mode == 0) {
		nak(EBADOP);
		exit(1);
	}
	if (tftpDebugLevel > 0) {
		char buf[1024];
		buf[0] = '\0';
		getwd(buf);
		syslog(LOG_DEBUG, "request %s '%s' from %s; cwd='%s'",
			(tp->th_opcode == RRQ ? "read" : "write"),
			filename, inet_ntoa(from.sin_addr),
			buf);
	}
	ecode = (*pf->f_validate)(filename, tp->th_opcode);
	if (ecode) {
		nak(ecode);
		exit(1);
	}
	if (tp->th_opcode == WRQ) {
		char *status;
		if ((*pf->f_recv)(pf) >= 0)
			status = "succeeded";
		else
			status = "failed";
		syslog(LOG_INFO, "received '%s' from %s: %s", filename,
			inet_ntoa(from.sin_addr), status);
	}
	else {
		char *status;
		if ((*pf->f_send)(pf) >= 0)
			status = "succeeded";
		else
			status = "failed";
		syslog(LOG_INFO, "sent '%s' to %s: %s", filename,
			inet_ntoa(from.sin_addr), status);
	}
	exit(0);
}


FILE *file;

/*
 * Validate file access.
 *
 * Terminology:
 *
 *  +	A file pathname is "rooted" if it begins with a '/'.
 *
 *  +	The "DefaultDirectory" is the pathname to be used as
 *	the directory prefix for non-rooted requests.  This is
 *	specified by the configuration options "defaultDirectory".
 *
 *  +	The "RootDirectory" is the pathname to be used as the
 *	virtual root directory of the filesystem.  This is specified
 *	by the configuration file option "rootDirectory".
 *
 * Rules:
 *
 *  1)	If the pathname is not rooted, and there is no DefaultDirectory
 *	and there is no RootDirectory, DENY.
 *
 *  2)	If the pathname is rooted and there is a RootDirectory, insure
 *	the requested file is within the specified RootDirectory.
 *	If not, DENY. 
 *
 *  3)	If the pathname is not rooted and there is no DefaultDirectory,
 *	use the RootDirectory instead.
 *
 *  4)	If there is no access list specified for the pathname, or the
 *	specified access list is not defined, use the default access list.
 *
 *  5)	If there is an access list in effect for the pathname, grant
 *	access according to the list.
 *
 *  6)	Read access is granted only on files which exist and are publicly
 *	readable, unless specific permission is granted in a controlling
 *	access list.
 *
 *  7)	Write access is granted only if the requesting system has
 *	read-write permission to the requested file in the controlling
 *	access list.
 *
 *  8)	Pre-empting all rules above, DENY any access to the configuration
 *	file.
 *
 */
#define IS_ROOTED(S)	(*(S) == '/')
validate_access(filename, mode)
	char *filename;
	int mode;
{
	struct stat stbuf;
	int	fd;
	char	tmpPath[1024];
	int	permission;

	/* Rule 1:
	 */
	if (tftpDefaultDirectory == 0 && tftpRootDirectory == 0
	    && !IS_ROOTED(filename)) {
		if (tftpDebugLevel > 1)
			syslog(LOG_DEBUG, "file=%s; un-rooted access denied",
				filename);
		return EACCESS;
	}

	/* Rule 2:
	 */
	if ((tftpRootDirectory != 0 && IS_ROOTED(filename)) ||
	    (tftpDefaultDirectory != 0 && IS_ROOTED(filename))) {
		char _tmp[1024];
		char* realRootDir; 
		int maxPath;
		int rootLen;

		if (tftpRootDirectory != 0 ) {
			realRootDir = tftpRootDirectory;
		}
		else {
			realRootDir = tftpDefaultDirectory;
		}

		rootLen = strlen (realRootDir);

		/* make sure the pathname doesn't already contain
		 * the virtual root.
		 */

			/* Insure our temporary space is big enough */
			maxPath = ((sizeof _tmp) - 1) - rootLen;
			if (strlen(filename) >= maxPath) {
				if (tftpDebugLevel > 1)
					syslog (LOG_DEBUG,
					    "requested pathname too long (%d)",
						strlen (filename));
				return EACCESS;
			}

		if (strncmp(filename,realRootDir,rootLen) != 0) {

			/* Squeeze out any '.' or '..' components */
			strcpy (tmpPath, filename);
			if (realPath (tmpPath, _tmp) < 0) {
				if (tftpDebugLevel > 1)
					syslog (LOG_DEBUG, "realPath fails");
				return EACCESS;
			}

			/* Create the full pathname, prefixed by the
			 * virtual root.
			 */
			strcpy (tmpPath, realRootDir);
			strcat (tmpPath, _tmp);
			filename = tmpPath;
		}
		else {
			/* Squeeze out any '.' or '..' components */
		        strcpy (tmpPath, filename);
                        if (realPath (tmpPath, _tmp) < 0) {
                                if (tftpDebugLevel > 1)
                                        syslog (LOG_DEBUG, "realPath fails");
                                return EACCESS;
	}
			/* Create the full pathname */
			strcpy (tmpPath,_tmp);
			filename = tmpPath;
			if (strncmp(filename,realRootDir,rootLen) != 0) {
			    if (tftpDebugLevel > 1) {
				syslog(LOG_DEBUG, "file=%s; invalid access denied", filename);
				return EACCESS;
	                    }	
			}
		}
	}

	/* Rule 3:
	 */
	if ((!IS_ROOTED(filename)  && tftpRootDirectory != 0) ||
	    (!IS_ROOTED(filename)  && tftpDefaultDirectory != 0)) {
		char _tmp[1024];
		strcat (tmpPath, filename);
	        /* Squeeze out any '.' or '..' components */
                        strcpy (tmpPath, filename);
                        if (realPath (tmpPath, _tmp) < 0) {
                                if (tftpDebugLevel > 1)
                                        syslog (LOG_DEBUG, "realPath fails");
                                return EACCESS;
                        }
		if ( tftpDefaultDirectory == 0 ) {
			strcpy (tmpPath, tftpRootDirectory);
		}
		else {
			strcpy (tmpPath, tftpDefaultDirectory);
		}
		strcat (tmpPath, _tmp);
		filename = tmpPath;
	}


	/* Check access lists */
	/* Rules 4&5:
	 */
	permission = validateAccessToFile(filename, from.sin_addr.s_addr, mode);
	if (permission == 0) {
		if (tftpDebugLevel)
			syslog (LOG_DEBUG, "%s access denied",
				(mode==RRQ ? "read" : "write"));
		return EACCESS;
	}

	/* After all that, does it even exist? */
	/* Rules 6&7:
	 */
	if (stat(filename, &stbuf) < 0) {
		if (tftpDebugLevel > 1)
			syslog(LOG_DEBUG, "stat '%s' fails: %s",
				filename, strerror(errno));
		return (errno == ENOENT ? ENOTFOUND : EACCESS);
	}

	/* Permission 1 is equal to the old access rules.
	 * The file must already exist and be publically
	 * readable for read access, or publically writable
	 * for write access.
	 */
	if (permission == 1) {
		/* Rule 6:
		 */
		if (mode == RRQ) {
			if ((stbuf.st_mode&(S_IREAD >> 6)) == 0) {
				syslog (LOG_DEBUG, "read denied; mode = %o",
					stbuf.st_mode);
				return EACCESS;
			}
		/* Rule 7:
		 */
		} else {
			if ((stbuf.st_mode&(S_IWRITE >> 6)) == 0) {
				syslog (LOG_DEBUG, "write denied; mode = %o",
					stbuf.st_mode);
				return EACCESS;
			}
		}
	}

	/* Rule 8:
	 */
	if (isConfigFile (&stbuf)) {
		if (tftpDebugLevel > 1)
			syslog (LOG_DEBUG, "access to config file prohibited");
		return EACCESS;
	}

	/* If all access checks have passed, attempt to open the file.
	 * This will be done with the effective permissions of the TFTPD
	 * process.
	 */
	fd = open(filename, mode == RRQ ? 0 : 1);
	if (fd < 0) {
		syslog (LOG_DEBUG, "open fails; errno = %d", errno);
		return errno+100;
	}
	file = fdopen(fd, (mode == RRQ)? "r":"w");
	if (file == NULL) {
		syslog (LOG_DEBUG, "fdopen fails; errno = %d", errno);
		return errno+100;
	}
	return (0);
}

int	timeout;
jmp_buf	timeoutbuf;

void timer()
{

	timeout += rexmtval;
	if (timeout >= maxtimeout)
		exit(1);
	longjmp(timeoutbuf, 1);
}

/*
 * Send the requested file.
 */
tftpsendfile(pf)
	struct formats *pf;
{
	struct tftphdr *dp, *r_init();
	register struct tftphdr *ap;    /* ack packet */
	register int block = 1, size, n;

	signal(SIGALRM, timer);
	dp = r_init();
	ap = (struct tftphdr *)ackbuf;
	do {
		size = readit(file, &dp, pf->f_convert);
		if (size < 0) {
			nak(errno + 100);
			goto abort;
		}
		dp->th_opcode = htons((u_short)DATA);
		dp->th_block = htons((u_short)block);
		timeout = 0;
		(void) setjmp(timeoutbuf);

send_data:
		if (send(peer, dp, size + 4, 0) != size + 4) {
			syslog(LOG_ERR, "tftpd: write: %m\n");
			goto abort;
		}
		read_ahead(file, pf->f_convert);
		for ( ; ; ) {
			alarm(rexmtval);        /* read the ack */
			n = recv(peer, ackbuf, sizeof (ackbuf), 0);
			alarm(0);
			if (n < 0) {
				syslog(LOG_ERR, "tftpd: read: %m\n");
				goto abort;
			}
			ap->th_opcode = ntohs((u_short)ap->th_opcode);
			ap->th_block = ntohs((u_short)ap->th_block);

			if (ap->th_opcode == ERROR)
				goto abort;
			
			if (ap->th_opcode == ACK) {
				if (ap->th_block == block) {
					break;
				}
				/* Re-synchronize with the other side */
				(void) synchnet(peer);
				if (ap->th_block == (block -1)) {
					goto send_data;
				}
			}

		}
		block++;
	} while (size == SEGSIZE);
	(void) fclose(file);
	return 0;
abort:
	(void) fclose(file);
	return -1;
}

void justquit()
{
	exit(0);
}


/*
 * Receive a file.
 */
tftprecvfile(pf)
	struct formats *pf;
{
	struct tftphdr *dp, *w_init();
	register struct tftphdr *ap;    /* ack buffer */
	register int block = 0, n, size;

	signal(SIGALRM, timer);
	dp = w_init();
	ap = (struct tftphdr *)ackbuf;
	do {
		timeout = 0;
		ap->th_opcode = htons((u_short)ACK);
		ap->th_block = htons((u_short)block);
		block++;
		(void) setjmp(timeoutbuf);
send_ack:
		if (send(peer, ackbuf, 4, 0) != 4) {
			syslog(LOG_ERR, "tftpd: write: %m\n");
			goto abort;
		}
		write_behind(file, pf->f_convert);
		for ( ; ; ) {
			alarm(rexmtval);
			n = recv(peer, dp, PKTSIZE, 0);
			alarm(0);
			if (n < 0) {            /* really? */
				syslog(LOG_ERR, "tftpd: read: %m\n");
				goto abort;
			}
			dp->th_opcode = ntohs((u_short)dp->th_opcode);
			dp->th_block = ntohs((u_short)dp->th_block);
			if (dp->th_opcode == ERROR)
				goto abort;
			if (dp->th_opcode == DATA) {
				if (dp->th_block == block) {
					break;   /* normal */
				}
				/* Re-synchronize with the other side */
				(void) synchnet(peer);
				if (dp->th_block == (block-1))
					goto send_ack;          /* rexmit */
			}
		}
		/*  size = write(file, dp->th_data, n - 4); */
		size = writeit(file, &dp, n - 4, pf->f_convert);
		if (size != (n-4)) {                    /* ahem */
			if (size < 0) nak(errno + 100);
			else nak(ENOSPACE);
			goto abort;
		}
	} while (size == SEGSIZE);
	write_behind(file, pf->f_convert);
	(void) fclose(file);            /* close data file */

	ap->th_opcode = htons((u_short)ACK);    /* send the "final" ack */
	ap->th_block = htons((u_short)(block));
	(void) send(peer, ackbuf, 4, 0);

	signal(SIGALRM, justquit);      /* just quit on timeout */
	alarm(rexmtval);
	n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
	alarm(0);
	if (n >= 4 &&                   /* if read some data */
	    dp->th_opcode == DATA &&    /* and got a data block */
	    block == dp->th_block) {	/* then my last ack was lost */
		(void) send(peer, ackbuf, 4, 0);     /* resend final ack */
	}
	return 0;
abort:
	return -1;
}

struct errmsg {
	int	e_code;
	char	*e_msg;
} errmsgs[] = {
	{ EUNDEF,	"Undefined error code" },
	{ ENOTFOUND,	"File not found" },
	{ EACCESS,	"Access violation" },
	{ ENOSPACE,	"Disk full or allocation exceeded" },
	{ EBADOP,	"Illegal TFTP operation" },
	{ EBADID,	"Unknown transfer ID" },
	{ EEXISTS,	"File already exists" },
	{ ENOUSER,	"No such user" },
	{ -1,		0 }
};

/*
 * Send a nak packet (error message).
 * Error code passed in is one of the
 * standard TFTP codes, or a UNIX errno
 * offset by 100.
 */
nak(error)
	int error;
{
	register struct tftphdr *tp;
	int length;
	register struct errmsg *pe;
	extern char* strerror();

	tp = (struct tftphdr *)buf;
	tp->th_opcode = htons((u_short)ERROR);
	tp->th_code = htons((u_short)error);
	for (pe = errmsgs; pe->e_code >= 0; pe++)
		if (pe->e_code == error)
			break;
	if (pe->e_code < 0) {
		pe->e_msg = strerror(error - 100);
		tp->th_code = EUNDEF;   /* set 'undef' errorcode */
	}
	strcpy(tp->th_msg, pe->e_msg);
	length = strlen(pe->e_msg);
	tp->th_msg[length] = '\0';
	length += 5;
	if (send(peer, buf, length, 0) != length)
		syslog(LOG_ERR, "nak: %m\n");
}



syntax highlighted by Code2HTML, v. 0.9.1