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 */
116 static int synchnet(curl_socket_t);
117 static struct tftphdr *r_init(void);
118 static struct tftphdr *w_init(void);
119 static int readit(struct testcase *test, struct tftphdr **dpp, int convert);
120 static int writeit(struct testcase *test, struct tftphdr **dpp, int ct,
122 static void mysignal(int, void (*func)(int));
127 #define PKTSIZE SEGSIZE+4
130 static int tftp(struct testcase *test, struct tftphdr *tp, int size);
131 static void nak(int error);
132 static void sendtftp(struct testcase *test, struct formats *pf);
133 static void recvtftp(struct testcase *test, struct formats *pf);
134 static int validate_access(struct testcase *test, const char *, int);
136 static curl_socket_t peer;
137 static int rexmtval = TIMEOUT;
138 static int maxtimeout = 5*TIMEOUT;
140 static char buf[PKTSIZE];
141 static char ackbuf[PKTSIZE];
142 static struct sockaddr_in from;
143 static socklen_t fromlen;
146 int counter; /* size of data in buffer, or flag */
147 char buf[PKTSIZE]; /* room for data packet */
150 /* Values for bf.counter */
151 #define BF_ALLOC -3 /* alloc'd but not yet filled */
152 #define BF_FREE -2 /* free */
153 /* [-1 .. SEGSIZE] = size of data in the data buffer */
155 static int nextone; /* index of next buffer to use */
156 static int current; /* index of buffer in use */
158 /* control flags for crlf conversions */
159 int newline = 0; /* fillbuf: in middle of newline expansion */
160 int prevchar = -1; /* putbuf: previous char (cr check) */
162 static void read_ahead(struct testcase *test,
163 int convert /* if true, convert to ascii */);
164 static ssize_t write_behind(struct testcase *test, int convert);
165 static struct tftphdr *rw_init(int);
166 static struct tftphdr *w_init(void) { return rw_init(0); } /* write-behind */
167 static struct tftphdr *r_init(void) { return rw_init(1); } /* read-ahead */
169 static struct tftphdr *
170 rw_init(int x) /* init for either read-ahead or write-behind */
171 { /* zero for write-behind, one for read-head */
172 newline = 0; /* init crlf flag */
174 bfs[0].counter = BF_ALLOC; /* pass out the first buffer */
176 bfs[1].counter = BF_FREE;
177 nextone = x; /* ahead or behind? */
178 return (struct tftphdr *)bfs[0].buf;
182 /* Have emptied current buffer by sending to net and getting ack.
183 Free it and return next buffer filled with data.
185 static int readit(struct testcase *test, struct tftphdr **dpp,
186 int convert /* if true, convert to ascii */)
190 bfs[current].counter = BF_FREE; /* free old one */
191 current = !current; /* "incr" current */
193 b = &bfs[current]; /* look at new buffer */
194 if (b->counter == BF_FREE) /* if it's empty */
195 read_ahead(test, convert); /* fill it */
197 *dpp = (struct tftphdr *)b->buf; /* set caller's ptr */
201 #undef MIN /* some systems have this defined already, some don't */
202 #define MIN(x,y) ((x)<(y)?(x):(y));
205 * fill the input buffer, doing ascii conversions if requested
206 * conversions are lf -> cr,lf and cr -> cr, nul
208 static void read_ahead(struct testcase *test,
209 int convert /* if true, convert to ascii */)
217 b = &bfs[nextone]; /* look at "next" buffer */
218 if (b->counter != BF_FREE) /* nop if not free */
220 nextone = !nextone; /* "incr" next buffer ptr */
222 dp = (struct tftphdr *)b->buf;
225 /* The former file reading code did this:
226 b->counter = read(fileno(file), dp->th_data, SEGSIZE); */
227 size_t copy_n = MIN(SEGSIZE, test->rcount);
228 memcpy(dp->th_data, test->rptr, copy_n);
230 /* decrease amount, advance pointer */
231 test->rcount -= copy_n;
232 test->rptr += copy_n;
233 b->counter = (int)copy_n;
238 for (i = 0 ; i < SEGSIZE; i++) {
240 if (prevchar == '\n')
241 c = '\n'; /* lf to cr,lf */
243 c = '\0'; /* cr to cr,nul */
254 if (c == '\n' || c == '\r') {
262 b->counter = (int)(p - dp->th_data);
265 /* Update count associated with the buffer, get new buffer from the queue.
266 Calls write_behind only if next buffer not available.
268 static int writeit(struct testcase *test, struct tftphdr **dpp,
271 bfs[current].counter = ct; /* set size of data to write */
272 current = !current; /* switch to other buffer */
273 if (bfs[current].counter != BF_FREE) /* if not free */
274 write_behind(test, convert); /* flush it */
275 bfs[current].counter = BF_ALLOC; /* mark as alloc'd */
276 *dpp = (struct tftphdr *)bfs[current].buf;
277 return ct; /* this is a lie of course */
281 * Output a buffer to a file, converting from netascii if requested.
282 * CR,NUL -> CR and CR,LF => LF.
283 * Note spec is undefined if we get CR as last byte of file or a
284 * CR followed by anything else. In this case we leave it alone.
286 static ssize_t write_behind(struct testcase *test, int convert)
292 int c; /* current character */
297 if (b->counter < -1) /* anything to flush? */
298 return 0; /* just nop if nothing to do */
302 snprintf(outfile, sizeof(outfile), "log/upload.%ld", test->num);
303 test->ofile=open(outfile, O_CREAT|O_RDWR, 0777);
304 if(test->ofile == -1) {
305 logmsg("Couldn't create and/or open file %s for upload!", outfile);
306 return -1; /* failure! */
310 count = b->counter; /* remember byte count */
311 b->counter = BF_FREE; /* reset flag */
312 dp = (struct tftphdr *)b->buf;
313 nextone = !nextone; /* incr for next time */
314 writebuf = dp->th_data;
317 return -1; /* nak logic? */
320 return write(test->ofile, writebuf, count);
324 while (ct--) { /* loop over the buffer */
325 c = *p++; /* pick up a character */
326 if (prevchar == '\r') { /* if prev char was cr */
327 if (c == '\n') /* if have cr,lf then just */
328 lseek(test->ofile, -1, SEEK_CUR); /* smash lf on top of the cr */
330 if (c == '\0') /* if have cr,nul then */
331 goto skipit; /* just skip over the putc */
332 /* else just fall through and allow it */
336 write(test->ofile, &c, 1);
344 /* When an error has occurred, it is possible that the two sides are out of
345 * synch. Ie: that what I think is the other side's response to packet N is
346 * really their response to packet N-1.
348 * So, to try to prevent that, we flush all the input queued up for us on the
349 * network connection on our host.
351 * We return the number of packets we flushed (mostly for reporting when trace
355 static int synchnet(curl_socket_t f /* socket to flush */)
358 #if defined(HAVE_IOCTLSOCKET)
365 struct sockaddr_in fromaddr;
366 socklen_t fromaddrlen;
369 #if defined(HAVE_IOCTLSOCKET)
370 (void) ioctlsocket(f, FIONREAD, &i);
372 (void) ioctl(f, FIONREAD, &i);
376 fromaddrlen = sizeof fromaddr;
377 (void) recvfrom(f, rbuf, sizeof (rbuf), 0,
378 (struct sockaddr *)&fromaddr, &fromaddrlen);
386 #if defined(HAVE_ALARM) && defined(SIGALRM)
388 * Like signal(), but with well-defined semantics.
390 static void mysignal(int sig, void (*handler)(int))
393 memset(&sa, 0, sizeof(sa));
394 sa.sa_handler = handler;
395 sigaction(sig, &sa, NULL);
399 #ifndef DEFAULT_LOGFILE
400 #define DEFAULT_LOGFILE "log/tftpd.log"
403 #define DEFAULT_PORT 8999 /* UDP */
404 const char *serverlogfile = DEFAULT_LOGFILE;
406 #define REQUEST_DUMP "log/server.input"
410 int main(int argc, char **argv)
412 struct sockaddr_in me;
414 struct sockaddr_in6 me6;
415 #endif /* ENABLE_IPV6 */
421 char *pidname= (char *)".tftpd.pid";
422 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++]);
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");
512 pidfile = fopen(pidname, "w");
514 long pid = (long)getpid();
515 fprintf(pidfile, "%ld\n", pid);
517 logmsg("Wrote pid %ld to %s", pid, pidname);
521 logmsg("fopen() failed with error: %d %s", error, strerror(error));
522 logmsg("Error opening file: %s", pidname);
523 logmsg("Couldn't write pid file");
528 logmsg("Running IPv%d version on port UDP/%d",
537 fromlen = sizeof(from);
538 n = recvfrom(sock, buf, sizeof (buf), 0,
539 (struct sockaddr *)&from, &fromlen);
541 logmsg("recvfrom:\n");
545 from.sin_family = AF_INET;
547 peer = socket(AF_INET, SOCK_DGRAM, 0);
553 if (connect(peer, (struct sockaddr *)&from, sizeof(from)) < 0) {
554 logmsg("connect: fail\n");
557 maxtimeout = 5*TIMEOUT;
559 tp = (struct tftphdr *)buf;
560 tp->th_opcode = ntohs(tp->th_opcode);
561 if (tp->th_opcode == RRQ || tp->th_opcode == WRQ) {
562 memset(&test, 0, sizeof(test));
563 if (tftp(&test, tp, n) < 0)
583 * Handle initial connection protocol.
585 static int tftp(struct testcase *test, struct tftphdr *tp, int size)
588 int first = 1, ecode;
590 char *filename, *mode = NULL;
594 /* Open request dump file. */
595 server = fopen(REQUEST_DUMP, "ab");
598 logmsg("fopen() failed with error: %d %s", error, strerror(error));
599 logmsg("Error opening file: %s", REQUEST_DUMP);
603 /* store input protocol */
604 fprintf(server, "opcode: %x\n", tp->th_opcode);
606 cp = (char *)&tp->th_stuff;
609 while (cp < buf + size) {
624 /* store input protocol */
625 fprintf(server, "filename: %s\n", filename);
627 for (cp = mode; *cp; cp++)
629 *cp = (char)tolower((int)*cp);
631 /* store input protocol */
632 fprintf(server, "mode: %s\n", mode);
635 for (pf = formats; pf->f_mode; pf++)
636 if (strcmp(pf->f_mode, mode) == 0)
642 ecode = validate_access(test, filename, tp->th_opcode);
647 if (tp->th_opcode == WRQ)
656 * Validate file access.
658 static int validate_access(struct testcase *test,
659 const char *filename, int mode)
664 char partbuf[80]="data";
666 logmsg("trying to get file: %s mode %x", filename, mode);
668 if(!strncmp("verifiedserver", filename, 14)) {
670 size_t count = sprintf(weare, "WE ROOLZ: %ld\r\n", (long)getpid());
672 logmsg("Are-we-friendly question received");
673 test->buffer = strdup(weare);
674 test->rptr = test->buffer; /* set read pointer */
675 test->bufsize = count; /* set total count */
676 test->rcount = count; /* set data left to read */
680 /* find the last slash */
681 ptr = strrchr(filename, '/');
686 ptr++; /* skip the slash */
688 /* skip all non-numericals following the slash */
689 while(*ptr && !ISDIGIT(*ptr))
693 testno = strtol(ptr, &ptr, 10);
696 partno = testno % 10000;
703 logmsg("requested test number %ld part %ld", testno, partno);
707 file = test2file(testno);
710 sprintf(partbuf, "data%ld", partno);
713 FILE *stream=fopen(file, "rb");
716 logmsg("fopen() failed with error: %d %s", error, strerror(error));
717 logmsg("Error opening file: %s", file);
718 logmsg("Couldn't open test file: %s", file);
723 test->buffer = (char *)spitout(stream, "reply", partbuf, &count);
726 test->rptr = test->buffer; /* set read pointer */
727 test->bufsize = count; /* set total count */
728 test->rcount = count; /* set data left to read */
739 logmsg("no slash found in path");
740 return EACCESS; /* failure */
747 #ifdef HAVE_SIGSETJMP
748 sigjmp_buf timeoutbuf;
751 static void timer(int signum)
758 if (timeout >= maxtimeout)
760 #ifdef HAVE_SIGSETJMP
761 siglongjmp(timeoutbuf, 1);
766 * Send the requested file.
768 static void sendtftp(struct testcase *test, struct formats *pf)
771 struct tftphdr *ap; /* ack packet */
772 unsigned short block = 1;
775 #if defined(HAVE_ALARM) && defined(SIGALRM)
776 mysignal(SIGALRM, timer);
779 ap = (struct tftphdr *)ackbuf;
781 size = readit(test, &dp, pf->f_convert);
786 dp->th_opcode = htons((u_short)DATA);
787 dp->th_block = htons((u_short)block);
789 #ifdef HAVE_SIGSETJMP
790 (void) sigsetjmp(timeoutbuf, 1);
793 if (swrite(peer, dp, size + 4) != size + 4) {
797 read_ahead(test, pf->f_convert);
800 alarm(rexmtval); /* read the ack */
802 n = sread(peer, ackbuf, sizeof (ackbuf));
807 logmsg("read: fail\n");
810 ap->th_opcode = ntohs((u_short)ap->th_opcode);
811 ap->th_block = ntohs((u_short)ap->th_block);
813 if (ap->th_opcode == ERROR) {
818 if (ap->th_opcode == ACK) {
819 if (ap->th_block == block) {
822 /* Re-synchronize with the other side */
823 (void) synchnet(peer);
824 if (ap->th_block == (block -1)) {
831 } while (size == SEGSIZE);
834 static void justtimeout(int signum)
843 static void recvtftp(struct testcase *test, struct formats *pf)
846 struct tftphdr *ap; /* ack buffer */
847 unsigned short block = 0;
849 #if defined(HAVE_ALARM) && defined(SIGALRM)
850 mysignal(SIGALRM, timer);
853 ap = (struct tftphdr *)ackbuf;
856 ap->th_opcode = htons((u_short)ACK);
857 ap->th_block = htons((u_short)block);
859 #ifdef HAVE_SIGSETJMP
860 (void) sigsetjmp(timeoutbuf, 1);
863 if (swrite(peer, ackbuf, 4) != 4) {
864 logmsg("write: fail\n");
867 write_behind(test, pf->f_convert);
872 n = sread(peer, dp, PKTSIZE);
876 if (n < 0) { /* really? */
877 logmsg("read: fail\n");
880 dp->th_opcode = ntohs((u_short)dp->th_opcode);
881 dp->th_block = ntohs((u_short)dp->th_block);
882 if (dp->th_opcode == ERROR)
884 if (dp->th_opcode == DATA) {
885 if (dp->th_block == block) {
888 /* Re-synchronize with the other side */
889 (void) synchnet(peer);
890 if (dp->th_block == (block-1))
891 goto send_ack; /* rexmit */
895 size = writeit(test, &dp, (int)(n - 4), pf->f_convert);
896 if (size != (n-4)) { /* ahem */
903 } while (size == SEGSIZE);
904 write_behind(test, pf->f_convert);
906 ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */
907 ap->th_block = htons((u_short)(block));
908 (void) swrite(peer, ackbuf, 4);
909 #if defined(HAVE_ALARM) && defined(SIGALRM)
910 mysignal(SIGALRM, justtimeout); /* just abort read on timeout */
913 n = sread(peer, buf, sizeof(buf)); /* normally times out and quits */
917 if (n >= 4 && /* if read some data */
918 dp->th_opcode == DATA && /* and got a data block */
919 block == dp->th_block) { /* then my last ack was lost */
920 (void) swrite(peer, ackbuf, 4); /* resend final ack */
930 { EUNDEF, "Undefined error code" },
931 { ENOTFOUND, "File not found" },
932 { EACCESS, "Access violation" },
933 { ENOSPACE, "Disk full or allocation exceeded" },
934 { EBADOP, "Illegal TFTP operation" },
935 { EBADID, "Unknown transfer ID" },
936 { EEXISTS, "File already exists" },
937 { ENOUSER, "No such user" },
942 * Send a nak packet (error message). Error code passed in is one of the
943 * standard TFTP codes, or a UNIX errno offset by 100.
945 static void nak(int error)
951 tp = (struct tftphdr *)buf;
952 tp->th_opcode = htons((u_short)ERROR);
953 tp->th_code = htons((u_short)error);
954 for (pe = errmsgs; pe->e_code >= 0; pe++)
955 if (pe->e_code == error)
957 if (pe->e_code < 0) {
958 pe->e_msg = strerror(error - 100);
959 tp->th_code = EUNDEF; /* set 'undef' errorcode */
961 strcpy(tp->th_msg, pe->e_msg);
962 length = (int)strlen(pe->e_msg);
963 tp->th_msg[length] = '\0';
965 if (swrite(peer, buf, length) != length)
966 logmsg("nak: fail\n");