1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
10 * Trivial file transfer protocol server.
12 * This code includes many modifications by Jim Guyton <guyton@rand-unix>
14 * This source file was started based on netkit-tftpd 0.17
15 * Heavily modified for curl's test suite
19 * Copyright (c) 1983 Regents of the University of California.
20 * All rights reserved.
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the above copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 * must display the following acknowledgement:
32 * This product includes software developed by the University of
33 * California, Berkeley and its contributors.
34 * 4. Neither the name of the University nor the names of its contributors
35 * may be used to endorse or promote products derived from this software
36 * without specific prior written permission.
38 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
39 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
40 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
41 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
42 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
43 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
44 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
45 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
46 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
47 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51 #include "setup.h" /* portability help from the lib directory */
53 #ifdef HAVE_SYS_IOCTL_H
54 #include <sys/ioctl.h>
62 #ifdef HAVE_SYS_SOCKET_H
63 #include <sys/socket.h>
65 #ifdef HAVE_NETINET_IN_H
66 #include <netinet/in.h>
68 #ifdef HAVE_ARPA_INET_H
69 #include <arpa/inet.h>
71 #ifdef HAVE_ARPA_TFTP_H
72 #include <arpa/tftp.h>
79 #ifdef HAVE_SYS_FILIO_H
80 /* FIONREAD on Solaris 7 */
81 #include <sys/filio.h>
92 #define ENABLE_CURLX_PRINTF
93 /* make the curlx header define all printf() functions to use the curlx_*
95 #include "curlx.h" /* from the private lib dir */
99 /* include memdebug.h last */
100 #include "memdebug.h"
102 /*****************************************************************************
103 * STRUCT DECLARATIONS AND DEFINES *
104 *****************************************************************************/
106 #define PKTSIZE (SEGSIZE + 4) /* SEGSIZE defined in arpa/tftp.h */
109 char *buffer; /* holds the file data to send to the client */
110 size_t bufsize; /* size of the data in buffer */
111 char *rptr; /* read pointer into the buffer */
112 size_t rcount; /* amount of data left to read of the file */
113 long num; /* test case number */
114 int ofile; /* file descriptor for output file when uploading to us */
128 * bf.counter values in range [-1 .. SEGSIZE] represents size of data in the
129 * bf.buf buffer. Additionally it can also hold flags BF_ALLOC or BF_FREE.
133 int counter; /* size of data in buffer, or flag */
134 char buf[PKTSIZE]; /* room for data packet */
137 #define BF_ALLOC -3 /* alloc'd but not yet filled */
138 #define BF_FREE -2 /* free */
142 #define opcode_DATA 3
144 #define opcode_ERROR 5
149 #define MIN(x,y) ((x)<(y)?(x):(y))
151 #ifndef DEFAULT_LOGFILE
152 #define DEFAULT_LOGFILE "log/tftpd.log"
155 #define REQUEST_DUMP "log/server.input"
157 #define DEFAULT_PORT 8999 /* UDP */
159 /*****************************************************************************
161 *****************************************************************************/
163 static struct errmsg errmsgs[] = {
164 { EUNDEF, "Undefined error code" },
165 { ENOTFOUND, "File not found" },
166 { EACCESS, "Access violation" },
167 { ENOSPACE, "Disk full or allocation exceeded" },
168 { EBADOP, "Illegal TFTP operation" },
169 { EBADID, "Unknown transfer ID" },
170 { EEXISTS, "File already exists" },
171 { ENOUSER, "No such user" },
175 static struct formats formata[] = {
181 static struct bf bfs[2];
183 static int nextone; /* index of next buffer to use */
184 static int current; /* index of buffer in use */
186 /* control flags for crlf conversions */
187 static int newline = 0; /* fillbuf: in middle of newline expansion */
188 static int prevchar = -1; /* putbuf: previous char (cr check) */
190 static char buf[PKTSIZE];
191 static char ackbuf[PKTSIZE];
193 static struct sockaddr_in from;
194 static curl_socklen_t fromlen;
196 static curl_socket_t peer = CURL_SOCKET_BAD;
199 static int maxtimeout = 5 * TIMEOUT;
201 static unsigned short sendblock; /* block count used by sendtftp() */
202 static struct tftphdr *sdp; /* data buffer used by sendtftp() */
203 static struct tftphdr *sap; /* ack buffer used by sendtftp() */
205 static unsigned short recvblock; /* block count used by recvtftp() */
206 static struct tftphdr *rdp; /* data buffer used by recvtftp() */
207 static struct tftphdr *rap; /* ack buffer used by recvtftp() */
210 static bool use_ipv6 = FALSE;
212 static const char *ipv_inuse = "IPv4";
214 const char *serverlogfile = DEFAULT_LOGFILE;
215 static char *pidname= (char *)".tftpd.pid";
216 static int serverlogslocked = 0;
217 static int wrotepidfile = 0;
219 #ifdef HAVE_SIGSETJMP
220 static sigjmp_buf timeoutbuf;
223 #if defined(HAVE_ALARM) && defined(SIGALRM)
224 static int rexmtval = TIMEOUT;
227 /* do-nothing macro replacement for systems which lack siginterrupt() */
229 #ifndef HAVE_SIGINTERRUPT
230 #define siginterrupt(x,y) do {} while(0)
233 /* vars used to keep around previous signal handlers */
235 typedef RETSIGTYPE (*SIGHANDLER_T)(int);
238 static SIGHANDLER_T old_sighup_handler = SIG_ERR;
242 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
246 static SIGHANDLER_T old_sigint_handler = SIG_ERR;
250 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
253 /* var which if set indicates that the program should finish execution */
255 SIG_ATOMIC_T got_exit_signal = 0;
257 /* if next is set indicates the first signal handled in exit_signal_handler */
259 static volatile int exit_signal = 0;
261 /*****************************************************************************
262 * FUNCTION PROTOTYPES *
263 *****************************************************************************/
265 static struct tftphdr *rw_init(int);
267 static struct tftphdr *w_init(void);
269 static struct tftphdr *r_init(void);
271 static int readit(struct testcase *test,
272 struct tftphdr **dpp,
275 static int writeit(struct testcase *test,
276 struct tftphdr **dpp,
280 static void read_ahead(struct testcase *test, int convert);
282 static ssize_t write_behind(struct testcase *test, int convert);
284 static int synchnet(curl_socket_t);
286 static int do_tftp(struct testcase *test, struct tftphdr *tp, ssize_t size);
288 static int validate_access(struct testcase *test, const char *fname, int mode);
290 static void sendtftp(struct testcase *test, struct formats *pf);
292 static void recvtftp(struct testcase *test, struct formats *pf);
294 static void nak(int error);
296 #if defined(HAVE_ALARM) && defined(SIGALRM)
298 static void mysignal(int sig, void (*handler)(int));
300 static void timer(int signum);
302 static void justtimeout(int signum);
304 #endif /* HAVE_ALARM && SIGALRM */
306 static RETSIGTYPE exit_signal_handler(int signum);
308 static void install_signal_handlers(void);
310 static void restore_signal_handlers(void);
312 /*****************************************************************************
313 * FUNCTION IMPLEMENTATIONS *
314 *****************************************************************************/
316 #if defined(HAVE_ALARM) && defined(SIGALRM)
319 * Like signal(), but with well-defined semantics.
321 static void mysignal(int sig, void (*handler)(int))
324 memset(&sa, 0, sizeof(sa));
325 sa.sa_handler = handler;
326 sigaction(sig, &sa, NULL);
329 static void timer(int signum)
336 if(timeout >= maxtimeout) {
341 if(serverlogslocked) {
342 serverlogslocked = 0;
343 clear_advisor_read_lock(SERVERLOGS_LOCK);
347 #ifdef HAVE_SIGSETJMP
348 siglongjmp(timeoutbuf, 1);
352 static void justtimeout(int signum)
357 #endif /* HAVE_ALARM && SIGALRM */
359 /* signal handler that will be triggered to indicate that the program
360 should finish its execution in a controlled manner as soon as possible.
361 The first time this is called it will set got_exit_signal to one and
362 store in exit_signal the signal that triggered its execution. */
364 static RETSIGTYPE exit_signal_handler(int signum)
366 int old_errno = ERRNO;
367 if(got_exit_signal == 0) {
369 exit_signal = signum;
371 (void)signal(signum, exit_signal_handler);
372 SET_ERRNO(old_errno);
375 static void install_signal_handlers(void)
378 /* ignore SIGHUP signal */
379 if((old_sighup_handler = signal(SIGHUP, SIG_IGN)) == SIG_ERR)
380 logmsg("cannot install SIGHUP handler: %s", strerror(ERRNO));
383 /* ignore SIGPIPE signal */
384 if((old_sigpipe_handler = signal(SIGPIPE, SIG_IGN)) == SIG_ERR)
385 logmsg("cannot install SIGPIPE handler: %s", strerror(ERRNO));
388 /* handle SIGINT signal with our exit_signal_handler */
389 if((old_sigint_handler = signal(SIGINT, exit_signal_handler)) == SIG_ERR)
390 logmsg("cannot install SIGINT handler: %s", strerror(ERRNO));
392 siginterrupt(SIGINT, 1);
395 /* handle SIGTERM signal with our exit_signal_handler */
396 if((old_sigterm_handler = signal(SIGTERM, exit_signal_handler)) == SIG_ERR)
397 logmsg("cannot install SIGTERM handler: %s", strerror(ERRNO));
399 siginterrupt(SIGTERM, 1);
403 static void restore_signal_handlers(void)
406 if(SIG_ERR != old_sighup_handler)
407 (void)signal(SIGHUP, old_sighup_handler);
410 if(SIG_ERR != old_sigpipe_handler)
411 (void)signal(SIGPIPE, old_sigpipe_handler);
414 if(SIG_ERR != old_sigint_handler)
415 (void)signal(SIGINT, old_sigint_handler);
418 if(SIG_ERR != old_sigterm_handler)
419 (void)signal(SIGTERM, old_sigterm_handler);
424 * init for either read-ahead or write-behind.
425 * zero for write-behind, one for read-head.
427 static struct tftphdr *rw_init(int x)
429 newline = 0; /* init crlf flag */
431 bfs[0].counter = BF_ALLOC; /* pass out the first buffer */
433 bfs[1].counter = BF_FREE;
434 nextone = x; /* ahead or behind? */
435 return (struct tftphdr *)bfs[0].buf;
438 static struct tftphdr *w_init(void)
440 return rw_init(0); /* write-behind */
443 static struct tftphdr *r_init(void)
445 return rw_init(1); /* read-ahead */
448 /* Have emptied current buffer by sending to net and getting ack.
449 Free it and return next buffer filled with data.
451 static int readit(struct testcase *test, struct tftphdr **dpp,
452 int convert /* if true, convert to ascii */)
456 bfs[current].counter = BF_FREE; /* free old one */
457 current = !current; /* "incr" current */
459 b = &bfs[current]; /* look at new buffer */
460 if (b->counter == BF_FREE) /* if it's empty */
461 read_ahead(test, convert); /* fill it */
463 *dpp = (struct tftphdr *)b->buf; /* set caller's ptr */
468 * fill the input buffer, doing ascii conversions if requested
469 * conversions are lf -> cr,lf and cr -> cr, nul
471 static void read_ahead(struct testcase *test,
472 int convert /* if true, convert to ascii */)
480 b = &bfs[nextone]; /* look at "next" buffer */
481 if (b->counter != BF_FREE) /* nop if not free */
483 nextone = !nextone; /* "incr" next buffer ptr */
485 dp = (struct tftphdr *)b->buf;
488 /* The former file reading code did this:
489 b->counter = read(fileno(file), dp->th_data, SEGSIZE); */
490 size_t copy_n = MIN(SEGSIZE, test->rcount);
491 memcpy(dp->th_data, test->rptr, copy_n);
493 /* decrease amount, advance pointer */
494 test->rcount -= copy_n;
495 test->rptr += copy_n;
496 b->counter = (int)copy_n;
501 for (i = 0 ; i < SEGSIZE; i++) {
503 if (prevchar == '\n')
504 c = '\n'; /* lf to cr,lf */
506 c = '\0'; /* cr to cr,nul */
517 if (c == '\n' || c == '\r') {
525 b->counter = (int)(p - dp->th_data);
528 /* Update count associated with the buffer, get new buffer from the queue.
529 Calls write_behind only if next buffer not available.
531 static int writeit(struct testcase *test, struct tftphdr **dpp,
534 bfs[current].counter = ct; /* set size of data to write */
535 current = !current; /* switch to other buffer */
536 if (bfs[current].counter != BF_FREE) /* if not free */
537 write_behind(test, convert); /* flush it */
538 bfs[current].counter = BF_ALLOC; /* mark as alloc'd */
539 *dpp = (struct tftphdr *)bfs[current].buf;
540 return ct; /* this is a lie of course */
544 * Output a buffer to a file, converting from netascii if requested.
545 * CR,NUL -> CR and CR,LF => LF.
546 * Note spec is undefined if we get CR as last byte of file or a
547 * CR followed by anything else. In this case we leave it alone.
549 static ssize_t write_behind(struct testcase *test, int convert)
555 int c; /* current character */
560 if (b->counter < -1) /* anything to flush? */
561 return 0; /* just nop if nothing to do */
565 snprintf(outfile, sizeof(outfile), "log/upload.%ld", test->num);
566 test->ofile=open(outfile, O_CREAT|O_RDWR, 0777);
567 if(test->ofile == -1) {
568 logmsg("Couldn't create and/or open file %s for upload!", outfile);
569 return -1; /* failure! */
573 count = b->counter; /* remember byte count */
574 b->counter = BF_FREE; /* reset flag */
575 dp = (struct tftphdr *)b->buf;
576 nextone = !nextone; /* incr for next time */
577 writebuf = dp->th_data;
580 return -1; /* nak logic? */
583 return write(test->ofile, writebuf, count);
587 while (ct--) { /* loop over the buffer */
588 c = *p++; /* pick up a character */
589 if (prevchar == '\r') { /* if prev char was cr */
590 if (c == '\n') /* if have cr,lf then just */
591 lseek(test->ofile, -1, SEEK_CUR); /* smash lf on top of the cr */
593 if (c == '\0') /* if have cr,nul then */
594 goto skipit; /* just skip over the putc */
595 /* else just fall through and allow it */
599 write(test->ofile, &c, 1);
606 /* When an error has occurred, it is possible that the two sides are out of
607 * synch. Ie: that what I think is the other side's response to packet N is
608 * really their response to packet N-1.
610 * So, to try to prevent that, we flush all the input queued up for us on the
611 * network connection on our host.
613 * We return the number of packets we flushed (mostly for reporting when trace
617 static int synchnet(curl_socket_t f /* socket to flush */)
620 #if defined(HAVE_IOCTLSOCKET)
627 struct sockaddr_in fromaddr;
628 curl_socklen_t fromaddrlen;
631 #if defined(HAVE_IOCTLSOCKET)
632 (void) ioctlsocket(f, FIONREAD, &i);
634 (void) ioctl(f, FIONREAD, &i);
638 fromaddrlen = sizeof(fromaddr);
639 (void)recvfrom(f, rbuf, sizeof(rbuf), 0,
640 (struct sockaddr *)&fromaddr, &fromaddrlen);
648 int main(int argc, char **argv)
650 struct sockaddr_in me;
652 struct sockaddr_in6 me6;
653 #endif /* ENABLE_IPV6 */
658 unsigned short port = DEFAULT_PORT;
659 curl_socket_t sock = CURL_SOCKET_BAD;
664 struct testcase test;
667 memset(&test, 0, sizeof(test));
670 if(!strcmp("--version", argv[arg])) {
671 printf("tftpd IPv4%s\n",
680 else if(!strcmp("--pidfile", argv[arg])) {
683 pidname = argv[arg++];
685 else if(!strcmp("--logfile", argv[arg])) {
688 serverlogfile = argv[arg++];
690 else if(!strcmp("--ipv4", argv[arg])) {
697 else if(!strcmp("--ipv6", argv[arg])) {
704 else if(!strcmp("--port", argv[arg])) {
707 port = (unsigned short)atoi(argv[arg]);
711 else if(!strcmp("--srcdir", argv[arg])) {
719 puts("Usage: tftpd [option]\n"
721 " --logfile [file]\n"
722 " --pidfile [file]\n"
726 " --srcdir [path]\n");
733 atexit(win32_cleanup);
736 install_signal_handlers();
738 pid = (long)getpid();
743 sock = socket(AF_INET, SOCK_DGRAM, 0);
746 sock = socket(AF_INET6, SOCK_DGRAM, 0);
749 if(CURL_SOCKET_BAD == sock) {
751 logmsg("Error creating socket: (%d) %s",
752 error, strerror(error));
758 if (0 != setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
759 (void *)&flag, sizeof(flag))) {
761 logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
762 error, strerror(error));
770 memset(&me, 0, sizeof(me));
771 me.sin_family = AF_INET;
772 me.sin_addr.s_addr = INADDR_ANY;
773 me.sin_port = htons(port);
774 rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
778 memset(&me6, 0, sizeof(me6));
779 me6.sin6_family = AF_INET6;
780 me6.sin6_addr = in6addr_any;
781 me6.sin6_port = htons(port);
782 rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
784 #endif /* ENABLE_IPV6 */
787 logmsg("Error binding socket on port %hu: (%d) %s",
788 port, error, strerror(error));
793 wrotepidfile = write_pidfile(pidname);
799 logmsg("Running %s version on port UDP/%d", ipv_inuse, (int)port);
802 fromlen = sizeof(from);
803 n = (ssize_t)recvfrom(sock, buf, sizeof(buf), 0,
804 (struct sockaddr *)&from, &fromlen);
813 set_advisor_read_lock(SERVERLOGS_LOCK);
814 serverlogslocked = 1;
816 from.sin_family = AF_INET;
818 peer = socket(AF_INET, SOCK_DGRAM, 0);
819 if(CURL_SOCKET_BAD == peer) {
825 if (connect(peer, (struct sockaddr *)&from, sizeof(from)) < 0) {
826 logmsg("connect: fail");
830 maxtimeout = 5*TIMEOUT;
832 tp = (struct tftphdr *)buf;
833 tp->th_opcode = ntohs(tp->th_opcode);
834 if (tp->th_opcode == opcode_RRQ || tp->th_opcode == opcode_WRQ) {
835 memset(&test, 0, sizeof(test));
836 if (do_tftp(&test, tp, n) < 0)
842 peer = CURL_SOCKET_BAD;
852 if(serverlogslocked) {
853 serverlogslocked = 0;
854 clear_advisor_read_lock(SERVERLOGS_LOCK);
857 logmsg("end of one transfer");
866 if((peer != sock) && (peer != CURL_SOCKET_BAD))
869 if(sock != CURL_SOCKET_BAD)
873 logmsg("signalled to die");
878 if(serverlogslocked) {
879 serverlogslocked = 0;
880 clear_advisor_read_lock(SERVERLOGS_LOCK);
883 restore_signal_handlers();
885 if(got_exit_signal) {
886 logmsg("========> %s tftpd (port: %d pid: %ld) exits with signal (%d)",
887 ipv_inuse, (int)port, pid, exit_signal);
889 * To properly set the return status of the process we
890 * must raise the same signal SIGINT or SIGTERM that we
891 * caught and let the old handler take care of it.
896 logmsg("========> tftpd quits");
901 * Handle initial connection protocol.
903 static int do_tftp(struct testcase *test, struct tftphdr *tp, ssize_t size)
906 int first = 1, ecode;
908 char *filename, *mode = NULL;
912 /* Open request dump file. */
913 server = fopen(REQUEST_DUMP, "ab");
916 logmsg("fopen() failed with error: %d %s", error, strerror(error));
917 logmsg("Error opening file: %s", REQUEST_DUMP);
921 /* store input protocol */
922 fprintf(server, "opcode: %x\n", tp->th_opcode);
924 cp = (char *)&tp->th_stuff;
927 while (cp < buf + size) {
942 /* store input protocol */
943 fprintf(server, "filename: %s\n", filename);
945 for (cp = mode; cp && *cp; cp++)
947 *cp = (char)tolower((int)*cp);
949 /* store input protocol */
950 fprintf(server, "mode: %s\n", mode);
953 for (pf = formata; pf->f_mode; pf++)
954 if (strcmp(pf->f_mode, mode) == 0)
960 ecode = validate_access(test, filename, tp->th_opcode);
965 if (tp->th_opcode == opcode_WRQ)
974 * Validate file access.
976 static int validate_access(struct testcase *test,
977 const char *filename, int mode)
982 char partbuf[80]="data";
984 logmsg("trying to get file: %s mode %x", filename, mode);
986 if(!strncmp("verifiedserver", filename, 14)) {
988 size_t count = sprintf(weare, "WE ROOLZ: %ld\r\n", (long)getpid());
990 logmsg("Are-we-friendly question received");
991 test->buffer = strdup(weare);
992 test->rptr = test->buffer; /* set read pointer */
993 test->bufsize = count; /* set total count */
994 test->rcount = count; /* set data left to read */
998 /* find the last slash */
999 ptr = strrchr(filename, '/');
1004 ptr++; /* skip the slash */
1006 /* skip all non-numericals following the slash */
1007 while(*ptr && !ISDIGIT(*ptr))
1010 /* get the number */
1011 testno = strtol(ptr, &ptr, 10);
1013 if(testno > 10000) {
1014 partno = testno % 10000;
1021 logmsg("requested test number %ld part %ld", testno, partno);
1025 file = test2file(testno);
1028 sprintf(partbuf, "data%ld", partno);
1031 FILE *stream=fopen(file, "rb");
1034 logmsg("fopen() failed with error: %d %s", error, strerror(error));
1035 logmsg("Error opening file: %s", file);
1036 logmsg("Couldn't open test file: %s", file);
1041 test->buffer = (char *)spitout(stream, "reply", partbuf, &count);
1044 test->rptr = test->buffer; /* set read pointer */
1045 test->bufsize = count; /* set total count */
1046 test->rcount = count; /* set data left to read */
1057 logmsg("no slash found in path");
1058 return EACCESS; /* failure */
1061 logmsg("file opened and all is good");
1066 * Send the requested file.
1068 static void sendtftp(struct testcase *test, struct formats *pf)
1073 #if defined(HAVE_ALARM) && defined(SIGALRM)
1074 mysignal(SIGALRM, timer);
1077 sap = (struct tftphdr *)ackbuf;
1079 size = readit(test, &sdp, pf->f_convert);
1084 sdp->th_opcode = htons((u_short)opcode_DATA);
1085 sdp->th_block = htons((u_short)sendblock);
1087 #ifdef HAVE_SIGSETJMP
1088 (void) sigsetjmp(timeoutbuf, 1);
1091 if (swrite(peer, sdp, size + 4) != size + 4) {
1095 read_ahead(test, pf->f_convert);
1098 alarm(rexmtval); /* read the ack */
1100 n = sread(peer, ackbuf, sizeof (ackbuf));
1107 logmsg("read: fail");
1110 sap->th_opcode = ntohs((u_short)sap->th_opcode);
1111 sap->th_block = ntohs((u_short)sap->th_block);
1113 if (sap->th_opcode == opcode_ERROR) {
1114 logmsg("got ERROR");
1118 if (sap->th_opcode == opcode_ACK) {
1119 if (sap->th_block == sendblock) {
1122 /* Re-synchronize with the other side */
1123 (void) synchnet(peer);
1124 if (sap->th_block == (sendblock-1)) {
1131 } while (size == SEGSIZE);
1137 static void recvtftp(struct testcase *test, struct formats *pf)
1141 #if defined(HAVE_ALARM) && defined(SIGALRM)
1142 mysignal(SIGALRM, timer);
1145 rap = (struct tftphdr *)ackbuf;
1148 rap->th_opcode = htons((u_short)opcode_ACK);
1149 rap->th_block = htons((u_short)recvblock);
1151 #ifdef HAVE_SIGSETJMP
1152 (void) sigsetjmp(timeoutbuf, 1);
1155 if (swrite(peer, ackbuf, 4) != 4) {
1156 logmsg("write: fail\n");
1159 write_behind(test, pf->f_convert);
1164 n = sread(peer, rdp, PKTSIZE);
1170 if (n < 0) { /* really? */
1171 logmsg("read: fail\n");
1174 rdp->th_opcode = ntohs((u_short)rdp->th_opcode);
1175 rdp->th_block = ntohs((u_short)rdp->th_block);
1176 if (rdp->th_opcode == opcode_ERROR)
1178 if (rdp->th_opcode == opcode_DATA) {
1179 if (rdp->th_block == recvblock) {
1182 /* Re-synchronize with the other side */
1183 (void) synchnet(peer);
1184 if (rdp->th_block == (recvblock-1))
1185 goto send_ack; /* rexmit */
1189 size = writeit(test, &rdp, (int)(n - 4), pf->f_convert);
1190 if (size != (n-4)) { /* ahem */
1197 } while (size == SEGSIZE);
1198 write_behind(test, pf->f_convert);
1200 rap->th_opcode = htons((u_short)opcode_ACK); /* send the "final" ack */
1201 rap->th_block = htons((u_short)recvblock);
1202 (void) swrite(peer, ackbuf, 4);
1203 #if defined(HAVE_ALARM) && defined(SIGALRM)
1204 mysignal(SIGALRM, justtimeout); /* just abort read on timeout */
1207 n = sread(peer, buf, sizeof(buf)); /* normally times out and quits */
1213 if (n >= 4 && /* if read some data */
1214 rdp->th_opcode == opcode_DATA && /* and got a data block */
1215 recvblock == rdp->th_block) { /* then my last ack was lost */
1216 (void) swrite(peer, ackbuf, 4); /* resend final ack */
1223 * Send a nak packet (error message). Error code passed in is one of the
1224 * standard TFTP codes, or a UNIX errno offset by 100.
1226 static void nak(int error)
1232 tp = (struct tftphdr *)buf;
1233 tp->th_opcode = htons((u_short)opcode_ERROR);
1234 tp->th_code = htons((u_short)error);
1235 for (pe = errmsgs; pe->e_code >= 0; pe++)
1236 if (pe->e_code == error)
1238 if (pe->e_code < 0) {
1239 pe->e_msg = strerror(error - 100);
1240 tp->th_code = EUNDEF; /* set 'undef' errorcode */
1242 strcpy(tp->th_msg, pe->e_msg);
1243 length = (int)strlen(pe->e_msg);
1244 tp->th_msg[length] = '\0';
1246 if (swrite(peer, buf, length) != length)
1247 logmsg("nak: fail\n");