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