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>
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 5 /* Default timeout (seconds) */
83 #define TRIES 4 /* Number of attempts to send each packet */
84 #define TIMEOUT_LIMIT (TRIES*(TRIES+1)/2)
88 int timeout
= TIMEOUT
;
89 int rexmtval
= TIMEOUT
;
90 int maxtimeout
= TIMEOUT_LIMIT
*TIMEOUT
;
92 #define PKTSIZE MAX_SEGSIZE+4
95 struct sockaddr_in from
;
111 static struct rule
*rewrite_rules
= NULL
;
114 int tftp(struct tftphdr
*, int);
118 void do_opt(char *, char *, char **);
120 int set_blksize(char *, char **);
121 int set_blksize2(char *, char **);
122 int set_tsize(char *, char **);
123 int set_timeout(char *, char **);
127 int (*o_fnc
)(char *, char **);
129 { "blksize", set_blksize
},
130 { "blksize2", set_blksize2
},
131 { "tsize", set_tsize
},
132 { "timeout", set_timeout
},
136 /* Simple handler for SIGHUP */
137 static volatile sig_atomic_t caught_sighup
= 0;
138 static void handle_sighup(int sig
)
140 (void)sig
; /* Suppress unused warning */
148 syslog(LOG_ERR
, "Usage: %s [-vcl][-a address][-m mappings][-u user][-t timeout][-r option...] [-s] [directory ...]",
156 read_remap_rules(const char *file
)
161 f
= fopen(file
, "rt");
163 syslog(LOG_ERR
, "Cannot open map file: %s: %m", file
);
166 rulep
= parserulefile(f
);
174 set_socket_nonblock(int fd
, int flag
)
178 #if defined(HAVE_FCNTL) && defined(HAVE_O_NONBLOCK_DEFINITION)
179 /* Posixly correct */
180 err
= ((flags
= fcntl(fd
, F_GETFL
, 0)) < 0) ||
181 (fcntl(fd
, F_SETFL
, flag
? flags
|O_NONBLOCK
: flags
&~O_NONBLOCK
) < 0);
183 flags
= flag
? 1 : 0;
184 err
= (ioctl(fd
, FIONBIO
, &flags
) < 0);
187 syslog(LOG_ERR
, "Cannot set nonblock flag on socket: %m");
193 main(int argc
, char **argv
)
198 struct sockaddr_in myaddr
;
199 struct sockaddr_in bindaddr
;
202 int standalone
= 0; /* Standalone (listen) mode */
203 char *address
= NULL
; /* Address to listen to */
209 int waittime
= 900; /* Default time to wait for a connect*/
210 const char *user
= "nobody"; /* Default user */
213 char *rewrite_file
= NULL
;
216 /* basename() is way too much of a pain from a portability standpoint */
218 p
= strrchr(argv
[0], '/');
219 __progname
= (p
&& p
[1]) ? p
+1 : argv
[0];
221 openlog(__progname
, LOG_PID
|LOG_NDELAY
, LOG_DAEMON
);
223 while ((c
= getopt(argc
, argv
, "cspvVla:u:U:r:t:m:")) != -1)
241 waittime
= atoi(optarg
);
247 my_umask
= strtoul(optarg
, &ep
, 8);
249 syslog(LOG_ERR
, "Invalid umask: %s", optarg
);
255 for ( opt
= options
; opt
->o_opt
; opt
++ ) {
256 if ( !strcasecmp(optarg
, opt
->o_opt
) ) {
257 opt
->o_opt
= ""; /* Don't support this option */
262 syslog(LOG_ERR
, "Unknown option: %s", optarg
);
268 if ( rewrite_file
) {
269 syslog(LOG_ERR
, "Multiple -m options");
272 rewrite_file
= optarg
;
279 /* Print configuration to stdout and exit */
280 printf("%s\n", TFTPD_CONFIG_STR
);
288 dirs
= xmalloc((argc
-optind
+1)*sizeof(char *));
289 for ( ndirs
= 0 ; optind
!= argc
; optind
++ )
290 dirs
[ndirs
++] = argv
[optind
];
296 syslog(LOG_ERR
, "no -s directory");
300 syslog(LOG_ERR
, "too many -s directories");
303 if (chdir(dirs
[0])) {
304 syslog(LOG_ERR
, "%s: %m", dirs
[0]);
311 syslog(LOG_ERR
, "no user %s: %m", user
);
315 if ( spec_umask
|| !unixperms
)
318 /* Note: on Cygwin, select() on a nonblocking socket becomes
319 a nonblocking select. */
321 set_socket_nonblock(fd
, 1);
326 rewrite_rules
= read_remap_rules(rewrite_file
);
329 /* If we're running standalone, set up the input port */
331 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
333 memset(&bindaddr
, 0, sizeof bindaddr
);
334 bindaddr
.sin_family
= AF_INET
;
335 bindaddr
.sin_addr
.s_addr
= INADDR_ANY
;
336 bindaddr
.sin_port
= htons(IPPORT_TFTP
);
339 char *portptr
, *eportptr
;
340 struct hostent
*hostent
;
341 struct servent
*servent
;
344 address
= tfstrdup(address
);
345 portptr
= strrchr(address
, ':');
350 hostent
= gethostbyname(address
);
351 if ( !hostent
|| hostent
->h_addrtype
!= AF_INET
) {
352 syslog(LOG_ERR
, "cannot resolve local bind address: %s", address
);
355 memcpy(&bindaddr
.sin_addr
, hostent
->h_addr
, hostent
->h_length
);
357 /* Default to using INADDR_ANY */
360 if ( portptr
&& *portptr
) {
361 servent
= getservbyname(portptr
, "udp");
363 bindaddr
.sin_port
= servent
->s_port
;
364 } else if ( (port
= strtoul(portptr
, &eportptr
, 0)) && !*eportptr
) {
365 bindaddr
.sin_port
= htons(port
);
366 } else if ( !strcmp(portptr
, "tftp") ) {
367 /* It's TFTP, we're OK */
369 syslog(LOG_ERR
, "cannot resolve local bind port: %s", portptr
);
375 if (bind(fd
, (struct sockaddr
*)&bindaddr
, sizeof bindaddr
) < 0) {
376 syslog(LOG_ERR
, "cannot bind to local socket: %m");
380 /* Daemonize this process */
387 syslog(LOG_ERR
, "cannot fork: %m");
390 nfd
= open("/dev/null", O_RDWR
);
403 close(0); close(1); close(2);
406 #ifndef __CYGWIN__ /* Kills the process on Cygwin? */
412 /* 0 is our socket descriptor */
416 /* This means we don't want to wait() for children */
418 set_signal(SIGCHLD
, SIG_IGN
, SA_NOCLDSTOP
|SA_NOCLDWAIT
);
420 set_signal(SIGCHLD
, SIG_IGN
, SA_NOCLDSTOP
);
423 /* Take SIGHUP and use it to set a variable. This
424 is polled synchronously to make sure we don't
425 lose packets as a result. */
426 set_signal(SIGHUP
, handle_sighup
, 0);
430 struct timeval tv_waittime
;
433 if ( caught_sighup
) {
437 if ( rewrite_file
) {
438 freerules(rewrite_rules
);
439 rewrite_rules
= read_remap_rules(rewrite_file
);
443 /* Return to inetd for respawn */
449 FD_SET(fd
, &readset
);
450 tv_waittime
.tv_sec
= waittime
;
451 tv_waittime
.tv_usec
= 0;
454 /* On Cygwin, select() on a nonblocking socket returns immediately,
456 set_socket_nonblock(fd
, 0);
459 /* Never time out if we're in standalone mode */
460 rv
= select(fd
+1, &readset
, NULL
, NULL
, standalone
? NULL
: &tv_waittime
);
461 if ( rv
== -1 && errno
== EINTR
)
462 continue; /* Signal caught, reloop */
464 syslog(LOG_ERR
, "select loop: %m");
466 } else if ( rv
== 0 ) {
467 exit(0); /* Timeout, return to inetd */
471 set_socket_nonblock(fd
, 1);
474 fromlen
= sizeof (from
);
475 n
= myrecvfrom(fd
, buf
, sizeof (buf
), 0,
476 (struct sockaddr
*)&from
, &fromlen
,
480 if ( E_WOULD_BLOCK(errno
) || errno
== EINTR
) {
481 continue; /* Again, from the top */
483 syslog(LOG_ERR
, "recvfrom: %m");
488 if ( standalone
&& myaddr
.sin_addr
.s_addr
== INADDR_ANY
) {
489 /* myrecvfrom() didn't capture the source address; but we might
490 have bound to a specific address, if so we should use it */
491 memcpy(&myaddr
.sin_addr
, &bindaddr
.sin_addr
, sizeof bindaddr
.sin_addr
);
495 * Now that we have read the request packet from the UDP
496 * socket, we fork and go back to listening to the socket.
500 syslog(LOG_ERR
, "fork: %m");
501 exit(EX_OSERR
); /* Return to inetd, just in case */
502 } else if ( pid
== 0 )
503 break; /* Child exit, parent loop */
506 /* Child process: handle the actual request here */
509 set_signal(SIGHUP
, SIG_IGN
, 0);
511 #ifdef HAVE_TCPWRAPPERS
512 /* Verify if this was a legal request for us. This has to be
513 done before the chroot, while /etc is still accessible. */
514 request_init(&wrap_request
,
515 RQ_DAEMON
, __progname
,
517 RQ_CLIENT_SIN
, &from
,
518 RQ_SERVER_SIN
, &myaddr
,
520 sock_methods(&wrap_request
);
521 if ( hosts_access(&wrap_request
) == 0 ) {
522 if ( deny_severity
!= -1 )
523 syslog(deny_severity
, "connection refused from %s",
524 inet_ntoa(from
.sin_addr
));
525 exit(EX_NOPERM
); /* Access denied */
526 } else if ( allow_severity
!= -1 ) {
527 syslog(allow_severity
, "connect from %s",
528 inet_ntoa(from
.sin_addr
));
532 /* Close file descriptors we don't need */
535 /* Get a socket. This has to be done before the chroot(), since
536 some systems require access to /dev to create a socket. */
538 peer
= socket(AF_INET
, SOCK_DGRAM
, 0);
540 syslog(LOG_ERR
, "socket: %m");
544 /* Set up the supplementary group access list if possible */
545 /* /etc/group still need to be accessible at this point */
546 #ifdef HAVE_INITGROUPS
547 setrv
= initgroups(user
, pw
->pw_gid
);
549 syslog(LOG_ERR
, "cannot set groups for user %s", user
);
553 #ifdef HAVE_SETGROUPS
554 if ( setgroups(0, NULL
) ) {
555 syslog(LOG_ERR
, "cannot clear group list");
560 /* Chroot and drop privileges */
562 if (secure
&& chroot(".")) {
563 syslog(LOG_ERR
, "chroot: %m");
568 chdir("/"); /* Cygwin chroot() bug workaround */
572 setrv
= setregid(pw
->pw_gid
, pw
->pw_gid
);
574 setrv
= setegid(pw
->pw_gid
) || setgid(pw
->pw_gid
);
578 setrv
= setrv
|| setreuid(pw
->pw_uid
, pw
->pw_uid
);
580 /* Important: setuid() must come first */
581 setrv
= setrv
|| setuid(pw
->pw_uid
) ||
582 (geteuid() != pw
->pw_uid
&& seteuid(pw
->pw_uid
));
586 syslog(LOG_ERR
, "cannot drop privileges: %m");
590 /* Other basic setup */
591 from
.sin_family
= AF_INET
;
594 /* Process the request... */
596 myaddr
.sin_port
= htons(0); /* We want a new local port */
597 if (bind(peer
, (struct sockaddr
*)&myaddr
, sizeof myaddr
) < 0) {
598 syslog(LOG_ERR
, "bind: %m");
601 if (connect(peer
, (struct sockaddr
*)&from
, sizeof from
) < 0) {
602 syslog(LOG_ERR
, "connect: %m");
605 tp
= (struct tftphdr
*)buf
;
606 tp
->th_opcode
= ntohs(tp
->th_opcode
);
607 if (tp
->th_opcode
== RRQ
|| tp
->th_opcode
== WRQ
)
612 char *rewrite_access(char *, int);
613 int validate_access(char *, int, struct formats
*);
614 void tftp_sendfile(struct formats
*, struct tftphdr
*, int);
615 void tftp_recvfile(struct formats
*, struct tftphdr
*, int);
619 char *(*f_rewrite
)(char *, int);
620 int (*f_validate
)(char *, int, struct formats
*);
621 void (*f_send
)(struct formats
*, struct tftphdr
*, int);
622 void (*f_recv
)(struct formats
*, struct tftphdr
*, int);
625 { "netascii", rewrite_access
, validate_access
, tftp_sendfile
, tftp_recvfile
, 1 },
626 { "octet", rewrite_access
, validate_access
, tftp_sendfile
, tftp_recvfile
, 0 },
627 { NULL
, NULL
, NULL
, NULL
, NULL
, 0 }
631 * Handle initial connection protocol.
634 tftp(struct tftphdr
*tp
, int size
)
638 struct formats
*pf
= NULL
;
640 char *filename
, *mode
= NULL
;
642 char *val
= NULL
, *opt
= NULL
;
643 char *ap
= ackbuf
+ 2;
645 ((struct tftphdr
*)ackbuf
)->th_opcode
= ntohs(OACK
);
647 origfilename
= cp
= (char *) &(tp
->th_stuff
);
650 while ( cp
< buf
+ size
&& *cp
) {
653 } while (cp
< buf
+ size
&& *cp
);
656 nak(EBADOP
); /* Corrupt packet - no final NULL */
663 } else if (argn
== 2) {
664 for (cp
= mode
; *cp
; cp
++)
666 for (pf
= formats
; pf
->f_mode
; pf
++) {
667 if (!strcmp(pf
->f_mode
, mode
))
674 if ( !(filename
= (*pf
->f_rewrite
)(origfilename
, tp
->th_opcode
)) ) {
675 nak(EACCESS
); /* File denied by mapping rule */
678 if ( verbosity
>= 1 ) {
679 if ( filename
== origfilename
|| !strcmp(filename
, origfilename
) )
680 syslog(LOG_NOTICE
, "%s from %s filename %s\n",
681 tp
->th_opcode
== WRQ
? "WRQ" : "RRQ",
682 inet_ntoa(from
.sin_addr
), filename
);
684 syslog(LOG_NOTICE
, "%s from %s filename %s remapped to %s\n",
685 tp
->th_opcode
== WRQ
? "WRQ" : "RRQ",
686 inet_ntoa(from
.sin_addr
), origfilename
, filename
);
688 ecode
= (*pf
->f_validate
)(filename
, tp
->th_opcode
, pf
);
694 } else if ( argn
& 1 ) {
697 do_opt(opt
, val
, &ap
);
707 if ( ap
!= (ackbuf
+2) ) {
708 if ( tp
->th_opcode
== WRQ
)
709 (*pf
->f_recv
)(pf
, (struct tftphdr
*)ackbuf
, ap
-ackbuf
);
711 (*pf
->f_send
)(pf
, (struct tftphdr
*)ackbuf
, ap
-ackbuf
);
713 if (tp
->th_opcode
== WRQ
)
714 (*pf
->f_recv
)(pf
, NULL
, 0);
716 (*pf
->f_send
)(pf
, NULL
, 0);
718 exit(0); /* Request completed */
721 static int blksize_set
;
724 * Set a non-standard block size (c.f. RFC2348)
727 set_blksize(char *val
, char **ret
)
729 static char b_ret
[6];
733 sz
= (unsigned int)strtoul(val
, &vend
, 10);
735 if ( blksize_set
|| *vend
)
740 else if (sz
> MAX_SEGSIZE
)
744 sprintf(*ret
= b_ret
, "%u", sz
);
752 * Set a power-of-two block size (nonstandard)
755 set_blksize2(char *val
, char **ret
)
757 static char b_ret
[6];
761 sz
= (unsigned int)strtoul(val
, &vend
, 10);
763 if ( blksize_set
|| *vend
)
768 else if (sz
> MAX_SEGSIZE
)
771 /* Convert to a power of two */
773 unsigned int sz1
= 1;
774 /* Not a power of two - need to convert */
781 sprintf(*ret
= b_ret
, "%u", sz
);
789 * Return a file size (c.f. RFC2349)
790 * For netascii mode, we don't know the size ahead of time;
791 * so reject the option.
794 set_tsize(char *val
, char **ret
)
796 static char b_ret
[sizeof(uintmax_t)*CHAR_BIT
/3+2];
800 sz
= strtoumax(val
, &vend
, 10);
802 if ( !tsize_ok
|| *vend
)
806 sz
= (uintmax_t)tsize
;
808 sprintf(*ret
= b_ret
, "%"PRIuMAX
, sz
);
813 * Set the timeout (c.f. RFC2349)
816 set_timeout(char *val
, char **ret
)
818 static char b_ret
[4];
822 to
= strtoul(val
, &vend
, 10);
824 if ( to
< 1 || to
> 255 || *vend
)
829 maxtimeout
= TIMEOUT_LIMIT
*to
;
831 sprintf(*ret
= b_ret
, "%lu", to
);
836 * Parse RFC2347 style options
839 do_opt(char *opt
, char *val
, char **ap
)
844 /* Global option-parsing variables initialization */
850 for (po
= options
; po
->o_opt
; po
++)
851 if (!strcasecmp(po
->o_opt
, opt
)) {
852 if (po
->o_fnc(val
, &ret
)) {
853 if (*ap
+ strlen(opt
) + strlen(ret
) + 2 >=
854 ackbuf
+ sizeof(ackbuf
)) {
855 nak(ENOSPACE
); /* EOPTNEG? */
858 *ap
= strrchr(strcpy(strrchr(strcpy(*ap
, opt
),'\0') + 1,
872 * This is called by the remap engine when it encounters macros such
873 * as \i. It should write the output in "output" if non-NULL, and
874 * return the length of the output (generated or not).
876 * Return -1 on failure.
879 rewrite_macros(char macro
, char *output
);
882 rewrite_macros(char macro
, char *output
)
888 p
= inet_ntoa(from
.sin_addr
);
895 sprintf(output
, "%08X",
896 ntohl(from
.sin_addr
.s_addr
));
905 * Modify the filename, if applicable. If it returns NULL, deny the access.
908 rewrite_access(char *filename
, int mode
)
910 if ( rewrite_rules
) {
911 char *newname
= rewrite_string(filename
, rewrite_rules
,
912 mode
!= RRQ
, rewrite_macros
);
920 rewrite_access(char *filename
, int mode
)
922 (void)mode
; /* Avoid warning */
929 * Validate file access. Since we
930 * have no uid or gid, for now require
931 * file to exist and be publicly
932 * readable/writable, unless -p specified.
933 * If we were invoked with arguments
934 * from inetd then the file must also be
935 * in one of the given directory prefixes.
936 * Note also, full path name must be
937 * given as we have no login directory.
940 validate_access(char *filename
, int mode
, struct formats
*pf
)
944 int fd
, wmode
, rmode
;
952 if (*filename
!= '/')
955 * prevent tricksters from getting around the directory
958 len
= strlen(filename
);
959 for ( i
= 1 ; i
< len
-3 ; i
++ ) {
961 if ( *cp
== '.' && memcmp(cp
-1, "/../", 4) == 0)
965 for (dirp
= dirs
; *dirp
; dirp
++)
966 if (strncmp(filename
, *dirp
, strlen(*dirp
)) == 0)
968 if (*dirp
==0 && dirp
!=dirs
)
973 * We use different a different permissions scheme if `cancreate' is
977 (cancreate
? O_CREAT
: 0) |
978 (unixperms
? O_TRUNC
: 0) |
979 (pf
->f_convert
? O_TEXT
: O_BINARY
);
981 (pf
->f_convert
? O_TEXT
: O_BINARY
);
983 fd
= open(filename
, mode
== RRQ
? rmode
: wmode
, 0666);
998 if ( fstat(fd
, &stbuf
) < 0 )
999 exit(EX_OSERR
); /* This shouldn't happen */
1002 if ( !unixperms
&& (stbuf
.st_mode
& (S_IREAD
>> 6)) == 0 )
1004 tsize
= stbuf
.st_size
;
1005 /* We don't know the tsize if conversion is needed */
1006 tsize_ok
= !pf
->f_convert
;
1009 if ( (stbuf
.st_mode
& (S_IWRITE
>> 6)) == 0 )
1012 /* We didn't get to truncate the file at open() time */
1013 #ifdef HAVE_FTRUNCATE
1014 if ( ftruncate(fd
, (off_t
)0) )
1022 stdio_mode
[0] = (mode
== RRQ
) ? 'r':'w';
1023 stdio_mode
[1] = (pf
->f_convert
) ? 't':'b';
1024 stdio_mode
[2] = '\0';
1026 file
= fdopen(fd
, stdio_mode
);
1028 exit(EX_OSERR
); /* Internal error */
1034 sigjmp_buf timeoutbuf
;
1036 /* Handle timeout signal */
1040 (void)sig
; /* Suppress unused warning */
1041 timeout
+= rexmtval
;
1042 if (timeout
>= maxtimeout
)
1044 siglongjmp(timeoutbuf
, 1);
1048 * Send the requested file.
1051 tftp_sendfile(struct formats
*pf
, struct tftphdr
*oap
, int oacklen
)
1054 struct tftphdr
*ap
; /* ack packet */
1055 static u_short block
= 1; /* Static to avoid longjmp funnies */
1058 ap
= (struct tftphdr
*)ackbuf
;
1062 (void)sigsetjmp(timeoutbuf
,1);
1064 if (send(peer
, oap
, oacklen
, 0) != oacklen
) {
1065 syslog(LOG_ERR
, "tftpd: oack: %m\n");
1069 set_signal(SIGALRM
, timer
, SA_RESTART
);
1071 n
= recv(peer
, ackbuf
, sizeof(ackbuf
), 0);
1074 syslog(LOG_ERR
, "tftpd: read: %m\n");
1077 ap
->th_opcode
= ntohs((u_short
)ap
->th_opcode
);
1078 ap
->th_block
= ntohs((u_short
)ap
->th_block
);
1080 if (ap
->th_opcode
== ERROR
) {
1081 syslog(LOG_ERR
, "tftp: client does not accept "
1085 if (ap
->th_opcode
== ACK
) {
1086 if (ap
->th_block
== 0)
1088 /* Resynchronize with the other side */
1089 (void)synchnet(peer
);
1097 size
= readit(file
, &dp
, pf
->f_convert
);
1102 dp
->th_opcode
= htons((u_short
)DATA
);
1103 dp
->th_block
= htons((u_short
)block
);
1105 (void) sigsetjmp(timeoutbuf
,1);
1107 if (send(peer
, dp
, size
+ 4, 0) != size
+ 4) {
1108 syslog(LOG_ERR
, "tftpd: write: %m");
1111 read_ahead(file
, pf
->f_convert
);
1113 set_signal(SIGALRM
, timer
, SA_RESTART
);
1114 alarm(rexmtval
); /* read the ack */
1115 n
= recv(peer
, ackbuf
, sizeof (ackbuf
), 0);
1118 syslog(LOG_ERR
, "tftpd: read(ack): %m");
1121 ap
->th_opcode
= ntohs((u_short
)ap
->th_opcode
);
1122 ap
->th_block
= ntohs((u_short
)ap
->th_block
);
1124 if (ap
->th_opcode
== ERROR
)
1127 if (ap
->th_opcode
== ACK
) {
1128 if (ap
->th_block
== block
) {
1131 /* Re-synchronize with the other side */
1132 (void) synchnet(peer
);
1134 * RFC1129/RFC1350: We MUST NOT re-send the DATA
1135 * packet in response to an invalid ACK. Doing so
1136 * would cause the Sorcerer's Apprentice bug.
1142 } while (size
== segsize
);
1144 (void) fclose(file
);
1147 /* Bail out signal handler */
1151 (void)sig
; /* Suppress unused warning */
1160 tftp_recvfile(struct formats
*pf
, struct tftphdr
*oap
, int oacklen
)
1164 /* These are "static" to avoid longjmp funnies */
1165 static struct tftphdr
*ap
; /* ack buffer */
1166 static u_short block
= 0;
1173 if (!block
&& oap
) {
1174 ap
= (struct tftphdr
*)ackbuf
;
1177 ap
= (struct tftphdr
*)ackbuf
;
1178 ap
->th_opcode
= htons((u_short
)ACK
);
1179 ap
->th_block
= htons((u_short
)block
);
1183 (void) sigsetjmp(timeoutbuf
,1);
1184 set_signal(SIGALRM
, timer
, SA_RESTART
);
1186 if (send(peer
, ackbuf
, acksize
, 0) != acksize
) {
1187 syslog(LOG_ERR
, "tftpd: write(ack): %m");
1190 write_behind(file
, pf
->f_convert
);
1192 set_signal(SIGALRM
, timer
, SA_RESTART
);
1194 n
= recv(peer
, dp
, PKTSIZE
, 0);
1196 if (n
< 0) { /* really? */
1197 syslog(LOG_ERR
, "tftpd: read: %m");
1200 dp
->th_opcode
= ntohs((u_short
)dp
->th_opcode
);
1201 dp
->th_block
= ntohs((u_short
)dp
->th_block
);
1202 if (dp
->th_opcode
== ERROR
)
1204 if (dp
->th_opcode
== DATA
) {
1205 if (dp
->th_block
== block
) {
1208 /* Re-synchronize with the other side */
1209 (void) synchnet(peer
);
1210 if (dp
->th_block
== (block
-1))
1211 goto send_ack
; /* rexmit */
1214 /* size = write(file, dp->th_data, n - 4); */
1215 size
= writeit(file
, &dp
, n
- 4, pf
->f_convert
);
1216 if (size
!= (n
-4)) { /* ahem */
1217 if (size
< 0) nak(errno
+ 100);
1221 } while (size
== segsize
);
1222 write_behind(file
, pf
->f_convert
);
1223 (void) fclose(file
); /* close data file */
1225 ap
->th_opcode
= htons((u_short
)ACK
); /* send the "final" ack */
1226 ap
->th_block
= htons((u_short
)(block
));
1227 (void) send(peer
, ackbuf
, 4, 0);
1229 set_signal(SIGALRM
, justquit
, 0); /* just quit on timeout */
1231 n
= recv(peer
, buf
, sizeof (buf
), 0); /* normally times out and quits */
1233 if (n
>= 4 && /* if read some data */
1234 dp
->th_opcode
== DATA
&& /* and got a data block */
1235 block
== dp
->th_block
) { /* then my last ack was lost */
1236 (void) send(peer
, ackbuf
, 4, 0); /* resend final ack */
1246 { EUNDEF
, "Undefined error code" },
1247 { ENOTFOUND
, "File not found" },
1248 { EACCESS
, "Access violation" },
1249 { ENOSPACE
, "Disk full or allocation exceeded" },
1250 { EBADOP
, "Illegal TFTP operation" },
1251 { EBADID
, "Unknown transfer ID" },
1252 { EEXISTS
, "File already exists" },
1253 { ENOUSER
, "No such user" },
1254 { EOPTNEG
, "Failure to negotiate RFC2347 options" },
1259 * Send a nak packet (error message).
1260 * Error code passed in is one of the
1261 * standard TFTP codes, or a UNIX errno
1271 tp
= (struct tftphdr
*)buf
;
1272 tp
->th_opcode
= htons((u_short
)ERROR
);
1273 tp
->th_code
= htons((u_short
)error
);
1274 for (pe
= errmsgs
; pe
->e_code
>= 0; pe
++)
1275 if (pe
->e_code
== error
)
1277 if (pe
->e_code
< 0) {
1278 pe
->e_msg
= strerror(error
- 100);
1279 tp
->th_code
= EUNDEF
; /* set 'undef' errorcode */
1281 strcpy(tp
->th_msg
, pe
->e_msg
);
1282 length
= strlen(pe
->e_msg
);
1283 tp
->th_msg
[length
] = '\0';
1286 if ( verbosity
>= 2 ) {
1287 syslog(LOG_INFO
, "sending NAK (%d, %s) to %s",
1288 error
, tp
->th_msg
, inet_ntoa(from
.sin_addr
));
1291 if (send(peer
, buf
, length
, 0) != length
)
1292 syslog(LOG_ERR
, "nak: %m");