tftpd.c revision 112452
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 112452 2003-03-20 22:42:22Z dwmalone $";
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 {
106112452Sdwmalone	const char	*name;
1071592Srgrimes	int	len;
1081592Srgrimes} dirs[MAXDIRS+1];
1091592Srgrimesstatic int	suppress_naks;
1101592Srgrimesstatic int	logging;
11171616Sbillfstatic int	ipchroot;
1121592Srgrimes
113112452Sdwmalonestatic const char *errtomsg(int);
11490333Simpstatic void  nak(int);
115112452Sdwmalonestatic void  oack(void);
1161592Srgrimes
117112452Sdwmalonestatic void  timer(int);
118112452Sdwmalonestatic void  justquit(int);
119112452Sdwmalone
1201592Srgrimesint
12190333Simpmain(int argc, char *argv[])
1221592Srgrimes{
12390333Simp	struct tftphdr *tp;
12490333Simp	int n;
1251592Srgrimes	int ch, on;
12694443Sume	struct sockaddr_storage me;
12794443Sume	int len;
12818458Simp	char *chroot_dir = NULL;
12918458Simp	struct passwd *nobody;
130112452Sdwmalone	const char *chuser = "nobody";
1311592Srgrimes
13235152Sphk	openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
13371616Sbillf	while ((ch = getopt(argc, argv, "cClns:u:")) != -1) {
1341592Srgrimes		switch (ch) {
13571616Sbillf		case 'c':
13671616Sbillf			ipchroot = 1;
13771616Sbillf			break;
13871616Sbillf		case 'C':
13971616Sbillf			ipchroot = 2;
14071616Sbillf			break;
1411592Srgrimes		case 'l':
1421592Srgrimes			logging = 1;
1431592Srgrimes			break;
1441592Srgrimes		case 'n':
1451592Srgrimes			suppress_naks = 1;
1461592Srgrimes			break;
14718458Simp		case 's':
14818458Simp			chroot_dir = optarg;
14918458Simp			break;
15065850Swollman		case 'u':
15165850Swollman			chuser = optarg;
15265850Swollman			break;
1531592Srgrimes		default:
1541592Srgrimes			syslog(LOG_WARNING, "ignoring unknown option -%c", ch);
1551592Srgrimes		}
1561592Srgrimes	}
1571592Srgrimes	if (optind < argc) {
1581592Srgrimes		struct dirlist *dirp;
1591592Srgrimes
1601592Srgrimes		/* Get list of directory prefixes. Skip relative pathnames. */
1611592Srgrimes		for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
1621592Srgrimes		     optind++) {
1631592Srgrimes			if (argv[optind][0] == '/') {
1641592Srgrimes				dirp->name = argv[optind];
1651592Srgrimes				dirp->len  = strlen(dirp->name);
1661592Srgrimes				dirp++;
1671592Srgrimes			}
1681592Srgrimes		}
1691592Srgrimes	}
17018458Simp	else if (chroot_dir) {
17118458Simp		dirs->name = "/";
17218458Simp		dirs->len = 1;
17318458Simp	}
17471616Sbillf	if (ipchroot && chroot_dir == NULL) {
17571616Sbillf		syslog(LOG_ERR, "-c requires -s");
17671616Sbillf		exit(1);
17771616Sbillf	}
1781592Srgrimes
1791592Srgrimes	on = 1;
1801592Srgrimes	if (ioctl(0, FIONBIO, &on) < 0) {
18131512Scharnier		syslog(LOG_ERR, "ioctl(FIONBIO): %m");
1821592Srgrimes		exit(1);
1831592Srgrimes	}
1841592Srgrimes	fromlen = sizeof (from);
1851592Srgrimes	n = recvfrom(0, buf, sizeof (buf), 0,
1861592Srgrimes	    (struct sockaddr *)&from, &fromlen);
1871592Srgrimes	if (n < 0) {
18831512Scharnier		syslog(LOG_ERR, "recvfrom: %m");
1891592Srgrimes		exit(1);
1901592Srgrimes	}
1911592Srgrimes	/*
1921592Srgrimes	 * Now that we have read the message out of the UDP
1931592Srgrimes	 * socket, we fork and exit.  Thus, inetd will go back
1941592Srgrimes	 * to listening to the tftp port, and the next request
1951592Srgrimes	 * to come in will start up a new instance of tftpd.
1961592Srgrimes	 *
1971592Srgrimes	 * We do this so that inetd can run tftpd in "wait" mode.
1981592Srgrimes	 * The problem with tftpd running in "nowait" mode is that
1991592Srgrimes	 * inetd may get one or more successful "selects" on the
2001592Srgrimes	 * tftp port before we do our receive, so more than one
2011592Srgrimes	 * instance of tftpd may be started up.  Worse, if tftpd
2021592Srgrimes	 * break before doing the above "recvfrom", inetd would
2031592Srgrimes	 * spawn endless instances, clogging the system.
2041592Srgrimes	 */
2051592Srgrimes	{
2061592Srgrimes		int pid;
2071592Srgrimes		int i, j;
2081592Srgrimes
2091592Srgrimes		for (i = 1; i < 20; i++) {
2101592Srgrimes		    pid = fork();
2111592Srgrimes		    if (pid < 0) {
2121592Srgrimes				sleep(i);
2131592Srgrimes				/*
2141592Srgrimes				 * flush out to most recently sent request.
2151592Srgrimes				 *
2161592Srgrimes				 * This may drop some request, but those
2171592Srgrimes				 * will be resent by the clients when
2181592Srgrimes				 * they timeout.  The positive effect of
2191592Srgrimes				 * this flush is to (try to) prevent more
2201592Srgrimes				 * than one tftpd being started up to service
2211592Srgrimes				 * a single request from a single client.
2221592Srgrimes				 */
2231592Srgrimes				j = sizeof from;
2241592Srgrimes				i = recvfrom(0, buf, sizeof (buf), 0,
2251592Srgrimes				    (struct sockaddr *)&from, &j);
2261592Srgrimes				if (i > 0) {
2271592Srgrimes					n = i;
2281592Srgrimes					fromlen = j;
2291592Srgrimes				}
2301592Srgrimes		    } else {
2311592Srgrimes				break;
2321592Srgrimes		    }
2331592Srgrimes		}
2341592Srgrimes		if (pid < 0) {
23531512Scharnier			syslog(LOG_ERR, "fork: %m");
2361592Srgrimes			exit(1);
2371592Srgrimes		} else if (pid != 0) {
2381592Srgrimes			exit(0);
2391592Srgrimes		}
2401592Srgrimes	}
24118458Simp
24218458Simp	/*
24318458Simp	 * Since we exit here, we should do that only after the above
24418458Simp	 * recvfrom to keep inetd from constantly forking should there
24518458Simp	 * be a problem.  See the above comment about system clogging.
24618458Simp	 */
24718458Simp	if (chroot_dir) {
24871616Sbillf		if (ipchroot) {
24971616Sbillf			char *tempchroot;
25071616Sbillf			struct stat sb;
25171616Sbillf			int statret;
25294443Sume			struct sockaddr_storage ss;
25394443Sume			char hbuf[NI_MAXHOST];
25471616Sbillf
25594443Sume			memcpy(&ss, &from, from.ss_len);
25694443Sume			unmappedaddr((struct sockaddr_in6 *)&ss);
25794443Sume			getnameinfo((struct sockaddr *)&ss, ss.ss_len,
25894443Sume				    hbuf, sizeof(hbuf), NULL, 0,
25994443Sume				    NI_NUMERICHOST | NI_WITHSCOPEID);
26094443Sume			asprintf(&tempchroot, "%s/%s", chroot_dir, hbuf);
26171616Sbillf			statret = stat(tempchroot, &sb);
26271616Sbillf			if ((sb.st_mode & S_IFDIR) &&
26371616Sbillf			    (statret == 0 || (statret == -1 && ipchroot == 1)))
26471616Sbillf				chroot_dir = tempchroot;
26571616Sbillf		}
26618458Simp		/* Must get this before chroot because /etc might go away */
26765850Swollman		if ((nobody = getpwnam(chuser)) == NULL) {
26865850Swollman			syslog(LOG_ERR, "%s: no such user", chuser);
26918458Simp			exit(1);
27018458Simp		}
27118458Simp		if (chroot(chroot_dir)) {
27218458Simp			syslog(LOG_ERR, "chroot: %s: %m", chroot_dir);
27318458Simp			exit(1);
27418458Simp		}
27518458Simp		chdir( "/" );
27618458Simp		setuid(nobody->pw_uid);
27785299Sobrien		setgroups(1, &nobody->pw_gid);
27818458Simp	}
27918458Simp
28094443Sume	len = sizeof(me);
28194443Sume	if (getsockname(0, (struct sockaddr *)&me, &len) == 0) {
28294443Sume		switch (me.ss_family) {
28394443Sume		case AF_INET:
28494443Sume			((struct sockaddr_in *)&me)->sin_port = 0;
28594443Sume			break;
28694443Sume		case AF_INET6:
28794443Sume			((struct sockaddr_in6 *)&me)->sin6_port = 0;
28894443Sume			break;
28994443Sume		default:
29094443Sume			/* unsupported */
29194443Sume			break;
29294443Sume		}
29394443Sume	} else {
29494443Sume		memset(&me, 0, sizeof(me));
29594443Sume		me.ss_family = from.ss_family;
29694443Sume		me.ss_len = from.ss_len;
29794443Sume	}
2981592Srgrimes	alarm(0);
2991592Srgrimes	close(0);
3001592Srgrimes	close(1);
30194443Sume	peer = socket(from.ss_family, SOCK_DGRAM, 0);
3021592Srgrimes	if (peer < 0) {
30331512Scharnier		syslog(LOG_ERR, "socket: %m");
3041592Srgrimes		exit(1);
3051592Srgrimes	}
30694443Sume	if (bind(peer, (struct sockaddr *)&me, me.ss_len) < 0) {
30731512Scharnier		syslog(LOG_ERR, "bind: %m");
3081592Srgrimes		exit(1);
3091592Srgrimes	}
31094443Sume	if (connect(peer, (struct sockaddr *)&from, from.ss_len) < 0) {
31131512Scharnier		syslog(LOG_ERR, "connect: %m");
3121592Srgrimes		exit(1);
3131592Srgrimes	}
3141592Srgrimes	tp = (struct tftphdr *)buf;
3151592Srgrimes	tp->th_opcode = ntohs(tp->th_opcode);
3161592Srgrimes	if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
3171592Srgrimes		tftp(tp, n);
3181592Srgrimes	exit(1);
3191592Srgrimes}
3201592Srgrimes
3211592Srgrimesstruct formats;
32290333Simpint	validate_access(char **, int);
32390333Simpvoid	xmitfile(struct formats *);
32490333Simpvoid	recvfile(struct formats *);
3251592Srgrimes
3261592Srgrimesstruct formats {
327112452Sdwmalone	const char	*f_mode;
32890333Simp	int	(*f_validate)(char **, int);
32990333Simp	void	(*f_send)(struct formats *);
33090333Simp	void	(*f_recv)(struct formats *);
3311592Srgrimes	int	f_convert;
3321592Srgrimes} formats[] = {
33340765Sdg	{ "netascii",	validate_access,	xmitfile,	recvfile, 1 },
33440765Sdg	{ "octet",	validate_access,	xmitfile,	recvfile, 0 },
3351592Srgrimes#ifdef notdef
3361592Srgrimes	{ "mail",	validate_user,		sendmail,	recvmail, 1 },
3371592Srgrimes#endif
338112452Sdwmalone	{ 0,		NULL,			NULL,		NULL,	  0 }
3391592Srgrimes};
3401592Srgrimes
34184047Sobrienstruct options {
342112452Sdwmalone	const char	*o_type;
34384047Sobrien	char	*o_request;
34484047Sobrien	int	o_reply;	/* turn into union if need be */
34584047Sobrien} options[] = {
346112452Sdwmalone	{ "tsize",	NULL, 0 },		/* OPT_TSIZE */
347112452Sdwmalone	{ "timeout",	NULL, 0 },		/* OPT_TIMEOUT */
348112452Sdwmalone	{ NULL,		NULL, 0 }
34984047Sobrien};
35084047Sobrien
35184047Sobrienenum opt_enum {
35284047Sobrien	OPT_TSIZE = 0,
35384047Sobrien	OPT_TIMEOUT,
35484047Sobrien};
35584047Sobrien
3561592Srgrimes/*
3571592Srgrimes * Handle initial connection protocol.
3581592Srgrimes */
3591592Srgrimesvoid
36090333Simptftp(struct tftphdr *tp, int size)
3611592Srgrimes{
36290333Simp	char *cp;
36384047Sobrien	int i, first = 1, has_options = 0, ecode;
36490333Simp	struct formats *pf;
36584047Sobrien	char *filename, *mode, *option, *ccp;
3661592Srgrimes
3671592Srgrimes	filename = cp = tp->th_stuff;
3681592Srgrimesagain:
3691592Srgrimes	while (cp < buf + size) {
3701592Srgrimes		if (*cp == '\0')
3711592Srgrimes			break;
3721592Srgrimes		cp++;
3731592Srgrimes	}
3741592Srgrimes	if (*cp != '\0') {
3751592Srgrimes		nak(EBADOP);
3761592Srgrimes		exit(1);
3771592Srgrimes	}
3781592Srgrimes	if (first) {
3791592Srgrimes		mode = ++cp;
3801592Srgrimes		first = 0;
3811592Srgrimes		goto again;
3821592Srgrimes	}
3831592Srgrimes	for (cp = mode; *cp; cp++)
3841592Srgrimes		if (isupper(*cp))
3851592Srgrimes			*cp = tolower(*cp);
3861592Srgrimes	for (pf = formats; pf->f_mode; pf++)
3871592Srgrimes		if (strcmp(pf->f_mode, mode) == 0)
3881592Srgrimes			break;
3891592Srgrimes	if (pf->f_mode == 0) {
3901592Srgrimes		nak(EBADOP);
3911592Srgrimes		exit(1);
3921592Srgrimes	}
39384047Sobrien	while (++cp < buf + size) {
39484047Sobrien		for (i = 2, ccp = cp; i > 0; ccp++) {
39584047Sobrien			if (ccp >= buf + size) {
39686765Sbenno				/*
39786765Sbenno				 * Don't reject the request, just stop trying
39886765Sbenno				 * to parse the option and get on with it.
39986765Sbenno				 * Some Apple OpenFirmware versions have
40086765Sbenno				 * trailing garbage on the end of otherwise
40186765Sbenno				 * valid requests.
40286765Sbenno				 */
40386765Sbenno				goto option_fail;
40484047Sobrien			} else if (*ccp == '\0')
40584047Sobrien				i--;
40684047Sobrien		}
40784047Sobrien		for (option = cp; *cp; cp++)
40884047Sobrien			if (isupper(*cp))
40984047Sobrien				*cp = tolower(*cp);
41084047Sobrien		for (i = 0; options[i].o_type != NULL; i++)
41184047Sobrien			if (strcmp(option, options[i].o_type) == 0) {
41284047Sobrien				options[i].o_request = ++cp;
41384047Sobrien				has_options = 1;
41484047Sobrien			}
41584047Sobrien		cp = ccp-1;
41684047Sobrien	}
41784047Sobrien
41886765Sbennooption_fail:
41984047Sobrien	if (options[OPT_TIMEOUT].o_request) {
42084047Sobrien		int to = atoi(options[OPT_TIMEOUT].o_request);
42184047Sobrien		if (to < 1 || to > 255) {
42284047Sobrien			nak(EBADOP);
42384047Sobrien			exit(1);
42484047Sobrien		}
42584047Sobrien		else if (to <= max_rexmtval)
42684047Sobrien			options[OPT_TIMEOUT].o_reply = rexmtval = to;
42784047Sobrien		else
42884047Sobrien			options[OPT_TIMEOUT].o_request = NULL;
42984047Sobrien	}
43084047Sobrien
4311592Srgrimes	ecode = (*pf->f_validate)(&filename, tp->th_opcode);
43284047Sobrien	if (has_options)
43384047Sobrien		oack();
4341592Srgrimes	if (logging) {
43594443Sume		char hbuf[NI_MAXHOST];
43645393Sbrian
43794443Sume		getnameinfo((struct sockaddr *)&from, from.ss_len,
43894443Sume			    hbuf, sizeof(hbuf), NULL, 0,
43994443Sume			    NI_WITHSCOPEID);
44094443Sume		syslog(LOG_INFO, "%s: %s request for %s: %s", hbuf,
4411592Srgrimes			tp->th_opcode == WRQ ? "write" : "read",
4421592Srgrimes			filename, errtomsg(ecode));
4431592Srgrimes	}
4441592Srgrimes	if (ecode) {
4451592Srgrimes		/*
4461592Srgrimes		 * Avoid storms of naks to a RRQ broadcast for a relative
4471592Srgrimes		 * bootfile pathname from a diskless Sun.
4481592Srgrimes		 */
4491592Srgrimes		if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
4501592Srgrimes			exit(0);
4511592Srgrimes		nak(ecode);
4521592Srgrimes		exit(1);
4531592Srgrimes	}
4541592Srgrimes	if (tp->th_opcode == WRQ)
4551592Srgrimes		(*pf->f_recv)(pf);
4561592Srgrimes	else
4571592Srgrimes		(*pf->f_send)(pf);
4581592Srgrimes	exit(0);
4591592Srgrimes}
4601592Srgrimes
4611592Srgrimes
4621592SrgrimesFILE *file;
4631592Srgrimes
4641592Srgrimes/*
4651592Srgrimes * Validate file access.  Since we
4661592Srgrimes * have no uid or gid, for now require
4671592Srgrimes * file to exist and be publicly
4681592Srgrimes * readable/writable.
4691592Srgrimes * If we were invoked with arguments
4701592Srgrimes * from inetd then the file must also be
4711592Srgrimes * in one of the given directory prefixes.
4721592Srgrimes * Note also, full path name must be
4731592Srgrimes * given as we have no login directory.
4741592Srgrimes */
4751592Srgrimesint
47690333Simpvalidate_access(char **filep, int mode)
4771592Srgrimes{
4781592Srgrimes	struct stat stbuf;
4791592Srgrimes	int	fd;
4801592Srgrimes	struct dirlist *dirp;
4811592Srgrimes	static char pathname[MAXPATHLEN];
4821592Srgrimes	char *filename = *filep;
4831592Srgrimes
4841592Srgrimes	/*
4851592Srgrimes	 * Prevent tricksters from getting around the directory restrictions
4861592Srgrimes	 */
4871592Srgrimes	if (strstr(filename, "/../"))
4881592Srgrimes		return (EACCESS);
4891592Srgrimes
4901592Srgrimes	if (*filename == '/') {
4911592Srgrimes		/*
4921592Srgrimes		 * Allow the request if it's in one of the approved locations.
4931592Srgrimes		 * Special case: check the null prefix ("/") by looking
4941592Srgrimes		 * for length = 1 and relying on the arg. processing that
4951592Srgrimes		 * it's a /.
4961592Srgrimes		 */
4971592Srgrimes		for (dirp = dirs; dirp->name != NULL; dirp++) {
4981592Srgrimes			if (dirp->len == 1 ||
4991592Srgrimes			    (!strncmp(filename, dirp->name, dirp->len) &&
5001592Srgrimes			     filename[dirp->len] == '/'))
5011592Srgrimes				    break;
5021592Srgrimes		}
5031592Srgrimes		/* If directory list is empty, allow access to any file */
5041592Srgrimes		if (dirp->name == NULL && dirp != dirs)
5051592Srgrimes			return (EACCESS);
5061592Srgrimes		if (stat(filename, &stbuf) < 0)
5071592Srgrimes			return (errno == ENOENT ? ENOTFOUND : EACCESS);
5081592Srgrimes		if ((stbuf.st_mode & S_IFMT) != S_IFREG)
5091592Srgrimes			return (ENOTFOUND);
5101592Srgrimes		if (mode == RRQ) {
5111592Srgrimes			if ((stbuf.st_mode & S_IROTH) == 0)
5121592Srgrimes				return (EACCESS);
5131592Srgrimes		} else {
5141592Srgrimes			if ((stbuf.st_mode & S_IWOTH) == 0)
5151592Srgrimes				return (EACCESS);
5161592Srgrimes		}
5171592Srgrimes	} else {
5181592Srgrimes		int err;
5191592Srgrimes
5201592Srgrimes		/*
5211592Srgrimes		 * Relative file name: search the approved locations for it.
5226750Sjkh		 * Don't allow write requests that avoid directory
5231592Srgrimes		 * restrictions.
5241592Srgrimes		 */
5251592Srgrimes
5266750Sjkh		if (!strncmp(filename, "../", 3))
5271592Srgrimes			return (EACCESS);
5281592Srgrimes
5291592Srgrimes		/*
5301592Srgrimes		 * If the file exists in one of the directories and isn't
5311592Srgrimes		 * readable, continue looking. However, change the error code
5321592Srgrimes		 * to give an indication that the file exists.
5331592Srgrimes		 */
5341592Srgrimes		err = ENOTFOUND;
5351592Srgrimes		for (dirp = dirs; dirp->name != NULL; dirp++) {
53624193Simp			snprintf(pathname, sizeof(pathname), "%s/%s",
53724193Simp				dirp->name, filename);
5381592Srgrimes			if (stat(pathname, &stbuf) == 0 &&
5391592Srgrimes			    (stbuf.st_mode & S_IFMT) == S_IFREG) {
5401592Srgrimes				if ((stbuf.st_mode & S_IROTH) != 0) {
5411592Srgrimes					break;
5421592Srgrimes				}
5431592Srgrimes				err = EACCESS;
5441592Srgrimes			}
5451592Srgrimes		}
5461592Srgrimes		if (dirp->name == NULL)
5471592Srgrimes			return (err);
5481592Srgrimes		*filep = filename = pathname;
5491592Srgrimes	}
55084047Sobrien	if (options[OPT_TSIZE].o_request) {
55184047Sobrien		if (mode == RRQ)
55284047Sobrien			options[OPT_TSIZE].o_reply = stbuf.st_size;
55384047Sobrien		else
55484047Sobrien			/* XXX Allows writes of all sizes. */
55584047Sobrien			options[OPT_TSIZE].o_reply =
55684047Sobrien				atoi(options[OPT_TSIZE].o_request);
55784047Sobrien	}
55820052Sjoerg	fd = open(filename, mode == RRQ ? O_RDONLY : O_WRONLY|O_TRUNC);
5591592Srgrimes	if (fd < 0)
5601592Srgrimes		return (errno + 100);
5611592Srgrimes	file = fdopen(fd, (mode == RRQ)? "r":"w");
5621592Srgrimes	if (file == NULL) {
5631592Srgrimes		return errno+100;
5641592Srgrimes	}
5651592Srgrimes	return (0);
5661592Srgrimes}
5671592Srgrimes
56884047Sobrienint	timeouts;
5691592Srgrimesjmp_buf	timeoutbuf;
5701592Srgrimes
5711592Srgrimesvoid
57290333Simptimer(int sig __unused)
5731592Srgrimes{
57484047Sobrien	if (++timeouts > MAX_TIMEOUTS)
5751592Srgrimes		exit(1);
5761592Srgrimes	longjmp(timeoutbuf, 1);
5771592Srgrimes}
5781592Srgrimes
5791592Srgrimes/*
5801592Srgrimes * Send the requested file.
5811592Srgrimes */
5821592Srgrimesvoid
58390333Simpxmitfile(struct formats *pf)
5841592Srgrimes{
585112452Sdwmalone	struct tftphdr *dp;
58690333Simp	struct tftphdr *ap;    /* ack packet */
58790333Simp	int size, n;
58871926Sasmodai	volatile unsigned short block;
5891592Srgrimes
5901592Srgrimes	signal(SIGALRM, timer);
5911592Srgrimes	dp = r_init();
5921592Srgrimes	ap = (struct tftphdr *)ackbuf;
5931592Srgrimes	block = 1;
5941592Srgrimes	do {
5951592Srgrimes		size = readit(file, &dp, pf->f_convert);
5961592Srgrimes		if (size < 0) {
5971592Srgrimes			nak(errno + 100);
5981592Srgrimes			goto abort;
5991592Srgrimes		}
6001592Srgrimes		dp->th_opcode = htons((u_short)DATA);
6011592Srgrimes		dp->th_block = htons((u_short)block);
60284047Sobrien		timeouts = 0;
6031592Srgrimes		(void)setjmp(timeoutbuf);
6041592Srgrimes
6051592Srgrimessend_data:
60694299Sambrisko		{
60794299Sambrisko			int i, t = 1;
60894299Sambrisko			for (i = 0; ; i++){
60994299Sambrisko				if (send(peer, dp, size + 4, 0) != size + 4) {
61094299Sambrisko					sleep(t);
61194299Sambrisko					t = (t < 32) ? t<< 1 : t;
61294299Sambrisko					if (i >= 12) {
61394299Sambrisko						syslog(LOG_ERR, "write: %m");
61494299Sambrisko						goto abort;
61594299Sambrisko					}
61694299Sambrisko				}
61794299Sambrisko				break;
61894299Sambrisko			}
6191592Srgrimes		}
6201592Srgrimes		read_ahead(file, pf->f_convert);
6211592Srgrimes		for ( ; ; ) {
6221592Srgrimes			alarm(rexmtval);        /* read the ack */
6231592Srgrimes			n = recv(peer, ackbuf, sizeof (ackbuf), 0);
6241592Srgrimes			alarm(0);
6251592Srgrimes			if (n < 0) {
62631512Scharnier				syslog(LOG_ERR, "read: %m");
6271592Srgrimes				goto abort;
6281592Srgrimes			}
6291592Srgrimes			ap->th_opcode = ntohs((u_short)ap->th_opcode);
6301592Srgrimes			ap->th_block = ntohs((u_short)ap->th_block);
6311592Srgrimes
6321592Srgrimes			if (ap->th_opcode == ERROR)
6331592Srgrimes				goto abort;
6341592Srgrimes
6351592Srgrimes			if (ap->th_opcode == ACK) {
6361592Srgrimes				if (ap->th_block == block)
6371592Srgrimes					break;
6381592Srgrimes				/* Re-synchronize with the other side */
6391592Srgrimes				(void) synchnet(peer);
6401592Srgrimes				if (ap->th_block == (block -1))
6411592Srgrimes					goto send_data;
6421592Srgrimes			}
6431592Srgrimes
6441592Srgrimes		}
6451592Srgrimes		block++;
6461592Srgrimes	} while (size == SEGSIZE);
6471592Srgrimesabort:
6481592Srgrimes	(void) fclose(file);
6491592Srgrimes}
6501592Srgrimes
6511592Srgrimesvoid
65290333Simpjustquit(int sig __unused)
6531592Srgrimes{
6541592Srgrimes	exit(0);
6551592Srgrimes}
6561592Srgrimes
6571592Srgrimes
6581592Srgrimes/*
6591592Srgrimes * Receive a file.
6601592Srgrimes */
6611592Srgrimesvoid
66290333Simprecvfile(struct formats *pf)
6631592Srgrimes{
664112452Sdwmalone	struct tftphdr *dp;
66590333Simp	struct tftphdr *ap;    /* ack buffer */
66690333Simp	int n, size;
66771926Sasmodai	volatile unsigned short block;
6681592Srgrimes
6691592Srgrimes	signal(SIGALRM, timer);
6701592Srgrimes	dp = w_init();
6711592Srgrimes	ap = (struct tftphdr *)ackbuf;
6721592Srgrimes	block = 0;
6731592Srgrimes	do {
67484047Sobrien		timeouts = 0;
6751592Srgrimes		ap->th_opcode = htons((u_short)ACK);
6761592Srgrimes		ap->th_block = htons((u_short)block);
6771592Srgrimes		block++;
6781592Srgrimes		(void) setjmp(timeoutbuf);
6791592Srgrimessend_ack:
6801592Srgrimes		if (send(peer, ackbuf, 4, 0) != 4) {
68131512Scharnier			syslog(LOG_ERR, "write: %m");
6821592Srgrimes			goto abort;
6831592Srgrimes		}
6841592Srgrimes		write_behind(file, pf->f_convert);
6851592Srgrimes		for ( ; ; ) {
6861592Srgrimes			alarm(rexmtval);
6871592Srgrimes			n = recv(peer, dp, PKTSIZE, 0);
6881592Srgrimes			alarm(0);
6891592Srgrimes			if (n < 0) {            /* really? */
69031512Scharnier				syslog(LOG_ERR, "read: %m");
6911592Srgrimes				goto abort;
6921592Srgrimes			}
6931592Srgrimes			dp->th_opcode = ntohs((u_short)dp->th_opcode);
6941592Srgrimes			dp->th_block = ntohs((u_short)dp->th_block);
6951592Srgrimes			if (dp->th_opcode == ERROR)
6961592Srgrimes				goto abort;
6971592Srgrimes			if (dp->th_opcode == DATA) {
6981592Srgrimes				if (dp->th_block == block) {
6991592Srgrimes					break;   /* normal */
7001592Srgrimes				}
7011592Srgrimes				/* Re-synchronize with the other side */
7021592Srgrimes				(void) synchnet(peer);
7031592Srgrimes				if (dp->th_block == (block-1))
7041592Srgrimes					goto send_ack;          /* rexmit */
7051592Srgrimes			}
7061592Srgrimes		}
7071592Srgrimes		/*  size = write(file, dp->th_data, n - 4); */
7081592Srgrimes		size = writeit(file, &dp, n - 4, pf->f_convert);
7091592Srgrimes		if (size != (n-4)) {                    /* ahem */
7101592Srgrimes			if (size < 0) nak(errno + 100);
7111592Srgrimes			else nak(ENOSPACE);
7121592Srgrimes			goto abort;
7131592Srgrimes		}
7141592Srgrimes	} while (size == SEGSIZE);
7151592Srgrimes	write_behind(file, pf->f_convert);
7161592Srgrimes	(void) fclose(file);            /* close data file */
7171592Srgrimes
7181592Srgrimes	ap->th_opcode = htons((u_short)ACK);    /* send the "final" ack */
7191592Srgrimes	ap->th_block = htons((u_short)(block));
7201592Srgrimes	(void) send(peer, ackbuf, 4, 0);
7211592Srgrimes
7221592Srgrimes	signal(SIGALRM, justquit);      /* just quit on timeout */
7231592Srgrimes	alarm(rexmtval);
7241592Srgrimes	n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
7251592Srgrimes	alarm(0);
7261592Srgrimes	if (n >= 4 &&                   /* if read some data */
7271592Srgrimes	    dp->th_opcode == DATA &&    /* and got a data block */
7281592Srgrimes	    block == dp->th_block) {	/* then my last ack was lost */
7291592Srgrimes		(void) send(peer, ackbuf, 4, 0);     /* resend final ack */
7301592Srgrimes	}
7311592Srgrimesabort:
7321592Srgrimes	return;
7331592Srgrimes}
7341592Srgrimes
7351592Srgrimesstruct errmsg {
7361592Srgrimes	int	e_code;
737112452Sdwmalone	const char	*e_msg;
7381592Srgrimes} errmsgs[] = {
7391592Srgrimes	{ EUNDEF,	"Undefined error code" },
7401592Srgrimes	{ ENOTFOUND,	"File not found" },
7411592Srgrimes	{ EACCESS,	"Access violation" },
7421592Srgrimes	{ ENOSPACE,	"Disk full or allocation exceeded" },
7431592Srgrimes	{ EBADOP,	"Illegal TFTP operation" },
7441592Srgrimes	{ EBADID,	"Unknown transfer ID" },
7451592Srgrimes	{ EEXISTS,	"File already exists" },
7461592Srgrimes	{ ENOUSER,	"No such user" },
74784047Sobrien	{ EOPTNEG,	"Option negotiation" },
7481592Srgrimes	{ -1,		0 }
7491592Srgrimes};
7501592Srgrimes
751112452Sdwmalonestatic const char *
75290333Simperrtomsg(int error)
7531592Srgrimes{
754112452Sdwmalone	static char ebuf[20];
75590333Simp	struct errmsg *pe;
7561592Srgrimes	if (error == 0)
7571592Srgrimes		return "success";
7581592Srgrimes	for (pe = errmsgs; pe->e_code >= 0; pe++)
7591592Srgrimes		if (pe->e_code == error)
7601592Srgrimes			return pe->e_msg;
761112452Sdwmalone	snprintf(ebuf, sizeof(buf), "error %d", error);
762112452Sdwmalone	return ebuf;
7631592Srgrimes}
7641592Srgrimes
7651592Srgrimes/*
7661592Srgrimes * Send a nak packet (error message).
7671592Srgrimes * Error code passed in is one of the
7681592Srgrimes * standard TFTP codes, or a UNIX errno
7691592Srgrimes * offset by 100.
7701592Srgrimes */
7711592Srgrimesstatic void
77290333Simpnak(int error)
7731592Srgrimes{
77490333Simp	struct tftphdr *tp;
7751592Srgrimes	int length;
77690333Simp	struct errmsg *pe;
7771592Srgrimes
7781592Srgrimes	tp = (struct tftphdr *)buf;
7791592Srgrimes	tp->th_opcode = htons((u_short)ERROR);
7801592Srgrimes	tp->th_code = htons((u_short)error);
7811592Srgrimes	for (pe = errmsgs; pe->e_code >= 0; pe++)
7821592Srgrimes		if (pe->e_code == error)
7831592Srgrimes			break;
7841592Srgrimes	if (pe->e_code < 0) {
7851592Srgrimes		pe->e_msg = strerror(error - 100);
7861592Srgrimes		tp->th_code = EUNDEF;   /* set 'undef' errorcode */
7871592Srgrimes	}
7881592Srgrimes	strcpy(tp->th_msg, pe->e_msg);
7891592Srgrimes	length = strlen(pe->e_msg);
7901592Srgrimes	tp->th_msg[length] = '\0';
7911592Srgrimes	length += 5;
7921592Srgrimes	if (send(peer, buf, length, 0) != length)
79331512Scharnier		syslog(LOG_ERR, "nak: %m");
7941592Srgrimes}
79584047Sobrien
79694443Sume/* translate IPv4 mapped IPv6 address to IPv4 address */
79794443Sumestatic void
79894443Sumeunmappedaddr(struct sockaddr_in6 *sin6)
79994443Sume{
80095496Sume	struct sockaddr_in *sin4;
80195496Sume	u_int32_t addr;
80295496Sume	int port;
80394443Sume
80495496Sume	if (sin6->sin6_family != AF_INET6 ||
80595496Sume	    !IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
80695496Sume		return;
80795496Sume	sin4 = (struct sockaddr_in *)sin6;
80895496Sume	addr = *(u_int32_t *)&sin6->sin6_addr.s6_addr[12];
80995496Sume	port = sin6->sin6_port;
81095496Sume	memset(sin4, 0, sizeof(struct sockaddr_in));
81195496Sume	sin4->sin_addr.s_addr = addr;
81295496Sume	sin4->sin_port = port;
81395496Sume	sin4->sin_family = AF_INET;
81495496Sume	sin4->sin_len = sizeof(struct sockaddr_in);
81594443Sume}
81694443Sume
81784047Sobrien/*
81884047Sobrien * Send an oack packet (option acknowledgement).
81984047Sobrien */
82084047Sobrienstatic void
82190333Simpoack(void)
82284047Sobrien{
82384047Sobrien	struct tftphdr *tp, *ap;
82484047Sobrien	int size, i, n;
82584047Sobrien	char *bp;
82684047Sobrien
82784047Sobrien	tp = (struct tftphdr *)buf;
82884047Sobrien	bp = buf + 2;
82984047Sobrien	size = sizeof(buf) - 2;
83084047Sobrien	tp->th_opcode = htons((u_short)OACK);
83184047Sobrien	for (i = 0; options[i].o_type != NULL; i++) {
83284047Sobrien		if (options[i].o_request) {
83384047Sobrien			n = snprintf(bp, size, "%s%c%d", options[i].o_type,
83484047Sobrien				     0, options[i].o_reply);
83584047Sobrien			bp += n+1;
83684047Sobrien			size -= n+1;
83784047Sobrien			if (size < 0) {
83884047Sobrien				syslog(LOG_ERR, "oack: buffer overflow");
83984047Sobrien				exit(1);
84084047Sobrien			}
84184047Sobrien		}
84284047Sobrien	}
84384047Sobrien	size = bp - buf;
84484047Sobrien	ap = (struct tftphdr *)ackbuf;
84584047Sobrien	signal(SIGALRM, timer);
84684047Sobrien	timeouts = 0;
84784047Sobrien
84884047Sobrien	(void)setjmp(timeoutbuf);
84984047Sobrien	if (send(peer, buf, size, 0) != size) {
85084047Sobrien		syslog(LOG_INFO, "oack: %m");
85184047Sobrien		exit(1);
85284047Sobrien	}
85384047Sobrien
85484047Sobrien	for (;;) {
85584047Sobrien		alarm(rexmtval);
85684047Sobrien		n = recv(peer, ackbuf, sizeof (ackbuf), 0);
85784047Sobrien		alarm(0);
85884047Sobrien		if (n < 0) {
85984047Sobrien			syslog(LOG_ERR, "recv: %m");
86084047Sobrien			exit(1);
86184047Sobrien		}
86284047Sobrien		ap->th_opcode = ntohs((u_short)ap->th_opcode);
86384047Sobrien		ap->th_block = ntohs((u_short)ap->th_block);
86484047Sobrien		if (ap->th_opcode == ERROR)
86584047Sobrien			exit(1);
86684047Sobrien		if (ap->th_opcode == ACK && ap->th_block == 0)
86784047Sobrien			break;
86884047Sobrien	}
86984047Sobrien}
870