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 char *buffer; /* holds the file data to send to the client */
101 size_t bufsize; /* size of the data in buffer */
102 char *rptr; /* read pointer into the buffer */
103 size_t rcount; /* amount of data left to read of the file */
104 long num; /* test case number */
105 int ofile; /* file descriptor for output file when uploading to us */
108 static int synchnet(curl_socket_t);
109 static struct tftphdr *r_init(void);
110 static struct tftphdr *w_init(void);
111 static int readit(struct testcase *test, struct tftphdr **dpp, int convert);
112 static int writeit(struct testcase *test, struct tftphdr **dpp, int ct,
114 static void mysignal(int, void (*func)(int));
119 #define PKTSIZE SEGSIZE+4
125 static struct formats formata[] = {
131 static int tftp(struct testcase *test, struct tftphdr *tp, ssize_t 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 */
150 static struct bf bfs[2];
152 /* Values for bf.counter */
153 #define BF_ALLOC -3 /* alloc'd but not yet filled */
154 #define BF_FREE -2 /* free */
155 /* [-1 .. SEGSIZE] = size of data in the data buffer */
157 static int nextone; /* index of next buffer to use */
158 static int current; /* index of buffer in use */
160 /* control flags for crlf conversions */
161 static int newline = 0; /* fillbuf: in middle of newline expansion */
162 static int prevchar = -1; /* putbuf: previous char (cr check) */
164 static void read_ahead(struct testcase *test,
165 int convert /* if true, convert to ascii */);
166 static ssize_t write_behind(struct testcase *test, int convert);
167 static struct tftphdr *rw_init(int);
168 static struct tftphdr *w_init(void) { return rw_init(0); } /* write-behind */
169 static struct tftphdr *r_init(void) { return rw_init(1); } /* read-ahead */
171 static struct tftphdr *
172 rw_init(int x) /* init for either read-ahead or write-behind */
173 { /* zero for write-behind, one for read-head */
174 newline = 0; /* init crlf flag */
176 bfs[0].counter = BF_ALLOC; /* pass out the first buffer */
178 bfs[1].counter = BF_FREE;
179 nextone = x; /* ahead or behind? */
180 return (struct tftphdr *)bfs[0].buf;
184 /* Have emptied current buffer by sending to net and getting ack.
185 Free it and return next buffer filled with data.
187 static int readit(struct testcase *test, struct tftphdr **dpp,
188 int convert /* if true, convert to ascii */)
192 bfs[current].counter = BF_FREE; /* free old one */
193 current = !current; /* "incr" current */
195 b = &bfs[current]; /* look at new buffer */
196 if (b->counter == BF_FREE) /* if it's empty */
197 read_ahead(test, convert); /* fill it */
199 *dpp = (struct tftphdr *)b->buf; /* set caller's ptr */
203 #undef MIN /* some systems have this defined already, some don't */
204 #define MIN(x,y) ((x)<(y)?(x):(y));
207 * fill the input buffer, doing ascii conversions if requested
208 * conversions are lf -> cr,lf and cr -> cr, nul
210 static void read_ahead(struct testcase *test,
211 int convert /* if true, convert to ascii */)
219 b = &bfs[nextone]; /* look at "next" buffer */
220 if (b->counter != BF_FREE) /* nop if not free */
222 nextone = !nextone; /* "incr" next buffer ptr */
224 dp = (struct tftphdr *)b->buf;
227 /* The former file reading code did this:
228 b->counter = read(fileno(file), dp->th_data, SEGSIZE); */
229 size_t copy_n = MIN(SEGSIZE, test->rcount);
230 memcpy(dp->th_data, test->rptr, copy_n);
232 /* decrease amount, advance pointer */
233 test->rcount -= copy_n;
234 test->rptr += copy_n;
235 b->counter = (int)copy_n;
240 for (i = 0 ; i < SEGSIZE; i++) {
242 if (prevchar == '\n')
243 c = '\n'; /* lf to cr,lf */
245 c = '\0'; /* cr to cr,nul */
256 if (c == '\n' || c == '\r') {
264 b->counter = (int)(p - dp->th_data);
267 /* Update count associated with the buffer, get new buffer from the queue.
268 Calls write_behind only if next buffer not available.
270 static int writeit(struct testcase *test, struct tftphdr **dpp,
273 bfs[current].counter = ct; /* set size of data to write */
274 current = !current; /* switch to other buffer */
275 if (bfs[current].counter != BF_FREE) /* if not free */
276 write_behind(test, convert); /* flush it */
277 bfs[current].counter = BF_ALLOC; /* mark as alloc'd */
278 *dpp = (struct tftphdr *)bfs[current].buf;
279 return ct; /* this is a lie of course */
283 * Output a buffer to a file, converting from netascii if requested.
284 * CR,NUL -> CR and CR,LF => LF.
285 * Note spec is undefined if we get CR as last byte of file or a
286 * CR followed by anything else. In this case we leave it alone.
288 static ssize_t write_behind(struct testcase *test, int convert)
294 int c; /* current character */
299 if (b->counter < -1) /* anything to flush? */
300 return 0; /* just nop if nothing to do */
304 snprintf(outfile, sizeof(outfile), "log/upload.%ld", test->num);
305 test->ofile=open(outfile, O_CREAT|O_RDWR, 0777);
306 if(test->ofile == -1) {
307 logmsg("Couldn't create and/or open file %s for upload!", outfile);
308 return -1; /* failure! */
312 count = b->counter; /* remember byte count */
313 b->counter = BF_FREE; /* reset flag */
314 dp = (struct tftphdr *)b->buf;
315 nextone = !nextone; /* incr for next time */
316 writebuf = dp->th_data;
319 return -1; /* nak logic? */
322 return write(test->ofile, writebuf, count);
326 while (ct--) { /* loop over the buffer */
327 c = *p++; /* pick up a character */
328 if (prevchar == '\r') { /* if prev char was cr */
329 if (c == '\n') /* if have cr,lf then just */
330 lseek(test->ofile, -1, SEEK_CUR); /* smash lf on top of the cr */
332 if (c == '\0') /* if have cr,nul then */
333 goto skipit; /* just skip over the putc */
334 /* else just fall through and allow it */
338 write(test->ofile, &c, 1);
346 /* When an error has occurred, it is possible that the two sides are out of
347 * synch. Ie: that what I think is the other side's response to packet N is
348 * really their response to packet N-1.
350 * So, to try to prevent that, we flush all the input queued up for us on the
351 * network connection on our host.
353 * We return the number of packets we flushed (mostly for reporting when trace
357 static int synchnet(curl_socket_t f /* socket to flush */)
360 #if defined(HAVE_IOCTLSOCKET)
367 struct sockaddr_in fromaddr;
368 socklen_t fromaddrlen;
371 #if defined(HAVE_IOCTLSOCKET)
372 (void) ioctlsocket(f, FIONREAD, &i);
374 (void) ioctl(f, FIONREAD, &i);
378 fromaddrlen = sizeof(fromaddr);
379 (void)recvfrom(f, rbuf, sizeof(rbuf), 0,
380 (struct sockaddr *)&fromaddr, &fromaddrlen);
388 #if defined(HAVE_ALARM) && defined(SIGALRM)
390 * Like signal(), but with well-defined semantics.
392 static void mysignal(int sig, void (*handler)(int))
395 memset(&sa, 0, sizeof(sa));
396 sa.sa_handler = handler;
397 sigaction(sig, &sa, NULL);
401 #ifndef DEFAULT_LOGFILE
402 #define DEFAULT_LOGFILE "log/tftpd.log"
405 #define DEFAULT_PORT 8999 /* UDP */
406 const char *serverlogfile = DEFAULT_LOGFILE;
408 #define REQUEST_DUMP "log/server.input"
410 static char use_ipv6=FALSE;
412 int main(int argc, char **argv)
414 struct sockaddr_in me;
416 struct sockaddr_in6 me6;
417 #endif /* ENABLE_IPV6 */
422 char *pidname= (char *)".tftpd.pid";
423 unsigned short port = DEFAULT_PORT;
427 struct testcase test;
431 if(!strcmp("--version", argv[arg])) {
432 printf("tftpd IPv4%s\n",
441 else if(!strcmp("--pidfile", argv[arg])) {
444 pidname = argv[arg++];
446 else if(!strcmp("--ipv6", argv[arg])) {
455 port = (unsigned short)atoi(argv[arg++]);
464 atexit(win32_cleanup);
470 sock = socket(AF_INET, SOCK_DGRAM, 0);
473 sock = socket(AF_INET6, SOCK_DGRAM, 0);
477 perror("opening stream socket");
478 logmsg("Error opening socket");
484 (sock, SOL_SOCKET, SO_REUSEADDR, (const void *) &flag,
486 perror("setsockopt(SO_REUSEADDR)");
492 me.sin_family = AF_INET;
493 me.sin_addr.s_addr = INADDR_ANY;
494 me.sin_port = htons(port);
495 rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
499 memset(&me6, 0, sizeof(struct sockaddr_in6));
500 me6.sin6_family = AF_INET6;
501 me6.sin6_addr = in6addr_any;
502 me6.sin6_port = htons(port);
503 rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
505 #endif /* ENABLE_IPV6 */
507 perror("binding stream socket");
508 logmsg("Error binding socket");
513 if(!write_pidfile(pidname)) {
518 logmsg("Running IPv%d version on port UDP/%hu",
527 fromlen = sizeof(from);
528 n = (ssize_t)recvfrom(sock, buf, sizeof(buf), 0,
529 (struct sockaddr *)&from, &fromlen);
531 logmsg("recvfrom:\n");
536 set_advisor_read_lock(SERVERLOGS_LOCK);
538 from.sin_family = AF_INET;
540 peer = socket(AF_INET, SOCK_DGRAM, 0);
547 if (connect(peer, (struct sockaddr *)&from, sizeof(from)) < 0) {
548 logmsg("connect: fail\n");
552 maxtimeout = 5*TIMEOUT;
554 tp = (struct tftphdr *)buf;
555 tp->th_opcode = ntohs(tp->th_opcode);
556 if (tp->th_opcode == RRQ || tp->th_opcode == WRQ) {
557 memset(&test, 0, sizeof(test));
558 if (tftp(&test, tp, n) < 0)
565 clear_advisor_read_lock(SERVERLOGS_LOCK);
569 clear_advisor_read_lock(SERVERLOGS_LOCK);
575 * Handle initial connection protocol.
577 static int tftp(struct testcase *test, struct tftphdr *tp, ssize_t size)
580 int first = 1, ecode;
582 char *filename, *mode = NULL;
586 /* Open request dump file. */
587 server = fopen(REQUEST_DUMP, "ab");
590 logmsg("fopen() failed with error: %d %s", error, strerror(error));
591 logmsg("Error opening file: %s", REQUEST_DUMP);
595 /* store input protocol */
596 fprintf(server, "opcode: %x\n", tp->th_opcode);
598 cp = (char *)&tp->th_stuff;
601 while (cp < buf + size) {
616 /* store input protocol */
617 fprintf(server, "filename: %s\n", filename);
619 for (cp = mode; *cp; cp++)
621 *cp = (char)tolower((int)*cp);
623 /* store input protocol */
624 fprintf(server, "mode: %s\n", mode);
627 for (pf = formata; pf->f_mode; pf++)
628 if (strcmp(pf->f_mode, mode) == 0)
634 ecode = validate_access(test, filename, tp->th_opcode);
639 if (tp->th_opcode == WRQ)
648 * Validate file access.
650 static int validate_access(struct testcase *test,
651 const char *filename, int mode)
656 char partbuf[80]="data";
658 logmsg("trying to get file: %s mode %x", filename, mode);
660 if(!strncmp("verifiedserver", filename, 14)) {
662 size_t count = sprintf(weare, "WE ROOLZ: %ld\r\n", (long)getpid());
664 logmsg("Are-we-friendly question received");
665 test->buffer = strdup(weare);
666 test->rptr = test->buffer; /* set read pointer */
667 test->bufsize = count; /* set total count */
668 test->rcount = count; /* set data left to read */
672 /* find the last slash */
673 ptr = strrchr(filename, '/');
678 ptr++; /* skip the slash */
680 /* skip all non-numericals following the slash */
681 while(*ptr && !ISDIGIT(*ptr))
685 testno = strtol(ptr, &ptr, 10);
688 partno = testno % 10000;
695 logmsg("requested test number %ld part %ld", testno, partno);
699 file = test2file(testno);
702 sprintf(partbuf, "data%ld", partno);
705 FILE *stream=fopen(file, "rb");
708 logmsg("fopen() failed with error: %d %s", error, strerror(error));
709 logmsg("Error opening file: %s", file);
710 logmsg("Couldn't open test file: %s", file);
715 test->buffer = (char *)spitout(stream, "reply", partbuf, &count);
718 test->rptr = test->buffer; /* set read pointer */
719 test->bufsize = count; /* set total count */
720 test->rcount = count; /* set data left to read */
731 logmsg("no slash found in path");
732 return EACCESS; /* failure */
739 #ifdef HAVE_SIGSETJMP
740 static sigjmp_buf timeoutbuf;
743 static void timer(int signum)
750 if(timeout >= maxtimeout) {
751 clear_advisor_read_lock(SERVERLOGS_LOCK);
754 #ifdef HAVE_SIGSETJMP
755 siglongjmp(timeoutbuf, 1);
760 * Send the requested file.
762 static void sendtftp(struct testcase *test, struct formats *pf)
765 struct tftphdr *ap; /* ack packet */
766 unsigned short block = 1;
769 #if defined(HAVE_ALARM) && defined(SIGALRM)
770 mysignal(SIGALRM, timer);
773 ap = (struct tftphdr *)ackbuf;
775 size = readit(test, &dp, pf->f_convert);
780 dp->th_opcode = htons((u_short)DATA);
781 dp->th_block = htons((u_short)block);
783 #ifdef HAVE_SIGSETJMP
784 (void) sigsetjmp(timeoutbuf, 1);
787 if (swrite(peer, dp, size + 4) != size + 4) {
791 read_ahead(test, pf->f_convert);
794 alarm(rexmtval); /* read the ack */
796 n = sread(peer, ackbuf, sizeof (ackbuf));
801 logmsg("read: fail\n");
804 ap->th_opcode = ntohs((u_short)ap->th_opcode);
805 ap->th_block = ntohs((u_short)ap->th_block);
807 if (ap->th_opcode == ERROR) {
812 if (ap->th_opcode == ACK) {
813 if (ap->th_block == block) {
816 /* Re-synchronize with the other side */
817 (void) synchnet(peer);
818 if (ap->th_block == (block -1)) {
825 } while (size == SEGSIZE);
828 static void justtimeout(int signum)
837 static void recvtftp(struct testcase *test, struct formats *pf)
840 struct tftphdr *ap; /* ack buffer */
841 unsigned short block = 0;
843 #if defined(HAVE_ALARM) && defined(SIGALRM)
844 mysignal(SIGALRM, timer);
847 ap = (struct tftphdr *)ackbuf;
850 ap->th_opcode = htons((u_short)ACK);
851 ap->th_block = htons((u_short)block);
853 #ifdef HAVE_SIGSETJMP
854 (void) sigsetjmp(timeoutbuf, 1);
857 if (swrite(peer, ackbuf, 4) != 4) {
858 logmsg("write: fail\n");
861 write_behind(test, pf->f_convert);
866 n = sread(peer, dp, PKTSIZE);
870 if (n < 0) { /* really? */
871 logmsg("read: fail\n");
874 dp->th_opcode = ntohs((u_short)dp->th_opcode);
875 dp->th_block = ntohs((u_short)dp->th_block);
876 if (dp->th_opcode == ERROR)
878 if (dp->th_opcode == DATA) {
879 if (dp->th_block == block) {
882 /* Re-synchronize with the other side */
883 (void) synchnet(peer);
884 if (dp->th_block == (block-1))
885 goto send_ack; /* rexmit */
889 size = writeit(test, &dp, (int)(n - 4), pf->f_convert);
890 if (size != (n-4)) { /* ahem */
897 } while (size == SEGSIZE);
898 write_behind(test, pf->f_convert);
900 ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */
901 ap->th_block = htons((u_short)(block));
902 (void) swrite(peer, ackbuf, 4);
903 #if defined(HAVE_ALARM) && defined(SIGALRM)
904 mysignal(SIGALRM, justtimeout); /* just abort read on timeout */
907 n = sread(peer, buf, sizeof(buf)); /* normally times out and quits */
911 if (n >= 4 && /* if read some data */
912 dp->th_opcode == DATA && /* and got a data block */
913 block == dp->th_block) { /* then my last ack was lost */
914 (void) swrite(peer, ackbuf, 4); /* resend final ack */
924 static struct errmsg errmsgs[] = {
925 { EUNDEF, "Undefined error code" },
926 { ENOTFOUND, "File not found" },
927 { EACCESS, "Access violation" },
928 { ENOSPACE, "Disk full or allocation exceeded" },
929 { EBADOP, "Illegal TFTP operation" },
930 { EBADID, "Unknown transfer ID" },
931 { EEXISTS, "File already exists" },
932 { ENOUSER, "No such user" },
937 * Send a nak packet (error message). Error code passed in is one of the
938 * standard TFTP codes, or a UNIX errno offset by 100.
940 static void nak(int error)
946 tp = (struct tftphdr *)buf;
947 tp->th_opcode = htons((u_short)ERROR);
948 tp->th_code = htons((u_short)error);
949 for (pe = errmsgs; pe->e_code >= 0; pe++)
950 if (pe->e_code == error)
952 if (pe->e_code < 0) {
953 pe->e_msg = strerror(error - 100);
954 tp->th_code = EUNDEF; /* set 'undef' errorcode */
956 strcpy(tp->th_msg, pe->e_msg);
957 length = (int)strlen(pe->e_msg);
958 tp->th_msg[length] = '\0';
960 if (swrite(peer, buf, length) != length)
961 logmsg("nak: fail\n");