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"
103 static bool use_ipv6 = FALSE;
105 static const char *ipv_inuse = "IPv4";
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,
125 #define opcode_DATA 3
127 #define opcode_ERROR 5
131 #define PKTSIZE SEGSIZE+4
137 static struct formats formata[] = {
143 static int tftp(struct testcase *test, struct tftphdr *tp, ssize_t size);
144 static void nak(int error);
145 static void sendtftp(struct testcase *test, struct formats *pf);
146 static void recvtftp(struct testcase *test, struct formats *pf);
147 static int validate_access(struct testcase *test, const char *, int);
149 static curl_socket_t peer;
150 static int maxtimeout = 5*TIMEOUT;
152 static char buf[PKTSIZE];
153 static char ackbuf[PKTSIZE];
154 static struct sockaddr_in from;
155 static curl_socklen_t fromlen;
158 int counter; /* size of data in buffer, or flag */
159 char buf[PKTSIZE]; /* room for data packet */
161 static struct bf bfs[2];
163 /* Values for bf.counter */
164 #define BF_ALLOC -3 /* alloc'd but not yet filled */
165 #define BF_FREE -2 /* free */
166 /* [-1 .. SEGSIZE] = size of data in the data buffer */
168 static int nextone; /* index of next buffer to use */
169 static int current; /* index of buffer in use */
171 /* control flags for crlf conversions */
172 static int newline = 0; /* fillbuf: in middle of newline expansion */
173 static int prevchar = -1; /* putbuf: previous char (cr check) */
175 static void read_ahead(struct testcase *test,
176 int convert /* if true, convert to ascii */);
177 static ssize_t write_behind(struct testcase *test, int convert);
178 static struct tftphdr *rw_init(int);
179 static struct tftphdr *w_init(void) { return rw_init(0); } /* write-behind */
180 static struct tftphdr *r_init(void) { return rw_init(1); } /* read-ahead */
182 static struct tftphdr *
183 rw_init(int x) /* init for either read-ahead or write-behind */
184 { /* zero for write-behind, one for read-head */
185 newline = 0; /* init crlf flag */
187 bfs[0].counter = BF_ALLOC; /* pass out the first buffer */
189 bfs[1].counter = BF_FREE;
190 nextone = x; /* ahead or behind? */
191 return (struct tftphdr *)bfs[0].buf;
195 /* Have emptied current buffer by sending to net and getting ack.
196 Free it and return next buffer filled with data.
198 static int readit(struct testcase *test, struct tftphdr **dpp,
199 int convert /* if true, convert to ascii */)
203 bfs[current].counter = BF_FREE; /* free old one */
204 current = !current; /* "incr" current */
206 b = &bfs[current]; /* look at new buffer */
207 if (b->counter == BF_FREE) /* if it's empty */
208 read_ahead(test, convert); /* fill it */
210 *dpp = (struct tftphdr *)b->buf; /* set caller's ptr */
214 #undef MIN /* some systems have this defined already, some don't */
215 #define MIN(x,y) ((x)<(y)?(x):(y));
218 * fill the input buffer, doing ascii conversions if requested
219 * conversions are lf -> cr,lf and cr -> cr, nul
221 static void read_ahead(struct testcase *test,
222 int convert /* if true, convert to ascii */)
230 b = &bfs[nextone]; /* look at "next" buffer */
231 if (b->counter != BF_FREE) /* nop if not free */
233 nextone = !nextone; /* "incr" next buffer ptr */
235 dp = (struct tftphdr *)b->buf;
238 /* The former file reading code did this:
239 b->counter = read(fileno(file), dp->th_data, SEGSIZE); */
240 size_t copy_n = MIN(SEGSIZE, test->rcount);
241 memcpy(dp->th_data, test->rptr, copy_n);
243 /* decrease amount, advance pointer */
244 test->rcount -= copy_n;
245 test->rptr += copy_n;
246 b->counter = (int)copy_n;
251 for (i = 0 ; i < SEGSIZE; i++) {
253 if (prevchar == '\n')
254 c = '\n'; /* lf to cr,lf */
256 c = '\0'; /* cr to cr,nul */
267 if (c == '\n' || c == '\r') {
275 b->counter = (int)(p - dp->th_data);
278 /* Update count associated with the buffer, get new buffer from the queue.
279 Calls write_behind only if next buffer not available.
281 static int writeit(struct testcase *test, struct tftphdr **dpp,
284 bfs[current].counter = ct; /* set size of data to write */
285 current = !current; /* switch to other buffer */
286 if (bfs[current].counter != BF_FREE) /* if not free */
287 write_behind(test, convert); /* flush it */
288 bfs[current].counter = BF_ALLOC; /* mark as alloc'd */
289 *dpp = (struct tftphdr *)bfs[current].buf;
290 return ct; /* this is a lie of course */
294 * Output a buffer to a file, converting from netascii if requested.
295 * CR,NUL -> CR and CR,LF => LF.
296 * Note spec is undefined if we get CR as last byte of file or a
297 * CR followed by anything else. In this case we leave it alone.
299 static ssize_t write_behind(struct testcase *test, int convert)
305 int c; /* current character */
310 if (b->counter < -1) /* anything to flush? */
311 return 0; /* just nop if nothing to do */
315 snprintf(outfile, sizeof(outfile), "log/upload.%ld", test->num);
316 test->ofile=open(outfile, O_CREAT|O_RDWR, 0777);
317 if(test->ofile == -1) {
318 logmsg("Couldn't create and/or open file %s for upload!", outfile);
319 return -1; /* failure! */
323 count = b->counter; /* remember byte count */
324 b->counter = BF_FREE; /* reset flag */
325 dp = (struct tftphdr *)b->buf;
326 nextone = !nextone; /* incr for next time */
327 writebuf = dp->th_data;
330 return -1; /* nak logic? */
333 return write(test->ofile, writebuf, count);
337 while (ct--) { /* loop over the buffer */
338 c = *p++; /* pick up a character */
339 if (prevchar == '\r') { /* if prev char was cr */
340 if (c == '\n') /* if have cr,lf then just */
341 lseek(test->ofile, -1, SEEK_CUR); /* smash lf on top of the cr */
343 if (c == '\0') /* if have cr,nul then */
344 goto skipit; /* just skip over the putc */
345 /* else just fall through and allow it */
349 write(test->ofile, &c, 1);
357 /* When an error has occurred, it is possible that the two sides are out of
358 * synch. Ie: that what I think is the other side's response to packet N is
359 * really their response to packet N-1.
361 * So, to try to prevent that, we flush all the input queued up for us on the
362 * network connection on our host.
364 * We return the number of packets we flushed (mostly for reporting when trace
368 static int synchnet(curl_socket_t f /* socket to flush */)
371 #if defined(HAVE_IOCTLSOCKET)
378 struct sockaddr_in fromaddr;
379 curl_socklen_t fromaddrlen;
382 #if defined(HAVE_IOCTLSOCKET)
383 (void) ioctlsocket(f, FIONREAD, &i);
385 (void) ioctl(f, FIONREAD, &i);
389 fromaddrlen = sizeof(fromaddr);
390 (void)recvfrom(f, rbuf, sizeof(rbuf), 0,
391 (struct sockaddr *)&fromaddr, &fromaddrlen);
399 #if defined(HAVE_ALARM) && defined(SIGALRM)
401 * Like signal(), but with well-defined semantics.
403 static void mysignal(int sig, void (*handler)(int))
406 memset(&sa, 0, sizeof(sa));
407 sa.sa_handler = handler;
408 sigaction(sig, &sa, NULL);
412 #ifndef DEFAULT_LOGFILE
413 #define DEFAULT_LOGFILE "log/tftpd.log"
416 #define DEFAULT_PORT 8999 /* UDP */
417 const char *serverlogfile = DEFAULT_LOGFILE;
419 #define REQUEST_DUMP "log/server.input"
422 int main(int argc, char **argv)
424 struct sockaddr_in me;
426 struct sockaddr_in6 me6;
427 #endif /* ENABLE_IPV6 */
432 char *pidname= (char *)".tftpd.pid";
433 unsigned short port = DEFAULT_PORT;
437 struct testcase test;
441 if(!strcmp("--version", argv[arg])) {
442 printf("tftpd IPv4%s\n",
451 else if(!strcmp("--pidfile", argv[arg])) {
454 pidname = argv[arg++];
456 else if(!strcmp("--ipv6", argv[arg])) {
466 port = (unsigned short)atoi(argv[arg++]);
475 atexit(win32_cleanup);
481 sock = socket(AF_INET, SOCK_DGRAM, 0);
484 sock = socket(AF_INET6, SOCK_DGRAM, 0);
487 if(CURL_SOCKET_BAD == sock) {
488 perror("opening stream socket");
489 logmsg("Error opening socket");
495 (sock, SOL_SOCKET, SO_REUSEADDR, (const void *) &flag,
497 perror("setsockopt(SO_REUSEADDR)");
503 me.sin_family = AF_INET;
504 me.sin_addr.s_addr = INADDR_ANY;
505 me.sin_port = htons(port);
506 rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
510 memset(&me6, 0, sizeof(struct sockaddr_in6));
511 me6.sin6_family = AF_INET6;
512 me6.sin6_addr = in6addr_any;
513 me6.sin6_port = htons(port);
514 rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
516 #endif /* ENABLE_IPV6 */
518 perror("binding stream socket");
519 logmsg("Error binding socket");
524 if(!write_pidfile(pidname)) {
529 logmsg("Running %s version on port UDP/%d", ipv_inuse, (int)port);
532 fromlen = sizeof(from);
533 n = (ssize_t)recvfrom(sock, buf, sizeof(buf), 0,
534 (struct sockaddr *)&from, &fromlen);
541 set_advisor_read_lock(SERVERLOGS_LOCK);
543 from.sin_family = AF_INET;
545 peer = socket(AF_INET, SOCK_DGRAM, 0);
546 if(CURL_SOCKET_BAD == peer) {
552 if (connect(peer, (struct sockaddr *)&from, sizeof(from)) < 0) {
553 logmsg("connect: fail");
557 maxtimeout = 5*TIMEOUT;
559 tp = (struct tftphdr *)buf;
560 tp->th_opcode = ntohs(tp->th_opcode);
561 if (tp->th_opcode == opcode_RRQ || tp->th_opcode == opcode_WRQ) {
562 memset(&test, 0, sizeof(test));
563 if (tftp(&test, tp, n) < 0)
570 clear_advisor_read_lock(SERVERLOGS_LOCK);
572 logmsg("end of one transfer");
576 clear_advisor_read_lock(SERVERLOGS_LOCK);
582 * Handle initial connection protocol.
584 static int tftp(struct testcase *test, struct tftphdr *tp, ssize_t size)
587 int first = 1, ecode;
589 char *filename, *mode = NULL;
593 /* Open request dump file. */
594 server = fopen(REQUEST_DUMP, "ab");
597 logmsg("fopen() failed with error: %d %s", error, strerror(error));
598 logmsg("Error opening file: %s", REQUEST_DUMP);
602 /* store input protocol */
603 fprintf(server, "opcode: %x\n", tp->th_opcode);
605 cp = (char *)&tp->th_stuff;
608 while (cp < buf + size) {
623 /* store input protocol */
624 fprintf(server, "filename: %s\n", filename);
626 for (cp = mode; cp && *cp; cp++)
628 *cp = (char)tolower((int)*cp);
630 /* store input protocol */
631 fprintf(server, "mode: %s\n", mode);
634 for (pf = formata; pf->f_mode; pf++)
635 if (strcmp(pf->f_mode, mode) == 0)
641 ecode = validate_access(test, filename, tp->th_opcode);
646 if (tp->th_opcode == opcode_WRQ)
655 * Validate file access.
657 static int validate_access(struct testcase *test,
658 const char *filename, int mode)
663 char partbuf[80]="data";
665 logmsg("trying to get file: %s mode %x", filename, mode);
667 if(!strncmp("verifiedserver", filename, 14)) {
669 size_t count = sprintf(weare, "WE ROOLZ: %ld\r\n", (long)getpid());
671 logmsg("Are-we-friendly question received");
672 test->buffer = strdup(weare);
673 test->rptr = test->buffer; /* set read pointer */
674 test->bufsize = count; /* set total count */
675 test->rcount = count; /* set data left to read */
679 /* find the last slash */
680 ptr = strrchr(filename, '/');
685 ptr++; /* skip the slash */
687 /* skip all non-numericals following the slash */
688 while(*ptr && !ISDIGIT(*ptr))
692 testno = strtol(ptr, &ptr, 10);
695 partno = testno % 10000;
702 logmsg("requested test number %ld part %ld", testno, partno);
706 file = test2file(testno);
709 sprintf(partbuf, "data%ld", partno);
712 FILE *stream=fopen(file, "rb");
715 logmsg("fopen() failed with error: %d %s", error, strerror(error));
716 logmsg("Error opening file: %s", file);
717 logmsg("Couldn't open test file: %s", file);
722 test->buffer = (char *)spitout(stream, "reply", partbuf, &count);
725 test->rptr = test->buffer; /* set read pointer */
726 test->bufsize = count; /* set total count */
727 test->rcount = count; /* set data left to read */
738 logmsg("no slash found in path");
739 return EACCESS; /* failure */
742 logmsg("file opened and all is good");
747 #ifdef HAVE_SIGSETJMP
748 static sigjmp_buf timeoutbuf;
751 #if defined(HAVE_ALARM) && defined(SIGALRM)
752 static int rexmtval = TIMEOUT;
754 static void timer(int signum)
761 if(timeout >= maxtimeout) {
762 clear_advisor_read_lock(SERVERLOGS_LOCK);
765 #ifdef HAVE_SIGSETJMP
766 siglongjmp(timeoutbuf, 1);
770 static void justtimeout(int signum)
774 #endif /* HAVE_ALARM && SIGALRM */
776 static unsigned short sendblock;
777 static struct tftphdr *sdp;
778 static struct tftphdr *sap; /* ack packet */
780 * Send the requested file.
782 static void sendtftp(struct testcase *test, struct formats *pf)
787 #if defined(HAVE_ALARM) && defined(SIGALRM)
788 mysignal(SIGALRM, timer);
791 sap = (struct tftphdr *)ackbuf;
793 size = readit(test, &sdp, pf->f_convert);
798 sdp->th_opcode = htons((u_short)opcode_DATA);
799 sdp->th_block = htons((u_short)sendblock);
801 #ifdef HAVE_SIGSETJMP
802 (void) sigsetjmp(timeoutbuf, 1);
805 if (swrite(peer, sdp, size + 4) != size + 4) {
809 read_ahead(test, pf->f_convert);
812 alarm(rexmtval); /* read the ack */
814 n = sread(peer, ackbuf, sizeof (ackbuf));
819 logmsg("read: fail");
822 sap->th_opcode = ntohs((u_short)sap->th_opcode);
823 sap->th_block = ntohs((u_short)sap->th_block);
825 if (sap->th_opcode == opcode_ERROR) {
830 if (sap->th_opcode == opcode_ACK) {
831 if (sap->th_block == sendblock) {
834 /* Re-synchronize with the other side */
835 (void) synchnet(peer);
836 if (sap->th_block == (sendblock-1)) {
843 } while (size == SEGSIZE);
847 static unsigned short recvblock;
848 static struct tftphdr *rdp;
849 static struct tftphdr *rap; /* ack buffer */
853 static void recvtftp(struct testcase *test, struct formats *pf)
857 #if defined(HAVE_ALARM) && defined(SIGALRM)
858 mysignal(SIGALRM, timer);
861 rap = (struct tftphdr *)ackbuf;
864 rap->th_opcode = htons((u_short)opcode_ACK);
865 rap->th_block = htons((u_short)recvblock);
867 #ifdef HAVE_SIGSETJMP
868 (void) sigsetjmp(timeoutbuf, 1);
871 if (swrite(peer, ackbuf, 4) != 4) {
872 logmsg("write: fail\n");
875 write_behind(test, pf->f_convert);
880 n = sread(peer, rdp, PKTSIZE);
884 if (n < 0) { /* really? */
885 logmsg("read: fail\n");
888 rdp->th_opcode = ntohs((u_short)rdp->th_opcode);
889 rdp->th_block = ntohs((u_short)rdp->th_block);
890 if (rdp->th_opcode == opcode_ERROR)
892 if (rdp->th_opcode == opcode_DATA) {
893 if (rdp->th_block == recvblock) {
896 /* Re-synchronize with the other side */
897 (void) synchnet(peer);
898 if (rdp->th_block == (recvblock-1))
899 goto send_ack; /* rexmit */
903 size = writeit(test, &rdp, (int)(n - 4), pf->f_convert);
904 if (size != (n-4)) { /* ahem */
911 } while (size == SEGSIZE);
912 write_behind(test, pf->f_convert);
914 rap->th_opcode = htons((u_short)opcode_ACK); /* send the "final" ack */
915 rap->th_block = htons((u_short)recvblock);
916 (void) swrite(peer, ackbuf, 4);
917 #if defined(HAVE_ALARM) && defined(SIGALRM)
918 mysignal(SIGALRM, justtimeout); /* just abort read on timeout */
921 n = sread(peer, buf, sizeof(buf)); /* normally times out and quits */
925 if (n >= 4 && /* if read some data */
926 rdp->th_opcode == opcode_DATA && /* and got a data block */
927 recvblock == rdp->th_block) { /* then my last ack was lost */
928 (void) swrite(peer, ackbuf, 4); /* resend final ack */
938 static struct errmsg errmsgs[] = {
939 { EUNDEF, "Undefined error code" },
940 { ENOTFOUND, "File not found" },
941 { EACCESS, "Access violation" },
942 { ENOSPACE, "Disk full or allocation exceeded" },
943 { EBADOP, "Illegal TFTP operation" },
944 { EBADID, "Unknown transfer ID" },
945 { EEXISTS, "File already exists" },
946 { ENOUSER, "No such user" },
951 * Send a nak packet (error message). Error code passed in is one of the
952 * standard TFTP codes, or a UNIX errno offset by 100.
954 static void nak(int error)
960 tp = (struct tftphdr *)buf;
961 tp->th_opcode = htons((u_short)opcode_ERROR);
962 tp->th_code = htons((u_short)error);
963 for (pe = errmsgs; pe->e_code >= 0; pe++)
964 if (pe->e_code == error)
966 if (pe->e_code < 0) {
967 pe->e_msg = strerror(error - 100);
968 tp->th_code = EUNDEF; /* set 'undef' errorcode */
970 strcpy(tp->th_msg, pe->e_msg);
971 length = (int)strlen(pe->e_msg);
972 tp->th_msg[length] = '\0';
974 if (swrite(peer, buf, length) != length)
975 logmsg("nak: fail\n");