1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
9 * Trivial file transfer protocol server.
11 * This code includes many modifications by Jim Guyton <guyton@rand-unix>
13 * This source file was started based on netkit-tftpd 0.17
14 * Heavily modified for curl's test suite
18 * Copyright (c) 1983 Regents of the University of California.
19 * All rights reserved.
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
29 * 3. All advertising materials mentioning features or use of this software
30 * must display the following acknowledgement:
31 * This product includes software developed by the University of
32 * California, Berkeley and its contributors.
33 * 4. Neither the name of the University nor the names of its contributors
34 * may be used to endorse or promote products derived from this software
35 * without specific prior written permission.
37 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
38 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
39 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
40 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
41 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
42 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
43 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
45 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
46 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50 #include "server_setup.h"
52 #ifdef HAVE_SYS_IOCTL_H
53 #include <sys/ioctl.h>
61 #ifdef HAVE_NETINET_IN_H
62 #include <netinet/in.h>
64 #ifdef HAVE_ARPA_INET_H
65 #include <arpa/inet.h>
67 #ifdef HAVE_ARPA_TFTP_H
68 #include <arpa/tftp.h>
75 #ifdef HAVE_SYS_FILIO_H
76 /* FIONREAD on Solaris 7 */
77 #include <sys/filio.h>
86 #define ENABLE_CURLX_PRINTF
87 /* make the curlx header define all printf() functions to use the curlx_*
89 #include "curlx.h" /* from the private lib dir */
92 #include "server_sockaddr.h"
94 /* include memdebug.h last */
97 /*****************************************************************************
98 * STRUCT DECLARATIONS AND DEFINES *
99 *****************************************************************************/
102 #define PKTSIZE (SEGSIZE + 4) /* SEGSIZE defined in arpa/tftp.h */
106 char *buffer; /* holds the file data to send to the client */
107 size_t bufsize; /* size of the data in buffer */
108 char *rptr; /* read pointer into the buffer */
109 size_t rcount; /* amount of data left to read of the file */
110 long num; /* test case number */
111 int ofile; /* file descriptor for output file when uploading to us */
126 char storage[PKTSIZE];
130 * bf.counter values in range [-1 .. SEGSIZE] represents size of data in the
131 * bf.buf buffer. Additionally it can also hold flags BF_ALLOC or BF_FREE.
135 int counter; /* size of data in buffer, or flag */
136 tftphdr_storage_t buf; /* room for data packet */
139 #define BF_ALLOC -3 /* alloc'd but not yet filled */
140 #define BF_FREE -2 /* free */
144 #define opcode_DATA 3
146 #define opcode_ERROR 5
151 #define MIN(x,y) ((x)<(y)?(x):(y))
153 #ifndef DEFAULT_LOGFILE
154 #define DEFAULT_LOGFILE "log/tftpd.log"
157 #define REQUEST_DUMP "log/server.input"
159 #define DEFAULT_PORT 8999 /* UDP */
161 /*****************************************************************************
163 *****************************************************************************/
165 static struct errmsg errmsgs[] = {
166 { EUNDEF, "Undefined error code" },
167 { ENOTFOUND, "File not found" },
168 { EACCESS, "Access violation" },
169 { ENOSPACE, "Disk full or allocation exceeded" },
170 { EBADOP, "Illegal TFTP operation" },
171 { EBADID, "Unknown transfer ID" },
172 { EEXISTS, "File already exists" },
173 { ENOUSER, "No such user" },
177 static struct formats formata[] = {
183 static struct bf bfs[2];
185 static int nextone; /* index of next buffer to use */
186 static int current; /* index of buffer in use */
188 /* control flags for crlf conversions */
189 static int newline = 0; /* fillbuf: in middle of newline expansion */
190 static int prevchar = -1; /* putbuf: previous char (cr check) */
192 static tftphdr_storage_t buf;
193 static tftphdr_storage_t ackbuf;
195 static srvr_sockaddr_union_t from;
196 static curl_socklen_t fromlen;
198 static curl_socket_t peer = CURL_SOCKET_BAD;
201 static int maxtimeout = 5 * TIMEOUT;
203 static unsigned short sendblock; /* block count used by sendtftp() */
204 static struct tftphdr *sdp; /* data buffer used by sendtftp() */
205 static struct tftphdr *sap; /* ack buffer used by sendtftp() */
207 static unsigned short recvblock; /* block count used by recvtftp() */
208 static struct tftphdr *rdp; /* data buffer used by recvtftp() */
209 static struct tftphdr *rap; /* ack buffer used by recvtftp() */
212 static bool use_ipv6 = FALSE;
214 static const char *ipv_inuse = "IPv4";
216 const char *serverlogfile = DEFAULT_LOGFILE;
217 static char *pidname= (char *)".tftpd.pid";
218 static int serverlogslocked = 0;
219 static int wrotepidfile = 0;
221 #ifdef HAVE_SIGSETJMP
222 static sigjmp_buf timeoutbuf;
225 #if defined(HAVE_ALARM) && defined(SIGALRM)
226 static int rexmtval = TIMEOUT;
229 /* do-nothing macro replacement for systems which lack siginterrupt() */
231 #ifndef HAVE_SIGINTERRUPT
232 #define siginterrupt(x,y) do {} while(0)
235 /* vars used to keep around previous signal handlers */
237 typedef RETSIGTYPE (*SIGHANDLER_T)(int);
240 static SIGHANDLER_T old_sighup_handler = SIG_ERR;
244 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
248 static SIGHANDLER_T old_sigint_handler = SIG_ERR;
252 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
255 /* var which if set indicates that the program should finish execution */
257 SIG_ATOMIC_T got_exit_signal = 0;
259 /* if next is set indicates the first signal handled in exit_signal_handler */
261 static volatile int exit_signal = 0;
263 /*****************************************************************************
264 * FUNCTION PROTOTYPES *
265 *****************************************************************************/
267 static struct tftphdr *rw_init(int);
269 static struct tftphdr *w_init(void);
271 static struct tftphdr *r_init(void);
273 static int readit(struct testcase *test,
274 struct tftphdr **dpp,
277 static int writeit(struct testcase *test,
278 struct tftphdr **dpp,
282 static void read_ahead(struct testcase *test, int convert);
284 static ssize_t write_behind(struct testcase *test, int convert);
286 static int synchnet(curl_socket_t);
288 static int do_tftp(struct testcase *test, struct tftphdr *tp, ssize_t size);
290 static int validate_access(struct testcase *test, const char *fname, int mode);
292 static void sendtftp(struct testcase *test, struct formats *pf);
294 static void recvtftp(struct testcase *test, struct formats *pf);
296 static void nak(int error);
298 #if defined(HAVE_ALARM) && defined(SIGALRM)
300 static void mysignal(int sig, void (*handler)(int));
302 static void timer(int signum);
304 static void justtimeout(int signum);
306 #endif /* HAVE_ALARM && SIGALRM */
308 static RETSIGTYPE exit_signal_handler(int signum);
310 static void install_signal_handlers(void);
312 static void restore_signal_handlers(void);
314 /*****************************************************************************
315 * FUNCTION IMPLEMENTATIONS *
316 *****************************************************************************/
318 #if defined(HAVE_ALARM) && defined(SIGALRM)
321 * Like signal(), but with well-defined semantics.
323 static void mysignal(int sig, void (*handler)(int))
326 memset(&sa, 0, sizeof(sa));
327 sa.sa_handler = handler;
328 sigaction(sig, &sa, NULL);
331 static void timer(int signum)
338 if(timeout >= maxtimeout) {
343 if(serverlogslocked) {
344 serverlogslocked = 0;
345 clear_advisor_read_lock(SERVERLOGS_LOCK);
349 #ifdef HAVE_SIGSETJMP
350 siglongjmp(timeoutbuf, 1);
354 static void justtimeout(int signum)
359 #endif /* HAVE_ALARM && SIGALRM */
361 /* signal handler that will be triggered to indicate that the program
362 should finish its execution in a controlled manner as soon as possible.
363 The first time this is called it will set got_exit_signal to one and
364 store in exit_signal the signal that triggered its execution. */
366 static RETSIGTYPE exit_signal_handler(int signum)
368 int old_errno = ERRNO;
369 if(got_exit_signal == 0) {
371 exit_signal = signum;
373 (void)signal(signum, exit_signal_handler);
374 SET_ERRNO(old_errno);
377 static void install_signal_handlers(void)
380 /* ignore SIGHUP signal */
381 if((old_sighup_handler = signal(SIGHUP, SIG_IGN)) == SIG_ERR)
382 logmsg("cannot install SIGHUP handler: %s", strerror(ERRNO));
385 /* ignore SIGPIPE signal */
386 if((old_sigpipe_handler = signal(SIGPIPE, SIG_IGN)) == SIG_ERR)
387 logmsg("cannot install SIGPIPE handler: %s", strerror(ERRNO));
390 /* handle SIGINT signal with our exit_signal_handler */
391 if((old_sigint_handler = signal(SIGINT, exit_signal_handler)) == SIG_ERR)
392 logmsg("cannot install SIGINT handler: %s", strerror(ERRNO));
394 siginterrupt(SIGINT, 1);
397 /* handle SIGTERM signal with our exit_signal_handler */
398 if((old_sigterm_handler = signal(SIGTERM, exit_signal_handler)) == SIG_ERR)
399 logmsg("cannot install SIGTERM handler: %s", strerror(ERRNO));
401 siginterrupt(SIGTERM, 1);
405 static void restore_signal_handlers(void)
408 if(SIG_ERR != old_sighup_handler)
409 (void)signal(SIGHUP, old_sighup_handler);
412 if(SIG_ERR != old_sigpipe_handler)
413 (void)signal(SIGPIPE, old_sigpipe_handler);
416 if(SIG_ERR != old_sigint_handler)
417 (void)signal(SIGINT, old_sigint_handler);
420 if(SIG_ERR != old_sigterm_handler)
421 (void)signal(SIGTERM, old_sigterm_handler);
426 * init for either read-ahead or write-behind.
427 * zero for write-behind, one for read-head.
429 static struct tftphdr *rw_init(int x)
431 newline = 0; /* init crlf flag */
433 bfs[0].counter = BF_ALLOC; /* pass out the first buffer */
435 bfs[1].counter = BF_FREE;
436 nextone = x; /* ahead or behind? */
437 return &bfs[0].buf.hdr;
440 static struct tftphdr *w_init(void)
442 return rw_init(0); /* write-behind */
445 static struct tftphdr *r_init(void)
447 return rw_init(1); /* read-ahead */
450 /* Have emptied current buffer by sending to net and getting ack.
451 Free it and return next buffer filled with data.
453 static int readit(struct testcase *test, struct tftphdr **dpp,
454 int convert /* if true, convert to ascii */)
458 bfs[current].counter = BF_FREE; /* free old one */
459 current = !current; /* "incr" current */
461 b = &bfs[current]; /* look at new buffer */
462 if (b->counter == BF_FREE) /* if it's empty */
463 read_ahead(test, convert); /* fill it */
465 *dpp = &b->buf.hdr; /* set caller's ptr */
470 * fill the input buffer, doing ascii conversions if requested
471 * conversions are lf -> cr,lf and cr -> cr, nul
473 static void read_ahead(struct testcase *test,
474 int convert /* if true, convert to ascii */)
482 b = &bfs[nextone]; /* look at "next" buffer */
483 if (b->counter != BF_FREE) /* nop if not free */
485 nextone = !nextone; /* "incr" next buffer ptr */
490 /* The former file reading code did this:
491 b->counter = read(fileno(file), dp->th_data, SEGSIZE); */
492 size_t copy_n = MIN(SEGSIZE, test->rcount);
493 memcpy(dp->th_data, test->rptr, copy_n);
495 /* decrease amount, advance pointer */
496 test->rcount -= copy_n;
497 test->rptr += copy_n;
498 b->counter = (int)copy_n;
503 for (i = 0 ; i < SEGSIZE; i++) {
505 if (prevchar == '\n')
506 c = '\n'; /* lf to cr,lf */
508 c = '\0'; /* cr to cr,nul */
519 if (c == '\n' || c == '\r') {
527 b->counter = (int)(p - dp->th_data);
530 /* Update count associated with the buffer, get new buffer from the queue.
531 Calls write_behind only if next buffer not available.
533 static int writeit(struct testcase *test, struct tftphdr **dpp,
536 bfs[current].counter = ct; /* set size of data to write */
537 current = !current; /* switch to other buffer */
538 if (bfs[current].counter != BF_FREE) /* if not free */
539 write_behind(test, convert); /* flush it */
540 bfs[current].counter = BF_ALLOC; /* mark as alloc'd */
541 *dpp = &bfs[current].buf.hdr;
542 return ct; /* this is a lie of course */
546 * Output a buffer to a file, converting from netascii if requested.
547 * CR,NUL -> CR and CR,LF => LF.
548 * Note spec is undefined if we get CR as last byte of file or a
549 * CR followed by anything else. In this case we leave it alone.
551 static ssize_t write_behind(struct testcase *test, int convert)
557 int c; /* current character */
562 if (b->counter < -1) /* anything to flush? */
563 return 0; /* just nop if nothing to do */
567 snprintf(outfile, sizeof(outfile), "log/upload.%ld", test->num);
568 test->ofile=open(outfile, O_CREAT|O_RDWR, 0777);
569 if(test->ofile == -1) {
570 logmsg("Couldn't create and/or open file %s for upload!", outfile);
571 return -1; /* failure! */
575 count = b->counter; /* remember byte count */
576 b->counter = BF_FREE; /* reset flag */
578 nextone = !nextone; /* incr for next time */
579 writebuf = dp->th_data;
582 return -1; /* nak logic? */
585 return write(test->ofile, writebuf, count);
589 while (ct--) { /* loop over the buffer */
590 c = *p++; /* pick up a character */
591 if (prevchar == '\r') { /* if prev char was cr */
592 if (c == '\n') /* if have cr,lf then just */
593 lseek(test->ofile, -1, SEEK_CUR); /* smash lf on top of the cr */
595 if (c == '\0') /* if have cr,nul then */
596 goto skipit; /* just skip over the putc */
597 /* else just fall through and allow it */
601 if(1 != write(test->ofile, &c, 1))
609 /* When an error has occurred, it is possible that the two sides are out of
610 * synch. Ie: that what I think is the other side's response to packet N is
611 * really their response to packet N-1.
613 * So, to try to prevent that, we flush all the input queued up for us on the
614 * network connection on our host.
616 * We return the number of packets we flushed (mostly for reporting when trace
620 static int synchnet(curl_socket_t f /* socket to flush */)
623 #if defined(HAVE_IOCTLSOCKET)
630 srvr_sockaddr_union_t fromaddr;
631 curl_socklen_t fromaddrlen;
634 #if defined(HAVE_IOCTLSOCKET)
635 (void) ioctlsocket(f, FIONREAD, &i);
637 (void) ioctl(f, FIONREAD, &i);
644 fromaddrlen = sizeof(fromaddr.sa4);
647 fromaddrlen = sizeof(fromaddr.sa6);
649 (void) recvfrom(f, rbuf, sizeof(rbuf), 0,
650 &fromaddr.sa, &fromaddrlen);
658 int main(int argc, char **argv)
660 srvr_sockaddr_union_t me;
664 unsigned short port = DEFAULT_PORT;
665 curl_socket_t sock = CURL_SOCKET_BAD;
670 struct testcase test;
673 memset(&test, 0, sizeof(test));
676 if(!strcmp("--version", argv[arg])) {
677 printf("tftpd IPv4%s\n",
686 else if(!strcmp("--pidfile", argv[arg])) {
689 pidname = argv[arg++];
691 else if(!strcmp("--logfile", argv[arg])) {
694 serverlogfile = argv[arg++];
696 else if(!strcmp("--ipv4", argv[arg])) {
703 else if(!strcmp("--ipv6", argv[arg])) {
710 else if(!strcmp("--port", argv[arg])) {
714 unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
715 if((endptr != argv[arg] + strlen(argv[arg])) ||
716 (ulnum < 1025UL) || (ulnum > 65535UL)) {
717 fprintf(stderr, "tftpd: invalid --port argument (%s)\n",
721 port = curlx_ultous(ulnum);
725 else if(!strcmp("--srcdir", argv[arg])) {
733 puts("Usage: tftpd [option]\n"
735 " --logfile [file]\n"
736 " --pidfile [file]\n"
747 atexit(win32_cleanup);
750 install_signal_handlers();
752 pid = (long)getpid();
757 sock = socket(AF_INET, SOCK_DGRAM, 0);
760 sock = socket(AF_INET6, SOCK_DGRAM, 0);
763 if(CURL_SOCKET_BAD == sock) {
765 logmsg("Error creating socket: (%d) %s",
766 error, strerror(error));
772 if (0 != setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
773 (void *)&flag, sizeof(flag))) {
775 logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
776 error, strerror(error));
784 memset(&me.sa4, 0, sizeof(me.sa4));
785 me.sa4.sin_family = AF_INET;
786 me.sa4.sin_addr.s_addr = INADDR_ANY;
787 me.sa4.sin_port = htons(port);
788 rc = bind(sock, &me.sa, sizeof(me.sa4));
792 memset(&me.sa6, 0, sizeof(me.sa6));
793 me.sa6.sin6_family = AF_INET6;
794 me.sa6.sin6_addr = in6addr_any;
795 me.sa6.sin6_port = htons(port);
796 rc = bind(sock, &me.sa, sizeof(me.sa6));
798 #endif /* ENABLE_IPV6 */
801 logmsg("Error binding socket on port %hu: (%d) %s",
802 port, error, strerror(error));
807 wrotepidfile = write_pidfile(pidname);
813 logmsg("Running %s version on port UDP/%d", ipv_inuse, (int)port);
816 fromlen = sizeof(from);
820 fromlen = sizeof(from.sa4);
823 fromlen = sizeof(from.sa6);
825 n = (ssize_t)recvfrom(sock, &buf.storage[0], sizeof(buf.storage), 0,
835 set_advisor_read_lock(SERVERLOGS_LOCK);
836 serverlogslocked = 1;
841 from.sa4.sin_family = AF_INET;
842 peer = socket(AF_INET, SOCK_DGRAM, 0);
843 if(CURL_SOCKET_BAD == peer) {
848 if(connect(peer, &from.sa, sizeof(from.sa4)) < 0) {
849 logmsg("connect: fail");
856 from.sa6.sin6_family = AF_INET6;
857 peer = socket(AF_INET6, SOCK_DGRAM, 0);
858 if(CURL_SOCKET_BAD == peer) {
863 if (connect(peer, &from.sa, sizeof(from.sa6)) < 0) {
864 logmsg("connect: fail");
871 maxtimeout = 5*TIMEOUT;
874 tp->th_opcode = ntohs(tp->th_opcode);
875 if (tp->th_opcode == opcode_RRQ || tp->th_opcode == opcode_WRQ) {
876 memset(&test, 0, sizeof(test));
877 if (do_tftp(&test, tp, n) < 0)
883 peer = CURL_SOCKET_BAD;
893 if(serverlogslocked) {
894 serverlogslocked = 0;
895 clear_advisor_read_lock(SERVERLOGS_LOCK);
898 logmsg("end of one transfer");
907 if((peer != sock) && (peer != CURL_SOCKET_BAD))
910 if(sock != CURL_SOCKET_BAD)
914 logmsg("signalled to die");
919 if(serverlogslocked) {
920 serverlogslocked = 0;
921 clear_advisor_read_lock(SERVERLOGS_LOCK);
924 restore_signal_handlers();
926 if(got_exit_signal) {
927 logmsg("========> %s tftpd (port: %d pid: %ld) exits with signal (%d)",
928 ipv_inuse, (int)port, pid, exit_signal);
930 * To properly set the return status of the process we
931 * must raise the same signal SIGINT or SIGTERM that we
932 * caught and let the old handler take care of it.
937 logmsg("========> tftpd quits");
942 * Handle initial connection protocol.
944 static int do_tftp(struct testcase *test, struct tftphdr *tp, ssize_t size)
947 int first = 1, ecode;
949 char *filename, *mode = NULL;
953 /* Open request dump file. */
954 server = fopen(REQUEST_DUMP, "ab");
957 logmsg("fopen() failed with error: %d %s", error, strerror(error));
958 logmsg("Error opening file: %s", REQUEST_DUMP);
962 /* store input protocol */
963 fprintf(server, "opcode: %x\n", tp->th_opcode);
965 cp = (char *)&tp->th_stuff;
968 while (cp < &buf.storage[size]) {
983 /* store input protocol */
984 fprintf(server, "filename: %s\n", filename);
986 for (cp = mode; cp && *cp; cp++)
988 *cp = (char)tolower((int)*cp);
990 /* store input protocol */
991 fprintf(server, "mode: %s\n", mode);
994 for (pf = formata; pf->f_mode; pf++)
995 if (strcmp(pf->f_mode, mode) == 0)
1001 ecode = validate_access(test, filename, tp->th_opcode);
1006 if (tp->th_opcode == opcode_WRQ)
1015 * Validate file access.
1017 static int validate_access(struct testcase *test,
1018 const char *filename, int mode)
1021 long testno, partno;
1023 char partbuf[80]="data";
1025 logmsg("trying to get file: %s mode %x", filename, mode);
1027 if(!strncmp("verifiedserver", filename, 14)) {
1029 size_t count = sprintf(weare, "WE ROOLZ: %ld\r\n", (long)getpid());
1031 logmsg("Are-we-friendly question received");
1032 test->buffer = strdup(weare);
1033 test->rptr = test->buffer; /* set read pointer */
1034 test->bufsize = count; /* set total count */
1035 test->rcount = count; /* set data left to read */
1036 return 0; /* fine */
1039 /* find the last slash */
1040 ptr = strrchr(filename, '/');
1045 ptr++; /* skip the slash */
1047 /* skip all non-numericals following the slash */
1048 while(*ptr && !ISDIGIT(*ptr))
1051 /* get the number */
1052 testno = strtol(ptr, &ptr, 10);
1054 if(testno > 10000) {
1055 partno = testno % 10000;
1062 logmsg("requested test number %ld part %ld", testno, partno);
1066 file = test2file(testno);
1069 sprintf(partbuf, "data%ld", partno);
1072 FILE *stream=fopen(file, "rb");
1075 logmsg("fopen() failed with error: %d %s", error, strerror(error));
1076 logmsg("Error opening file: %s", file);
1077 logmsg("Couldn't open test file: %s", file);
1082 error = getpart(&test->buffer, &count, "reply", partbuf, stream);
1085 logmsg("getpart() failed with error: %d", error);
1089 test->rptr = test->buffer; /* set read pointer */
1090 test->bufsize = count; /* set total count */
1091 test->rcount = count; /* set data left to read */
1102 logmsg("no slash found in path");
1103 return EACCESS; /* failure */
1106 logmsg("file opened and all is good");
1111 * Send the requested file.
1113 static void sendtftp(struct testcase *test, struct formats *pf)
1118 #if defined(HAVE_ALARM) && defined(SIGALRM)
1119 mysignal(SIGALRM, timer);
1124 size = readit(test, &sdp, pf->f_convert);
1129 sdp->th_opcode = htons((unsigned short)opcode_DATA);
1130 sdp->th_block = htons(sendblock);
1132 #ifdef HAVE_SIGSETJMP
1133 (void) sigsetjmp(timeoutbuf, 1);
1136 if (swrite(peer, sdp, size + 4) != size + 4) {
1140 read_ahead(test, pf->f_convert);
1143 alarm(rexmtval); /* read the ack */
1145 n = sread(peer, &ackbuf.storage[0], sizeof(ackbuf.storage));
1152 logmsg("read: fail");
1155 sap->th_opcode = ntohs((unsigned short)sap->th_opcode);
1156 sap->th_block = ntohs(sap->th_block);
1158 if (sap->th_opcode == opcode_ERROR) {
1159 logmsg("got ERROR");
1163 if (sap->th_opcode == opcode_ACK) {
1164 if (sap->th_block == sendblock) {
1167 /* Re-synchronize with the other side */
1168 (void) synchnet(peer);
1169 if (sap->th_block == (sendblock-1)) {
1176 } while (size == SEGSIZE);
1182 static void recvtftp(struct testcase *test, struct formats *pf)
1186 #if defined(HAVE_ALARM) && defined(SIGALRM)
1187 mysignal(SIGALRM, timer);
1193 rap->th_opcode = htons((unsigned short)opcode_ACK);
1194 rap->th_block = htons(recvblock);
1196 #ifdef HAVE_SIGSETJMP
1197 (void) sigsetjmp(timeoutbuf, 1);
1200 if (swrite(peer, &ackbuf.storage[0], 4) != 4) {
1201 logmsg("write: fail\n");
1204 write_behind(test, pf->f_convert);
1209 n = sread(peer, rdp, PKTSIZE);
1215 if (n < 0) { /* really? */
1216 logmsg("read: fail\n");
1219 rdp->th_opcode = ntohs((unsigned short)rdp->th_opcode);
1220 rdp->th_block = ntohs(rdp->th_block);
1221 if (rdp->th_opcode == opcode_ERROR)
1223 if (rdp->th_opcode == opcode_DATA) {
1224 if (rdp->th_block == recvblock) {
1227 /* Re-synchronize with the other side */
1228 (void) synchnet(peer);
1229 if (rdp->th_block == (recvblock-1))
1230 goto send_ack; /* rexmit */
1234 size = writeit(test, &rdp, (int)(n - 4), pf->f_convert);
1235 if (size != (n-4)) { /* ahem */
1242 } while (size == SEGSIZE);
1243 write_behind(test, pf->f_convert);
1245 rap->th_opcode = htons((unsigned short)opcode_ACK); /* send the "final" ack */
1246 rap->th_block = htons(recvblock);
1247 (void) swrite(peer, &ackbuf.storage[0], 4);
1248 #if defined(HAVE_ALARM) && defined(SIGALRM)
1249 mysignal(SIGALRM, justtimeout); /* just abort read on timeout */
1252 /* normally times out and quits */
1253 n = sread(peer, &buf.storage[0], sizeof(buf.storage));
1259 if (n >= 4 && /* if read some data */
1260 rdp->th_opcode == opcode_DATA && /* and got a data block */
1261 recvblock == rdp->th_block) { /* then my last ack was lost */
1262 (void) swrite(peer, &ackbuf.storage[0], 4); /* resend final ack */
1269 * Send a nak packet (error message). Error code passed in is one of the
1270 * standard TFTP codes, or a UNIX errno offset by 100.
1272 static void nak(int error)
1279 tp->th_opcode = htons((unsigned short)opcode_ERROR);
1280 tp->th_code = htons((unsigned short)error);
1281 for (pe = errmsgs; pe->e_code >= 0; pe++)
1282 if (pe->e_code == error)
1284 if (pe->e_code < 0) {
1285 pe->e_msg = strerror(error - 100);
1286 tp->th_code = EUNDEF; /* set 'undef' errorcode */
1288 length = (int)strlen(pe->e_msg);
1290 /* we use memcpy() instead of strcpy() in order to avoid buffer overflow
1291 * report from glibc with FORTIFY_SOURCE */
1292 memcpy(tp->th_msg, pe->e_msg, length + 1);
1294 if (swrite(peer, &buf.storage[0], length) != length)
1295 logmsg("nak: fail\n");