Make sure we include <sys/socket.h> when checking for socklen_t
[tftp-hpa.git] / tftpd / tftpd.c
blob7e0d1f09d433bd96cd0cfef12729c77997424834
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 "common/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 socklen_t 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;
278 main(int argc, char **argv)
280 struct tftphdr *tp;
281 struct passwd *pw;
282 struct options *opt;
283 struct sockaddr_in myaddr;
284 struct sockaddr_in bindaddr;
285 int n;
286 int fd = 0;
287 int standalone = 0; /* Standalone (listen) mode */
288 char *address = NULL; /* Address to listen to */
289 pid_t pid;
290 mode_t my_umask = 0;
291 int spec_umask = 0;
292 int c;
293 int setrv;
294 int waittime = 900; /* Default time to wait for a connect*/
295 const char *user = "nobody"; /* Default user */
296 char *p, *ep;
297 #ifdef WITH_REGEX
298 char *rewrite_file = NULL;
299 #endif
300 u_short tp_opcode;
302 /* basename() is way too much of a pain from a portability standpoint */
304 p = strrchr(argv[0], '/');
305 __progname = (p && p[1]) ? p+1 : argv[0];
307 openlog(__progname, LOG_PID|LOG_NDELAY, LOG_DAEMON);
309 srand(time(NULL) ^ getpid());
311 while ((c = getopt(argc, argv, "cspvVla:B:u:U:r:t:T:R:m:")) != -1)
312 switch (c) {
313 case 'c':
314 cancreate = 1;
315 break;
316 case 's':
317 secure = 1;
318 break;
319 case 'p':
320 unixperms = 1;
321 break;
322 case 'l':
323 standalone = 1;
324 break;
325 case 'a':
326 address = optarg;
327 break;
328 case 't':
329 waittime = atoi(optarg);
330 break;
331 case 'B':
333 char *vp;
334 max_blksize = (unsigned int)strtoul(optarg, &vp, 10);
335 if ( max_blksize < 512 || max_blksize > MAX_SEGSIZE || *vp ) {
336 syslog(LOG_ERR, "Bad maximum blocksize value (range 512-%d): %s",
337 MAX_SEGSIZE, optarg);
338 exit(EX_USAGE);
341 break;
342 case 'T':
344 char *vp;
345 unsigned long tov = strtoul(optarg, &vp, 10);
346 if ( tov < 10000UL || tov > 255000000UL || *vp ) {
347 syslog(LOG_ERR, "Bad timeout value: %s", optarg);
348 exit(EX_USAGE);
350 rexmtval = timeout = tov;
351 maxtimeout = rexmtval*TIMEOUT_LIMIT;
353 break;
354 case 'R':
356 if ( sscanf(optarg, "%u:%u", &portrange_from, &portrange_to) != 2 ||
357 portrange_from > portrange_to || portrange_to >= 65535 ) {
358 syslog(LOG_ERR, "Bad port range: %s", optarg);
359 exit(EX_USAGE);
361 portrange = 1;
363 break;
364 case 'u':
365 user = optarg;
366 break;
367 case 'U':
368 my_umask = strtoul(optarg, &ep, 8);
369 if ( *ep ) {
370 syslog(LOG_ERR, "Invalid umask: %s", optarg);
371 exit(EX_USAGE);
373 spec_umask = 1;
374 break;
375 case 'r':
376 for ( opt = options ; opt->o_opt ; opt++ ) {
377 if ( !strcasecmp(optarg, opt->o_opt) ) {
378 opt->o_opt = ""; /* Don't support this option */
379 break;
382 if ( !opt->o_opt ) {
383 syslog(LOG_ERR, "Unknown option: %s", optarg);
384 exit(EX_USAGE);
386 break;
387 #ifdef WITH_REGEX
388 case 'm':
389 if ( rewrite_file ) {
390 syslog(LOG_ERR, "Multiple -m options");
391 exit(EX_USAGE);
393 rewrite_file = optarg;
394 break;
395 #endif
396 case 'v':
397 verbosity++;
398 break;
399 case 'V':
400 /* Print configuration to stdout and exit */
401 printf("%s\n", TFTPD_CONFIG_STR);
402 exit(0);
403 break;
404 default:
405 usage();
406 break;
409 dirs = xmalloc((argc-optind+1)*sizeof(char *));
410 for ( ndirs = 0 ; optind != argc ; optind++ )
411 dirs[ndirs++] = argv[optind];
413 dirs[ndirs] = NULL;
415 if (secure) {
416 if (ndirs == 0) {
417 syslog(LOG_ERR, "no -s directory");
418 exit(EX_USAGE);
420 if (ndirs > 1) {
421 syslog(LOG_ERR, "too many -s directories");
422 exit(EX_USAGE);
424 if (chdir(dirs[0])) {
425 syslog(LOG_ERR, "%s: %m", dirs[0]);
426 exit(EX_NOINPUT);
430 pw = getpwnam(user);
431 if (!pw) {
432 syslog(LOG_ERR, "no user %s: %m", user);
433 exit(EX_NOUSER);
436 if ( spec_umask || !unixperms )
437 umask(my_umask);
439 /* Note: on Cygwin, select() on a nonblocking socket becomes
440 a nonblocking select. */
441 #ifndef __CYGWIN__
442 set_socket_nonblock(fd, 1);
443 #endif
445 #ifdef WITH_REGEX
446 if ( rewrite_file )
447 rewrite_rules = read_remap_rules(rewrite_file);
448 #endif
450 /* If we're running standalone, set up the input port */
451 if ( standalone ) {
452 fd = socket(PF_INET, SOCK_DGRAM, 0);
454 memset(&bindaddr, 0, sizeof bindaddr);
455 bindaddr.sin_family = AF_INET;
456 bindaddr.sin_addr.s_addr = INADDR_ANY;
457 bindaddr.sin_port = htons(IPPORT_TFTP);
459 if ( address ) {
460 char *portptr, *eportptr;
461 struct hostent *hostent;
462 struct servent *servent;
463 unsigned long port;
465 address = tfstrdup(address);
466 portptr = strrchr(address, ':');
467 if ( portptr )
468 *portptr++ = '\0';
470 if ( *address ) {
471 hostent = gethostbyname(address);
472 if ( !hostent || hostent->h_addrtype != AF_INET ) {
473 syslog(LOG_ERR, "cannot resolve local bind address: %s", address);
474 exit(EX_NOINPUT);
476 memcpy(&bindaddr.sin_addr, hostent->h_addr, hostent->h_length);
477 } else {
478 /* Default to using INADDR_ANY */
481 if ( portptr && *portptr ) {
482 servent = getservbyname(portptr, "udp");
483 if ( servent ) {
484 bindaddr.sin_port = servent->s_port;
485 } else if ( (port = strtoul(portptr, &eportptr, 0)) && !*eportptr ) {
486 bindaddr.sin_port = htons(port);
487 } else if ( !strcmp(portptr, "tftp") ) {
488 /* It's TFTP, we're OK */
489 } else {
490 syslog(LOG_ERR, "cannot resolve local bind port: %s", portptr);
491 exit(EX_NOINPUT);
496 if (bind(fd, (struct sockaddr *)&bindaddr, sizeof bindaddr) < 0) {
497 syslog(LOG_ERR, "cannot bind to local socket: %m");
498 exit(EX_OSERR);
501 /* Daemonize this process */
503 pid_t f = fork();
504 int nfd;
505 if ( f > 0 )
506 exit(0);
507 if ( f < 0 ) {
508 syslog(LOG_ERR, "cannot fork: %m");
509 exit(EX_OSERR);
511 nfd = open("/dev/null", O_RDWR);
512 if ( nfd >= 3 ) {
513 #ifdef HAVE_DUP2
514 dup2(nfd, 0);
515 dup2(nfd, 1);
516 dup2(nfd, 2);
517 #else
518 close(0); dup(nfd);
519 close(1); dup(nfd);
520 close(2); dup(nfd);
521 #endif
522 close(nfd);
523 } else if ( nfd < 0 ) {
524 close(0); close(1); close(2);
526 #ifdef HAVE_SETSID
527 setsid();
528 #endif
530 } else {
531 /* 0 is our socket descriptor */
532 close(1); close(2);
535 /* Disable path MTU discovery */
536 pmtu_discovery_off(0);
538 /* This means we don't want to wait() for children */
539 #ifdef SA_NOCLDWAIT
540 set_signal(SIGCHLD, SIG_IGN, SA_NOCLDSTOP|SA_NOCLDWAIT);
541 #else
542 set_signal(SIGCHLD, SIG_IGN, SA_NOCLDSTOP);
543 #endif
545 /* Take SIGHUP and use it to set a variable. This
546 is polled synchronously to make sure we don't
547 lose packets as a result. */
548 set_signal(SIGHUP, handle_sighup, 0);
550 while ( 1 ) {
551 fd_set readset;
552 struct timeval tv_waittime;
553 int rv;
555 if ( caught_sighup ) {
556 caught_sighup = 0;
557 if ( standalone ) {
558 #ifdef WITH_REGEX
559 if ( rewrite_file ) {
560 freerules(rewrite_rules);
561 rewrite_rules = read_remap_rules(rewrite_file);
563 #endif
564 } else {
565 /* Return to inetd for respawn */
566 exit(0);
570 FD_ZERO(&readset);
571 FD_SET(fd, &readset);
572 tv_waittime.tv_sec = waittime;
573 tv_waittime.tv_usec = 0;
575 #ifdef __CYGWIN__
576 /* On Cygwin, select() on a nonblocking socket returns immediately,
577 with a rv of 0! */
578 set_socket_nonblock(fd, 0);
579 #endif
581 /* Never time out if we're in standalone mode */
582 rv = select(fd+1, &readset, NULL, NULL, standalone ? NULL : &tv_waittime);
583 if ( rv == -1 && errno == EINTR )
584 continue; /* Signal caught, reloop */
585 if ( rv == -1 ) {
586 syslog(LOG_ERR, "select loop: %m");
587 exit(EX_IOERR);
588 } else if ( rv == 0 ) {
589 exit(0); /* Timeout, return to inetd */
592 #ifdef __CYGWIN__
593 set_socket_nonblock(fd, 1);
594 #endif
596 fromlen = sizeof (from);
597 n = myrecvfrom(fd, buf, sizeof (buf), 0,
598 (struct sockaddr *)&from, &fromlen,
599 &myaddr);
601 if ( n < 0 ) {
602 if ( E_WOULD_BLOCK(errno) || errno == EINTR ) {
603 continue; /* Again, from the top */
604 } else {
605 syslog(LOG_ERR, "recvfrom: %m");
606 exit(EX_IOERR);
610 if ( from.sin_family != AF_INET ) {
611 syslog(LOG_ERR, "received address was not AF_INET, please check your inetd config");
612 exit(EX_PROTOCOL);
615 if ( standalone && myaddr.sin_addr.s_addr == INADDR_ANY ) {
616 /* myrecvfrom() didn't capture the source address; but we might
617 have bound to a specific address, if so we should use it */
618 memcpy(&myaddr.sin_addr, &bindaddr.sin_addr, sizeof bindaddr.sin_addr);
622 * Now that we have read the request packet from the UDP
623 * socket, we fork and go back to listening to the socket.
625 pid = fork();
626 if (pid < 0) {
627 syslog(LOG_ERR, "fork: %m");
628 exit(EX_OSERR); /* Return to inetd, just in case */
629 } else if ( pid == 0 )
630 break; /* Child exit, parent loop */
633 /* Child process: handle the actual request here */
635 /* Ignore SIGHUP */
636 set_signal(SIGHUP, SIG_IGN, 0);
638 #ifdef HAVE_TCPWRAPPERS
639 /* Verify if this was a legal request for us. This has to be
640 done before the chroot, while /etc is still accessible. */
641 request_init(&wrap_request,
642 RQ_DAEMON, __progname,
643 RQ_FILE, fd,
644 RQ_CLIENT_SIN, &from,
645 RQ_SERVER_SIN, &myaddr,
647 sock_methods(&wrap_request);
648 if ( hosts_access(&wrap_request) == 0 ) {
649 if ( deny_severity != -1 )
650 syslog(deny_severity, "connection refused from %s",
651 inet_ntoa(from.sin_addr));
652 exit(EX_NOPERM); /* Access denied */
653 } else if ( allow_severity != -1 ) {
654 syslog(allow_severity, "connect from %s",
655 inet_ntoa(from.sin_addr));
657 #endif
659 /* Close file descriptors we don't need */
660 close(fd);
662 /* Get a socket. This has to be done before the chroot(), since
663 some systems require access to /dev to create a socket. */
665 peer = socket(AF_INET, SOCK_DGRAM, 0);
666 if (peer < 0) {
667 syslog(LOG_ERR, "socket: %m");
668 exit(EX_IOERR);
671 /* Set up the supplementary group access list if possible */
672 /* /etc/group still need to be accessible at this point */
673 #ifdef HAVE_INITGROUPS
674 setrv = initgroups(user, pw->pw_gid);
675 if ( setrv ) {
676 syslog(LOG_ERR, "cannot set groups for user %s", user);
677 exit(EX_OSERR);
679 #else
680 #ifdef HAVE_SETGROUPS
681 if ( setgroups(0, NULL) ) {
682 syslog(LOG_ERR, "cannot clear group list");
684 #endif
685 #endif
687 /* Chroot and drop privileges */
688 if (secure) {
689 if (chroot(".")) {
690 syslog(LOG_ERR, "chroot: %m");
691 exit(EX_OSERR);
693 #ifdef __CYGWIN__
694 chdir("/"); /* Cygwin chroot() bug workaround */
695 #endif
698 #ifdef HAVE_SETREGID
699 setrv = setregid(pw->pw_gid, pw->pw_gid);
700 #else
701 setrv = setegid(pw->pw_gid) || setgid(pw->pw_gid);
702 #endif
704 #ifdef HAVE_SETREUID
705 setrv = setrv || setreuid(pw->pw_uid, pw->pw_uid);
706 #else
707 /* Important: setuid() must come first */
708 setrv = setrv || setuid(pw->pw_uid) ||
709 (geteuid() != pw->pw_uid && seteuid(pw->pw_uid));
710 #endif
712 if ( setrv ) {
713 syslog(LOG_ERR, "cannot drop privileges: %m");
714 exit(EX_OSERR);
717 /* Other basic setup */
718 from.sin_family = AF_INET;
720 /* Process the request... */
721 if (pick_port_bind(peer, &myaddr, portrange_from, portrange_to) < 0) {
722 syslog(LOG_ERR, "bind: %m");
723 exit(EX_IOERR);
726 if (connect(peer, (struct sockaddr *)&from, sizeof from) < 0) {
727 syslog(LOG_ERR, "connect: %m");
728 exit(EX_IOERR);
731 /* Disable path MTU discovery */
732 pmtu_discovery_off(0);
734 tp = (struct tftphdr *)buf;
735 tp_opcode = ntohs(tp->th_opcode);
736 if (tp_opcode == RRQ || tp_opcode == WRQ)
737 tftp(tp, n);
738 exit(0);
741 char *rewrite_access(char *, int, const char **);
742 int validate_access(char *, int, struct formats *, const char **);
743 void tftp_sendfile(struct formats *, struct tftphdr *, int);
744 void tftp_recvfile(struct formats *, struct tftphdr *, int);
746 struct formats {
747 const char *f_mode;
748 char *(*f_rewrite)(char *, int, const char **);
749 int (*f_validate)(char *, int, struct formats *, const char **);
750 void (*f_send)(struct formats *, struct tftphdr *, int);
751 void (*f_recv)(struct formats *, struct tftphdr *, int);
752 int f_convert;
753 } formats[] = {
754 { "netascii", rewrite_access, validate_access, tftp_sendfile, tftp_recvfile, 1 },
755 { "octet", rewrite_access, validate_access, tftp_sendfile, tftp_recvfile, 0 },
756 { NULL, NULL, NULL, NULL, NULL, 0 }
760 * Handle initial connection protocol.
763 tftp(struct tftphdr *tp, int size)
765 char *cp, *end;
766 int argn, ecode;
767 struct formats *pf = NULL;
768 char *origfilename;
769 char *filename, *mode = NULL;
770 const char *errmsgptr;
771 u_short tp_opcode = ntohs(tp->th_opcode);
773 char *val = NULL, *opt = NULL;
774 char *ap = ackbuf + 2;
776 ((struct tftphdr *)ackbuf)->th_opcode = htons(OACK);
778 origfilename = cp = (char *) &(tp->th_stuff);
779 argn = 0;
781 end = (char *)tp + size;
783 while ( cp < end && *cp ) {
784 do {
785 cp++;
786 } while (cp < end && *cp);
788 if ( *cp ) {
789 nak(EBADOP, "Request not null-terminated");
790 exit(0);
793 argn++;
794 if (argn == 1) {
795 mode = ++cp;
796 } else if (argn == 2) {
797 for (cp = mode; *cp; cp++)
798 *cp = tolower(*cp);
799 for (pf = formats; pf->f_mode; pf++) {
800 if (!strcmp(pf->f_mode, mode))
801 break;
803 if (!pf->f_mode) {
804 nak(EBADOP, "Unknown mode");
805 exit(0);
807 if ( !(filename =
808 (*pf->f_rewrite)(origfilename, tp_opcode, &errmsgptr)) ) {
809 nak(EACCESS, errmsgptr); /* File denied by mapping rule */
810 exit(0);
812 if ( verbosity >= 1 ) {
813 if ( filename == origfilename || !strcmp(filename, origfilename) )
814 syslog(LOG_NOTICE, "%s from %s filename %s\n",
815 tp_opcode == WRQ ? "WRQ" : "RRQ",
816 inet_ntoa(from.sin_addr), filename);
817 else
818 syslog(LOG_NOTICE, "%s from %s filename %s remapped to %s\n",
819 tp_opcode == WRQ ? "WRQ" : "RRQ",
820 inet_ntoa(from.sin_addr), origfilename, filename);
822 ecode = (*pf->f_validate)(filename, tp_opcode, pf, &errmsgptr);
823 if (ecode) {
824 nak(ecode, errmsgptr);
825 exit(0);
827 opt = ++cp;
828 } else if ( argn & 1 ) {
829 val = ++cp;
830 } else {
831 do_opt(opt, val, &ap);
832 opt = ++cp;
836 if (!pf) {
837 nak(EBADOP, "Missing mode");
838 exit(0);
841 if ( ap != (ackbuf+2) ) {
842 if ( tp_opcode == WRQ )
843 (*pf->f_recv)(pf, (struct tftphdr *)ackbuf, ap-ackbuf);
844 else
845 (*pf->f_send)(pf, (struct tftphdr *)ackbuf, ap-ackbuf);
846 } else {
847 if (tp_opcode == WRQ)
848 (*pf->f_recv)(pf, NULL, 0);
849 else
850 (*pf->f_send)(pf, NULL, 0);
852 exit(0); /* Request completed */
855 static int blksize_set;
858 * Set a non-standard block size (c.f. RFC2348)
861 set_blksize(char *val, char **ret)
863 static char b_ret[6];
864 unsigned int sz;
865 char *vend;
867 sz = (unsigned int)strtoul(val, &vend, 10);
869 if ( blksize_set || *vend )
870 return 0;
872 if (sz < 8)
873 return(0);
874 else if (sz > max_blksize)
875 sz = max_blksize;
877 segsize = sz;
878 sprintf(*ret = b_ret, "%u", sz);
880 blksize_set = 1;
882 return(1);
886 * Set a power-of-two block size (nonstandard)
889 set_blksize2(char *val, char **ret)
891 static char b_ret[6];
892 unsigned int sz;
893 char *vend;
895 sz = (unsigned int)strtoul(val, &vend, 10);
897 if ( blksize_set || *vend )
898 return 0;
900 if (sz < 8)
901 return(0);
902 else if (sz > max_blksize)
903 sz = max_blksize;
905 /* Convert to a power of two */
906 if ( sz & (sz-1) ) {
907 unsigned int sz1 = 1;
908 /* Not a power of two - need to convert */
909 while ( sz >>= 1 )
910 sz1 <<= 1;
911 sz = sz1;
914 segsize = sz;
915 sprintf(*ret = b_ret, "%u", sz);
917 blksize_set = 1;
919 return(1);
923 * Return a file size (c.f. RFC2349)
924 * For netascii mode, we don't know the size ahead of time;
925 * so reject the option.
928 set_tsize(char *val, char **ret)
930 static char b_ret[sizeof(uintmax_t)*CHAR_BIT/3+2];
931 uintmax_t sz;
932 char *vend;
934 sz = strtoumax(val, &vend, 10);
936 if ( !tsize_ok || *vend )
937 return 0;
939 if (sz == 0)
940 sz = (uintmax_t)tsize;
942 sprintf(*ret = b_ret, "%"PRIuMAX, sz);
943 return(1);
947 * Set the timeout (c.f. RFC2349). This is supposed
948 * to be the (default) retransmission timeout, but being an
949 * integer in seconds it seems a bit limited.
952 set_timeout(char *val, char **ret)
954 static char b_ret[4];
955 unsigned long to;
956 char *vend;
958 to = strtoul(val, &vend, 10);
960 if ( to < 1 || to > 255 || *vend )
961 return 0;
963 rexmtval = timeout = to*1000000UL;
964 maxtimeout = rexmtval*TIMEOUT_LIMIT;
966 sprintf(*ret = b_ret, "%lu", to);
967 return(1);
970 /* Similar, but in microseconds. We allow down to 10 ms. */
972 set_utimeout(char *val, char **ret)
974 static char b_ret[4];
975 unsigned long to;
976 char *vend;
978 to = strtoul(val, &vend, 10);
980 if ( to < 10000UL || to > 255000000UL || *vend )
981 return 0;
983 rexmtval = timeout = to;
984 maxtimeout = rexmtval*TIMEOUT_LIMIT;
986 sprintf(*ret = b_ret, "%lu", to);
987 return(1);
990 * Parse RFC2347 style options
992 void
993 do_opt(char *opt, char *val, char **ap)
995 struct options *po;
996 char *ret;
998 /* Global option-parsing variables initialization */
999 blksize_set = 0;
1001 if ( !*opt )
1002 return;
1004 for (po = options; po->o_opt; po++)
1005 if (!strcasecmp(po->o_opt, opt)) {
1006 if (po->o_fnc(val, &ret)) {
1007 if (*ap + strlen(opt) + strlen(ret) + 2 >=
1008 ackbuf + sizeof(ackbuf)) {
1009 nak(EOPTNEG, "Insufficient space for options");
1010 exit(0);
1012 *ap = strrchr(strcpy(strrchr(strcpy(*ap, opt),'\0') + 1,
1013 ret),'\0') + 1;
1014 } else {
1015 nak(EOPTNEG, "Unsupported option(s) requested");
1016 exit(0);
1018 break;
1020 return;
1023 #ifdef WITH_REGEX
1026 * This is called by the remap engine when it encounters macros such
1027 * as \i. It should write the output in "output" if non-NULL, and
1028 * return the length of the output (generated or not).
1030 * Return -1 on failure.
1033 rewrite_macros(char macro, char *output);
1036 rewrite_macros(char macro, char *output)
1038 char *p;
1040 switch (macro) {
1041 case 'i':
1042 p = inet_ntoa(from.sin_addr);
1043 if ( output )
1044 strcpy(output, p);
1045 return strlen(p);
1047 case 'x':
1048 if ( output )
1049 sprintf(output, "%08lX", (unsigned long)ntohl(from.sin_addr.s_addr));
1050 return 8;
1052 default:
1053 return -1;
1058 * Modify the filename, if applicable. If it returns NULL, deny the access.
1060 char *
1061 rewrite_access(char *filename, int mode, const char **msg)
1063 if ( rewrite_rules ) {
1064 char *newname = rewrite_string(filename, rewrite_rules, mode != RRQ,
1065 rewrite_macros, msg);
1066 filename = newname;
1068 return filename;
1071 #else
1072 char *
1073 rewrite_access(char *filename, int mode, const char **msg)
1075 (void)mode; /* Avoid warning */
1076 (void)msg;
1077 return filename;
1079 #endif
1081 FILE *file;
1083 * Validate file access. Since we
1084 * have no uid or gid, for now require
1085 * file to exist and be publicly
1086 * readable/writable, unless -p specified.
1087 * If we were invoked with arguments
1088 * from inetd then the file must also be
1089 * in one of the given directory prefixes.
1090 * Note also, full path name must be
1091 * given as we have no login directory.
1094 validate_access(char *filename, int mode,
1095 struct formats *pf, const char **errmsg)
1097 struct stat stbuf;
1098 int i, len;
1099 int fd, wmode, rmode;
1100 char *cp;
1101 const char **dirp;
1102 char stdio_mode[3];
1104 tsize_ok = 0;
1105 *errmsg = NULL;
1107 if (!secure) {
1108 if (*filename != '/') {
1109 *errmsg = "Only absolute filenames allowed";
1110 return (EACCESS);
1114 * prevent tricksters from getting around the directory
1115 * restrictions
1117 len = strlen(filename);
1118 for ( i = 1 ; i < len-3 ; i++ ) {
1119 cp = filename + i;
1120 if ( *cp == '.' && memcmp(cp-1, "/../", 4) == 0 ) {
1121 *errmsg = "Reverse path not allowed";
1122 return(EACCESS);
1126 for (dirp = dirs; *dirp; dirp++)
1127 if (strncmp(filename, *dirp, strlen(*dirp)) == 0)
1128 break;
1129 if (*dirp==0 && dirp!=dirs) {
1130 *errmsg = "Forbidden directory";
1131 return (EACCESS);
1136 * We use different a different permissions scheme if `cancreate' is
1137 * set.
1139 wmode = O_WRONLY |
1140 (cancreate ? O_CREAT : 0) |
1141 (unixperms ? O_TRUNC : 0) |
1142 (pf->f_convert ? O_TEXT : O_BINARY);
1143 rmode = O_RDONLY |
1144 (pf->f_convert ? O_TEXT : O_BINARY);
1146 fd = open(filename, mode == RRQ ? rmode : wmode, 0666);
1147 if (fd < 0) {
1148 switch (errno) {
1149 case ENOENT:
1150 case ENOTDIR:
1151 return ENOTFOUND;
1152 case ENOSPC:
1153 return ENOSPACE;
1154 case EEXIST:
1155 return EEXISTS;
1156 default:
1157 return errno+100;
1161 if ( fstat(fd, &stbuf) < 0 )
1162 exit(EX_OSERR); /* This shouldn't happen */
1164 if (mode == RRQ) {
1165 if ( !unixperms && (stbuf.st_mode & (S_IREAD >> 6)) == 0 ) {
1166 *errmsg = "File must have global read permissions";
1167 return (EACCESS);
1169 tsize = stbuf.st_size;
1170 /* We don't know the tsize if conversion is needed */
1171 tsize_ok = !pf->f_convert;
1172 } else {
1173 if ( !unixperms ) {
1174 if ( (stbuf.st_mode & (S_IWRITE >> 6)) == 0 ) {
1175 *errmsg = "File must have global write permissions";
1176 return (EACCESS);
1179 /* We didn't get to truncate the file at open() time */
1180 #ifdef HAVE_FTRUNCATE
1181 if ( ftruncate(fd, (off_t)0) ) {
1182 *errmsg = "Cannot reset file size";
1183 return(EACCESS);
1185 #endif
1187 tsize = 0;
1188 tsize_ok = 1;
1191 stdio_mode[0] = (mode == RRQ) ? 'r':'w';
1192 stdio_mode[1] = (pf->f_convert) ? 't':'b';
1193 stdio_mode[2] = '\0';
1195 file = fdopen(fd, stdio_mode);
1196 if (file == NULL)
1197 exit(EX_OSERR); /* Internal error */
1199 return (0);
1203 * Send the requested file.
1205 void
1206 tftp_sendfile(struct formats *pf, struct tftphdr *oap, int oacklen)
1208 struct tftphdr *dp;
1209 struct tftphdr *ap; /* ack packet */
1210 static u_short block = 1; /* Static to avoid longjmp funnies */
1211 u_short ap_opcode, ap_block;
1212 unsigned long r_timeout;
1213 int size, n;
1215 if (oap) {
1216 timeout = rexmtval;
1217 (void)sigsetjmp(timeoutbuf,1);
1218 oack:
1219 r_timeout = timeout;
1220 if (send(peer, oap, oacklen, 0) != oacklen) {
1221 syslog(LOG_WARNING, "tftpd: oack: %m\n");
1222 goto abort;
1224 for ( ; ; ) {
1225 n = recv_time(peer, ackbuf, sizeof(ackbuf), 0, &r_timeout);
1226 if (n < 0) {
1227 syslog(LOG_WARNING, "tftpd: read: %m\n");
1228 goto abort;
1230 ap = (struct tftphdr *)ackbuf;
1231 ap_opcode = ntohs((u_short)ap->th_opcode);
1232 ap_block = ntohs((u_short)ap->th_block);
1234 if (ap_opcode == ERROR) {
1235 syslog(LOG_WARNING, "tftp: client does not accept options\n");
1236 goto abort;
1238 if (ap_opcode == ACK) {
1239 if (ap_block == 0)
1240 break;
1241 /* Resynchronize with the other side */
1242 (void)synchnet(peer);
1243 goto oack;
1248 dp = r_init();
1249 do {
1250 size = readit(file, &dp, pf->f_convert);
1251 if (size < 0) {
1252 nak(errno + 100, NULL);
1253 goto abort;
1255 dp->th_opcode = htons((u_short)DATA);
1256 dp->th_block = htons((u_short)block);
1257 timeout = rexmtval;
1258 (void) sigsetjmp(timeoutbuf,1);
1260 r_timeout = timeout;
1261 if (send(peer, dp, size + 4, 0) != size + 4) {
1262 syslog(LOG_WARNING, "tftpd: write: %m");
1263 goto abort;
1265 read_ahead(file, pf->f_convert);
1266 for ( ; ; ) {
1267 n = recv_time(peer, ackbuf, sizeof (ackbuf), 0, &r_timeout);
1268 if (n < 0) {
1269 syslog(LOG_WARNING, "tftpd: read(ack): %m");
1270 goto abort;
1272 ap = (struct tftphdr *)ackbuf;
1273 ap_opcode = ntohs((u_short)ap->th_opcode);
1274 ap_block = ntohs((u_short)ap->th_block);
1276 if (ap_opcode == ERROR)
1277 goto abort;
1279 if (ap_opcode == ACK) {
1280 if (ap_block == block) {
1281 break;
1283 /* Re-synchronize with the other side */
1284 (void) synchnet(peer);
1286 * RFC1129/RFC1350: We MUST NOT re-send the DATA
1287 * packet in response to an invalid ACK. Doing so
1288 * would cause the Sorcerer's Apprentice bug.
1293 block++;
1294 } while (size == segsize);
1295 abort:
1296 (void) fclose(file);
1299 /* Bail out signal handler */
1300 void
1301 justquit(int sig)
1303 (void)sig; /* Suppress unused warning */
1304 exit(0);
1309 * Receive a file.
1311 void
1312 tftp_recvfile(struct formats *pf, struct tftphdr *oap, int oacklen)
1314 struct tftphdr *dp;
1315 int n, size;
1316 /* These are "static" to avoid longjmp funnies */
1317 static struct tftphdr *ap; /* ack buffer */
1318 static u_short block = 0;
1319 static int acksize;
1320 u_short dp_opcode, dp_block;
1321 unsigned long r_timeout;
1323 dp = w_init();
1324 do {
1325 timeout = rexmtval;
1327 if (!block && oap) {
1328 ap = (struct tftphdr *)ackbuf;
1329 acksize = oacklen;
1330 } else {
1331 ap = (struct tftphdr *)ackbuf;
1332 ap->th_opcode = htons((u_short)ACK);
1333 ap->th_block = htons((u_short)block);
1334 acksize = 4;
1336 block++;
1337 (void) sigsetjmp(timeoutbuf,1);
1338 send_ack:
1339 r_timeout = timeout;
1340 if (send(peer, ackbuf, acksize, 0) != acksize) {
1341 syslog(LOG_WARNING, "tftpd: write(ack): %m");
1342 goto abort;
1344 write_behind(file, pf->f_convert);
1345 for ( ; ; ) {
1346 n = recv_time(peer, dp, PKTSIZE, 0, &r_timeout);
1347 if (n < 0) { /* really? */
1348 syslog(LOG_WARNING, "tftpd: read: %m");
1349 goto abort;
1351 dp_opcode = ntohs((u_short)dp->th_opcode);
1352 dp_block = ntohs((u_short)dp->th_block);
1353 if (dp_opcode == ERROR)
1354 goto abort;
1355 if (dp_opcode == DATA) {
1356 if (dp_block == block) {
1357 break; /* normal */
1359 /* Re-synchronize with the other side */
1360 (void) synchnet(peer);
1361 if (dp_block == (block-1))
1362 goto send_ack; /* rexmit */
1365 /* size = write(file, dp->th_data, n - 4); */
1366 size = writeit(file, &dp, n - 4, pf->f_convert);
1367 if (size != (n-4)) { /* ahem */
1368 if (size < 0) nak(errno + 100, NULL);
1369 else nak(ENOSPACE, NULL);
1370 goto abort;
1372 } while (size == segsize);
1373 write_behind(file, pf->f_convert);
1374 (void) fclose(file); /* close data file */
1376 ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */
1377 ap->th_block = htons((u_short)(block));
1378 (void) send(peer, ackbuf, 4, 0);
1380 timeout_quit = 1; /* just quit on timeout */
1381 n = recv_time(peer, buf, sizeof (buf), 0, &timeout); /* normally times out and quits */
1382 timeout_quit = 0;
1384 if (n >= 4 && /* if read some data */
1385 dp_opcode == DATA && /* and got a data block */
1386 block == dp_block) { /* then my last ack was lost */
1387 (void) send(peer, ackbuf, 4, 0); /* resend final ack */
1389 abort:
1390 return;
1393 static const char * const errmsgs[] =
1395 "Undefined error code", /* 0 - EUNDEF */
1396 "File not found", /* 1 - ENOTFOUND */
1397 "Access denied", /* 2 - EACCESS */
1398 "Disk full or allocation exceeded", /* 3 - ENOSPACE */
1399 "Illegal TFTP operation", /* 4 - EBADOP */
1400 "Unknown transfer ID", /* 5 - EBADID */
1401 "File already exists", /* 6 - EEXISTS */
1402 "No such user", /* 7 - ENOUSER */
1403 "Failure to negotiate RFC2347 options" /* 8 - EOPTNEG */
1405 #define ERR_CNT (sizeof(errmsgs)/sizeof(const char *))
1408 * Send a nak packet (error message).
1409 * Error code passed in is one of the
1410 * standard TFTP codes, or a UNIX errno
1411 * offset by 100.
1413 static void
1414 nak(int error, const char *msg)
1416 struct tftphdr *tp;
1417 int length;
1419 tp = (struct tftphdr *)buf;
1420 tp->th_opcode = htons((u_short)ERROR);
1422 if ( error >= 100 ) {
1423 /* This is a Unix errno+100 */
1424 if ( !msg )
1425 msg = strerror(error - 100);
1426 error = EUNDEF;
1427 } else {
1428 if ( (unsigned)error >= ERR_CNT )
1429 error = EUNDEF;
1431 if ( !msg )
1432 msg = errmsgs[error];
1435 tp->th_code = htons((u_short)error);
1437 length = strlen(msg)+1;
1438 memcpy(tp->th_msg, msg, length);
1439 length += 4; /* Add space for header */
1441 if ( verbosity >= 2 ) {
1442 syslog(LOG_INFO, "sending NAK (%d, %s) to %s",
1443 error, tp->th_msg, inet_ntoa(from.sin_addr));
1446 if (send(peer, buf, length, 0) != length)
1447 syslog(LOG_WARNING, "nak: %m");