Update version for release
[tftp-hpa.git] / tftpd / tftpd.c
blob92a68892082e03fe86ef26e670ac587df89aa641
1 /* $OpenBSD: tftpd.c,v 1.13 1999/06/23 17:01:36 deraadt Exp $ */
3 /*
4 * Copyright (c) 1983 Regents of the University of California.
5 * All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgement:
17 * This product includes software developed by the University of
18 * California, Berkeley and its contributors.
19 * 4. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
36 #include "config.h" /* Must be included first */
37 #include "tftpd.h"
39 #ifndef lint
40 static const char *copyright UNUSED =
41 "@(#) Copyright (c) 1983 Regents of the University of California.\n\
42 All rights reserved.\n";
43 /*static char sccsid[] = "from: @(#)tftpd.c 5.13 (Berkeley) 2/26/91";*/
44 /*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 $";*/
45 static const char *rcsid UNUSED =
46 "tftp-hpa $Id$";
47 #endif /* not lint */
50 * Trivial file transfer protocol server.
52 * This version includes many modifications by Jim Guyton <guyton@rand-unix>
55 #include <sys/ioctl.h>
56 #include <signal.h>
57 #include <netdb.h>
58 #include <ctype.h>
59 #include <pwd.h>
60 #include <limits.h>
61 #include <syslog.h>
63 #include "common/tftpsubs.h"
64 #include "recvfrom.h"
65 #include "remap.h"
67 #ifdef HAVE_SYS_FILIO_H
68 #include <sys/filio.h> /* Necessary for FIONBIO on Solaris */
69 #endif
71 #ifdef HAVE_TCPWRAPPERS
72 #include <tcpd.h>
74 int deny_severity = LOG_WARNING;
75 int allow_severity = -1; /* Don't log at all */
77 struct request_info wrap_request;
78 #endif
80 #define TIMEOUT 1000000 /* Default timeout (us) */
81 #define TRIES 6 /* Number of attempts to send each packet */
82 #define TIMEOUT_LIMIT ((1 << TRIES)-1)
84 const char *__progname;
85 int peer;
86 unsigned long timeout = TIMEOUT; /* Current timeout value */
87 unsigned long rexmtval = TIMEOUT; /* Basic timeout value */
88 unsigned long maxtimeout = TIMEOUT_LIMIT*TIMEOUT;
89 int timeout_quit = 0;
90 sigjmp_buf timeoutbuf;
92 #define PKTSIZE MAX_SEGSIZE+4
93 char buf[PKTSIZE];
94 char ackbuf[PKTSIZE];
95 unsigned int max_blksize = MAX_SEGSIZE;
97 struct sockaddr_in from;
98 socklen_t fromlen;
99 off_t tsize;
100 int tsize_ok;
102 int ndirs;
103 const char **dirs;
105 int secure = 0;
106 int cancreate = 0;
107 int unixperms = 0;
108 int portrange = 0;
109 unsigned int portrange_from, portrange_to;
110 int verbosity = 0;
112 struct formats;
113 #ifdef WITH_REGEX
114 static struct rule *rewrite_rules = NULL;
115 #endif
117 int tftp(struct tftphdr *, int);
118 static void nak(int, const char *);
119 void timer(int);
120 void justquit(int);
121 void do_opt(char *, char *, char **);
123 int set_blksize(char *, char **);
124 int set_blksize2(char *, char **);
125 int set_tsize(char *, char **);
126 int set_timeout(char *, char **);
127 int set_utimeout(char *, char **);
129 struct options {
130 const char *o_opt;
131 int (*o_fnc)(char *, char **);
132 } options[] = {
133 { "blksize", set_blksize },
134 { "blksize2", set_blksize2 },
135 { "tsize", set_tsize },
136 { "timeout", set_timeout },
137 { "utimeout", set_utimeout },
138 { NULL, NULL }
141 /* Simple handler for SIGHUP */
142 static volatile sig_atomic_t caught_sighup = 0;
143 static void handle_sighup(int sig)
145 (void)sig; /* Suppress unused warning */
146 caught_sighup = 1;
150 /* Handle timeout signal or timeout event */
151 void
152 timer(int sig)
154 (void)sig; /* Suppress unused warning */
155 timeout <<= 1;
156 if (timeout >= maxtimeout || timeout_quit)
157 exit(0);
158 siglongjmp(timeoutbuf, 1);
161 static void
162 usage(void)
164 syslog(LOG_ERR, "Usage: %s [-vcl][-a address][-m mappings][-u user][-t inetd_timeout][-T pkt_timeout][-r option...] [-s] [directory ...]",
165 __progname);
166 exit(EX_USAGE);
170 #ifdef WITH_REGEX
171 static struct rule *
172 read_remap_rules(const char *file)
174 FILE *f;
175 struct rule *rulep;
177 f = fopen(file, "rt");
178 if ( !f ) {
179 syslog(LOG_ERR, "Cannot open map file: %s: %m", file);
180 exit(EX_NOINPUT);
182 rulep = parserulefile(f);
183 fclose(f);
185 return rulep;
187 #endif
189 static void
190 set_socket_nonblock(int fd, int flag)
192 int err;
193 int flags;
194 #if defined(HAVE_FCNTL) && defined(HAVE_O_NONBLOCK_DEFINITION)
195 /* Posixly correct */
196 err = ((flags = fcntl(fd, F_GETFL, 0)) < 0) ||
197 (fcntl(fd, F_SETFL, flag ? flags|O_NONBLOCK : flags&~O_NONBLOCK) < 0);
198 #else
199 flags = flag ? 1 : 0;
200 err = (ioctl(fd, FIONBIO, &flags) < 0);
201 #endif
202 if ( err ) {
203 syslog(LOG_ERR, "Cannot set nonblock flag on socket: %m");
204 exit(EX_OSERR);
208 static void
209 pmtu_discovery_off(int fd)
211 #if defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
212 int pmtu = IP_PMTUDISC_DONT;
214 setsockopt(fd, IPPROTO_IP, IP_MTU_DISCOVER, &pmtu, sizeof(pmtu));
215 #endif
219 * Receive packet with synchronous timeout; timeout is adjusted
220 * to account for time spent waiting.
222 static int recv_time(int s, void *rbuf, int len, unsigned int flags,
223 unsigned long *timeout_us_p)
225 fd_set fdset;
226 struct timeval tmv, t0, t1;
227 int rv, err;
228 unsigned long timeout_us = *timeout_us_p;
229 unsigned long timeout_left, dt;
231 gettimeofday(&t0, NULL);
232 timeout_left = timeout_us;
234 for ( ; ; ) {
235 FD_ZERO(&fdset);
236 FD_SET(s, &fdset);
238 do {
239 tmv.tv_sec = timeout_left / 1000000;
240 tmv.tv_usec = timeout_left % 1000000;
242 rv = select(s+1, &fdset, NULL, NULL, &tmv);
243 err = errno;
245 gettimeofday(&t1, NULL);
247 dt = (t1.tv_sec - t0.tv_sec)*1000000 + (t1.tv_usec - t0.tv_usec);
248 *timeout_us_p = timeout_left = ( dt >= timeout_us ) ? 1 : (timeout_us - dt);
249 } while ( rv == -1 && err == EINTR );
251 if ( rv == 0 ) {
252 timer(0); /* Should not return */
253 return -1;
256 set_socket_nonblock(s, 1);
257 rv = recv(s, rbuf, len, flags);
258 err = errno;
259 set_socket_nonblock(s, 0);
261 if ( rv < 0 ) {
262 if ( E_WOULD_BLOCK(err) || err == EINTR ) {
263 continue; /* Once again, with feeling... */
264 } else {
265 errno = err;
266 return rv;
268 } else {
269 return rv;
276 main(int argc, char **argv)
278 struct tftphdr *tp;
279 struct passwd *pw;
280 struct options *opt;
281 struct sockaddr_in myaddr;
282 struct sockaddr_in bindaddr;
283 int n;
284 int fd = 0;
285 int standalone = 0; /* Standalone (listen) mode */
286 int nodaemon = 0; /* Do not detach process */
287 char *address = NULL; /* Address to listen to */
288 pid_t pid;
289 mode_t my_umask = 0;
290 int spec_umask = 0;
291 int c;
292 int setrv;
293 int waittime = 900; /* Default time to wait for a connect*/
294 const char *user = "nobody"; /* Default user */
295 char *p, *ep;
296 #ifdef WITH_REGEX
297 char *rewrite_file = NULL;
298 #endif
299 u_short tp_opcode;
301 /* basename() is way too much of a pain from a portability standpoint */
303 p = strrchr(argv[0], '/');
304 __progname = (p && p[1]) ? p+1 : argv[0];
306 openlog(__progname, LOG_PID|LOG_NDELAY, LOG_DAEMON);
308 srand(time(NULL) ^ getpid());
310 while ((c = getopt(argc, argv, "cspvVlLa:B:u:U:r:t:T:R:m:")) != -1)
311 switch (c) {
312 case 'c':
313 cancreate = 1;
314 break;
315 case 's':
316 secure = 1;
317 break;
318 case 'p':
319 unixperms = 1;
320 break;
321 case 'l':
322 standalone = 1;
323 break;
324 case 'L':
325 standalone = 1;
326 nodaemon = 1;
327 break;
328 case 'a':
329 address = optarg;
330 break;
331 case 't':
332 waittime = atoi(optarg);
333 break;
334 case 'B':
336 char *vp;
337 max_blksize = (unsigned int)strtoul(optarg, &vp, 10);
338 if ( max_blksize < 512 || max_blksize > MAX_SEGSIZE || *vp ) {
339 syslog(LOG_ERR, "Bad maximum blocksize value (range 512-%d): %s",
340 MAX_SEGSIZE, optarg);
341 exit(EX_USAGE);
344 break;
345 case 'T':
347 char *vp;
348 unsigned long tov = strtoul(optarg, &vp, 10);
349 if ( tov < 10000UL || tov > 255000000UL || *vp ) {
350 syslog(LOG_ERR, "Bad timeout value: %s", optarg);
351 exit(EX_USAGE);
353 rexmtval = timeout = tov;
354 maxtimeout = rexmtval*TIMEOUT_LIMIT;
356 break;
357 case 'R':
359 if ( sscanf(optarg, "%u:%u", &portrange_from, &portrange_to) != 2 ||
360 portrange_from > portrange_to || portrange_to >= 65535 ) {
361 syslog(LOG_ERR, "Bad port range: %s", optarg);
362 exit(EX_USAGE);
364 portrange = 1;
366 break;
367 case 'u':
368 user = optarg;
369 break;
370 case 'U':
371 my_umask = strtoul(optarg, &ep, 8);
372 if ( *ep ) {
373 syslog(LOG_ERR, "Invalid umask: %s", optarg);
374 exit(EX_USAGE);
376 spec_umask = 1;
377 break;
378 case 'r':
379 for ( opt = options ; opt->o_opt ; opt++ ) {
380 if ( !strcasecmp(optarg, opt->o_opt) ) {
381 opt->o_opt = ""; /* Don't support this option */
382 break;
385 if ( !opt->o_opt ) {
386 syslog(LOG_ERR, "Unknown option: %s", optarg);
387 exit(EX_USAGE);
389 break;
390 #ifdef WITH_REGEX
391 case 'm':
392 if ( rewrite_file ) {
393 syslog(LOG_ERR, "Multiple -m options");
394 exit(EX_USAGE);
396 rewrite_file = optarg;
397 break;
398 #endif
399 case 'v':
400 verbosity++;
401 break;
402 case 'V':
403 /* Print configuration to stdout and exit */
404 printf("%s\n", TFTPD_CONFIG_STR);
405 exit(0);
406 break;
407 default:
408 usage();
409 break;
412 dirs = xmalloc((argc-optind+1)*sizeof(char *));
413 for ( ndirs = 0 ; optind != argc ; optind++ )
414 dirs[ndirs++] = argv[optind];
416 dirs[ndirs] = NULL;
418 if (secure) {
419 if (ndirs == 0) {
420 syslog(LOG_ERR, "no -s directory");
421 exit(EX_USAGE);
423 if (ndirs > 1) {
424 syslog(LOG_ERR, "too many -s directories");
425 exit(EX_USAGE);
427 if (chdir(dirs[0])) {
428 syslog(LOG_ERR, "%s: %m", dirs[0]);
429 exit(EX_NOINPUT);
433 pw = getpwnam(user);
434 if (!pw) {
435 syslog(LOG_ERR, "no user %s: %m", user);
436 exit(EX_NOUSER);
439 if ( spec_umask || !unixperms )
440 umask(my_umask);
442 /* Note: on Cygwin, select() on a nonblocking socket becomes
443 a nonblocking select. */
444 #ifndef __CYGWIN__
445 set_socket_nonblock(fd, 1);
446 #endif
448 #ifdef WITH_REGEX
449 if ( rewrite_file )
450 rewrite_rules = read_remap_rules(rewrite_file);
451 #endif
453 /* If we're running standalone, set up the input port */
454 if ( standalone ) {
455 fd = socket(PF_INET, SOCK_DGRAM, 0);
457 memset(&bindaddr, 0, sizeof bindaddr);
458 bindaddr.sin_family = AF_INET;
459 bindaddr.sin_addr.s_addr = INADDR_ANY;
460 bindaddr.sin_port = htons(IPPORT_TFTP);
462 if ( address ) {
463 char *portptr, *eportptr;
464 struct hostent *hostent;
465 struct servent *servent;
466 unsigned long port;
468 address = tfstrdup(address);
469 portptr = strrchr(address, ':');
470 if ( portptr )
471 *portptr++ = '\0';
473 if ( *address ) {
474 hostent = gethostbyname(address);
475 if ( !hostent || hostent->h_addrtype != AF_INET ) {
476 syslog(LOG_ERR, "cannot resolve local bind address: %s", address);
477 exit(EX_NOINPUT);
479 memcpy(&bindaddr.sin_addr, hostent->h_addr, hostent->h_length);
480 } else {
481 /* Default to using INADDR_ANY */
484 if ( portptr && *portptr ) {
485 servent = getservbyname(portptr, "udp");
486 if ( servent ) {
487 bindaddr.sin_port = servent->s_port;
488 } else if ( (port = strtoul(portptr, &eportptr, 0)) && !*eportptr ) {
489 bindaddr.sin_port = htons(port);
490 } else if ( !strcmp(portptr, "tftp") ) {
491 /* It's TFTP, we're OK */
492 } else {
493 syslog(LOG_ERR, "cannot resolve local bind port: %s", portptr);
494 exit(EX_NOINPUT);
499 if (bind(fd, (struct sockaddr *)&bindaddr, sizeof bindaddr) < 0) {
500 syslog(LOG_ERR, "cannot bind to local socket: %m");
501 exit(EX_OSERR);
504 /* Daemonize this process */
505 /* Note: when running in secure mode (-s), we must not chroot, since
506 we are already in the proper directory. */
507 if (!nodaemon && daemon(secure, 0) < 0) {
508 syslog(LOG_ERR, "cannot daemonize: %m");
509 exit(EX_OSERR);
511 } else {
512 /* 0 is our socket descriptor */
513 close(1); close(2);
516 /* Disable path MTU discovery */
517 pmtu_discovery_off(0);
519 /* This means we don't want to wait() for children */
520 #ifdef SA_NOCLDWAIT
521 set_signal(SIGCHLD, SIG_IGN, SA_NOCLDSTOP|SA_NOCLDWAIT);
522 #else
523 set_signal(SIGCHLD, SIG_IGN, SA_NOCLDSTOP);
524 #endif
526 /* Take SIGHUP and use it to set a variable. This
527 is polled synchronously to make sure we don't
528 lose packets as a result. */
529 set_signal(SIGHUP, handle_sighup, 0);
531 while ( 1 ) {
532 fd_set readset;
533 struct timeval tv_waittime;
534 int rv;
536 if ( caught_sighup ) {
537 caught_sighup = 0;
538 if ( standalone ) {
539 #ifdef WITH_REGEX
540 if ( rewrite_file ) {
541 freerules(rewrite_rules);
542 rewrite_rules = read_remap_rules(rewrite_file);
544 #endif
545 } else {
546 /* Return to inetd for respawn */
547 exit(0);
551 FD_ZERO(&readset);
552 FD_SET(fd, &readset);
553 tv_waittime.tv_sec = waittime;
554 tv_waittime.tv_usec = 0;
556 #ifdef __CYGWIN__
557 /* On Cygwin, select() on a nonblocking socket returns immediately,
558 with a rv of 0! */
559 set_socket_nonblock(fd, 0);
560 #endif
562 /* Never time out if we're in standalone mode */
563 rv = select(fd+1, &readset, NULL, NULL, standalone ? NULL : &tv_waittime);
564 if ( rv == -1 && errno == EINTR )
565 continue; /* Signal caught, reloop */
566 if ( rv == -1 ) {
567 syslog(LOG_ERR, "select loop: %m");
568 exit(EX_IOERR);
569 } else if ( rv == 0 ) {
570 exit(0); /* Timeout, return to inetd */
573 #ifdef __CYGWIN__
574 set_socket_nonblock(fd, 1);
575 #endif
577 fromlen = sizeof (from);
578 n = myrecvfrom(fd, buf, sizeof (buf), 0,
579 (struct sockaddr *)&from, &fromlen,
580 &myaddr);
582 if ( n < 0 ) {
583 if ( E_WOULD_BLOCK(errno) || errno == EINTR ) {
584 continue; /* Again, from the top */
585 } else {
586 syslog(LOG_ERR, "recvfrom: %m");
587 exit(EX_IOERR);
591 if ( from.sin_family != AF_INET ) {
592 syslog(LOG_ERR, "received address was not AF_INET, please check your inetd config");
593 exit(EX_PROTOCOL);
596 if ( standalone && myaddr.sin_addr.s_addr == INADDR_ANY ) {
597 /* myrecvfrom() didn't capture the source address; but we might
598 have bound to a specific address, if so we should use it */
599 memcpy(&myaddr.sin_addr, &bindaddr.sin_addr, sizeof bindaddr.sin_addr);
603 * Now that we have read the request packet from the UDP
604 * socket, we fork and go back to listening to the socket.
606 pid = fork();
607 if (pid < 0) {
608 syslog(LOG_ERR, "fork: %m");
609 exit(EX_OSERR); /* Return to inetd, just in case */
610 } else if ( pid == 0 )
611 break; /* Child exit, parent loop */
614 /* Child process: handle the actual request here */
616 /* Ignore SIGHUP */
617 set_signal(SIGHUP, SIG_IGN, 0);
619 #ifdef HAVE_TCPWRAPPERS
620 /* Verify if this was a legal request for us. This has to be
621 done before the chroot, while /etc is still accessible. */
622 request_init(&wrap_request,
623 RQ_DAEMON, __progname,
624 RQ_FILE, fd,
625 RQ_CLIENT_SIN, &from,
626 RQ_SERVER_SIN, &myaddr,
628 sock_methods(&wrap_request);
629 if ( hosts_access(&wrap_request) == 0 ) {
630 if ( deny_severity != -1 )
631 syslog(deny_severity, "connection refused from %s",
632 inet_ntoa(from.sin_addr));
633 exit(EX_NOPERM); /* Access denied */
634 } else if ( allow_severity != -1 ) {
635 syslog(allow_severity, "connect from %s",
636 inet_ntoa(from.sin_addr));
638 #endif
640 /* Close file descriptors we don't need */
641 close(fd);
643 /* Get a socket. This has to be done before the chroot(), since
644 some systems require access to /dev to create a socket. */
646 peer = socket(AF_INET, SOCK_DGRAM, 0);
647 if (peer < 0) {
648 syslog(LOG_ERR, "socket: %m");
649 exit(EX_IOERR);
652 /* Set up the supplementary group access list if possible */
653 /* /etc/group still need to be accessible at this point */
654 #ifdef HAVE_INITGROUPS
655 setrv = initgroups(user, pw->pw_gid);
656 if ( setrv ) {
657 syslog(LOG_ERR, "cannot set groups for user %s", user);
658 exit(EX_OSERR);
660 #else
661 #ifdef HAVE_SETGROUPS
662 if ( setgroups(0, NULL) ) {
663 syslog(LOG_ERR, "cannot clear group list");
665 #endif
666 #endif
668 /* Chroot and drop privileges */
669 if (secure) {
670 if (chroot(".")) {
671 syslog(LOG_ERR, "chroot: %m");
672 exit(EX_OSERR);
674 #ifdef __CYGWIN__
675 chdir("/"); /* Cygwin chroot() bug workaround */
676 #endif
679 #ifdef HAVE_SETREGID
680 setrv = setregid(pw->pw_gid, pw->pw_gid);
681 #else
682 setrv = setegid(pw->pw_gid) || setgid(pw->pw_gid);
683 #endif
685 #ifdef HAVE_SETREUID
686 setrv = setrv || setreuid(pw->pw_uid, pw->pw_uid);
687 #else
688 /* Important: setuid() must come first */
689 setrv = setrv || setuid(pw->pw_uid) ||
690 (geteuid() != pw->pw_uid && seteuid(pw->pw_uid));
691 #endif
693 if ( setrv ) {
694 syslog(LOG_ERR, "cannot drop privileges: %m");
695 exit(EX_OSERR);
698 /* Other basic setup */
699 from.sin_family = AF_INET;
701 /* Process the request... */
702 if (pick_port_bind(peer, &myaddr, portrange_from, portrange_to) < 0) {
703 syslog(LOG_ERR, "bind: %m");
704 exit(EX_IOERR);
707 if (connect(peer, (struct sockaddr *)&from, sizeof from) < 0) {
708 syslog(LOG_ERR, "connect: %m");
709 exit(EX_IOERR);
712 /* Disable path MTU discovery */
713 pmtu_discovery_off(0);
715 tp = (struct tftphdr *)buf;
716 tp_opcode = ntohs(tp->th_opcode);
717 if (tp_opcode == RRQ || tp_opcode == WRQ)
718 tftp(tp, n);
719 exit(0);
722 char *rewrite_access(char *, int, const char **);
723 int validate_access(char *, int, struct formats *, const char **);
724 void tftp_sendfile(struct formats *, struct tftphdr *, int);
725 void tftp_recvfile(struct formats *, struct tftphdr *, int);
727 struct formats {
728 const char *f_mode;
729 char *(*f_rewrite)(char *, int, const char **);
730 int (*f_validate)(char *, int, struct formats *, const char **);
731 void (*f_send)(struct formats *, struct tftphdr *, int);
732 void (*f_recv)(struct formats *, struct tftphdr *, int);
733 int f_convert;
734 } formats[] = {
735 { "netascii", rewrite_access, validate_access, tftp_sendfile, tftp_recvfile, 1 },
736 { "octet", rewrite_access, validate_access, tftp_sendfile, tftp_recvfile, 0 },
737 { NULL, NULL, NULL, NULL, NULL, 0 }
741 * Handle initial connection protocol.
744 tftp(struct tftphdr *tp, int size)
746 char *cp, *end;
747 int argn, ecode;
748 struct formats *pf = NULL;
749 char *origfilename;
750 char *filename, *mode = NULL;
751 const char *errmsgptr;
752 u_short tp_opcode = ntohs(tp->th_opcode);
754 char *val = NULL, *opt = NULL;
755 char *ap = ackbuf + 2;
757 ((struct tftphdr *)ackbuf)->th_opcode = htons(OACK);
759 origfilename = cp = (char *) &(tp->th_stuff);
760 argn = 0;
762 end = (char *)tp + size;
764 while ( cp < end && *cp ) {
765 do {
766 cp++;
767 } while (cp < end && *cp);
769 if ( *cp ) {
770 nak(EBADOP, "Request not null-terminated");
771 exit(0);
774 argn++;
775 if (argn == 1) {
776 mode = ++cp;
777 } else if (argn == 2) {
778 for (cp = mode; *cp; cp++)
779 *cp = tolower(*cp);
780 for (pf = formats; pf->f_mode; pf++) {
781 if (!strcmp(pf->f_mode, mode))
782 break;
784 if (!pf->f_mode) {
785 nak(EBADOP, "Unknown mode");
786 exit(0);
788 if ( !(filename =
789 (*pf->f_rewrite)(origfilename, tp_opcode, &errmsgptr)) ) {
790 nak(EACCESS, errmsgptr); /* File denied by mapping rule */
791 exit(0);
793 if ( verbosity >= 1 ) {
794 if ( filename == origfilename || !strcmp(filename, origfilename) )
795 syslog(LOG_NOTICE, "%s from %s filename %s\n",
796 tp_opcode == WRQ ? "WRQ" : "RRQ",
797 inet_ntoa(from.sin_addr), filename);
798 else
799 syslog(LOG_NOTICE, "%s from %s filename %s remapped to %s\n",
800 tp_opcode == WRQ ? "WRQ" : "RRQ",
801 inet_ntoa(from.sin_addr), origfilename, filename);
803 ecode = (*pf->f_validate)(filename, tp_opcode, pf, &errmsgptr);
804 if (ecode) {
805 nak(ecode, errmsgptr);
806 exit(0);
808 opt = ++cp;
809 } else if ( argn & 1 ) {
810 val = ++cp;
811 } else {
812 do_opt(opt, val, &ap);
813 opt = ++cp;
817 if (!pf) {
818 nak(EBADOP, "Missing mode");
819 exit(0);
822 if ( ap != (ackbuf+2) ) {
823 if ( tp_opcode == WRQ )
824 (*pf->f_recv)(pf, (struct tftphdr *)ackbuf, ap-ackbuf);
825 else
826 (*pf->f_send)(pf, (struct tftphdr *)ackbuf, ap-ackbuf);
827 } else {
828 if (tp_opcode == WRQ)
829 (*pf->f_recv)(pf, NULL, 0);
830 else
831 (*pf->f_send)(pf, NULL, 0);
833 exit(0); /* Request completed */
836 static int blksize_set;
839 * Set a non-standard block size (c.f. RFC2348)
842 set_blksize(char *val, char **ret)
844 static char b_ret[6];
845 unsigned int sz;
846 char *vend;
848 sz = (unsigned int)strtoul(val, &vend, 10);
850 if ( blksize_set || *vend )
851 return 0;
853 if (sz < 8)
854 return(0);
855 else if (sz > max_blksize)
856 sz = max_blksize;
858 segsize = sz;
859 sprintf(*ret = b_ret, "%u", sz);
861 blksize_set = 1;
863 return(1);
867 * Set a power-of-two block size (nonstandard)
870 set_blksize2(char *val, char **ret)
872 static char b_ret[6];
873 unsigned int sz;
874 char *vend;
876 sz = (unsigned int)strtoul(val, &vend, 10);
878 if ( blksize_set || *vend )
879 return 0;
881 if (sz < 8)
882 return(0);
883 else if (sz > max_blksize)
884 sz = max_blksize;
886 /* Convert to a power of two */
887 if ( sz & (sz-1) ) {
888 unsigned int sz1 = 1;
889 /* Not a power of two - need to convert */
890 while ( sz >>= 1 )
891 sz1 <<= 1;
892 sz = sz1;
895 segsize = sz;
896 sprintf(*ret = b_ret, "%u", sz);
898 blksize_set = 1;
900 return(1);
904 * Return a file size (c.f. RFC2349)
905 * For netascii mode, we don't know the size ahead of time;
906 * so reject the option.
909 set_tsize(char *val, char **ret)
911 static char b_ret[sizeof(uintmax_t)*CHAR_BIT/3+2];
912 uintmax_t sz;
913 char *vend;
915 sz = strtoumax(val, &vend, 10);
917 if ( !tsize_ok || *vend )
918 return 0;
920 if (sz == 0)
921 sz = (uintmax_t)tsize;
923 sprintf(*ret = b_ret, "%"PRIuMAX, sz);
924 return(1);
928 * Set the timeout (c.f. RFC2349). This is supposed
929 * to be the (default) retransmission timeout, but being an
930 * integer in seconds it seems a bit limited.
933 set_timeout(char *val, char **ret)
935 static char b_ret[4];
936 unsigned long to;
937 char *vend;
939 to = strtoul(val, &vend, 10);
941 if ( to < 1 || to > 255 || *vend )
942 return 0;
944 rexmtval = timeout = to*1000000UL;
945 maxtimeout = rexmtval*TIMEOUT_LIMIT;
947 sprintf(*ret = b_ret, "%lu", to);
948 return(1);
951 /* Similar, but in microseconds. We allow down to 10 ms. */
953 set_utimeout(char *val, char **ret)
955 static char b_ret[4];
956 unsigned long to;
957 char *vend;
959 to = strtoul(val, &vend, 10);
961 if ( to < 10000UL || to > 255000000UL || *vend )
962 return 0;
964 rexmtval = timeout = to;
965 maxtimeout = rexmtval*TIMEOUT_LIMIT;
967 sprintf(*ret = b_ret, "%lu", to);
968 return(1);
971 * Parse RFC2347 style options
973 void
974 do_opt(char *opt, char *val, char **ap)
976 struct options *po;
977 char *ret;
979 /* Global option-parsing variables initialization */
980 blksize_set = 0;
982 if ( !*opt )
983 return;
985 for (po = options; po->o_opt; po++)
986 if (!strcasecmp(po->o_opt, opt)) {
987 if (po->o_fnc(val, &ret)) {
988 if (*ap + strlen(opt) + strlen(ret) + 2 >=
989 ackbuf + sizeof(ackbuf)) {
990 nak(EOPTNEG, "Insufficient space for options");
991 exit(0);
993 *ap = strrchr(strcpy(strrchr(strcpy(*ap, opt),'\0') + 1,
994 ret),'\0') + 1;
995 } else {
996 nak(EOPTNEG, "Unsupported option(s) requested");
997 exit(0);
999 break;
1001 return;
1004 #ifdef WITH_REGEX
1007 * This is called by the remap engine when it encounters macros such
1008 * as \i. It should write the output in "output" if non-NULL, and
1009 * return the length of the output (generated or not).
1011 * Return -1 on failure.
1014 rewrite_macros(char macro, char *output);
1017 rewrite_macros(char macro, char *output)
1019 char *p;
1021 switch (macro) {
1022 case 'i':
1023 p = inet_ntoa(from.sin_addr);
1024 if ( output )
1025 strcpy(output, p);
1026 return strlen(p);
1028 case 'x':
1029 if ( output )
1030 sprintf(output, "%08lX", (unsigned long)ntohl(from.sin_addr.s_addr));
1031 return 8;
1033 default:
1034 return -1;
1039 * Modify the filename, if applicable. If it returns NULL, deny the access.
1041 char *
1042 rewrite_access(char *filename, int mode, const char **msg)
1044 if ( rewrite_rules ) {
1045 char *newname = rewrite_string(filename, rewrite_rules, mode != RRQ,
1046 rewrite_macros, msg);
1047 filename = newname;
1049 return filename;
1052 #else
1053 char *
1054 rewrite_access(char *filename, int mode, const char **msg)
1056 (void)mode; /* Avoid warning */
1057 (void)msg;
1058 return filename;
1060 #endif
1062 FILE *file;
1064 * Validate file access. Since we
1065 * have no uid or gid, for now require
1066 * file to exist and be publicly
1067 * readable/writable, unless -p specified.
1068 * If we were invoked with arguments
1069 * from inetd then the file must also be
1070 * in one of the given directory prefixes.
1071 * Note also, full path name must be
1072 * given as we have no login directory.
1075 validate_access(char *filename, int mode,
1076 struct formats *pf, const char **errmsg)
1078 struct stat stbuf;
1079 int i, len;
1080 int fd, wmode, rmode;
1081 char *cp;
1082 const char **dirp;
1083 char stdio_mode[3];
1085 tsize_ok = 0;
1086 *errmsg = NULL;
1088 if (!secure) {
1089 if (*filename != '/') {
1090 *errmsg = "Only absolute filenames allowed";
1091 return (EACCESS);
1095 * prevent tricksters from getting around the directory
1096 * restrictions
1098 len = strlen(filename);
1099 for ( i = 1 ; i < len-3 ; i++ ) {
1100 cp = filename + i;
1101 if ( *cp == '.' && memcmp(cp-1, "/../", 4) == 0 ) {
1102 *errmsg = "Reverse path not allowed";
1103 return(EACCESS);
1107 for (dirp = dirs; *dirp; dirp++)
1108 if (strncmp(filename, *dirp, strlen(*dirp)) == 0)
1109 break;
1110 if (*dirp==0 && dirp!=dirs) {
1111 *errmsg = "Forbidden directory";
1112 return (EACCESS);
1117 * We use different a different permissions scheme if `cancreate' is
1118 * set.
1120 wmode = O_WRONLY |
1121 (cancreate ? O_CREAT : 0) |
1122 (unixperms ? O_TRUNC : 0) |
1123 (pf->f_convert ? O_TEXT : O_BINARY);
1124 rmode = O_RDONLY |
1125 (pf->f_convert ? O_TEXT : O_BINARY);
1127 fd = open(filename, mode == RRQ ? rmode : wmode, 0666);
1128 if (fd < 0) {
1129 switch (errno) {
1130 case ENOENT:
1131 case ENOTDIR:
1132 return ENOTFOUND;
1133 case ENOSPC:
1134 return ENOSPACE;
1135 case EEXIST:
1136 return EEXISTS;
1137 default:
1138 return errno+100;
1142 if ( fstat(fd, &stbuf) < 0 )
1143 exit(EX_OSERR); /* This shouldn't happen */
1145 if (mode == RRQ) {
1146 if ( !unixperms && (stbuf.st_mode & (S_IREAD >> 6)) == 0 ) {
1147 *errmsg = "File must have global read permissions";
1148 return (EACCESS);
1150 tsize = stbuf.st_size;
1151 /* We don't know the tsize if conversion is needed */
1152 tsize_ok = !pf->f_convert;
1153 } else {
1154 if ( !unixperms ) {
1155 if ( (stbuf.st_mode & (S_IWRITE >> 6)) == 0 ) {
1156 *errmsg = "File must have global write permissions";
1157 return (EACCESS);
1160 /* We didn't get to truncate the file at open() time */
1161 #ifdef HAVE_FTRUNCATE
1162 if ( ftruncate(fd, (off_t)0) ) {
1163 *errmsg = "Cannot reset file size";
1164 return(EACCESS);
1166 #endif
1168 tsize = 0;
1169 tsize_ok = 1;
1172 stdio_mode[0] = (mode == RRQ) ? 'r':'w';
1173 stdio_mode[1] = (pf->f_convert) ? 't':'b';
1174 stdio_mode[2] = '\0';
1176 file = fdopen(fd, stdio_mode);
1177 if (file == NULL)
1178 exit(EX_OSERR); /* Internal error */
1180 return (0);
1184 * Send the requested file.
1186 void
1187 tftp_sendfile(struct formats *pf, struct tftphdr *oap, int oacklen)
1189 struct tftphdr *dp;
1190 struct tftphdr *ap; /* ack packet */
1191 static u_short block = 1; /* Static to avoid longjmp funnies */
1192 u_short ap_opcode, ap_block;
1193 unsigned long r_timeout;
1194 int size, n;
1196 if (oap) {
1197 timeout = rexmtval;
1198 (void)sigsetjmp(timeoutbuf,1);
1199 oack:
1200 r_timeout = timeout;
1201 if (send(peer, oap, oacklen, 0) != oacklen) {
1202 syslog(LOG_WARNING, "tftpd: oack: %m\n");
1203 goto abort;
1205 for ( ; ; ) {
1206 n = recv_time(peer, ackbuf, sizeof(ackbuf), 0, &r_timeout);
1207 if (n < 0) {
1208 syslog(LOG_WARNING, "tftpd: read: %m\n");
1209 goto abort;
1211 ap = (struct tftphdr *)ackbuf;
1212 ap_opcode = ntohs((u_short)ap->th_opcode);
1213 ap_block = ntohs((u_short)ap->th_block);
1215 if (ap_opcode == ERROR) {
1216 syslog(LOG_WARNING, "tftp: client does not accept options\n");
1217 goto abort;
1219 if (ap_opcode == ACK) {
1220 if (ap_block == 0)
1221 break;
1222 /* Resynchronize with the other side */
1223 (void)synchnet(peer);
1224 goto oack;
1229 dp = r_init();
1230 do {
1231 size = readit(file, &dp, pf->f_convert);
1232 if (size < 0) {
1233 nak(errno + 100, NULL);
1234 goto abort;
1236 dp->th_opcode = htons((u_short)DATA);
1237 dp->th_block = htons((u_short)block);
1238 timeout = rexmtval;
1239 (void) sigsetjmp(timeoutbuf,1);
1241 r_timeout = timeout;
1242 if (send(peer, dp, size + 4, 0) != size + 4) {
1243 syslog(LOG_WARNING, "tftpd: write: %m");
1244 goto abort;
1246 read_ahead(file, pf->f_convert);
1247 for ( ; ; ) {
1248 n = recv_time(peer, ackbuf, sizeof (ackbuf), 0, &r_timeout);
1249 if (n < 0) {
1250 syslog(LOG_WARNING, "tftpd: read(ack): %m");
1251 goto abort;
1253 ap = (struct tftphdr *)ackbuf;
1254 ap_opcode = ntohs((u_short)ap->th_opcode);
1255 ap_block = ntohs((u_short)ap->th_block);
1257 if (ap_opcode == ERROR)
1258 goto abort;
1260 if (ap_opcode == ACK) {
1261 if (ap_block == block) {
1262 break;
1264 /* Re-synchronize with the other side */
1265 (void) synchnet(peer);
1267 * RFC1129/RFC1350: We MUST NOT re-send the DATA
1268 * packet in response to an invalid ACK. Doing so
1269 * would cause the Sorcerer's Apprentice bug.
1274 block++;
1275 } while (size == segsize);
1276 abort:
1277 (void) fclose(file);
1280 /* Bail out signal handler */
1281 void
1282 justquit(int sig)
1284 (void)sig; /* Suppress unused warning */
1285 exit(0);
1290 * Receive a file.
1292 void
1293 tftp_recvfile(struct formats *pf, struct tftphdr *oap, int oacklen)
1295 struct tftphdr *dp;
1296 int n, size;
1297 /* These are "static" to avoid longjmp funnies */
1298 static struct tftphdr *ap; /* ack buffer */
1299 static u_short block = 0;
1300 static int acksize;
1301 u_short dp_opcode, dp_block;
1302 unsigned long r_timeout;
1304 dp = w_init();
1305 do {
1306 timeout = rexmtval;
1308 if (!block && oap) {
1309 ap = (struct tftphdr *)ackbuf;
1310 acksize = oacklen;
1311 } else {
1312 ap = (struct tftphdr *)ackbuf;
1313 ap->th_opcode = htons((u_short)ACK);
1314 ap->th_block = htons((u_short)block);
1315 acksize = 4;
1317 block++;
1318 (void) sigsetjmp(timeoutbuf,1);
1319 send_ack:
1320 r_timeout = timeout;
1321 if (send(peer, ackbuf, acksize, 0) != acksize) {
1322 syslog(LOG_WARNING, "tftpd: write(ack): %m");
1323 goto abort;
1325 write_behind(file, pf->f_convert);
1326 for ( ; ; ) {
1327 n = recv_time(peer, dp, PKTSIZE, 0, &r_timeout);
1328 if (n < 0) { /* really? */
1329 syslog(LOG_WARNING, "tftpd: read: %m");
1330 goto abort;
1332 dp_opcode = ntohs((u_short)dp->th_opcode);
1333 dp_block = ntohs((u_short)dp->th_block);
1334 if (dp_opcode == ERROR)
1335 goto abort;
1336 if (dp_opcode == DATA) {
1337 if (dp_block == block) {
1338 break; /* normal */
1340 /* Re-synchronize with the other side */
1341 (void) synchnet(peer);
1342 if (dp_block == (block-1))
1343 goto send_ack; /* rexmit */
1346 /* size = write(file, dp->th_data, n - 4); */
1347 size = writeit(file, &dp, n - 4, pf->f_convert);
1348 if (size != (n-4)) { /* ahem */
1349 if (size < 0) nak(errno + 100, NULL);
1350 else nak(ENOSPACE, NULL);
1351 goto abort;
1353 } while (size == segsize);
1354 write_behind(file, pf->f_convert);
1355 (void) fclose(file); /* close data file */
1357 ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */
1358 ap->th_block = htons((u_short)(block));
1359 (void) send(peer, ackbuf, 4, 0);
1361 timeout_quit = 1; /* just quit on timeout */
1362 n = recv_time(peer, buf, sizeof (buf), 0, &timeout); /* normally times out and quits */
1363 timeout_quit = 0;
1365 if (n >= 4 && /* if read some data */
1366 dp_opcode == DATA && /* and got a data block */
1367 block == dp_block) { /* then my last ack was lost */
1368 (void) send(peer, ackbuf, 4, 0); /* resend final ack */
1370 abort:
1371 return;
1374 static const char * const errmsgs[] =
1376 "Undefined error code", /* 0 - EUNDEF */
1377 "File not found", /* 1 - ENOTFOUND */
1378 "Access denied", /* 2 - EACCESS */
1379 "Disk full or allocation exceeded", /* 3 - ENOSPACE */
1380 "Illegal TFTP operation", /* 4 - EBADOP */
1381 "Unknown transfer ID", /* 5 - EBADID */
1382 "File already exists", /* 6 - EEXISTS */
1383 "No such user", /* 7 - ENOUSER */
1384 "Failure to negotiate RFC2347 options" /* 8 - EOPTNEG */
1386 #define ERR_CNT (sizeof(errmsgs)/sizeof(const char *))
1389 * Send a nak packet (error message).
1390 * Error code passed in is one of the
1391 * standard TFTP codes, or a UNIX errno
1392 * offset by 100.
1394 static void
1395 nak(int error, const char *msg)
1397 struct tftphdr *tp;
1398 int length;
1400 tp = (struct tftphdr *)buf;
1401 tp->th_opcode = htons((u_short)ERROR);
1403 if ( error >= 100 ) {
1404 /* This is a Unix errno+100 */
1405 if ( !msg )
1406 msg = strerror(error - 100);
1407 error = EUNDEF;
1408 } else {
1409 if ( (unsigned)error >= ERR_CNT )
1410 error = EUNDEF;
1412 if ( !msg )
1413 msg = errmsgs[error];
1416 tp->th_code = htons((u_short)error);
1418 length = strlen(msg)+1;
1419 memcpy(tp->th_msg, msg, length);
1420 length += 4; /* Add space for header */
1422 if ( verbosity >= 2 ) {
1423 syslog(LOG_INFO, "sending NAK (%d, %s) to %s",
1424 error, tp->th_msg, inet_ntoa(from.sin_addr));
1427 if (send(peer, buf, length, 0) != length)
1428 syslog(LOG_WARNING, "nak: %m");