tftpd.c revision 262136
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.
13262136Sbrueffer * 3. Neither the name of the University nor the names of its contributors
141592Srgrimes *    may be used to endorse or promote products derived from this software
151592Srgrimes *    without specific prior written permission.
161592Srgrimes *
171592Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
181592Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
191592Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
201592Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
211592Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
221592Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
231592Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
241592Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
251592Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
261592Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
271592Srgrimes * SUCH DAMAGE.
281592Srgrimes */
291592Srgrimes
301592Srgrimes#ifndef lint
3131512Scharnierstatic const char copyright[] =
321592Srgrimes"@(#) Copyright (c) 1983, 1993\n\
331592Srgrimes	The Regents of the University of California.  All rights reserved.\n";
341592Srgrimes#endif /* not lint */
351592Srgrimes
361592Srgrimes#ifndef lint
3731512Scharnier#if 0
381592Srgrimesstatic char sccsid[] = "@(#)tftpd.c	8.1 (Berkeley) 6/4/93";
3931512Scharnier#endif
401592Srgrimes#endif /* not lint */
41207608Simp#include <sys/cdefs.h>
42207608Simp__FBSDID("$FreeBSD: head/libexec/tftpd/tftpd.c 262136 2014-02-17 22:27:32Z brueffer $");
431592Srgrimes
441592Srgrimes/*
451592Srgrimes * Trivial file transfer protocol server.
461592Srgrimes *
471592Srgrimes * This version includes many modifications by Jim Guyton
481592Srgrimes * <guyton@rand-unix>.
491592Srgrimes */
501592Srgrimes
511592Srgrimes#include <sys/param.h>
521592Srgrimes#include <sys/ioctl.h>
531592Srgrimes#include <sys/stat.h>
541592Srgrimes#include <sys/socket.h>
551592Srgrimes
561592Srgrimes#include <netinet/in.h>
571592Srgrimes#include <arpa/tftp.h>
581592Srgrimes
591592Srgrimes#include <ctype.h>
601592Srgrimes#include <errno.h>
611592Srgrimes#include <fcntl.h>
621592Srgrimes#include <netdb.h>
6331512Scharnier#include <pwd.h>
64246139Smarius#include <stdint.h>
651592Srgrimes#include <stdio.h>
661592Srgrimes#include <stdlib.h>
671592Srgrimes#include <string.h>
681592Srgrimes#include <syslog.h>
69207608Simp#include <tcpd.h>
701592Srgrimes#include <unistd.h>
711592Srgrimes
72207608Simp#include "tftp-file.h"
73207608Simp#include "tftp-io.h"
74207608Simp#include "tftp-utils.h"
75207608Simp#include "tftp-transfer.h"
76207608Simp#include "tftp-options.h"
771592Srgrimes
78207608Simpstatic void	tftp_wrq(int peer, char *, ssize_t);
79207608Simpstatic void	tftp_rrq(int peer, char *, ssize_t);
801592Srgrimes
811592Srgrimes/*
821592Srgrimes * Null-terminated directory prefix list for absolute pathname requests and
831592Srgrimes * search list for relative pathname requests.
841592Srgrimes *
851592Srgrimes * MAXDIRS should be at least as large as the number of arguments that
861592Srgrimes * inetd allows (currently 20).
871592Srgrimes */
881592Srgrimes#define MAXDIRS	20
891592Srgrimesstatic struct dirlist {
90112452Sdwmalone	const char	*name;
911592Srgrimes	int	len;
921592Srgrimes} dirs[MAXDIRS+1];
931592Srgrimesstatic int	suppress_naks;
941592Srgrimesstatic int	logging;
9571616Sbillfstatic int	ipchroot;
96129680Smdoddstatic int	create_new = 0;
97213099Smariusstatic const char *newfile_format = "%Y%m%d";
98173852Sedwinstatic int	increase_name = 0;
99207608Simpstatic mode_t	mask = S_IWGRP | S_IWOTH;
1001592Srgrimes
101207608Simpstruct formats;
102207608Simpstatic void	tftp_recvfile(int peer, const char *mode);
103207608Simpstatic void	tftp_xmitfile(int peer, const char *mode);
104207608Simpstatic int	validate_access(int peer, char **, int);
105207608Simpstatic char	peername[NI_MAXHOST];
1061592Srgrimes
107241720Sedstatic FILE *file;
108112452Sdwmalone
109241720Sedstatic struct formats {
110207608Simp	const char	*f_mode;
111207608Simp	int	f_convert;
112207608Simp} formats[] = {
113207608Simp	{ "netascii",	1 },
114207608Simp	{ "octet",	0 },
115207608Simp	{ NULL,		0 }
116207608Simp};
117207608Simp
1181592Srgrimesint
11990333Simpmain(int argc, char *argv[])
1201592Srgrimes{
12190333Simp	struct tftphdr *tp;
122207608Simp	int		peer;
123207608Simp	socklen_t	peerlen, len;
124207608Simp	ssize_t		n;
125207608Simp	int		ch;
126207608Simp	char		*chroot_dir = NULL;
127207608Simp	struct passwd	*nobody;
128207608Simp	const char	*chuser = "nobody";
129207608Simp	char		recvbuffer[MAXPKTSIZE];
130207608Simp	int		allow_ro = 1, allow_wo = 1;
1311592Srgrimes
132130839Sbrian	tzset();			/* syslog in localtime */
133207608Simp	acting_as_client = 0;
134130839Sbrian
135207608Simp	tftp_openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
136207608Simp	while ((ch = getopt(argc, argv, "cCd:F:lnoOp:s:u:U:wW")) != -1) {
1371592Srgrimes		switch (ch) {
13871616Sbillf		case 'c':
13971616Sbillf			ipchroot = 1;
14071616Sbillf			break;
14171616Sbillf		case 'C':
14271616Sbillf			ipchroot = 2;
14371616Sbillf			break;
144207608Simp		case 'd':
145207608Simp			if (atoi(optarg) != 0)
146207608Simp				debug += atoi(optarg);
147207608Simp			else
148207608Simp				debug |= debug_finds(optarg);
149207608Simp			break;
150173852Sedwin		case 'F':
151173852Sedwin			newfile_format = optarg;
152173852Sedwin			break;
1531592Srgrimes		case 'l':
1541592Srgrimes			logging = 1;
1551592Srgrimes			break;
1561592Srgrimes		case 'n':
1571592Srgrimes			suppress_naks = 1;
1581592Srgrimes			break;
159207608Simp		case 'o':
160207608Simp			options_rfc_enabled = 0;
161207608Simp			break;
162207608Simp		case 'O':
163207608Simp			options_extra_enabled = 0;
164207608Simp			break;
165207608Simp		case 'p':
166207608Simp			packetdroppercentage = atoi(optarg);
167207608Simp			tftp_log(LOG_INFO,
168207608Simp			    "Randomly dropping %d out of 100 packets",
169207608Simp			    packetdroppercentage);
170207608Simp			break;
17118458Simp		case 's':
17218458Simp			chroot_dir = optarg;
17318458Simp			break;
17465850Swollman		case 'u':
17565850Swollman			chuser = optarg;
17665850Swollman			break;
177129680Smdodd		case 'U':
178129680Smdodd			mask = strtol(optarg, NULL, 0);
179129680Smdodd			break;
180129680Smdodd		case 'w':
181129680Smdodd			create_new = 1;
182129680Smdodd			break;
183173852Sedwin		case 'W':
184173852Sedwin			create_new = 1;
185173852Sedwin			increase_name = 1;
186173852Sedwin			break;
1871592Srgrimes		default:
188207608Simp			tftp_log(LOG_WARNING,
189207608Simp				"ignoring unknown option -%c", ch);
1901592Srgrimes		}
1911592Srgrimes	}
1921592Srgrimes	if (optind < argc) {
1931592Srgrimes		struct dirlist *dirp;
1941592Srgrimes
1951592Srgrimes		/* Get list of directory prefixes. Skip relative pathnames. */
1961592Srgrimes		for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
1971592Srgrimes		     optind++) {
1981592Srgrimes			if (argv[optind][0] == '/') {
1991592Srgrimes				dirp->name = argv[optind];
2001592Srgrimes				dirp->len  = strlen(dirp->name);
2011592Srgrimes				dirp++;
2021592Srgrimes			}
2031592Srgrimes		}
2041592Srgrimes	}
20518458Simp	else if (chroot_dir) {
20618458Simp		dirs->name = "/";
20718458Simp		dirs->len = 1;
20818458Simp	}
209113714Sbillf	if (ipchroot > 0 && chroot_dir == NULL) {
210207608Simp		tftp_log(LOG_ERR, "-c requires -s");
21171616Sbillf		exit(1);
21271616Sbillf	}
2131592Srgrimes
214129680Smdodd	umask(mask);
215129680Smdodd
216207608Simp	{
217207608Simp		int on = 1;
218207608Simp		if (ioctl(0, FIONBIO, &on) < 0) {
219207608Simp			tftp_log(LOG_ERR, "ioctl(FIONBIO): %s", strerror(errno));
220207608Simp			exit(1);
221207608Simp		}
2221592Srgrimes	}
223207608Simp
224207608Simp	/* Find out who we are talking to and what we are going to do */
225207608Simp	peerlen = sizeof(peer_sock);
226207608Simp	n = recvfrom(0, recvbuffer, MAXPKTSIZE, 0,
227207608Simp	    (struct sockaddr *)&peer_sock, &peerlen);
2281592Srgrimes	if (n < 0) {
229207608Simp		tftp_log(LOG_ERR, "recvfrom: %s", strerror(errno));
2301592Srgrimes		exit(1);
2311592Srgrimes	}
232207608Simp	getnameinfo((struct sockaddr *)&peer_sock, peer_sock.ss_len,
233207608Simp	    peername, sizeof(peername), NULL, 0, NI_NUMERICHOST);
234207608Simp
2351592Srgrimes	/*
2361592Srgrimes	 * Now that we have read the message out of the UDP
2371592Srgrimes	 * socket, we fork and exit.  Thus, inetd will go back
2381592Srgrimes	 * to listening to the tftp port, and the next request
2391592Srgrimes	 * to come in will start up a new instance of tftpd.
2401592Srgrimes	 *
2411592Srgrimes	 * We do this so that inetd can run tftpd in "wait" mode.
2421592Srgrimes	 * The problem with tftpd running in "nowait" mode is that
2431592Srgrimes	 * inetd may get one or more successful "selects" on the
2441592Srgrimes	 * tftp port before we do our receive, so more than one
2451592Srgrimes	 * instance of tftpd may be started up.  Worse, if tftpd
2461592Srgrimes	 * break before doing the above "recvfrom", inetd would
2471592Srgrimes	 * spawn endless instances, clogging the system.
2481592Srgrimes	 */
2491592Srgrimes	{
250141922Sstefanf		int i, pid;
2511592Srgrimes
2521592Srgrimes		for (i = 1; i < 20; i++) {
2531592Srgrimes		    pid = fork();
2541592Srgrimes		    if (pid < 0) {
2551592Srgrimes				sleep(i);
2561592Srgrimes				/*
2571592Srgrimes				 * flush out to most recently sent request.
2581592Srgrimes				 *
2591592Srgrimes				 * This may drop some request, but those
2601592Srgrimes				 * will be resent by the clients when
2611592Srgrimes				 * they timeout.  The positive effect of
2621592Srgrimes				 * this flush is to (try to) prevent more
2631592Srgrimes				 * than one tftpd being started up to service
2641592Srgrimes				 * a single request from a single client.
2651592Srgrimes				 */
266207608Simp				peerlen = sizeof peer_sock;
267207608Simp				i = recvfrom(0, recvbuffer, MAXPKTSIZE, 0,
268207608Simp				    (struct sockaddr *)&peer_sock, &peerlen);
2691592Srgrimes				if (i > 0) {
2701592Srgrimes					n = i;
2711592Srgrimes				}
2721592Srgrimes		    } else {
2731592Srgrimes				break;
2741592Srgrimes		    }
2751592Srgrimes		}
2761592Srgrimes		if (pid < 0) {
277207608Simp			tftp_log(LOG_ERR, "fork: %s", strerror(errno));
2781592Srgrimes			exit(1);
2791592Srgrimes		} else if (pid != 0) {
2801592Srgrimes			exit(0);
2811592Srgrimes		}
2821592Srgrimes	}
28318458Simp
28418458Simp	/*
285207608Simp	 * See if the client is allowed to talk to me.
286207608Simp	 * (This needs to be done before the chroot())
287207608Simp	 */
288207608Simp	{
289207608Simp		struct request_info req;
290207608Simp
291207608Simp		request_init(&req, RQ_CLIENT_ADDR, peername, 0);
292207608Simp		request_set(&req, RQ_DAEMON, "tftpd", 0);
293207608Simp
294207608Simp		if (hosts_access(&req) == 0) {
295207608Simp			if (debug&DEBUG_ACCESS)
296207608Simp				tftp_log(LOG_WARNING,
297207608Simp				    "Access denied by 'tftpd' entry "
298207608Simp				    "in /etc/hosts.allow");
299207608Simp
300207608Simp			/*
301207608Simp			 * Full access might be disabled, but maybe the
302207608Simp			 * client is allowed to do read-only access.
303207608Simp			 */
304207608Simp			request_set(&req, RQ_DAEMON, "tftpd-ro", 0);
305207608Simp			allow_ro = hosts_access(&req);
306207608Simp
307207608Simp			request_set(&req, RQ_DAEMON, "tftpd-wo", 0);
308207608Simp			allow_wo = hosts_access(&req);
309207608Simp
310207608Simp			if (allow_ro == 0 && allow_wo == 0) {
311207608Simp				tftp_log(LOG_WARNING,
312207608Simp				    "Unauthorized access from %s", peername);
313207608Simp				exit(1);
314207608Simp			}
315207608Simp
316207608Simp			if (debug&DEBUG_ACCESS) {
317207608Simp				if (allow_ro)
318207608Simp					tftp_log(LOG_WARNING,
319207608Simp					    "But allowed readonly access "
320207608Simp					    "via 'tftpd-ro' entry");
321207608Simp				if (allow_wo)
322207608Simp					tftp_log(LOG_WARNING,
323207608Simp					    "But allowed writeonly access "
324207608Simp					    "via 'tftpd-wo' entry");
325207608Simp			}
326207608Simp		} else
327207608Simp			if (debug&DEBUG_ACCESS)
328207608Simp				tftp_log(LOG_WARNING,
329207608Simp				    "Full access allowed"
330207608Simp				    "in /etc/hosts.allow");
331207608Simp	}
332207608Simp
333207608Simp	/*
33418458Simp	 * Since we exit here, we should do that only after the above
33518458Simp	 * recvfrom to keep inetd from constantly forking should there
33618458Simp	 * be a problem.  See the above comment about system clogging.
33718458Simp	 */
33818458Simp	if (chroot_dir) {
339113714Sbillf		if (ipchroot > 0) {
34071616Sbillf			char *tempchroot;
34171616Sbillf			struct stat sb;
34271616Sbillf			int statret;
34394443Sume			struct sockaddr_storage ss;
34494443Sume			char hbuf[NI_MAXHOST];
34571616Sbillf
346207608Simp			statret = -1;
347207608Simp			memcpy(&ss, &peer_sock, peer_sock.ss_len);
34894443Sume			unmappedaddr((struct sockaddr_in6 *)&ss);
34994443Sume			getnameinfo((struct sockaddr *)&ss, ss.ss_len,
35094443Sume				    hbuf, sizeof(hbuf), NULL, 0,
351146187Sume				    NI_NUMERICHOST);
35294443Sume			asprintf(&tempchroot, "%s/%s", chroot_dir, hbuf);
353113714Sbillf			if (ipchroot == 2)
354113714Sbillf				statret = stat(tempchroot, &sb);
355113714Sbillf			if (ipchroot == 1 ||
356113714Sbillf			    (statret == 0 && (sb.st_mode & S_IFDIR)))
35771616Sbillf				chroot_dir = tempchroot;
35871616Sbillf		}
35918458Simp		/* Must get this before chroot because /etc might go away */
36065850Swollman		if ((nobody = getpwnam(chuser)) == NULL) {
361207608Simp			tftp_log(LOG_ERR, "%s: no such user", chuser);
36218458Simp			exit(1);
36318458Simp		}
36418458Simp		if (chroot(chroot_dir)) {
365207608Simp			tftp_log(LOG_ERR, "chroot: %s: %s",
366207608Simp			    chroot_dir, strerror(errno));
36718458Simp			exit(1);
36818458Simp		}
369131358Scsjp		chdir("/");
370131358Scsjp		setgroups(1, &nobody->pw_gid);
371241848Seadler		if (setuid(nobody->pw_uid) != 0) {
372241848Seadler			tftp_log(LOG_ERR, "setuid failed");
373241848Seadler			exit(1);
374241848Seadler		}
37518458Simp	}
37618458Simp
377207608Simp	len = sizeof(me_sock);
378207608Simp	if (getsockname(0, (struct sockaddr *)&me_sock, &len) == 0) {
379207608Simp		switch (me_sock.ss_family) {
38094443Sume		case AF_INET:
381207608Simp			((struct sockaddr_in *)&me_sock)->sin_port = 0;
38294443Sume			break;
38394443Sume		case AF_INET6:
384207608Simp			((struct sockaddr_in6 *)&me_sock)->sin6_port = 0;
38594443Sume			break;
38694443Sume		default:
38794443Sume			/* unsupported */
38894443Sume			break;
38994443Sume		}
39094443Sume	} else {
391207608Simp		memset(&me_sock, 0, sizeof(me_sock));
392207608Simp		me_sock.ss_family = peer_sock.ss_family;
393207608Simp		me_sock.ss_len = peer_sock.ss_len;
39494443Sume	}
3951592Srgrimes	close(0);
3961592Srgrimes	close(1);
397207608Simp	peer = socket(peer_sock.ss_family, SOCK_DGRAM, 0);
3981592Srgrimes	if (peer < 0) {
399207608Simp		tftp_log(LOG_ERR, "socket: %s", strerror(errno));
4001592Srgrimes		exit(1);
4011592Srgrimes	}
402207608Simp	if (bind(peer, (struct sockaddr *)&me_sock, me_sock.ss_len) < 0) {
403207608Simp		tftp_log(LOG_ERR, "bind: %s", strerror(errno));
4041592Srgrimes		exit(1);
4051592Srgrimes	}
406207608Simp
407207608Simp	tp = (struct tftphdr *)recvbuffer;
408207608Simp	tp->th_opcode = ntohs(tp->th_opcode);
409207608Simp	if (tp->th_opcode == RRQ) {
410207608Simp		if (allow_ro)
411207608Simp			tftp_rrq(peer, tp->th_stuff, n - 1);
412207608Simp		else {
413207608Simp			tftp_log(LOG_WARNING,
414207608Simp			    "%s read access denied", peername);
415207608Simp			exit(1);
416207608Simp		}
4171592Srgrimes	}
418207608Simp	if (tp->th_opcode == WRQ) {
419207608Simp		if (allow_wo)
420207608Simp			tftp_wrq(peer, tp->th_stuff, n - 1);
421207608Simp		else {
422207608Simp			tftp_log(LOG_WARNING,
423207608Simp			    "%s write access denied", peername);
424207608Simp			exit(1);
425207608Simp		}
426207608Simp	}
4271592Srgrimes	exit(1);
4281592Srgrimes}
4291592Srgrimes
430130834Sbrianstatic void
431130834Sbrianreduce_path(char *fn)
432130834Sbrian{
433130834Sbrian	char *slash, *ptr;
434130834Sbrian
435130834Sbrian	/* Reduce all "/+./" to "/" (just in case we've got "/./../" later */
436130834Sbrian	while ((slash = strstr(fn, "/./")) != NULL) {
437130834Sbrian		for (ptr = slash; ptr > fn && ptr[-1] == '/'; ptr--)
438130834Sbrian			;
439130834Sbrian		slash += 2;
440130834Sbrian		while (*slash)
441130834Sbrian			*++ptr = *++slash;
442130834Sbrian	}
443130834Sbrian
444130834Sbrian	/* Now reduce all "/something/+../" to "/" */
445130834Sbrian	while ((slash = strstr(fn, "/../")) != NULL) {
446130834Sbrian		if (slash == fn)
447130834Sbrian			break;
448130834Sbrian		for (ptr = slash; ptr > fn && ptr[-1] == '/'; ptr--)
449130834Sbrian			;
450130834Sbrian		for (ptr--; ptr >= fn; ptr--)
451130834Sbrian			if (*ptr == '/')
452130834Sbrian				break;
453130834Sbrian		if (ptr < fn)
454130834Sbrian			break;
455130834Sbrian		slash += 3;
456130834Sbrian		while (*slash)
457130834Sbrian			*++ptr = *++slash;
458130834Sbrian	}
459130834Sbrian}
460130834Sbrian
461207608Simpstatic char *
462207608Simpparse_header(int peer, char *recvbuffer, ssize_t size,
463207608Simp	char **filename, char **mode)
464207608Simp{
465207608Simp	char	*cp;
466207608Simp	int	i;
467207608Simp	struct formats *pf;
4681592Srgrimes
469207608Simp	*mode = NULL;
470207608Simp	cp = recvbuffer;
4711592Srgrimes
472207608Simp	i = get_field(peer, recvbuffer, size);
473207608Simp	if (i >= PATH_MAX) {
474207608Simp		tftp_log(LOG_ERR, "Bad option - filename too long");
475207608Simp		send_error(peer, EBADOP);
476207608Simp		exit(1);
477207608Simp	}
478207608Simp	*filename = recvbuffer;
479207608Simp	tftp_log(LOG_INFO, "Filename: '%s'", *filename);
480207608Simp	cp += i;
48184047Sobrien
482207608Simp	i = get_field(peer, cp, size);
483207608Simp	*mode = cp;
484207608Simp	cp += i;
48584047Sobrien
486207608Simp	/* Find the file transfer mode */
487207608Simp	for (cp = *mode; *cp; cp++)
488207608Simp		if (isupper(*cp))
489207608Simp			*cp = tolower(*cp);
490207608Simp	for (pf = formats; pf->f_mode; pf++)
491207608Simp		if (strcmp(pf->f_mode, *mode) == 0)
492207608Simp			break;
493207608Simp	if (pf->f_mode == NULL) {
494207608Simp		tftp_log(LOG_ERR,
495207608Simp		    "Bad option - Unknown transfer mode (%s)", *mode);
496207608Simp		send_error(peer, EBADOP);
497207608Simp		exit(1);
498207608Simp	}
499207608Simp	tftp_log(LOG_INFO, "Mode: '%s'", *mode);
500207608Simp
501207608Simp	return (cp + 1);
502207608Simp}
503207608Simp
5041592Srgrimes/*
505207608Simp * WRQ - receive a file from the client
5061592Srgrimes */
5071592Srgrimesvoid
508207608Simptftp_wrq(int peer, char *recvbuffer, ssize_t size)
5091592Srgrimes{
51090333Simp	char *cp;
511207608Simp	int has_options = 0, ecode;
512207608Simp	char *filename, *mode;
513141922Sstefanf	char fnbuf[PATH_MAX];
5141592Srgrimes
515207608Simp	cp = parse_header(peer, recvbuffer, size, &filename, &mode);
516207608Simp	size -= (cp - recvbuffer) + 1;
517207608Simp
518207608Simp	strcpy(fnbuf, filename);
519207608Simp	reduce_path(fnbuf);
520207608Simp	filename = fnbuf;
521207608Simp
522207608Simp	if (size > 0) {
523207608Simp		if (options_rfc_enabled)
524207608Simp			has_options = !parse_options(peer, cp, size);
525207608Simp		else
526207608Simp			tftp_log(LOG_INFO, "Options found but not enabled");
5271592Srgrimes	}
528207608Simp
529207608Simp	ecode = validate_access(peer, &filename, WRQ);
530207608Simp	if (ecode == 0) {
531207608Simp		if (has_options)
532207608Simp			send_oack(peer);
533207608Simp		else
534207608Simp			send_ack(peer, 0);
5351592Srgrimes	}
536207608Simp	if (logging) {
537207608Simp		tftp_log(LOG_INFO, "%s: write request for %s: %s", peername,
538207608Simp			    filename, errtomsg(ecode));
539122916Ssobomax	}
540207608Simp
541207608Simp	tftp_recvfile(peer, mode);
542207608Simp	exit(0);
543207608Simp}
544207608Simp
545207608Simp/*
546207608Simp * RRQ - send a file to the client
547207608Simp */
548207608Simpvoid
549207608Simptftp_rrq(int peer, char *recvbuffer, ssize_t size)
550207608Simp{
551207608Simp	char *cp;
552207608Simp	int has_options = 0, ecode;
553207608Simp	char *filename, *mode;
554207608Simp	char	fnbuf[PATH_MAX];
555207608Simp
556207608Simp	cp = parse_header(peer, recvbuffer, size, &filename, &mode);
557207608Simp	size -= (cp - recvbuffer) + 1;
558207608Simp
559207608Simp	strcpy(fnbuf, filename);
560130834Sbrian	reduce_path(fnbuf);
561122916Ssobomax	filename = fnbuf;
562207608Simp
563207608Simp	if (size > 0) {
564207608Simp		if (options_rfc_enabled)
565207608Simp			has_options = !parse_options(peer, cp, size);
566207608Simp		else
567207608Simp			tftp_log(LOG_INFO, "Options found but not enabled");
5681592Srgrimes	}
569207608Simp
570207608Simp	ecode = validate_access(peer, &filename, RRQ);
571207608Simp	if (ecode == 0) {
572207608Simp		if (has_options) {
573207608Simp			int n;
574207608Simp			char lrecvbuffer[MAXPKTSIZE];
575207608Simp			struct tftphdr *rp = (struct tftphdr *)lrecvbuffer;
576207608Simp
577207608Simp			send_oack(peer);
578207608Simp			n = receive_packet(peer, lrecvbuffer, MAXPKTSIZE,
579207608Simp				NULL, timeoutpacket);
580207608Simp			if (n < 0) {
581207608Simp				if (debug&DEBUG_SIMPLE)
582207608Simp					tftp_log(LOG_DEBUG, "Aborting: %s",
583207608Simp					    rp_strerror(n));
584207608Simp				return;
58584047Sobrien			}
586207608Simp			if (rp->th_opcode != ACK) {
587207608Simp				if (debug&DEBUG_SIMPLE)
588207608Simp					tftp_log(LOG_DEBUG,
589207608Simp					    "Expected ACK, got %s on OACK",
590207608Simp					    packettype(rp->th_opcode));
591207608Simp				return;
592207608Simp			}
59384047Sobrien		}
59484047Sobrien	}
59584047Sobrien
596207608Simp	if (logging)
597207608Simp		tftp_log(LOG_INFO, "%s: read request for %s: %s", peername,
598207608Simp			    filename, errtomsg(ecode));
59945393Sbrian
6001592Srgrimes	if (ecode) {
6011592Srgrimes		/*
6021592Srgrimes		 * Avoid storms of naks to a RRQ broadcast for a relative
6031592Srgrimes		 * bootfile pathname from a diskless Sun.
6041592Srgrimes		 */
6051592Srgrimes		if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
6061592Srgrimes			exit(0);
607207608Simp		send_error(peer, ecode);
6081592Srgrimes		exit(1);
6091592Srgrimes	}
610207608Simp	tftp_xmitfile(peer, mode);
6111592Srgrimes}
6121592Srgrimes
6131592Srgrimes/*
614173852Sedwin * Find the next value for YYYYMMDD.nn when the file to be written should
615173852Sedwin * be unique. Due to the limitations of nn, we will fail if nn reaches 100.
616173852Sedwin * Besides, that is four updates per hour on a file, which is kind of
617173852Sedwin * execessive anyway.
618173852Sedwin */
619173852Sedwinstatic int
620173852Sedwinfind_next_name(char *filename, int *fd)
621173852Sedwin{
622173852Sedwin	int i;
623173852Sedwin	time_t tval;
624173852Sedwin	size_t len;
625173852Sedwin	struct tm lt;
626173852Sedwin	char yyyymmdd[MAXPATHLEN];
627173852Sedwin	char newname[MAXPATHLEN];
628173852Sedwin
629173852Sedwin	/* Create the YYYYMMDD part of the filename */
630173852Sedwin	time(&tval);
631173852Sedwin	lt = *localtime(&tval);
632173852Sedwin	len = strftime(yyyymmdd, sizeof(yyyymmdd), newfile_format, &lt);
633173852Sedwin	if (len == 0) {
634173852Sedwin		syslog(LOG_WARNING,
635173852Sedwin			"Filename suffix too long (%d characters maximum)",
636173852Sedwin			MAXPATHLEN);
637173852Sedwin		return (EACCESS);
638173852Sedwin	}
639173852Sedwin
640173852Sedwin	/* Make sure the new filename is not too long */
641173852Sedwin	if (strlen(filename) > MAXPATHLEN - len - 5) {
642173852Sedwin		syslog(LOG_WARNING,
643207608Simp			"Filename too long (%zd characters, %zd maximum)",
644173852Sedwin			strlen(filename), MAXPATHLEN - len - 5);
645173852Sedwin		return (EACCESS);
646173852Sedwin	}
647173852Sedwin
648173852Sedwin	/* Find the first file which doesn't exist */
649173852Sedwin	for (i = 0; i < 100; i++) {
650173852Sedwin		sprintf(newname, "%s.%s.%02d", filename, yyyymmdd, i);
651173852Sedwin		*fd = open(newname,
652173852Sedwin		    O_WRONLY | O_CREAT | O_EXCL,
653173852Sedwin		    S_IRUSR | S_IWUSR | S_IRGRP |
654173852Sedwin		    S_IWGRP | S_IROTH | S_IWOTH);
655173852Sedwin		if (*fd > 0)
656173852Sedwin			return 0;
657173852Sedwin	}
658173852Sedwin
659173852Sedwin	return (EEXIST);
660173852Sedwin}
661173852Sedwin
662173852Sedwin/*
6631592Srgrimes * Validate file access.  Since we
6641592Srgrimes * have no uid or gid, for now require
6651592Srgrimes * file to exist and be publicly
6661592Srgrimes * readable/writable.
6671592Srgrimes * If we were invoked with arguments
6681592Srgrimes * from inetd then the file must also be
6691592Srgrimes * in one of the given directory prefixes.
6701592Srgrimes * Note also, full path name must be
6711592Srgrimes * given as we have no login directory.
6721592Srgrimes */
6731592Srgrimesint
674207608Simpvalidate_access(int peer, char **filep, int mode)
6751592Srgrimes{
6761592Srgrimes	struct stat stbuf;
6771592Srgrimes	int	fd;
678173852Sedwin	int	error;
6791592Srgrimes	struct dirlist *dirp;
6801592Srgrimes	static char pathname[MAXPATHLEN];
6811592Srgrimes	char *filename = *filep;
6821592Srgrimes
6831592Srgrimes	/*
6841592Srgrimes	 * Prevent tricksters from getting around the directory restrictions
6851592Srgrimes	 */
6861592Srgrimes	if (strstr(filename, "/../"))
6871592Srgrimes		return (EACCESS);
6881592Srgrimes
6891592Srgrimes	if (*filename == '/') {
6901592Srgrimes		/*
6911592Srgrimes		 * Allow the request if it's in one of the approved locations.
6921592Srgrimes		 * Special case: check the null prefix ("/") by looking
6931592Srgrimes		 * for length = 1 and relying on the arg. processing that
6941592Srgrimes		 * it's a /.
6951592Srgrimes		 */
6961592Srgrimes		for (dirp = dirs; dirp->name != NULL; dirp++) {
6971592Srgrimes			if (dirp->len == 1 ||
6981592Srgrimes			    (!strncmp(filename, dirp->name, dirp->len) &&
6991592Srgrimes			     filename[dirp->len] == '/'))
7001592Srgrimes				    break;
7011592Srgrimes		}
7021592Srgrimes		/* If directory list is empty, allow access to any file */
7031592Srgrimes		if (dirp->name == NULL && dirp != dirs)
7041592Srgrimes			return (EACCESS);
7051592Srgrimes		if (stat(filename, &stbuf) < 0)
7061592Srgrimes			return (errno == ENOENT ? ENOTFOUND : EACCESS);
7071592Srgrimes		if ((stbuf.st_mode & S_IFMT) != S_IFREG)
7081592Srgrimes			return (ENOTFOUND);
7091592Srgrimes		if (mode == RRQ) {
7101592Srgrimes			if ((stbuf.st_mode & S_IROTH) == 0)
7111592Srgrimes				return (EACCESS);
7121592Srgrimes		} else {
7131592Srgrimes			if ((stbuf.st_mode & S_IWOTH) == 0)
7141592Srgrimes				return (EACCESS);
7151592Srgrimes		}
7161592Srgrimes	} else {
7171592Srgrimes		int err;
7181592Srgrimes
7191592Srgrimes		/*
7201592Srgrimes		 * Relative file name: search the approved locations for it.
7216750Sjkh		 * Don't allow write requests that avoid directory
7221592Srgrimes		 * restrictions.
7231592Srgrimes		 */
7241592Srgrimes
7256750Sjkh		if (!strncmp(filename, "../", 3))
7261592Srgrimes			return (EACCESS);
7271592Srgrimes
7281592Srgrimes		/*
7291592Srgrimes		 * If the file exists in one of the directories and isn't
7301592Srgrimes		 * readable, continue looking. However, change the error code
7311592Srgrimes		 * to give an indication that the file exists.
7321592Srgrimes		 */
7331592Srgrimes		err = ENOTFOUND;
7341592Srgrimes		for (dirp = dirs; dirp->name != NULL; dirp++) {
73524193Simp			snprintf(pathname, sizeof(pathname), "%s/%s",
73624193Simp				dirp->name, filename);
7371592Srgrimes			if (stat(pathname, &stbuf) == 0 &&
7381592Srgrimes			    (stbuf.st_mode & S_IFMT) == S_IFREG) {
7391592Srgrimes				if ((stbuf.st_mode & S_IROTH) != 0) {
7401592Srgrimes					break;
7411592Srgrimes				}
7421592Srgrimes				err = EACCESS;
7431592Srgrimes			}
7441592Srgrimes		}
745129680Smdodd		if (dirp->name != NULL)
746129680Smdodd			*filep = filename = pathname;
747129680Smdodd		else if (mode == RRQ)
7481592Srgrimes			return (err);
7491592Srgrimes	}
750207608Simp
751207608Simp	/*
752207608Simp	 * This option is handled here because it (might) require(s) the
753207608Simp	 * size of the file.
754207608Simp	 */
755207608Simp	option_tsize(peer, NULL, mode, &stbuf);
756207608Simp
757129680Smdodd	if (mode == RRQ)
758129680Smdodd		fd = open(filename, O_RDONLY);
759129680Smdodd	else {
760173852Sedwin		if (create_new) {
761173852Sedwin			if (increase_name) {
762173852Sedwin				error = find_next_name(filename, &fd);
763173852Sedwin				if (error > 0)
764173852Sedwin					return (error + 100);
765173852Sedwin			} else
766173852Sedwin				fd = open(filename,
767173852Sedwin				    O_WRONLY | O_TRUNC | O_CREAT,
768173852Sedwin				    S_IRUSR | S_IWUSR | S_IRGRP |
769173852Sedwin				    S_IWGRP | S_IROTH | S_IWOTH );
770173852Sedwin		} else
771173852Sedwin			fd = open(filename, O_WRONLY | O_TRUNC);
772129680Smdodd	}
7731592Srgrimes	if (fd < 0)
7741592Srgrimes		return (errno + 100);
7751592Srgrimes	file = fdopen(fd, (mode == RRQ)? "r":"w");
7761592Srgrimes	if (file == NULL) {
777129683Smdodd		close(fd);
778129683Smdodd		return (errno + 100);
7791592Srgrimes	}
7801592Srgrimes	return (0);
7811592Srgrimes}
7821592Srgrimes
783207608Simpstatic void
784207608Simptftp_xmitfile(int peer, const char *mode)
7851592Srgrimes{
786207608Simp	uint16_t block;
787207608Simp	time_t now;
788207608Simp	struct tftp_stats ts;
7891592Srgrimes
790207608Simp	now = time(NULL);
791207608Simp	if (debug&DEBUG_SIMPLE)
792207608Simp		tftp_log(LOG_DEBUG, "Transmitting file");
7931592Srgrimes
794207608Simp	read_init(0, file, mode);
7951592Srgrimes	block = 1;
796207608Simp	tftp_send(peer, &block, &ts);
797207608Simp	read_close();
798207608Simp	if (debug&DEBUG_SIMPLE)
799246139Smarius		tftp_log(LOG_INFO, "Sent %jd bytes in %jd seconds",
800246139Smarius		    (intmax_t)ts.amount, (intmax_t)time(NULL) - now);
8011592Srgrimes}
8021592Srgrimes
803207608Simpstatic void
804207608Simptftp_recvfile(int peer, const char *mode)
8051592Srgrimes{
806207608Simp	uint16_t block;
807207608Simp	struct timeval now1, now2;
808207608Simp	struct tftp_stats ts;
8091592Srgrimes
810207608Simp	gettimeofday(&now1, NULL);
811207608Simp	if (debug&DEBUG_SIMPLE)
812207608Simp		tftp_log(LOG_DEBUG, "Receiving file");
8131592Srgrimes
814207608Simp	write_init(0, file, mode);
8151592Srgrimes
8161592Srgrimes	block = 0;
817207608Simp	tftp_receive(peer, &block, &ts, NULL, 0);
8181592Srgrimes
819207608Simp	write_close();
820213099Smarius	gettimeofday(&now2, NULL);
8211592Srgrimes
822207608Simp	if (debug&DEBUG_SIMPLE) {
823207608Simp		double f;
824207608Simp		if (now1.tv_usec > now2.tv_usec) {
825207608Simp			now2.tv_usec += 1000000;
826207608Simp			now2.tv_sec--;
827207608Simp		}
8281592Srgrimes
829207608Simp		f = now2.tv_sec - now1.tv_sec +
830207608Simp		    (now2.tv_usec - now1.tv_usec) / 100000.0;
831207608Simp		tftp_log(LOG_INFO,
832246139Smarius		    "Download of %jd bytes in %d blocks completed after %0.1f seconds\n",
833246139Smarius		    (intmax_t)ts.amount, block, f);
8341592Srgrimes	}
83584047Sobrien
836207608Simp	return;
83794443Sume}
838