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