tftpd.c revision 94443
11592Srgrimes/*
21592Srgrimes * Copyright (c) 1983, 1993
31592Srgrimes *	The Regents of the University of California.  All rights reserved.
41592Srgrimes *
51592Srgrimes * Redistribution and use in source and binary forms, with or without
61592Srgrimes * modification, are permitted provided that the following conditions
71592Srgrimes * are met:
81592Srgrimes * 1. Redistributions of source code must retain the above copyright
91592Srgrimes *    notice, this list of conditions and the following disclaimer.
101592Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
111592Srgrimes *    notice, this list of conditions and the following disclaimer in the
121592Srgrimes *    documentation and/or other materials provided with the distribution.
131592Srgrimes * 3. All advertising materials mentioning features or use of this software
141592Srgrimes *    must display the following acknowledgement:
151592Srgrimes *	This product includes software developed by the University of
161592Srgrimes *	California, Berkeley and its contributors.
171592Srgrimes * 4. Neither the name of the University nor the names of its contributors
181592Srgrimes *    may be used to endorse or promote products derived from this software
191592Srgrimes *    without specific prior written permission.
201592Srgrimes *
211592Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
221592Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
231592Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
241592Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
251592Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
261592Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
271592Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
281592Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
291592Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
301592Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
311592Srgrimes * SUCH DAMAGE.
321592Srgrimes */
331592Srgrimes
341592Srgrimes#ifndef lint
3531512Scharnierstatic const char copyright[] =
361592Srgrimes"@(#) Copyright (c) 1983, 1993\n\
371592Srgrimes	The Regents of the University of California.  All rights reserved.\n";
381592Srgrimes#endif /* not lint */
391592Srgrimes
401592Srgrimes#ifndef lint
4131512Scharnier#if 0
421592Srgrimesstatic char sccsid[] = "@(#)tftpd.c	8.1 (Berkeley) 6/4/93";
4331512Scharnier#endif
4431512Scharnierstatic const char rcsid[] =
4550476Speter  "$FreeBSD: head/libexec/tftpd/tftpd.c 94443 2002-04-11 17:14:22Z ume $";
461592Srgrimes#endif /* not lint */
471592Srgrimes
481592Srgrimes/*
491592Srgrimes * Trivial file transfer protocol server.
501592Srgrimes *
511592Srgrimes * This version includes many modifications by Jim Guyton
521592Srgrimes * <guyton@rand-unix>.
531592Srgrimes */
541592Srgrimes
551592Srgrimes#include <sys/param.h>
561592Srgrimes#include <sys/ioctl.h>
571592Srgrimes#include <sys/stat.h>
581592Srgrimes#include <sys/socket.h>
5918458Simp#include <sys/types.h>
601592Srgrimes
611592Srgrimes#include <netinet/in.h>
621592Srgrimes#include <arpa/tftp.h>
631592Srgrimes#include <arpa/inet.h>
641592Srgrimes
651592Srgrimes#include <ctype.h>
661592Srgrimes#include <errno.h>
671592Srgrimes#include <fcntl.h>
6845393Sbrian#include <libutil.h>
691592Srgrimes#include <netdb.h>
7031512Scharnier#include <pwd.h>
711592Srgrimes#include <setjmp.h>
721592Srgrimes#include <signal.h>
731592Srgrimes#include <stdio.h>
741592Srgrimes#include <stdlib.h>
751592Srgrimes#include <string.h>
761592Srgrimes#include <syslog.h>
771592Srgrimes#include <unistd.h>
781592Srgrimes
791592Srgrimes#include "tftpsubs.h"
801592Srgrimes
811592Srgrimes#define	TIMEOUT		5
8284047Sobrien#define	MAX_TIMEOUTS	5
831592Srgrimes
841592Srgrimesint	peer;
851592Srgrimesint	rexmtval = TIMEOUT;
8684047Sobrienint	max_rexmtval = 2*TIMEOUT;
871592Srgrimes
881592Srgrimes#define	PKTSIZE	SEGSIZE+4
891592Srgrimeschar	buf[PKTSIZE];
901592Srgrimeschar	ackbuf[PKTSIZE];
9194443Sumestruct	sockaddr_storage from;
921592Srgrimesint	fromlen;
931592Srgrimes
9490333Simpvoid	tftp(struct tftphdr *, int);
9594443Sumestatic void unmappedaddr(struct sockaddr_in6 *);
961592Srgrimes
971592Srgrimes/*
981592Srgrimes * Null-terminated directory prefix list for absolute pathname requests and
991592Srgrimes * search list for relative pathname requests.
1001592Srgrimes *
1011592Srgrimes * MAXDIRS should be at least as large as the number of arguments that
1021592Srgrimes * inetd allows (currently 20).
1031592Srgrimes */
1041592Srgrimes#define MAXDIRS	20
1051592Srgrimesstatic struct dirlist {
1061592Srgrimes	char	*name;
1071592Srgrimes	int	len;
1081592Srgrimes} dirs[MAXDIRS+1];
1091592Srgrimesstatic int	suppress_naks;
1101592Srgrimesstatic int	logging;
11171616Sbillfstatic int	ipchroot;
1121592Srgrimes
11390333Simpstatic char *errtomsg(int);
11490333Simpstatic void  nak(int);
11590333Simpstatic void  oack();
1161592Srgrimes
1171592Srgrimesint
11890333Simpmain(int argc, char *argv[])
1191592Srgrimes{
12090333Simp	struct tftphdr *tp;
12190333Simp	int n;
1221592Srgrimes	int ch, on;
12394443Sume	struct sockaddr_storage me;
12494443Sume	int len;
12518458Simp	char *chroot_dir = NULL;
12618458Simp	struct passwd *nobody;
12765850Swollman	char *chuser = "nobody";
1281592Srgrimes
12935152Sphk	openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
13071616Sbillf	while ((ch = getopt(argc, argv, "cClns:u:")) != -1) {
1311592Srgrimes		switch (ch) {
13271616Sbillf		case 'c':
13371616Sbillf			ipchroot = 1;
13471616Sbillf			break;
13571616Sbillf		case 'C':
13671616Sbillf			ipchroot = 2;
13771616Sbillf			break;
1381592Srgrimes		case 'l':
1391592Srgrimes			logging = 1;
1401592Srgrimes			break;
1411592Srgrimes		case 'n':
1421592Srgrimes			suppress_naks = 1;
1431592Srgrimes			break;
14418458Simp		case 's':
14518458Simp			chroot_dir = optarg;
14618458Simp			break;
14765850Swollman		case 'u':
14865850Swollman			chuser = optarg;
14965850Swollman			break;
1501592Srgrimes		default:
1511592Srgrimes			syslog(LOG_WARNING, "ignoring unknown option -%c", ch);
1521592Srgrimes		}
1531592Srgrimes	}
1541592Srgrimes	if (optind < argc) {
1551592Srgrimes		struct dirlist *dirp;
1561592Srgrimes
1571592Srgrimes		/* Get list of directory prefixes. Skip relative pathnames. */
1581592Srgrimes		for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
1591592Srgrimes		     optind++) {
1601592Srgrimes			if (argv[optind][0] == '/') {
1611592Srgrimes				dirp->name = argv[optind];
1621592Srgrimes				dirp->len  = strlen(dirp->name);
1631592Srgrimes				dirp++;
1641592Srgrimes			}
1651592Srgrimes		}
1661592Srgrimes	}
16718458Simp	else if (chroot_dir) {
16818458Simp		dirs->name = "/";
16918458Simp		dirs->len = 1;
17018458Simp	}
17171616Sbillf	if (ipchroot && chroot_dir == NULL) {
17271616Sbillf		syslog(LOG_ERR, "-c requires -s");
17371616Sbillf		exit(1);
17471616Sbillf	}
1751592Srgrimes
1761592Srgrimes	on = 1;
1771592Srgrimes	if (ioctl(0, FIONBIO, &on) < 0) {
17831512Scharnier		syslog(LOG_ERR, "ioctl(FIONBIO): %m");
1791592Srgrimes		exit(1);
1801592Srgrimes	}
1811592Srgrimes	fromlen = sizeof (from);
1821592Srgrimes	n = recvfrom(0, buf, sizeof (buf), 0,
1831592Srgrimes	    (struct sockaddr *)&from, &fromlen);
1841592Srgrimes	if (n < 0) {
18531512Scharnier		syslog(LOG_ERR, "recvfrom: %m");
1861592Srgrimes		exit(1);
1871592Srgrimes	}
1881592Srgrimes	/*
1891592Srgrimes	 * Now that we have read the message out of the UDP
1901592Srgrimes	 * socket, we fork and exit.  Thus, inetd will go back
1911592Srgrimes	 * to listening to the tftp port, and the next request
1921592Srgrimes	 * to come in will start up a new instance of tftpd.
1931592Srgrimes	 *
1941592Srgrimes	 * We do this so that inetd can run tftpd in "wait" mode.
1951592Srgrimes	 * The problem with tftpd running in "nowait" mode is that
1961592Srgrimes	 * inetd may get one or more successful "selects" on the
1971592Srgrimes	 * tftp port before we do our receive, so more than one
1981592Srgrimes	 * instance of tftpd may be started up.  Worse, if tftpd
1991592Srgrimes	 * break before doing the above "recvfrom", inetd would
2001592Srgrimes	 * spawn endless instances, clogging the system.
2011592Srgrimes	 */
2021592Srgrimes	{
2031592Srgrimes		int pid;
2041592Srgrimes		int i, j;
2051592Srgrimes
2061592Srgrimes		for (i = 1; i < 20; i++) {
2071592Srgrimes		    pid = fork();
2081592Srgrimes		    if (pid < 0) {
2091592Srgrimes				sleep(i);
2101592Srgrimes				/*
2111592Srgrimes				 * flush out to most recently sent request.
2121592Srgrimes				 *
2131592Srgrimes				 * This may drop some request, but those
2141592Srgrimes				 * will be resent by the clients when
2151592Srgrimes				 * they timeout.  The positive effect of
2161592Srgrimes				 * this flush is to (try to) prevent more
2171592Srgrimes				 * than one tftpd being started up to service
2181592Srgrimes				 * a single request from a single client.
2191592Srgrimes				 */
2201592Srgrimes				j = sizeof from;
2211592Srgrimes				i = recvfrom(0, buf, sizeof (buf), 0,
2221592Srgrimes				    (struct sockaddr *)&from, &j);
2231592Srgrimes				if (i > 0) {
2241592Srgrimes					n = i;
2251592Srgrimes					fromlen = j;
2261592Srgrimes				}
2271592Srgrimes		    } else {
2281592Srgrimes				break;
2291592Srgrimes		    }
2301592Srgrimes		}
2311592Srgrimes		if (pid < 0) {
23231512Scharnier			syslog(LOG_ERR, "fork: %m");
2331592Srgrimes			exit(1);
2341592Srgrimes		} else if (pid != 0) {
2351592Srgrimes			exit(0);
2361592Srgrimes		}
2371592Srgrimes	}
23818458Simp
23918458Simp	/*
24018458Simp	 * Since we exit here, we should do that only after the above
24118458Simp	 * recvfrom to keep inetd from constantly forking should there
24218458Simp	 * be a problem.  See the above comment about system clogging.
24318458Simp	 */
24418458Simp	if (chroot_dir) {
24571616Sbillf		if (ipchroot) {
24671616Sbillf			char *tempchroot;
24771616Sbillf			struct stat sb;
24871616Sbillf			int statret;
24994443Sume			struct sockaddr_storage ss;
25094443Sume			char hbuf[NI_MAXHOST];
25171616Sbillf
25294443Sume			memcpy(&ss, &from, from.ss_len);
25394443Sume			unmappedaddr((struct sockaddr_in6 *)&ss);
25494443Sume			getnameinfo((struct sockaddr *)&ss, ss.ss_len,
25594443Sume				    hbuf, sizeof(hbuf), NULL, 0,
25694443Sume				    NI_NUMERICHOST | NI_WITHSCOPEID);
25794443Sume			asprintf(&tempchroot, "%s/%s", chroot_dir, hbuf);
25871616Sbillf			statret = stat(tempchroot, &sb);
25971616Sbillf			if ((sb.st_mode & S_IFDIR) &&
26071616Sbillf			    (statret == 0 || (statret == -1 && ipchroot == 1)))
26171616Sbillf				chroot_dir = tempchroot;
26271616Sbillf		}
26318458Simp		/* Must get this before chroot because /etc might go away */
26465850Swollman		if ((nobody = getpwnam(chuser)) == NULL) {
26565850Swollman			syslog(LOG_ERR, "%s: no such user", chuser);
26618458Simp			exit(1);
26718458Simp		}
26818458Simp		if (chroot(chroot_dir)) {
26918458Simp			syslog(LOG_ERR, "chroot: %s: %m", chroot_dir);
27018458Simp			exit(1);
27118458Simp		}
27218458Simp		chdir( "/" );
27318458Simp		setuid(nobody->pw_uid);
27485299Sobrien		setgroups(1, &nobody->pw_gid);
27518458Simp	}
27618458Simp
27794443Sume	len = sizeof(me);
27894443Sume	if (getsockname(0, (struct sockaddr *)&me, &len) == 0) {
27994443Sume		switch (me.ss_family) {
28094443Sume		case AF_INET:
28194443Sume			((struct sockaddr_in *)&me)->sin_port = 0;
28294443Sume			break;
28394443Sume		case AF_INET6:
28494443Sume			((struct sockaddr_in6 *)&me)->sin6_port = 0;
28594443Sume			break;
28694443Sume		default:
28794443Sume			/* unsupported */
28894443Sume			break;
28994443Sume		}
29094443Sume	} else {
29194443Sume		memset(&me, 0, sizeof(me));
29294443Sume		me.ss_family = from.ss_family;
29394443Sume		me.ss_len = from.ss_len;
29494443Sume	}
2951592Srgrimes	alarm(0);
2961592Srgrimes	close(0);
2971592Srgrimes	close(1);
29894443Sume	peer = socket(from.ss_family, SOCK_DGRAM, 0);
2991592Srgrimes	if (peer < 0) {
30031512Scharnier		syslog(LOG_ERR, "socket: %m");
3011592Srgrimes		exit(1);
3021592Srgrimes	}
30394443Sume	if (bind(peer, (struct sockaddr *)&me, me.ss_len) < 0) {
30431512Scharnier		syslog(LOG_ERR, "bind: %m");
3051592Srgrimes		exit(1);
3061592Srgrimes	}
30794443Sume	if (connect(peer, (struct sockaddr *)&from, from.ss_len) < 0) {
30831512Scharnier		syslog(LOG_ERR, "connect: %m");
3091592Srgrimes		exit(1);
3101592Srgrimes	}
3111592Srgrimes	tp = (struct tftphdr *)buf;
3121592Srgrimes	tp->th_opcode = ntohs(tp->th_opcode);
3131592Srgrimes	if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
3141592Srgrimes		tftp(tp, n);
3151592Srgrimes	exit(1);
3161592Srgrimes}
3171592Srgrimes
3181592Srgrimesstruct formats;
31990333Simpint	validate_access(char **, int);
32090333Simpvoid	xmitfile(struct formats *);
32190333Simpvoid	recvfile(struct formats *);
3221592Srgrimes
3231592Srgrimesstruct formats {
3241592Srgrimes	char	*f_mode;
32590333Simp	int	(*f_validate)(char **, int);
32690333Simp	void	(*f_send)(struct formats *);
32790333Simp	void	(*f_recv)(struct formats *);
3281592Srgrimes	int	f_convert;
3291592Srgrimes} formats[] = {
33040765Sdg	{ "netascii",	validate_access,	xmitfile,	recvfile, 1 },
33140765Sdg	{ "octet",	validate_access,	xmitfile,	recvfile, 0 },
3321592Srgrimes#ifdef notdef
3331592Srgrimes	{ "mail",	validate_user,		sendmail,	recvmail, 1 },
3341592Srgrimes#endif
3351592Srgrimes	{ 0 }
3361592Srgrimes};
3371592Srgrimes
33884047Sobrienstruct options {
33984047Sobrien	char	*o_type;
34084047Sobrien	char	*o_request;
34184047Sobrien	int	o_reply;	/* turn into union if need be */
34284047Sobrien} options[] = {
34384047Sobrien	{ "tsize" },		/* OPT_TSIZE */
34484047Sobrien	{ "timeout" },		/* OPT_TIMEOUT */
34584047Sobrien	{ NULL }
34684047Sobrien};
34784047Sobrien
34884047Sobrienenum opt_enum {
34984047Sobrien	OPT_TSIZE = 0,
35084047Sobrien	OPT_TIMEOUT,
35184047Sobrien};
35284047Sobrien
3531592Srgrimes/*
3541592Srgrimes * Handle initial connection protocol.
3551592Srgrimes */
3561592Srgrimesvoid
35790333Simptftp(struct tftphdr *tp, int size)
3581592Srgrimes{
35990333Simp	char *cp;
36084047Sobrien	int i, first = 1, has_options = 0, ecode;
36190333Simp	struct formats *pf;
36284047Sobrien	char *filename, *mode, *option, *ccp;
3631592Srgrimes
3641592Srgrimes	filename = cp = tp->th_stuff;
3651592Srgrimesagain:
3661592Srgrimes	while (cp < buf + size) {
3671592Srgrimes		if (*cp == '\0')
3681592Srgrimes			break;
3691592Srgrimes		cp++;
3701592Srgrimes	}
3711592Srgrimes	if (*cp != '\0') {
3721592Srgrimes		nak(EBADOP);
3731592Srgrimes		exit(1);
3741592Srgrimes	}
3751592Srgrimes	if (first) {
3761592Srgrimes		mode = ++cp;
3771592Srgrimes		first = 0;
3781592Srgrimes		goto again;
3791592Srgrimes	}
3801592Srgrimes	for (cp = mode; *cp; cp++)
3811592Srgrimes		if (isupper(*cp))
3821592Srgrimes			*cp = tolower(*cp);
3831592Srgrimes	for (pf = formats; pf->f_mode; pf++)
3841592Srgrimes		if (strcmp(pf->f_mode, mode) == 0)
3851592Srgrimes			break;
3861592Srgrimes	if (pf->f_mode == 0) {
3871592Srgrimes		nak(EBADOP);
3881592Srgrimes		exit(1);
3891592Srgrimes	}
39084047Sobrien	while (++cp < buf + size) {
39184047Sobrien		for (i = 2, ccp = cp; i > 0; ccp++) {
39284047Sobrien			if (ccp >= buf + size) {
39386765Sbenno				/*
39486765Sbenno				 * Don't reject the request, just stop trying
39586765Sbenno				 * to parse the option and get on with it.
39686765Sbenno				 * Some Apple OpenFirmware versions have
39786765Sbenno				 * trailing garbage on the end of otherwise
39886765Sbenno				 * valid requests.
39986765Sbenno				 */
40086765Sbenno				goto option_fail;
40184047Sobrien			} else if (*ccp == '\0')
40284047Sobrien				i--;
40384047Sobrien		}
40484047Sobrien		for (option = cp; *cp; cp++)
40584047Sobrien			if (isupper(*cp))
40684047Sobrien				*cp = tolower(*cp);
40784047Sobrien		for (i = 0; options[i].o_type != NULL; i++)
40884047Sobrien			if (strcmp(option, options[i].o_type) == 0) {
40984047Sobrien				options[i].o_request = ++cp;
41084047Sobrien				has_options = 1;
41184047Sobrien			}
41284047Sobrien		cp = ccp-1;
41384047Sobrien	}
41484047Sobrien
41586765Sbennooption_fail:
41684047Sobrien	if (options[OPT_TIMEOUT].o_request) {
41784047Sobrien		int to = atoi(options[OPT_TIMEOUT].o_request);
41884047Sobrien		if (to < 1 || to > 255) {
41984047Sobrien			nak(EBADOP);
42084047Sobrien			exit(1);
42184047Sobrien		}
42284047Sobrien		else if (to <= max_rexmtval)
42384047Sobrien			options[OPT_TIMEOUT].o_reply = rexmtval = to;
42484047Sobrien		else
42584047Sobrien			options[OPT_TIMEOUT].o_request = NULL;
42684047Sobrien	}
42784047Sobrien
4281592Srgrimes	ecode = (*pf->f_validate)(&filename, tp->th_opcode);
42984047Sobrien	if (has_options)
43084047Sobrien		oack();
4311592Srgrimes	if (logging) {
43294443Sume		char hbuf[NI_MAXHOST];
43345393Sbrian
43494443Sume		getnameinfo((struct sockaddr *)&from, from.ss_len,
43594443Sume			    hbuf, sizeof(hbuf), NULL, 0,
43694443Sume			    NI_WITHSCOPEID);
43794443Sume		syslog(LOG_INFO, "%s: %s request for %s: %s", hbuf,
4381592Srgrimes			tp->th_opcode == WRQ ? "write" : "read",
4391592Srgrimes			filename, errtomsg(ecode));
4401592Srgrimes	}
4411592Srgrimes	if (ecode) {
4421592Srgrimes		/*
4431592Srgrimes		 * Avoid storms of naks to a RRQ broadcast for a relative
4441592Srgrimes		 * bootfile pathname from a diskless Sun.
4451592Srgrimes		 */
4461592Srgrimes		if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
4471592Srgrimes			exit(0);
4481592Srgrimes		nak(ecode);
4491592Srgrimes		exit(1);
4501592Srgrimes	}
4511592Srgrimes	if (tp->th_opcode == WRQ)
4521592Srgrimes		(*pf->f_recv)(pf);
4531592Srgrimes	else
4541592Srgrimes		(*pf->f_send)(pf);
4551592Srgrimes	exit(0);
4561592Srgrimes}
4571592Srgrimes
4581592Srgrimes
4591592SrgrimesFILE *file;
4601592Srgrimes
4611592Srgrimes/*
4621592Srgrimes * Validate file access.  Since we
4631592Srgrimes * have no uid or gid, for now require
4641592Srgrimes * file to exist and be publicly
4651592Srgrimes * readable/writable.
4661592Srgrimes * If we were invoked with arguments
4671592Srgrimes * from inetd then the file must also be
4681592Srgrimes * in one of the given directory prefixes.
4691592Srgrimes * Note also, full path name must be
4701592Srgrimes * given as we have no login directory.
4711592Srgrimes */
4721592Srgrimesint
47390333Simpvalidate_access(char **filep, int mode)
4741592Srgrimes{
4751592Srgrimes	struct stat stbuf;
4761592Srgrimes	int	fd;
4771592Srgrimes	struct dirlist *dirp;
4781592Srgrimes	static char pathname[MAXPATHLEN];
4791592Srgrimes	char *filename = *filep;
4801592Srgrimes
4811592Srgrimes	/*
4821592Srgrimes	 * Prevent tricksters from getting around the directory restrictions
4831592Srgrimes	 */
4841592Srgrimes	if (strstr(filename, "/../"))
4851592Srgrimes		return (EACCESS);
4861592Srgrimes
4871592Srgrimes	if (*filename == '/') {
4881592Srgrimes		/*
4891592Srgrimes		 * Allow the request if it's in one of the approved locations.
4901592Srgrimes		 * Special case: check the null prefix ("/") by looking
4911592Srgrimes		 * for length = 1 and relying on the arg. processing that
4921592Srgrimes		 * it's a /.
4931592Srgrimes		 */
4941592Srgrimes		for (dirp = dirs; dirp->name != NULL; dirp++) {
4951592Srgrimes			if (dirp->len == 1 ||
4961592Srgrimes			    (!strncmp(filename, dirp->name, dirp->len) &&
4971592Srgrimes			     filename[dirp->len] == '/'))
4981592Srgrimes				    break;
4991592Srgrimes		}
5001592Srgrimes		/* If directory list is empty, allow access to any file */
5011592Srgrimes		if (dirp->name == NULL && dirp != dirs)
5021592Srgrimes			return (EACCESS);
5031592Srgrimes		if (stat(filename, &stbuf) < 0)
5041592Srgrimes			return (errno == ENOENT ? ENOTFOUND : EACCESS);
5051592Srgrimes		if ((stbuf.st_mode & S_IFMT) != S_IFREG)
5061592Srgrimes			return (ENOTFOUND);
5071592Srgrimes		if (mode == RRQ) {
5081592Srgrimes			if ((stbuf.st_mode & S_IROTH) == 0)
5091592Srgrimes				return (EACCESS);
5101592Srgrimes		} else {
5111592Srgrimes			if ((stbuf.st_mode & S_IWOTH) == 0)
5121592Srgrimes				return (EACCESS);
5131592Srgrimes		}
5141592Srgrimes	} else {
5151592Srgrimes		int err;
5161592Srgrimes
5171592Srgrimes		/*
5181592Srgrimes		 * Relative file name: search the approved locations for it.
5196750Sjkh		 * Don't allow write requests that avoid directory
5201592Srgrimes		 * restrictions.
5211592Srgrimes		 */
5221592Srgrimes
5236750Sjkh		if (!strncmp(filename, "../", 3))
5241592Srgrimes			return (EACCESS);
5251592Srgrimes
5261592Srgrimes		/*
5271592Srgrimes		 * If the file exists in one of the directories and isn't
5281592Srgrimes		 * readable, continue looking. However, change the error code
5291592Srgrimes		 * to give an indication that the file exists.
5301592Srgrimes		 */
5311592Srgrimes		err = ENOTFOUND;
5321592Srgrimes		for (dirp = dirs; dirp->name != NULL; dirp++) {
53324193Simp			snprintf(pathname, sizeof(pathname), "%s/%s",
53424193Simp				dirp->name, filename);
5351592Srgrimes			if (stat(pathname, &stbuf) == 0 &&
5361592Srgrimes			    (stbuf.st_mode & S_IFMT) == S_IFREG) {
5371592Srgrimes				if ((stbuf.st_mode & S_IROTH) != 0) {
5381592Srgrimes					break;
5391592Srgrimes				}
5401592Srgrimes				err = EACCESS;
5411592Srgrimes			}
5421592Srgrimes		}
5431592Srgrimes		if (dirp->name == NULL)
5441592Srgrimes			return (err);
5451592Srgrimes		*filep = filename = pathname;
5461592Srgrimes	}
54784047Sobrien	if (options[OPT_TSIZE].o_request) {
54884047Sobrien		if (mode == RRQ)
54984047Sobrien			options[OPT_TSIZE].o_reply = stbuf.st_size;
55084047Sobrien		else
55184047Sobrien			/* XXX Allows writes of all sizes. */
55284047Sobrien			options[OPT_TSIZE].o_reply =
55384047Sobrien				atoi(options[OPT_TSIZE].o_request);
55484047Sobrien	}
55520052Sjoerg	fd = open(filename, mode == RRQ ? O_RDONLY : O_WRONLY|O_TRUNC);
5561592Srgrimes	if (fd < 0)
5571592Srgrimes		return (errno + 100);
5581592Srgrimes	file = fdopen(fd, (mode == RRQ)? "r":"w");
5591592Srgrimes	if (file == NULL) {
5601592Srgrimes		return errno+100;
5611592Srgrimes	}
5621592Srgrimes	return (0);
5631592Srgrimes}
5641592Srgrimes
56584047Sobrienint	timeouts;
5661592Srgrimesjmp_buf	timeoutbuf;
5671592Srgrimes
5681592Srgrimesvoid
56990333Simptimer(int sig __unused)
5701592Srgrimes{
57184047Sobrien	if (++timeouts > MAX_TIMEOUTS)
5721592Srgrimes		exit(1);
5731592Srgrimes	longjmp(timeoutbuf, 1);
5741592Srgrimes}
5751592Srgrimes
5761592Srgrimes/*
5771592Srgrimes * Send the requested file.
5781592Srgrimes */
5791592Srgrimesvoid
58090333Simpxmitfile(struct formats *pf)
5811592Srgrimes{
5821592Srgrimes	struct tftphdr *dp, *r_init();
58390333Simp	struct tftphdr *ap;    /* ack packet */
58490333Simp	int size, n;
58571926Sasmodai	volatile unsigned short block;
5861592Srgrimes
5871592Srgrimes	signal(SIGALRM, timer);
5881592Srgrimes	dp = r_init();
5891592Srgrimes	ap = (struct tftphdr *)ackbuf;
5901592Srgrimes	block = 1;
5911592Srgrimes	do {
5921592Srgrimes		size = readit(file, &dp, pf->f_convert);
5931592Srgrimes		if (size < 0) {
5941592Srgrimes			nak(errno + 100);
5951592Srgrimes			goto abort;
5961592Srgrimes		}
5971592Srgrimes		dp->th_opcode = htons((u_short)DATA);
5981592Srgrimes		dp->th_block = htons((u_short)block);
59984047Sobrien		timeouts = 0;
6001592Srgrimes		(void)setjmp(timeoutbuf);
6011592Srgrimes
6021592Srgrimessend_data:
60394299Sambrisko		{
60494299Sambrisko			int i, t = 1;
60594299Sambrisko			for (i = 0; ; i++){
60694299Sambrisko				if (send(peer, dp, size + 4, 0) != size + 4) {
60794299Sambrisko					sleep(t);
60894299Sambrisko					t = (t < 32) ? t<< 1 : t;
60994299Sambrisko					if (i >= 12) {
61094299Sambrisko						syslog(LOG_ERR, "write: %m");
61194299Sambrisko						goto abort;
61294299Sambrisko					}
61394299Sambrisko				}
61494299Sambrisko				break;
61594299Sambrisko			}
6161592Srgrimes		}
6171592Srgrimes		read_ahead(file, pf->f_convert);
6181592Srgrimes		for ( ; ; ) {
6191592Srgrimes			alarm(rexmtval);        /* read the ack */
6201592Srgrimes			n = recv(peer, ackbuf, sizeof (ackbuf), 0);
6211592Srgrimes			alarm(0);
6221592Srgrimes			if (n < 0) {
62331512Scharnier				syslog(LOG_ERR, "read: %m");
6241592Srgrimes				goto abort;
6251592Srgrimes			}
6261592Srgrimes			ap->th_opcode = ntohs((u_short)ap->th_opcode);
6271592Srgrimes			ap->th_block = ntohs((u_short)ap->th_block);
6281592Srgrimes
6291592Srgrimes			if (ap->th_opcode == ERROR)
6301592Srgrimes				goto abort;
6311592Srgrimes
6321592Srgrimes			if (ap->th_opcode == ACK) {
6331592Srgrimes				if (ap->th_block == block)
6341592Srgrimes					break;
6351592Srgrimes				/* Re-synchronize with the other side */
6361592Srgrimes				(void) synchnet(peer);
6371592Srgrimes				if (ap->th_block == (block -1))
6381592Srgrimes					goto send_data;
6391592Srgrimes			}
6401592Srgrimes
6411592Srgrimes		}
6421592Srgrimes		block++;
6431592Srgrimes	} while (size == SEGSIZE);
6441592Srgrimesabort:
6451592Srgrimes	(void) fclose(file);
6461592Srgrimes}
6471592Srgrimes
6481592Srgrimesvoid
64990333Simpjustquit(int sig __unused)
6501592Srgrimes{
6511592Srgrimes	exit(0);
6521592Srgrimes}
6531592Srgrimes
6541592Srgrimes
6551592Srgrimes/*
6561592Srgrimes * Receive a file.
6571592Srgrimes */
6581592Srgrimesvoid
65990333Simprecvfile(struct formats *pf)
6601592Srgrimes{
6611592Srgrimes	struct tftphdr *dp, *w_init();
66290333Simp	struct tftphdr *ap;    /* ack buffer */
66390333Simp	int n, size;
66471926Sasmodai	volatile unsigned short block;
6651592Srgrimes
6661592Srgrimes	signal(SIGALRM, timer);
6671592Srgrimes	dp = w_init();
6681592Srgrimes	ap = (struct tftphdr *)ackbuf;
6691592Srgrimes	block = 0;
6701592Srgrimes	do {
67184047Sobrien		timeouts = 0;
6721592Srgrimes		ap->th_opcode = htons((u_short)ACK);
6731592Srgrimes		ap->th_block = htons((u_short)block);
6741592Srgrimes		block++;
6751592Srgrimes		(void) setjmp(timeoutbuf);
6761592Srgrimessend_ack:
6771592Srgrimes		if (send(peer, ackbuf, 4, 0) != 4) {
67831512Scharnier			syslog(LOG_ERR, "write: %m");
6791592Srgrimes			goto abort;
6801592Srgrimes		}
6811592Srgrimes		write_behind(file, pf->f_convert);
6821592Srgrimes		for ( ; ; ) {
6831592Srgrimes			alarm(rexmtval);
6841592Srgrimes			n = recv(peer, dp, PKTSIZE, 0);
6851592Srgrimes			alarm(0);
6861592Srgrimes			if (n < 0) {            /* really? */
68731512Scharnier				syslog(LOG_ERR, "read: %m");
6881592Srgrimes				goto abort;
6891592Srgrimes			}
6901592Srgrimes			dp->th_opcode = ntohs((u_short)dp->th_opcode);
6911592Srgrimes			dp->th_block = ntohs((u_short)dp->th_block);
6921592Srgrimes			if (dp->th_opcode == ERROR)
6931592Srgrimes				goto abort;
6941592Srgrimes			if (dp->th_opcode == DATA) {
6951592Srgrimes				if (dp->th_block == block) {
6961592Srgrimes					break;   /* normal */
6971592Srgrimes				}
6981592Srgrimes				/* Re-synchronize with the other side */
6991592Srgrimes				(void) synchnet(peer);
7001592Srgrimes				if (dp->th_block == (block-1))
7011592Srgrimes					goto send_ack;          /* rexmit */
7021592Srgrimes			}
7031592Srgrimes		}
7041592Srgrimes		/*  size = write(file, dp->th_data, n - 4); */
7051592Srgrimes		size = writeit(file, &dp, n - 4, pf->f_convert);
7061592Srgrimes		if (size != (n-4)) {                    /* ahem */
7071592Srgrimes			if (size < 0) nak(errno + 100);
7081592Srgrimes			else nak(ENOSPACE);
7091592Srgrimes			goto abort;
7101592Srgrimes		}
7111592Srgrimes	} while (size == SEGSIZE);
7121592Srgrimes	write_behind(file, pf->f_convert);
7131592Srgrimes	(void) fclose(file);            /* close data file */
7141592Srgrimes
7151592Srgrimes	ap->th_opcode = htons((u_short)ACK);    /* send the "final" ack */
7161592Srgrimes	ap->th_block = htons((u_short)(block));
7171592Srgrimes	(void) send(peer, ackbuf, 4, 0);
7181592Srgrimes
7191592Srgrimes	signal(SIGALRM, justquit);      /* just quit on timeout */
7201592Srgrimes	alarm(rexmtval);
7211592Srgrimes	n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
7221592Srgrimes	alarm(0);
7231592Srgrimes	if (n >= 4 &&                   /* if read some data */
7241592Srgrimes	    dp->th_opcode == DATA &&    /* and got a data block */
7251592Srgrimes	    block == dp->th_block) {	/* then my last ack was lost */
7261592Srgrimes		(void) send(peer, ackbuf, 4, 0);     /* resend final ack */
7271592Srgrimes	}
7281592Srgrimesabort:
7291592Srgrimes	return;
7301592Srgrimes}
7311592Srgrimes
7321592Srgrimesstruct errmsg {
7331592Srgrimes	int	e_code;
7341592Srgrimes	char	*e_msg;
7351592Srgrimes} errmsgs[] = {
7361592Srgrimes	{ EUNDEF,	"Undefined error code" },
7371592Srgrimes	{ ENOTFOUND,	"File not found" },
7381592Srgrimes	{ EACCESS,	"Access violation" },
7391592Srgrimes	{ ENOSPACE,	"Disk full or allocation exceeded" },
7401592Srgrimes	{ EBADOP,	"Illegal TFTP operation" },
7411592Srgrimes	{ EBADID,	"Unknown transfer ID" },
7421592Srgrimes	{ EEXISTS,	"File already exists" },
7431592Srgrimes	{ ENOUSER,	"No such user" },
74484047Sobrien	{ EOPTNEG,	"Option negotiation" },
7451592Srgrimes	{ -1,		0 }
7461592Srgrimes};
7471592Srgrimes
7481592Srgrimesstatic char *
74990333Simperrtomsg(int error)
7501592Srgrimes{
7511592Srgrimes	static char buf[20];
75290333Simp	struct errmsg *pe;
7531592Srgrimes	if (error == 0)
7541592Srgrimes		return "success";
7551592Srgrimes	for (pe = errmsgs; pe->e_code >= 0; pe++)
7561592Srgrimes		if (pe->e_code == error)
7571592Srgrimes			return pe->e_msg;
75824193Simp	snprintf(buf, sizeof(buf), "error %d", error);
7591592Srgrimes	return buf;
7601592Srgrimes}
7611592Srgrimes
7621592Srgrimes/*
7631592Srgrimes * Send a nak packet (error message).
7641592Srgrimes * Error code passed in is one of the
7651592Srgrimes * standard TFTP codes, or a UNIX errno
7661592Srgrimes * offset by 100.
7671592Srgrimes */
7681592Srgrimesstatic void
76990333Simpnak(int error)
7701592Srgrimes{
77190333Simp	struct tftphdr *tp;
7721592Srgrimes	int length;
77390333Simp	struct errmsg *pe;
7741592Srgrimes
7751592Srgrimes	tp = (struct tftphdr *)buf;
7761592Srgrimes	tp->th_opcode = htons((u_short)ERROR);
7771592Srgrimes	tp->th_code = htons((u_short)error);
7781592Srgrimes	for (pe = errmsgs; pe->e_code >= 0; pe++)
7791592Srgrimes		if (pe->e_code == error)
7801592Srgrimes			break;
7811592Srgrimes	if (pe->e_code < 0) {
7821592Srgrimes		pe->e_msg = strerror(error - 100);
7831592Srgrimes		tp->th_code = EUNDEF;   /* set 'undef' errorcode */
7841592Srgrimes	}
7851592Srgrimes	strcpy(tp->th_msg, pe->e_msg);
7861592Srgrimes	length = strlen(pe->e_msg);
7871592Srgrimes	tp->th_msg[length] = '\0';
7881592Srgrimes	length += 5;
7891592Srgrimes	if (send(peer, buf, length, 0) != length)
79031512Scharnier		syslog(LOG_ERR, "nak: %m");
7911592Srgrimes}
79284047Sobrien
79394443Sume/* translate IPv4 mapped IPv6 address to IPv4 address */
79494443Sumestatic void
79594443Sumeunmappedaddr(struct sockaddr_in6 *sin6)
79694443Sume{
79794443Sume    struct sockaddr_in *sin4;
79894443Sume    u_int32_t addr;
79994443Sume    int port;
80094443Sume
80194443Sume    if (sin6->sin6_family != AF_INET6 ||
80294443Sume	!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
80394443Sume	return;
80494443Sume    sin4 = (struct sockaddr_in *)sin6;
80594443Sume    addr = *(u_int32_t *)&sin6->sin6_addr.s6_addr[12];
80694443Sume    port = sin6->sin6_port;
80794443Sume    memset(sin4, 0, sizeof(struct sockaddr_in));
80894443Sume    sin4->sin_addr.s_addr = addr;
80994443Sume    sin4->sin_port = port;
81094443Sume    sin4->sin_family = AF_INET;
81194443Sume    sin4->sin_len = sizeof(struct sockaddr_in);
81294443Sume}
81394443Sume
81484047Sobrien/*
81584047Sobrien * Send an oack packet (option acknowledgement).
81684047Sobrien */
81784047Sobrienstatic void
81890333Simpoack(void)
81984047Sobrien{
82084047Sobrien	struct tftphdr *tp, *ap;
82184047Sobrien	int size, i, n;
82284047Sobrien	char *bp;
82384047Sobrien
82484047Sobrien	tp = (struct tftphdr *)buf;
82584047Sobrien	bp = buf + 2;
82684047Sobrien	size = sizeof(buf) - 2;
82784047Sobrien	tp->th_opcode = htons((u_short)OACK);
82884047Sobrien	for (i = 0; options[i].o_type != NULL; i++) {
82984047Sobrien		if (options[i].o_request) {
83084047Sobrien			n = snprintf(bp, size, "%s%c%d", options[i].o_type,
83184047Sobrien				     0, options[i].o_reply);
83284047Sobrien			bp += n+1;
83384047Sobrien			size -= n+1;
83484047Sobrien			if (size < 0) {
83584047Sobrien				syslog(LOG_ERR, "oack: buffer overflow");
83684047Sobrien				exit(1);
83784047Sobrien			}
83884047Sobrien		}
83984047Sobrien	}
84084047Sobrien	size = bp - buf;
84184047Sobrien	ap = (struct tftphdr *)ackbuf;
84284047Sobrien	signal(SIGALRM, timer);
84384047Sobrien	timeouts = 0;
84484047Sobrien
84584047Sobrien	(void)setjmp(timeoutbuf);
84684047Sobrien	if (send(peer, buf, size, 0) != size) {
84784047Sobrien		syslog(LOG_INFO, "oack: %m");
84884047Sobrien		exit(1);
84984047Sobrien	}
85084047Sobrien
85184047Sobrien	for (;;) {
85284047Sobrien		alarm(rexmtval);
85384047Sobrien		n = recv(peer, ackbuf, sizeof (ackbuf), 0);
85484047Sobrien		alarm(0);
85584047Sobrien		if (n < 0) {
85684047Sobrien			syslog(LOG_ERR, "recv: %m");
85784047Sobrien			exit(1);
85884047Sobrien		}
85984047Sobrien		ap->th_opcode = ntohs((u_short)ap->th_opcode);
86084047Sobrien		ap->th_block = ntohs((u_short)ap->th_block);
86184047Sobrien		if (ap->th_opcode == ERROR)
86284047Sobrien			exit(1);
86384047Sobrien		if (ap->th_opcode == ACK && ap->th_block == 0)
86484047Sobrien			break;
86584047Sobrien	}
86684047Sobrien}
867