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