3 /* $OpenBSD: tftpd.c,v 1.13 1999/06/23 17:01:36 deraadt Exp $ */
6 * Copyright (c) 1983 Regents of the University of California.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
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
38 #include "config.h" /* Must be included first */
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
=
52 * Trivial file transfer protocol server.
54 * This version includes many modifications by Jim Guyton <guyton@rand-unix>
57 #include <sys/ioctl.h>
65 #include "common/tftpsubs.h"
69 #ifdef HAVE_SYS_FILIO_H
70 #include <sys/filio.h> /* Necessary for FIONBIO on Solaris */
73 #ifdef HAVE_TCPWRAPPERS
76 int deny_severity
= LOG_WARNING
;
77 int allow_severity
= -1; /* Don't log at all */
79 struct request_info wrap_request
;
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
;
88 unsigned long timeout
= TIMEOUT
; /* Current timeout value */
89 unsigned long rexmtval
= TIMEOUT
; /* Basic timeout value */
90 unsigned long maxtimeout
= TIMEOUT_LIMIT
*TIMEOUT
;
92 sigjmp_buf timeoutbuf
;
94 #define PKTSIZE MAX_SEGSIZE+4
97 unsigned int max_blksize
= MAX_SEGSIZE
;
99 struct sockaddr_in from
;
111 unsigned int portrange_from
, portrange_to
;
116 static struct rule
*rewrite_rules
= NULL
;
119 int tftp(struct tftphdr
*, int);
120 static void nak(int, const char *);
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 **);
133 int (*o_fnc
)(char *, char **);
135 { "blksize", set_blksize
},
136 { "blksize2", set_blksize2
},
137 { "tsize", set_tsize
},
138 { "timeout", set_timeout
},
139 { "utimeout", set_utimeout
},
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 */
152 /* Handle timeout signal or timeout event */
156 (void)sig
; /* Suppress unused warning */
158 if (timeout
>= maxtimeout
|| timeout_quit
)
160 siglongjmp(timeoutbuf
, 1);
166 syslog(LOG_ERR
, "Usage: %s [-vcl][-a address][-m mappings][-u user][-t inetd_timeout][-T pkt_timeout][-r option...] [-s] [directory ...]",
174 read_remap_rules(const char *file
)
179 f
= fopen(file
, "rt");
181 syslog(LOG_ERR
, "Cannot open map file: %s: %m", file
);
184 rulep
= parserulefile(f
);
192 set_socket_nonblock(int fd
, int flag
)
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);
201 flags
= flag
? 1 : 0;
202 err
= (ioctl(fd
, FIONBIO
, &flags
) < 0);
205 syslog(LOG_ERR
, "Cannot set nonblock flag on socket: %m");
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
));
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
)
228 struct timeval tmv
, t0
, t1
;
230 unsigned long timeout_us
= *timeout_us_p
;
231 unsigned long timeout_left
, dt
;
233 gettimeofday(&t0
, NULL
);
234 timeout_left
= timeout_us
;
241 tmv
.tv_sec
= timeout_left
/ 1000000;
242 tmv
.tv_usec
= timeout_left
% 1000000;
244 rv
= select(s
+1, &fdset
, NULL
, NULL
, &tmv
);
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
);
254 timer(0); /* Should not return */
258 set_socket_nonblock(s
, 1);
259 rv
= recv(s
, rbuf
, len
, flags
);
261 set_socket_nonblock(s
, 0);
264 if ( E_WOULD_BLOCK(err
) || err
== EINTR
) {
265 continue; /* Once again, with feeling... */
278 main(int argc
, char **argv
)
283 struct sockaddr_in myaddr
;
284 struct sockaddr_in bindaddr
;
287 int standalone
= 0; /* Standalone (listen) mode */
288 char *address
= NULL
; /* Address to listen to */
294 int waittime
= 900; /* Default time to wait for a connect*/
295 const char *user
= "nobody"; /* Default user */
298 char *rewrite_file
= NULL
;
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)
329 waittime
= atoi(optarg
);
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
);
345 unsigned long tov
= strtoul(optarg
, &vp
, 10);
346 if ( tov
< 10000UL || tov
> 255000000UL || *vp
) {
347 syslog(LOG_ERR
, "Bad timeout value: %s", optarg
);
350 rexmtval
= timeout
= tov
;
351 maxtimeout
= rexmtval
*TIMEOUT_LIMIT
;
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
);
368 my_umask
= strtoul(optarg
, &ep
, 8);
370 syslog(LOG_ERR
, "Invalid umask: %s", optarg
);
376 for ( opt
= options
; opt
->o_opt
; opt
++ ) {
377 if ( !strcasecmp(optarg
, opt
->o_opt
) ) {
378 opt
->o_opt
= ""; /* Don't support this option */
383 syslog(LOG_ERR
, "Unknown option: %s", optarg
);
389 if ( rewrite_file
) {
390 syslog(LOG_ERR
, "Multiple -m options");
393 rewrite_file
= optarg
;
400 /* Print configuration to stdout and exit */
401 printf("%s\n", TFTPD_CONFIG_STR
);
409 dirs
= xmalloc((argc
-optind
+1)*sizeof(char *));
410 for ( ndirs
= 0 ; optind
!= argc
; optind
++ )
411 dirs
[ndirs
++] = argv
[optind
];
417 syslog(LOG_ERR
, "no -s directory");
421 syslog(LOG_ERR
, "too many -s directories");
424 if (chdir(dirs
[0])) {
425 syslog(LOG_ERR
, "%s: %m", dirs
[0]);
432 syslog(LOG_ERR
, "no user %s: %m", user
);
436 if ( spec_umask
|| !unixperms
)
439 /* Note: on Cygwin, select() on a nonblocking socket becomes
440 a nonblocking select. */
442 set_socket_nonblock(fd
, 1);
447 rewrite_rules
= read_remap_rules(rewrite_file
);
450 /* If we're running standalone, set up the input port */
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
);
460 char *portptr
, *eportptr
;
461 struct hostent
*hostent
;
462 struct servent
*servent
;
465 address
= tfstrdup(address
);
466 portptr
= strrchr(address
, ':');
471 hostent
= gethostbyname(address
);
472 if ( !hostent
|| hostent
->h_addrtype
!= AF_INET
) {
473 syslog(LOG_ERR
, "cannot resolve local bind address: %s", address
);
476 memcpy(&bindaddr
.sin_addr
, hostent
->h_addr
, hostent
->h_length
);
478 /* Default to using INADDR_ANY */
481 if ( portptr
&& *portptr
) {
482 servent
= getservbyname(portptr
, "udp");
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 */
490 syslog(LOG_ERR
, "cannot resolve local bind port: %s", portptr
);
496 if (bind(fd
, (struct sockaddr
*)&bindaddr
, sizeof bindaddr
) < 0) {
497 syslog(LOG_ERR
, "cannot bind to local socket: %m");
501 /* Daemonize this process */
508 syslog(LOG_ERR
, "cannot fork: %m");
511 nfd
= open("/dev/null", O_RDWR
);
523 } else if ( nfd
< 0 ) {
524 close(0); close(1); close(2);
531 /* 0 is our socket descriptor */
535 /* Disable path MTU discovery */
536 pmtu_discovery_off(0);
538 /* This means we don't want to wait() for children */
540 set_signal(SIGCHLD
, SIG_IGN
, SA_NOCLDSTOP
|SA_NOCLDWAIT
);
542 set_signal(SIGCHLD
, SIG_IGN
, SA_NOCLDSTOP
);
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);
552 struct timeval tv_waittime
;
555 if ( caught_sighup
) {
559 if ( rewrite_file
) {
560 freerules(rewrite_rules
);
561 rewrite_rules
= read_remap_rules(rewrite_file
);
565 /* Return to inetd for respawn */
571 FD_SET(fd
, &readset
);
572 tv_waittime
.tv_sec
= waittime
;
573 tv_waittime
.tv_usec
= 0;
576 /* On Cygwin, select() on a nonblocking socket returns immediately,
578 set_socket_nonblock(fd
, 0);
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 */
586 syslog(LOG_ERR
, "select loop: %m");
588 } else if ( rv
== 0 ) {
589 exit(0); /* Timeout, return to inetd */
593 set_socket_nonblock(fd
, 1);
596 fromlen
= sizeof (from
);
597 n
= myrecvfrom(fd
, buf
, sizeof (buf
), 0,
598 (struct sockaddr
*)&from
, &fromlen
,
602 if ( E_WOULD_BLOCK(errno
) || errno
== EINTR
) {
603 continue; /* Again, from the top */
605 syslog(LOG_ERR
, "recvfrom: %m");
610 if ( from
.sin_family
!= AF_INET
) {
611 syslog(LOG_ERR
, "received address was not AF_INET, please check your inetd config");
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.
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 */
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
,
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
));
659 /* Close file descriptors we don't need */
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);
667 syslog(LOG_ERR
, "socket: %m");
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
);
676 syslog(LOG_ERR
, "cannot set groups for user %s", user
);
680 #ifdef HAVE_SETGROUPS
681 if ( setgroups(0, NULL
) ) {
682 syslog(LOG_ERR
, "cannot clear group list");
687 /* Chroot and drop privileges */
690 syslog(LOG_ERR
, "chroot: %m");
694 chdir("/"); /* Cygwin chroot() bug workaround */
699 setrv
= setregid(pw
->pw_gid
, pw
->pw_gid
);
701 setrv
= setegid(pw
->pw_gid
) || setgid(pw
->pw_gid
);
705 setrv
= setrv
|| setreuid(pw
->pw_uid
, pw
->pw_uid
);
707 /* Important: setuid() must come first */
708 setrv
= setrv
|| setuid(pw
->pw_uid
) ||
709 (geteuid() != pw
->pw_uid
&& seteuid(pw
->pw_uid
));
713 syslog(LOG_ERR
, "cannot drop privileges: %m");
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");
726 if (connect(peer
, (struct sockaddr
*)&from
, sizeof from
) < 0) {
727 syslog(LOG_ERR
, "connect: %m");
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
)
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);
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);
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
)
767 struct formats
*pf
= NULL
;
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
);
781 end
= (char *)tp
+ size
;
783 while ( cp
< end
&& *cp
) {
786 } while (cp
< end
&& *cp
);
789 nak(EBADOP
, "Request not null-terminated");
796 } else if (argn
== 2) {
797 for (cp
= mode
; *cp
; cp
++)
799 for (pf
= formats
; pf
->f_mode
; pf
++) {
800 if (!strcmp(pf
->f_mode
, mode
))
804 nak(EBADOP
, "Unknown mode");
808 (*pf
->f_rewrite
)(origfilename
, tp_opcode
, &errmsgptr
)) ) {
809 nak(EACCESS
, errmsgptr
); /* File denied by mapping rule */
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
);
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
);
824 nak(ecode
, errmsgptr
);
828 } else if ( argn
& 1 ) {
831 do_opt(opt
, val
, &ap
);
837 nak(EBADOP
, "Missing mode");
841 if ( ap
!= (ackbuf
+2) ) {
842 if ( tp_opcode
== WRQ
)
843 (*pf
->f_recv
)(pf
, (struct tftphdr
*)ackbuf
, ap
-ackbuf
);
845 (*pf
->f_send
)(pf
, (struct tftphdr
*)ackbuf
, ap
-ackbuf
);
847 if (tp_opcode
== WRQ
)
848 (*pf
->f_recv
)(pf
, NULL
, 0);
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];
867 sz
= (unsigned int)strtoul(val
, &vend
, 10);
869 if ( blksize_set
|| *vend
)
874 else if (sz
> max_blksize
)
878 sprintf(*ret
= b_ret
, "%u", sz
);
886 * Set a power-of-two block size (nonstandard)
889 set_blksize2(char *val
, char **ret
)
891 static char b_ret
[6];
895 sz
= (unsigned int)strtoul(val
, &vend
, 10);
897 if ( blksize_set
|| *vend
)
902 else if (sz
> max_blksize
)
905 /* Convert to a power of two */
907 unsigned int sz1
= 1;
908 /* Not a power of two - need to convert */
915 sprintf(*ret
= b_ret
, "%u", sz
);
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];
934 sz
= strtoumax(val
, &vend
, 10);
936 if ( !tsize_ok
|| *vend
)
940 sz
= (uintmax_t)tsize
;
942 sprintf(*ret
= b_ret
, "%"PRIuMAX
, sz
);
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];
958 to
= strtoul(val
, &vend
, 10);
960 if ( to
< 1 || to
> 255 || *vend
)
963 rexmtval
= timeout
= to
*1000000UL;
964 maxtimeout
= rexmtval
*TIMEOUT_LIMIT
;
966 sprintf(*ret
= b_ret
, "%lu", to
);
970 /* Similar, but in microseconds. We allow down to 10 ms. */
972 set_utimeout(char *val
, char **ret
)
974 static char b_ret
[4];
978 to
= strtoul(val
, &vend
, 10);
980 if ( to
< 10000UL || to
> 255000000UL || *vend
)
983 rexmtval
= timeout
= to
;
984 maxtimeout
= rexmtval
*TIMEOUT_LIMIT
;
986 sprintf(*ret
= b_ret
, "%lu", to
);
990 * Parse RFC2347 style options
993 do_opt(char *opt
, char *val
, char **ap
)
998 /* Global option-parsing variables initialization */
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");
1012 *ap
= strrchr(strcpy(strrchr(strcpy(*ap
, opt
),'\0') + 1,
1015 nak(EOPTNEG
, "Unsupported option(s) requested");
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
)
1042 p
= inet_ntoa(from
.sin_addr
);
1049 sprintf(output
, "%08lX", (unsigned long)ntohl(from
.sin_addr
.s_addr
));
1058 * Modify the filename, if applicable. If it returns NULL, deny the access.
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
);
1073 rewrite_access(char *filename
, int mode
, const char **msg
)
1075 (void)mode
; /* Avoid warning */
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
)
1099 int fd
, wmode
, rmode
;
1108 if (*filename
!= '/') {
1109 *errmsg
= "Only absolute filenames allowed";
1114 * prevent tricksters from getting around the directory
1117 len
= strlen(filename
);
1118 for ( i
= 1 ; i
< len
-3 ; i
++ ) {
1120 if ( *cp
== '.' && memcmp(cp
-1, "/../", 4) == 0 ) {
1121 *errmsg
= "Reverse path not allowed";
1126 for (dirp
= dirs
; *dirp
; dirp
++)
1127 if (strncmp(filename
, *dirp
, strlen(*dirp
)) == 0)
1129 if (*dirp
==0 && dirp
!=dirs
) {
1130 *errmsg
= "Forbidden directory";
1136 * We use different a different permissions scheme if `cancreate' is
1140 (cancreate
? O_CREAT
: 0) |
1141 (unixperms
? O_TRUNC
: 0) |
1142 (pf
->f_convert
? O_TEXT
: O_BINARY
);
1144 (pf
->f_convert
? O_TEXT
: O_BINARY
);
1146 fd
= open(filename
, mode
== RRQ
? rmode
: wmode
, 0666);
1161 if ( fstat(fd
, &stbuf
) < 0 )
1162 exit(EX_OSERR
); /* This shouldn't happen */
1165 if ( !unixperms
&& (stbuf
.st_mode
& (S_IREAD
>> 6)) == 0 ) {
1166 *errmsg
= "File must have global read permissions";
1169 tsize
= stbuf
.st_size
;
1170 /* We don't know the tsize if conversion is needed */
1171 tsize_ok
= !pf
->f_convert
;
1174 if ( (stbuf
.st_mode
& (S_IWRITE
>> 6)) == 0 ) {
1175 *errmsg
= "File must have global write permissions";
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";
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
);
1197 exit(EX_OSERR
); /* Internal error */
1203 * Send the requested file.
1206 tftp_sendfile(struct formats
*pf
, struct tftphdr
*oap
, int oacklen
)
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
;
1217 (void)sigsetjmp(timeoutbuf
,1);
1219 r_timeout
= timeout
;
1220 if (send(peer
, oap
, oacklen
, 0) != oacklen
) {
1221 syslog(LOG_WARNING
, "tftpd: oack: %m\n");
1225 n
= recv_time(peer
, ackbuf
, sizeof(ackbuf
), 0, &r_timeout
);
1227 syslog(LOG_WARNING
, "tftpd: read: %m\n");
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");
1238 if (ap_opcode
== ACK
) {
1241 /* Resynchronize with the other side */
1242 (void)synchnet(peer
);
1250 size
= readit(file
, &dp
, pf
->f_convert
);
1252 nak(errno
+ 100, NULL
);
1255 dp
->th_opcode
= htons((u_short
)DATA
);
1256 dp
->th_block
= htons((u_short
)block
);
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");
1265 read_ahead(file
, pf
->f_convert
);
1267 n
= recv_time(peer
, ackbuf
, sizeof (ackbuf
), 0, &r_timeout
);
1269 syslog(LOG_WARNING
, "tftpd: read(ack): %m");
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
)
1279 if (ap_opcode
== ACK
) {
1280 if (ap_block
== block
) {
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.
1294 } while (size
== segsize
);
1296 (void) fclose(file
);
1299 /* Bail out signal handler */
1303 (void)sig
; /* Suppress unused warning */
1312 tftp_recvfile(struct formats
*pf
, struct tftphdr
*oap
, int oacklen
)
1316 /* These are "static" to avoid longjmp funnies */
1317 static struct tftphdr
*ap
; /* ack buffer */
1318 static u_short block
= 0;
1320 u_short dp_opcode
, dp_block
;
1321 unsigned long r_timeout
;
1327 if (!block
&& oap
) {
1328 ap
= (struct tftphdr
*)ackbuf
;
1331 ap
= (struct tftphdr
*)ackbuf
;
1332 ap
->th_opcode
= htons((u_short
)ACK
);
1333 ap
->th_block
= htons((u_short
)block
);
1337 (void) sigsetjmp(timeoutbuf
,1);
1339 r_timeout
= timeout
;
1340 if (send(peer
, ackbuf
, acksize
, 0) != acksize
) {
1341 syslog(LOG_WARNING
, "tftpd: write(ack): %m");
1344 write_behind(file
, pf
->f_convert
);
1346 n
= recv_time(peer
, dp
, PKTSIZE
, 0, &r_timeout
);
1347 if (n
< 0) { /* really? */
1348 syslog(LOG_WARNING
, "tftpd: read: %m");
1351 dp_opcode
= ntohs((u_short
)dp
->th_opcode
);
1352 dp_block
= ntohs((u_short
)dp
->th_block
);
1353 if (dp_opcode
== ERROR
)
1355 if (dp_opcode
== DATA
) {
1356 if (dp_block
== block
) {
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
);
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 */
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 */
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
1414 nak(int error
, const char *msg
)
1419 tp
= (struct tftphdr
*)buf
;
1420 tp
->th_opcode
= htons((u_short
)ERROR
);
1422 if ( error
>= 100 ) {
1423 /* This is a Unix errno+100 */
1425 msg
= strerror(error
- 100);
1428 if ( (unsigned)error
>= ERR_CNT
)
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");