• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  *
9  * Trivial file transfer protocol server.
10  *
11  * This code includes many modifications by Jim Guyton <guyton@rand-unix>
12  *
13  * This source file was started based on netkit-tftpd 0.17
14  * Heavily modified for curl's test suite
15  */
16 
17 /*
18  * Copyright (C) 2005 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
19  * Copyright (c) 1983, Regents of the University of California.
20  * All rights reserved.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
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.
37  *
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
48  * SUCH DAMAGE.
49  */
50 
51 #include "server_setup.h"
52 
53 #ifdef HAVE_SYS_IOCTL_H
54 #include <sys/ioctl.h>
55 #endif
56 #ifdef HAVE_SIGNAL_H
57 #include <signal.h>
58 #endif
59 #ifdef HAVE_FCNTL_H
60 #include <fcntl.h>
61 #endif
62 #ifdef HAVE_NETINET_IN_H
63 #include <netinet/in.h>
64 #endif
65 #ifdef HAVE_ARPA_INET_H
66 #include <arpa/inet.h>
67 #endif
68 #ifdef HAVE_ARPA_TFTP_H
69 #include <arpa/tftp.h>
70 #else
71 #include "tftp.h"
72 #endif
73 #ifdef HAVE_NETDB_H
74 #include <netdb.h>
75 #endif
76 #ifdef HAVE_SYS_FILIO_H
77 /* FIONREAD on Solaris 7 */
78 #include <sys/filio.h>
79 #endif
80 
81 #ifdef HAVE_SETJMP_H
82 #include <setjmp.h>
83 #endif
84 
85 #ifdef HAVE_PWD_H
86 #include <pwd.h>
87 #endif
88 
89 #define ENABLE_CURLX_PRINTF
90 /* make the curlx header define all printf() functions to use the curlx_*
91    versions instead */
92 #include "curlx.h" /* from the private lib dir */
93 #include "getpart.h"
94 #include "util.h"
95 #include "server_sockaddr.h"
96 
97 /* include memdebug.h last */
98 #include "memdebug.h"
99 
100 /*****************************************************************************
101 *                      STRUCT DECLARATIONS AND DEFINES                       *
102 *****************************************************************************/
103 
104 #ifndef PKTSIZE
105 #define PKTSIZE (SEGSIZE + 4)  /* SEGSIZE defined in arpa/tftp.h */
106 #endif
107 
108 struct testcase {
109   char *buffer;   /* holds the file data to send to the client */
110   size_t bufsize; /* size of the data in buffer */
111   char *rptr;     /* read pointer into the buffer */
112   size_t rcount;  /* amount of data left to read of the file */
113   long testno;    /* test case number */
114   int ofile;      /* file descriptor for output file when uploading to us */
115 
116   int writedelay; /* number of seconds between each packet */
117 };
118 
119 struct formats {
120   const char *f_mode;
121   int f_convert;
122 };
123 
124 struct errmsg {
125   int e_code;
126   const char *e_msg;
127 };
128 
129 typedef union {
130   struct tftphdr hdr;
131   char storage[PKTSIZE];
132 } tftphdr_storage_t;
133 
134 /*
135  * bf.counter values in range [-1 .. SEGSIZE] represents size of data in the
136  * bf.buf buffer. Additionally it can also hold flags BF_ALLOC or BF_FREE.
137  */
138 
139 struct bf {
140   int counter;            /* size of data in buffer, or flag */
141   tftphdr_storage_t buf;  /* room for data packet */
142 };
143 
144 #define BF_ALLOC -3       /* alloc'd but not yet filled */
145 #define BF_FREE  -2       /* free */
146 
147 #define opcode_RRQ   1
148 #define opcode_WRQ   2
149 #define opcode_DATA  3
150 #define opcode_ACK   4
151 #define opcode_ERROR 5
152 
153 #define TIMEOUT      5
154 
155 #undef MIN
156 #define MIN(x,y) ((x)<(y)?(x):(y))
157 
158 #ifndef DEFAULT_LOGFILE
159 #define DEFAULT_LOGFILE "log/tftpd.log"
160 #endif
161 
162 #define REQUEST_DUMP  "log/server.input"
163 
164 #define DEFAULT_PORT 8999 /* UDP */
165 
166 /*****************************************************************************
167 *                              GLOBAL VARIABLES                              *
168 *****************************************************************************/
169 
170 static struct errmsg errmsgs[] = {
171   { EUNDEF,       "Undefined error code" },
172   { ENOTFOUND,    "File not found" },
173   { EACCESS,      "Access violation" },
174   { ENOSPACE,     "Disk full or allocation exceeded" },
175   { EBADOP,       "Illegal TFTP operation" },
176   { EBADID,       "Unknown transfer ID" },
177   { EEXISTS,      "File already exists" },
178   { ENOUSER,      "No such user" },
179   { -1,           0 }
180 };
181 
182 static struct formats formata[] = {
183   { "netascii",   1 },
184   { "octet",      0 },
185   { NULL,         0 }
186 };
187 
188 static struct bf bfs[2];
189 
190 static int nextone;     /* index of next buffer to use */
191 static int current;     /* index of buffer in use */
192 
193                            /* control flags for crlf conversions */
194 static int newline = 0;    /* fillbuf: in middle of newline expansion */
195 static int prevchar = -1;  /* putbuf: previous char (cr check) */
196 
197 static tftphdr_storage_t buf;
198 static tftphdr_storage_t ackbuf;
199 
200 static srvr_sockaddr_union_t from;
201 static curl_socklen_t fromlen;
202 
203 static curl_socket_t peer = CURL_SOCKET_BAD;
204 
205 static unsigned int timeout;
206 static unsigned int maxtimeout = 5 * TIMEOUT;
207 
208 #ifdef ENABLE_IPV6
209 static bool use_ipv6 = FALSE;
210 #endif
211 static const char *ipv_inuse = "IPv4";
212 
213 const  char *serverlogfile = DEFAULT_LOGFILE;
214 static const char *pidname = ".tftpd.pid";
215 static const char *portfile = NULL;
216 static int serverlogslocked = 0;
217 static int wrotepidfile = 0;
218 
219 #ifdef HAVE_SIGSETJMP
220 static sigjmp_buf timeoutbuf;
221 #endif
222 
223 #if defined(HAVE_ALARM) && defined(SIGALRM)
224 static const unsigned int rexmtval = TIMEOUT;
225 #endif
226 
227 /*****************************************************************************
228 *                            FUNCTION PROTOTYPES                             *
229 *****************************************************************************/
230 
231 static struct tftphdr *rw_init(int);
232 
233 static struct tftphdr *w_init(void);
234 
235 static struct tftphdr *r_init(void);
236 
237 static void read_ahead(struct testcase *test, int convert);
238 
239 static ssize_t write_behind(struct testcase *test, int convert);
240 
241 static int synchnet(curl_socket_t);
242 
243 static int do_tftp(struct testcase *test, struct tftphdr *tp, ssize_t size);
244 
245 static int validate_access(struct testcase *test, const char *fname, int mode);
246 
247 static void sendtftp(struct testcase *test, struct formats *pf);
248 
249 static void recvtftp(struct testcase *test, struct formats *pf);
250 
251 static void nak(int error);
252 
253 #if defined(HAVE_ALARM) && defined(SIGALRM)
254 
255 static void mysignal(int sig, void (*handler)(int));
256 
257 static void timer(int signum);
258 
259 static void justtimeout(int signum);
260 
261 #endif /* HAVE_ALARM && SIGALRM */
262 
263 /*****************************************************************************
264 *                          FUNCTION IMPLEMENTATIONS                          *
265 *****************************************************************************/
266 
267 #if defined(HAVE_ALARM) && defined(SIGALRM)
268 
269 /*
270  * Like signal(), but with well-defined semantics.
271  */
mysignal(int sig,void (* handler)(int))272 static void mysignal(int sig, void (*handler)(int))
273 {
274   struct sigaction sa;
275   memset(&sa, 0, sizeof(sa));
276   sa.sa_handler = handler;
277   sigaction(sig, &sa, NULL);
278 }
279 
timer(int signum)280 static void timer(int signum)
281 {
282   (void)signum;
283 
284   logmsg("alarm!");
285 
286   timeout += rexmtval;
287   if(timeout >= maxtimeout) {
288     if(wrotepidfile) {
289       wrotepidfile = 0;
290       unlink(pidname);
291     }
292     if(serverlogslocked) {
293       serverlogslocked = 0;
294       clear_advisor_read_lock(SERVERLOGS_LOCK);
295     }
296     exit(1);
297   }
298 #ifdef HAVE_SIGSETJMP
299   siglongjmp(timeoutbuf, 1);
300 #endif
301 }
302 
justtimeout(int signum)303 static void justtimeout(int signum)
304 {
305   (void)signum;
306 }
307 
308 #endif /* HAVE_ALARM && SIGALRM */
309 
310 /*
311  * init for either read-ahead or write-behind.
312  * zero for write-behind, one for read-head.
313  */
rw_init(int x)314 static struct tftphdr *rw_init(int x)
315 {
316   newline = 0;                    /* init crlf flag */
317   prevchar = -1;
318   bfs[0].counter =  BF_ALLOC;     /* pass out the first buffer */
319   current = 0;
320   bfs[1].counter = BF_FREE;
321   nextone = x;                    /* ahead or behind? */
322   return &bfs[0].buf.hdr;
323 }
324 
w_init(void)325 static struct tftphdr *w_init(void)
326 {
327   return rw_init(0); /* write-behind */
328 }
329 
r_init(void)330 static struct tftphdr *r_init(void)
331 {
332   return rw_init(1); /* read-ahead */
333 }
334 
335 /* Have emptied current buffer by sending to net and getting ack.
336    Free it and return next buffer filled with data.
337  */
readit(struct testcase * test,struct tftphdr ** dpp,int convert)338 static int readit(struct testcase *test, struct tftphdr **dpp,
339                   int convert /* if true, convert to ascii */)
340 {
341   struct bf *b;
342 
343   bfs[current].counter = BF_FREE; /* free old one */
344   current = !current;             /* "incr" current */
345 
346   b = &bfs[current];              /* look at new buffer */
347   if(b->counter == BF_FREE)      /* if it's empty */
348     read_ahead(test, convert);    /* fill it */
349 
350   *dpp = &b->buf.hdr;             /* set caller's ptr */
351   return b->counter;
352 }
353 
354 /*
355  * fill the input buffer, doing ascii conversions if requested
356  * conversions are  lf -> cr, lf  and cr -> cr, nul
357  */
read_ahead(struct testcase * test,int convert)358 static void read_ahead(struct testcase *test,
359                        int convert /* if true, convert to ascii */)
360 {
361   int i;
362   char *p;
363   int c;
364   struct bf *b;
365   struct tftphdr *dp;
366 
367   b = &bfs[nextone];              /* look at "next" buffer */
368   if(b->counter != BF_FREE)      /* nop if not free */
369     return;
370   nextone = !nextone;             /* "incr" next buffer ptr */
371 
372   dp = &b->buf.hdr;
373 
374   if(convert == 0) {
375     /* The former file reading code did this:
376        b->counter = read(fileno(file), dp->th_data, SEGSIZE); */
377     size_t copy_n = MIN(SEGSIZE, test->rcount);
378     memcpy(dp->th_data, test->rptr, copy_n);
379 
380     /* decrease amount, advance pointer */
381     test->rcount -= copy_n;
382     test->rptr += copy_n;
383     b->counter = (int)copy_n;
384     return;
385   }
386 
387   p = dp->th_data;
388   for(i = 0 ; i < SEGSIZE; i++) {
389     if(newline) {
390       if(prevchar == '\n')
391         c = '\n';       /* lf to cr,lf */
392       else
393         c = '\0';       /* cr to cr,nul */
394       newline = 0;
395     }
396     else {
397       if(test->rcount) {
398         c = test->rptr[0];
399         test->rptr++;
400         test->rcount--;
401       }
402       else
403         break;
404       if(c == '\n' || c == '\r') {
405         prevchar = c;
406         c = '\r';
407         newline = 1;
408       }
409     }
410     *p++ = (char)c;
411   }
412   b->counter = (int)(p - dp->th_data);
413 }
414 
415 /* Update count associated with the buffer, get new buffer from the queue.
416    Calls write_behind only if next buffer not available.
417  */
writeit(struct testcase * test,struct tftphdr * volatile * dpp,int ct,int convert)418 static int writeit(struct testcase *test, struct tftphdr * volatile *dpp,
419                    int ct, int convert)
420 {
421   bfs[current].counter = ct;      /* set size of data to write */
422   current = !current;             /* switch to other buffer */
423   if(bfs[current].counter != BF_FREE)     /* if not free */
424     write_behind(test, convert);     /* flush it */
425   bfs[current].counter = BF_ALLOC;        /* mark as alloc'd */
426   *dpp =  &bfs[current].buf.hdr;
427   return ct;                      /* this is a lie of course */
428 }
429 
430 /*
431  * Output a buffer to a file, converting from netascii if requested.
432  * CR, NUL -> CR  and CR, LF => LF.
433  * Note spec is undefined if we get CR as last byte of file or a
434  * CR followed by anything else.  In this case we leave it alone.
435  */
write_behind(struct testcase * test,int convert)436 static ssize_t write_behind(struct testcase *test, int convert)
437 {
438   char *writebuf;
439   int count;
440   int ct;
441   char *p;
442   int c;                          /* current character */
443   struct bf *b;
444   struct tftphdr *dp;
445 
446   b = &bfs[nextone];
447   if(b->counter < -1)            /* anything to flush? */
448     return 0;                     /* just nop if nothing to do */
449 
450   if(!test->ofile) {
451     char outfile[256];
452     msnprintf(outfile, sizeof(outfile), "log/upload.%ld", test->testno);
453 #ifdef WIN32
454     test->ofile = open(outfile, O_CREAT|O_RDWR|O_BINARY, 0777);
455 #else
456     test->ofile = open(outfile, O_CREAT|O_RDWR, 0777);
457 #endif
458     if(test->ofile == -1) {
459       logmsg("Couldn't create and/or open file %s for upload!", outfile);
460       return -1; /* failure! */
461     }
462   }
463 
464   count = b->counter;             /* remember byte count */
465   b->counter = BF_FREE;           /* reset flag */
466   dp = &b->buf.hdr;
467   nextone = !nextone;             /* incr for next time */
468   writebuf = dp->th_data;
469 
470   if(count <= 0)
471     return -1;                    /* nak logic? */
472 
473   if(convert == 0)
474     return write(test->ofile, writebuf, count);
475 
476   p = writebuf;
477   ct = count;
478   while(ct--) {                   /* loop over the buffer */
479     c = *p++;                     /* pick up a character */
480     if(prevchar == '\r') {        /* if prev char was cr */
481       if(c == '\n')               /* if have cr,lf then just */
482         lseek(test->ofile, -1, SEEK_CUR); /* smash lf on top of the cr */
483       else
484         if(c == '\0')             /* if have cr,nul then */
485           goto skipit;            /* just skip over the putc */
486       /* else just fall through and allow it */
487     }
488     /* formerly
489        putc(c, file); */
490     if(1 != write(test->ofile, &c, 1))
491       break;
492     skipit:
493     prevchar = c;
494   }
495   return count;
496 }
497 
498 /* When an error has occurred, it is possible that the two sides are out of
499  * synch.  Ie: that what I think is the other side's response to packet N is
500  * really their response to packet N-1.
501  *
502  * So, to try to prevent that, we flush all the input queued up for us on the
503  * network connection on our host.
504  *
505  * We return the number of packets we flushed (mostly for reporting when trace
506  * is active).
507  */
508 
synchnet(curl_socket_t f)509 static int synchnet(curl_socket_t f /* socket to flush */)
510 {
511 
512 #if defined(HAVE_IOCTLSOCKET)
513   unsigned long i;
514 #else
515   int i;
516 #endif
517   int j = 0;
518   char rbuf[PKTSIZE];
519   srvr_sockaddr_union_t fromaddr;
520   curl_socklen_t fromaddrlen;
521 
522   for(;;) {
523 #if defined(HAVE_IOCTLSOCKET)
524     (void) ioctlsocket(f, FIONREAD, &i);
525 #else
526     (void) ioctl(f, FIONREAD, &i);
527 #endif
528     if(i) {
529       j++;
530 #ifdef ENABLE_IPV6
531       if(!use_ipv6)
532 #endif
533         fromaddrlen = sizeof(fromaddr.sa4);
534 #ifdef ENABLE_IPV6
535       else
536         fromaddrlen = sizeof(fromaddr.sa6);
537 #endif
538       (void) recvfrom(f, rbuf, sizeof(rbuf), 0,
539                       &fromaddr.sa, &fromaddrlen);
540     }
541     else
542       break;
543   }
544   return j;
545 }
546 
main(int argc,char ** argv)547 int main(int argc, char **argv)
548 {
549   srvr_sockaddr_union_t me;
550   struct tftphdr *tp;
551   ssize_t n = 0;
552   int arg = 1;
553   unsigned short port = DEFAULT_PORT;
554   curl_socket_t sock = CURL_SOCKET_BAD;
555   int flag;
556   int rc;
557   int error;
558   long pid;
559   struct testcase test;
560   int result = 0;
561 
562   memset(&test, 0, sizeof(test));
563 
564   while(argc>arg) {
565     if(!strcmp("--version", argv[arg])) {
566       printf("tftpd IPv4%s\n",
567 #ifdef ENABLE_IPV6
568              "/IPv6"
569 #else
570              ""
571 #endif
572              );
573       return 0;
574     }
575     else if(!strcmp("--pidfile", argv[arg])) {
576       arg++;
577       if(argc>arg)
578         pidname = argv[arg++];
579     }
580     else if(!strcmp("--portfile", argv[arg])) {
581       arg++;
582       if(argc>arg)
583         portfile = argv[arg++];
584     }
585     else if(!strcmp("--logfile", argv[arg])) {
586       arg++;
587       if(argc>arg)
588         serverlogfile = argv[arg++];
589     }
590     else if(!strcmp("--ipv4", argv[arg])) {
591 #ifdef ENABLE_IPV6
592       ipv_inuse = "IPv4";
593       use_ipv6 = FALSE;
594 #endif
595       arg++;
596     }
597     else if(!strcmp("--ipv6", argv[arg])) {
598 #ifdef ENABLE_IPV6
599       ipv_inuse = "IPv6";
600       use_ipv6 = TRUE;
601 #endif
602       arg++;
603     }
604     else if(!strcmp("--port", argv[arg])) {
605       arg++;
606       if(argc>arg) {
607         char *endptr;
608         unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
609         port = curlx_ultous(ulnum);
610         arg++;
611       }
612     }
613     else if(!strcmp("--srcdir", argv[arg])) {
614       arg++;
615       if(argc>arg) {
616         path = argv[arg];
617         arg++;
618       }
619     }
620     else {
621       puts("Usage: tftpd [option]\n"
622            " --version\n"
623            " --logfile [file]\n"
624            " --pidfile [file]\n"
625            " --ipv4\n"
626            " --ipv6\n"
627            " --port [port]\n"
628            " --srcdir [path]");
629       return 0;
630     }
631   }
632 
633 #ifdef WIN32
634   win32_init();
635   atexit(win32_cleanup);
636 #endif
637 
638   install_signal_handlers(true);
639 
640   pid = (long)getpid();
641 
642 #ifdef ENABLE_IPV6
643   if(!use_ipv6)
644 #endif
645     sock = socket(AF_INET, SOCK_DGRAM, 0);
646 #ifdef ENABLE_IPV6
647   else
648     sock = socket(AF_INET6, SOCK_DGRAM, 0);
649 #endif
650 
651   if(CURL_SOCKET_BAD == sock) {
652     error = SOCKERRNO;
653     logmsg("Error creating socket: (%d) %s",
654            error, strerror(error));
655     result = 1;
656     goto tftpd_cleanup;
657   }
658 
659   flag = 1;
660   if(0 != setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
661             (void *)&flag, sizeof(flag))) {
662     error = SOCKERRNO;
663     logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
664            error, strerror(error));
665     result = 1;
666     goto tftpd_cleanup;
667   }
668 
669 #ifdef ENABLE_IPV6
670   if(!use_ipv6) {
671 #endif
672     memset(&me.sa4, 0, sizeof(me.sa4));
673     me.sa4.sin_family = AF_INET;
674     me.sa4.sin_addr.s_addr = INADDR_ANY;
675     me.sa4.sin_port = htons(port);
676     rc = bind(sock, &me.sa, sizeof(me.sa4));
677 #ifdef ENABLE_IPV6
678   }
679   else {
680     memset(&me.sa6, 0, sizeof(me.sa6));
681     me.sa6.sin6_family = AF_INET6;
682     me.sa6.sin6_addr = in6addr_any;
683     me.sa6.sin6_port = htons(port);
684     rc = bind(sock, &me.sa, sizeof(me.sa6));
685   }
686 #endif /* ENABLE_IPV6 */
687   if(0 != rc) {
688     error = SOCKERRNO;
689     logmsg("Error binding socket on port %hu: (%d) %s",
690            port, error, strerror(error));
691     result = 1;
692     goto tftpd_cleanup;
693   }
694 
695   if(!port) {
696     /* The system was supposed to choose a port number, figure out which
697        port we actually got and update the listener port value with it. */
698     curl_socklen_t la_size;
699     srvr_sockaddr_union_t localaddr;
700 #ifdef ENABLE_IPV6
701     if(!use_ipv6)
702 #endif
703       la_size = sizeof(localaddr.sa4);
704 #ifdef ENABLE_IPV6
705     else
706       la_size = sizeof(localaddr.sa6);
707 #endif
708     memset(&localaddr.sa, 0, (size_t)la_size);
709     if(getsockname(sock, &localaddr.sa, &la_size) < 0) {
710       error = SOCKERRNO;
711       logmsg("getsockname() failed with error: (%d) %s",
712              error, strerror(error));
713       sclose(sock);
714       goto tftpd_cleanup;
715     }
716     switch(localaddr.sa.sa_family) {
717     case AF_INET:
718       port = ntohs(localaddr.sa4.sin_port);
719       break;
720 #ifdef ENABLE_IPV6
721     case AF_INET6:
722       port = ntohs(localaddr.sa6.sin6_port);
723       break;
724 #endif
725     default:
726       break;
727     }
728     if(!port) {
729       /* Real failure, listener port shall not be zero beyond this point. */
730       logmsg("Apparently getsockname() succeeded, with listener port zero.");
731       logmsg("A valid reason for this failure is a binary built without");
732       logmsg("proper network library linkage. This might not be the only");
733       logmsg("reason, but double check it before anything else.");
734       result = 2;
735       goto tftpd_cleanup;
736     }
737   }
738 
739   wrotepidfile = write_pidfile(pidname);
740   if(!wrotepidfile) {
741     result = 1;
742     goto tftpd_cleanup;
743   }
744 
745   if(portfile) {
746     wrotepidfile = write_portfile(portfile, port);
747     if(!wrotepidfile) {
748       result = 1;
749       goto tftpd_cleanup;
750     }
751   }
752 
753   logmsg("Running %s version on port UDP/%d", ipv_inuse, (int)port);
754 
755   for(;;) {
756     fromlen = sizeof(from);
757 #ifdef ENABLE_IPV6
758     if(!use_ipv6)
759 #endif
760       fromlen = sizeof(from.sa4);
761 #ifdef ENABLE_IPV6
762     else
763       fromlen = sizeof(from.sa6);
764 #endif
765     n = (ssize_t)recvfrom(sock, &buf.storage[0], sizeof(buf.storage), 0,
766                           &from.sa, &fromlen);
767     if(got_exit_signal)
768       break;
769     if(n < 0) {
770       logmsg("recvfrom");
771       result = 3;
772       break;
773     }
774 
775     set_advisor_read_lock(SERVERLOGS_LOCK);
776     serverlogslocked = 1;
777 
778 #ifdef ENABLE_IPV6
779     if(!use_ipv6) {
780 #endif
781       from.sa4.sin_family = AF_INET;
782       peer = socket(AF_INET, SOCK_DGRAM, 0);
783       if(CURL_SOCKET_BAD == peer) {
784         logmsg("socket");
785         result = 2;
786         break;
787       }
788       if(connect(peer, &from.sa, sizeof(from.sa4)) < 0) {
789         logmsg("connect: fail");
790         result = 1;
791         break;
792       }
793 #ifdef ENABLE_IPV6
794     }
795     else {
796       from.sa6.sin6_family = AF_INET6;
797       peer = socket(AF_INET6, SOCK_DGRAM, 0);
798       if(CURL_SOCKET_BAD == peer) {
799         logmsg("socket");
800         result = 2;
801         break;
802       }
803       if(connect(peer, &from.sa, sizeof(from.sa6)) < 0) {
804         logmsg("connect: fail");
805         result = 1;
806         break;
807       }
808     }
809 #endif
810 
811     maxtimeout = 5*TIMEOUT;
812 
813     tp = &buf.hdr;
814     tp->th_opcode = ntohs(tp->th_opcode);
815     if(tp->th_opcode == opcode_RRQ || tp->th_opcode == opcode_WRQ) {
816       memset(&test, 0, sizeof(test));
817       if(do_tftp(&test, tp, n) < 0)
818         break;
819       free(test.buffer);
820     }
821     sclose(peer);
822     peer = CURL_SOCKET_BAD;
823 
824     if(got_exit_signal)
825       break;
826 
827     if(serverlogslocked) {
828       serverlogslocked = 0;
829       clear_advisor_read_lock(SERVERLOGS_LOCK);
830     }
831 
832     logmsg("end of one transfer");
833 
834   }
835 
836 tftpd_cleanup:
837 
838   if(test.ofile > 0)
839     close(test.ofile);
840 
841   if((peer != sock) && (peer != CURL_SOCKET_BAD))
842     sclose(peer);
843 
844   if(sock != CURL_SOCKET_BAD)
845     sclose(sock);
846 
847   if(got_exit_signal)
848     logmsg("signalled to die");
849 
850   if(wrotepidfile)
851     unlink(pidname);
852   if(portfile)
853     unlink(portfile);
854 
855   if(serverlogslocked) {
856     serverlogslocked = 0;
857     clear_advisor_read_lock(SERVERLOGS_LOCK);
858   }
859 
860   restore_signal_handlers(true);
861 
862   if(got_exit_signal) {
863     logmsg("========> %s tftpd (port: %d pid: %ld) exits with signal (%d)",
864            ipv_inuse, (int)port, pid, exit_signal);
865     /*
866      * To properly set the return status of the process we
867      * must raise the same signal SIGINT or SIGTERM that we
868      * caught and let the old handler take care of it.
869      */
870     raise(exit_signal);
871   }
872 
873   logmsg("========> tftpd quits");
874   return result;
875 }
876 
877 /*
878  * Handle initial connection protocol.
879  */
do_tftp(struct testcase * test,struct tftphdr * tp,ssize_t size)880 static int do_tftp(struct testcase *test, struct tftphdr *tp, ssize_t size)
881 {
882   char *cp;
883   int first = 1, ecode;
884   struct formats *pf;
885   char *filename, *mode = NULL;
886 #ifdef USE_WINSOCK
887   DWORD recvtimeout, recvtimeoutbak;
888 #endif
889   const char *option = "mode"; /* mode is implicit */
890   int toggle = 1;
891 
892   /* Open request dump file. */
893   FILE *server = fopen(REQUEST_DUMP, "ab");
894   if(!server) {
895     int error = errno;
896     logmsg("fopen() failed with error: %d %s", error, strerror(error));
897     logmsg("Error opening file: %s", REQUEST_DUMP);
898     return -1;
899   }
900 
901   /* store input protocol */
902   fprintf(server, "opcode: %x\n", tp->th_opcode);
903 
904   cp = (char *)&tp->th_stuff;
905   filename = cp;
906   do {
907     bool endofit = true;
908     while(cp < &buf.storage[size]) {
909       if(*cp == '\0') {
910         endofit = false;
911         break;
912       }
913       cp++;
914     }
915     if(endofit)
916       /* no more options */
917       break;
918 
919     /* before increasing pointer, make sure it is still within the legal
920        space */
921     if((cp + 1) < &buf.storage[size]) {
922       ++cp;
923       if(first) {
924         /* store the mode since we need it later */
925         mode = cp;
926         first = 0;
927       }
928       if(toggle)
929         /* name/value pair: */
930         fprintf(server, "%s: %s\n", option, cp);
931       else {
932         /* store the name pointer */
933         option = cp;
934       }
935       toggle ^= 1;
936     }
937     else
938       /* No more options */
939       break;
940   } while(1);
941 
942   if(*cp) {
943     nak(EBADOP);
944     fclose(server);
945     return 3;
946   }
947 
948   /* store input protocol */
949   fprintf(server, "filename: %s\n", filename);
950 
951   for(cp = mode; cp && *cp; cp++)
952     if(ISUPPER(*cp))
953       *cp = (char)tolower((int)*cp);
954 
955   /* store input protocol */
956   fclose(server);
957 
958   for(pf = formata; pf->f_mode; pf++)
959     if(strcmp(pf->f_mode, mode) == 0)
960       break;
961   if(!pf->f_mode) {
962     nak(EBADOP);
963     return 2;
964   }
965   ecode = validate_access(test, filename, tp->th_opcode);
966   if(ecode) {
967     nak(ecode);
968     return 1;
969   }
970 
971 #ifdef USE_WINSOCK
972   recvtimeout = sizeof(recvtimeoutbak);
973   getsockopt(peer, SOL_SOCKET, SO_RCVTIMEO,
974              (char *)&recvtimeoutbak, (int *)&recvtimeout);
975   recvtimeout = TIMEOUT*1000;
976   setsockopt(peer, SOL_SOCKET, SO_RCVTIMEO,
977              (const char *)&recvtimeout, sizeof(recvtimeout));
978 #endif
979 
980   if(tp->th_opcode == opcode_WRQ)
981     recvtftp(test, pf);
982   else
983     sendtftp(test, pf);
984 
985 #ifdef USE_WINSOCK
986   recvtimeout = recvtimeoutbak;
987   setsockopt(peer, SOL_SOCKET, SO_RCVTIMEO,
988              (const char *)&recvtimeout, sizeof(recvtimeout));
989 #endif
990 
991   return 0;
992 }
993 
994 /* Based on the testno, parse the correct server commands. */
parse_servercmd(struct testcase * req)995 static int parse_servercmd(struct testcase *req)
996 {
997   FILE *stream;
998   int error;
999 
1000   stream = test2fopen(req->testno);
1001   if(!stream) {
1002     error = errno;
1003     logmsg("fopen() failed with error: %d %s", error, strerror(error));
1004     logmsg("  Couldn't open test file %ld", req->testno);
1005     return 1; /* done */
1006   }
1007   else {
1008     char *orgcmd = NULL;
1009     char *cmd = NULL;
1010     size_t cmdsize = 0;
1011     int num = 0;
1012 
1013     /* get the custom server control "commands" */
1014     error = getpart(&orgcmd, &cmdsize, "reply", "servercmd", stream);
1015     fclose(stream);
1016     if(error) {
1017       logmsg("getpart() failed with error: %d", error);
1018       return 1; /* done */
1019     }
1020 
1021     cmd = orgcmd;
1022     while(cmd && cmdsize) {
1023       char *check;
1024       if(1 == sscanf(cmd, "writedelay: %d", &num)) {
1025         logmsg("instructed to delay %d secs between packets", num);
1026         req->writedelay = num;
1027       }
1028       else {
1029         logmsg("Unknown <servercmd> instruction found: %s", cmd);
1030       }
1031       /* try to deal with CRLF or just LF */
1032       check = strchr(cmd, '\r');
1033       if(!check)
1034         check = strchr(cmd, '\n');
1035 
1036       if(check) {
1037         /* get to the letter following the newline */
1038         while((*check == '\r') || (*check == '\n'))
1039           check++;
1040 
1041         if(!*check)
1042           /* if we reached a zero, get out */
1043           break;
1044         cmd = check;
1045       }
1046       else
1047         break;
1048     }
1049     free(orgcmd);
1050   }
1051 
1052   return 0; /* OK! */
1053 }
1054 
1055 
1056 /*
1057  * Validate file access.
1058  */
validate_access(struct testcase * test,const char * filename,int mode)1059 static int validate_access(struct testcase *test,
1060                            const char *filename, int mode)
1061 {
1062   char *ptr;
1063 
1064   logmsg("trying to get file: %s mode %x", filename, mode);
1065 
1066   if(!strncmp("verifiedserver", filename, 14)) {
1067     char weare[128];
1068     size_t count = msnprintf(weare, sizeof(weare),
1069                              "WE ROOLZ: %ld\r\n", (long)getpid());
1070 
1071     logmsg("Are-we-friendly question received");
1072     test->buffer = strdup(weare);
1073     test->rptr = test->buffer; /* set read pointer */
1074     test->bufsize = count;    /* set total count */
1075     test->rcount = count;     /* set data left to read */
1076     return 0; /* fine */
1077   }
1078 
1079   /* find the last slash */
1080   ptr = strrchr(filename, '/');
1081 
1082   if(ptr) {
1083     char partbuf[80]="data";
1084     long partno;
1085     long testno;
1086     FILE *stream;
1087 
1088     ptr++; /* skip the slash */
1089 
1090     /* skip all non-numericals following the slash */
1091     while(*ptr && !ISDIGIT(*ptr))
1092       ptr++;
1093 
1094     /* get the number */
1095     testno = strtol(ptr, &ptr, 10);
1096 
1097     if(testno > 10000) {
1098       partno = testno % 10000;
1099       testno /= 10000;
1100     }
1101     else
1102       partno = 0;
1103 
1104 
1105     logmsg("requested test number %ld part %ld", testno, partno);
1106 
1107     test->testno = testno;
1108 
1109     (void)parse_servercmd(test);
1110 
1111     stream = test2fopen(testno);
1112 
1113     if(0 != partno)
1114       msnprintf(partbuf, sizeof(partbuf), "data%ld", partno);
1115 
1116     if(!stream) {
1117       int error = errno;
1118       logmsg("fopen() failed with error: %d %s", error, strerror(error));
1119       logmsg("Couldn't open test file for test : %d", testno);
1120       return EACCESS;
1121     }
1122     else {
1123       size_t count;
1124       int error = getpart(&test->buffer, &count, "reply", partbuf, stream);
1125       fclose(stream);
1126       if(error) {
1127         logmsg("getpart() failed with error: %d", error);
1128         return EACCESS;
1129       }
1130       if(test->buffer) {
1131         test->rptr = test->buffer; /* set read pointer */
1132         test->bufsize = count;    /* set total count */
1133         test->rcount = count;     /* set data left to read */
1134       }
1135       else
1136         return EACCESS;
1137     }
1138   }
1139   else {
1140     logmsg("no slash found in path");
1141     return EACCESS; /* failure */
1142   }
1143 
1144   logmsg("file opened and all is good");
1145   return 0;
1146 }
1147 
1148 /*
1149  * Send the requested file.
1150  */
sendtftp(struct testcase * test,struct formats * pf)1151 static void sendtftp(struct testcase *test, struct formats *pf)
1152 {
1153   int size;
1154   ssize_t n;
1155   /* These are volatile to live through a siglongjmp */
1156   volatile unsigned short sendblock; /* block count */
1157   struct tftphdr * volatile sdp = r_init(); /* data buffer */
1158   struct tftphdr * const sap = &ackbuf.hdr; /* ack buffer */
1159 
1160   sendblock = 1;
1161 #if defined(HAVE_ALARM) && defined(SIGALRM)
1162   mysignal(SIGALRM, timer);
1163 #endif
1164   do {
1165     size = readit(test, (struct tftphdr **)&sdp, pf->f_convert);
1166     if(size < 0) {
1167       nak(errno + 100);
1168       return;
1169     }
1170     sdp->th_opcode = htons((unsigned short)opcode_DATA);
1171     sdp->th_block = htons(sendblock);
1172     timeout = 0;
1173 #ifdef HAVE_SIGSETJMP
1174     (void) sigsetjmp(timeoutbuf, 1);
1175 #endif
1176     if(test->writedelay) {
1177       logmsg("Pausing %d seconds before %d bytes", test->writedelay,
1178              size);
1179       wait_ms(1000*test->writedelay);
1180     }
1181 
1182     send_data:
1183     logmsg("write");
1184     if(swrite(peer, sdp, size + 4) != size + 4) {
1185       logmsg("write: fail");
1186       return;
1187     }
1188     read_ahead(test, pf->f_convert);
1189     for(;;) {
1190 #ifdef HAVE_ALARM
1191       alarm(rexmtval);        /* read the ack */
1192 #endif
1193       logmsg("read");
1194       n = sread(peer, &ackbuf.storage[0], sizeof(ackbuf.storage));
1195       logmsg("read: %zd", n);
1196 #ifdef HAVE_ALARM
1197       alarm(0);
1198 #endif
1199       if(got_exit_signal)
1200         return;
1201       if(n < 0) {
1202         logmsg("read: fail");
1203         return;
1204       }
1205       sap->th_opcode = ntohs((unsigned short)sap->th_opcode);
1206       sap->th_block = ntohs(sap->th_block);
1207 
1208       if(sap->th_opcode == opcode_ERROR) {
1209         logmsg("got ERROR");
1210         return;
1211       }
1212 
1213       if(sap->th_opcode == opcode_ACK) {
1214         if(sap->th_block == sendblock) {
1215           break;
1216         }
1217         /* Re-synchronize with the other side */
1218         (void) synchnet(peer);
1219         if(sap->th_block == (sendblock-1)) {
1220           goto send_data;
1221         }
1222       }
1223 
1224     }
1225     sendblock++;
1226   } while(size == SEGSIZE);
1227 }
1228 
1229 /*
1230  * Receive a file.
1231  */
recvtftp(struct testcase * test,struct formats * pf)1232 static void recvtftp(struct testcase *test, struct formats *pf)
1233 {
1234   ssize_t n, size;
1235   /* These are volatile to live through a siglongjmp */
1236   volatile unsigned short recvblock; /* block count */
1237   struct tftphdr * volatile rdp;     /* data buffer */
1238   struct tftphdr *rap;      /* ack buffer */
1239 
1240   recvblock = 0;
1241   rdp = w_init();
1242 #if defined(HAVE_ALARM) && defined(SIGALRM)
1243   mysignal(SIGALRM, timer);
1244 #endif
1245   rap = &ackbuf.hdr;
1246   do {
1247     timeout = 0;
1248     rap->th_opcode = htons((unsigned short)opcode_ACK);
1249     rap->th_block = htons(recvblock);
1250     recvblock++;
1251 #ifdef HAVE_SIGSETJMP
1252     (void) sigsetjmp(timeoutbuf, 1);
1253 #endif
1254 send_ack:
1255     logmsg("write");
1256     if(swrite(peer, &ackbuf.storage[0], 4) != 4) {
1257       logmsg("write: fail");
1258       goto abort;
1259     }
1260     write_behind(test, pf->f_convert);
1261     for(;;) {
1262 #ifdef HAVE_ALARM
1263       alarm(rexmtval);
1264 #endif
1265       logmsg("read");
1266       n = sread(peer, rdp, PKTSIZE);
1267       logmsg("read: %zd", n);
1268 #ifdef HAVE_ALARM
1269       alarm(0);
1270 #endif
1271       if(got_exit_signal)
1272         goto abort;
1273       if(n < 0) {                       /* really? */
1274         logmsg("read: fail");
1275         goto abort;
1276       }
1277       rdp->th_opcode = ntohs((unsigned short)rdp->th_opcode);
1278       rdp->th_block = ntohs(rdp->th_block);
1279       if(rdp->th_opcode == opcode_ERROR)
1280         goto abort;
1281       if(rdp->th_opcode == opcode_DATA) {
1282         if(rdp->th_block == recvblock) {
1283           break;                         /* normal */
1284         }
1285         /* Re-synchronize with the other side */
1286         (void) synchnet(peer);
1287         if(rdp->th_block == (recvblock-1))
1288           goto send_ack;                 /* rexmit */
1289       }
1290     }
1291 
1292     size = writeit(test, &rdp, (int)(n - 4), pf->f_convert);
1293     if(size != (n-4)) {                 /* ahem */
1294       if(size < 0)
1295         nak(errno + 100);
1296       else
1297         nak(ENOSPACE);
1298       goto abort;
1299     }
1300   } while(size == SEGSIZE);
1301   write_behind(test, pf->f_convert);
1302   /* close the output file as early as possible after upload completion */
1303   if(test->ofile > 0) {
1304     close(test->ofile);
1305     test->ofile = 0;
1306   }
1307 
1308   rap->th_opcode = htons((unsigned short)opcode_ACK);  /* send the "final"
1309                                                           ack */
1310   rap->th_block = htons(recvblock);
1311   (void) swrite(peer, &ackbuf.storage[0], 4);
1312 #if defined(HAVE_ALARM) && defined(SIGALRM)
1313   mysignal(SIGALRM, justtimeout);        /* just abort read on timeout */
1314   alarm(rexmtval);
1315 #endif
1316   /* normally times out and quits */
1317   n = sread(peer, &buf.storage[0], sizeof(buf.storage));
1318 #ifdef HAVE_ALARM
1319   alarm(0);
1320 #endif
1321   if(got_exit_signal)
1322     goto abort;
1323   if(n >= 4 &&                               /* if read some data */
1324      rdp->th_opcode == opcode_DATA &&        /* and got a data block */
1325      recvblock == rdp->th_block) {           /* then my last ack was lost */
1326     (void) swrite(peer, &ackbuf.storage[0], 4);  /* resend final ack */
1327   }
1328 abort:
1329   /* make sure the output file is closed in case of abort */
1330   if(test->ofile > 0) {
1331     close(test->ofile);
1332     test->ofile = 0;
1333   }
1334   return;
1335 }
1336 
1337 /*
1338  * Send a nak packet (error message).  Error code passed in is one of the
1339  * standard TFTP codes, or a Unix errno offset by 100.
1340  */
nak(int error)1341 static void nak(int error)
1342 {
1343   struct tftphdr *tp;
1344   int length;
1345   struct errmsg *pe;
1346 
1347   tp = &buf.hdr;
1348   tp->th_opcode = htons((unsigned short)opcode_ERROR);
1349   tp->th_code = htons((unsigned short)error);
1350   for(pe = errmsgs; pe->e_code >= 0; pe++)
1351     if(pe->e_code == error)
1352       break;
1353   if(pe->e_code < 0) {
1354     pe->e_msg = strerror(error - 100);
1355     tp->th_code = EUNDEF;   /* set 'undef' errorcode */
1356   }
1357   length = (int)strlen(pe->e_msg);
1358 
1359   /* we use memcpy() instead of strcpy() in order to avoid buffer overflow
1360    * report from glibc with FORTIFY_SOURCE */
1361   memcpy(tp->th_msg, pe->e_msg, length + 1);
1362   length += 5;
1363   if(swrite(peer, &buf.storage[0], length) != length)
1364     logmsg("nak: fail\n");
1365 }
1366