1
/***************************************************************************
3
* Project ___| | | | _ \| |
5
* | (__| |_| | _ <| |___
6
* \___|\___/|_| \_\_____|
8
* $Id: tftpd.c,v 1.10 2005/12/06 07:47:37 bagder Exp $
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>
79
#ifdef HAVE_SYS_FILIO_H
80
/* FIONREAD on Solaris 7 */
81
#include <sys/filio.h>
94
#define ENABLE_CURLX_PRINTF
95
/* make the curlx header define all printf() functions to use the curlx_*
97
#include "curlx.h" /* from the private lib dir */
101
/* include memdebug.h last */
102
#include "memdebug.h"
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 */
111
FILE *server; /* write input "protocol" there for client verification */
114
static int synchnet(int);
115
static struct tftphdr *r_init(void);
116
static struct tftphdr *w_init(void);
117
static int readit(struct testcase *test, struct tftphdr **dpp, int convert);
118
static int writeit(struct testcase *test, struct tftphdr **dpp, int ct,
120
static void mysignal(int, void (*func)(int));
125
#define PKTSIZE SEGSIZE+4
128
static int tftp(struct testcase *test, struct tftphdr *tp, int size);
129
static void nak(int error);
130
static void sendtftp(struct testcase *test, struct formats *pf);
131
static void recvtftp(struct testcase *test, struct formats *pf);
132
static int validate_access(struct testcase *test, const char *, int);
134
static curl_socket_t peer;
135
static int rexmtval = TIMEOUT;
136
static int maxtimeout = 5*TIMEOUT;
138
static char buf[PKTSIZE];
139
static char ackbuf[PKTSIZE];
140
static struct sockaddr_in from;
141
static socklen_t fromlen;
144
int counter; /* size of data in buffer, or flag */
145
char buf[PKTSIZE]; /* room for data packet */
148
/* Values for bf.counter */
149
#define BF_ALLOC -3 /* alloc'd but not yet filled */
150
#define BF_FREE -2 /* free */
151
/* [-1 .. SEGSIZE] = size of data in the data buffer */
153
static int nextone; /* index of next buffer to use */
154
static int current; /* index of buffer in use */
156
/* control flags for crlf conversions */
157
int newline = 0; /* fillbuf: in middle of newline expansion */
158
int prevchar = -1; /* putbuf: previous char (cr check) */
160
static void read_ahead(struct testcase *test,
161
int convert /* if true, convert to ascii */);
162
static int write_behind(struct testcase *test, int convert);
163
static struct tftphdr *rw_init(int);
164
static struct tftphdr *w_init(void) { return rw_init(0); } /* write-behind */
165
static struct tftphdr *r_init(void) { return rw_init(1); } /* read-ahead */
167
static struct tftphdr *
168
rw_init(int x) /* init for either read-ahead or write-behind */
169
{ /* zero for write-behind, one for read-head */
170
newline = 0; /* init crlf flag */
172
bfs[0].counter = BF_ALLOC; /* pass out the first buffer */
174
bfs[1].counter = BF_FREE;
175
nextone = x; /* ahead or behind? */
176
return (struct tftphdr *)bfs[0].buf;
180
/* Have emptied current buffer by sending to net and getting ack.
181
Free it and return next buffer filled with data.
183
static int readit(struct testcase *test, struct tftphdr **dpp,
184
int convert /* if true, convert to ascii */)
188
bfs[current].counter = BF_FREE; /* free old one */
189
current = !current; /* "incr" current */
191
b = &bfs[current]; /* look at new buffer */
192
if (b->counter == BF_FREE) /* if it's empty */
193
read_ahead(test, convert); /* fill it */
195
*dpp = (struct tftphdr *)b->buf; /* set caller's ptr */
199
#undef MIN /* some systems have this defined already, some don't */
200
#define MIN(x,y) ((x)<(y)?(x):(y));
203
* fill the input buffer, doing ascii conversions if requested
204
* conversions are lf -> cr,lf and cr -> cr, nul
206
static void read_ahead(struct testcase *test,
207
int convert /* if true, convert to ascii */)
215
b = &bfs[nextone]; /* look at "next" buffer */
216
if (b->counter != BF_FREE) /* nop if not free */
218
nextone = !nextone; /* "incr" next buffer ptr */
220
dp = (struct tftphdr *)b->buf;
223
/* The former file reading code did this:
224
b->counter = read(fileno(file), dp->th_data, SEGSIZE); */
225
size_t copy_n = MIN(SEGSIZE, test->rcount);
226
memcpy(dp->th_data, test->rptr, copy_n);
228
/* decrease amount, advance pointer */
229
test->rcount -= copy_n;
230
test->rptr += copy_n;
231
b->counter = (int)copy_n;
236
for (i = 0 ; i < SEGSIZE; i++) {
238
if (prevchar == '\n')
239
c = '\n'; /* lf to cr,lf */
241
c = '\0'; /* cr to cr,nul */
252
if (c == '\n' || c == '\r') {
260
b->counter = (int)(p - dp->th_data);
263
/* Update count associated with the buffer, get new buffer from the queue.
264
Calls write_behind only if next buffer not available.
266
static int writeit(struct testcase *test, struct tftphdr **dpp,
269
bfs[current].counter = ct; /* set size of data to write */
270
current = !current; /* switch to other buffer */
271
if (bfs[current].counter != BF_FREE) /* if not free */
272
write_behind(test, convert); /* flush it */
273
bfs[current].counter = BF_ALLOC; /* mark as alloc'd */
274
*dpp = (struct tftphdr *)bfs[current].buf;
275
return ct; /* this is a lie of course */
279
* Output a buffer to a file, converting from netascii if requested.
280
* CR,NUL -> CR and CR,LF => LF.
281
* Note spec is undefined if we get CR as last byte of file or a
282
* CR followed by anything else. In this case we leave it alone.
284
static int write_behind(struct testcase *test, int convert)
290
int c; /* current character */
295
if (b->counter < -1) /* anything to flush? */
296
return 0; /* just nop if nothing to do */
300
snprintf(outfile, sizeof(outfile), "log/upload.%ld", test->num);
301
test->ofile=open(outfile, O_CREAT|O_RDWR, 0777);
302
if(test->ofile == -1) {
303
logmsg("Couldn't create and/or open file %s for upload!", outfile);
304
return -1; /* failure! */
308
count = b->counter; /* remember byte count */
309
b->counter = BF_FREE; /* reset flag */
310
dp = (struct tftphdr *)b->buf;
311
nextone = !nextone; /* incr for next time */
315
return -1; /* nak logic? */
318
return write(test->ofile, buf, count);
322
while (ct--) { /* loop over the buffer */
323
c = *p++; /* pick up a character */
324
if (prevchar == '\r') { /* if prev char was cr */
325
if (c == '\n') /* if have cr,lf then just */
326
lseek(test->ofile, -1, SEEK_CUR); /* smash lf on top of the cr */
328
if (c == '\0') /* if have cr,nul then */
329
goto skipit; /* just skip over the putc */
330
/* else just fall through and allow it */
334
write(test->ofile, &c, 1);
342
/* When an error has occurred, it is possible that the two sides are out of
343
* synch. Ie: that what I think is the other side's response to packet N is
344
* really their response to packet N-1.
346
* So, to try to prevent that, we flush all the input queued up for us on the
347
* network connection on our host.
349
* We return the number of packets we flushed (mostly for reporting when trace
353
static int synchnet(curl_socket_t f /* socket to flush */)
357
struct sockaddr_in from;
361
(void) ioctl(f, FIONREAD, &i);
364
fromlen = sizeof from;
365
(void) recvfrom(f, rbuf, sizeof (rbuf), 0,
366
(struct sockaddr *)&from, &fromlen);
374
* Like signal(), but with well-defined semantics.
376
static void mysignal(int sig, void (*handler)(int))
379
memset(&sa, 0, sizeof(sa));
380
sa.sa_handler = handler;
381
sigaction(sig, &sa, NULL);
385
#ifndef DEFAULT_LOGFILE
386
#define DEFAULT_LOGFILE "log/tftpd.log"
389
#define DEFAULT_PORT 8999 /* UDP */
390
const char *serverlogfile = DEFAULT_LOGFILE;
392
#define REQUEST_DUMP "log/server.input"
396
int main(int argc, char **argv)
398
struct sockaddr_in me;
400
struct sockaddr_in6 me6;
401
#endif /* ENABLE_IPV6 */
407
char *pidname= (char *)".tftpd.pid";
408
unsigned short port = DEFAULT_PORT;
412
struct testcase test;
415
if(!strcmp("--version", argv[arg])) {
416
printf("tftpd IPv4%s\n",
425
else if(!strcmp("--pidfile", argv[arg])) {
428
pidname = argv[arg++];
430
else if(!strcmp("--ipv6", argv[arg])) {
439
port = (unsigned short)atoi(argv[arg++]);
446
#if defined(WIN32) && !defined(__GNUC__) || defined(__MINGW32__)
448
atexit(win32_cleanup);
454
sock = socket(AF_INET, SOCK_DGRAM, 0);
457
sock = socket(AF_INET6, SOCK_DGRAM, 0);
461
perror("opening stream socket");
462
logmsg("Error opening socket");
468
(sock, SOL_SOCKET, SO_REUSEADDR, (const void *) &flag,
470
perror("setsockopt(SO_REUSEADDR)");
476
me.sin_family = AF_INET;
477
me.sin_addr.s_addr = INADDR_ANY;
478
me.sin_port = htons(port);
479
rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
483
memset(&me6, 0, sizeof(struct sockaddr_in6));
484
me6.sin6_family = AF_INET6;
485
me6.sin6_addr = in6addr_any;
486
me6.sin6_port = htons(port);
487
rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
489
#endif /* ENABLE_IPV6 */
491
perror("binding stream socket");
492
logmsg("Error binding socket");
496
pidfile = fopen(pidname, "w");
498
fprintf(pidfile, "%d\n", (int)getpid());
502
fprintf(stderr, "Couldn't write pid file\n");
504
logmsg("Running IPv%d version on port UDP/%d",
515
fromlen = sizeof(from);
516
n = recvfrom(sock, buf, sizeof (buf), 0,
517
(struct sockaddr *)&from, &fromlen);
519
logmsg("recvfrom:\n");
523
from.sin_family = AF_INET;
525
peer = socket(AF_INET, SOCK_DGRAM, 0);
531
if (connect(peer, (struct sockaddr *)&from, sizeof(from)) < 0) {
532
logmsg("connect: fail\n");
535
maxtimeout = 5*TIMEOUT;
537
tp = (struct tftphdr *)buf;
538
tp->th_opcode = ntohs(tp->th_opcode);
539
if (tp->th_opcode == RRQ || tp->th_opcode == WRQ) {
540
memset(&test, 0, sizeof(test));
541
server = fopen(REQUEST_DUMP, "ab");
544
test.server = server;
565
* Handle initial connection protocol.
567
static int tftp(struct testcase *test, struct tftphdr *tp, int size)
570
int first = 1, ecode;
572
char *filename, *mode = NULL;
574
/* store input protocol */
575
fprintf(test->server, "opcode: %x\n", tp->th_opcode);
577
cp = (char *)&tp->th_stuff;
580
while (cp < buf + size) {
594
/* store input protocol */
595
fprintf(test->server, "filename: %s\n", filename);
597
for (cp = mode; *cp; cp++)
598
if (isupper((int)*cp))
599
*cp = tolower((int)*cp);
601
/* store input protocol */
602
fprintf(test->server, "mode: %s\n", mode);
604
for (pf = formats; pf->f_mode; pf++)
605
if (strcmp(pf->f_mode, mode) == 0)
611
ecode = validate_access(test, filename, tp->th_opcode);
616
if (tp->th_opcode == WRQ)
625
* Validate file access.
627
static int validate_access(struct testcase *test,
628
const char *filename, int mode)
633
logmsg("trying to get file: %s mode %x", filename, mode);
635
if(!strncmp("/verifiedserver", filename, 15)) {
637
size_t count = sprintf(weare, "WE ROOLZ: %d\r\n", (int)getpid());
639
logmsg("Are-we-friendly question received");
640
test->buffer = strdup(weare);
641
test->rptr = test->buffer; /* set read pointer */
642
test->bufsize = count; /* set total count */
643
test->rcount = count; /* set data left to read */
647
/* find the last slash */
648
ptr = strrchr(filename, '/');
653
ptr++; /* skip the slash */
655
/* skip all non-numericals following the slash */
656
while(*ptr && !isdigit((int)*ptr))
660
testno = strtol(ptr, &ptr, 10);
662
logmsg("requested test number %d", testno);
666
file = test2file(testno);
669
FILE *stream=fopen(file, "rb");
671
logmsg("Couldn't open test file: %s", file);
676
test->buffer = (char *)spitout(stream, "reply", "data", &count);
679
test->rptr = test->buffer; /* set read pointer */
680
test->bufsize = count; /* set total count */
681
test->rcount = count; /* set data left to read */
692
logmsg("no slash found in path");
693
return EACCESS; /* failure */
700
sigjmp_buf timeoutbuf;
702
static void timer(int signum)
709
if (timeout >= maxtimeout)
711
siglongjmp(timeoutbuf, 1);
715
* Send the requested file.
717
static void sendtftp(struct testcase *test, struct formats *pf)
720
struct tftphdr *ap; /* ack packet */
721
unsigned short block = 1;
724
mysignal(SIGALRM, timer);
726
ap = (struct tftphdr *)ackbuf;
728
size = readit(test, &dp, pf->f_convert);
733
dp->th_opcode = htons((u_short)DATA);
734
dp->th_block = htons((u_short)block);
736
(void) sigsetjmp(timeoutbuf, 1);
739
if (send(peer, dp, size + 4, 0) != size + 4) {
743
read_ahead(test, pf->f_convert);
745
alarm(rexmtval); /* read the ack */
746
n = recv(peer, ackbuf, sizeof (ackbuf), 0);
749
logmsg("read: fail\n");
752
ap->th_opcode = ntohs((u_short)ap->th_opcode);
753
ap->th_block = ntohs((u_short)ap->th_block);
755
if (ap->th_opcode == ERROR) {
760
if (ap->th_opcode == ACK) {
761
if (ap->th_block == block) {
764
/* Re-synchronize with the other side */
765
(void) synchnet(peer);
766
if (ap->th_block == (block -1)) {
773
} while (size == SEGSIZE);
776
static void justquit(int signum)
786
static void recvtftp(struct testcase *test, struct formats *pf)
789
struct tftphdr *ap; /* ack buffer */
790
unsigned short block = 0;
793
mysignal(SIGALRM, timer);
795
ap = (struct tftphdr *)ackbuf;
798
ap->th_opcode = htons((u_short)ACK);
799
ap->th_block = htons((u_short)block);
801
(void) sigsetjmp(timeoutbuf, 1);
803
if (send(peer, ackbuf, 4, 0) != 4) {
804
logmsg("write: fail\n");
807
write_behind(test, pf->f_convert);
810
n = recv(peer, dp, PKTSIZE, 0);
812
if (n < 0) { /* really? */
813
logmsg("read: fail\n");
816
dp->th_opcode = ntohs((u_short)dp->th_opcode);
817
dp->th_block = ntohs((u_short)dp->th_block);
818
if (dp->th_opcode == ERROR)
820
if (dp->th_opcode == DATA) {
821
if (dp->th_block == block) {
824
/* Re-synchronize with the other side */
825
(void) synchnet(peer);
826
if (dp->th_block == (block-1))
827
goto send_ack; /* rexmit */
831
size = writeit(test, &dp, n - 4, pf->f_convert);
832
if (size != (n-4)) { /* ahem */
839
} while (size == SEGSIZE);
840
write_behind(test, pf->f_convert);
842
ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */
843
ap->th_block = htons((u_short)(block));
844
(void) send(peer, ackbuf, 4, 0);
846
mysignal(SIGALRM, justquit); /* just quit on timeout */
848
n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
850
if (n >= 4 && /* if read some data */
851
dp->th_opcode == DATA && /* and got a data block */
852
block == dp->th_block) { /* then my last ack was lost */
853
(void) send(peer, ackbuf, 4, 0); /* resend final ack */
863
{ EUNDEF, "Undefined error code" },
864
{ ENOTFOUND, "File not found" },
865
{ EACCESS, "Access violation" },
866
{ ENOSPACE, "Disk full or allocation exceeded" },
867
{ EBADOP, "Illegal TFTP operation" },
868
{ EBADID, "Unknown transfer ID" },
869
{ EEXISTS, "File already exists" },
870
{ ENOUSER, "No such user" },
875
* Send a nak packet (error message). Error code passed in is one of the
876
* standard TFTP codes, or a UNIX errno offset by 100.
878
static void nak(int error)
884
tp = (struct tftphdr *)buf;
885
tp->th_opcode = htons((u_short)ERROR);
886
tp->th_code = htons((u_short)error);
887
for (pe = errmsgs; pe->e_code >= 0; pe++)
888
if (pe->e_code == error)
890
if (pe->e_code < 0) {
891
pe->e_msg = strerror(error - 100);
892
tp->th_code = EUNDEF; /* set 'undef' errorcode */
894
strcpy(tp->th_msg, pe->e_msg);
895
length = (int)strlen(pe->e_msg);
896
tp->th_msg[length] = '\0';
898
if (send(peer, buf, length, 0) != length)
899
logmsg("nak: fail\n");