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