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, 2016 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 testno; /* test case number */
111 int ofile; /* file descriptor for output file when uploading to us */
113 int writedelay; /* number of seconds between each packet */
128 char storage[PKTSIZE];
132 * bf.counter values in range [-1 .. SEGSIZE] represents size of data in the
133 * bf.buf buffer. Additionally it can also hold flags BF_ALLOC or BF_FREE.
137 int counter; /* size of data in buffer, or flag */
138 tftphdr_storage_t buf; /* room for data packet */
141 #define BF_ALLOC -3 /* alloc'd but not yet filled */
142 #define BF_FREE -2 /* free */
146 #define opcode_DATA 3
148 #define opcode_ERROR 5
153 #define MIN(x,y) ((x)<(y)?(x):(y))
155 #ifndef DEFAULT_LOGFILE
156 #define DEFAULT_LOGFILE "log/tftpd.log"
159 #define REQUEST_DUMP "log/server.input"
161 #define DEFAULT_PORT 8999 /* UDP */
163 /*****************************************************************************
165 *****************************************************************************/
167 static struct errmsg errmsgs[] = {
168 { EUNDEF, "Undefined error code" },
169 { ENOTFOUND, "File not found" },
170 { EACCESS, "Access violation" },
171 { ENOSPACE, "Disk full or allocation exceeded" },
172 { EBADOP, "Illegal TFTP operation" },
173 { EBADID, "Unknown transfer ID" },
174 { EEXISTS, "File already exists" },
175 { ENOUSER, "No such user" },
179 static struct formats formata[] = {
185 static struct bf bfs[2];
187 static int nextone; /* index of next buffer to use */
188 static int current; /* index of buffer in use */
190 /* control flags for crlf conversions */
191 static int newline = 0; /* fillbuf: in middle of newline expansion */
192 static int prevchar = -1; /* putbuf: previous char (cr check) */
194 static tftphdr_storage_t buf;
195 static tftphdr_storage_t ackbuf;
197 static srvr_sockaddr_union_t from;
198 static curl_socklen_t fromlen;
200 static curl_socket_t peer = CURL_SOCKET_BAD;
203 static int maxtimeout = 5 * TIMEOUT;
206 static bool use_ipv6 = FALSE;
208 static const char *ipv_inuse = "IPv4";
210 const char *serverlogfile = DEFAULT_LOGFILE;
211 static char *pidname= (char *)".tftpd.pid";
212 static int serverlogslocked = 0;
213 static int wrotepidfile = 0;
215 #ifdef HAVE_SIGSETJMP
216 static sigjmp_buf timeoutbuf;
219 #if defined(HAVE_ALARM) && defined(SIGALRM)
220 static int rexmtval = TIMEOUT;
223 /* do-nothing macro replacement for systems which lack siginterrupt() */
225 #ifndef HAVE_SIGINTERRUPT
226 #define siginterrupt(x,y) do {} while(0)
229 /* vars used to keep around previous signal handlers */
231 typedef RETSIGTYPE (*SIGHANDLER_T)(int);
234 static SIGHANDLER_T old_sighup_handler = SIG_ERR;
238 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
242 static SIGHANDLER_T old_sigint_handler = SIG_ERR;
246 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
249 #if defined(SIGBREAK) && defined(WIN32)
250 static SIGHANDLER_T old_sigbreak_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 void read_ahead(struct testcase *test, int convert);
273 static ssize_t write_behind(struct testcase *test, int convert);
275 static int synchnet(curl_socket_t);
277 static int do_tftp(struct testcase *test, struct tftphdr *tp, ssize_t size);
279 static int validate_access(struct testcase *test, const char *fname, int mode);
281 static void sendtftp(struct testcase *test, struct formats *pf);
283 static void recvtftp(struct testcase *test, struct formats *pf);
285 static void nak(int error);
287 #if defined(HAVE_ALARM) && defined(SIGALRM)
289 static void mysignal(int sig, void (*handler)(int));
291 static void timer(int signum);
293 static void justtimeout(int signum);
295 #endif /* HAVE_ALARM && SIGALRM */
297 static RETSIGTYPE exit_signal_handler(int signum);
299 static void install_signal_handlers(void);
301 static void restore_signal_handlers(void);
303 /*****************************************************************************
304 * FUNCTION IMPLEMENTATIONS *
305 *****************************************************************************/
307 #if defined(HAVE_ALARM) && defined(SIGALRM)
310 * Like signal(), but with well-defined semantics.
312 static void mysignal(int sig, void (*handler)(int))
315 memset(&sa, 0, sizeof(sa));
316 sa.sa_handler = handler;
317 sigaction(sig, &sa, NULL);
320 static void timer(int signum)
327 if(timeout >= maxtimeout) {
332 if(serverlogslocked) {
333 serverlogslocked = 0;
334 clear_advisor_read_lock(SERVERLOGS_LOCK);
338 #ifdef HAVE_SIGSETJMP
339 siglongjmp(timeoutbuf, 1);
343 static void justtimeout(int signum)
348 #endif /* HAVE_ALARM && SIGALRM */
350 /* signal handler that will be triggered to indicate that the program
351 should finish its execution in a controlled manner as soon as possible.
352 The first time this is called it will set got_exit_signal to one and
353 store in exit_signal the signal that triggered its execution. */
355 static RETSIGTYPE exit_signal_handler(int signum)
357 int old_errno = errno;
358 if(got_exit_signal == 0) {
360 exit_signal = signum;
362 (void)signal(signum, exit_signal_handler);
366 static void install_signal_handlers(void)
369 /* ignore SIGHUP signal */
370 old_sighup_handler = signal(SIGHUP, SIG_IGN);
371 if(old_sighup_handler == SIG_ERR)
372 logmsg("cannot install SIGHUP handler: %s", strerror(errno));
375 /* ignore SIGPIPE signal */
376 old_sigpipe_handler = signal(SIGPIPE, SIG_IGN);
377 if(old_sigpipe_handler == SIG_ERR)
378 logmsg("cannot install SIGPIPE handler: %s", strerror(errno));
381 /* handle SIGINT signal with our exit_signal_handler */
382 old_sigint_handler = signal(SIGINT, exit_signal_handler);
383 if(old_sigint_handler == SIG_ERR)
384 logmsg("cannot install SIGINT handler: %s", strerror(errno));
386 siginterrupt(SIGINT, 1);
389 /* handle SIGTERM signal with our exit_signal_handler */
390 old_sigterm_handler = signal(SIGTERM, exit_signal_handler);
391 if(old_sigterm_handler == SIG_ERR)
392 logmsg("cannot install SIGTERM handler: %s", strerror(errno));
394 siginterrupt(SIGTERM, 1);
396 #if defined(SIGBREAK) && defined(WIN32)
397 /* handle SIGBREAK signal with our exit_signal_handler */
398 old_sigbreak_handler = signal(SIGBREAK, exit_signal_handler);
399 if(old_sigbreak_handler == SIG_ERR)
400 logmsg("cannot install SIGBREAK handler: %s", strerror(errno));
402 siginterrupt(SIGBREAK, 1);
406 static void restore_signal_handlers(void)
409 if(SIG_ERR != old_sighup_handler)
410 (void)signal(SIGHUP, old_sighup_handler);
413 if(SIG_ERR != old_sigpipe_handler)
414 (void)signal(SIGPIPE, old_sigpipe_handler);
417 if(SIG_ERR != old_sigint_handler)
418 (void)signal(SIGINT, old_sigint_handler);
421 if(SIG_ERR != old_sigterm_handler)
422 (void)signal(SIGTERM, old_sigterm_handler);
424 #if defined(SIGBREAK) && defined(WIN32)
425 if(SIG_ERR != old_sigbreak_handler)
426 (void)signal(SIGBREAK, old_sigbreak_handler);
431 * init for either read-ahead or write-behind.
432 * zero for write-behind, one for read-head.
434 static struct tftphdr *rw_init(int x)
436 newline = 0; /* init crlf flag */
438 bfs[0].counter = BF_ALLOC; /* pass out the first buffer */
440 bfs[1].counter = BF_FREE;
441 nextone = x; /* ahead or behind? */
442 return &bfs[0].buf.hdr;
445 static struct tftphdr *w_init(void)
447 return rw_init(0); /* write-behind */
450 static struct tftphdr *r_init(void)
452 return rw_init(1); /* read-ahead */
455 /* Have emptied current buffer by sending to net and getting ack.
456 Free it and return next buffer filled with data.
458 static int readit(struct testcase *test, struct tftphdr **dpp,
459 int convert /* if true, convert to ascii */)
463 bfs[current].counter = BF_FREE; /* free old one */
464 current = !current; /* "incr" current */
466 b = &bfs[current]; /* look at new buffer */
467 if(b->counter == BF_FREE) /* if it's empty */
468 read_ahead(test, convert); /* fill it */
470 *dpp = &b->buf.hdr; /* set caller's ptr */
475 * fill the input buffer, doing ascii conversions if requested
476 * conversions are lf -> cr, lf and cr -> cr, nul
478 static void read_ahead(struct testcase *test,
479 int convert /* if true, convert to ascii */)
487 b = &bfs[nextone]; /* look at "next" buffer */
488 if(b->counter != BF_FREE) /* nop if not free */
490 nextone = !nextone; /* "incr" next buffer ptr */
495 /* The former file reading code did this:
496 b->counter = read(fileno(file), dp->th_data, SEGSIZE); */
497 size_t copy_n = MIN(SEGSIZE, test->rcount);
498 memcpy(dp->th_data, test->rptr, copy_n);
500 /* decrease amount, advance pointer */
501 test->rcount -= copy_n;
502 test->rptr += copy_n;
503 b->counter = (int)copy_n;
508 for(i = 0 ; i < SEGSIZE; i++) {
511 c = '\n'; /* lf to cr,lf */
513 c = '\0'; /* cr to cr,nul */
524 if(c == '\n' || c == '\r') {
532 b->counter = (int)(p - dp->th_data);
535 /* Update count associated with the buffer, get new buffer from the queue.
536 Calls write_behind only if next buffer not available.
538 static int writeit(struct testcase *test, struct tftphdr * volatile *dpp,
541 bfs[current].counter = ct; /* set size of data to write */
542 current = !current; /* switch to other buffer */
543 if(bfs[current].counter != BF_FREE) /* if not free */
544 write_behind(test, convert); /* flush it */
545 bfs[current].counter = BF_ALLOC; /* mark as alloc'd */
546 *dpp = &bfs[current].buf.hdr;
547 return ct; /* this is a lie of course */
551 * Output a buffer to a file, converting from netascii if requested.
552 * CR, NUL -> CR and CR, LF => LF.
553 * Note spec is undefined if we get CR as last byte of file or a
554 * CR followed by anything else. In this case we leave it alone.
556 static ssize_t write_behind(struct testcase *test, int convert)
562 int c; /* current character */
567 if(b->counter < -1) /* anything to flush? */
568 return 0; /* just nop if nothing to do */
572 snprintf(outfile, sizeof(outfile), "log/upload.%ld", test->testno);
574 test->ofile=open(outfile, O_CREAT|O_RDWR|O_BINARY, 0777);
576 test->ofile=open(outfile, O_CREAT|O_RDWR, 0777);
578 if(test->ofile == -1) {
579 logmsg("Couldn't create and/or open file %s for upload!", outfile);
580 return -1; /* failure! */
584 count = b->counter; /* remember byte count */
585 b->counter = BF_FREE; /* reset flag */
587 nextone = !nextone; /* incr for next time */
588 writebuf = dp->th_data;
591 return -1; /* nak logic? */
594 return write(test->ofile, writebuf, count);
598 while(ct--) { /* loop over the buffer */
599 c = *p++; /* pick up a character */
600 if(prevchar == '\r') { /* if prev char was cr */
601 if(c == '\n') /* if have cr,lf then just */
602 lseek(test->ofile, -1, SEEK_CUR); /* smash lf on top of the cr */
604 if(c == '\0') /* if have cr,nul then */
605 goto skipit; /* just skip over the putc */
606 /* else just fall through and allow it */
610 if(1 != write(test->ofile, &c, 1))
618 /* When an error has occurred, it is possible that the two sides are out of
619 * synch. Ie: that what I think is the other side's response to packet N is
620 * really their response to packet N-1.
622 * So, to try to prevent that, we flush all the input queued up for us on the
623 * network connection on our host.
625 * We return the number of packets we flushed (mostly for reporting when trace
629 static int synchnet(curl_socket_t f /* socket to flush */)
632 #if defined(HAVE_IOCTLSOCKET)
639 srvr_sockaddr_union_t fromaddr;
640 curl_socklen_t fromaddrlen;
643 #if defined(HAVE_IOCTLSOCKET)
644 (void) ioctlsocket(f, FIONREAD, &i);
646 (void) ioctl(f, FIONREAD, &i);
653 fromaddrlen = sizeof(fromaddr.sa4);
656 fromaddrlen = sizeof(fromaddr.sa6);
658 (void) recvfrom(f, rbuf, sizeof(rbuf), 0,
659 &fromaddr.sa, &fromaddrlen);
667 int main(int argc, char **argv)
669 srvr_sockaddr_union_t me;
673 unsigned short port = DEFAULT_PORT;
674 curl_socket_t sock = CURL_SOCKET_BAD;
679 struct testcase test;
682 memset(&test, 0, sizeof(test));
685 if(!strcmp("--version", argv[arg])) {
686 printf("tftpd IPv4%s\n",
695 else if(!strcmp("--pidfile", argv[arg])) {
698 pidname = argv[arg++];
700 else if(!strcmp("--logfile", argv[arg])) {
703 serverlogfile = argv[arg++];
705 else if(!strcmp("--ipv4", argv[arg])) {
712 else if(!strcmp("--ipv6", argv[arg])) {
719 else if(!strcmp("--port", argv[arg])) {
723 unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
724 if((endptr != argv[arg] + strlen(argv[arg])) ||
725 (ulnum < 1025UL) || (ulnum > 65535UL)) {
726 fprintf(stderr, "tftpd: invalid --port argument (%s)\n",
730 port = curlx_ultous(ulnum);
734 else if(!strcmp("--srcdir", argv[arg])) {
742 puts("Usage: tftpd [option]\n"
744 " --logfile [file]\n"
745 " --pidfile [file]\n"
756 atexit(win32_cleanup);
759 install_signal_handlers();
761 pid = (long)getpid();
766 sock = socket(AF_INET, SOCK_DGRAM, 0);
769 sock = socket(AF_INET6, SOCK_DGRAM, 0);
772 if(CURL_SOCKET_BAD == sock) {
774 logmsg("Error creating socket: (%d) %s",
775 error, strerror(error));
781 if(0 != setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
782 (void *)&flag, sizeof(flag))) {
784 logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
785 error, strerror(error));
793 memset(&me.sa4, 0, sizeof(me.sa4));
794 me.sa4.sin_family = AF_INET;
795 me.sa4.sin_addr.s_addr = INADDR_ANY;
796 me.sa4.sin_port = htons(port);
797 rc = bind(sock, &me.sa, sizeof(me.sa4));
801 memset(&me.sa6, 0, sizeof(me.sa6));
802 me.sa6.sin6_family = AF_INET6;
803 me.sa6.sin6_addr = in6addr_any;
804 me.sa6.sin6_port = htons(port);
805 rc = bind(sock, &me.sa, sizeof(me.sa6));
807 #endif /* ENABLE_IPV6 */
810 logmsg("Error binding socket on port %hu: (%d) %s",
811 port, error, strerror(error));
816 wrotepidfile = write_pidfile(pidname);
822 logmsg("Running %s version on port UDP/%d", ipv_inuse, (int)port);
825 fromlen = sizeof(from);
829 fromlen = sizeof(from.sa4);
832 fromlen = sizeof(from.sa6);
834 n = (ssize_t)recvfrom(sock, &buf.storage[0], sizeof(buf.storage), 0,
844 set_advisor_read_lock(SERVERLOGS_LOCK);
845 serverlogslocked = 1;
850 from.sa4.sin_family = AF_INET;
851 peer = socket(AF_INET, SOCK_DGRAM, 0);
852 if(CURL_SOCKET_BAD == peer) {
857 if(connect(peer, &from.sa, sizeof(from.sa4)) < 0) {
858 logmsg("connect: fail");
865 from.sa6.sin6_family = AF_INET6;
866 peer = socket(AF_INET6, SOCK_DGRAM, 0);
867 if(CURL_SOCKET_BAD == peer) {
872 if(connect(peer, &from.sa, sizeof(from.sa6)) < 0) {
873 logmsg("connect: fail");
880 maxtimeout = 5*TIMEOUT;
883 tp->th_opcode = ntohs(tp->th_opcode);
884 if(tp->th_opcode == opcode_RRQ || tp->th_opcode == opcode_WRQ) {
885 memset(&test, 0, sizeof(test));
886 if(do_tftp(&test, tp, n) < 0)
891 peer = CURL_SOCKET_BAD;
901 if(serverlogslocked) {
902 serverlogslocked = 0;
903 clear_advisor_read_lock(SERVERLOGS_LOCK);
906 logmsg("end of one transfer");
915 if((peer != sock) && (peer != CURL_SOCKET_BAD))
918 if(sock != CURL_SOCKET_BAD)
922 logmsg("signalled to die");
927 if(serverlogslocked) {
928 serverlogslocked = 0;
929 clear_advisor_read_lock(SERVERLOGS_LOCK);
932 restore_signal_handlers();
934 if(got_exit_signal) {
935 logmsg("========> %s tftpd (port: %d pid: %ld) exits with signal (%d)",
936 ipv_inuse, (int)port, pid, exit_signal);
938 * To properly set the return status of the process we
939 * must raise the same signal SIGINT or SIGTERM that we
940 * caught and let the old handler take care of it.
945 logmsg("========> tftpd quits");
950 * Handle initial connection protocol.
952 static int do_tftp(struct testcase *test, struct tftphdr *tp, ssize_t size)
955 int first = 1, ecode;
957 char *filename, *mode = NULL;
961 DWORD recvtimeout, recvtimeoutbak;
963 char *option = (char *)"mode"; /* mode is implicit */
966 /* Open request dump file. */
967 server = fopen(REQUEST_DUMP, "ab");
970 logmsg("fopen() failed with error: %d %s", error, strerror(error));
971 logmsg("Error opening file: %s", REQUEST_DUMP);
975 /* store input protocol */
976 fprintf(server, "opcode: %x\n", tp->th_opcode);
978 cp = (char *)&tp->th_stuff;
982 while(cp < &buf.storage[size]) {
990 /* no more options */
993 /* before increasing pointer, make sure it is still within the legal
995 if((cp+1) < &buf.storage[size]) {
998 /* store the mode since we need it later */
1003 /* name/value pair: */
1004 fprintf(server, "%s: %s\n", option, cp);
1006 /* store the name pointer */
1012 /* No more options */
1022 /* store input protocol */
1023 fprintf(server, "filename: %s\n", filename);
1025 for(cp = mode; cp && *cp; cp++)
1027 *cp = (char)tolower((int)*cp);
1029 /* store input protocol */
1032 for(pf = formata; pf->f_mode; pf++)
1033 if(strcmp(pf->f_mode, mode) == 0)
1039 ecode = validate_access(test, filename, tp->th_opcode);
1046 recvtimeout = sizeof(recvtimeoutbak);
1047 getsockopt(peer, SOL_SOCKET, SO_RCVTIMEO,
1048 (char *)&recvtimeoutbak, (int *)&recvtimeout);
1049 recvtimeout = TIMEOUT*1000;
1050 setsockopt(peer, SOL_SOCKET, SO_RCVTIMEO,
1051 (const char *)&recvtimeout, sizeof(recvtimeout));
1054 if(tp->th_opcode == opcode_WRQ)
1060 recvtimeout = recvtimeoutbak;
1061 setsockopt(peer, SOL_SOCKET, SO_RCVTIMEO,
1062 (const char *)&recvtimeout, sizeof(recvtimeout));
1068 /* Based on the testno, parse the correct server commands. */
1069 static int parse_servercmd(struct testcase *req)
1075 filename = test2file(req->testno);
1077 stream=fopen(filename, "rb");
1080 logmsg("fopen() failed with error: %d %s", error, strerror(error));
1081 logmsg(" [1] Error opening file: %s", filename);
1082 logmsg(" Couldn't open test file %ld", req->testno);
1083 return 1; /* done */
1086 char *orgcmd = NULL;
1091 /* get the custom server control "commands" */
1092 error = getpart(&orgcmd, &cmdsize, "reply", "servercmd", stream);
1095 logmsg("getpart() failed with error: %d", error);
1096 return 1; /* done */
1100 while(cmd && cmdsize) {
1102 if(1 == sscanf(cmd, "writedelay: %d", &num)) {
1103 logmsg("instructed to delay %d secs between packets", num);
1104 req->writedelay = num;
1107 logmsg("Unknown <servercmd> instruction found: %s", cmd);
1109 /* try to deal with CRLF or just LF */
1110 check = strchr(cmd, '\r');
1112 check = strchr(cmd, '\n');
1115 /* get to the letter following the newline */
1116 while((*check == '\r') || (*check == '\n'))
1120 /* if we reached a zero, get out */
1135 * Validate file access.
1137 static int validate_access(struct testcase *test,
1138 const char *filename, int mode)
1141 long testno, partno;
1143 char partbuf[80]="data";
1145 logmsg("trying to get file: %s mode %x", filename, mode);
1147 if(!strncmp("verifiedserver", filename, 14)) {
1149 size_t count = snprintf(weare, sizeof(weare),
1150 "WE ROOLZ: %ld\r\n", (long)getpid());
1152 logmsg("Are-we-friendly question received");
1153 test->buffer = strdup(weare);
1154 test->rptr = test->buffer; /* set read pointer */
1155 test->bufsize = count; /* set total count */
1156 test->rcount = count; /* set data left to read */
1157 return 0; /* fine */
1160 /* find the last slash */
1161 ptr = strrchr(filename, '/');
1166 ptr++; /* skip the slash */
1168 /* skip all non-numericals following the slash */
1169 while(*ptr && !ISDIGIT(*ptr))
1172 /* get the number */
1173 testno = strtol(ptr, &ptr, 10);
1175 if(testno > 10000) {
1176 partno = testno % 10000;
1183 logmsg("requested test number %ld part %ld", testno, partno);
1185 test->testno = testno;
1187 (void)parse_servercmd(test);
1189 file = test2file(testno);
1192 snprintf(partbuf, sizeof(partbuf), "data%ld", partno);
1195 FILE *stream=fopen(file, "rb");
1198 logmsg("fopen() failed with error: %d %s", error, strerror(error));
1199 logmsg("Error opening file: %s", file);
1200 logmsg("Couldn't open test file: %s", file);
1205 error = getpart(&test->buffer, &count, "reply", partbuf, stream);
1208 logmsg("getpart() failed with error: %d", error);
1212 test->rptr = test->buffer; /* set read pointer */
1213 test->bufsize = count; /* set total count */
1214 test->rcount = count; /* set data left to read */
1225 logmsg("no slash found in path");
1226 return EACCESS; /* failure */
1229 logmsg("file opened and all is good");
1234 * Send the requested file.
1236 static void sendtftp(struct testcase *test, struct formats *pf)
1240 /* These are volatile to live through a siglongjmp */
1241 volatile unsigned short sendblock; /* block count */
1242 struct tftphdr * volatile sdp = r_init(); /* data buffer */
1243 struct tftphdr * const sap = &ackbuf.hdr; /* ack buffer */
1246 #if defined(HAVE_ALARM) && defined(SIGALRM)
1247 mysignal(SIGALRM, timer);
1250 size = readit(test, (struct tftphdr **)&sdp, pf->f_convert);
1255 sdp->th_opcode = htons((unsigned short)opcode_DATA);
1256 sdp->th_block = htons(sendblock);
1258 #ifdef HAVE_SIGSETJMP
1259 (void) sigsetjmp(timeoutbuf, 1);
1261 if(test->writedelay) {
1262 logmsg("Pausing %d seconds before %d bytes", test->writedelay,
1264 wait_ms(1000*test->writedelay);
1268 if(swrite(peer, sdp, size + 4) != size + 4) {
1272 read_ahead(test, pf->f_convert);
1275 alarm(rexmtval); /* read the ack */
1277 n = sread(peer, &ackbuf.storage[0], sizeof(ackbuf.storage));
1284 logmsg("read: fail");
1287 sap->th_opcode = ntohs((unsigned short)sap->th_opcode);
1288 sap->th_block = ntohs(sap->th_block);
1290 if(sap->th_opcode == opcode_ERROR) {
1291 logmsg("got ERROR");
1295 if(sap->th_opcode == opcode_ACK) {
1296 if(sap->th_block == sendblock) {
1299 /* Re-synchronize with the other side */
1300 (void) synchnet(peer);
1301 if(sap->th_block == (sendblock-1)) {
1308 } while(size == SEGSIZE);
1314 static void recvtftp(struct testcase *test, struct formats *pf)
1317 /* These are volatile to live through a siglongjmp */
1318 volatile unsigned short recvblock; /* block count */
1319 struct tftphdr * volatile rdp; /* data buffer */
1320 struct tftphdr *rap; /* ack buffer */
1324 #if defined(HAVE_ALARM) && defined(SIGALRM)
1325 mysignal(SIGALRM, timer);
1330 rap->th_opcode = htons((unsigned short)opcode_ACK);
1331 rap->th_block = htons(recvblock);
1333 #ifdef HAVE_SIGSETJMP
1334 (void) sigsetjmp(timeoutbuf, 1);
1337 if(swrite(peer, &ackbuf.storage[0], 4) != 4) {
1338 logmsg("write: fail\n");
1341 write_behind(test, pf->f_convert);
1346 n = sread(peer, rdp, PKTSIZE);
1352 if(n < 0) { /* really? */
1353 logmsg("read: fail\n");
1356 rdp->th_opcode = ntohs((unsigned short)rdp->th_opcode);
1357 rdp->th_block = ntohs(rdp->th_block);
1358 if(rdp->th_opcode == opcode_ERROR)
1360 if(rdp->th_opcode == opcode_DATA) {
1361 if(rdp->th_block == recvblock) {
1364 /* Re-synchronize with the other side */
1365 (void) synchnet(peer);
1366 if(rdp->th_block == (recvblock-1))
1367 goto send_ack; /* rexmit */
1371 size = writeit(test, &rdp, (int)(n - 4), pf->f_convert);
1372 if(size != (n-4)) { /* ahem */
1379 } while(size == SEGSIZE);
1380 write_behind(test, pf->f_convert);
1382 rap->th_opcode = htons((unsigned short)opcode_ACK); /* send the "final"
1384 rap->th_block = htons(recvblock);
1385 (void) swrite(peer, &ackbuf.storage[0], 4);
1386 #if defined(HAVE_ALARM) && defined(SIGALRM)
1387 mysignal(SIGALRM, justtimeout); /* just abort read on timeout */
1390 /* normally times out and quits */
1391 n = sread(peer, &buf.storage[0], sizeof(buf.storage));
1397 if(n >= 4 && /* if read some data */
1398 rdp->th_opcode == opcode_DATA && /* and got a data block */
1399 recvblock == rdp->th_block) { /* then my last ack was lost */
1400 (void) swrite(peer, &ackbuf.storage[0], 4); /* resend final ack */
1407 * Send a nak packet (error message). Error code passed in is one of the
1408 * standard TFTP codes, or a Unix errno offset by 100.
1410 static void nak(int error)
1417 tp->th_opcode = htons((unsigned short)opcode_ERROR);
1418 tp->th_code = htons((unsigned short)error);
1419 for(pe = errmsgs; pe->e_code >= 0; pe++)
1420 if(pe->e_code == error)
1422 if(pe->e_code < 0) {
1423 pe->e_msg = strerror(error - 100);
1424 tp->th_code = EUNDEF; /* set 'undef' errorcode */
1426 length = (int)strlen(pe->e_msg);
1428 /* we use memcpy() instead of strcpy() in order to avoid buffer overflow
1429 * report from glibc with FORTIFY_SOURCE */
1430 memcpy(tp->th_msg, pe->e_msg, length + 1);
1432 if(swrite(peer, &buf.storage[0], length) != length)
1433 logmsg("nak: fail\n");