tftpd.c revision 146187
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 146187 2005-05-13 16:31:11Z 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>
60130839Sbrian#include <sys/time.h>
611592Srgrimes
621592Srgrimes#include <netinet/in.h>
631592Srgrimes#include <arpa/tftp.h>
641592Srgrimes#include <arpa/inet.h>
651592Srgrimes
661592Srgrimes#include <ctype.h>
671592Srgrimes#include <errno.h>
681592Srgrimes#include <fcntl.h>
6945393Sbrian#include <libutil.h>
701592Srgrimes#include <netdb.h>
7131512Scharnier#include <pwd.h>
721592Srgrimes#include <setjmp.h>
731592Srgrimes#include <signal.h>
741592Srgrimes#include <stdio.h>
751592Srgrimes#include <stdlib.h>
761592Srgrimes#include <string.h>
771592Srgrimes#include <syslog.h>
781592Srgrimes#include <unistd.h>
791592Srgrimes
801592Srgrimes#include "tftpsubs.h"
811592Srgrimes
821592Srgrimes#define	TIMEOUT		5
8384047Sobrien#define	MAX_TIMEOUTS	5
841592Srgrimes
851592Srgrimesint	peer;
861592Srgrimesint	rexmtval = TIMEOUT;
8784047Sobrienint	max_rexmtval = 2*TIMEOUT;
881592Srgrimes
891592Srgrimes#define	PKTSIZE	SEGSIZE+4
901592Srgrimeschar	buf[PKTSIZE];
911592Srgrimeschar	ackbuf[PKTSIZE];
9294443Sumestruct	sockaddr_storage from;
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;
112129680Smdoddstatic int	create_new = 0;
113129680Smdoddstatic mode_t	mask = S_IWGRP|S_IWOTH;
1141592Srgrimes
115112452Sdwmalonestatic const char *errtomsg(int);
11690333Simpstatic void  nak(int);
117112452Sdwmalonestatic void  oack(void);
1181592Srgrimes
119112452Sdwmalonestatic void  timer(int);
120112452Sdwmalonestatic void  justquit(int);
121112452Sdwmalone
1221592Srgrimesint
12390333Simpmain(int argc, char *argv[])
1241592Srgrimes{
12590333Simp	struct tftphdr *tp;
126141922Sstefanf	socklen_t fromlen, len;
12790333Simp	int n;
1281592Srgrimes	int ch, on;
12994443Sume	struct sockaddr_storage me;
13018458Simp	char *chroot_dir = NULL;
13118458Simp	struct passwd *nobody;
132112452Sdwmalone	const char *chuser = "nobody";
1331592Srgrimes
134130839Sbrian	tzset();			/* syslog in localtime */
135130839Sbrian
13635152Sphk	openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
137129680Smdodd	while ((ch = getopt(argc, argv, "cClns:u:Uw")) != -1) {
1381592Srgrimes		switch (ch) {
13971616Sbillf		case 'c':
14071616Sbillf			ipchroot = 1;
14171616Sbillf			break;
14271616Sbillf		case 'C':
14371616Sbillf			ipchroot = 2;
14471616Sbillf			break;
1451592Srgrimes		case 'l':
1461592Srgrimes			logging = 1;
1471592Srgrimes			break;
1481592Srgrimes		case 'n':
1491592Srgrimes			suppress_naks = 1;
1501592Srgrimes			break;
15118458Simp		case 's':
15218458Simp			chroot_dir = optarg;
15318458Simp			break;
15465850Swollman		case 'u':
15565850Swollman			chuser = optarg;
15665850Swollman			break;
157129680Smdodd		case 'U':
158129680Smdodd			mask = strtol(optarg, NULL, 0);
159129680Smdodd			break;
160129680Smdodd		case 'w':
161129680Smdodd			create_new = 1;
162129680Smdodd			break;
1631592Srgrimes		default:
1641592Srgrimes			syslog(LOG_WARNING, "ignoring unknown option -%c", ch);
1651592Srgrimes		}
1661592Srgrimes	}
1671592Srgrimes	if (optind < argc) {
1681592Srgrimes		struct dirlist *dirp;
1691592Srgrimes
1701592Srgrimes		/* Get list of directory prefixes. Skip relative pathnames. */
1711592Srgrimes		for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
1721592Srgrimes		     optind++) {
1731592Srgrimes			if (argv[optind][0] == '/') {
1741592Srgrimes				dirp->name = argv[optind];
1751592Srgrimes				dirp->len  = strlen(dirp->name);
1761592Srgrimes				dirp++;
1771592Srgrimes			}
1781592Srgrimes		}
1791592Srgrimes	}
18018458Simp	else if (chroot_dir) {
18118458Simp		dirs->name = "/";
18218458Simp		dirs->len = 1;
18318458Simp	}
184113714Sbillf	if (ipchroot > 0 && chroot_dir == NULL) {
18571616Sbillf		syslog(LOG_ERR, "-c requires -s");
18671616Sbillf		exit(1);
18771616Sbillf	}
1881592Srgrimes
189129680Smdodd	umask(mask);
190129680Smdodd
1911592Srgrimes	on = 1;
1921592Srgrimes	if (ioctl(0, FIONBIO, &on) < 0) {
19331512Scharnier		syslog(LOG_ERR, "ioctl(FIONBIO): %m");
1941592Srgrimes		exit(1);
1951592Srgrimes	}
1961592Srgrimes	fromlen = sizeof (from);
1971592Srgrimes	n = recvfrom(0, buf, sizeof (buf), 0,
1981592Srgrimes	    (struct sockaddr *)&from, &fromlen);
1991592Srgrimes	if (n < 0) {
20031512Scharnier		syslog(LOG_ERR, "recvfrom: %m");
2011592Srgrimes		exit(1);
2021592Srgrimes	}
2031592Srgrimes	/*
2041592Srgrimes	 * Now that we have read the message out of the UDP
2051592Srgrimes	 * socket, we fork and exit.  Thus, inetd will go back
2061592Srgrimes	 * to listening to the tftp port, and the next request
2071592Srgrimes	 * to come in will start up a new instance of tftpd.
2081592Srgrimes	 *
2091592Srgrimes	 * We do this so that inetd can run tftpd in "wait" mode.
2101592Srgrimes	 * The problem with tftpd running in "nowait" mode is that
2111592Srgrimes	 * inetd may get one or more successful "selects" on the
2121592Srgrimes	 * tftp port before we do our receive, so more than one
2131592Srgrimes	 * instance of tftpd may be started up.  Worse, if tftpd
2141592Srgrimes	 * break before doing the above "recvfrom", inetd would
2151592Srgrimes	 * spawn endless instances, clogging the system.
2161592Srgrimes	 */
2171592Srgrimes	{
218141922Sstefanf		int i, pid;
2191592Srgrimes
2201592Srgrimes		for (i = 1; i < 20; i++) {
2211592Srgrimes		    pid = fork();
2221592Srgrimes		    if (pid < 0) {
2231592Srgrimes				sleep(i);
2241592Srgrimes				/*
2251592Srgrimes				 * flush out to most recently sent request.
2261592Srgrimes				 *
2271592Srgrimes				 * This may drop some request, but those
2281592Srgrimes				 * will be resent by the clients when
2291592Srgrimes				 * they timeout.  The positive effect of
2301592Srgrimes				 * this flush is to (try to) prevent more
2311592Srgrimes				 * than one tftpd being started up to service
2321592Srgrimes				 * a single request from a single client.
2331592Srgrimes				 */
234141922Sstefanf				fromlen = sizeof from;
2351592Srgrimes				i = recvfrom(0, buf, sizeof (buf), 0,
236141922Sstefanf				    (struct sockaddr *)&from, &fromlen);
2371592Srgrimes				if (i > 0) {
2381592Srgrimes					n = i;
2391592Srgrimes				}
2401592Srgrimes		    } else {
2411592Srgrimes				break;
2421592Srgrimes		    }
2431592Srgrimes		}
2441592Srgrimes		if (pid < 0) {
24531512Scharnier			syslog(LOG_ERR, "fork: %m");
2461592Srgrimes			exit(1);
2471592Srgrimes		} else if (pid != 0) {
2481592Srgrimes			exit(0);
2491592Srgrimes		}
2501592Srgrimes	}
25118458Simp
25218458Simp	/*
25318458Simp	 * Since we exit here, we should do that only after the above
25418458Simp	 * recvfrom to keep inetd from constantly forking should there
25518458Simp	 * be a problem.  See the above comment about system clogging.
25618458Simp	 */
25718458Simp	if (chroot_dir) {
258113714Sbillf		if (ipchroot > 0) {
25971616Sbillf			char *tempchroot;
26071616Sbillf			struct stat sb;
26171616Sbillf			int statret;
26294443Sume			struct sockaddr_storage ss;
26394443Sume			char hbuf[NI_MAXHOST];
26471616Sbillf
26594443Sume			memcpy(&ss, &from, from.ss_len);
26694443Sume			unmappedaddr((struct sockaddr_in6 *)&ss);
26794443Sume			getnameinfo((struct sockaddr *)&ss, ss.ss_len,
26894443Sume				    hbuf, sizeof(hbuf), NULL, 0,
269146187Sume				    NI_NUMERICHOST);
27094443Sume			asprintf(&tempchroot, "%s/%s", chroot_dir, hbuf);
271113714Sbillf			if (ipchroot == 2)
272113714Sbillf				statret = stat(tempchroot, &sb);
273113714Sbillf			if (ipchroot == 1 ||
274113714Sbillf			    (statret == 0 && (sb.st_mode & S_IFDIR)))
27571616Sbillf				chroot_dir = tempchroot;
27671616Sbillf		}
27718458Simp		/* Must get this before chroot because /etc might go away */
27865850Swollman		if ((nobody = getpwnam(chuser)) == NULL) {
27965850Swollman			syslog(LOG_ERR, "%s: no such user", chuser);
28018458Simp			exit(1);
28118458Simp		}
28218458Simp		if (chroot(chroot_dir)) {
28318458Simp			syslog(LOG_ERR, "chroot: %s: %m", chroot_dir);
28418458Simp			exit(1);
28518458Simp		}
286131358Scsjp		chdir("/");
287131358Scsjp		setgroups(1, &nobody->pw_gid);
28818458Simp		setuid(nobody->pw_uid);
28918458Simp	}
29018458Simp
29194443Sume	len = sizeof(me);
29294443Sume	if (getsockname(0, (struct sockaddr *)&me, &len) == 0) {
29394443Sume		switch (me.ss_family) {
29494443Sume		case AF_INET:
29594443Sume			((struct sockaddr_in *)&me)->sin_port = 0;
29694443Sume			break;
29794443Sume		case AF_INET6:
29894443Sume			((struct sockaddr_in6 *)&me)->sin6_port = 0;
29994443Sume			break;
30094443Sume		default:
30194443Sume			/* unsupported */
30294443Sume			break;
30394443Sume		}
30494443Sume	} else {
30594443Sume		memset(&me, 0, sizeof(me));
30694443Sume		me.ss_family = from.ss_family;
30794443Sume		me.ss_len = from.ss_len;
30894443Sume	}
3091592Srgrimes	alarm(0);
3101592Srgrimes	close(0);
3111592Srgrimes	close(1);
31294443Sume	peer = socket(from.ss_family, SOCK_DGRAM, 0);
3131592Srgrimes	if (peer < 0) {
31431512Scharnier		syslog(LOG_ERR, "socket: %m");
3151592Srgrimes		exit(1);
3161592Srgrimes	}
31794443Sume	if (bind(peer, (struct sockaddr *)&me, me.ss_len) < 0) {
31831512Scharnier		syslog(LOG_ERR, "bind: %m");
3191592Srgrimes		exit(1);
3201592Srgrimes	}
32194443Sume	if (connect(peer, (struct sockaddr *)&from, from.ss_len) < 0) {
32231512Scharnier		syslog(LOG_ERR, "connect: %m");
3231592Srgrimes		exit(1);
3241592Srgrimes	}
3251592Srgrimes	tp = (struct tftphdr *)buf;
3261592Srgrimes	tp->th_opcode = ntohs(tp->th_opcode);
3271592Srgrimes	if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
3281592Srgrimes		tftp(tp, n);
3291592Srgrimes	exit(1);
3301592Srgrimes}
3311592Srgrimes
332130834Sbrianstatic void
333130834Sbrianreduce_path(char *fn)
334130834Sbrian{
335130834Sbrian	char *slash, *ptr;
336130834Sbrian
337130834Sbrian	/* Reduce all "/+./" to "/" (just in case we've got "/./../" later */
338130834Sbrian	while ((slash = strstr(fn, "/./")) != NULL) {
339130834Sbrian		for (ptr = slash; ptr > fn && ptr[-1] == '/'; ptr--)
340130834Sbrian			;
341130834Sbrian		slash += 2;
342130834Sbrian		while (*slash)
343130834Sbrian			*++ptr = *++slash;
344130834Sbrian	}
345130834Sbrian
346130834Sbrian	/* Now reduce all "/something/+../" to "/" */
347130834Sbrian	while ((slash = strstr(fn, "/../")) != NULL) {
348130834Sbrian		if (slash == fn)
349130834Sbrian			break;
350130834Sbrian		for (ptr = slash; ptr > fn && ptr[-1] == '/'; ptr--)
351130834Sbrian			;
352130834Sbrian		for (ptr--; ptr >= fn; ptr--)
353130834Sbrian			if (*ptr == '/')
354130834Sbrian				break;
355130834Sbrian		if (ptr < fn)
356130834Sbrian			break;
357130834Sbrian		slash += 3;
358130834Sbrian		while (*slash)
359130834Sbrian			*++ptr = *++slash;
360130834Sbrian	}
361130834Sbrian}
362130834Sbrian
3631592Srgrimesstruct formats;
36490333Simpint	validate_access(char **, int);
36590333Simpvoid	xmitfile(struct formats *);
36690333Simpvoid	recvfile(struct formats *);
3671592Srgrimes
3681592Srgrimesstruct formats {
369112452Sdwmalone	const char	*f_mode;
37090333Simp	int	(*f_validate)(char **, int);
37190333Simp	void	(*f_send)(struct formats *);
37290333Simp	void	(*f_recv)(struct formats *);
3731592Srgrimes	int	f_convert;
3741592Srgrimes} formats[] = {
37540765Sdg	{ "netascii",	validate_access,	xmitfile,	recvfile, 1 },
37640765Sdg	{ "octet",	validate_access,	xmitfile,	recvfile, 0 },
3771592Srgrimes#ifdef notdef
3781592Srgrimes	{ "mail",	validate_user,		sendmail,	recvmail, 1 },
3791592Srgrimes#endif
380112452Sdwmalone	{ 0,		NULL,			NULL,		NULL,	  0 }
3811592Srgrimes};
3821592Srgrimes
38384047Sobrienstruct options {
384112452Sdwmalone	const char	*o_type;
38584047Sobrien	char	*o_request;
38684047Sobrien	int	o_reply;	/* turn into union if need be */
38784047Sobrien} options[] = {
388112452Sdwmalone	{ "tsize",	NULL, 0 },		/* OPT_TSIZE */
389112452Sdwmalone	{ "timeout",	NULL, 0 },		/* OPT_TIMEOUT */
390112452Sdwmalone	{ NULL,		NULL, 0 }
39184047Sobrien};
39284047Sobrien
39384047Sobrienenum opt_enum {
39484047Sobrien	OPT_TSIZE = 0,
39584047Sobrien	OPT_TIMEOUT,
39684047Sobrien};
39784047Sobrien
3981592Srgrimes/*
3991592Srgrimes * Handle initial connection protocol.
4001592Srgrimes */
4011592Srgrimesvoid
40290333Simptftp(struct tftphdr *tp, int size)
4031592Srgrimes{
40490333Simp	char *cp;
40584047Sobrien	int i, first = 1, has_options = 0, ecode;
40690333Simp	struct formats *pf;
40784047Sobrien	char *filename, *mode, *option, *ccp;
408141922Sstefanf	char fnbuf[PATH_MAX];
4091592Srgrimes
410122916Ssobomax	cp = tp->th_stuff;
4111592Srgrimesagain:
4121592Srgrimes	while (cp < buf + size) {
4131592Srgrimes		if (*cp == '\0')
4141592Srgrimes			break;
4151592Srgrimes		cp++;
4161592Srgrimes	}
4171592Srgrimes	if (*cp != '\0') {
4181592Srgrimes		nak(EBADOP);
4191592Srgrimes		exit(1);
4201592Srgrimes	}
421122916Ssobomax	i = cp - tp->th_stuff;
422122916Ssobomax	if (i >= sizeof(fnbuf)) {
423122916Ssobomax		nak(EBADOP);
424122916Ssobomax		exit(1);
425122916Ssobomax	}
426122916Ssobomax	memcpy(fnbuf, tp->th_stuff, i);
427122916Ssobomax	fnbuf[i] = '\0';
428130834Sbrian	reduce_path(fnbuf);
429122916Ssobomax	filename = fnbuf;
4301592Srgrimes	if (first) {
4311592Srgrimes		mode = ++cp;
4321592Srgrimes		first = 0;
4331592Srgrimes		goto again;
4341592Srgrimes	}
4351592Srgrimes	for (cp = mode; *cp; cp++)
4361592Srgrimes		if (isupper(*cp))
4371592Srgrimes			*cp = tolower(*cp);
4381592Srgrimes	for (pf = formats; pf->f_mode; pf++)
4391592Srgrimes		if (strcmp(pf->f_mode, mode) == 0)
4401592Srgrimes			break;
4411592Srgrimes	if (pf->f_mode == 0) {
4421592Srgrimes		nak(EBADOP);
4431592Srgrimes		exit(1);
4441592Srgrimes	}
44584047Sobrien	while (++cp < buf + size) {
44684047Sobrien		for (i = 2, ccp = cp; i > 0; ccp++) {
44784047Sobrien			if (ccp >= buf + size) {
44886765Sbenno				/*
44986765Sbenno				 * Don't reject the request, just stop trying
45086765Sbenno				 * to parse the option and get on with it.
451133862Smarius				 * Some Apple Open Firmware versions have
45286765Sbenno				 * trailing garbage on the end of otherwise
45386765Sbenno				 * valid requests.
45486765Sbenno				 */
45586765Sbenno				goto option_fail;
45684047Sobrien			} else if (*ccp == '\0')
45784047Sobrien				i--;
45884047Sobrien		}
45984047Sobrien		for (option = cp; *cp; cp++)
46084047Sobrien			if (isupper(*cp))
46184047Sobrien				*cp = tolower(*cp);
46284047Sobrien		for (i = 0; options[i].o_type != NULL; i++)
46384047Sobrien			if (strcmp(option, options[i].o_type) == 0) {
46484047Sobrien				options[i].o_request = ++cp;
46584047Sobrien				has_options = 1;
46684047Sobrien			}
46784047Sobrien		cp = ccp-1;
46884047Sobrien	}
46984047Sobrien
47086765Sbennooption_fail:
47184047Sobrien	if (options[OPT_TIMEOUT].o_request) {
47284047Sobrien		int to = atoi(options[OPT_TIMEOUT].o_request);
47384047Sobrien		if (to < 1 || to > 255) {
47484047Sobrien			nak(EBADOP);
47584047Sobrien			exit(1);
47684047Sobrien		}
47784047Sobrien		else if (to <= max_rexmtval)
47884047Sobrien			options[OPT_TIMEOUT].o_reply = rexmtval = to;
47984047Sobrien		else
48084047Sobrien			options[OPT_TIMEOUT].o_request = NULL;
48184047Sobrien	}
48284047Sobrien
4831592Srgrimes	ecode = (*pf->f_validate)(&filename, tp->th_opcode);
484130834Sbrian	if (has_options && ecode == 0)
48584047Sobrien		oack();
4861592Srgrimes	if (logging) {
48794443Sume		char hbuf[NI_MAXHOST];
48845393Sbrian
48994443Sume		getnameinfo((struct sockaddr *)&from, from.ss_len,
490146187Sume			    hbuf, sizeof(hbuf), NULL, 0, 0);
49194443Sume		syslog(LOG_INFO, "%s: %s request for %s: %s", hbuf,
4921592Srgrimes			tp->th_opcode == WRQ ? "write" : "read",
4931592Srgrimes			filename, errtomsg(ecode));
4941592Srgrimes	}
4951592Srgrimes	if (ecode) {
4961592Srgrimes		/*
4971592Srgrimes		 * Avoid storms of naks to a RRQ broadcast for a relative
4981592Srgrimes		 * bootfile pathname from a diskless Sun.
4991592Srgrimes		 */
5001592Srgrimes		if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
5011592Srgrimes			exit(0);
5021592Srgrimes		nak(ecode);
5031592Srgrimes		exit(1);
5041592Srgrimes	}
5051592Srgrimes	if (tp->th_opcode == WRQ)
5061592Srgrimes		(*pf->f_recv)(pf);
5071592Srgrimes	else
5081592Srgrimes		(*pf->f_send)(pf);
5091592Srgrimes	exit(0);
5101592Srgrimes}
5111592Srgrimes
5121592Srgrimes
5131592SrgrimesFILE *file;
5141592Srgrimes
5151592Srgrimes/*
5161592Srgrimes * Validate file access.  Since we
5171592Srgrimes * have no uid or gid, for now require
5181592Srgrimes * file to exist and be publicly
5191592Srgrimes * readable/writable.
5201592Srgrimes * If we were invoked with arguments
5211592Srgrimes * from inetd then the file must also be
5221592Srgrimes * in one of the given directory prefixes.
5231592Srgrimes * Note also, full path name must be
5241592Srgrimes * given as we have no login directory.
5251592Srgrimes */
5261592Srgrimesint
52790333Simpvalidate_access(char **filep, int mode)
5281592Srgrimes{
5291592Srgrimes	struct stat stbuf;
5301592Srgrimes	int	fd;
5311592Srgrimes	struct dirlist *dirp;
5321592Srgrimes	static char pathname[MAXPATHLEN];
5331592Srgrimes	char *filename = *filep;
5341592Srgrimes
5351592Srgrimes	/*
5361592Srgrimes	 * Prevent tricksters from getting around the directory restrictions
5371592Srgrimes	 */
5381592Srgrimes	if (strstr(filename, "/../"))
5391592Srgrimes		return (EACCESS);
5401592Srgrimes
5411592Srgrimes	if (*filename == '/') {
5421592Srgrimes		/*
5431592Srgrimes		 * Allow the request if it's in one of the approved locations.
5441592Srgrimes		 * Special case: check the null prefix ("/") by looking
5451592Srgrimes		 * for length = 1 and relying on the arg. processing that
5461592Srgrimes		 * it's a /.
5471592Srgrimes		 */
5481592Srgrimes		for (dirp = dirs; dirp->name != NULL; dirp++) {
5491592Srgrimes			if (dirp->len == 1 ||
5501592Srgrimes			    (!strncmp(filename, dirp->name, dirp->len) &&
5511592Srgrimes			     filename[dirp->len] == '/'))
5521592Srgrimes				    break;
5531592Srgrimes		}
5541592Srgrimes		/* If directory list is empty, allow access to any file */
5551592Srgrimes		if (dirp->name == NULL && dirp != dirs)
5561592Srgrimes			return (EACCESS);
5571592Srgrimes		if (stat(filename, &stbuf) < 0)
5581592Srgrimes			return (errno == ENOENT ? ENOTFOUND : EACCESS);
5591592Srgrimes		if ((stbuf.st_mode & S_IFMT) != S_IFREG)
5601592Srgrimes			return (ENOTFOUND);
5611592Srgrimes		if (mode == RRQ) {
5621592Srgrimes			if ((stbuf.st_mode & S_IROTH) == 0)
5631592Srgrimes				return (EACCESS);
5641592Srgrimes		} else {
5651592Srgrimes			if ((stbuf.st_mode & S_IWOTH) == 0)
5661592Srgrimes				return (EACCESS);
5671592Srgrimes		}
5681592Srgrimes	} else {
5691592Srgrimes		int err;
5701592Srgrimes
5711592Srgrimes		/*
5721592Srgrimes		 * Relative file name: search the approved locations for it.
5736750Sjkh		 * Don't allow write requests that avoid directory
5741592Srgrimes		 * restrictions.
5751592Srgrimes		 */
5761592Srgrimes
5776750Sjkh		if (!strncmp(filename, "../", 3))
5781592Srgrimes			return (EACCESS);
5791592Srgrimes
5801592Srgrimes		/*
5811592Srgrimes		 * If the file exists in one of the directories and isn't
5821592Srgrimes		 * readable, continue looking. However, change the error code
5831592Srgrimes		 * to give an indication that the file exists.
5841592Srgrimes		 */
5851592Srgrimes		err = ENOTFOUND;
5861592Srgrimes		for (dirp = dirs; dirp->name != NULL; dirp++) {
58724193Simp			snprintf(pathname, sizeof(pathname), "%s/%s",
58824193Simp				dirp->name, filename);
5891592Srgrimes			if (stat(pathname, &stbuf) == 0 &&
5901592Srgrimes			    (stbuf.st_mode & S_IFMT) == S_IFREG) {
5911592Srgrimes				if ((stbuf.st_mode & S_IROTH) != 0) {
5921592Srgrimes					break;
5931592Srgrimes				}
5941592Srgrimes				err = EACCESS;
5951592Srgrimes			}
5961592Srgrimes		}
597129680Smdodd		if (dirp->name != NULL)
598129680Smdodd			*filep = filename = pathname;
599129680Smdodd		else if (mode == RRQ)
6001592Srgrimes			return (err);
6011592Srgrimes	}
60284047Sobrien	if (options[OPT_TSIZE].o_request) {
60384047Sobrien		if (mode == RRQ)
60484047Sobrien			options[OPT_TSIZE].o_reply = stbuf.st_size;
60584047Sobrien		else
60684047Sobrien			/* XXX Allows writes of all sizes. */
60784047Sobrien			options[OPT_TSIZE].o_reply =
60884047Sobrien				atoi(options[OPT_TSIZE].o_request);
60984047Sobrien	}
610129680Smdodd	if (mode == RRQ)
611129680Smdodd		fd = open(filename, O_RDONLY);
612129680Smdodd	else {
613129680Smdodd		if (create_new)
614129680Smdodd			fd = open(filename, O_WRONLY|O_TRUNC|O_CREAT, 0666);
615129680Smdodd		else
616129680Smdodd			fd = open(filename, O_WRONLY|O_TRUNC);
617129680Smdodd	}
6181592Srgrimes	if (fd < 0)
6191592Srgrimes		return (errno + 100);
6201592Srgrimes	file = fdopen(fd, (mode == RRQ)? "r":"w");
6211592Srgrimes	if (file == NULL) {
622129683Smdodd		close(fd);
623129683Smdodd		return (errno + 100);
6241592Srgrimes	}
6251592Srgrimes	return (0);
6261592Srgrimes}
6271592Srgrimes
62884047Sobrienint	timeouts;
6291592Srgrimesjmp_buf	timeoutbuf;
6301592Srgrimes
6311592Srgrimesvoid
63290333Simptimer(int sig __unused)
6331592Srgrimes{
63484047Sobrien	if (++timeouts > MAX_TIMEOUTS)
6351592Srgrimes		exit(1);
6361592Srgrimes	longjmp(timeoutbuf, 1);
6371592Srgrimes}
6381592Srgrimes
6391592Srgrimes/*
6401592Srgrimes * Send the requested file.
6411592Srgrimes */
6421592Srgrimesvoid
64390333Simpxmitfile(struct formats *pf)
6441592Srgrimes{
645112452Sdwmalone	struct tftphdr *dp;
64690333Simp	struct tftphdr *ap;    /* ack packet */
64790333Simp	int size, n;
64871926Sasmodai	volatile unsigned short block;
6491592Srgrimes
6501592Srgrimes	signal(SIGALRM, timer);
6511592Srgrimes	dp = r_init();
6521592Srgrimes	ap = (struct tftphdr *)ackbuf;
6531592Srgrimes	block = 1;
6541592Srgrimes	do {
6551592Srgrimes		size = readit(file, &dp, pf->f_convert);
6561592Srgrimes		if (size < 0) {
6571592Srgrimes			nak(errno + 100);
6581592Srgrimes			goto abort;
6591592Srgrimes		}
6601592Srgrimes		dp->th_opcode = htons((u_short)DATA);
6611592Srgrimes		dp->th_block = htons((u_short)block);
66284047Sobrien		timeouts = 0;
6631592Srgrimes		(void)setjmp(timeoutbuf);
6641592Srgrimes
6651592Srgrimessend_data:
66694299Sambrisko		{
66794299Sambrisko			int i, t = 1;
66894299Sambrisko			for (i = 0; ; i++){
66994299Sambrisko				if (send(peer, dp, size + 4, 0) != size + 4) {
67094299Sambrisko					sleep(t);
67194299Sambrisko					t = (t < 32) ? t<< 1 : t;
67294299Sambrisko					if (i >= 12) {
67394299Sambrisko						syslog(LOG_ERR, "write: %m");
67494299Sambrisko						goto abort;
67594299Sambrisko					}
67694299Sambrisko				}
67794299Sambrisko				break;
67894299Sambrisko			}
6791592Srgrimes		}
6801592Srgrimes		read_ahead(file, pf->f_convert);
6811592Srgrimes		for ( ; ; ) {
6821592Srgrimes			alarm(rexmtval);        /* read the ack */
6831592Srgrimes			n = recv(peer, ackbuf, sizeof (ackbuf), 0);
6841592Srgrimes			alarm(0);
6851592Srgrimes			if (n < 0) {
68631512Scharnier				syslog(LOG_ERR, "read: %m");
6871592Srgrimes				goto abort;
6881592Srgrimes			}
6891592Srgrimes			ap->th_opcode = ntohs((u_short)ap->th_opcode);
6901592Srgrimes			ap->th_block = ntohs((u_short)ap->th_block);
6911592Srgrimes
6921592Srgrimes			if (ap->th_opcode == ERROR)
6931592Srgrimes				goto abort;
6941592Srgrimes
6951592Srgrimes			if (ap->th_opcode == ACK) {
6961592Srgrimes				if (ap->th_block == block)
6971592Srgrimes					break;
6981592Srgrimes				/* Re-synchronize with the other side */
6991592Srgrimes				(void) synchnet(peer);
7001592Srgrimes				if (ap->th_block == (block -1))
7011592Srgrimes					goto send_data;
7021592Srgrimes			}
7031592Srgrimes
7041592Srgrimes		}
7051592Srgrimes		block++;
7061592Srgrimes	} while (size == SEGSIZE);
7071592Srgrimesabort:
7081592Srgrimes	(void) fclose(file);
7091592Srgrimes}
7101592Srgrimes
7111592Srgrimesvoid
71290333Simpjustquit(int sig __unused)
7131592Srgrimes{
7141592Srgrimes	exit(0);
7151592Srgrimes}
7161592Srgrimes
7171592Srgrimes
7181592Srgrimes/*
7191592Srgrimes * Receive a file.
7201592Srgrimes */
7211592Srgrimesvoid
72290333Simprecvfile(struct formats *pf)
7231592Srgrimes{
724112452Sdwmalone	struct tftphdr *dp;
72590333Simp	struct tftphdr *ap;    /* ack buffer */
72690333Simp	int n, size;
72771926Sasmodai	volatile unsigned short block;
7281592Srgrimes
7291592Srgrimes	signal(SIGALRM, timer);
7301592Srgrimes	dp = w_init();
7311592Srgrimes	ap = (struct tftphdr *)ackbuf;
7321592Srgrimes	block = 0;
7331592Srgrimes	do {
73484047Sobrien		timeouts = 0;
7351592Srgrimes		ap->th_opcode = htons((u_short)ACK);
7361592Srgrimes		ap->th_block = htons((u_short)block);
7371592Srgrimes		block++;
7381592Srgrimes		(void) setjmp(timeoutbuf);
7391592Srgrimessend_ack:
7401592Srgrimes		if (send(peer, ackbuf, 4, 0) != 4) {
74131512Scharnier			syslog(LOG_ERR, "write: %m");
7421592Srgrimes			goto abort;
7431592Srgrimes		}
7441592Srgrimes		write_behind(file, pf->f_convert);
7451592Srgrimes		for ( ; ; ) {
7461592Srgrimes			alarm(rexmtval);
7471592Srgrimes			n = recv(peer, dp, PKTSIZE, 0);
7481592Srgrimes			alarm(0);
7491592Srgrimes			if (n < 0) {            /* really? */
75031512Scharnier				syslog(LOG_ERR, "read: %m");
7511592Srgrimes				goto abort;
7521592Srgrimes			}
7531592Srgrimes			dp->th_opcode = ntohs((u_short)dp->th_opcode);
7541592Srgrimes			dp->th_block = ntohs((u_short)dp->th_block);
7551592Srgrimes			if (dp->th_opcode == ERROR)
7561592Srgrimes				goto abort;
7571592Srgrimes			if (dp->th_opcode == DATA) {
7581592Srgrimes				if (dp->th_block == block) {
7591592Srgrimes					break;   /* normal */
7601592Srgrimes				}
7611592Srgrimes				/* Re-synchronize with the other side */
7621592Srgrimes				(void) synchnet(peer);
7631592Srgrimes				if (dp->th_block == (block-1))
7641592Srgrimes					goto send_ack;          /* rexmit */
7651592Srgrimes			}
7661592Srgrimes		}
7671592Srgrimes		/*  size = write(file, dp->th_data, n - 4); */
7681592Srgrimes		size = writeit(file, &dp, n - 4, pf->f_convert);
7691592Srgrimes		if (size != (n-4)) {                    /* ahem */
7701592Srgrimes			if (size < 0) nak(errno + 100);
7711592Srgrimes			else nak(ENOSPACE);
7721592Srgrimes			goto abort;
7731592Srgrimes		}
7741592Srgrimes	} while (size == SEGSIZE);
7751592Srgrimes	write_behind(file, pf->f_convert);
7761592Srgrimes	(void) fclose(file);            /* close data file */
7771592Srgrimes
7781592Srgrimes	ap->th_opcode = htons((u_short)ACK);    /* send the "final" ack */
7791592Srgrimes	ap->th_block = htons((u_short)(block));
7801592Srgrimes	(void) send(peer, ackbuf, 4, 0);
7811592Srgrimes
7821592Srgrimes	signal(SIGALRM, justquit);      /* just quit on timeout */
7831592Srgrimes	alarm(rexmtval);
7841592Srgrimes	n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
7851592Srgrimes	alarm(0);
7861592Srgrimes	if (n >= 4 &&                   /* if read some data */
7871592Srgrimes	    dp->th_opcode == DATA &&    /* and got a data block */
7881592Srgrimes	    block == dp->th_block) {	/* then my last ack was lost */
7891592Srgrimes		(void) send(peer, ackbuf, 4, 0);     /* resend final ack */
7901592Srgrimes	}
7911592Srgrimesabort:
7921592Srgrimes	return;
7931592Srgrimes}
7941592Srgrimes
7951592Srgrimesstruct errmsg {
7961592Srgrimes	int	e_code;
797112452Sdwmalone	const char	*e_msg;
7981592Srgrimes} errmsgs[] = {
7991592Srgrimes	{ EUNDEF,	"Undefined error code" },
8001592Srgrimes	{ ENOTFOUND,	"File not found" },
8011592Srgrimes	{ EACCESS,	"Access violation" },
8021592Srgrimes	{ ENOSPACE,	"Disk full or allocation exceeded" },
8031592Srgrimes	{ EBADOP,	"Illegal TFTP operation" },
8041592Srgrimes	{ EBADID,	"Unknown transfer ID" },
8051592Srgrimes	{ EEXISTS,	"File already exists" },
8061592Srgrimes	{ ENOUSER,	"No such user" },
80784047Sobrien	{ EOPTNEG,	"Option negotiation" },
8081592Srgrimes	{ -1,		0 }
8091592Srgrimes};
8101592Srgrimes
811112452Sdwmalonestatic const char *
81290333Simperrtomsg(int error)
8131592Srgrimes{
814112452Sdwmalone	static char ebuf[20];
81590333Simp	struct errmsg *pe;
8161592Srgrimes	if (error == 0)
8171592Srgrimes		return "success";
8181592Srgrimes	for (pe = errmsgs; pe->e_code >= 0; pe++)
8191592Srgrimes		if (pe->e_code == error)
8201592Srgrimes			return pe->e_msg;
821112452Sdwmalone	snprintf(ebuf, sizeof(buf), "error %d", error);
822112452Sdwmalone	return ebuf;
8231592Srgrimes}
8241592Srgrimes
8251592Srgrimes/*
8261592Srgrimes * Send a nak packet (error message).
8271592Srgrimes * Error code passed in is one of the
8281592Srgrimes * standard TFTP codes, or a UNIX errno
8291592Srgrimes * offset by 100.
8301592Srgrimes */
8311592Srgrimesstatic void
83290333Simpnak(int error)
8331592Srgrimes{
83490333Simp	struct tftphdr *tp;
8351592Srgrimes	int length;
83690333Simp	struct errmsg *pe;
8371592Srgrimes
8381592Srgrimes	tp = (struct tftphdr *)buf;
8391592Srgrimes	tp->th_opcode = htons((u_short)ERROR);
8401592Srgrimes	tp->th_code = htons((u_short)error);
8411592Srgrimes	for (pe = errmsgs; pe->e_code >= 0; pe++)
8421592Srgrimes		if (pe->e_code == error)
8431592Srgrimes			break;
8441592Srgrimes	if (pe->e_code < 0) {
8451592Srgrimes		pe->e_msg = strerror(error - 100);
8461592Srgrimes		tp->th_code = EUNDEF;   /* set 'undef' errorcode */
8471592Srgrimes	}
8481592Srgrimes	strcpy(tp->th_msg, pe->e_msg);
8491592Srgrimes	length = strlen(pe->e_msg);
8501592Srgrimes	tp->th_msg[length] = '\0';
8511592Srgrimes	length += 5;
8521592Srgrimes	if (send(peer, buf, length, 0) != length)
85331512Scharnier		syslog(LOG_ERR, "nak: %m");
8541592Srgrimes}
85584047Sobrien
85694443Sume/* translate IPv4 mapped IPv6 address to IPv4 address */
85794443Sumestatic void
85894443Sumeunmappedaddr(struct sockaddr_in6 *sin6)
85994443Sume{
86095496Sume	struct sockaddr_in *sin4;
86195496Sume	u_int32_t addr;
86295496Sume	int port;
86394443Sume
86495496Sume	if (sin6->sin6_family != AF_INET6 ||
86595496Sume	    !IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
86695496Sume		return;
86795496Sume	sin4 = (struct sockaddr_in *)sin6;
86895496Sume	addr = *(u_int32_t *)&sin6->sin6_addr.s6_addr[12];
86995496Sume	port = sin6->sin6_port;
87095496Sume	memset(sin4, 0, sizeof(struct sockaddr_in));
87195496Sume	sin4->sin_addr.s_addr = addr;
87295496Sume	sin4->sin_port = port;
87395496Sume	sin4->sin_family = AF_INET;
87495496Sume	sin4->sin_len = sizeof(struct sockaddr_in);
87594443Sume}
87694443Sume
87784047Sobrien/*
87884047Sobrien * Send an oack packet (option acknowledgement).
87984047Sobrien */
88084047Sobrienstatic void
88190333Simpoack(void)
88284047Sobrien{
88384047Sobrien	struct tftphdr *tp, *ap;
88484047Sobrien	int size, i, n;
88584047Sobrien	char *bp;
88684047Sobrien
88784047Sobrien	tp = (struct tftphdr *)buf;
88884047Sobrien	bp = buf + 2;
88984047Sobrien	size = sizeof(buf) - 2;
89084047Sobrien	tp->th_opcode = htons((u_short)OACK);
89184047Sobrien	for (i = 0; options[i].o_type != NULL; i++) {
89284047Sobrien		if (options[i].o_request) {
89384047Sobrien			n = snprintf(bp, size, "%s%c%d", options[i].o_type,
89484047Sobrien				     0, options[i].o_reply);
89584047Sobrien			bp += n+1;
89684047Sobrien			size -= n+1;
89784047Sobrien			if (size < 0) {
89884047Sobrien				syslog(LOG_ERR, "oack: buffer overflow");
89984047Sobrien				exit(1);
90084047Sobrien			}
90184047Sobrien		}
90284047Sobrien	}
90384047Sobrien	size = bp - buf;
90484047Sobrien	ap = (struct tftphdr *)ackbuf;
90584047Sobrien	signal(SIGALRM, timer);
90684047Sobrien	timeouts = 0;
90784047Sobrien
90884047Sobrien	(void)setjmp(timeoutbuf);
90984047Sobrien	if (send(peer, buf, size, 0) != size) {
91084047Sobrien		syslog(LOG_INFO, "oack: %m");
91184047Sobrien		exit(1);
91284047Sobrien	}
91384047Sobrien
91484047Sobrien	for (;;) {
91584047Sobrien		alarm(rexmtval);
91684047Sobrien		n = recv(peer, ackbuf, sizeof (ackbuf), 0);
91784047Sobrien		alarm(0);
91884047Sobrien		if (n < 0) {
91984047Sobrien			syslog(LOG_ERR, "recv: %m");
92084047Sobrien			exit(1);
92184047Sobrien		}
92284047Sobrien		ap->th_opcode = ntohs((u_short)ap->th_opcode);
92384047Sobrien		ap->th_block = ntohs((u_short)ap->th_block);
92484047Sobrien		if (ap->th_opcode == ERROR)
92584047Sobrien			exit(1);
92684047Sobrien		if (ap->th_opcode == ACK && ap->th_block == 0)
92784047Sobrien			break;
92884047Sobrien	}
92984047Sobrien}
930