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