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 */
52 #ifdef HAVE_SYS_TYPES_H
53 #include <sys/types.h>
55 #ifdef HAVE_SYS_IOCTL_H
56 #include <sys/ioctl.h>
58 #ifdef HAVE_SYS_STAT_H
67 #ifdef HAVE_SYS_SOCKET_H
68 #include <sys/socket.h>
70 #ifdef HAVE_NETINET_IN_H
71 #include <netinet/in.h>
73 #ifdef HAVE_ARPA_TFTP_H
74 #include <arpa/tftp.h>
81 #ifdef HAVE_SYS_FILIO_H
82 /* FIONREAD on Solaris 7 */
83 #include <sys/filio.h>
97 #define ENABLE_CURLX_PRINTF
98 /* make the curlx header define all printf() functions to use the curlx_*
100 #include "curlx.h" /* from the private lib dir */
104 /* include memdebug.h last */
105 #include "memdebug.h"
108 char *buffer; /* holds the file data to send to the client */
109 size_t bufsize; /* size of the data in buffer */
110 char *rptr; /* read pointer into the buffer */
111 size_t rcount; /* amount of data left to read of the file */
112 long num; /* test case number */
113 int ofile; /* file descriptor for output file when uploading to us */
114 FILE *server; /* write input "protocol" there for client verification */
117 static int synchnet(curl_socket_t);
118 static struct tftphdr *r_init(void);
119 static struct tftphdr *w_init(void);
120 static int readit(struct testcase *test, struct tftphdr **dpp, int convert);
121 static int writeit(struct testcase *test, struct tftphdr **dpp, int ct,
123 static void mysignal(int, void (*func)(int));
128 #define PKTSIZE SEGSIZE+4
131 static int tftp(struct testcase *test, struct tftphdr *tp, int size);
132 static void nak(int error);
133 static void sendtftp(struct testcase *test, struct formats *pf);
134 static void recvtftp(struct testcase *test, struct formats *pf);
135 static int validate_access(struct testcase *test, const char *, int);
137 static curl_socket_t peer;
138 static int rexmtval = TIMEOUT;
139 static int maxtimeout = 5*TIMEOUT;
141 static char buf[PKTSIZE];
142 static char ackbuf[PKTSIZE];
143 static struct sockaddr_in from;
144 static socklen_t fromlen;
147 int counter; /* size of data in buffer, or flag */
148 char buf[PKTSIZE]; /* room for data packet */
151 /* Values for bf.counter */
152 #define BF_ALLOC -3 /* alloc'd but not yet filled */
153 #define BF_FREE -2 /* free */
154 /* [-1 .. SEGSIZE] = size of data in the data buffer */
156 static int nextone; /* index of next buffer to use */
157 static int current; /* index of buffer in use */
159 /* control flags for crlf conversions */
160 int newline = 0; /* fillbuf: in middle of newline expansion */
161 int prevchar = -1; /* putbuf: previous char (cr check) */
163 static void read_ahead(struct testcase *test,
164 int convert /* if true, convert to ascii */);
165 static ssize_t write_behind(struct testcase *test, int convert);
166 static struct tftphdr *rw_init(int);
167 static struct tftphdr *w_init(void) { return rw_init(0); } /* write-behind */
168 static struct tftphdr *r_init(void) { return rw_init(1); } /* read-ahead */
170 static struct tftphdr *
171 rw_init(int x) /* init for either read-ahead or write-behind */
172 { /* zero for write-behind, one for read-head */
173 newline = 0; /* init crlf flag */
175 bfs[0].counter = BF_ALLOC; /* pass out the first buffer */
177 bfs[1].counter = BF_FREE;
178 nextone = x; /* ahead or behind? */
179 return (struct tftphdr *)bfs[0].buf;
183 /* Have emptied current buffer by sending to net and getting ack.
184 Free it and return next buffer filled with data.
186 static int readit(struct testcase *test, struct tftphdr **dpp,
187 int convert /* if true, convert to ascii */)
191 bfs[current].counter = BF_FREE; /* free old one */
192 current = !current; /* "incr" current */
194 b = &bfs[current]; /* look at new buffer */
195 if (b->counter == BF_FREE) /* if it's empty */
196 read_ahead(test, convert); /* fill it */
198 *dpp = (struct tftphdr *)b->buf; /* set caller's ptr */
202 #undef MIN /* some systems have this defined already, some don't */
203 #define MIN(x,y) ((x)<(y)?(x):(y));
206 * fill the input buffer, doing ascii conversions if requested
207 * conversions are lf -> cr,lf and cr -> cr, nul
209 static void read_ahead(struct testcase *test,
210 int convert /* if true, convert to ascii */)
218 b = &bfs[nextone]; /* look at "next" buffer */
219 if (b->counter != BF_FREE) /* nop if not free */
221 nextone = !nextone; /* "incr" next buffer ptr */
223 dp = (struct tftphdr *)b->buf;
226 /* The former file reading code did this:
227 b->counter = read(fileno(file), dp->th_data, SEGSIZE); */
228 size_t copy_n = MIN(SEGSIZE, test->rcount);
229 memcpy(dp->th_data, test->rptr, copy_n);
231 /* decrease amount, advance pointer */
232 test->rcount -= copy_n;
233 test->rptr += copy_n;
234 b->counter = (int)copy_n;
239 for (i = 0 ; i < SEGSIZE; i++) {
241 if (prevchar == '\n')
242 c = '\n'; /* lf to cr,lf */
244 c = '\0'; /* cr to cr,nul */
255 if (c == '\n' || c == '\r') {
263 b->counter = (int)(p - dp->th_data);
266 /* Update count associated with the buffer, get new buffer from the queue.
267 Calls write_behind only if next buffer not available.
269 static int writeit(struct testcase *test, struct tftphdr **dpp,
272 bfs[current].counter = ct; /* set size of data to write */
273 current = !current; /* switch to other buffer */
274 if (bfs[current].counter != BF_FREE) /* if not free */
275 write_behind(test, convert); /* flush it */
276 bfs[current].counter = BF_ALLOC; /* mark as alloc'd */
277 *dpp = (struct tftphdr *)bfs[current].buf;
278 return ct; /* this is a lie of course */
282 * Output a buffer to a file, converting from netascii if requested.
283 * CR,NUL -> CR and CR,LF => LF.
284 * Note spec is undefined if we get CR as last byte of file or a
285 * CR followed by anything else. In this case we leave it alone.
287 static ssize_t write_behind(struct testcase *test, int convert)
293 int c; /* current character */
298 if (b->counter < -1) /* anything to flush? */
299 return 0; /* just nop if nothing to do */
303 snprintf(outfile, sizeof(outfile), "log/upload.%ld", test->num);
304 test->ofile=open(outfile, O_CREAT|O_RDWR, 0777);
305 if(test->ofile == -1) {
306 logmsg("Couldn't create and/or open file %s for upload!", outfile);
307 return -1; /* failure! */
311 count = b->counter; /* remember byte count */
312 b->counter = BF_FREE; /* reset flag */
313 dp = (struct tftphdr *)b->buf;
314 nextone = !nextone; /* incr for next time */
318 return -1; /* nak logic? */
321 return write(test->ofile, buf, count);
325 while (ct--) { /* loop over the buffer */
326 c = *p++; /* pick up a character */
327 if (prevchar == '\r') { /* if prev char was cr */
328 if (c == '\n') /* if have cr,lf then just */
329 lseek(test->ofile, -1, SEEK_CUR); /* smash lf on top of the cr */
331 if (c == '\0') /* if have cr,nul then */
332 goto skipit; /* just skip over the putc */
333 /* else just fall through and allow it */
337 write(test->ofile, &c, 1);
345 /* When an error has occurred, it is possible that the two sides are out of
346 * synch. Ie: that what I think is the other side's response to packet N is
347 * really their response to packet N-1.
349 * So, to try to prevent that, we flush all the input queued up for us on the
350 * network connection on our host.
352 * We return the number of packets we flushed (mostly for reporting when trace
356 static int synchnet(curl_socket_t f /* socket to flush */)
359 #if defined(HAVE_IOCTLSOCKET)
366 struct sockaddr_in from;
370 #if defined(HAVE_IOCTLSOCKET)
371 (void) ioctlsocket(f, FIONREAD, &i);
373 (void) ioctl(f, FIONREAD, &i);
377 fromlen = sizeof from;
378 (void) recvfrom(f, rbuf, sizeof (rbuf), 0,
379 (struct sockaddr *)&from, &fromlen);
387 #if defined(HAVE_ALARM) && defined(SIGALRM)
389 * Like signal(), but with well-defined semantics.
391 static void mysignal(int sig, void (*handler)(int))
394 memset(&sa, 0, sizeof(sa));
395 sa.sa_handler = handler;
396 sigaction(sig, &sa, NULL);
400 #ifndef DEFAULT_LOGFILE
401 #define DEFAULT_LOGFILE "log/tftpd.log"
404 #define DEFAULT_PORT 8999 /* UDP */
405 const char *serverlogfile = DEFAULT_LOGFILE;
407 #define REQUEST_DUMP "log/server.input"
411 int main(int argc, char **argv)
413 struct sockaddr_in me;
415 struct sockaddr_in6 me6;
416 #endif /* ENABLE_IPV6 */
422 char *pidname= (char *)".tftpd.pid";
423 unsigned short port = DEFAULT_PORT;
427 struct testcase test;
430 if(!strcmp("--version", argv[arg])) {
431 printf("tftpd IPv4%s\n",
440 else if(!strcmp("--pidfile", argv[arg])) {
443 pidname = argv[arg++];
445 else if(!strcmp("--ipv6", argv[arg])) {
454 port = (unsigned short)atoi(argv[arg++]);
461 #if defined(WIN32) && !defined(__GNUC__) || defined(__MINGW32__)
463 atexit(win32_cleanup);
469 sock = socket(AF_INET, SOCK_DGRAM, 0);
472 sock = socket(AF_INET6, SOCK_DGRAM, 0);
476 perror("opening stream socket");
477 logmsg("Error opening socket");
483 (sock, SOL_SOCKET, SO_REUSEADDR, (const void *) &flag,
485 perror("setsockopt(SO_REUSEADDR)");
491 me.sin_family = AF_INET;
492 me.sin_addr.s_addr = INADDR_ANY;
493 me.sin_port = htons(port);
494 rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
498 memset(&me6, 0, sizeof(struct sockaddr_in6));
499 me6.sin6_family = AF_INET6;
500 me6.sin6_addr = in6addr_any;
501 me6.sin6_port = htons(port);
502 rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
504 #endif /* ENABLE_IPV6 */
506 perror("binding stream socket");
507 logmsg("Error binding socket");
511 pidfile = fopen(pidname, "w");
513 fprintf(pidfile, "%d\n", (int)getpid());
517 fprintf(stderr, "Couldn't write pid file\n");
519 logmsg("Running IPv%d version on port UDP/%d",
530 fromlen = sizeof(from);
531 n = recvfrom(sock, buf, sizeof (buf), 0,
532 (struct sockaddr *)&from, &fromlen);
534 logmsg("recvfrom:\n");
538 from.sin_family = AF_INET;
540 peer = socket(AF_INET, SOCK_DGRAM, 0);
546 if (connect(peer, (struct sockaddr *)&from, sizeof(from)) < 0) {
547 logmsg("connect: fail\n");
550 maxtimeout = 5*TIMEOUT;
552 tp = (struct tftphdr *)buf;
553 tp->th_opcode = ntohs(tp->th_opcode);
554 if (tp->th_opcode == RRQ || tp->th_opcode == WRQ) {
555 memset(&test, 0, sizeof(test));
556 server = fopen(REQUEST_DUMP, "ab");
559 test.server = server;
580 * Handle initial connection protocol.
582 static int tftp(struct testcase *test, struct tftphdr *tp, int size)
585 int first = 1, ecode;
587 char *filename, *mode = NULL;
589 /* store input protocol */
590 fprintf(test->server, "opcode: %x\n", tp->th_opcode);
592 cp = (char *)&tp->th_stuff;
595 while (cp < buf + size) {
609 /* store input protocol */
610 fprintf(test->server, "filename: %s\n", filename);
612 for (cp = mode; *cp; cp++)
613 if (isupper((int)*cp))
614 *cp = tolower((int)*cp);
616 /* store input protocol */
617 fprintf(test->server, "mode: %s\n", mode);
619 for (pf = formats; pf->f_mode; pf++)
620 if (strcmp(pf->f_mode, mode) == 0)
626 ecode = validate_access(test, filename, tp->th_opcode);
631 if (tp->th_opcode == WRQ)
640 * Validate file access.
642 static int validate_access(struct testcase *test,
643 const char *filename, int mode)
648 logmsg("trying to get file: %s mode %x", filename, mode);
650 if(!strncmp("/verifiedserver", filename, 15)) {
652 size_t count = sprintf(weare, "WE ROOLZ: %d\r\n", (int)getpid());
654 logmsg("Are-we-friendly question received");
655 test->buffer = strdup(weare);
656 test->rptr = test->buffer; /* set read pointer */
657 test->bufsize = count; /* set total count */
658 test->rcount = count; /* set data left to read */
662 /* find the last slash */
663 ptr = strrchr(filename, '/');
668 ptr++; /* skip the slash */
670 /* skip all non-numericals following the slash */
671 while(*ptr && !isdigit((int)*ptr))
675 testno = strtol(ptr, &ptr, 10);
677 logmsg("requested test number %d", testno);
681 file = test2file(testno);
684 FILE *stream=fopen(file, "rb");
686 logmsg("Couldn't open test file: %s", file);
691 test->buffer = (char *)spitout(stream, "reply", "data", &count);
694 test->rptr = test->buffer; /* set read pointer */
695 test->bufsize = count; /* set total count */
696 test->rcount = count; /* set data left to read */
707 logmsg("no slash found in path");
708 return EACCESS; /* failure */
715 #ifdef HAVE_SIGSETJMP
716 sigjmp_buf timeoutbuf;
719 static void timer(int signum)
726 if (timeout >= maxtimeout)
728 #ifdef HAVE_SIGSETJMP
729 siglongjmp(timeoutbuf, 1);
734 * Send the requested file.
736 static void sendtftp(struct testcase *test, struct formats *pf)
739 struct tftphdr *ap; /* ack packet */
740 unsigned short block = 1;
742 #if defined(HAVE_ALARM) && defined(SIGALRM)
743 mysignal(SIGALRM, timer);
746 ap = (struct tftphdr *)ackbuf;
748 size = readit(test, &dp, pf->f_convert);
753 dp->th_opcode = htons((u_short)DATA);
754 dp->th_block = htons((u_short)block);
756 #ifdef HAVE_SIGSETJMP
757 (void) sigsetjmp(timeoutbuf, 1);
760 if (send(peer, dp, size + 4, 0) != size + 4) {
764 read_ahead(test, pf->f_convert);
767 alarm(rexmtval); /* read the ack */
769 n = recv(peer, ackbuf, sizeof (ackbuf), 0);
774 logmsg("read: fail\n");
777 ap->th_opcode = ntohs((u_short)ap->th_opcode);
778 ap->th_block = ntohs((u_short)ap->th_block);
780 if (ap->th_opcode == ERROR) {
785 if (ap->th_opcode == ACK) {
786 if (ap->th_block == block) {
789 /* Re-synchronize with the other side */
790 (void) synchnet(peer);
791 if (ap->th_block == (block -1)) {
798 } while (size == SEGSIZE);
801 static void justquit(int signum)
811 static void recvtftp(struct testcase *test, struct formats *pf)
814 struct tftphdr *ap; /* ack buffer */
815 unsigned short block = 0;
817 #if defined(HAVE_ALARM) && defined(SIGALRM)
818 mysignal(SIGALRM, timer);
821 ap = (struct tftphdr *)ackbuf;
824 ap->th_opcode = htons((u_short)ACK);
825 ap->th_block = htons((u_short)block);
827 #ifdef HAVE_SIGSETJMP
828 (void) sigsetjmp(timeoutbuf, 1);
831 if (send(peer, ackbuf, 4, 0) != 4) {
832 logmsg("write: fail\n");
835 write_behind(test, pf->f_convert);
840 n = recv(peer, dp, PKTSIZE, 0);
844 if (n < 0) { /* really? */
845 logmsg("read: fail\n");
848 dp->th_opcode = ntohs((u_short)dp->th_opcode);
849 dp->th_block = ntohs((u_short)dp->th_block);
850 if (dp->th_opcode == ERROR)
852 if (dp->th_opcode == DATA) {
853 if (dp->th_block == block) {
856 /* Re-synchronize with the other side */
857 (void) synchnet(peer);
858 if (dp->th_block == (block-1))
859 goto send_ack; /* rexmit */
863 size = writeit(test, &dp, n - 4, pf->f_convert);
864 if (size != (n-4)) { /* ahem */
871 } while (size == SEGSIZE);
872 write_behind(test, pf->f_convert);
874 ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */
875 ap->th_block = htons((u_short)(block));
876 (void) send(peer, ackbuf, 4, 0);
877 #if defined(HAVE_ALARM) && defined(SIGALRM)
878 mysignal(SIGALRM, justquit); /* just quit on timeout */
881 n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
885 if (n >= 4 && /* if read some data */
886 dp->th_opcode == DATA && /* and got a data block */
887 block == dp->th_block) { /* then my last ack was lost */
888 (void) send(peer, ackbuf, 4, 0); /* resend final ack */
898 { EUNDEF, "Undefined error code" },
899 { ENOTFOUND, "File not found" },
900 { EACCESS, "Access violation" },
901 { ENOSPACE, "Disk full or allocation exceeded" },
902 { EBADOP, "Illegal TFTP operation" },
903 { EBADID, "Unknown transfer ID" },
904 { EEXISTS, "File already exists" },
905 { ENOUSER, "No such user" },
910 * Send a nak packet (error message). Error code passed in is one of the
911 * standard TFTP codes, or a UNIX errno offset by 100.
913 static void nak(int error)
919 tp = (struct tftphdr *)buf;
920 tp->th_opcode = htons((u_short)ERROR);
921 tp->th_code = htons((u_short)error);
922 for (pe = errmsgs; pe->e_code >= 0; pe++)
923 if (pe->e_code == error)
925 if (pe->e_code < 0) {
926 pe->e_msg = strerror(error - 100);
927 tp->th_code = EUNDEF; /* set 'undef' errorcode */
929 strcpy(tp->th_msg, pe->e_msg);
930 length = (int)strlen(pe->e_msg);
931 tp->th_msg[length] = '\0';
933 if (send(peer, buf, length, 0) != length)
934 logmsg("nak: fail\n");