Actually allow tests of the release mechanism...
[tftp-hpa.git] / tftpd / tftpd.c
blob24fe904aa34d18664e74592d18089497ef0045ab
1 /* tftp-hpa: $Id$ */
3 /* $OpenBSD: tftpd.c,v 1.13 1999/06/23 17:01:36 deraadt Exp $ */
5 /*
6 * Copyright (c) 1983 Regents of the University of California.
7 * All rights reserved.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed by the University of
20 * California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * SUCH DAMAGE.
38 #include "config.h" /* Must be included first */
39 #include "tftpd.h"
41 #ifndef lint
42 static const char *copyright UNUSED =
43 "@(#) Copyright (c) 1983 Regents of the University of California.\n\
44 All rights reserved.\n";
45 /*static char sccsid[] = "from: @(#)tftpd.c 5.13 (Berkeley) 2/26/91";*/
46 /*static char rcsid[] = "$OpenBSD: tftpd.c,v 1.13 1999/06/23 17:01:36 deraadt Exp $: tftpd.c,v 1.6 1997/02/16 23:49:21 deraadt Exp $";*/
47 static const char *rcsid UNUSED =
48 "tftp-hpa $Id$";
49 #endif /* not lint */
52 * Trivial file transfer protocol server.
54 * This version includes many modifications by Jim Guyton <guyton@rand-unix>
57 #include <sys/ioctl.h>
58 #include <signal.h>
59 #include <netdb.h>
60 #include <ctype.h>
61 #include <pwd.h>
62 #include <limits.h>
63 #include <syslog.h>
65 #include "tftpsubs.h"
66 #include "recvfrom.h"
67 #include "remap.h"
69 #ifdef HAVE_SYS_FILIO_H
70 #include <sys/filio.h> /* Necessary for FIONBIO on Solaris */
71 #endif
73 #ifdef HAVE_TCPWRAPPERS
74 #include <tcpd.h>
76 int deny_severity = LOG_WARNING;
77 int allow_severity = -1; /* Don't log at all */
79 struct request_info wrap_request;
80 #endif
82 #define TIMEOUT 1000000 /* Default timeout (us) */
83 #define TRIES 6 /* Number of attempts to send each packet */
84 #define TIMEOUT_LIMIT ((1 << TRIES)-1)
86 const char *__progname;
87 int peer;
88 unsigned long timeout = TIMEOUT; /* Current timeout value */
89 unsigned long rexmtval = TIMEOUT; /* Basic timeout value */
90 unsigned long maxtimeout = TIMEOUT_LIMIT*TIMEOUT;
91 int timeout_quit = 0;
92 sigjmp_buf timeoutbuf;
94 #define PKTSIZE MAX_SEGSIZE+4
95 char buf[PKTSIZE];
96 char ackbuf[PKTSIZE];
97 unsigned int max_blksize = MAX_SEGSIZE;
99 struct sockaddr_in from;
100 int fromlen;
101 off_t tsize;
102 int tsize_ok;
104 int ndirs;
105 const char **dirs;
107 int secure = 0;
108 int cancreate = 0;
109 int unixperms = 0;
110 int portrange = 0;
111 unsigned int portrange_from, portrange_to;
112 int verbosity = 0;
114 struct formats;
115 #ifdef WITH_REGEX
116 static struct rule *rewrite_rules = NULL;
117 #endif
119 int tftp(struct tftphdr *, int);
120 static void nak(int, const char *);
121 void timer(int);
122 void justquit(int);
123 void do_opt(char *, char *, char **);
125 int set_blksize(char *, char **);
126 int set_blksize2(char *, char **);
127 int set_tsize(char *, char **);
128 int set_timeout(char *, char **);
129 int set_utimeout(char *, char **);
131 struct options {
132 const char *o_opt;
133 int (*o_fnc)(char *, char **);
134 } options[] = {
135 { "blksize", set_blksize },
136 { "blksize2", set_blksize2 },
137 { "tsize", set_tsize },
138 { "timeout", set_timeout },
139 { "utimeout", set_utimeout },
140 { NULL, NULL }
143 /* Simple handler for SIGHUP */
144 static volatile sig_atomic_t caught_sighup = 0;
145 static void handle_sighup(int sig)
147 (void)sig; /* Suppress unused warning */
148 caught_sighup = 1;
152 /* Handle timeout signal or timeout event */
153 void
154 timer(int sig)
156 (void)sig; /* Suppress unused warning */
157 timeout <<= 1;
158 if (timeout >= maxtimeout || timeout_quit)
159 exit(0);
160 siglongjmp(timeoutbuf, 1);
163 static void
164 usage(void)
166 syslog(LOG_ERR, "Usage: %s [-vcl][-a address][-m mappings][-u user][-t inetd_timeout][-T pkt_timeout][-r option...] [-s] [directory ...]",
167 __progname);
168 exit(EX_USAGE);
172 #ifdef WITH_REGEX
173 static struct rule *
174 read_remap_rules(const char *file)
176 FILE *f;
177 struct rule *rulep;
179 f = fopen(file, "rt");
180 if ( !f ) {
181 syslog(LOG_ERR, "Cannot open map file: %s: %m", file);
182 exit(EX_NOINPUT);
184 rulep = parserulefile(f);
185 fclose(f);
187 return rulep;
189 #endif
191 static void
192 set_socket_nonblock(int fd, int flag)
194 int err;
195 int flags;
196 #if defined(HAVE_FCNTL) && defined(HAVE_O_NONBLOCK_DEFINITION)
197 /* Posixly correct */
198 err = ((flags = fcntl(fd, F_GETFL, 0)) < 0) ||
199 (fcntl(fd, F_SETFL, flag ? flags|O_NONBLOCK : flags&~O_NONBLOCK) < 0);
200 #else
201 flags = flag ? 1 : 0;
202 err = (ioctl(fd, FIONBIO, &flags) < 0);
203 #endif
204 if ( err ) {
205 syslog(LOG_ERR, "Cannot set nonblock flag on socket: %m");
206 exit(EX_OSERR);
210 static void
211 pmtu_discovery_off(int fd)
213 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
214 int pmtu = IP_PMTUDISC_DONT;
216 setsockopt(fd, IPPROTO_IP, IP_MTU_DISCOVER, &pmtu, sizeof(pmtu));
217 #endif
221 * Receive packet with synchronous timeout; timeout is adjusted
222 * to account for time spent waiting.
224 static int recv_time(int s, void *rbuf, int len, unsigned int flags,
225 unsigned long *timeout_us_p)
227 fd_set fdset;
228 struct timeval tmv, t0, t1;
229 int rv, err;
230 unsigned long timeout_us = *timeout_us_p;
231 unsigned long timeout_left, dt;
233 gettimeofday(&t0, NULL);
234 timeout_left = timeout_us;
236 for ( ; ; ) {
237 FD_ZERO(&fdset);
238 FD_SET(s, &fdset);
240 do {
241 tmv.tv_sec = timeout_left / 1000000;
242 tmv.tv_usec = timeout_left % 1000000;
244 rv = select(s+1, &fdset, NULL, NULL, &tmv);
245 err = errno;
247 gettimeofday(&t1, NULL);
249 dt = (t1.tv_sec - t0.tv_sec)*1000000 + (t1.tv_usec - t0.tv_usec);
250 *timeout_us_p = timeout_left = ( dt >= timeout_us ) ? 1 : (timeout_us - dt);
251 } while ( rv == -1 && err == EINTR );
253 if ( rv == 0 ) {
254 timer(0); /* Should not return */
255 return -1;
258 set_socket_nonblock(s, 1);
259 rv = recv(s, rbuf, len, flags);
260 err = errno;
261 set_socket_nonblock(s, 0);
263 if ( rv < 0 ) {
264 if ( E_WOULD_BLOCK(err) || err == EINTR ) {
265 continue; /* Once again, with feeling... */
266 } else {
267 errno = err;
268 return rv;
270 } else {
271 return rv;
276 static int
277 pick_port_bind(int sockfd, struct sockaddr_in *myaddr)
279 unsigned int port, firstport;
281 firstport = portrange
282 ? portrange_from + rand() % (portrange_to-portrange_from+1)
283 : 0;
285 port = firstport;
287 do {
288 myaddr->sin_port = htons(port);
290 if (bind(sockfd, (struct sockaddr *)myaddr, sizeof *myaddr) < 0) {
291 /* Some versions of Linux return EINVAL instead of EADDRINUSE */
292 if ( !(portrange && (errno == EINVAL || errno == EADDRINUSE)) )
293 return -1;
295 /* Normally, we shouldn't have to loop, but some situations involving
296 aborted transfers make it possible. */
297 } else {
298 return 0;
301 port++;
302 if ( port > portrange_to )
303 port = portrange_from;
304 } while ( port != firstport );
306 return -1;
310 main(int argc, char **argv)
312 struct tftphdr *tp;
313 struct passwd *pw;
314 struct options *opt;
315 struct sockaddr_in myaddr;
316 struct sockaddr_in bindaddr;
317 int n;
318 int fd = 0;
319 int standalone = 0; /* Standalone (listen) mode */
320 char *address = NULL; /* Address to listen to */
321 pid_t pid;
322 mode_t my_umask = 0;
323 int spec_umask = 0;
324 int c;
325 int setrv;
326 int waittime = 900; /* Default time to wait for a connect*/
327 const char *user = "nobody"; /* Default user */
328 char *p, *ep;
329 #ifdef WITH_REGEX
330 char *rewrite_file = NULL;
331 #endif
332 u_short tp_opcode;
334 /* basename() is way too much of a pain from a portability standpoint */
336 p = strrchr(argv[0], '/');
337 __progname = (p && p[1]) ? p+1 : argv[0];
339 openlog(__progname, LOG_PID|LOG_NDELAY, LOG_DAEMON);
341 srand(time(NULL) ^ getpid());
343 while ((c = getopt(argc, argv, "cspvVla:B:u:U:r:t:T:R:m:")) != -1)
344 switch (c) {
345 case 'c':
346 cancreate = 1;
347 break;
348 case 's':
349 secure = 1;
350 break;
351 case 'p':
352 unixperms = 1;
353 break;
354 case 'l':
355 standalone = 1;
356 break;
357 case 'a':
358 address = optarg;
359 break;
360 case 't':
361 waittime = atoi(optarg);
362 break;
363 case 'B':
365 char *vp;
366 max_blksize = (unsigned int)strtoul(optarg, &vp, 10);
367 if ( max_blksize < 512 || max_blksize > MAX_SEGSIZE || *vp ) {
368 syslog(LOG_ERR, "Bad maximum blocksize value (range 512-%d): %s",
369 MAX_SEGSIZE, optarg);
370 exit(EX_USAGE);
373 break;
374 case 'T':
376 char *vp;
377 unsigned long tov = strtoul(optarg, &vp, 10);
378 if ( tov < 10000UL || tov > 255000000UL || *vp ) {
379 syslog(LOG_ERR, "Bad timeout value: %s", optarg);
380 exit(EX_USAGE);
382 rexmtval = timeout = tov;
383 maxtimeout = rexmtval*TIMEOUT_LIMIT;
385 break;
386 case 'R':
388 if ( sscanf(optarg, "%u:%u", &portrange_from, &portrange_to) != 2 ||
389 portrange_from > portrange_to || portrange_to >= 65535 ) {
390 syslog(LOG_ERR, "Bad port range: %s", optarg);
391 exit(EX_USAGE);
393 portrange = 1;
395 break;
396 case 'u':
397 user = optarg;
398 break;
399 case 'U':
400 my_umask = strtoul(optarg, &ep, 8);
401 if ( *ep ) {
402 syslog(LOG_ERR, "Invalid umask: %s", optarg);
403 exit(EX_USAGE);
405 spec_umask = 1;
406 break;
407 case 'r':
408 for ( opt = options ; opt->o_opt ; opt++ ) {
409 if ( !strcasecmp(optarg, opt->o_opt) ) {
410 opt->o_opt = ""; /* Don't support this option */
411 break;
414 if ( !opt->o_opt ) {
415 syslog(LOG_ERR, "Unknown option: %s", optarg);
416 exit(EX_USAGE);
418 break;
419 #ifdef WITH_REGEX
420 case 'm':
421 if ( rewrite_file ) {
422 syslog(LOG_ERR, "Multiple -m options");
423 exit(EX_USAGE);
425 rewrite_file = optarg;
426 break;
427 #endif
428 case 'v':
429 verbosity++;
430 break;
431 case 'V':
432 /* Print configuration to stdout and exit */
433 printf("%s\n", TFTPD_CONFIG_STR);
434 exit(0);
435 break;
436 default:
437 usage();
438 break;
441 dirs = xmalloc((argc-optind+1)*sizeof(char *));
442 for ( ndirs = 0 ; optind != argc ; optind++ )
443 dirs[ndirs++] = argv[optind];
445 dirs[ndirs] = NULL;
447 if (secure) {
448 if (ndirs == 0) {
449 syslog(LOG_ERR, "no -s directory");
450 exit(EX_USAGE);
452 if (ndirs > 1) {
453 syslog(LOG_ERR, "too many -s directories");
454 exit(EX_USAGE);
456 if (chdir(dirs[0])) {
457 syslog(LOG_ERR, "%s: %m", dirs[0]);
458 exit(EX_NOINPUT);
462 pw = getpwnam(user);
463 if (!pw) {
464 syslog(LOG_ERR, "no user %s: %m", user);
465 exit(EX_NOUSER);
468 if ( spec_umask || !unixperms )
469 umask(my_umask);
471 /* Note: on Cygwin, select() on a nonblocking socket becomes
472 a nonblocking select. */
473 #ifndef __CYGWIN__
474 set_socket_nonblock(fd, 1);
475 #endif
477 #ifdef WITH_REGEX
478 if ( rewrite_file )
479 rewrite_rules = read_remap_rules(rewrite_file);
480 #endif
482 /* If we're running standalone, set up the input port */
483 if ( standalone ) {
484 fd = socket(PF_INET, SOCK_DGRAM, 0);
486 memset(&bindaddr, 0, sizeof bindaddr);
487 bindaddr.sin_family = AF_INET;
488 bindaddr.sin_addr.s_addr = INADDR_ANY;
489 bindaddr.sin_port = htons(IPPORT_TFTP);
491 if ( address ) {
492 char *portptr, *eportptr;
493 struct hostent *hostent;
494 struct servent *servent;
495 unsigned long port;
497 address = tfstrdup(address);
498 portptr = strrchr(address, ':');
499 if ( portptr )
500 *portptr++ = '\0';
502 if ( *address ) {
503 hostent = gethostbyname(address);
504 if ( !hostent || hostent->h_addrtype != AF_INET ) {
505 syslog(LOG_ERR, "cannot resolve local bind address: %s", address);
506 exit(EX_NOINPUT);
508 memcpy(&bindaddr.sin_addr, hostent->h_addr, hostent->h_length);
509 } else {
510 /* Default to using INADDR_ANY */
513 if ( portptr && *portptr ) {
514 servent = getservbyname(portptr, "udp");
515 if ( servent ) {
516 bindaddr.sin_port = servent->s_port;
517 } else if ( (port = strtoul(portptr, &eportptr, 0)) && !*eportptr ) {
518 bindaddr.sin_port = htons(port);
519 } else if ( !strcmp(portptr, "tftp") ) {
520 /* It's TFTP, we're OK */
521 } else {
522 syslog(LOG_ERR, "cannot resolve local bind port: %s", portptr);
523 exit(EX_NOINPUT);
528 if (bind(fd, (struct sockaddr *)&bindaddr, sizeof bindaddr) < 0) {
529 syslog(LOG_ERR, "cannot bind to local socket: %m");
530 exit(EX_OSERR);
533 /* Daemonize this process */
535 pid_t f = fork();
536 int nfd;
537 if ( f > 0 )
538 exit(0);
539 if ( f < 0 ) {
540 syslog(LOG_ERR, "cannot fork: %m");
541 exit(EX_OSERR);
543 nfd = open("/dev/null", O_RDWR);
544 if ( nfd >= 3 ) {
545 #ifdef HAVE_DUP2
546 dup2(nfd, 0);
547 dup2(nfd, 1);
548 dup2(nfd, 2);
549 #else
550 close(0); dup(nfd);
551 close(1); dup(nfd);
552 close(2); dup(nfd);
553 #endif
554 close(nfd);
555 } else if ( nfd < 0 ) {
556 close(0); close(1); close(2);
558 #ifdef HAVE_SETSID
559 setsid();
560 #endif
562 } else {
563 /* 0 is our socket descriptor */
564 close(1); close(2);
567 /* Disable path MTU discovery */
568 pmtu_discovery_off(0);
570 /* This means we don't want to wait() for children */
571 #ifdef SA_NOCLDWAIT
572 set_signal(SIGCHLD, SIG_IGN, SA_NOCLDSTOP|SA_NOCLDWAIT);
573 #else
574 set_signal(SIGCHLD, SIG_IGN, SA_NOCLDSTOP);
575 #endif
577 /* Take SIGHUP and use it to set a variable. This
578 is polled synchronously to make sure we don't
579 lose packets as a result. */
580 set_signal(SIGHUP, handle_sighup, 0);
582 while ( 1 ) {
583 fd_set readset;
584 struct timeval tv_waittime;
585 int rv;
587 if ( caught_sighup ) {
588 caught_sighup = 0;
589 if ( standalone ) {
590 #ifdef HAVE_REGEX
591 if ( rewrite_file ) {
592 freerules(rewrite_rules);
593 rewrite_rules = read_remap_rules(rewrite_file);
595 #endif
596 } else {
597 /* Return to inetd for respawn */
598 exit(0);
602 FD_ZERO(&readset);
603 FD_SET(fd, &readset);
604 tv_waittime.tv_sec = waittime;
605 tv_waittime.tv_usec = 0;
607 #ifdef __CYGWIN__
608 /* On Cygwin, select() on a nonblocking socket returns immediately,
609 with a rv of 0! */
610 set_socket_nonblock(fd, 0);
611 #endif
613 /* Never time out if we're in standalone mode */
614 rv = select(fd+1, &readset, NULL, NULL, standalone ? NULL : &tv_waittime);
615 if ( rv == -1 && errno == EINTR )
616 continue; /* Signal caught, reloop */
617 if ( rv == -1 ) {
618 syslog(LOG_ERR, "select loop: %m");
619 exit(EX_IOERR);
620 } else if ( rv == 0 ) {
621 exit(0); /* Timeout, return to inetd */
624 #ifdef __CYGWIN__
625 set_socket_nonblock(fd, 1);
626 #endif
628 fromlen = sizeof (from);
629 n = myrecvfrom(fd, buf, sizeof (buf), 0,
630 (struct sockaddr *)&from, &fromlen,
631 &myaddr);
633 if ( n < 0 ) {
634 if ( E_WOULD_BLOCK(errno) || errno == EINTR ) {
635 continue; /* Again, from the top */
636 } else {
637 syslog(LOG_ERR, "recvfrom: %m");
638 exit(EX_IOERR);
642 if ( from.sin_family != AF_INET ) {
643 syslog(LOG_ERR, "received address was not AF_INET, please check your inetd config");
644 exit(EX_PROTOCOL);
647 if ( standalone && myaddr.sin_addr.s_addr == INADDR_ANY ) {
648 /* myrecvfrom() didn't capture the source address; but we might
649 have bound to a specific address, if so we should use it */
650 memcpy(&myaddr.sin_addr, &bindaddr.sin_addr, sizeof bindaddr.sin_addr);
654 * Now that we have read the request packet from the UDP
655 * socket, we fork and go back to listening to the socket.
657 pid = fork();
658 if (pid < 0) {
659 syslog(LOG_ERR, "fork: %m");
660 exit(EX_OSERR); /* Return to inetd, just in case */
661 } else if ( pid == 0 )
662 break; /* Child exit, parent loop */
665 /* Child process: handle the actual request here */
667 /* Ignore SIGHUP */
668 set_signal(SIGHUP, SIG_IGN, 0);
670 #ifdef HAVE_TCPWRAPPERS
671 /* Verify if this was a legal request for us. This has to be
672 done before the chroot, while /etc is still accessible. */
673 request_init(&wrap_request,
674 RQ_DAEMON, __progname,
675 RQ_FILE, fd,
676 RQ_CLIENT_SIN, &from,
677 RQ_SERVER_SIN, &myaddr,
679 sock_methods(&wrap_request);
680 if ( hosts_access(&wrap_request) == 0 ) {
681 if ( deny_severity != -1 )
682 syslog(deny_severity, "connection refused from %s",
683 inet_ntoa(from.sin_addr));
684 exit(EX_NOPERM); /* Access denied */
685 } else if ( allow_severity != -1 ) {
686 syslog(allow_severity, "connect from %s",
687 inet_ntoa(from.sin_addr));
689 #endif
691 /* Close file descriptors we don't need */
692 close(fd);
694 /* Get a socket. This has to be done before the chroot(), since
695 some systems require access to /dev to create a socket. */
697 peer = socket(AF_INET, SOCK_DGRAM, 0);
698 if (peer < 0) {
699 syslog(LOG_ERR, "socket: %m");
700 exit(EX_IOERR);
703 /* Set up the supplementary group access list if possible */
704 /* /etc/group still need to be accessible at this point */
705 #ifdef HAVE_INITGROUPS
706 setrv = initgroups(user, pw->pw_gid);
707 if ( setrv ) {
708 syslog(LOG_ERR, "cannot set groups for user %s", user);
709 exit(EX_OSERR);
711 #else
712 #ifdef HAVE_SETGROUPS
713 if ( setgroups(0, NULL) ) {
714 syslog(LOG_ERR, "cannot clear group list");
716 #endif
717 #endif
719 /* Chroot and drop privileges */
720 if (secure) {
721 if (chroot(".")) {
722 syslog(LOG_ERR, "chroot: %m");
723 exit(EX_OSERR);
725 #ifdef __CYGWIN__
726 chdir("/"); /* Cygwin chroot() bug workaround */
727 #endif
730 #ifdef HAVE_SETREGID
731 setrv = setregid(pw->pw_gid, pw->pw_gid);
732 #else
733 setrv = setegid(pw->pw_gid) || setgid(pw->pw_gid);
734 #endif
736 #ifdef HAVE_SETREUID
737 setrv = setrv || setreuid(pw->pw_uid, pw->pw_uid);
738 #else
739 /* Important: setuid() must come first */
740 setrv = setrv || setuid(pw->pw_uid) ||
741 (geteuid() != pw->pw_uid && seteuid(pw->pw_uid));
742 #endif
744 if ( setrv ) {
745 syslog(LOG_ERR, "cannot drop privileges: %m");
746 exit(EX_OSERR);
749 /* Other basic setup */
750 from.sin_family = AF_INET;
752 /* Process the request... */
753 if (pick_port_bind(peer, &myaddr) < 0) {
754 syslog(LOG_ERR, "bind: %m");
755 exit(EX_IOERR);
758 if (connect(peer, (struct sockaddr *)&from, sizeof from) < 0) {
759 syslog(LOG_ERR, "connect: %m");
760 exit(EX_IOERR);
763 /* Disable path MTU discovery */
764 pmtu_discovery_off(0);
766 tp = (struct tftphdr *)buf;
767 tp_opcode = ntohs(tp->th_opcode);
768 if (tp_opcode == RRQ || tp_opcode == WRQ)
769 tftp(tp, n);
770 exit(0);
773 char *rewrite_access(char *, int, const char **);
774 int validate_access(char *, int, struct formats *, const char **);
775 void tftp_sendfile(struct formats *, struct tftphdr *, int);
776 void tftp_recvfile(struct formats *, struct tftphdr *, int);
778 struct formats {
779 const char *f_mode;
780 char *(*f_rewrite)(char *, int, const char **);
781 int (*f_validate)(char *, int, struct formats *, const char **);
782 void (*f_send)(struct formats *, struct tftphdr *, int);
783 void (*f_recv)(struct formats *, struct tftphdr *, int);
784 int f_convert;
785 } formats[] = {
786 { "netascii", rewrite_access, validate_access, tftp_sendfile, tftp_recvfile, 1 },
787 { "octet", rewrite_access, validate_access, tftp_sendfile, tftp_recvfile, 0 },
788 { NULL, NULL, NULL, NULL, NULL, 0 }
792 * Handle initial connection protocol.
795 tftp(struct tftphdr *tp, int size)
797 char *cp, *end;
798 int argn, ecode;
799 struct formats *pf = NULL;
800 char *origfilename;
801 char *filename, *mode = NULL;
802 const char *errmsgptr;
803 u_short tp_opcode = ntohs(tp->th_opcode);
805 char *val = NULL, *opt = NULL;
806 char *ap = ackbuf + 2;
808 ((struct tftphdr *)ackbuf)->th_opcode = htons(OACK);
810 origfilename = cp = (char *) &(tp->th_stuff);
811 argn = 0;
813 end = (char *)tp + size;
815 while ( cp < end && *cp ) {
816 do {
817 cp++;
818 } while (cp < end && *cp);
820 if ( *cp ) {
821 nak(EBADOP, "Request not null-terminated");
822 exit(0);
825 argn++;
826 if (argn == 1) {
827 mode = ++cp;
828 } else if (argn == 2) {
829 for (cp = mode; *cp; cp++)
830 *cp = tolower(*cp);
831 for (pf = formats; pf->f_mode; pf++) {
832 if (!strcmp(pf->f_mode, mode))
833 break;
835 if (!pf->f_mode) {
836 nak(EBADOP, "Unknown mode");
837 exit(0);
839 if ( !(filename =
840 (*pf->f_rewrite)(origfilename, tp_opcode, &errmsgptr)) ) {
841 nak(EACCESS, errmsgptr); /* File denied by mapping rule */
842 exit(0);
844 if ( verbosity >= 1 ) {
845 if ( filename == origfilename || !strcmp(filename, origfilename) )
846 syslog(LOG_NOTICE, "%s from %s filename %s\n",
847 tp_opcode == WRQ ? "WRQ" : "RRQ",
848 inet_ntoa(from.sin_addr), filename);
849 else
850 syslog(LOG_NOTICE, "%s from %s filename %s remapped to %s\n",
851 tp_opcode == WRQ ? "WRQ" : "RRQ",
852 inet_ntoa(from.sin_addr), origfilename, filename);
854 ecode = (*pf->f_validate)(filename, tp_opcode, pf, &errmsgptr);
855 if (ecode) {
856 nak(ecode, errmsgptr);
857 exit(0);
859 opt = ++cp;
860 } else if ( argn & 1 ) {
861 val = ++cp;
862 } else {
863 do_opt(opt, val, &ap);
864 opt = ++cp;
868 if (!pf) {
869 nak(EBADOP, "Missing mode");
870 exit(0);
873 if ( ap != (ackbuf+2) ) {
874 if ( tp_opcode == WRQ )
875 (*pf->f_recv)(pf, (struct tftphdr *)ackbuf, ap-ackbuf);
876 else
877 (*pf->f_send)(pf, (struct tftphdr *)ackbuf, ap-ackbuf);
878 } else {
879 if (tp_opcode == WRQ)
880 (*pf->f_recv)(pf, NULL, 0);
881 else
882 (*pf->f_send)(pf, NULL, 0);
884 exit(0); /* Request completed */
887 static int blksize_set;
890 * Set a non-standard block size (c.f. RFC2348)
893 set_blksize(char *val, char **ret)
895 static char b_ret[6];
896 unsigned int sz;
897 char *vend;
899 sz = (unsigned int)strtoul(val, &vend, 10);
901 if ( blksize_set || *vend )
902 return 0;
904 if (sz < 8)
905 return(0);
906 else if (sz > max_blksize)
907 sz = max_blksize;
909 segsize = sz;
910 sprintf(*ret = b_ret, "%u", sz);
912 blksize_set = 1;
914 return(1);
918 * Set a power-of-two block size (nonstandard)
921 set_blksize2(char *val, char **ret)
923 static char b_ret[6];
924 unsigned int sz;
925 char *vend;
927 sz = (unsigned int)strtoul(val, &vend, 10);
929 if ( blksize_set || *vend )
930 return 0;
932 if (sz < 8)
933 return(0);
934 else if (sz > max_blksize)
935 sz = max_blksize;
937 /* Convert to a power of two */
938 if ( sz & (sz-1) ) {
939 unsigned int sz1 = 1;
940 /* Not a power of two - need to convert */
941 while ( sz >>= 1 )
942 sz1 <<= 1;
943 sz = sz1;
946 segsize = sz;
947 sprintf(*ret = b_ret, "%u", sz);
949 blksize_set = 1;
951 return(1);
955 * Return a file size (c.f. RFC2349)
956 * For netascii mode, we don't know the size ahead of time;
957 * so reject the option.
960 set_tsize(char *val, char **ret)
962 static char b_ret[sizeof(uintmax_t)*CHAR_BIT/3+2];
963 uintmax_t sz;
964 char *vend;
966 sz = strtoumax(val, &vend, 10);
968 if ( !tsize_ok || *vend )
969 return 0;
971 if (sz == 0)
972 sz = (uintmax_t)tsize;
974 sprintf(*ret = b_ret, "%"PRIuMAX, sz);
975 return(1);
979 * Set the timeout (c.f. RFC2349). This is supposed
980 * to be the (default) retransmission timeout, but being an
981 * integer in seconds it seems a bit limited.
984 set_timeout(char *val, char **ret)
986 static char b_ret[4];
987 unsigned long to;
988 char *vend;
990 to = strtoul(val, &vend, 10);
992 if ( to < 1 || to > 255 || *vend )
993 return 0;
995 rexmtval = timeout = to*1000000UL;
996 maxtimeout = rexmtval*TIMEOUT_LIMIT;
998 sprintf(*ret = b_ret, "%lu", to);
999 return(1);
1002 /* Similar, but in microseconds. We allow down to 10 ms. */
1004 set_utimeout(char *val, char **ret)
1006 static char b_ret[4];
1007 unsigned long to;
1008 char *vend;
1010 to = strtoul(val, &vend, 10);
1012 if ( to < 10000UL || to > 255000000UL || *vend )
1013 return 0;
1015 rexmtval = timeout = to;
1016 maxtimeout = rexmtval*TIMEOUT_LIMIT;
1018 sprintf(*ret = b_ret, "%lu", to);
1019 return(1);
1022 * Parse RFC2347 style options
1024 void
1025 do_opt(char *opt, char *val, char **ap)
1027 struct options *po;
1028 char *ret;
1030 /* Global option-parsing variables initialization */
1031 blksize_set = 0;
1033 if ( !*opt )
1034 return;
1036 for (po = options; po->o_opt; po++)
1037 if (!strcasecmp(po->o_opt, opt)) {
1038 if (po->o_fnc(val, &ret)) {
1039 if (*ap + strlen(opt) + strlen(ret) + 2 >=
1040 ackbuf + sizeof(ackbuf)) {
1041 nak(EOPTNEG, "Insufficient space for options");
1042 exit(0);
1044 *ap = strrchr(strcpy(strrchr(strcpy(*ap, opt),'\0') + 1,
1045 ret),'\0') + 1;
1046 } else {
1047 nak(EOPTNEG, "Unsupported option(s) requested");
1048 exit(0);
1050 break;
1052 return;
1055 #ifdef WITH_REGEX
1058 * This is called by the remap engine when it encounters macros such
1059 * as \i. It should write the output in "output" if non-NULL, and
1060 * return the length of the output (generated or not).
1062 * Return -1 on failure.
1065 rewrite_macros(char macro, char *output);
1068 rewrite_macros(char macro, char *output)
1070 char *p;
1072 switch (macro) {
1073 case 'i':
1074 p = inet_ntoa(from.sin_addr);
1075 if ( output )
1076 strcpy(output, p);
1077 return strlen(p);
1079 case 'x':
1080 if ( output )
1081 sprintf(output, "%08X",
1082 ntohl(from.sin_addr.s_addr));
1083 return 8;
1085 default:
1086 return -1;
1091 * Modify the filename, if applicable. If it returns NULL, deny the access.
1093 char *
1094 rewrite_access(char *filename, int mode, const char **msg)
1096 if ( rewrite_rules ) {
1097 char *newname = rewrite_string(filename, rewrite_rules, mode != RRQ,
1098 rewrite_macros, msg);
1099 filename = newname;
1101 return filename;
1104 #else
1105 char *
1106 rewrite_access(char *filename, int mode, const char **msg)
1108 (void)mode; /* Avoid warning */
1109 (void)msg;
1110 return filename;
1112 #endif
1114 FILE *file;
1116 * Validate file access. Since we
1117 * have no uid or gid, for now require
1118 * file to exist and be publicly
1119 * readable/writable, unless -p specified.
1120 * If we were invoked with arguments
1121 * from inetd then the file must also be
1122 * in one of the given directory prefixes.
1123 * Note also, full path name must be
1124 * given as we have no login directory.
1127 validate_access(char *filename, int mode,
1128 struct formats *pf, const char **errmsg)
1130 struct stat stbuf;
1131 int i, len;
1132 int fd, wmode, rmode;
1133 char *cp;
1134 const char **dirp;
1135 char stdio_mode[3];
1137 tsize_ok = 0;
1138 *errmsg = NULL;
1140 if (!secure) {
1141 if (*filename != '/') {
1142 *errmsg = "Only absolute filenames allowed";
1143 return (EACCESS);
1147 * prevent tricksters from getting around the directory
1148 * restrictions
1150 len = strlen(filename);
1151 for ( i = 1 ; i < len-3 ; i++ ) {
1152 cp = filename + i;
1153 if ( *cp == '.' && memcmp(cp-1, "/../", 4) == 0 ) {
1154 *errmsg = "Reverse path not allowed";
1155 return(EACCESS);
1159 for (dirp = dirs; *dirp; dirp++)
1160 if (strncmp(filename, *dirp, strlen(*dirp)) == 0)
1161 break;
1162 if (*dirp==0 && dirp!=dirs) {
1163 *errmsg = "Forbidden directory";
1164 return (EACCESS);
1169 * We use different a different permissions scheme if `cancreate' is
1170 * set.
1172 wmode = O_WRONLY |
1173 (cancreate ? O_CREAT : 0) |
1174 (unixperms ? O_TRUNC : 0) |
1175 (pf->f_convert ? O_TEXT : O_BINARY);
1176 rmode = O_RDONLY |
1177 (pf->f_convert ? O_TEXT : O_BINARY);
1179 fd = open(filename, mode == RRQ ? rmode : wmode, 0666);
1180 if (fd < 0) {
1181 switch (errno) {
1182 case ENOENT:
1183 case ENOTDIR:
1184 return ENOTFOUND;
1185 case ENOSPC:
1186 return ENOSPACE;
1187 case EEXIST:
1188 return EEXISTS;
1189 default:
1190 return errno+100;
1194 if ( fstat(fd, &stbuf) < 0 )
1195 exit(EX_OSERR); /* This shouldn't happen */
1197 if (mode == RRQ) {
1198 if ( !unixperms && (stbuf.st_mode & (S_IREAD >> 6)) == 0 ) {
1199 *errmsg = "File must have global read permissions";
1200 return (EACCESS);
1202 tsize = stbuf.st_size;
1203 /* We don't know the tsize if conversion is needed */
1204 tsize_ok = !pf->f_convert;
1205 } else {
1206 if ( !unixperms ) {
1207 if ( (stbuf.st_mode & (S_IWRITE >> 6)) == 0 ) {
1208 *errmsg = "File must have global write permissions";
1209 return (EACCESS);
1212 /* We didn't get to truncate the file at open() time */
1213 #ifdef HAVE_FTRUNCATE
1214 if ( ftruncate(fd, (off_t)0) ) {
1215 *errmsg = "Cannot reset file size";
1216 return(EACCESS);
1218 #endif
1220 tsize = 0;
1221 tsize_ok = 1;
1224 stdio_mode[0] = (mode == RRQ) ? 'r':'w';
1225 stdio_mode[1] = (pf->f_convert) ? 't':'b';
1226 stdio_mode[2] = '\0';
1228 file = fdopen(fd, stdio_mode);
1229 if (file == NULL)
1230 exit(EX_OSERR); /* Internal error */
1232 return (0);
1236 * Send the requested file.
1238 void
1239 tftp_sendfile(struct formats *pf, struct tftphdr *oap, int oacklen)
1241 struct tftphdr *dp;
1242 struct tftphdr *ap; /* ack packet */
1243 static u_short block = 1; /* Static to avoid longjmp funnies */
1244 u_short ap_opcode, ap_block;
1245 unsigned long r_timeout;
1246 int size, n;
1248 if (oap) {
1249 timeout = rexmtval;
1250 (void)sigsetjmp(timeoutbuf,1);
1251 oack:
1252 r_timeout = timeout;
1253 if (send(peer, oap, oacklen, 0) != oacklen) {
1254 syslog(LOG_WARNING, "tftpd: oack: %m\n");
1255 goto abort;
1257 for ( ; ; ) {
1258 n = recv_time(peer, ackbuf, sizeof(ackbuf), 0, &r_timeout);
1259 if (n < 0) {
1260 syslog(LOG_WARNING, "tftpd: read: %m\n");
1261 goto abort;
1263 ap = (struct tftphdr *)ackbuf;
1264 ap_opcode = ntohs((u_short)ap->th_opcode);
1265 ap_block = ntohs((u_short)ap->th_block);
1267 if (ap_opcode == ERROR) {
1268 syslog(LOG_WARNING, "tftp: client does not accept options\n");
1269 goto abort;
1271 if (ap_opcode == ACK) {
1272 if (ap_block == 0)
1273 break;
1274 /* Resynchronize with the other side */
1275 (void)synchnet(peer);
1276 goto oack;
1281 dp = r_init();
1282 do {
1283 size = readit(file, &dp, pf->f_convert);
1284 if (size < 0) {
1285 nak(errno + 100, NULL);
1286 goto abort;
1288 dp->th_opcode = htons((u_short)DATA);
1289 dp->th_block = htons((u_short)block);
1290 timeout = rexmtval;
1291 (void) sigsetjmp(timeoutbuf,1);
1293 r_timeout = timeout;
1294 if (send(peer, dp, size + 4, 0) != size + 4) {
1295 syslog(LOG_WARNING, "tftpd: write: %m");
1296 goto abort;
1298 read_ahead(file, pf->f_convert);
1299 for ( ; ; ) {
1300 n = recv_time(peer, ackbuf, sizeof (ackbuf), 0, &r_timeout);
1301 if (n < 0) {
1302 syslog(LOG_WARNING, "tftpd: read(ack): %m");
1303 goto abort;
1305 ap = (struct tftphdr *)ackbuf;
1306 ap_opcode = ntohs((u_short)ap->th_opcode);
1307 ap_block = ntohs((u_short)ap->th_block);
1309 if (ap_opcode == ERROR)
1310 goto abort;
1312 if (ap_opcode == ACK) {
1313 if (ap_block == block) {
1314 break;
1316 /* Re-synchronize with the other side */
1317 (void) synchnet(peer);
1319 * RFC1129/RFC1350: We MUST NOT re-send the DATA
1320 * packet in response to an invalid ACK. Doing so
1321 * would cause the Sorcerer's Apprentice bug.
1326 block++;
1327 } while (size == segsize);
1328 abort:
1329 (void) fclose(file);
1332 /* Bail out signal handler */
1333 void
1334 justquit(int sig)
1336 (void)sig; /* Suppress unused warning */
1337 exit(0);
1342 * Receive a file.
1344 void
1345 tftp_recvfile(struct formats *pf, struct tftphdr *oap, int oacklen)
1347 struct tftphdr *dp;
1348 int n, size;
1349 /* These are "static" to avoid longjmp funnies */
1350 static struct tftphdr *ap; /* ack buffer */
1351 static u_short block = 0;
1352 static int acksize;
1353 u_short dp_opcode, dp_block;
1354 unsigned long r_timeout;
1356 dp = w_init();
1357 do {
1358 timeout = rexmtval;
1360 if (!block && oap) {
1361 ap = (struct tftphdr *)ackbuf;
1362 acksize = oacklen;
1363 } else {
1364 ap = (struct tftphdr *)ackbuf;
1365 ap->th_opcode = htons((u_short)ACK);
1366 ap->th_block = htons((u_short)block);
1367 acksize = 4;
1369 block++;
1370 (void) sigsetjmp(timeoutbuf,1);
1371 send_ack:
1372 r_timeout = timeout;
1373 if (send(peer, ackbuf, acksize, 0) != acksize) {
1374 syslog(LOG_WARNING, "tftpd: write(ack): %m");
1375 goto abort;
1377 write_behind(file, pf->f_convert);
1378 for ( ; ; ) {
1379 n = recv_time(peer, dp, PKTSIZE, 0, &r_timeout);
1380 if (n < 0) { /* really? */
1381 syslog(LOG_WARNING, "tftpd: read: %m");
1382 goto abort;
1384 dp_opcode = ntohs((u_short)dp->th_opcode);
1385 dp_block = ntohs((u_short)dp->th_block);
1386 if (dp_opcode == ERROR)
1387 goto abort;
1388 if (dp_opcode == DATA) {
1389 if (dp_block == block) {
1390 break; /* normal */
1392 /* Re-synchronize with the other side */
1393 (void) synchnet(peer);
1394 if (dp_block == (block-1))
1395 goto send_ack; /* rexmit */
1398 /* size = write(file, dp->th_data, n - 4); */
1399 size = writeit(file, &dp, n - 4, pf->f_convert);
1400 if (size != (n-4)) { /* ahem */
1401 if (size < 0) nak(errno + 100, NULL);
1402 else nak(ENOSPACE, NULL);
1403 goto abort;
1405 } while (size == segsize);
1406 write_behind(file, pf->f_convert);
1407 (void) fclose(file); /* close data file */
1409 ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */
1410 ap->th_block = htons((u_short)(block));
1411 (void) send(peer, ackbuf, 4, 0);
1413 timeout_quit = 1; /* just quit on timeout */
1414 n = recv_time(peer, buf, sizeof (buf), 0, &timeout); /* normally times out and quits */
1415 timeout_quit = 0;
1417 if (n >= 4 && /* if read some data */
1418 dp_opcode == DATA && /* and got a data block */
1419 block == dp_block) { /* then my last ack was lost */
1420 (void) send(peer, ackbuf, 4, 0); /* resend final ack */
1422 abort:
1423 return;
1426 static const char * const errmsgs[] =
1428 "Undefined error code", /* 0 - EUNDEF */
1429 "File not found", /* 1 - ENOTFOUND */
1430 "Access denied", /* 2 - EACCESS */
1431 "Disk full or allocation exceeded", /* 3 - ENOSPACE */
1432 "Illegal TFTP operation", /* 4 - EBADOP */
1433 "Unknown transfer ID", /* 5 - EBADID */
1434 "File already exists", /* 6 - EEXISTS */
1435 "No such user", /* 7 - ENOUSER */
1436 "Failure to negotiate RFC2347 options" /* 8 - EOPTNEG */
1438 #define ERR_CNT (sizeof(errmsgs)/sizeof(const char *))
1441 * Send a nak packet (error message).
1442 * Error code passed in is one of the
1443 * standard TFTP codes, or a UNIX errno
1444 * offset by 100.
1446 static void
1447 nak(int error, const char *msg)
1449 struct tftphdr *tp;
1450 int length;
1452 tp = (struct tftphdr *)buf;
1453 tp->th_opcode = htons((u_short)ERROR);
1455 if ( error >= 100 ) {
1456 /* This is a Unix errno+100 */
1457 if ( !msg )
1458 msg = strerror(error - 100);
1459 error = EUNDEF;
1460 } else {
1461 if ( (unsigned)error >= ERR_CNT )
1462 error = EUNDEF;
1464 if ( !msg )
1465 msg = errmsgs[error];
1468 tp->th_code = htons((u_short)error);
1470 length = strlen(msg)+1;
1471 memcpy(tp->th_msg, msg, length);
1472 length += 4; /* Add space for header */
1474 if ( verbosity >= 2 ) {
1475 syslog(LOG_INFO, "sending NAK (%d, %s) to %s",
1476 error, tp->th_msg, inet_ntoa(from.sin_addr));
1479 if (send(peer, buf, length, 0) != length)
1480 syslog(LOG_WARNING, "nak: %m");