xref: /freebsd/libexec/tftpd/tftpd.c (revision b64c5a0ace59af62eff52bfe110a521dc73c937b)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1983, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 /*
33  * Trivial file transfer protocol server.
34  *
35  * This version includes many modifications by Jim Guyton
36  * <guyton@rand-unix>.
37  */
38 
39 #include <sys/param.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <sys/stat.h>
43 #include <sys/time.h>
44 
45 #include <netinet/in.h>
46 #include <arpa/tftp.h>
47 
48 #include <ctype.h>
49 #include <errno.h>
50 #include <fcntl.h>
51 #include <netdb.h>
52 #include <pwd.h>
53 #include <stdint.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <syslog.h>
58 #include <time.h>
59 #include <unistd.h>
60 
61 #include "tftp-file.h"
62 #include "tftp-io.h"
63 #include "tftp-utils.h"
64 #include "tftp-transfer.h"
65 #include "tftp-options.h"
66 
67 #ifdef	LIBWRAP
68 #include <tcpd.h>
69 #endif
70 
71 static void	tftp_wrq(int peer, char *, size_t);
72 static void	tftp_rrq(int peer, char *, size_t);
73 
74 /*
75  * Null-terminated directory prefix list for absolute pathname requests and
76  * search list for relative pathname requests.
77  *
78  * MAXDIRS should be at least as large as the number of arguments that
79  * inetd allows (currently 20).
80  */
81 #define MAXDIRS	20
82 static struct dirlist {
83 	const char	*name;
84 	size_t		len;
85 } dirs[MAXDIRS+1];
86 static int	suppress_naks;
87 static int	logging;
88 static int	ipchroot;
89 static int	check_woth = 1;
90 static int	create_new = 0;
91 static const char *newfile_format = "%Y%m%d";
92 static int	increase_name = 0;
93 static mode_t	mask = S_IWGRP | S_IWOTH;
94 
95 struct formats;
96 static void	tftp_recvfile(int peer, const char *mode);
97 static void	tftp_xmitfile(int peer, const char *mode);
98 static int	validate_access(int peer, char **, int);
99 static char	peername[NI_MAXHOST];
100 
101 static FILE *file;
102 
103 static struct formats {
104 	const char	*f_mode;
105 	int	f_convert;
106 } formats[] = {
107 	{ "netascii",	1 },
108 	{ "octet",	0 },
109 	{ NULL,		0 }
110 };
111 
112 int
113 main(int argc, char *argv[])
114 {
115 	struct tftphdr *tp;
116 	int		peer;
117 	socklen_t	peerlen, len;
118 	ssize_t		n;
119 	int		ch;
120 	char		*chroot_dir = NULL;
121 	struct passwd	*nobody;
122 	const char	*chuser = "nobody";
123 	char		recvbuffer[MAXPKTSIZE];
124 	int		allow_ro = 1, allow_wo = 1, block = 0, on = 1;
125 	pid_t		pid;
126 
127 	tzset();			/* syslog in localtime */
128 	acting_as_client = 0;
129 
130 	tftp_openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
131 	while ((ch = getopt(argc, argv, "bcCd::F:lnoOp:s:Su:U:wW")) != -1) {
132 		switch (ch) {
133 		case 'b':
134 			block = 1;
135 			break;
136 		case 'c':
137 			ipchroot = 1;
138 			break;
139 		case 'C':
140 			ipchroot = 2;
141 			break;
142 		case 'd':
143 			if (optarg == NULL)
144 				debug++;
145 			else if (atoi(optarg) != 0)
146 				debug += atoi(optarg);
147 			else
148 				debug |= debug_finds(optarg);
149 			break;
150 		case 'F':
151 			newfile_format = optarg;
152 			break;
153 		case 'l':
154 			logging = 1;
155 			break;
156 		case 'n':
157 			suppress_naks = 1;
158 			break;
159 		case 'o':
160 			options_rfc_enabled = 0;
161 			break;
162 		case 'O':
163 			options_extra_enabled = 0;
164 			break;
165 		case 'p':
166 			packetdroppercentage = (unsigned int)atoi(optarg);
167 			tftp_log(LOG_INFO,
168 			    "Randomly dropping %d out of 100 packets",
169 			    packetdroppercentage);
170 			break;
171 		case 's':
172 			chroot_dir = optarg;
173 			break;
174 		case 'S':
175 			check_woth = -1;
176 			break;
177 		case 'u':
178 			chuser = optarg;
179 			break;
180 		case 'U':
181 			mask = strtol(optarg, NULL, 0);
182 			break;
183 		case 'w':
184 			create_new = 1;
185 			break;
186 		case 'W':
187 			create_new = 1;
188 			increase_name = 1;
189 			break;
190 		default:
191 			tftp_log(LOG_WARNING,
192 				"ignoring unknown option -%c", ch);
193 		}
194 	}
195 	if (optind < argc) {
196 		struct dirlist *dirp;
197 
198 		/* Get list of directory prefixes. Skip relative pathnames. */
199 		for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
200 		     optind++) {
201 			if (argv[optind][0] == '/') {
202 				dirp->name = argv[optind];
203 				dirp->len  = strlen(dirp->name);
204 				dirp++;
205 			}
206 		}
207 	}
208 	else if (chroot_dir) {
209 		dirs->name = "/";
210 		dirs->len = 1;
211 	}
212 	if (ipchroot > 0 && chroot_dir == NULL) {
213 		tftp_log(LOG_ERR, "-c requires -s");
214 		exit(1);
215 	}
216 
217 	umask(mask);
218 
219 	/* Find out who we are talking to and what we are going to do */
220 	peerlen = sizeof(peer_sock);
221 	n = recvfrom(0, recvbuffer, MAXPKTSIZE, block ? 0 : MSG_DONTWAIT,
222 	    (struct sockaddr *)&peer_sock, &peerlen);
223 	if (n < 0) {
224 		tftp_log(LOG_ERR, "recvfrom: %s", strerror(errno));
225 		exit(1);
226 	}
227 	getnameinfo((struct sockaddr *)&peer_sock, peer_sock.ss_len,
228 	    peername, sizeof(peername), NULL, 0, NI_NUMERICHOST);
229 	if ((size_t)n < 4 /* tftphdr */) {
230 		tftp_log(LOG_ERR, "Rejecting %zd-byte request from %s",
231 		    n, peername);
232 		exit(1);
233 	}
234 
235 	if (ioctl(0, FIONBIO, &on) < 0) {
236 		tftp_log(LOG_ERR, "ioctl(FIONBIO): %s", strerror(errno));
237 		exit(1);
238 	}
239 
240 	/*
241 	 * Now that we have read the message out of the UDP
242 	 * socket, we fork and exit.  Thus, inetd will go back
243 	 * to listening to the tftp port, and the next request
244 	 * to come in will start up a new instance of tftpd.
245 	 *
246 	 * We do this so that inetd can run tftpd in "wait" mode.
247 	 * The problem with tftpd running in "nowait" mode is that
248 	 * inetd may get one or more successful "selects" on the
249 	 * tftp port before we do our receive, so more than one
250 	 * instance of tftpd may be started up.  Worse, if tftpd
251 	 * break before doing the above "recvfrom", inetd would
252 	 * spawn endless instances, clogging the system.
253 	 */
254 	pid = fork();
255 	if (pid < 0) {
256 		tftp_log(LOG_ERR, "fork: %s", strerror(errno));
257 		exit(1);
258 	} else if (pid != 0) {
259 		exit(0);
260 	}
261 	/* child */
262 
263 #ifdef	LIBWRAP
264 	/*
265 	 * See if the client is allowed to talk to me.
266 	 * (This needs to be done before the chroot())
267 	 */
268 	{
269 		struct request_info req;
270 
271 		request_init(&req, RQ_CLIENT_ADDR, peername, 0);
272 		request_set(&req, RQ_DAEMON, "tftpd", 0);
273 
274 		if (hosts_access(&req) == 0) {
275 			if (debug & DEBUG_ACCESS)
276 				tftp_log(LOG_WARNING,
277 				    "Access denied by 'tftpd' entry "
278 				    "in /etc/hosts.allow");
279 
280 			/*
281 			 * Full access might be disabled, but maybe the
282 			 * client is allowed to do read-only access.
283 			 */
284 			request_set(&req, RQ_DAEMON, "tftpd-ro", 0);
285 			allow_ro = hosts_access(&req);
286 
287 			request_set(&req, RQ_DAEMON, "tftpd-wo", 0);
288 			allow_wo = hosts_access(&req);
289 
290 			if (allow_ro == 0 && allow_wo == 0) {
291 				tftp_log(LOG_WARNING,
292 				    "Unauthorized access from %s", peername);
293 				exit(1);
294 			}
295 
296 			if (debug & DEBUG_ACCESS) {
297 				if (allow_ro)
298 					tftp_log(LOG_WARNING,
299 					    "But allowed readonly access "
300 					    "via 'tftpd-ro' entry");
301 				if (allow_wo)
302 					tftp_log(LOG_WARNING,
303 					    "But allowed writeonly access "
304 					    "via 'tftpd-wo' entry");
305 			}
306 		} else
307 			if (debug & DEBUG_ACCESS)
308 				tftp_log(LOG_WARNING,
309 				    "Full access allowed"
310 				    "in /etc/hosts.allow");
311 	}
312 #endif
313 
314 	/*
315 	 * Since we exit here, we should do that only after the above
316 	 * recvfrom to keep inetd from constantly forking should there
317 	 * be a problem.  See the above comment about system clogging.
318 	 */
319 	if (chroot_dir) {
320 		if (ipchroot > 0) {
321 			char *tempchroot;
322 			struct stat sb;
323 			int statret;
324 			struct sockaddr_storage ss;
325 			char hbuf[NI_MAXHOST];
326 
327 			statret = -1;
328 			memcpy(&ss, &peer_sock, peer_sock.ss_len);
329 			unmappedaddr((struct sockaddr_in6 *)&ss);
330 			getnameinfo((struct sockaddr *)&ss, ss.ss_len,
331 				    hbuf, sizeof(hbuf), NULL, 0,
332 				    NI_NUMERICHOST);
333 			asprintf(&tempchroot, "%s/%s", chroot_dir, hbuf);
334 			if (ipchroot == 2)
335 				statret = stat(tempchroot, &sb);
336 			if (ipchroot == 1 ||
337 			    (statret == 0 && (sb.st_mode & S_IFDIR)))
338 				chroot_dir = tempchroot;
339 		}
340 		/* Must get this before chroot because /etc might go away */
341 		if ((nobody = getpwnam(chuser)) == NULL) {
342 			tftp_log(LOG_ERR, "%s: no such user", chuser);
343 			exit(1);
344 		}
345 		if (chroot(chroot_dir)) {
346 			tftp_log(LOG_ERR, "chroot: %s: %s",
347 			    chroot_dir, strerror(errno));
348 			exit(1);
349 		}
350 		if (chdir("/") != 0) {
351 			tftp_log(LOG_ERR, "chdir: %s", strerror(errno));
352 			exit(1);
353 		}
354 		if (setgroups(1, &nobody->pw_gid) != 0) {
355 			tftp_log(LOG_ERR, "setgroups failed");
356 			exit(1);
357 		}
358 		if (setuid(nobody->pw_uid) != 0) {
359 			tftp_log(LOG_ERR, "setuid failed");
360 			exit(1);
361 		}
362 		if (check_woth == -1)
363 			check_woth = 0;
364 	}
365 	if (check_woth == -1)
366 		check_woth = 1;
367 
368 	len = sizeof(me_sock);
369 	if (getsockname(0, (struct sockaddr *)&me_sock, &len) == 0) {
370 		switch (me_sock.ss_family) {
371 		case AF_INET:
372 			((struct sockaddr_in *)&me_sock)->sin_port = 0;
373 			break;
374 		case AF_INET6:
375 			((struct sockaddr_in6 *)&me_sock)->sin6_port = 0;
376 			break;
377 		default:
378 			/* unsupported */
379 			break;
380 		}
381 	} else {
382 		memset(&me_sock, 0, sizeof(me_sock));
383 		me_sock.ss_family = peer_sock.ss_family;
384 		me_sock.ss_len = peer_sock.ss_len;
385 	}
386 	close(STDIN_FILENO);
387 	close(STDOUT_FILENO);
388 	close(STDERR_FILENO);
389 	peer = socket(peer_sock.ss_family, SOCK_DGRAM, 0);
390 	if (peer < 0) {
391 		tftp_log(LOG_ERR, "socket: %s", strerror(errno));
392 		exit(1);
393 	}
394 	if (bind(peer, (struct sockaddr *)&me_sock, me_sock.ss_len) < 0) {
395 		tftp_log(LOG_ERR, "bind: %s", strerror(errno));
396 		exit(1);
397 	}
398 
399 	tp = (struct tftphdr *)recvbuffer;
400 	tp->th_opcode = ntohs(tp->th_opcode);
401 	if (tp->th_opcode == RRQ) {
402 		if (allow_ro)
403 			tftp_rrq(peer, tp->th_stuff, (size_t)n - 1);
404 		else {
405 			tftp_log(LOG_WARNING,
406 			    "%s read access denied", peername);
407 			exit(1);
408 		}
409 	} else if (tp->th_opcode == WRQ) {
410 		if (allow_wo)
411 			tftp_wrq(peer, tp->th_stuff, (size_t)n - 1);
412 		else {
413 			tftp_log(LOG_WARNING,
414 			    "%s write access denied", peername);
415 			exit(1);
416 		}
417 	} else
418 		send_error(peer, EBADOP);
419 	exit(1);
420 }
421 
422 static void
423 reduce_path(char *fn)
424 {
425 	char *slash, *ptr;
426 
427 	/* Reduce all "/+./" to "/" (just in case we've got "/./../" later */
428 	while ((slash = strstr(fn, "/./")) != NULL) {
429 		for (ptr = slash; ptr > fn && ptr[-1] == '/'; ptr--)
430 			;
431 		slash += 2;
432 		while (*slash)
433 			*++ptr = *++slash;
434 	}
435 
436 	/* Now reduce all "/something/+../" to "/" */
437 	while ((slash = strstr(fn, "/../")) != NULL) {
438 		if (slash == fn)
439 			break;
440 		for (ptr = slash; ptr > fn && ptr[-1] == '/'; ptr--)
441 			;
442 		for (ptr--; ptr >= fn; ptr--)
443 			if (*ptr == '/')
444 				break;
445 		if (ptr < fn)
446 			break;
447 		slash += 3;
448 		while (*slash)
449 			*++ptr = *++slash;
450 	}
451 }
452 
453 static char *
454 parse_header(int peer, char *recvbuffer, size_t size,
455 	char **filename, char **mode)
456 {
457 	struct formats *pf;
458 	char	*cp;
459 	size_t	i;
460 
461 	*mode = NULL;
462 	cp = recvbuffer;
463 
464 	i = get_field(peer, recvbuffer, size);
465 	if (i >= PATH_MAX) {
466 		tftp_log(LOG_ERR, "Bad option - filename too long");
467 		send_error(peer, EBADOP);
468 		exit(1);
469 	}
470 	*filename = recvbuffer;
471 	tftp_log(LOG_INFO, "Filename: '%s'", *filename);
472 	cp += i;
473 
474 	i = get_field(peer, cp, size);
475 	*mode = cp;
476 
477 	/* Find the file transfer mode */
478 	for (; *cp; cp++)
479 		if (isupper((unsigned char)*cp))
480 			*cp = tolower((unsigned char)*cp);
481 	for (pf = formats; pf->f_mode; pf++)
482 		if (strcmp(pf->f_mode, *mode) == 0)
483 			break;
484 	if (pf->f_mode == NULL) {
485 		tftp_log(LOG_ERR,
486 		    "Bad option - Unknown transfer mode (%s)", *mode);
487 		send_error(peer, EBADOP);
488 		exit(1);
489 	}
490 	tftp_log(LOG_INFO, "Mode: '%s'", *mode);
491 
492 	return (cp + 1);
493 }
494 
495 /*
496  * WRQ - receive a file from the client
497  */
498 void
499 tftp_wrq(int peer, char *recvbuffer, size_t size)
500 {
501 	char *cp;
502 	int has_options = 0, ecode;
503 	char *filename, *mode;
504 	char fnbuf[PATH_MAX];
505 
506 	cp = parse_header(peer, recvbuffer, size, &filename, &mode);
507 	size -= (cp - recvbuffer) + 1;
508 
509 	strlcpy(fnbuf, filename, sizeof(fnbuf));
510 	reduce_path(fnbuf);
511 	filename = fnbuf;
512 
513 	if (size > 0) {
514 		if (options_rfc_enabled)
515 			has_options = !parse_options(peer, cp, size);
516 		else
517 			tftp_log(LOG_INFO, "Options found but not enabled");
518 	}
519 
520 	ecode = validate_access(peer, &filename, WRQ);
521 	if (ecode == 0) {
522 		if (has_options)
523 			send_oack(peer);
524 		else
525 			send_ack(peer, 0);
526 	}
527 	if (logging) {
528 		tftp_log(LOG_INFO, "%s: write request for %s: %s", peername,
529 			    filename, errtomsg(ecode));
530 	}
531 
532 	if (ecode) {
533 		send_error(peer, ecode);
534 		exit(1);
535 	}
536 	tftp_recvfile(peer, mode);
537 	exit(0);
538 }
539 
540 /*
541  * RRQ - send a file to the client
542  */
543 void
544 tftp_rrq(int peer, char *recvbuffer, size_t size)
545 {
546 	char *cp;
547 	int has_options = 0, ecode;
548 	char *filename, *mode;
549 	char	fnbuf[PATH_MAX];
550 
551 	cp = parse_header(peer, recvbuffer, size, &filename, &mode);
552 	size -= (cp - recvbuffer) + 1;
553 
554 	strlcpy(fnbuf, filename, sizeof(fnbuf));
555 	reduce_path(fnbuf);
556 	filename = fnbuf;
557 
558 	if (size > 0) {
559 		if (options_rfc_enabled)
560 			has_options = !parse_options(peer, cp, size);
561 		else
562 			tftp_log(LOG_INFO, "Options found but not enabled");
563 	}
564 
565 	ecode = validate_access(peer, &filename, RRQ);
566 	if (ecode == 0) {
567 		if (has_options) {
568 			int n;
569 			char lrecvbuffer[MAXPKTSIZE];
570 			struct tftphdr *rp = (struct tftphdr *)lrecvbuffer;
571 
572 			send_oack(peer);
573 			n = receive_packet(peer, lrecvbuffer, MAXPKTSIZE,
574 				NULL, timeoutpacket);
575 			if (n < 0) {
576 				if (debug & DEBUG_SIMPLE)
577 					tftp_log(LOG_DEBUG, "Aborting: %s",
578 					    rp_strerror(n));
579 				return;
580 			}
581 			if (rp->th_opcode != ACK) {
582 				if (debug & DEBUG_SIMPLE)
583 					tftp_log(LOG_DEBUG,
584 					    "Expected ACK, got %s on OACK",
585 					    packettype(rp->th_opcode));
586 				return;
587 			}
588 		}
589 	}
590 
591 	if (logging)
592 		tftp_log(LOG_INFO, "%s: read request for %s: %s", peername,
593 			    filename, errtomsg(ecode));
594 
595 	if (ecode) {
596 		/*
597 		 * Avoid storms of naks to a RRQ broadcast for a relative
598 		 * bootfile pathname from a diskless Sun.
599 		 */
600 		if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
601 			exit(0);
602 		send_error(peer, ecode);
603 		exit(1);
604 	}
605 	tftp_xmitfile(peer, mode);
606 }
607 
608 /*
609  * Find the next value for YYYYMMDD.nn when the file to be written should
610  * be unique. Due to the limitations of nn, we will fail if nn reaches 100.
611  * Besides, that is four updates per hour on a file, which is kind of
612  * execessive anyway.
613  */
614 static int
615 find_next_name(char *filename, int *fd)
616 {
617 	/*
618 	 * GCC "knows" that we might write all of yyyymmdd plus the static
619 	 * elemenents in the format into into newname and thus complains
620 	 * unless we reduce the size.  This array is still too big, but since
621 	 * the format is user supplied, it's not clear what a better limit
622 	 * value would be and this is sufficent to silence the warnings.
623 	 */
624 	static const int suffix_len = strlen("..00");
625 	char yyyymmdd[MAXPATHLEN - suffix_len];
626 	char newname[MAXPATHLEN];
627 	int i, ret;
628 	time_t tval;
629 	size_t len, namelen;
630 	struct tm lt;
631 
632 	/* Create the YYYYMMDD part of the filename */
633 	time(&tval);
634 	lt = *localtime(&tval);
635 	len = strftime(yyyymmdd, sizeof(yyyymmdd), newfile_format, &lt);
636 	if (len == 0) {
637 		syslog(LOG_WARNING,
638 			"Filename suffix too long (%zu characters maximum)",
639 			sizeof(yyyymmdd) - 1);
640 		return (EACCESS);
641 	}
642 
643 	/* Make sure the new filename is not too long */
644 	namelen = strlen(filename);
645 	if (namelen >= sizeof(newname) - len - suffix_len) {
646 		syslog(LOG_WARNING,
647 			"Filename too long (%zu characters, %zu maximum)",
648 			namelen,
649 			sizeof(newname) - len - suffix_len - 1);
650 		return (EACCESS);
651 	}
652 
653 	/* Find the first file which doesn't exist */
654 	for (i = 0; i < 100; i++) {
655 		ret = snprintf(newname, sizeof(newname), "%s.%s.%02d",
656 		    filename, yyyymmdd, i);
657 		/*
658 		 * Size checked above so this can't happen, we'd use a
659 		 * (void) cast, but gcc intentionally ignores that if
660 		 * snprintf has __attribute__((warn_unused_result)).
661 		 */
662 		if (ret < 0 || (size_t)ret >= sizeof(newname))
663 			__unreachable();
664 		*fd = open(newname, O_WRONLY | O_CREAT | O_EXCL, 0666);
665 		if (*fd > 0)
666 			return 0;
667 	}
668 
669 	return (EEXIST);
670 }
671 
672 /*
673  * Validate file access.  Since we
674  * have no uid or gid, for now require
675  * file to exist and be publicly
676  * readable/writable.
677  * If we were invoked with arguments
678  * from inetd then the file must also be
679  * in one of the given directory prefixes.
680  * Note also, full path name must be
681  * given as we have no login directory.
682  */
683 int
684 validate_access(int peer, char **filep, int mode)
685 {
686 	static char pathname[MAXPATHLEN];
687 	struct stat sb;
688 	struct dirlist *dirp;
689 	char *filename = *filep;
690 	int	err, fd;
691 
692 	/*
693 	 * Prevent tricksters from getting around the directory restrictions
694 	 */
695 	if (strncmp(filename, "../", 3) == 0 ||
696 	    strstr(filename, "/../") != NULL)
697 		return (EACCESS);
698 
699 	if (*filename == '/') {
700 		/*
701 		 * Absolute file name: allow the request if it's in one of the
702 		 * approved locations.
703 		 */
704 		for (dirp = dirs; dirp->name != NULL; dirp++) {
705 			if (dirp->len == 1)
706 				/* Only "/" can have len 1 */
707 				break;
708 			if (strncmp(filename, dirp->name, dirp->len) == 0 &&
709 			    filename[dirp->len] == '/')
710 				break;
711 		}
712 		/* If directory list is empty, allow access to any file */
713 		if (dirp->name == NULL && dirp != dirs)
714 			return (EACCESS);
715 		if (stat(filename, &sb) != 0)
716 			return (errno == ENOENT ? ENOTFOUND : EACCESS);
717 		if (!S_ISREG(sb.st_mode))
718 			return (ENOTFOUND);
719 		if (mode == RRQ) {
720 			if ((sb.st_mode & S_IROTH) == 0)
721 				return (EACCESS);
722 		} else {
723 			if (check_woth && (sb.st_mode & S_IWOTH) == 0)
724 				return (EACCESS);
725 		}
726 	} else {
727 		/*
728 		 * Relative file name: search the approved locations for it.
729 		 * If the file exists in one of the directories and isn't
730 		 * readable, continue looking. However, change the error code
731 		 * to give an indication that the file exists.
732 		 */
733 		err = ENOTFOUND;
734 		for (dirp = dirs; dirp->name != NULL; dirp++) {
735 			snprintf(pathname, sizeof(pathname), "%s/%s",
736 			    dirp->name, filename);
737 			if (stat(pathname, &sb) != 0)
738 				continue;
739 			if (!S_ISREG(sb.st_mode))
740 				continue;
741 			err = EACCESS;
742 			if (mode == RRQ) {
743 				if ((sb.st_mode & S_IROTH) == 0)
744 					continue;
745 			} else {
746 				if (check_woth && (sb.st_mode & S_IWOTH) == 0)
747 					continue;
748 			}
749 			break;
750 		}
751 		if (dirp->name != NULL)
752 			*filep = filename = pathname;
753 		else if (mode == RRQ)
754 			return (err);
755 		else if (err != ENOTFOUND || !create_new)
756 			return (err);
757 	}
758 
759 	/*
760 	 * This option is handled here because it (might) require(s) the
761 	 * size of the file.
762 	 */
763 	option_tsize(peer, NULL, mode, &sb);
764 
765 	if (mode == RRQ) {
766 		fd = open(filename, O_RDONLY);
767 	} else if (create_new) {
768 		if (increase_name) {
769 			err = find_next_name(filename, &fd);
770 			if (err > 0)
771 				return (err + 100);
772 		} else {
773 			fd = open(filename,
774 			    O_WRONLY | O_TRUNC | O_CREAT,
775 			    S_IRUSR | S_IWUSR | S_IRGRP |
776 			    S_IWGRP | S_IROTH | S_IWOTH );
777 		}
778 	} else {
779 		fd = open(filename, O_WRONLY | O_TRUNC);
780 	}
781 	if (fd < 0)
782 		return (errno + 100);
783 	file = fdopen(fd, mode == RRQ ? "r" : "w");
784 	if (file == NULL) {
785 		close(fd);
786 		return (errno + 100);
787 	}
788 	return (0);
789 }
790 
791 static void
792 tftp_xmitfile(int peer, const char *mode)
793 {
794 	uint16_t block;
795 	time_t now;
796 	struct tftp_stats ts;
797 
798 	memset(&ts, 0, sizeof(ts));
799 	now = time(NULL);
800 	if (debug & DEBUG_SIMPLE)
801 		tftp_log(LOG_DEBUG, "Transmitting file");
802 
803 	read_init(0, file, mode);
804 	block = 1;
805 	tftp_send(peer, &block, &ts);
806 	read_close();
807 	if (debug & DEBUG_SIMPLE)
808 		tftp_log(LOG_INFO, "Sent %jd bytes in %jd seconds",
809 		    (intmax_t)ts.amount, (intmax_t)time(NULL) - now);
810 }
811 
812 static void
813 tftp_recvfile(int peer, const char *mode)
814 {
815 	uint16_t block;
816 	struct timeval now1, now2;
817 	struct tftp_stats ts;
818 
819 	gettimeofday(&now1, NULL);
820 	if (debug & DEBUG_SIMPLE)
821 		tftp_log(LOG_DEBUG, "Receiving file");
822 
823 	write_init(0, file, mode);
824 
825 	block = 0;
826 	tftp_receive(peer, &block, &ts, NULL, 0);
827 
828 	gettimeofday(&now2, NULL);
829 
830 	if (debug & DEBUG_SIMPLE) {
831 		double f;
832 		if (now1.tv_usec > now2.tv_usec) {
833 			now2.tv_usec += 1000000;
834 			now2.tv_sec--;
835 		}
836 
837 		f = now2.tv_sec - now1.tv_sec +
838 		    (now2.tv_usec - now1.tv_usec) / 100000.0;
839 		tftp_log(LOG_INFO,
840 		    "Download of %jd bytes in %d blocks completed after %0.1f seconds\n",
841 		    (intmax_t)ts.amount, block, f);
842 	}
843 
844 	return;
845 }
846