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_TFTP_H
69 #include <arpa/tftp.h>
76 #ifdef HAVE_SYS_FILIO_H
77 /* FIONREAD on Solaris 7 */
78 #include <sys/filio.h>
89 #define ENABLE_CURLX_PRINTF
90 /* make the curlx header define all printf() functions to use the curlx_*
92 #include "curlx.h" /* from the private lib dir */
96 /* include memdebug.h last */
100 static bool use_ipv6 = FALSE;
102 static const char *ipv_inuse = "IPv4";
105 char *buffer; /* holds the file data to send to the client */
106 size_t bufsize; /* size of the data in buffer */
107 char *rptr; /* read pointer into the buffer */
108 size_t rcount; /* amount of data left to read of the file */
109 long num; /* test case number */
110 int ofile; /* file descriptor for output file when uploading to us */
113 static int synchnet(curl_socket_t);
114 static struct tftphdr *r_init(void);
115 static struct tftphdr *w_init(void);
116 static int readit(struct testcase *test, struct tftphdr **dpp, int convert);
117 static int writeit(struct testcase *test, struct tftphdr **dpp, int ct,
122 #define opcode_DATA 3
124 #define opcode_ERROR 5
128 #define PKTSIZE SEGSIZE+4
134 static struct formats formata[] = {
140 static int tftp(struct testcase *test, struct tftphdr *tp, ssize_t size);
141 static void nak(int error);
142 static void sendtftp(struct testcase *test, struct formats *pf);
143 static void recvtftp(struct testcase *test, struct formats *pf);
144 static int validate_access(struct testcase *test, const char *, int);
146 static curl_socket_t peer;
147 static int maxtimeout = 5*TIMEOUT;
149 static char buf[PKTSIZE];
150 static char ackbuf[PKTSIZE];
151 static struct sockaddr_in from;
152 static socklen_t fromlen;
155 int counter; /* size of data in buffer, or flag */
156 char buf[PKTSIZE]; /* room for data packet */
158 static struct bf bfs[2];
160 /* Values for bf.counter */
161 #define BF_ALLOC -3 /* alloc'd but not yet filled */
162 #define BF_FREE -2 /* free */
163 /* [-1 .. SEGSIZE] = size of data in the data buffer */
165 static int nextone; /* index of next buffer to use */
166 static int current; /* index of buffer in use */
168 /* control flags for crlf conversions */
169 static int newline = 0; /* fillbuf: in middle of newline expansion */
170 static int prevchar = -1; /* putbuf: previous char (cr check) */
172 static void read_ahead(struct testcase *test,
173 int convert /* if true, convert to ascii */);
174 static ssize_t write_behind(struct testcase *test, int convert);
175 static struct tftphdr *rw_init(int);
176 static struct tftphdr *w_init(void) { return rw_init(0); } /* write-behind */
177 static struct tftphdr *r_init(void) { return rw_init(1); } /* read-ahead */
179 static struct tftphdr *
180 rw_init(int x) /* init for either read-ahead or write-behind */
181 { /* zero for write-behind, one for read-head */
182 newline = 0; /* init crlf flag */
184 bfs[0].counter = BF_ALLOC; /* pass out the first buffer */
186 bfs[1].counter = BF_FREE;
187 nextone = x; /* ahead or behind? */
188 return (struct tftphdr *)bfs[0].buf;
192 /* Have emptied current buffer by sending to net and getting ack.
193 Free it and return next buffer filled with data.
195 static int readit(struct testcase *test, struct tftphdr **dpp,
196 int convert /* if true, convert to ascii */)
200 bfs[current].counter = BF_FREE; /* free old one */
201 current = !current; /* "incr" current */
203 b = &bfs[current]; /* look at new buffer */
204 if (b->counter == BF_FREE) /* if it's empty */
205 read_ahead(test, convert); /* fill it */
207 *dpp = (struct tftphdr *)b->buf; /* set caller's ptr */
211 #undef MIN /* some systems have this defined already, some don't */
212 #define MIN(x,y) ((x)<(y)?(x):(y));
215 * fill the input buffer, doing ascii conversions if requested
216 * conversions are lf -> cr,lf and cr -> cr, nul
218 static void read_ahead(struct testcase *test,
219 int convert /* if true, convert to ascii */)
227 b = &bfs[nextone]; /* look at "next" buffer */
228 if (b->counter != BF_FREE) /* nop if not free */
230 nextone = !nextone; /* "incr" next buffer ptr */
232 dp = (struct tftphdr *)b->buf;
235 /* The former file reading code did this:
236 b->counter = read(fileno(file), dp->th_data, SEGSIZE); */
237 size_t copy_n = MIN(SEGSIZE, test->rcount);
238 memcpy(dp->th_data, test->rptr, copy_n);
240 /* decrease amount, advance pointer */
241 test->rcount -= copy_n;
242 test->rptr += copy_n;
243 b->counter = (int)copy_n;
248 for (i = 0 ; i < SEGSIZE; i++) {
250 if (prevchar == '\n')
251 c = '\n'; /* lf to cr,lf */
253 c = '\0'; /* cr to cr,nul */
264 if (c == '\n' || c == '\r') {
272 b->counter = (int)(p - dp->th_data);
275 /* Update count associated with the buffer, get new buffer from the queue.
276 Calls write_behind only if next buffer not available.
278 static int writeit(struct testcase *test, struct tftphdr **dpp,
281 bfs[current].counter = ct; /* set size of data to write */
282 current = !current; /* switch to other buffer */
283 if (bfs[current].counter != BF_FREE) /* if not free */
284 write_behind(test, convert); /* flush it */
285 bfs[current].counter = BF_ALLOC; /* mark as alloc'd */
286 *dpp = (struct tftphdr *)bfs[current].buf;
287 return ct; /* this is a lie of course */
291 * Output a buffer to a file, converting from netascii if requested.
292 * CR,NUL -> CR and CR,LF => LF.
293 * Note spec is undefined if we get CR as last byte of file or a
294 * CR followed by anything else. In this case we leave it alone.
296 static ssize_t write_behind(struct testcase *test, int convert)
302 int c; /* current character */
307 if (b->counter < -1) /* anything to flush? */
308 return 0; /* just nop if nothing to do */
312 snprintf(outfile, sizeof(outfile), "log/upload.%ld", test->num);
313 test->ofile=open(outfile, O_CREAT|O_RDWR, 0777);
314 if(test->ofile == -1) {
315 logmsg("Couldn't create and/or open file %s for upload!", outfile);
316 return -1; /* failure! */
320 count = b->counter; /* remember byte count */
321 b->counter = BF_FREE; /* reset flag */
322 dp = (struct tftphdr *)b->buf;
323 nextone = !nextone; /* incr for next time */
324 writebuf = dp->th_data;
327 return -1; /* nak logic? */
330 return write(test->ofile, writebuf, count);
334 while (ct--) { /* loop over the buffer */
335 c = *p++; /* pick up a character */
336 if (prevchar == '\r') { /* if prev char was cr */
337 if (c == '\n') /* if have cr,lf then just */
338 lseek(test->ofile, -1, SEEK_CUR); /* smash lf on top of the cr */
340 if (c == '\0') /* if have cr,nul then */
341 goto skipit; /* just skip over the putc */
342 /* else just fall through and allow it */
346 write(test->ofile, &c, 1);
354 /* When an error has occurred, it is possible that the two sides are out of
355 * synch. Ie: that what I think is the other side's response to packet N is
356 * really their response to packet N-1.
358 * So, to try to prevent that, we flush all the input queued up for us on the
359 * network connection on our host.
361 * We return the number of packets we flushed (mostly for reporting when trace
365 static int synchnet(curl_socket_t f /* socket to flush */)
368 #if defined(HAVE_IOCTLSOCKET)
375 struct sockaddr_in fromaddr;
376 socklen_t fromaddrlen;
379 #if defined(HAVE_IOCTLSOCKET)
380 (void) ioctlsocket(f, FIONREAD, &i);
382 (void) ioctl(f, FIONREAD, &i);
386 fromaddrlen = sizeof(fromaddr);
387 (void)recvfrom(f, rbuf, sizeof(rbuf), 0,
388 (struct sockaddr *)&fromaddr, &fromaddrlen);
396 #if defined(HAVE_ALARM) && defined(SIGALRM)
398 * Like signal(), but with well-defined semantics.
400 static void mysignal(int sig, void (*handler)(int))
403 memset(&sa, 0, sizeof(sa));
404 sa.sa_handler = handler;
405 sigaction(sig, &sa, NULL);
409 #ifndef DEFAULT_LOGFILE
410 #define DEFAULT_LOGFILE "log/tftpd.log"
413 #define DEFAULT_PORT 8999 /* UDP */
414 const char *serverlogfile = DEFAULT_LOGFILE;
416 #define REQUEST_DUMP "log/server.input"
419 int main(int argc, char **argv)
421 struct sockaddr_in me;
423 struct sockaddr_in6 me6;
424 #endif /* ENABLE_IPV6 */
429 char *pidname= (char *)".tftpd.pid";
430 unsigned short port = DEFAULT_PORT;
434 struct testcase test;
438 if(!strcmp("--version", argv[arg])) {
439 printf("tftpd IPv4%s\n",
448 else if(!strcmp("--pidfile", argv[arg])) {
451 pidname = argv[arg++];
453 else if(!strcmp("--ipv6", argv[arg])) {
463 port = (unsigned short)atoi(argv[arg++]);
472 atexit(win32_cleanup);
478 sock = socket(AF_INET, SOCK_DGRAM, 0);
481 sock = socket(AF_INET6, SOCK_DGRAM, 0);
485 perror("opening stream socket");
486 logmsg("Error opening socket");
492 (sock, SOL_SOCKET, SO_REUSEADDR, (const void *) &flag,
494 perror("setsockopt(SO_REUSEADDR)");
500 me.sin_family = AF_INET;
501 me.sin_addr.s_addr = INADDR_ANY;
502 me.sin_port = htons(port);
503 rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
507 memset(&me6, 0, sizeof(struct sockaddr_in6));
508 me6.sin6_family = AF_INET6;
509 me6.sin6_addr = in6addr_any;
510 me6.sin6_port = htons(port);
511 rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
513 #endif /* ENABLE_IPV6 */
515 perror("binding stream socket");
516 logmsg("Error binding socket");
521 if(!write_pidfile(pidname)) {
526 logmsg("Running %s version on port UDP/%d", ipv_inuse, (int)port);
529 fromlen = sizeof(from);
530 n = (ssize_t)recvfrom(sock, buf, sizeof(buf), 0,
531 (struct sockaddr *)&from, &fromlen);
533 logmsg("recvfrom:\n");
538 set_advisor_read_lock(SERVERLOGS_LOCK);
540 from.sin_family = AF_INET;
542 peer = socket(AF_INET, SOCK_DGRAM, 0);
549 if (connect(peer, (struct sockaddr *)&from, sizeof(from)) < 0) {
550 logmsg("connect: fail\n");
554 maxtimeout = 5*TIMEOUT;
556 tp = (struct tftphdr *)buf;
557 tp->th_opcode = ntohs(tp->th_opcode);
558 if (tp->th_opcode == opcode_RRQ || tp->th_opcode == opcode_WRQ) {
559 memset(&test, 0, sizeof(test));
560 if (tftp(&test, tp, n) < 0)
567 clear_advisor_read_lock(SERVERLOGS_LOCK);
571 clear_advisor_read_lock(SERVERLOGS_LOCK);
577 * Handle initial connection protocol.
579 static int tftp(struct testcase *test, struct tftphdr *tp, ssize_t size)
582 int first = 1, ecode;
584 char *filename, *mode = NULL;
588 /* Open request dump file. */
589 server = fopen(REQUEST_DUMP, "ab");
592 logmsg("fopen() failed with error: %d %s", error, strerror(error));
593 logmsg("Error opening file: %s", REQUEST_DUMP);
597 /* store input protocol */
598 fprintf(server, "opcode: %x\n", tp->th_opcode);
600 cp = (char *)&tp->th_stuff;
603 while (cp < buf + size) {
618 /* store input protocol */
619 fprintf(server, "filename: %s\n", filename);
621 for (cp = mode; *cp; cp++)
623 *cp = (char)tolower((int)*cp);
625 /* store input protocol */
626 fprintf(server, "mode: %s\n", mode);
629 for (pf = formata; pf->f_mode; pf++)
630 if (strcmp(pf->f_mode, mode) == 0)
636 ecode = validate_access(test, filename, tp->th_opcode);
641 if (tp->th_opcode == opcode_WRQ)
650 * Validate file access.
652 static int validate_access(struct testcase *test,
653 const char *filename, int mode)
658 char partbuf[80]="data";
660 logmsg("trying to get file: %s mode %x", filename, mode);
662 if(!strncmp("verifiedserver", filename, 14)) {
664 size_t count = sprintf(weare, "WE ROOLZ: %ld\r\n", (long)getpid());
666 logmsg("Are-we-friendly question received");
667 test->buffer = strdup(weare);
668 test->rptr = test->buffer; /* set read pointer */
669 test->bufsize = count; /* set total count */
670 test->rcount = count; /* set data left to read */
674 /* find the last slash */
675 ptr = strrchr(filename, '/');
680 ptr++; /* skip the slash */
682 /* skip all non-numericals following the slash */
683 while(*ptr && !ISDIGIT(*ptr))
687 testno = strtol(ptr, &ptr, 10);
690 partno = testno % 10000;
697 logmsg("requested test number %ld part %ld", testno, partno);
701 file = test2file(testno);
704 sprintf(partbuf, "data%ld", partno);
707 FILE *stream=fopen(file, "rb");
710 logmsg("fopen() failed with error: %d %s", error, strerror(error));
711 logmsg("Error opening file: %s", file);
712 logmsg("Couldn't open test file: %s", file);
717 test->buffer = (char *)spitout(stream, "reply", partbuf, &count);
720 test->rptr = test->buffer; /* set read pointer */
721 test->bufsize = count; /* set total count */
722 test->rcount = count; /* set data left to read */
733 logmsg("no slash found in path");
734 return EACCESS; /* failure */
741 #ifdef HAVE_SIGSETJMP
742 static sigjmp_buf timeoutbuf;
745 #if defined(HAVE_ALARM) && defined(SIGALRM)
746 static int rexmtval = TIMEOUT;
748 static void timer(int signum)
755 if(timeout >= maxtimeout) {
756 clear_advisor_read_lock(SERVERLOGS_LOCK);
759 #ifdef HAVE_SIGSETJMP
760 siglongjmp(timeoutbuf, 1);
764 static void (int signum)
768 #endif /* HAVE_ALARM && SIGALRM */
770 static unsigned short sendblock;
771 static struct tftphdr *sdp;
772 static struct tftphdr *sap; /* ack packet */
774 * Send the requested file.
776 static void sendtftp(struct testcase *test, struct formats *pf)
781 #if defined(HAVE_ALARM) && defined(SIGALRM)
782 mysignal(SIGALRM, timer);
785 sap = (struct tftphdr *)ackbuf;
787 size = readit(test, &sdp, pf->f_convert);
792 sdp->th_opcode = htons((u_short)opcode_DATA);
793 sdp->th_block = htons((u_short)sendblock);
795 #ifdef HAVE_SIGSETJMP
796 (void) sigsetjmp(timeoutbuf, 1);
799 if (swrite(peer, sdp, size + 4) != size + 4) {
803 read_ahead(test, pf->f_convert);
806 alarm(rexmtval); /* read the ack */
808 n = sread(peer, ackbuf, sizeof (ackbuf));
813 logmsg("read: fail\n");
816 sap->th_opcode = ntohs((u_short)sap->th_opcode);
817 sap->th_block = ntohs((u_short)sap->th_block);
819 if (sap->th_opcode == opcode_ERROR) {
824 if (sap->th_opcode == opcode_ACK) {
825 if (sap->th_block == sendblock) {
828 /* Re-synchronize with the other side */
829 (void) synchnet(peer);
830 if (sap->th_block == (sendblock-1)) {
837 } while (size == SEGSIZE);
841 static unsigned short recvblock;
842 static struct tftphdr *rdp;
843 static struct tftphdr *rap; /* ack buffer */
847 static void recvtftp(struct testcase *test, struct formats *pf)
851 #if defined(HAVE_ALARM) && defined(SIGALRM)
852 mysignal(SIGALRM, timer);
855 rap = (struct tftphdr *)ackbuf;
858 rap->th_opcode = htons((u_short)opcode_ACK);
859 rap->th_block = htons((u_short)recvblock);
861 #ifdef HAVE_SIGSETJMP
862 (void) sigsetjmp(timeoutbuf, 1);
865 if (swrite(peer, ackbuf, 4) != 4) {
866 logmsg("write: fail\n");
869 write_behind(test, pf->f_convert);
874 n = sread(peer, rdp, PKTSIZE);
878 if (n < 0) { /* really? */
879 logmsg("read: fail\n");
882 rdp->th_opcode = ntohs((u_short)rdp->th_opcode);
883 rdp->th_block = ntohs((u_short)rdp->th_block);
884 if (rdp->th_opcode == opcode_ERROR)
886 if (rdp->th_opcode == opcode_DATA) {
887 if (rdp->th_block == recvblock) {
890 /* Re-synchronize with the other side */
891 (void) synchnet(peer);
892 if (rdp->th_block == (recvblock-1))
893 goto send_ack; /* rexmit */
897 size = writeit(test, &rdp, (int)(n - 4), pf->f_convert);
898 if (size != (n-4)) { /* ahem */
905 } while (size == SEGSIZE);
906 write_behind(test, pf->f_convert);
908 rap->th_opcode = htons((u_short)opcode_ACK); /* send the "final" ack */
909 rap->th_block = htons((u_short)recvblock);
910 (void) swrite(peer, ackbuf, 4);
911 #if defined(HAVE_ALARM) && defined(SIGALRM)
912 mysignal(SIGALRM, justtimeout); /* just abort read on timeout */
915 n = sread(peer, buf, sizeof(buf)); /* normally times out and quits */
919 if (n >= 4 && /* if read some data */
920 rdp->th_opcode == opcode_DATA && /* and got a data block */
921 recvblock == rdp->th_block) { /* then my last ack was lost */
922 (void) swrite(peer, ackbuf, 4); /* resend final ack */
932 static struct errmsg errmsgs[] = {
933 { EUNDEF, "Undefined error code" },
934 { ENOTFOUND, "File not found" },
935 { EACCESS, "Access violation" },
936 { ENOSPACE, "Disk full or allocation exceeded" },
937 { EBADOP, "Illegal TFTP operation" },
938 { EBADID, "Unknown transfer ID" },
939 { EEXISTS, "File already exists" },
940 { ENOUSER, "No such user" },
945 * Send a nak packet (error message). Error code passed in is one of the
946 * standard TFTP codes, or a UNIX errno offset by 100.
948 static void nak(int error)
954 tp = (struct tftphdr *)buf;
955 tp->th_opcode = htons((u_short)opcode_ERROR);
956 tp->th_code = htons((u_short)error);
957 for (pe = errmsgs; pe->e_code >= 0; pe++)
958 if (pe->e_code == error)
960 if (pe->e_code < 0) {
961 pe->e_msg = strerror(error - 100);
962 tp->th_code = EUNDEF; /* set 'undef' errorcode */
964 strcpy(tp->th_msg, pe->e_msg);
965 length = (int)strlen(pe->e_msg);
966 tp->th_msg[length] = '\0';
968 if (swrite(peer, buf, length) != length)
969 logmsg("nak: fail\n");