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