xref: /freebsd/libexec/tftpd/tftpd.c (revision 780fb4a2)
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 	} else if (tp->th_opcode == WRQ) {
425 		if (allow_wo)
426 			tftp_wrq(peer, tp->th_stuff, n - 1);
427 		else {
428 			tftp_log(LOG_WARNING,
429 			    "%s write access denied", peername);
430 			exit(1);
431 		}
432 	} else
433 		send_error(peer, EBADOP);
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 	if (ecode) {
549 		send_error(peer, ecode);
550 		exit(1);
551 	}
552 	tftp_recvfile(peer, mode);
553 	exit(0);
554 }
555 
556 /*
557  * RRQ - send a file to the client
558  */
559 void
560 tftp_rrq(int peer, char *recvbuffer, ssize_t size)
561 {
562 	char *cp;
563 	int has_options = 0, ecode;
564 	char *filename, *mode;
565 	char	fnbuf[PATH_MAX];
566 
567 	cp = parse_header(peer, recvbuffer, size, &filename, &mode);
568 	size -= (cp - recvbuffer) + 1;
569 
570 	strcpy(fnbuf, filename);
571 	reduce_path(fnbuf);
572 	filename = fnbuf;
573 
574 	if (size > 0) {
575 		if (options_rfc_enabled)
576 			has_options = !parse_options(peer, cp, size);
577 		else
578 			tftp_log(LOG_INFO, "Options found but not enabled");
579 	}
580 
581 	ecode = validate_access(peer, &filename, RRQ);
582 	if (ecode == 0) {
583 		if (has_options) {
584 			int n;
585 			char lrecvbuffer[MAXPKTSIZE];
586 			struct tftphdr *rp = (struct tftphdr *)lrecvbuffer;
587 
588 			send_oack(peer);
589 			n = receive_packet(peer, lrecvbuffer, MAXPKTSIZE,
590 				NULL, timeoutpacket);
591 			if (n < 0) {
592 				if (debug&DEBUG_SIMPLE)
593 					tftp_log(LOG_DEBUG, "Aborting: %s",
594 					    rp_strerror(n));
595 				return;
596 			}
597 			if (rp->th_opcode != ACK) {
598 				if (debug&DEBUG_SIMPLE)
599 					tftp_log(LOG_DEBUG,
600 					    "Expected ACK, got %s on OACK",
601 					    packettype(rp->th_opcode));
602 				return;
603 			}
604 		}
605 	}
606 
607 	if (logging)
608 		tftp_log(LOG_INFO, "%s: read request for %s: %s", peername,
609 			    filename, errtomsg(ecode));
610 
611 	if (ecode) {
612 		/*
613 		 * Avoid storms of naks to a RRQ broadcast for a relative
614 		 * bootfile pathname from a diskless Sun.
615 		 */
616 		if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
617 			exit(0);
618 		send_error(peer, ecode);
619 		exit(1);
620 	}
621 	tftp_xmitfile(peer, mode);
622 }
623 
624 /*
625  * Find the next value for YYYYMMDD.nn when the file to be written should
626  * be unique. Due to the limitations of nn, we will fail if nn reaches 100.
627  * Besides, that is four updates per hour on a file, which is kind of
628  * execessive anyway.
629  */
630 static int
631 find_next_name(char *filename, int *fd)
632 {
633 	int i;
634 	time_t tval;
635 	size_t len;
636 	struct tm lt;
637 	char yyyymmdd[MAXPATHLEN];
638 	char newname[MAXPATHLEN];
639 
640 	/* Create the YYYYMMDD part of the filename */
641 	time(&tval);
642 	lt = *localtime(&tval);
643 	len = strftime(yyyymmdd, sizeof(yyyymmdd), newfile_format, &lt);
644 	if (len == 0) {
645 		syslog(LOG_WARNING,
646 			"Filename suffix too long (%d characters maximum)",
647 			MAXPATHLEN);
648 		return (EACCESS);
649 	}
650 
651 	/* Make sure the new filename is not too long */
652 	if (strlen(filename) > MAXPATHLEN - len - 5) {
653 		syslog(LOG_WARNING,
654 			"Filename too long (%zd characters, %zd maximum)",
655 			strlen(filename), MAXPATHLEN - len - 5);
656 		return (EACCESS);
657 	}
658 
659 	/* Find the first file which doesn't exist */
660 	for (i = 0; i < 100; i++) {
661 		sprintf(newname, "%s.%s.%02d", filename, yyyymmdd, i);
662 		*fd = open(newname,
663 		    O_WRONLY | O_CREAT | O_EXCL,
664 		    S_IRUSR | S_IWUSR | S_IRGRP |
665 		    S_IWGRP | S_IROTH | S_IWOTH);
666 		if (*fd > 0)
667 			return 0;
668 	}
669 
670 	return (EEXIST);
671 }
672 
673 /*
674  * Validate file access.  Since we
675  * have no uid or gid, for now require
676  * file to exist and be publicly
677  * readable/writable.
678  * If we were invoked with arguments
679  * from inetd then the file must also be
680  * in one of the given directory prefixes.
681  * Note also, full path name must be
682  * given as we have no login directory.
683  */
684 int
685 validate_access(int peer, char **filep, int mode)
686 {
687 	struct stat stbuf;
688 	int	fd;
689 	int	error;
690 	struct dirlist *dirp;
691 	static char pathname[MAXPATHLEN];
692 	char *filename = *filep;
693 
694 	/*
695 	 * Prevent tricksters from getting around the directory restrictions
696 	 */
697 	if (strstr(filename, "/../"))
698 		return (EACCESS);
699 
700 	if (*filename == '/') {
701 		/*
702 		 * Allow the request if it's in one of the approved locations.
703 		 * Special case: check the null prefix ("/") by looking
704 		 * for length = 1 and relying on the arg. processing that
705 		 * it's a /.
706 		 */
707 		for (dirp = dirs; dirp->name != NULL; dirp++) {
708 			if (dirp->len == 1 ||
709 			    (!strncmp(filename, dirp->name, dirp->len) &&
710 			     filename[dirp->len] == '/'))
711 				    break;
712 		}
713 		/* If directory list is empty, allow access to any file */
714 		if (dirp->name == NULL && dirp != dirs)
715 			return (EACCESS);
716 		if (stat(filename, &stbuf) < 0)
717 			return (errno == ENOENT ? ENOTFOUND : EACCESS);
718 		if ((stbuf.st_mode & S_IFMT) != S_IFREG)
719 			return (ENOTFOUND);
720 		if (mode == RRQ) {
721 			if ((stbuf.st_mode & S_IROTH) == 0)
722 				return (EACCESS);
723 		} else {
724 			if ((stbuf.st_mode & S_IWOTH) == 0)
725 				return (EACCESS);
726 		}
727 	} else {
728 		int err;
729 
730 		/*
731 		 * Relative file name: search the approved locations for it.
732 		 * Don't allow write requests that avoid directory
733 		 * restrictions.
734 		 */
735 
736 		if (!strncmp(filename, "../", 3))
737 			return (EACCESS);
738 
739 		/*
740 		 * If the file exists in one of the directories and isn't
741 		 * readable, continue looking. However, change the error code
742 		 * to give an indication that the file exists.
743 		 */
744 		err = ENOTFOUND;
745 		for (dirp = dirs; dirp->name != NULL; dirp++) {
746 			snprintf(pathname, sizeof(pathname), "%s/%s",
747 				dirp->name, filename);
748 			if (stat(pathname, &stbuf) == 0 &&
749 			    (stbuf.st_mode & S_IFMT) == S_IFREG) {
750 				if (mode == RRQ) {
751 					if ((stbuf.st_mode & S_IROTH) != 0)
752 						break;
753 				} else {
754 					if ((stbuf.st_mode & S_IWOTH) != 0)
755 						break;
756 				}
757 				err = EACCESS;
758 			}
759 		}
760 		if (dirp->name != NULL)
761 			*filep = filename = pathname;
762 		else if (mode == RRQ)
763 			return (err);
764 		else if (err != ENOTFOUND || !create_new)
765 			return (err);
766 	}
767 
768 	/*
769 	 * This option is handled here because it (might) require(s) the
770 	 * size of the file.
771 	 */
772 	option_tsize(peer, NULL, mode, &stbuf);
773 
774 	if (mode == RRQ)
775 		fd = open(filename, O_RDONLY);
776 	else {
777 		if (create_new) {
778 			if (increase_name) {
779 				error = find_next_name(filename, &fd);
780 				if (error > 0)
781 					return (error + 100);
782 			} else
783 				fd = open(filename,
784 				    O_WRONLY | O_TRUNC | O_CREAT,
785 				    S_IRUSR | S_IWUSR | S_IRGRP |
786 				    S_IWGRP | S_IROTH | S_IWOTH );
787 		} else
788 			fd = open(filename, O_WRONLY | O_TRUNC);
789 	}
790 	if (fd < 0)
791 		return (errno + 100);
792 	file = fdopen(fd, (mode == RRQ)? "r":"w");
793 	if (file == NULL) {
794 		close(fd);
795 		return (errno + 100);
796 	}
797 	return (0);
798 }
799 
800 static void
801 tftp_xmitfile(int peer, const char *mode)
802 {
803 	uint16_t block;
804 	time_t now;
805 	struct tftp_stats ts;
806 
807 	now = time(NULL);
808 	if (debug&DEBUG_SIMPLE)
809 		tftp_log(LOG_DEBUG, "Transmitting file");
810 
811 	read_init(0, file, mode);
812 	block = 1;
813 	tftp_send(peer, &block, &ts);
814 	read_close();
815 	if (debug&DEBUG_SIMPLE)
816 		tftp_log(LOG_INFO, "Sent %jd bytes in %jd seconds",
817 		    (intmax_t)ts.amount, (intmax_t)time(NULL) - now);
818 }
819 
820 static void
821 tftp_recvfile(int peer, const char *mode)
822 {
823 	uint16_t block;
824 	struct timeval now1, now2;
825 	struct tftp_stats ts;
826 
827 	gettimeofday(&now1, NULL);
828 	if (debug&DEBUG_SIMPLE)
829 		tftp_log(LOG_DEBUG, "Receiving file");
830 
831 	write_init(0, file, mode);
832 
833 	block = 0;
834 	tftp_receive(peer, &block, &ts, NULL, 0);
835 
836 	gettimeofday(&now2, NULL);
837 
838 	if (debug&DEBUG_SIMPLE) {
839 		double f;
840 		if (now1.tv_usec > now2.tv_usec) {
841 			now2.tv_usec += 1000000;
842 			now2.tv_sec--;
843 		}
844 
845 		f = now2.tv_sec - now1.tv_sec +
846 		    (now2.tv_usec - now1.tv_usec) / 100000.0;
847 		tftp_log(LOG_INFO,
848 		    "Download of %jd bytes in %d blocks completed after %0.1f seconds\n",
849 		    (intmax_t)ts.amount, block, f);
850 	}
851 
852 	return;
853 }
854