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