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