]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - libexec/tftpd/tftpd.c
MFC: r262136
[FreeBSD/stable/10.git] / libexec / tftpd / tftpd.c
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. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29
30 #ifndef lint
31 static const char copyright[] =
32 "@(#) Copyright (c) 1983, 1993\n\
33         The Regents of the University of California.  All rights reserved.\n";
34 #endif /* not lint */
35
36 #ifndef lint
37 #if 0
38 static char sccsid[] = "@(#)tftpd.c     8.1 (Berkeley) 6/4/93";
39 #endif
40 #endif /* not lint */
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43
44 /*
45  * Trivial file transfer protocol server.
46  *
47  * This version includes many modifications by Jim Guyton
48  * <guyton@rand-unix>.
49  */
50
51 #include <sys/param.h>
52 #include <sys/ioctl.h>
53 #include <sys/stat.h>
54 #include <sys/socket.h>
55
56 #include <netinet/in.h>
57 #include <arpa/tftp.h>
58
59 #include <ctype.h>
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <netdb.h>
63 #include <pwd.h>
64 #include <stdint.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <syslog.h>
69 #include <tcpd.h>
70 #include <unistd.h>
71
72 #include "tftp-file.h"
73 #include "tftp-io.h"
74 #include "tftp-utils.h"
75 #include "tftp-transfer.h"
76 #include "tftp-options.h"
77
78 static void     tftp_wrq(int peer, char *, ssize_t);
79 static void     tftp_rrq(int peer, char *, ssize_t);
80
81 /*
82  * Null-terminated directory prefix list for absolute pathname requests and
83  * search list for relative pathname requests.
84  *
85  * MAXDIRS should be at least as large as the number of arguments that
86  * inetd allows (currently 20).
87  */
88 #define MAXDIRS 20
89 static struct dirlist {
90         const char      *name;
91         int     len;
92 } dirs[MAXDIRS+1];
93 static int      suppress_naks;
94 static int      logging;
95 static int      ipchroot;
96 static int      create_new = 0;
97 static const char *newfile_format = "%Y%m%d";
98 static int      increase_name = 0;
99 static mode_t   mask = S_IWGRP | S_IWOTH;
100
101 struct formats;
102 static void     tftp_recvfile(int peer, const char *mode);
103 static void     tftp_xmitfile(int peer, const char *mode);
104 static int      validate_access(int peer, char **, int);
105 static char     peername[NI_MAXHOST];
106
107 static FILE *file;
108
109 static struct formats {
110         const char      *f_mode;
111         int     f_convert;
112 } formats[] = {
113         { "netascii",   1 },
114         { "octet",      0 },
115         { NULL,         0 }
116 };
117
118 int
119 main(int argc, char *argv[])
120 {
121         struct tftphdr *tp;
122         int             peer;
123         socklen_t       peerlen, len;
124         ssize_t         n;
125         int             ch;
126         char            *chroot_dir = NULL;
127         struct passwd   *nobody;
128         const char      *chuser = "nobody";
129         char            recvbuffer[MAXPKTSIZE];
130         int             allow_ro = 1, allow_wo = 1;
131
132         tzset();                        /* syslog in localtime */
133         acting_as_client = 0;
134
135         tftp_openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
136         while ((ch = getopt(argc, argv, "cCd:F:lnoOp:s:u:U:wW")) != -1) {
137                 switch (ch) {
138                 case 'c':
139                         ipchroot = 1;
140                         break;
141                 case 'C':
142                         ipchroot = 2;
143                         break;
144                 case 'd':
145                         if (atoi(optarg) != 0)
146                                 debug += atoi(optarg);
147                         else
148                                 debug |= debug_finds(optarg);
149                         break;
150                 case 'F':
151                         newfile_format = optarg;
152                         break;
153                 case 'l':
154                         logging = 1;
155                         break;
156                 case 'n':
157                         suppress_naks = 1;
158                         break;
159                 case 'o':
160                         options_rfc_enabled = 0;
161                         break;
162                 case 'O':
163                         options_extra_enabled = 0;
164                         break;
165                 case 'p':
166                         packetdroppercentage = atoi(optarg);
167                         tftp_log(LOG_INFO,
168                             "Randomly dropping %d out of 100 packets",
169                             packetdroppercentage);
170                         break;
171                 case 's':
172                         chroot_dir = optarg;
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         {
217                 int on = 1;
218                 if (ioctl(0, FIONBIO, &on) < 0) {
219                         tftp_log(LOG_ERR, "ioctl(FIONBIO): %s", strerror(errno));
220                         exit(1);
221                 }
222         }
223
224         /* Find out who we are talking to and what we are going to do */
225         peerlen = sizeof(peer_sock);
226         n = recvfrom(0, recvbuffer, MAXPKTSIZE, 0,
227             (struct sockaddr *)&peer_sock, &peerlen);
228         if (n < 0) {
229                 tftp_log(LOG_ERR, "recvfrom: %s", strerror(errno));
230                 exit(1);
231         }
232         getnameinfo((struct sockaddr *)&peer_sock, peer_sock.ss_len,
233             peername, sizeof(peername), NULL, 0, NI_NUMERICHOST);
234
235         /*
236          * Now that we have read the message out of the UDP
237          * socket, we fork and exit.  Thus, inetd will go back
238          * to listening to the tftp port, and the next request
239          * to come in will start up a new instance of tftpd.
240          *
241          * We do this so that inetd can run tftpd in "wait" mode.
242          * The problem with tftpd running in "nowait" mode is that
243          * inetd may get one or more successful "selects" on the
244          * tftp port before we do our receive, so more than one
245          * instance of tftpd may be started up.  Worse, if tftpd
246          * break before doing the above "recvfrom", inetd would
247          * spawn endless instances, clogging the system.
248          */
249         {
250                 int i, pid;
251
252                 for (i = 1; i < 20; i++) {
253                     pid = fork();
254                     if (pid < 0) {
255                                 sleep(i);
256                                 /*
257                                  * flush out to most recently sent request.
258                                  *
259                                  * This may drop some request, but those
260                                  * will be resent by the clients when
261                                  * they timeout.  The positive effect of
262                                  * this flush is to (try to) prevent more
263                                  * than one tftpd being started up to service
264                                  * a single request from a single client.
265                                  */
266                                 peerlen = sizeof peer_sock;
267                                 i = recvfrom(0, recvbuffer, MAXPKTSIZE, 0,
268                                     (struct sockaddr *)&peer_sock, &peerlen);
269                                 if (i > 0) {
270                                         n = i;
271                                 }
272                     } else {
273                                 break;
274                     }
275                 }
276                 if (pid < 0) {
277                         tftp_log(LOG_ERR, "fork: %s", strerror(errno));
278                         exit(1);
279                 } else if (pid != 0) {
280                         exit(0);
281                 }
282         }
283
284         /*
285          * See if the client is allowed to talk to me.
286          * (This needs to be done before the chroot())
287          */
288         {
289                 struct request_info req;
290
291                 request_init(&req, RQ_CLIENT_ADDR, peername, 0);
292                 request_set(&req, RQ_DAEMON, "tftpd", 0);
293
294                 if (hosts_access(&req) == 0) {
295                         if (debug&DEBUG_ACCESS)
296                                 tftp_log(LOG_WARNING,
297                                     "Access denied by 'tftpd' entry "
298                                     "in /etc/hosts.allow");
299
300                         /*
301                          * Full access might be disabled, but maybe the
302                          * client is allowed to do read-only access.
303                          */
304                         request_set(&req, RQ_DAEMON, "tftpd-ro", 0);
305                         allow_ro = hosts_access(&req);
306
307                         request_set(&req, RQ_DAEMON, "tftpd-wo", 0);
308                         allow_wo = hosts_access(&req);
309
310                         if (allow_ro == 0 && allow_wo == 0) {
311                                 tftp_log(LOG_WARNING,
312                                     "Unauthorized access from %s", peername);
313                                 exit(1);
314                         }
315
316                         if (debug&DEBUG_ACCESS) {
317                                 if (allow_ro)
318                                         tftp_log(LOG_WARNING,
319                                             "But allowed readonly access "
320                                             "via 'tftpd-ro' entry");
321                                 if (allow_wo)
322                                         tftp_log(LOG_WARNING,
323                                             "But allowed writeonly access "
324                                             "via 'tftpd-wo' entry");
325                         }
326                 } else
327                         if (debug&DEBUG_ACCESS)
328                                 tftp_log(LOG_WARNING,
329                                     "Full access allowed"
330                                     "in /etc/hosts.allow");
331         }
332
333         /*
334          * Since we exit here, we should do that only after the above
335          * recvfrom to keep inetd from constantly forking should there
336          * be a problem.  See the above comment about system clogging.
337          */
338         if (chroot_dir) {
339                 if (ipchroot > 0) {
340                         char *tempchroot;
341                         struct stat sb;
342                         int statret;
343                         struct sockaddr_storage ss;
344                         char hbuf[NI_MAXHOST];
345
346                         statret = -1;
347                         memcpy(&ss, &peer_sock, peer_sock.ss_len);
348                         unmappedaddr((struct sockaddr_in6 *)&ss);
349                         getnameinfo((struct sockaddr *)&ss, ss.ss_len,
350                                     hbuf, sizeof(hbuf), NULL, 0,
351                                     NI_NUMERICHOST);
352                         asprintf(&tempchroot, "%s/%s", chroot_dir, hbuf);
353                         if (ipchroot == 2)
354                                 statret = stat(tempchroot, &sb);
355                         if (ipchroot == 1 ||
356                             (statret == 0 && (sb.st_mode & S_IFDIR)))
357                                 chroot_dir = tempchroot;
358                 }
359                 /* Must get this before chroot because /etc might go away */
360                 if ((nobody = getpwnam(chuser)) == NULL) {
361                         tftp_log(LOG_ERR, "%s: no such user", chuser);
362                         exit(1);
363                 }
364                 if (chroot(chroot_dir)) {
365                         tftp_log(LOG_ERR, "chroot: %s: %s",
366                             chroot_dir, strerror(errno));
367                         exit(1);
368                 }
369                 chdir("/");
370                 setgroups(1, &nobody->pw_gid);
371                 if (setuid(nobody->pw_uid) != 0) {
372                         tftp_log(LOG_ERR, "setuid failed");
373                         exit(1);
374                 }
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                 send_error(peer, ecode);
608                 exit(1);
609         }
610         tftp_xmitfile(peer, mode);
611 }
612
613 /*
614  * Find the next value for YYYYMMDD.nn when the file to be written should
615  * be unique. Due to the limitations of nn, we will fail if nn reaches 100.
616  * Besides, that is four updates per hour on a file, which is kind of
617  * execessive anyway.
618  */
619 static int
620 find_next_name(char *filename, int *fd)
621 {
622         int i;
623         time_t tval;
624         size_t len;
625         struct tm lt;
626         char yyyymmdd[MAXPATHLEN];
627         char newname[MAXPATHLEN];
628
629         /* Create the YYYYMMDD part of the filename */
630         time(&tval);
631         lt = *localtime(&tval);
632         len = strftime(yyyymmdd, sizeof(yyyymmdd), newfile_format, &lt);
633         if (len == 0) {
634                 syslog(LOG_WARNING,
635                         "Filename suffix too long (%d characters maximum)",
636                         MAXPATHLEN);
637                 return (EACCESS);
638         }
639
640         /* Make sure the new filename is not too long */
641         if (strlen(filename) > MAXPATHLEN - len - 5) {
642                 syslog(LOG_WARNING,
643                         "Filename too long (%zd characters, %zd maximum)",
644                         strlen(filename), MAXPATHLEN - len - 5);
645                 return (EACCESS);
646         }
647
648         /* Find the first file which doesn't exist */
649         for (i = 0; i < 100; i++) {
650                 sprintf(newname, "%s.%s.%02d", filename, yyyymmdd, i);
651                 *fd = open(newname,
652                     O_WRONLY | O_CREAT | O_EXCL, 
653                     S_IRUSR | S_IWUSR | S_IRGRP |
654                     S_IWGRP | S_IROTH | S_IWOTH);
655                 if (*fd > 0)
656                         return 0;
657         }
658
659         return (EEXIST);
660 }
661
662 /*
663  * Validate file access.  Since we
664  * have no uid or gid, for now require
665  * file to exist and be publicly
666  * readable/writable.
667  * If we were invoked with arguments
668  * from inetd then the file must also be
669  * in one of the given directory prefixes.
670  * Note also, full path name must be
671  * given as we have no login directory.
672  */
673 int
674 validate_access(int peer, char **filep, int mode)
675 {
676         struct stat stbuf;
677         int     fd;
678         int     error;
679         struct dirlist *dirp;
680         static char pathname[MAXPATHLEN];
681         char *filename = *filep;
682
683         /*
684          * Prevent tricksters from getting around the directory restrictions
685          */
686         if (strstr(filename, "/../"))
687                 return (EACCESS);
688
689         if (*filename == '/') {
690                 /*
691                  * Allow the request if it's in one of the approved locations.
692                  * Special case: check the null prefix ("/") by looking
693                  * for length = 1 and relying on the arg. processing that
694                  * it's a /.
695                  */
696                 for (dirp = dirs; dirp->name != NULL; dirp++) {
697                         if (dirp->len == 1 ||
698                             (!strncmp(filename, dirp->name, dirp->len) &&
699                              filename[dirp->len] == '/'))
700                                     break;
701                 }
702                 /* If directory list is empty, allow access to any file */
703                 if (dirp->name == NULL && dirp != dirs)
704                         return (EACCESS);
705                 if (stat(filename, &stbuf) < 0)
706                         return (errno == ENOENT ? ENOTFOUND : EACCESS);
707                 if ((stbuf.st_mode & S_IFMT) != S_IFREG)
708                         return (ENOTFOUND);
709                 if (mode == RRQ) {
710                         if ((stbuf.st_mode & S_IROTH) == 0)
711                                 return (EACCESS);
712                 } else {
713                         if ((stbuf.st_mode & S_IWOTH) == 0)
714                                 return (EACCESS);
715                 }
716         } else {
717                 int err;
718
719                 /*
720                  * Relative file name: search the approved locations for it.
721                  * Don't allow write requests that avoid directory
722                  * restrictions.
723                  */
724
725                 if (!strncmp(filename, "../", 3))
726                         return (EACCESS);
727
728                 /*
729                  * If the file exists in one of the directories and isn't
730                  * readable, continue looking. However, change the error code
731                  * to give an indication that the file exists.
732                  */
733                 err = ENOTFOUND;
734                 for (dirp = dirs; dirp->name != NULL; dirp++) {
735                         snprintf(pathname, sizeof(pathname), "%s/%s",
736                                 dirp->name, filename);
737                         if (stat(pathname, &stbuf) == 0 &&
738                             (stbuf.st_mode & S_IFMT) == S_IFREG) {
739                                 if ((stbuf.st_mode & S_IROTH) != 0) {
740                                         break;
741                                 }
742                                 err = EACCESS;
743                         }
744                 }
745                 if (dirp->name != NULL)
746                         *filep = filename = pathname;
747                 else if (mode == RRQ)
748                         return (err);
749         }
750
751         /*
752          * This option is handled here because it (might) require(s) the
753          * size of the file.
754          */
755         option_tsize(peer, NULL, mode, &stbuf);
756
757         if (mode == RRQ)
758                 fd = open(filename, O_RDONLY);
759         else {
760                 if (create_new) {
761                         if (increase_name) {
762                                 error = find_next_name(filename, &fd);
763                                 if (error > 0)
764                                         return (error + 100);
765                         } else
766                                 fd = open(filename,
767                                     O_WRONLY | O_TRUNC | O_CREAT, 
768                                     S_IRUSR | S_IWUSR | S_IRGRP | 
769                                     S_IWGRP | S_IROTH | S_IWOTH );
770                 } else
771                         fd = open(filename, O_WRONLY | O_TRUNC);
772         }
773         if (fd < 0)
774                 return (errno + 100);
775         file = fdopen(fd, (mode == RRQ)? "r":"w");
776         if (file == NULL) {
777                 close(fd);
778                 return (errno + 100);
779         }
780         return (0);
781 }
782
783 static void
784 tftp_xmitfile(int peer, const char *mode)
785 {
786         uint16_t block;
787         time_t now;
788         struct tftp_stats ts;
789
790         now = time(NULL);
791         if (debug&DEBUG_SIMPLE)
792                 tftp_log(LOG_DEBUG, "Transmitting file");
793
794         read_init(0, file, mode);
795         block = 1;
796         tftp_send(peer, &block, &ts);
797         read_close();
798         if (debug&DEBUG_SIMPLE)
799                 tftp_log(LOG_INFO, "Sent %jd bytes in %jd seconds",
800                     (intmax_t)ts.amount, (intmax_t)time(NULL) - now);
801 }
802
803 static void
804 tftp_recvfile(int peer, const char *mode)
805 {
806         uint16_t block;
807         struct timeval now1, now2;
808         struct tftp_stats ts;
809
810         gettimeofday(&now1, NULL);
811         if (debug&DEBUG_SIMPLE)
812                 tftp_log(LOG_DEBUG, "Receiving file");
813
814         write_init(0, file, mode);
815
816         block = 0;
817         tftp_receive(peer, &block, &ts, NULL, 0);
818
819         write_close();
820         gettimeofday(&now2, NULL);
821
822         if (debug&DEBUG_SIMPLE) {
823                 double f;
824                 if (now1.tv_usec > now2.tv_usec) {
825                         now2.tv_usec += 1000000;
826                         now2.tv_sec--;
827                 }
828
829                 f = now2.tv_sec - now1.tv_sec +
830                     (now2.tv_usec - now1.tv_usec) / 100000.0;
831                 tftp_log(LOG_INFO,
832                     "Download of %jd bytes in %d blocks completed after %0.1f seconds\n",
833                     (intmax_t)ts.amount, block, f);
834         }
835
836         return;
837 }