xref: /freebsd/libexec/tftpd/tftpd.c (revision c697fb7f)
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 		if (setgroups(1, &nobody->pw_gid) != 0) {
378 			tftp_log(LOG_ERR, "setgroups failed");
379 			exit(1);
380 		}
381 		if (setuid(nobody->pw_uid) != 0) {
382 			tftp_log(LOG_ERR, "setuid failed");
383 			exit(1);
384 		}
385 	}
386 
387 	len = sizeof(me_sock);
388 	if (getsockname(0, (struct sockaddr *)&me_sock, &len) == 0) {
389 		switch (me_sock.ss_family) {
390 		case AF_INET:
391 			((struct sockaddr_in *)&me_sock)->sin_port = 0;
392 			break;
393 		case AF_INET6:
394 			((struct sockaddr_in6 *)&me_sock)->sin6_port = 0;
395 			break;
396 		default:
397 			/* unsupported */
398 			break;
399 		}
400 	} else {
401 		memset(&me_sock, 0, sizeof(me_sock));
402 		me_sock.ss_family = peer_sock.ss_family;
403 		me_sock.ss_len = peer_sock.ss_len;
404 	}
405 	close(0);
406 	close(1);
407 	peer = socket(peer_sock.ss_family, SOCK_DGRAM, 0);
408 	if (peer < 0) {
409 		tftp_log(LOG_ERR, "socket: %s", strerror(errno));
410 		exit(1);
411 	}
412 	if (bind(peer, (struct sockaddr *)&me_sock, me_sock.ss_len) < 0) {
413 		tftp_log(LOG_ERR, "bind: %s", strerror(errno));
414 		exit(1);
415 	}
416 
417 	tp = (struct tftphdr *)recvbuffer;
418 	tp->th_opcode = ntohs(tp->th_opcode);
419 	if (tp->th_opcode == RRQ) {
420 		if (allow_ro)
421 			tftp_rrq(peer, tp->th_stuff, n - 1);
422 		else {
423 			tftp_log(LOG_WARNING,
424 			    "%s read access denied", peername);
425 			exit(1);
426 		}
427 	} else if (tp->th_opcode == WRQ) {
428 		if (allow_wo)
429 			tftp_wrq(peer, tp->th_stuff, n - 1);
430 		else {
431 			tftp_log(LOG_WARNING,
432 			    "%s write access denied", peername);
433 			exit(1);
434 		}
435 	} else
436 		send_error(peer, EBADOP);
437 	exit(1);
438 }
439 
440 static void
441 reduce_path(char *fn)
442 {
443 	char *slash, *ptr;
444 
445 	/* Reduce all "/+./" to "/" (just in case we've got "/./../" later */
446 	while ((slash = strstr(fn, "/./")) != NULL) {
447 		for (ptr = slash; ptr > fn && ptr[-1] == '/'; ptr--)
448 			;
449 		slash += 2;
450 		while (*slash)
451 			*++ptr = *++slash;
452 	}
453 
454 	/* Now reduce all "/something/+../" to "/" */
455 	while ((slash = strstr(fn, "/../")) != NULL) {
456 		if (slash == fn)
457 			break;
458 		for (ptr = slash; ptr > fn && ptr[-1] == '/'; ptr--)
459 			;
460 		for (ptr--; ptr >= fn; ptr--)
461 			if (*ptr == '/')
462 				break;
463 		if (ptr < fn)
464 			break;
465 		slash += 3;
466 		while (*slash)
467 			*++ptr = *++slash;
468 	}
469 }
470 
471 static char *
472 parse_header(int peer, char *recvbuffer, ssize_t size,
473 	char **filename, char **mode)
474 {
475 	char	*cp;
476 	int	i;
477 	struct formats *pf;
478 
479 	*mode = NULL;
480 	cp = recvbuffer;
481 
482 	i = get_field(peer, recvbuffer, size);
483 	if (i >= PATH_MAX) {
484 		tftp_log(LOG_ERR, "Bad option - filename too long");
485 		send_error(peer, EBADOP);
486 		exit(1);
487 	}
488 	*filename = recvbuffer;
489 	tftp_log(LOG_INFO, "Filename: '%s'", *filename);
490 	cp += i;
491 
492 	i = get_field(peer, cp, size);
493 	*mode = cp;
494 	cp += i;
495 
496 	/* Find the file transfer mode */
497 	for (cp = *mode; *cp; cp++)
498 		if (isupper(*cp))
499 			*cp = tolower(*cp);
500 	for (pf = formats; pf->f_mode; pf++)
501 		if (strcmp(pf->f_mode, *mode) == 0)
502 			break;
503 	if (pf->f_mode == NULL) {
504 		tftp_log(LOG_ERR,
505 		    "Bad option - Unknown transfer mode (%s)", *mode);
506 		send_error(peer, EBADOP);
507 		exit(1);
508 	}
509 	tftp_log(LOG_INFO, "Mode: '%s'", *mode);
510 
511 	return (cp + 1);
512 }
513 
514 /*
515  * WRQ - receive a file from the client
516  */
517 void
518 tftp_wrq(int peer, char *recvbuffer, ssize_t size)
519 {
520 	char *cp;
521 	int has_options = 0, ecode;
522 	char *filename, *mode;
523 	char fnbuf[PATH_MAX];
524 
525 	cp = parse_header(peer, recvbuffer, size, &filename, &mode);
526 	size -= (cp - recvbuffer) + 1;
527 
528 	strlcpy(fnbuf, filename, sizeof(fnbuf));
529 	reduce_path(fnbuf);
530 	filename = fnbuf;
531 
532 	if (size > 0) {
533 		if (options_rfc_enabled)
534 			has_options = !parse_options(peer, cp, size);
535 		else
536 			tftp_log(LOG_INFO, "Options found but not enabled");
537 	}
538 
539 	ecode = validate_access(peer, &filename, WRQ);
540 	if (ecode == 0) {
541 		if (has_options)
542 			send_oack(peer);
543 		else
544 			send_ack(peer, 0);
545 	}
546 	if (logging) {
547 		tftp_log(LOG_INFO, "%s: write request for %s: %s", peername,
548 			    filename, errtomsg(ecode));
549 	}
550 
551 	if (ecode) {
552 		send_error(peer, ecode);
553 		exit(1);
554 	}
555 	tftp_recvfile(peer, mode);
556 	exit(0);
557 }
558 
559 /*
560  * RRQ - send a file to the client
561  */
562 void
563 tftp_rrq(int peer, char *recvbuffer, ssize_t size)
564 {
565 	char *cp;
566 	int has_options = 0, ecode;
567 	char *filename, *mode;
568 	char	fnbuf[PATH_MAX];
569 
570 	cp = parse_header(peer, recvbuffer, size, &filename, &mode);
571 	size -= (cp - recvbuffer) + 1;
572 
573 	strlcpy(fnbuf, filename, sizeof(fnbuf));
574 	reduce_path(fnbuf);
575 	filename = fnbuf;
576 
577 	if (size > 0) {
578 		if (options_rfc_enabled)
579 			has_options = !parse_options(peer, cp, size);
580 		else
581 			tftp_log(LOG_INFO, "Options found but not enabled");
582 	}
583 
584 	ecode = validate_access(peer, &filename, RRQ);
585 	if (ecode == 0) {
586 		if (has_options) {
587 			int n;
588 			char lrecvbuffer[MAXPKTSIZE];
589 			struct tftphdr *rp = (struct tftphdr *)lrecvbuffer;
590 
591 			send_oack(peer);
592 			n = receive_packet(peer, lrecvbuffer, MAXPKTSIZE,
593 				NULL, timeoutpacket);
594 			if (n < 0) {
595 				if (debug&DEBUG_SIMPLE)
596 					tftp_log(LOG_DEBUG, "Aborting: %s",
597 					    rp_strerror(n));
598 				return;
599 			}
600 			if (rp->th_opcode != ACK) {
601 				if (debug&DEBUG_SIMPLE)
602 					tftp_log(LOG_DEBUG,
603 					    "Expected ACK, got %s on OACK",
604 					    packettype(rp->th_opcode));
605 				return;
606 			}
607 		}
608 	}
609 
610 	if (logging)
611 		tftp_log(LOG_INFO, "%s: read request for %s: %s", peername,
612 			    filename, errtomsg(ecode));
613 
614 	if (ecode) {
615 		/*
616 		 * Avoid storms of naks to a RRQ broadcast for a relative
617 		 * bootfile pathname from a diskless Sun.
618 		 */
619 		if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
620 			exit(0);
621 		send_error(peer, ecode);
622 		exit(1);
623 	}
624 	tftp_xmitfile(peer, mode);
625 }
626 
627 /*
628  * Find the next value for YYYYMMDD.nn when the file to be written should
629  * be unique. Due to the limitations of nn, we will fail if nn reaches 100.
630  * Besides, that is four updates per hour on a file, which is kind of
631  * execessive anyway.
632  */
633 static int
634 find_next_name(char *filename, int *fd)
635 {
636 	int i;
637 	time_t tval;
638 	size_t len;
639 	struct tm lt;
640 	char yyyymmdd[MAXPATHLEN];
641 	char newname[MAXPATHLEN];
642 
643 	/* Create the YYYYMMDD part of the filename */
644 	time(&tval);
645 	lt = *localtime(&tval);
646 	len = strftime(yyyymmdd, sizeof(yyyymmdd), newfile_format, &lt);
647 	if (len == 0) {
648 		syslog(LOG_WARNING,
649 			"Filename suffix too long (%d characters maximum)",
650 			MAXPATHLEN);
651 		return (EACCESS);
652 	}
653 
654 	/* Make sure the new filename is not too long */
655 	if (strlen(filename) > MAXPATHLEN - len - 5) {
656 		syslog(LOG_WARNING,
657 			"Filename too long (%zd characters, %zd maximum)",
658 			strlen(filename), MAXPATHLEN - len - 5);
659 		return (EACCESS);
660 	}
661 
662 	/* Find the first file which doesn't exist */
663 	for (i = 0; i < 100; i++) {
664 		sprintf(newname, "%s.%s.%02d", filename, yyyymmdd, i);
665 		*fd = open(newname,
666 		    O_WRONLY | O_CREAT | O_EXCL,
667 		    S_IRUSR | S_IWUSR | S_IRGRP |
668 		    S_IWGRP | S_IROTH | S_IWOTH);
669 		if (*fd > 0)
670 			return 0;
671 	}
672 
673 	return (EEXIST);
674 }
675 
676 /*
677  * Validate file access.  Since we
678  * have no uid or gid, for now require
679  * file to exist and be publicly
680  * readable/writable.
681  * If we were invoked with arguments
682  * from inetd then the file must also be
683  * in one of the given directory prefixes.
684  * Note also, full path name must be
685  * given as we have no login directory.
686  */
687 int
688 validate_access(int peer, char **filep, int mode)
689 {
690 	struct stat stbuf;
691 	int	fd;
692 	int	error;
693 	struct dirlist *dirp;
694 	static char pathname[MAXPATHLEN];
695 	char *filename = *filep;
696 
697 	/*
698 	 * Prevent tricksters from getting around the directory restrictions
699 	 */
700 	if (strstr(filename, "/../"))
701 		return (EACCESS);
702 
703 	if (*filename == '/') {
704 		/*
705 		 * Allow the request if it's in one of the approved locations.
706 		 * Special case: check the null prefix ("/") by looking
707 		 * for length = 1 and relying on the arg. processing that
708 		 * it's a /.
709 		 */
710 		for (dirp = dirs; dirp->name != NULL; dirp++) {
711 			if (dirp->len == 1 ||
712 			    (!strncmp(filename, dirp->name, dirp->len) &&
713 			     filename[dirp->len] == '/'))
714 				    break;
715 		}
716 		/* If directory list is empty, allow access to any file */
717 		if (dirp->name == NULL && dirp != dirs)
718 			return (EACCESS);
719 		if (stat(filename, &stbuf) < 0)
720 			return (errno == ENOENT ? ENOTFOUND : EACCESS);
721 		if ((stbuf.st_mode & S_IFMT) != S_IFREG)
722 			return (ENOTFOUND);
723 		if (mode == RRQ) {
724 			if ((stbuf.st_mode & S_IROTH) == 0)
725 				return (EACCESS);
726 		} else {
727 			if ((stbuf.st_mode & S_IWOTH) == 0)
728 				return (EACCESS);
729 		}
730 	} else {
731 		int err;
732 
733 		/*
734 		 * Relative file name: search the approved locations for it.
735 		 * Don't allow write requests that avoid directory
736 		 * restrictions.
737 		 */
738 
739 		if (!strncmp(filename, "../", 3))
740 			return (EACCESS);
741 
742 		/*
743 		 * If the file exists in one of the directories and isn't
744 		 * readable, continue looking. However, change the error code
745 		 * to give an indication that the file exists.
746 		 */
747 		err = ENOTFOUND;
748 		for (dirp = dirs; dirp->name != NULL; dirp++) {
749 			snprintf(pathname, sizeof(pathname), "%s/%s",
750 				dirp->name, filename);
751 			if (stat(pathname, &stbuf) == 0 &&
752 			    (stbuf.st_mode & S_IFMT) == S_IFREG) {
753 				if (mode == RRQ) {
754 					if ((stbuf.st_mode & S_IROTH) != 0)
755 						break;
756 				} else {
757 					if ((stbuf.st_mode & S_IWOTH) != 0)
758 						break;
759 				}
760 				err = EACCESS;
761 			}
762 		}
763 		if (dirp->name != NULL)
764 			*filep = filename = pathname;
765 		else if (mode == RRQ)
766 			return (err);
767 		else if (err != ENOTFOUND || !create_new)
768 			return (err);
769 	}
770 
771 	/*
772 	 * This option is handled here because it (might) require(s) the
773 	 * size of the file.
774 	 */
775 	option_tsize(peer, NULL, mode, &stbuf);
776 
777 	if (mode == RRQ)
778 		fd = open(filename, O_RDONLY);
779 	else {
780 		if (create_new) {
781 			if (increase_name) {
782 				error = find_next_name(filename, &fd);
783 				if (error > 0)
784 					return (error + 100);
785 			} else
786 				fd = open(filename,
787 				    O_WRONLY | O_TRUNC | O_CREAT,
788 				    S_IRUSR | S_IWUSR | S_IRGRP |
789 				    S_IWGRP | S_IROTH | S_IWOTH );
790 		} else
791 			fd = open(filename, O_WRONLY | O_TRUNC);
792 	}
793 	if (fd < 0)
794 		return (errno + 100);
795 	file = fdopen(fd, (mode == RRQ)? "r":"w");
796 	if (file == NULL) {
797 		close(fd);
798 		return (errno + 100);
799 	}
800 	return (0);
801 }
802 
803 static void
804 tftp_xmitfile(int peer, const char *mode)
805 {
806 	uint16_t block;
807 	time_t now;
808 	struct tftp_stats ts;
809 
810 	memset(&ts, 0, sizeof(ts));
811 	now = time(NULL);
812 	if (debug&DEBUG_SIMPLE)
813 		tftp_log(LOG_DEBUG, "Transmitting file");
814 
815 	read_init(0, file, mode);
816 	block = 1;
817 	tftp_send(peer, &block, &ts);
818 	read_close();
819 	if (debug&DEBUG_SIMPLE)
820 		tftp_log(LOG_INFO, "Sent %jd bytes in %jd seconds",
821 		    (intmax_t)ts.amount, (intmax_t)time(NULL) - now);
822 }
823 
824 static void
825 tftp_recvfile(int peer, const char *mode)
826 {
827 	uint16_t block;
828 	struct timeval now1, now2;
829 	struct tftp_stats ts;
830 
831 	gettimeofday(&now1, NULL);
832 	if (debug&DEBUG_SIMPLE)
833 		tftp_log(LOG_DEBUG, "Receiving file");
834 
835 	write_init(0, file, mode);
836 
837 	block = 0;
838 	tftp_receive(peer, &block, &ts, NULL, 0);
839 
840 	gettimeofday(&now2, NULL);
841 
842 	if (debug&DEBUG_SIMPLE) {
843 		double f;
844 		if (now1.tv_usec > now2.tv_usec) {
845 			now2.tv_usec += 1000000;
846 			now2.tv_sec--;
847 		}
848 
849 		f = now2.tv_sec - now1.tv_sec +
850 		    (now2.tv_usec - now1.tv_usec) / 100000.0;
851 		tftp_log(LOG_INFO,
852 		    "Download of %jd bytes in %d blocks completed after %0.1f seconds\n",
853 		    (intmax_t)ts.amount, block, f);
854 	}
855 
856 	return;
857 }
858