Git init
[external/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 #define CURL_NO_OLDIES
51
52 #include "setup.h" /* portability help from the lib directory */
53
54 #ifdef HAVE_SYS_IOCTL_H
55 #include <sys/ioctl.h>
56 #endif
57 #ifdef HAVE_SIGNAL_H
58 #include <signal.h>
59 #endif
60 #ifdef HAVE_FCNTL_H
61 #include <fcntl.h>
62 #endif
63 #ifdef HAVE_SYS_SOCKET_H
64 #include <sys/socket.h>
65 #endif
66 #ifdef HAVE_NETINET_IN_H
67 #include <netinet/in.h>
68 #endif
69 #ifdef HAVE_ARPA_INET_H
70 #include <arpa/inet.h>
71 #endif
72 #ifdef HAVE_ARPA_TFTP_H
73 #include <arpa/tftp.h>
74 #else
75 #include "tftp.h"
76 #endif
77 #ifdef HAVE_NETDB_H
78 #include <netdb.h>
79 #endif
80 #ifdef HAVE_SYS_FILIO_H
81 /* FIONREAD on Solaris 7 */
82 #include <sys/filio.h>
83 #endif
84
85 #include <setjmp.h>
86 #ifdef HAVE_UNISTD_H
87 #include <unistd.h>
88 #endif
89 #ifdef HAVE_PWD_H
90 #include <pwd.h>
91 #endif
92
93 #define ENABLE_CURLX_PRINTF
94 /* make the curlx header define all printf() functions to use the curlx_*
95    versions instead */
96 #include "curlx.h" /* from the private lib dir */
97 #include "getpart.h"
98 #include "util.h"
99 #include "server_sockaddr.h"
100
101 /* include memdebug.h last */
102 #include "memdebug.h"
103
104 /*****************************************************************************
105 *                      STRUCT DECLARATIONS AND DEFINES                       *
106 *****************************************************************************/
107
108 #ifndef PKTSIZE
109 #define PKTSIZE (SEGSIZE + 4)  /* SEGSIZE defined in arpa/tftp.h */
110 #endif
111
112 struct testcase {
113   char *buffer;   /* holds the file data to send to the client */
114   size_t bufsize; /* size of the data in buffer */
115   char *rptr;     /* read pointer into the buffer */
116   size_t rcount;  /* amount of data left to read of the file */
117   long num;       /* test case number */
118   int ofile;      /* file descriptor for output file when uploading to us */
119 };
120
121 struct formats {
122   const char *f_mode;
123   int f_convert;
124 };
125
126 struct errmsg {
127   int e_code;
128   const char *e_msg;
129 };
130
131 typedef union {
132   struct tftphdr hdr;
133   char storage[PKTSIZE];
134 } tftphdr_storage_t;
135
136 /*
137  * bf.counter values in range [-1 .. SEGSIZE] represents size of data in the
138  * bf.buf buffer. Additionally it can also hold flags BF_ALLOC or BF_FREE.
139  */
140
141 struct bf {
142   int counter;            /* size of data in buffer, or flag */
143   tftphdr_storage_t buf;  /* room for data packet */
144 };
145
146 #define BF_ALLOC -3       /* alloc'd but not yet filled */
147 #define BF_FREE  -2       /* free */
148
149 #define opcode_RRQ   1
150 #define opcode_WRQ   2
151 #define opcode_DATA  3
152 #define opcode_ACK   4
153 #define opcode_ERROR 5
154
155 #define TIMEOUT      5
156
157 #undef MIN
158 #define MIN(x,y) ((x)<(y)?(x):(y))
159
160 #ifndef DEFAULT_LOGFILE
161 #define DEFAULT_LOGFILE "log/tftpd.log"
162 #endif
163
164 #define REQUEST_DUMP  "log/server.input"
165
166 #define DEFAULT_PORT 8999 /* UDP */
167
168 /*****************************************************************************
169 *                              GLOBAL VARIABLES                              *
170 *****************************************************************************/
171
172 static struct errmsg errmsgs[] = {
173   { EUNDEF,       "Undefined error code" },
174   { ENOTFOUND,    "File not found" },
175   { EACCESS,      "Access violation" },
176   { ENOSPACE,     "Disk full or allocation exceeded" },
177   { EBADOP,       "Illegal TFTP operation" },
178   { EBADID,       "Unknown transfer ID" },
179   { EEXISTS,      "File already exists" },
180   { ENOUSER,      "No such user" },
181   { -1,           0 }
182 };
183
184 static struct formats formata[] = {
185   { "netascii",   1 },
186   { "octet",      0 },
187   { NULL,         0 }
188 };
189
190 static struct bf bfs[2];
191
192 static int nextone;     /* index of next buffer to use */
193 static int current;     /* index of buffer in use */
194
195                            /* control flags for crlf conversions */
196 static int newline = 0;    /* fillbuf: in middle of newline expansion */
197 static int prevchar = -1;  /* putbuf: previous char (cr check) */
198
199 static tftphdr_storage_t buf;
200 static tftphdr_storage_t ackbuf;
201
202 static srvr_sockaddr_union_t from;
203 static curl_socklen_t fromlen;
204
205 static curl_socket_t peer = CURL_SOCKET_BAD;
206
207 static int timeout;
208 static int maxtimeout = 5 * TIMEOUT;
209
210 static unsigned short sendblock; /* block count used by sendtftp() */
211 static struct tftphdr *sdp;      /* data buffer used by sendtftp() */
212 static struct tftphdr *sap;      /* ack buffer  used by sendtftp() */
213
214 static unsigned short recvblock; /* block count used by recvtftp() */
215 static struct tftphdr *rdp;      /* data buffer used by recvtftp() */
216 static struct tftphdr *rap;      /* ack buffer  used by recvtftp() */
217
218 #ifdef ENABLE_IPV6
219 static bool use_ipv6 = FALSE;
220 #endif
221 static const char *ipv_inuse = "IPv4";
222
223 const  char *serverlogfile = DEFAULT_LOGFILE;
224 static char *pidname= (char *)".tftpd.pid";
225 static int serverlogslocked = 0;
226 static int wrotepidfile = 0;
227
228 #ifdef HAVE_SIGSETJMP
229 static sigjmp_buf timeoutbuf;
230 #endif
231
232 #if defined(HAVE_ALARM) && defined(SIGALRM)
233 static int rexmtval = TIMEOUT;
234 #endif
235
236 /* do-nothing macro replacement for systems which lack siginterrupt() */
237
238 #ifndef HAVE_SIGINTERRUPT
239 #define siginterrupt(x,y) do {} while(0)
240 #endif
241
242 /* vars used to keep around previous signal handlers */
243
244 typedef RETSIGTYPE (*SIGHANDLER_T)(int);
245
246 #ifdef SIGHUP
247 static SIGHANDLER_T old_sighup_handler  = SIG_ERR;
248 #endif
249
250 #ifdef SIGPIPE
251 static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
252 #endif
253
254 #ifdef SIGINT
255 static SIGHANDLER_T old_sigint_handler  = SIG_ERR;
256 #endif
257
258 #ifdef SIGTERM
259 static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
260 #endif
261
262 /* var which if set indicates that the program should finish execution */
263
264 SIG_ATOMIC_T got_exit_signal = 0;
265
266 /* if next is set indicates the first signal handled in exit_signal_handler */
267
268 static volatile int exit_signal = 0;
269
270 /*****************************************************************************
271 *                            FUNCTION PROTOTYPES                             *
272 *****************************************************************************/
273
274 static struct tftphdr *rw_init(int);
275
276 static struct tftphdr *w_init(void);
277
278 static struct tftphdr *r_init(void);
279
280 static int readit(struct testcase *test,
281                   struct tftphdr **dpp,
282                   int convert);
283
284 static int writeit(struct testcase *test,
285                    struct tftphdr **dpp,
286                    int ct,
287                    int convert);
288
289 static void read_ahead(struct testcase *test, int convert);
290
291 static ssize_t write_behind(struct testcase *test, int convert);
292
293 static int synchnet(curl_socket_t);
294
295 static int do_tftp(struct testcase *test, struct tftphdr *tp, ssize_t size);
296
297 static int validate_access(struct testcase *test, const char *fname, int mode);
298
299 static void sendtftp(struct testcase *test, struct formats *pf);
300
301 static void recvtftp(struct testcase *test, struct formats *pf);
302
303 static void nak(int error);
304
305 #if defined(HAVE_ALARM) && defined(SIGALRM)
306
307 static void mysignal(int sig, void (*handler)(int));
308
309 static void timer(int signum);
310
311 static void justtimeout(int signum);
312
313 #endif /* HAVE_ALARM && SIGALRM */
314
315 static RETSIGTYPE exit_signal_handler(int signum);
316
317 static void install_signal_handlers(void);
318
319 static void restore_signal_handlers(void);
320
321 /*****************************************************************************
322 *                          FUNCTION IMPLEMENTATIONS                          *
323 *****************************************************************************/
324
325 #if defined(HAVE_ALARM) && defined(SIGALRM)
326
327 /*
328  * Like signal(), but with well-defined semantics.
329  */
330 static void mysignal(int sig, void (*handler)(int))
331 {
332   struct sigaction sa;
333   memset(&sa, 0, sizeof(sa));
334   sa.sa_handler = handler;
335   sigaction(sig, &sa, NULL);
336 }
337
338 static void timer(int signum)
339 {
340   (void)signum;
341
342   logmsg("alarm!");
343
344   timeout += rexmtval;
345   if(timeout >= maxtimeout) {
346     if(wrotepidfile) {
347       wrotepidfile = 0;
348       unlink(pidname);
349     }
350     if(serverlogslocked) {
351       serverlogslocked = 0;
352       clear_advisor_read_lock(SERVERLOGS_LOCK);
353     }
354     exit(1);
355   }
356 #ifdef HAVE_SIGSETJMP
357   siglongjmp(timeoutbuf, 1);
358 #endif
359 }
360
361 static void justtimeout(int signum)
362 {
363   (void)signum;
364 }
365
366 #endif /* HAVE_ALARM && SIGALRM */
367
368 /* signal handler that will be triggered to indicate that the program
369   should finish its execution in a controlled manner as soon as possible.
370   The first time this is called it will set got_exit_signal to one and
371   store in exit_signal the signal that triggered its execution. */
372
373 static RETSIGTYPE exit_signal_handler(int signum)
374 {
375   int old_errno = ERRNO;
376   if(got_exit_signal == 0) {
377     got_exit_signal = 1;
378     exit_signal = signum;
379   }
380   (void)signal(signum, exit_signal_handler);
381   SET_ERRNO(old_errno);
382 }
383
384 static void install_signal_handlers(void)
385 {
386 #ifdef SIGHUP
387   /* ignore SIGHUP signal */
388   if((old_sighup_handler = signal(SIGHUP, SIG_IGN)) == SIG_ERR)
389     logmsg("cannot install SIGHUP handler: %s", strerror(ERRNO));
390 #endif
391 #ifdef SIGPIPE
392   /* ignore SIGPIPE signal */
393   if((old_sigpipe_handler = signal(SIGPIPE, SIG_IGN)) == SIG_ERR)
394     logmsg("cannot install SIGPIPE handler: %s", strerror(ERRNO));
395 #endif
396 #ifdef SIGINT
397   /* handle SIGINT signal with our exit_signal_handler */
398   if((old_sigint_handler = signal(SIGINT, exit_signal_handler)) == SIG_ERR)
399     logmsg("cannot install SIGINT handler: %s", strerror(ERRNO));
400   else
401     siginterrupt(SIGINT, 1);
402 #endif
403 #ifdef SIGTERM
404   /* handle SIGTERM signal with our exit_signal_handler */
405   if((old_sigterm_handler = signal(SIGTERM, exit_signal_handler)) == SIG_ERR)
406     logmsg("cannot install SIGTERM handler: %s", strerror(ERRNO));
407   else
408     siginterrupt(SIGTERM, 1);
409 #endif
410 }
411
412 static void restore_signal_handlers(void)
413 {
414 #ifdef SIGHUP
415   if(SIG_ERR != old_sighup_handler)
416     (void)signal(SIGHUP, old_sighup_handler);
417 #endif
418 #ifdef SIGPIPE
419   if(SIG_ERR != old_sigpipe_handler)
420     (void)signal(SIGPIPE, old_sigpipe_handler);
421 #endif
422 #ifdef SIGINT
423   if(SIG_ERR != old_sigint_handler)
424     (void)signal(SIGINT, old_sigint_handler);
425 #endif
426 #ifdef SIGTERM
427   if(SIG_ERR != old_sigterm_handler)
428     (void)signal(SIGTERM, old_sigterm_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     write(test->ofile, &c, 1);
609     skipit:
610     prevchar = c;
611   }
612   return count;
613 }
614
615 /* When an error has occurred, it is possible that the two sides are out of
616  * synch.  Ie: that what I think is the other side's response to packet N is
617  * really their response to packet N-1.
618  *
619  * So, to try to prevent that, we flush all the input queued up for us on the
620  * network connection on our host.
621  *
622  * We return the number of packets we flushed (mostly for reporting when trace
623  * is active).
624  */
625
626 static int synchnet(curl_socket_t f /* socket to flush */)
627 {
628
629 #if defined(HAVE_IOCTLSOCKET)
630   unsigned long i;
631 #else
632   int i;
633 #endif
634   int j = 0;
635   char rbuf[PKTSIZE];
636   srvr_sockaddr_union_t fromaddr;
637   curl_socklen_t fromaddrlen;
638
639   for (;;) {
640 #if defined(HAVE_IOCTLSOCKET)
641     (void) ioctlsocket(f, FIONREAD, &i);
642 #else
643     (void) ioctl(f, FIONREAD, &i);
644 #endif
645     if (i) {
646       j++;
647 #ifdef ENABLE_IPV6
648       if(!use_ipv6)
649 #endif
650         fromaddrlen = sizeof(fromaddr.sa4);
651 #ifdef ENABLE_IPV6
652       else
653         fromaddrlen = sizeof(fromaddr.sa6);
654 #endif
655       (void) recvfrom(f, rbuf, sizeof(rbuf), 0,
656                       &fromaddr.sa, &fromaddrlen);
657     }
658     else
659       break;
660   }
661   return j;
662 }
663
664 int main(int argc, char **argv)
665 {
666   srvr_sockaddr_union_t me;
667   struct tftphdr *tp;
668   ssize_t n = 0;
669   int arg = 1;
670   unsigned short port = DEFAULT_PORT;
671   curl_socket_t sock = CURL_SOCKET_BAD;
672   int flag;
673   int rc;
674   int error;
675   long pid;
676   struct testcase test;
677   int result = 0;
678
679   memset(&test, 0, sizeof(test));
680
681   while(argc>arg) {
682     if(!strcmp("--version", argv[arg])) {
683       printf("tftpd IPv4%s\n",
684 #ifdef ENABLE_IPV6
685              "/IPv6"
686 #else
687              ""
688 #endif
689              );
690       return 0;
691     }
692     else if(!strcmp("--pidfile", argv[arg])) {
693       arg++;
694       if(argc>arg)
695         pidname = argv[arg++];
696     }
697     else if(!strcmp("--logfile", argv[arg])) {
698       arg++;
699       if(argc>arg)
700         serverlogfile = argv[arg++];
701     }
702     else if(!strcmp("--ipv4", argv[arg])) {
703 #ifdef ENABLE_IPV6
704       ipv_inuse = "IPv4";
705       use_ipv6 = FALSE;
706 #endif
707       arg++;
708     }
709     else if(!strcmp("--ipv6", argv[arg])) {
710 #ifdef ENABLE_IPV6
711       ipv_inuse = "IPv6";
712       use_ipv6 = TRUE;
713 #endif
714       arg++;
715     }
716     else if(!strcmp("--port", argv[arg])) {
717       arg++;
718       if(argc>arg) {
719         char *endptr;
720         unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
721         if((endptr != argv[arg] + strlen(argv[arg])) ||
722            (ulnum < 1025UL) || (ulnum > 65535UL)) {
723           fprintf(stderr, "tftpd: invalid --port argument (%s)\n",
724                   argv[arg]);
725           return 0;
726         }
727         port = curlx_ultous(ulnum);
728         arg++;
729       }
730     }
731     else if(!strcmp("--srcdir", argv[arg])) {
732       arg++;
733       if(argc>arg) {
734         path = argv[arg];
735         arg++;
736       }
737     }
738     else {
739       puts("Usage: tftpd [option]\n"
740            " --version\n"
741            " --logfile [file]\n"
742            " --pidfile [file]\n"
743            " --ipv4\n"
744            " --ipv6\n"
745            " --port [port]\n"
746            " --srcdir [path]");
747       return 0;
748     }
749   }
750
751 #ifdef WIN32
752   win32_init();
753   atexit(win32_cleanup);
754 #endif
755
756   install_signal_handlers();
757
758   pid = (long)getpid();
759
760 #ifdef ENABLE_IPV6
761   if(!use_ipv6)
762 #endif
763     sock = socket(AF_INET, SOCK_DGRAM, 0);
764 #ifdef ENABLE_IPV6
765   else
766     sock = socket(AF_INET6, SOCK_DGRAM, 0);
767 #endif
768
769   if(CURL_SOCKET_BAD == sock) {
770     error = SOCKERRNO;
771     logmsg("Error creating socket: (%d) %s",
772            error, strerror(error));
773     result = 1;
774     goto tftpd_cleanup;
775   }
776
777   flag = 1;
778   if (0 != setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
779             (void *)&flag, sizeof(flag))) {
780     error = SOCKERRNO;
781     logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
782            error, strerror(error));
783     result = 1;
784     goto tftpd_cleanup;
785   }
786
787 #ifdef ENABLE_IPV6
788   if(!use_ipv6) {
789 #endif
790     memset(&me.sa4, 0, sizeof(me.sa4));
791     me.sa4.sin_family = AF_INET;
792     me.sa4.sin_addr.s_addr = INADDR_ANY;
793     me.sa4.sin_port = htons(port);
794     rc = bind(sock, &me.sa, sizeof(me.sa4));
795 #ifdef ENABLE_IPV6
796   }
797   else {
798     memset(&me.sa6, 0, sizeof(me.sa6));
799     me.sa6.sin6_family = AF_INET6;
800     me.sa6.sin6_addr = in6addr_any;
801     me.sa6.sin6_port = htons(port);
802     rc = bind(sock, &me.sa, sizeof(me.sa6));
803   }
804 #endif /* ENABLE_IPV6 */
805   if(0 != rc) {
806     error = SOCKERRNO;
807     logmsg("Error binding socket on port %hu: (%d) %s",
808            port, error, strerror(error));
809     result = 1;
810     goto tftpd_cleanup;
811   }
812
813   wrotepidfile = write_pidfile(pidname);
814   if(!wrotepidfile) {
815     result = 1;
816     goto tftpd_cleanup;
817   }
818
819   logmsg("Running %s version on port UDP/%d", ipv_inuse, (int)port);
820
821   for (;;) {
822     fromlen = sizeof(from);
823 #ifdef ENABLE_IPV6
824     if(!use_ipv6)
825 #endif
826       fromlen = sizeof(from.sa4);
827 #ifdef ENABLE_IPV6
828     else
829       fromlen = sizeof(from.sa6);
830 #endif
831     n = (ssize_t)recvfrom(sock, &buf.storage[0], sizeof(buf.storage), 0,
832                           &from.sa, &fromlen);
833     if(got_exit_signal)
834       break;
835     if (n < 0) {
836       logmsg("recvfrom");
837       result = 3;
838       break;
839     }
840
841     set_advisor_read_lock(SERVERLOGS_LOCK);
842     serverlogslocked = 1;
843
844 #ifdef ENABLE_IPV6
845     if(!use_ipv6) {
846 #endif
847       from.sa4.sin_family = AF_INET;
848       peer = socket(AF_INET, SOCK_DGRAM, 0);
849       if(CURL_SOCKET_BAD == peer) {
850         logmsg("socket");
851         result = 2;
852         break;
853       }
854       if(connect(peer, &from.sa, sizeof(from.sa4)) < 0) {
855         logmsg("connect: fail");
856         result = 1;
857         break;
858       }
859 #ifdef ENABLE_IPV6
860     }
861     else {
862       from.sa6.sin6_family = AF_INET6;
863       peer = socket(AF_INET6, SOCK_DGRAM, 0);
864       if(CURL_SOCKET_BAD == peer) {
865         logmsg("socket");
866         result = 2;
867         break;
868       }
869       if (connect(peer, &from.sa, sizeof(from.sa6)) < 0) {
870         logmsg("connect: fail");
871         result = 1;
872         break;
873       }
874     }
875 #endif
876
877     maxtimeout = 5*TIMEOUT;
878
879     tp = &buf.hdr;
880     tp->th_opcode = ntohs(tp->th_opcode);
881     if (tp->th_opcode == opcode_RRQ || tp->th_opcode == opcode_WRQ) {
882       memset(&test, 0, sizeof(test));
883       if (do_tftp(&test, tp, n) < 0)
884         break;
885       if(test.buffer)
886         free(test.buffer);
887     }
888     sclose(peer);
889     peer = CURL_SOCKET_BAD;
890
891     if(test.ofile > 0) {
892       close(test.ofile);
893       test.ofile = 0;
894     }
895
896     if(got_exit_signal)
897       break;
898
899     if(serverlogslocked) {
900       serverlogslocked = 0;
901       clear_advisor_read_lock(SERVERLOGS_LOCK);
902     }
903
904     logmsg("end of one transfer");
905
906   }
907
908 tftpd_cleanup:
909
910   if(test.ofile > 0)
911     close(test.ofile);
912
913   if((peer != sock) && (peer != CURL_SOCKET_BAD))
914     sclose(peer);
915
916   if(sock != CURL_SOCKET_BAD)
917     sclose(sock);
918
919   if(got_exit_signal)
920     logmsg("signalled to die");
921
922   if(wrotepidfile)
923     unlink(pidname);
924
925   if(serverlogslocked) {
926     serverlogslocked = 0;
927     clear_advisor_read_lock(SERVERLOGS_LOCK);
928   }
929
930   restore_signal_handlers();
931
932   if(got_exit_signal) {
933     logmsg("========> %s tftpd (port: %d pid: %ld) exits with signal (%d)",
934            ipv_inuse, (int)port, pid, exit_signal);
935     /*
936      * To properly set the return status of the process we
937      * must raise the same signal SIGINT or SIGTERM that we
938      * caught and let the old handler take care of it.
939      */
940     raise(exit_signal);
941   }
942
943   logmsg("========> tftpd quits");
944   return result;
945 }
946
947 /*
948  * Handle initial connection protocol.
949  */
950 static int do_tftp(struct testcase *test, struct tftphdr *tp, ssize_t size)
951 {
952   char *cp;
953   int first = 1, ecode;
954   struct formats *pf;
955   char *filename, *mode = NULL;
956   int error;
957   FILE *server;
958
959   /* Open request dump file. */
960   server = fopen(REQUEST_DUMP, "ab");
961   if(!server) {
962     error = ERRNO;
963     logmsg("fopen() failed with error: %d %s", error, strerror(error));
964     logmsg("Error opening file: %s", REQUEST_DUMP);
965     return -1;
966   }
967
968   /* store input protocol */
969   fprintf(server, "opcode: %x\n", tp->th_opcode);
970
971   cp = (char *)&tp->th_stuff;
972   filename = cp;
973 again:
974   while (cp < &buf.storage[size]) {
975     if (*cp == '\0')
976       break;
977     cp++;
978   }
979   if (*cp) {
980     nak(EBADOP);
981     fclose(server);
982     return 3;
983   }
984   if (first) {
985     mode = ++cp;
986     first = 0;
987     goto again;
988   }
989   /* store input protocol */
990   fprintf(server, "filename: %s\n", filename);
991
992   for (cp = mode; cp && *cp; cp++)
993     if(ISUPPER(*cp))
994       *cp = (char)tolower((int)*cp);
995
996   /* store input protocol */
997   fprintf(server, "mode: %s\n", mode);
998   fclose(server);
999
1000   for (pf = formata; pf->f_mode; pf++)
1001     if (strcmp(pf->f_mode, mode) == 0)
1002       break;
1003   if (!pf->f_mode) {
1004     nak(EBADOP);
1005     return 2;
1006   }
1007   ecode = validate_access(test, filename, tp->th_opcode);
1008   if (ecode) {
1009     nak(ecode);
1010     return 1;
1011   }
1012   if (tp->th_opcode == opcode_WRQ)
1013     recvtftp(test, pf);
1014   else
1015     sendtftp(test, pf);
1016
1017   return 0;
1018 }
1019
1020 /*
1021  * Validate file access.
1022  */
1023 static int validate_access(struct testcase *test,
1024                            const char *filename, int mode)
1025 {
1026   char *ptr;
1027   long testno, partno;
1028   int error;
1029   char partbuf[80]="data";
1030
1031   logmsg("trying to get file: %s mode %x", filename, mode);
1032
1033   if(!strncmp("verifiedserver", filename, 14)) {
1034     char weare[128];
1035     size_t count = sprintf(weare, "WE ROOLZ: %ld\r\n", (long)getpid());
1036
1037     logmsg("Are-we-friendly question received");
1038     test->buffer = strdup(weare);
1039     test->rptr = test->buffer; /* set read pointer */
1040     test->bufsize = count;    /* set total count */
1041     test->rcount = count;     /* set data left to read */
1042     return 0; /* fine */
1043   }
1044
1045   /* find the last slash */
1046   ptr = strrchr(filename, '/');
1047
1048   if(ptr) {
1049     char *file;
1050
1051     ptr++; /* skip the slash */
1052
1053     /* skip all non-numericals following the slash */
1054     while(*ptr && !ISDIGIT(*ptr))
1055       ptr++;
1056
1057     /* get the number */
1058     testno = strtol(ptr, &ptr, 10);
1059
1060     if(testno > 10000) {
1061       partno = testno % 10000;
1062       testno /= 10000;
1063     }
1064     else
1065       partno = 0;
1066
1067
1068     logmsg("requested test number %ld part %ld", testno, partno);
1069
1070     test->num = testno;
1071
1072     file = test2file(testno);
1073
1074     if(0 != partno)
1075       sprintf(partbuf, "data%ld", partno);
1076
1077     if(file) {
1078       FILE *stream=fopen(file, "rb");
1079       if(!stream) {
1080         error = ERRNO;
1081         logmsg("fopen() failed with error: %d %s", error, strerror(error));
1082         logmsg("Error opening file: %s", file);
1083         logmsg("Couldn't open test file: %s", file);
1084         return EACCESS;
1085       }
1086       else {
1087         size_t count;
1088         error = getpart(&test->buffer, &count, "reply", partbuf, stream);
1089         fclose(stream);
1090         if(error) {
1091           logmsg("getpart() failed with error: %d", error);
1092           return EACCESS;
1093         }
1094         if(test->buffer) {
1095           test->rptr = test->buffer; /* set read pointer */
1096           test->bufsize = count;    /* set total count */
1097           test->rcount = count;     /* set data left to read */
1098         }
1099         else
1100           return EACCESS;
1101       }
1102
1103     }
1104     else
1105       return EACCESS;
1106   }
1107   else {
1108     logmsg("no slash found in path");
1109     return EACCESS; /* failure */
1110   }
1111
1112   logmsg("file opened and all is good");
1113   return 0;
1114 }
1115
1116 /*
1117  * Send the requested file.
1118  */
1119 static void sendtftp(struct testcase *test, struct formats *pf)
1120 {
1121   int size;
1122   ssize_t n;
1123   sendblock = 1;
1124 #if defined(HAVE_ALARM) && defined(SIGALRM)
1125   mysignal(SIGALRM, timer);
1126 #endif
1127   sdp = r_init();
1128   sap = &ackbuf.hdr;
1129   do {
1130     size = readit(test, &sdp, pf->f_convert);
1131     if (size < 0) {
1132       nak(ERRNO + 100);
1133       return;
1134     }
1135     sdp->th_opcode = htons((u_short)opcode_DATA);
1136     sdp->th_block = htons((u_short)sendblock);
1137     timeout = 0;
1138 #ifdef HAVE_SIGSETJMP
1139     (void) sigsetjmp(timeoutbuf, 1);
1140 #endif
1141     send_data:
1142     if (swrite(peer, sdp, size + 4) != size + 4) {
1143       logmsg("write");
1144       return;
1145     }
1146     read_ahead(test, pf->f_convert);
1147     for ( ; ; ) {
1148 #ifdef HAVE_ALARM
1149       alarm(rexmtval);        /* read the ack */
1150 #endif
1151       n = sread(peer, &ackbuf.storage[0], sizeof(ackbuf.storage));
1152 #ifdef HAVE_ALARM
1153       alarm(0);
1154 #endif
1155       if(got_exit_signal)
1156         return;
1157       if (n < 0) {
1158         logmsg("read: fail");
1159         return;
1160       }
1161       sap->th_opcode = ntohs((u_short)sap->th_opcode);
1162       sap->th_block = ntohs((u_short)sap->th_block);
1163
1164       if (sap->th_opcode == opcode_ERROR) {
1165         logmsg("got ERROR");
1166         return;
1167       }
1168
1169       if (sap->th_opcode == opcode_ACK) {
1170         if (sap->th_block == sendblock) {
1171           break;
1172         }
1173         /* Re-synchronize with the other side */
1174         (void) synchnet(peer);
1175         if (sap->th_block == (sendblock-1)) {
1176           goto send_data;
1177         }
1178       }
1179
1180     }
1181     sendblock++;
1182   } while (size == SEGSIZE);
1183 }
1184
1185 /*
1186  * Receive a file.
1187  */
1188 static void recvtftp(struct testcase *test, struct formats *pf)
1189 {
1190   ssize_t n, size;
1191   recvblock = 0;
1192 #if defined(HAVE_ALARM) && defined(SIGALRM)
1193   mysignal(SIGALRM, timer);
1194 #endif
1195   rdp = w_init();
1196   rap = &ackbuf.hdr;
1197   do {
1198     timeout = 0;
1199     rap->th_opcode = htons((u_short)opcode_ACK);
1200     rap->th_block = htons((u_short)recvblock);
1201     recvblock++;
1202 #ifdef HAVE_SIGSETJMP
1203     (void) sigsetjmp(timeoutbuf, 1);
1204 #endif
1205 send_ack:
1206     if (swrite(peer, &ackbuf.storage[0], 4) != 4) {
1207       logmsg("write: fail\n");
1208       goto abort;
1209     }
1210     write_behind(test, pf->f_convert);
1211     for ( ; ; ) {
1212 #ifdef HAVE_ALARM
1213       alarm(rexmtval);
1214 #endif
1215       n = sread(peer, rdp, PKTSIZE);
1216 #ifdef HAVE_ALARM
1217       alarm(0);
1218 #endif
1219       if(got_exit_signal)
1220         goto abort;
1221       if (n < 0) {                       /* really? */
1222         logmsg("read: fail\n");
1223         goto abort;
1224       }
1225       rdp->th_opcode = ntohs((u_short)rdp->th_opcode);
1226       rdp->th_block = ntohs((u_short)rdp->th_block);
1227       if (rdp->th_opcode == opcode_ERROR)
1228         goto abort;
1229       if (rdp->th_opcode == opcode_DATA) {
1230         if (rdp->th_block == recvblock) {
1231           break;                         /* normal */
1232         }
1233         /* Re-synchronize with the other side */
1234         (void) synchnet(peer);
1235         if (rdp->th_block == (recvblock-1))
1236           goto send_ack;                 /* rexmit */
1237       }
1238     }
1239
1240     size = writeit(test, &rdp, (int)(n - 4), pf->f_convert);
1241     if (size != (n-4)) {                 /* ahem */
1242       if (size < 0)
1243         nak(ERRNO + 100);
1244       else
1245         nak(ENOSPACE);
1246       goto abort;
1247     }
1248   } while (size == SEGSIZE);
1249   write_behind(test, pf->f_convert);
1250
1251   rap->th_opcode = htons((u_short)opcode_ACK);  /* send the "final" ack */
1252   rap->th_block = htons((u_short)recvblock);
1253   (void) swrite(peer, &ackbuf.storage[0], 4);
1254 #if defined(HAVE_ALARM) && defined(SIGALRM)
1255   mysignal(SIGALRM, justtimeout);        /* just abort read on timeout */
1256   alarm(rexmtval);
1257 #endif
1258   /* normally times out and quits */
1259   n = sread(peer, &buf.storage[0], sizeof(buf.storage));
1260 #ifdef HAVE_ALARM
1261   alarm(0);
1262 #endif
1263   if(got_exit_signal)
1264     goto abort;
1265   if (n >= 4 &&                               /* if read some data */
1266       rdp->th_opcode == opcode_DATA &&        /* and got a data block */
1267       recvblock == rdp->th_block) {           /* then my last ack was lost */
1268     (void) swrite(peer, &ackbuf.storage[0], 4);  /* resend final ack */
1269   }
1270 abort:
1271   return;
1272 }
1273
1274 /*
1275  * Send a nak packet (error message).  Error code passed in is one of the
1276  * standard TFTP codes, or a UNIX errno offset by 100.
1277  */
1278 static void nak(int error)
1279 {
1280   struct tftphdr *tp;
1281   int length;
1282   struct errmsg *pe;
1283
1284   tp = &buf.hdr;
1285   tp->th_opcode = htons((u_short)opcode_ERROR);
1286   tp->th_code = htons((u_short)error);
1287   for (pe = errmsgs; pe->e_code >= 0; pe++)
1288     if (pe->e_code == error)
1289       break;
1290   if (pe->e_code < 0) {
1291     pe->e_msg = strerror(error - 100);
1292     tp->th_code = EUNDEF;   /* set 'undef' errorcode */
1293   }
1294   strcpy(tp->th_msg, pe->e_msg);
1295   length = (int)strlen(pe->e_msg);
1296   tp->th_msg[length] = '\0';
1297   length += 5;
1298   if (swrite(peer, &buf.storage[0], length) != length)
1299     logmsg("nak: fail\n");
1300 }