• 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(test.ofile > 0) {
825       close(test.ofile);
826       test.ofile = 0;
827     }
828 
829     if(got_exit_signal)
830       break;
831 
832     if(serverlogslocked) {
833       serverlogslocked = 0;
834       clear_advisor_read_lock(SERVERLOGS_LOCK);
835     }
836 
837     logmsg("end of one transfer");
838 
839   }
840 
841 tftpd_cleanup:
842 
843   if(test.ofile > 0)
844     close(test.ofile);
845 
846   if((peer != sock) && (peer != CURL_SOCKET_BAD))
847     sclose(peer);
848 
849   if(sock != CURL_SOCKET_BAD)
850     sclose(sock);
851 
852   if(got_exit_signal)
853     logmsg("signalled to die");
854 
855   if(wrotepidfile)
856     unlink(pidname);
857   if(portfile)
858     unlink(portfile);
859 
860   if(serverlogslocked) {
861     serverlogslocked = 0;
862     clear_advisor_read_lock(SERVERLOGS_LOCK);
863   }
864 
865   restore_signal_handlers(true);
866 
867   if(got_exit_signal) {
868     logmsg("========> %s tftpd (port: %d pid: %ld) exits with signal (%d)",
869            ipv_inuse, (int)port, pid, exit_signal);
870     /*
871      * To properly set the return status of the process we
872      * must raise the same signal SIGINT or SIGTERM that we
873      * caught and let the old handler take care of it.
874      */
875     raise(exit_signal);
876   }
877 
878   logmsg("========> tftpd quits");
879   return result;
880 }
881 
882 /*
883  * Handle initial connection protocol.
884  */
do_tftp(struct testcase * test,struct tftphdr * tp,ssize_t size)885 static int do_tftp(struct testcase *test, struct tftphdr *tp, ssize_t size)
886 {
887   char *cp;
888   int first = 1, ecode;
889   struct formats *pf;
890   char *filename, *mode = NULL;
891 #ifdef USE_WINSOCK
892   DWORD recvtimeout, recvtimeoutbak;
893 #endif
894   const char *option = "mode"; /* mode is implicit */
895   int toggle = 1;
896 
897   /* Open request dump file. */
898   FILE *server = fopen(REQUEST_DUMP, "ab");
899   if(!server) {
900     int error = errno;
901     logmsg("fopen() failed with error: %d %s", error, strerror(error));
902     logmsg("Error opening file: %s", REQUEST_DUMP);
903     return -1;
904   }
905 
906   /* store input protocol */
907   fprintf(server, "opcode: %x\n", tp->th_opcode);
908 
909   cp = (char *)&tp->th_stuff;
910   filename = cp;
911   do {
912     bool endofit = true;
913     while(cp < &buf.storage[size]) {
914       if(*cp == '\0') {
915         endofit = false;
916         break;
917       }
918       cp++;
919     }
920     if(endofit)
921       /* no more options */
922       break;
923 
924     /* before increasing pointer, make sure it is still within the legal
925        space */
926     if((cp + 1) < &buf.storage[size]) {
927       ++cp;
928       if(first) {
929         /* store the mode since we need it later */
930         mode = cp;
931         first = 0;
932       }
933       if(toggle)
934         /* name/value pair: */
935         fprintf(server, "%s: %s\n", option, cp);
936       else {
937         /* store the name pointer */
938         option = cp;
939       }
940       toggle ^= 1;
941     }
942     else
943       /* No more options */
944       break;
945   } while(1);
946 
947   if(*cp) {
948     nak(EBADOP);
949     fclose(server);
950     return 3;
951   }
952 
953   /* store input protocol */
954   fprintf(server, "filename: %s\n", filename);
955 
956   for(cp = mode; cp && *cp; cp++)
957     if(ISUPPER(*cp))
958       *cp = (char)tolower((int)*cp);
959 
960   /* store input protocol */
961   fclose(server);
962 
963   for(pf = formata; pf->f_mode; pf++)
964     if(strcmp(pf->f_mode, mode) == 0)
965       break;
966   if(!pf->f_mode) {
967     nak(EBADOP);
968     return 2;
969   }
970   ecode = validate_access(test, filename, tp->th_opcode);
971   if(ecode) {
972     nak(ecode);
973     return 1;
974   }
975 
976 #ifdef USE_WINSOCK
977   recvtimeout = sizeof(recvtimeoutbak);
978   getsockopt(peer, SOL_SOCKET, SO_RCVTIMEO,
979              (char *)&recvtimeoutbak, (int *)&recvtimeout);
980   recvtimeout = TIMEOUT*1000;
981   setsockopt(peer, SOL_SOCKET, SO_RCVTIMEO,
982              (const char *)&recvtimeout, sizeof(recvtimeout));
983 #endif
984 
985   if(tp->th_opcode == opcode_WRQ)
986     recvtftp(test, pf);
987   else
988     sendtftp(test, pf);
989 
990 #ifdef USE_WINSOCK
991   recvtimeout = recvtimeoutbak;
992   setsockopt(peer, SOL_SOCKET, SO_RCVTIMEO,
993              (const char *)&recvtimeout, sizeof(recvtimeout));
994 #endif
995 
996   return 0;
997 }
998 
999 /* Based on the testno, parse the correct server commands. */
parse_servercmd(struct testcase * req)1000 static int parse_servercmd(struct testcase *req)
1001 {
1002   FILE *stream;
1003   int error;
1004 
1005   stream = test2fopen(req->testno);
1006   if(!stream) {
1007     error = errno;
1008     logmsg("fopen() failed with error: %d %s", error, strerror(error));
1009     logmsg("  Couldn't open test file %ld", req->testno);
1010     return 1; /* done */
1011   }
1012   else {
1013     char *orgcmd = NULL;
1014     char *cmd = NULL;
1015     size_t cmdsize = 0;
1016     int num = 0;
1017 
1018     /* get the custom server control "commands" */
1019     error = getpart(&orgcmd, &cmdsize, "reply", "servercmd", stream);
1020     fclose(stream);
1021     if(error) {
1022       logmsg("getpart() failed with error: %d", error);
1023       return 1; /* done */
1024     }
1025 
1026     cmd = orgcmd;
1027     while(cmd && cmdsize) {
1028       char *check;
1029       if(1 == sscanf(cmd, "writedelay: %d", &num)) {
1030         logmsg("instructed to delay %d secs between packets", num);
1031         req->writedelay = num;
1032       }
1033       else {
1034         logmsg("Unknown <servercmd> instruction found: %s", cmd);
1035       }
1036       /* try to deal with CRLF or just LF */
1037       check = strchr(cmd, '\r');
1038       if(!check)
1039         check = strchr(cmd, '\n');
1040 
1041       if(check) {
1042         /* get to the letter following the newline */
1043         while((*check == '\r') || (*check == '\n'))
1044           check++;
1045 
1046         if(!*check)
1047           /* if we reached a zero, get out */
1048           break;
1049         cmd = check;
1050       }
1051       else
1052         break;
1053     }
1054     free(orgcmd);
1055   }
1056 
1057   return 0; /* OK! */
1058 }
1059 
1060 
1061 /*
1062  * Validate file access.
1063  */
validate_access(struct testcase * test,const char * filename,int mode)1064 static int validate_access(struct testcase *test,
1065                            const char *filename, int mode)
1066 {
1067   char *ptr;
1068 
1069   logmsg("trying to get file: %s mode %x", filename, mode);
1070 
1071   if(!strncmp("verifiedserver", filename, 14)) {
1072     char weare[128];
1073     size_t count = msnprintf(weare, sizeof(weare),
1074                              "WE ROOLZ: %ld\r\n", (long)getpid());
1075 
1076     logmsg("Are-we-friendly question received");
1077     test->buffer = strdup(weare);
1078     test->rptr = test->buffer; /* set read pointer */
1079     test->bufsize = count;    /* set total count */
1080     test->rcount = count;     /* set data left to read */
1081     return 0; /* fine */
1082   }
1083 
1084   /* find the last slash */
1085   ptr = strrchr(filename, '/');
1086 
1087   if(ptr) {
1088     char partbuf[80]="data";
1089     long partno;
1090     long testno;
1091     FILE *stream;
1092 
1093     ptr++; /* skip the slash */
1094 
1095     /* skip all non-numericals following the slash */
1096     while(*ptr && !ISDIGIT(*ptr))
1097       ptr++;
1098 
1099     /* get the number */
1100     testno = strtol(ptr, &ptr, 10);
1101 
1102     if(testno > 10000) {
1103       partno = testno % 10000;
1104       testno /= 10000;
1105     }
1106     else
1107       partno = 0;
1108 
1109 
1110     logmsg("requested test number %ld part %ld", testno, partno);
1111 
1112     test->testno = testno;
1113 
1114     (void)parse_servercmd(test);
1115 
1116     stream = test2fopen(testno);
1117 
1118     if(0 != partno)
1119       msnprintf(partbuf, sizeof(partbuf), "data%ld", partno);
1120 
1121     if(!stream) {
1122       int error = errno;
1123       logmsg("fopen() failed with error: %d %s", error, strerror(error));
1124       logmsg("Couldn't open test file for test : %d", testno);
1125       return EACCESS;
1126     }
1127     else {
1128       size_t count;
1129       int error = getpart(&test->buffer, &count, "reply", partbuf, stream);
1130       fclose(stream);
1131       if(error) {
1132         logmsg("getpart() failed with error: %d", error);
1133         return EACCESS;
1134       }
1135       if(test->buffer) {
1136         test->rptr = test->buffer; /* set read pointer */
1137         test->bufsize = count;    /* set total count */
1138         test->rcount = count;     /* set data left to read */
1139       }
1140       else
1141         return EACCESS;
1142     }
1143   }
1144   else {
1145     logmsg("no slash found in path");
1146     return EACCESS; /* failure */
1147   }
1148 
1149   logmsg("file opened and all is good");
1150   return 0;
1151 }
1152 
1153 /*
1154  * Send the requested file.
1155  */
sendtftp(struct testcase * test,struct formats * pf)1156 static void sendtftp(struct testcase *test, struct formats *pf)
1157 {
1158   int size;
1159   ssize_t n;
1160   /* These are volatile to live through a siglongjmp */
1161   volatile unsigned short sendblock; /* block count */
1162   struct tftphdr * volatile sdp = r_init(); /* data buffer */
1163   struct tftphdr * const sap = &ackbuf.hdr; /* ack buffer */
1164 
1165   sendblock = 1;
1166 #if defined(HAVE_ALARM) && defined(SIGALRM)
1167   mysignal(SIGALRM, timer);
1168 #endif
1169   do {
1170     size = readit(test, (struct tftphdr **)&sdp, pf->f_convert);
1171     if(size < 0) {
1172       nak(errno + 100);
1173       return;
1174     }
1175     sdp->th_opcode = htons((unsigned short)opcode_DATA);
1176     sdp->th_block = htons(sendblock);
1177     timeout = 0;
1178 #ifdef HAVE_SIGSETJMP
1179     (void) sigsetjmp(timeoutbuf, 1);
1180 #endif
1181     if(test->writedelay) {
1182       logmsg("Pausing %d seconds before %d bytes", test->writedelay,
1183              size);
1184       wait_ms(1000*test->writedelay);
1185     }
1186 
1187     send_data:
1188     logmsg("write");
1189     if(swrite(peer, sdp, size + 4) != size + 4) {
1190       logmsg("write: fail");
1191       return;
1192     }
1193     read_ahead(test, pf->f_convert);
1194     for(;;) {
1195 #ifdef HAVE_ALARM
1196       alarm(rexmtval);        /* read the ack */
1197 #endif
1198       logmsg("read");
1199       n = sread(peer, &ackbuf.storage[0], sizeof(ackbuf.storage));
1200       logmsg("read: %zd", n);
1201 #ifdef HAVE_ALARM
1202       alarm(0);
1203 #endif
1204       if(got_exit_signal)
1205         return;
1206       if(n < 0) {
1207         logmsg("read: fail");
1208         return;
1209       }
1210       sap->th_opcode = ntohs((unsigned short)sap->th_opcode);
1211       sap->th_block = ntohs(sap->th_block);
1212 
1213       if(sap->th_opcode == opcode_ERROR) {
1214         logmsg("got ERROR");
1215         return;
1216       }
1217 
1218       if(sap->th_opcode == opcode_ACK) {
1219         if(sap->th_block == sendblock) {
1220           break;
1221         }
1222         /* Re-synchronize with the other side */
1223         (void) synchnet(peer);
1224         if(sap->th_block == (sendblock-1)) {
1225           goto send_data;
1226         }
1227       }
1228 
1229     }
1230     sendblock++;
1231   } while(size == SEGSIZE);
1232 }
1233 
1234 /*
1235  * Receive a file.
1236  */
recvtftp(struct testcase * test,struct formats * pf)1237 static void recvtftp(struct testcase *test, struct formats *pf)
1238 {
1239   ssize_t n, size;
1240   /* These are volatile to live through a siglongjmp */
1241   volatile unsigned short recvblock; /* block count */
1242   struct tftphdr * volatile rdp;     /* data buffer */
1243   struct tftphdr *rap;      /* ack buffer */
1244 
1245   recvblock = 0;
1246   rdp = w_init();
1247 #if defined(HAVE_ALARM) && defined(SIGALRM)
1248   mysignal(SIGALRM, timer);
1249 #endif
1250   rap = &ackbuf.hdr;
1251   do {
1252     timeout = 0;
1253     rap->th_opcode = htons((unsigned short)opcode_ACK);
1254     rap->th_block = htons(recvblock);
1255     recvblock++;
1256 #ifdef HAVE_SIGSETJMP
1257     (void) sigsetjmp(timeoutbuf, 1);
1258 #endif
1259 send_ack:
1260     logmsg("write");
1261     if(swrite(peer, &ackbuf.storage[0], 4) != 4) {
1262       logmsg("write: fail");
1263       goto abort;
1264     }
1265     write_behind(test, pf->f_convert);
1266     for(;;) {
1267 #ifdef HAVE_ALARM
1268       alarm(rexmtval);
1269 #endif
1270       logmsg("read");
1271       n = sread(peer, rdp, PKTSIZE);
1272       logmsg("read: %zd", n);
1273 #ifdef HAVE_ALARM
1274       alarm(0);
1275 #endif
1276       if(got_exit_signal)
1277         goto abort;
1278       if(n < 0) {                       /* really? */
1279         logmsg("read: fail");
1280         goto abort;
1281       }
1282       rdp->th_opcode = ntohs((unsigned short)rdp->th_opcode);
1283       rdp->th_block = ntohs(rdp->th_block);
1284       if(rdp->th_opcode == opcode_ERROR)
1285         goto abort;
1286       if(rdp->th_opcode == opcode_DATA) {
1287         if(rdp->th_block == recvblock) {
1288           break;                         /* normal */
1289         }
1290         /* Re-synchronize with the other side */
1291         (void) synchnet(peer);
1292         if(rdp->th_block == (recvblock-1))
1293           goto send_ack;                 /* rexmit */
1294       }
1295     }
1296 
1297     size = writeit(test, &rdp, (int)(n - 4), pf->f_convert);
1298     if(size != (n-4)) {                 /* ahem */
1299       if(size < 0)
1300         nak(errno + 100);
1301       else
1302         nak(ENOSPACE);
1303       goto abort;
1304     }
1305   } while(size == SEGSIZE);
1306   write_behind(test, pf->f_convert);
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   return;
1330 }
1331 
1332 /*
1333  * Send a nak packet (error message).  Error code passed in is one of the
1334  * standard TFTP codes, or a Unix errno offset by 100.
1335  */
nak(int error)1336 static void nak(int error)
1337 {
1338   struct tftphdr *tp;
1339   int length;
1340   struct errmsg *pe;
1341 
1342   tp = &buf.hdr;
1343   tp->th_opcode = htons((unsigned short)opcode_ERROR);
1344   tp->th_code = htons((unsigned short)error);
1345   for(pe = errmsgs; pe->e_code >= 0; pe++)
1346     if(pe->e_code == error)
1347       break;
1348   if(pe->e_code < 0) {
1349     pe->e_msg = strerror(error - 100);
1350     tp->th_code = EUNDEF;   /* set 'undef' errorcode */
1351   }
1352   length = (int)strlen(pe->e_msg);
1353 
1354   /* we use memcpy() instead of strcpy() in order to avoid buffer overflow
1355    * report from glibc with FORTIFY_SOURCE */
1356   memcpy(tp->th_msg, pe->e_msg, length + 1);
1357   length += 5;
1358   if(swrite(peer, &buf.storage[0], length) != length)
1359     logmsg("nak: fail\n");
1360 }
1361