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