~ubuntu-branches/ubuntu/feisty/curl/feisty

« back to all changes in this revision

Viewing changes to tests/server/tftpd.c

  • Committer: Bazaar Package Importer
  • Author(s): Martin Pitt
  • Date: 2005-12-12 15:04:52 UTC
  • mfrom: (1.1.4 upstream)
  • Revision ID: james.westby@ubuntu.com-20051212150452-2ymlra67b2p7kjyy
Tags: 7.15.1-1ubuntu1
Resynchronise with Debian to get URL parser overflow fix from 7.15.1
(CVE-2005-4077).

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/***************************************************************************
 
2
 *                                  _   _ ____  _
 
3
 *  Project                     ___| | | |  _ \| |
 
4
 *                             / __| | | | |_) | |
 
5
 *                            | (__| |_| |  _ <| |___
 
6
 *                             \___|\___/|_| \_\_____|
 
7
 *
 
8
 * $Id: tftpd.c,v 1.10 2005/12/06 07:47:37 bagder Exp $
 
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
#ifdef HAVE_SYS_TYPES_H
 
53
#include <sys/types.h>
 
54
#endif
 
55
#ifdef HAVE_SYS_IOCTL_H
 
56
#include <sys/ioctl.h>
 
57
#endif
 
58
#ifdef HAVE_SYS_STAT_H
 
59
#include <sys/stat.h>
 
60
#endif
 
61
 
 
62
#include <signal.h>
 
63
 
 
64
#ifdef HAVE_FCNTL_H
 
65
#include <fcntl.h>
 
66
#endif
 
67
#ifdef HAVE_SYS_SOCKET_H
 
68
#include <sys/socket.h>
 
69
#endif
 
70
#ifdef HAVE_NETINET_IN_H
 
71
#include <netinet/in.h>
 
72
#endif
 
73
#ifdef HAVE_ARPA_TFTP_H
 
74
#include <arpa/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
#include <stdio.h>
 
86
#include <errno.h>
 
87
#include <ctype.h>
 
88
#include <string.h>
 
89
#include <stdlib.h>
 
90
#include <unistd.h>
 
91
#include <pwd.h>
 
92
#include <grp.h>
 
93
 
 
94
#define ENABLE_CURLX_PRINTF
 
95
/* make the curlx header define all printf() functions to use the curlx_*
 
96
   versions instead */
 
97
#include "curlx.h" /* from the private lib dir */
 
98
#include "getpart.h"
 
99
#include "util.h"
 
100
 
 
101
/* include memdebug.h last */
 
102
#include "memdebug.h"
 
103
 
 
104
struct testcase {
 
105
  char *buffer;   /* holds the file data to send to the client */
 
106
  size_t bufsize; /* size of the data in buffer */
 
107
  char *rptr;     /* read pointer into the buffer */
 
108
  size_t rcount;  /* amount of data left to read of the file */
 
109
  long num;       /* test case number */
 
110
  int ofile;      /* file descriptor for output file when uploading to us */
 
111
  FILE *server;   /* write input "protocol" there for client verification */
 
112
};
 
113
 
 
114
static int synchnet(int);
 
115
static struct tftphdr *r_init(void);
 
116
static struct tftphdr *w_init(void);
 
117
static int readit(struct testcase *test, struct tftphdr **dpp, int convert);
 
118
static int writeit(struct testcase *test, struct tftphdr **dpp, int ct,
 
119
                   int convert);
 
120
static void mysignal(int, void (*func)(int));
 
121
 
 
122
 
 
123
#define TIMEOUT         5
 
124
 
 
125
#define PKTSIZE SEGSIZE+4
 
126
 
 
127
struct formats;
 
128
static int tftp(struct testcase *test, struct tftphdr *tp, int size);
 
129
static void nak(int error);
 
130
static void sendtftp(struct testcase *test, struct formats *pf);
 
131
static void recvtftp(struct testcase *test, struct formats *pf);
 
132
static int validate_access(struct testcase *test, const char *, int);
 
133
 
 
134
static curl_socket_t peer;
 
135
static int rexmtval = TIMEOUT;
 
136
static int maxtimeout = 5*TIMEOUT;
 
137
 
 
138
static char buf[PKTSIZE];
 
139
static char ackbuf[PKTSIZE];
 
140
static struct sockaddr_in from;
 
141
static socklen_t fromlen;
 
142
 
 
143
struct bf {
 
144
  int counter;            /* size of data in buffer, or flag */
 
145
  char buf[PKTSIZE];      /* room for data packet */
 
146
} bfs[2];
 
147
 
 
148
                                /* Values for bf.counter  */
 
149
#define BF_ALLOC -3             /* alloc'd but not yet filled */
 
150
#define BF_FREE  -2             /* free */
 
151
/* [-1 .. SEGSIZE] = size of data in the data buffer */
 
152
 
 
153
static int nextone;     /* index of next buffer to use */
 
154
static int current;     /* index of buffer in use */
 
155
 
 
156
                        /* control flags for crlf conversions */
 
157
int newline = 0;        /* fillbuf: in middle of newline expansion */
 
158
int prevchar = -1;      /* putbuf: previous char (cr check) */
 
159
 
 
160
static void read_ahead(struct testcase *test,
 
161
                       int convert /* if true, convert to ascii */);
 
162
static int write_behind(struct testcase *test, int convert);
 
163
static struct tftphdr *rw_init(int);
 
164
static struct tftphdr *w_init(void) { return rw_init(0); } /* write-behind */
 
165
static struct tftphdr *r_init(void) { return rw_init(1); } /* read-ahead */
 
166
 
 
167
static struct tftphdr *
 
168
rw_init(int x)              /* init for either read-ahead or write-behind */
 
169
{                           /* zero for write-behind, one for read-head */
 
170
  newline = 0;            /* init crlf flag */
 
171
  prevchar = -1;
 
172
  bfs[0].counter =  BF_ALLOC;     /* pass out the first buffer */
 
173
  current = 0;
 
174
  bfs[1].counter = BF_FREE;
 
175
  nextone = x;                    /* ahead or behind? */
 
176
  return (struct tftphdr *)bfs[0].buf;
 
177
}
 
178
 
 
179
 
 
180
/* Have emptied current buffer by sending to net and getting ack.
 
181
   Free it and return next buffer filled with data.
 
182
 */
 
183
static int readit(struct testcase *test, struct tftphdr **dpp,
 
184
           int convert /* if true, convert to ascii */)
 
185
{
 
186
  struct bf *b;
 
187
 
 
188
  bfs[current].counter = BF_FREE; /* free old one */
 
189
  current = !current;             /* "incr" current */
 
190
 
 
191
  b = &bfs[current];              /* look at new buffer */
 
192
  if (b->counter == BF_FREE)      /* if it's empty */
 
193
    read_ahead(test, convert);      /* fill it */
 
194
 
 
195
  *dpp = (struct tftphdr *)b->buf;        /* set caller's ptr */
 
196
  return b->counter;
 
197
}
 
198
 
 
199
#undef MIN /* some systems have this defined already, some don't */
 
200
#define MIN(x,y) ((x)<(y)?(x):(y));
 
201
 
 
202
/*
 
203
 * fill the input buffer, doing ascii conversions if requested
 
204
 * conversions are  lf -> cr,lf  and cr -> cr, nul
 
205
 */
 
206
static void read_ahead(struct testcase *test,
 
207
                       int convert /* if true, convert to ascii */)
 
208
{
 
209
  int i;
 
210
  char *p;
 
211
  int c;
 
212
  struct bf *b;
 
213
  struct tftphdr *dp;
 
214
 
 
215
  b = &bfs[nextone];              /* look at "next" buffer */
 
216
  if (b->counter != BF_FREE)      /* nop if not free */
 
217
    return;
 
218
  nextone = !nextone;             /* "incr" next buffer ptr */
 
219
 
 
220
  dp = (struct tftphdr *)b->buf;
 
221
 
 
222
  if (convert == 0) {
 
223
    /* The former file reading code did this:
 
224
       b->counter = read(fileno(file), dp->th_data, SEGSIZE); */
 
225
    size_t copy_n = MIN(SEGSIZE, test->rcount);
 
226
    memcpy(dp->th_data, test->rptr, copy_n);
 
227
 
 
228
    /* decrease amount, advance pointer */
 
229
    test->rcount -= copy_n;
 
230
    test->rptr += copy_n;
 
231
    b->counter = (int)copy_n;
 
232
    return;
 
233
  }
 
234
 
 
235
  p = dp->th_data;
 
236
  for (i = 0 ; i < SEGSIZE; i++) {
 
237
    if (newline) {
 
238
      if (prevchar == '\n')
 
239
        c = '\n';       /* lf to cr,lf */
 
240
      else
 
241
        c = '\0';       /* cr to cr,nul */
 
242
      newline = 0;
 
243
    }
 
244
    else {
 
245
      if(test->rcount) {
 
246
        c=test->rptr[0];
 
247
        test->rptr++;
 
248
        test->rcount--;
 
249
      }
 
250
      else
 
251
        break;
 
252
      if (c == '\n' || c == '\r') {
 
253
        prevchar = c;
 
254
        c = '\r';
 
255
        newline = 1;
 
256
      }
 
257
    }
 
258
    *p++ = c;
 
259
  }
 
260
  b->counter = (int)(p - dp->th_data);
 
261
}
 
262
 
 
263
/* Update count associated with the buffer, get new buffer from the queue.
 
264
   Calls write_behind only if next buffer not available.
 
265
 */
 
266
static int writeit(struct testcase *test, struct tftphdr **dpp,
 
267
                   int ct, int convert)
 
268
{
 
269
  bfs[current].counter = ct;      /* set size of data to write */
 
270
  current = !current;             /* switch to other buffer */
 
271
  if (bfs[current].counter != BF_FREE)     /* if not free */
 
272
    write_behind(test, convert);     /* flush it */
 
273
  bfs[current].counter = BF_ALLOC;        /* mark as alloc'd */
 
274
  *dpp =  (struct tftphdr *)bfs[current].buf;
 
275
  return ct;                      /* this is a lie of course */
 
276
}
 
277
 
 
278
/*
 
279
 * Output a buffer to a file, converting from netascii if requested.
 
280
 * CR,NUL -> CR  and CR,LF => LF.
 
281
 * Note spec is undefined if we get CR as last byte of file or a
 
282
 * CR followed by anything else.  In this case we leave it alone.
 
283
 */
 
284
static int write_behind(struct testcase *test, int convert)
 
285
{
 
286
  char *buf;
 
287
  int count;
 
288
  int ct;
 
289
  char *p;
 
290
  int c;                          /* current character */
 
291
  struct bf *b;
 
292
  struct tftphdr *dp;
 
293
 
 
294
  b = &bfs[nextone];
 
295
  if (b->counter < -1)            /* anything to flush? */
 
296
    return 0;                     /* just nop if nothing to do */
 
297
 
 
298
  if(!test->ofile) {
 
299
    char outfile[256];
 
300
    snprintf(outfile, sizeof(outfile), "log/upload.%ld", test->num);
 
301
    test->ofile=open(outfile, O_CREAT|O_RDWR, 0777);
 
302
    if(test->ofile == -1) {
 
303
      logmsg("Couldn't create and/or open file %s for upload!", outfile);
 
304
      return -1; /* failure! */
 
305
    }
 
306
  }
 
307
 
 
308
  count = b->counter;             /* remember byte count */
 
309
  b->counter = BF_FREE;           /* reset flag */
 
310
  dp = (struct tftphdr *)b->buf;
 
311
  nextone = !nextone;             /* incr for next time */
 
312
  buf = dp->th_data;
 
313
 
 
314
  if (count <= 0)
 
315
    return -1;                    /* nak logic? */
 
316
 
 
317
  if (convert == 0)
 
318
    return write(test->ofile, buf, count);
 
319
 
 
320
  p = buf;
 
321
  ct = count;
 
322
  while (ct--) {                  /* loop over the buffer */
 
323
    c = *p++;                     /* pick up a character */
 
324
    if (prevchar == '\r') {       /* if prev char was cr */
 
325
      if (c == '\n')              /* if have cr,lf then just */
 
326
        lseek(test->ofile, -1, SEEK_CUR); /* smash lf on top of the cr */
 
327
      else
 
328
        if (c == '\0')            /* if have cr,nul then */
 
329
          goto skipit;            /* just skip over the putc */
 
330
      /* else just fall through and allow it */
 
331
    }
 
332
    /* formerly
 
333
       putc(c, file); */
 
334
    write(test->ofile, &c, 1);
 
335
    skipit:
 
336
    prevchar = c;
 
337
  }
 
338
  return count;
 
339
}
 
340
 
 
341
 
 
342
/* When an error has occurred, it is possible that the two sides are out of
 
343
 * synch.  Ie: that what I think is the other side's response to packet N is
 
344
 * really their response to packet N-1.
 
345
 *
 
346
 * So, to try to prevent that, we flush all the input queued up for us on the
 
347
 * network connection on our host.
 
348
 *
 
349
 * We return the number of packets we flushed (mostly for reporting when trace
 
350
 * is active).
 
351
 */
 
352
 
 
353
static int synchnet(curl_socket_t f /* socket to flush */)
 
354
{
 
355
  int i, j = 0;
 
356
  char rbuf[PKTSIZE];
 
357
  struct sockaddr_in from;
 
358
  socklen_t fromlen;
 
359
 
 
360
  while (1) {
 
361
    (void) ioctl(f, FIONREAD, &i);
 
362
    if (i) {
 
363
      j++;
 
364
      fromlen = sizeof from;
 
365
      (void) recvfrom(f, rbuf, sizeof (rbuf), 0,
 
366
                      (struct sockaddr *)&from, &fromlen);
 
367
    }
 
368
    else
 
369
      return j;
 
370
  }
 
371
}
 
372
 
 
373
/*
 
374
 * Like signal(), but with well-defined semantics.
 
375
 */
 
376
static void mysignal(int sig, void (*handler)(int))
 
377
{
 
378
  struct sigaction sa;
 
379
  memset(&sa, 0, sizeof(sa));
 
380
  sa.sa_handler = handler;
 
381
  sigaction(sig, &sa, NULL);
 
382
}
 
383
 
 
384
 
 
385
#ifndef DEFAULT_LOGFILE
 
386
#define DEFAULT_LOGFILE "log/tftpd.log"
 
387
#endif
 
388
 
 
389
#define DEFAULT_PORT 8999 /* UDP */
 
390
const char *serverlogfile = DEFAULT_LOGFILE;
 
391
 
 
392
#define REQUEST_DUMP  "log/server.input"
 
393
 
 
394
char use_ipv6=FALSE;
 
395
 
 
396
int main(int argc, char **argv)
 
397
{
 
398
  struct sockaddr_in me;
 
399
#ifdef ENABLE_IPV6
 
400
  struct sockaddr_in6 me6;
 
401
#endif /* ENABLE_IPV6 */
 
402
 
 
403
  struct tftphdr *tp;
 
404
  int n = 0;
 
405
  int arg = 1;
 
406
  FILE *pidfile;
 
407
  char *pidname= (char *)".tftpd.pid";
 
408
  unsigned short port = DEFAULT_PORT;
 
409
  curl_socket_t sock;
 
410
  int flag;
 
411
  int rc;
 
412
  struct testcase test;
 
413
 
 
414
  while(argc>arg) {
 
415
    if(!strcmp("--version", argv[arg])) {
 
416
      printf("tftpd IPv4%s\n",
 
417
#ifdef ENABLE_IPV6
 
418
             "/IPv6"
 
419
#else
 
420
             ""
 
421
#endif
 
422
             );
 
423
      return 0;
 
424
    }
 
425
    else if(!strcmp("--pidfile", argv[arg])) {
 
426
      arg++;
 
427
      if(argc>arg)
 
428
        pidname = argv[arg++];
 
429
    }
 
430
    else if(!strcmp("--ipv6", argv[arg])) {
 
431
#ifdef ENABLE_IPV6
 
432
      use_ipv6=TRUE;
 
433
#endif
 
434
      arg++;
 
435
    }
 
436
    else if(argc>arg) {
 
437
 
 
438
      if(atoi(argv[arg]))
 
439
        port = (unsigned short)atoi(argv[arg++]);
 
440
 
 
441
      if(argc>arg)
 
442
        path = argv[arg++];
 
443
    }
 
444
  }
 
445
 
 
446
#if defined(WIN32) && !defined(__GNUC__) || defined(__MINGW32__)
 
447
  win32_init();
 
448
  atexit(win32_cleanup);
 
449
#endif
 
450
 
 
451
#ifdef ENABLE_IPV6
 
452
  if(!use_ipv6)
 
453
#endif
 
454
    sock = socket(AF_INET, SOCK_DGRAM, 0);
 
455
#ifdef ENABLE_IPV6
 
456
  else
 
457
    sock = socket(AF_INET6, SOCK_DGRAM, 0);
 
458
#endif
 
459
 
 
460
  if (sock < 0) {
 
461
    perror("opening stream socket");
 
462
    logmsg("Error opening socket");
 
463
    exit(1);
 
464
  }
 
465
 
 
466
  flag = 1;
 
467
  if (setsockopt
 
468
      (sock, SOL_SOCKET, SO_REUSEADDR, (const void *) &flag,
 
469
       sizeof(int)) < 0) {
 
470
    perror("setsockopt(SO_REUSEADDR)");
 
471
  }
 
472
 
 
473
#ifdef ENABLE_IPV6
 
474
  if(!use_ipv6) {
 
475
#endif
 
476
    me.sin_family = AF_INET;
 
477
    me.sin_addr.s_addr = INADDR_ANY;
 
478
    me.sin_port = htons(port);
 
479
    rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
 
480
#ifdef ENABLE_IPV6
 
481
  }
 
482
  else {
 
483
    memset(&me6, 0, sizeof(struct sockaddr_in6));
 
484
    me6.sin6_family = AF_INET6;
 
485
    me6.sin6_addr = in6addr_any;
 
486
    me6.sin6_port = htons(port);
 
487
    rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
 
488
  }
 
489
#endif /* ENABLE_IPV6 */
 
490
  if(rc < 0) {
 
491
    perror("binding stream socket");
 
492
    logmsg("Error binding socket");
 
493
    exit(1);
 
494
  }
 
495
 
 
496
  pidfile = fopen(pidname, "w");
 
497
  if(pidfile) {
 
498
    fprintf(pidfile, "%d\n", (int)getpid());
 
499
    fclose(pidfile);
 
500
  }
 
501
  else
 
502
    fprintf(stderr, "Couldn't write pid file\n");
 
503
 
 
504
  logmsg("Running IPv%d version on port UDP/%d",
 
505
#ifdef ENABLE_IPV6
 
506
         (use_ipv6?6:4)
 
507
#else
 
508
         4
 
509
#endif
 
510
         , port );
 
511
 
 
512
  do {
 
513
    FILE *server;
 
514
 
 
515
    fromlen = sizeof(from);
 
516
    n = recvfrom(sock, buf, sizeof (buf), 0,
 
517
                 (struct sockaddr *)&from, &fromlen);
 
518
    if (n < 0) {
 
519
      logmsg("recvfrom:\n");
 
520
      return 3;
 
521
    }
 
522
 
 
523
    from.sin_family = AF_INET;
 
524
 
 
525
    peer = socket(AF_INET, SOCK_DGRAM, 0);
 
526
    if (peer < 0) {
 
527
      logmsg("socket:\n");
 
528
      return 2;
 
529
    }
 
530
 
 
531
    if (connect(peer, (struct sockaddr *)&from, sizeof(from)) < 0) {
 
532
      logmsg("connect: fail\n");
 
533
      return 1;
 
534
    }
 
535
    maxtimeout = 5*TIMEOUT;
 
536
 
 
537
    tp = (struct tftphdr *)buf;
 
538
    tp->th_opcode = ntohs(tp->th_opcode);
 
539
    if (tp->th_opcode == RRQ || tp->th_opcode == WRQ) {
 
540
      memset(&test, 0, sizeof(test));
 
541
      server = fopen(REQUEST_DUMP, "ab");
 
542
      if(!server)
 
543
        break;
 
544
      test.server = server;
 
545
      tftp(&test, tp, n);
 
546
      if(test.buffer)
 
547
        free(test.buffer);
 
548
    }
 
549
    fclose(server);
 
550
    sclose(peer);
 
551
  } while(1);
 
552
  return 0;
 
553
}
 
554
 
 
555
struct formats {
 
556
  const char *f_mode;
 
557
  int f_convert;
 
558
} formats[] = {
 
559
  { "netascii",   1 },
 
560
  { "octet",      0 },
 
561
  { NULL,         0 }
 
562
};
 
563
 
 
564
/*
 
565
 * Handle initial connection protocol.
 
566
 */
 
567
static int tftp(struct testcase *test, struct tftphdr *tp, int size)
 
568
{
 
569
  char *cp;
 
570
  int first = 1, ecode;
 
571
  struct formats *pf;
 
572
  char *filename, *mode = NULL;
 
573
 
 
574
  /* store input protocol */
 
575
  fprintf(test->server, "opcode: %x\n", tp->th_opcode);
 
576
 
 
577
  cp = (char *)&tp->th_stuff;
 
578
  filename = cp;
 
579
again:
 
580
  while (cp < buf + size) {
 
581
    if (*cp == '\0')
 
582
      break;
 
583
    cp++;
 
584
  }
 
585
  if (*cp) {
 
586
    nak(EBADOP);
 
587
    return 3;
 
588
  }
 
589
  if (first) {
 
590
    mode = ++cp;
 
591
    first = 0;
 
592
    goto again;
 
593
  }
 
594
  /* store input protocol */
 
595
  fprintf(test->server, "filename: %s\n", filename);
 
596
 
 
597
  for (cp = mode; *cp; cp++)
 
598
    if (isupper((int)*cp))
 
599
      *cp = tolower((int)*cp);
 
600
 
 
601
  /* store input protocol */
 
602
  fprintf(test->server, "mode: %s\n", mode);
 
603
 
 
604
  for (pf = formats; pf->f_mode; pf++)
 
605
    if (strcmp(pf->f_mode, mode) == 0)
 
606
      break;
 
607
  if (!pf->f_mode) {
 
608
    nak(EBADOP);
 
609
    return 2;
 
610
  }
 
611
  ecode = validate_access(test, filename, tp->th_opcode);
 
612
  if (ecode) {
 
613
    nak(ecode);
 
614
    return 1;
 
615
  }
 
616
  if (tp->th_opcode == WRQ)
 
617
    recvtftp(test, pf);
 
618
  else
 
619
    sendtftp(test, pf);
 
620
 
 
621
  return 0;
 
622
}
 
623
 
 
624
/*
 
625
 * Validate file access.
 
626
 */
 
627
static int validate_access(struct testcase *test,
 
628
                           const char *filename, int mode)
 
629
{
 
630
  char *ptr;
 
631
  long testno;
 
632
 
 
633
  logmsg("trying to get file: %s mode %x", filename, mode);
 
634
 
 
635
  if(!strncmp("/verifiedserver", filename, 15)) {
 
636
    char weare[128];
 
637
    size_t count = sprintf(weare, "WE ROOLZ: %d\r\n", (int)getpid());
 
638
 
 
639
    logmsg("Are-we-friendly question received");
 
640
    test->buffer = strdup(weare);
 
641
    test->rptr = test->buffer; /* set read pointer */
 
642
    test->bufsize = count;    /* set total count */
 
643
    test->rcount = count;     /* set data left to read */
 
644
    return 0; /* fine */
 
645
  }
 
646
 
 
647
  /* find the last slash */
 
648
  ptr = strrchr(filename, '/');
 
649
 
 
650
  if(ptr) {
 
651
    char *file;
 
652
 
 
653
    ptr++; /* skip the slash */
 
654
 
 
655
    /* skip all non-numericals following the slash */
 
656
    while(*ptr && !isdigit((int)*ptr))
 
657
      ptr++;
 
658
 
 
659
    /* get the number */
 
660
    testno = strtol(ptr, &ptr, 10);
 
661
 
 
662
    logmsg("requested test number %d", testno);
 
663
 
 
664
    test->num = testno;
 
665
 
 
666
    file = test2file(testno);
 
667
 
 
668
    if(file) {
 
669
      FILE *stream=fopen(file, "rb");
 
670
      if(!stream) {
 
671
        logmsg("Couldn't open test file: %s", file);
 
672
        return EACCESS;
 
673
      }
 
674
      else {
 
675
        size_t count;
 
676
        test->buffer = (char *)spitout(stream, "reply", "data", &count);
 
677
        fclose(stream);
 
678
        if(test->buffer) {
 
679
          test->rptr = test->buffer; /* set read pointer */
 
680
          test->bufsize = count;    /* set total count */
 
681
          test->rcount = count;     /* set data left to read */
 
682
        }
 
683
        else
 
684
          return EACCESS;
 
685
      }
 
686
 
 
687
    }
 
688
    else
 
689
      return EACCESS;
 
690
  }
 
691
  else {
 
692
    logmsg("no slash found in path");
 
693
    return EACCESS; /* failure */
 
694
  }
 
695
 
 
696
  return 0;
 
697
}
 
698
 
 
699
int timeout;
 
700
sigjmp_buf timeoutbuf;
 
701
 
 
702
static void timer(int signum)
 
703
{
 
704
  (void)signum;
 
705
 
 
706
  logmsg("alarm!");
 
707
 
 
708
  timeout += rexmtval;
 
709
  if (timeout >= maxtimeout)
 
710
    exit(1);
 
711
  siglongjmp(timeoutbuf, 1);
 
712
}
 
713
 
 
714
/*
 
715
 * Send the requested file.
 
716
 */
 
717
static void sendtftp(struct testcase *test, struct formats *pf)
 
718
{
 
719
  struct tftphdr *dp;
 
720
  struct tftphdr *ap;    /* ack packet */
 
721
  unsigned short block = 1;
 
722
  int size, n;
 
723
 
 
724
  mysignal(SIGALRM, timer);
 
725
  dp = r_init();
 
726
  ap = (struct tftphdr *)ackbuf;
 
727
  do {
 
728
    size = readit(test, &dp, pf->f_convert);
 
729
    if (size < 0) {
 
730
      nak(errno + 100);
 
731
      return;
 
732
    }
 
733
    dp->th_opcode = htons((u_short)DATA);
 
734
    dp->th_block = htons((u_short)block);
 
735
    timeout = 0;
 
736
    (void) sigsetjmp(timeoutbuf, 1);
 
737
 
 
738
    send_data:
 
739
    if (send(peer, dp, size + 4, 0) != size + 4) {
 
740
      logmsg("write\n");
 
741
      return;
 
742
    }
 
743
    read_ahead(test, pf->f_convert);
 
744
    for ( ; ; ) {
 
745
      alarm(rexmtval);        /* read the ack */
 
746
      n = recv(peer, ackbuf, sizeof (ackbuf), 0);
 
747
      alarm(0);
 
748
      if (n < 0) {
 
749
        logmsg("read: fail\n");
 
750
        return;
 
751
      }
 
752
      ap->th_opcode = ntohs((u_short)ap->th_opcode);
 
753
      ap->th_block = ntohs((u_short)ap->th_block);
 
754
 
 
755
      if (ap->th_opcode == ERROR) {
 
756
        logmsg("got ERROR");
 
757
        return;
 
758
      }
 
759
 
 
760
      if (ap->th_opcode == ACK) {
 
761
        if (ap->th_block == block) {
 
762
          break;
 
763
        }
 
764
        /* Re-synchronize with the other side */
 
765
        (void) synchnet(peer);
 
766
        if (ap->th_block == (block -1)) {
 
767
          goto send_data;
 
768
        }
 
769
      }
 
770
 
 
771
    }
 
772
    block++;
 
773
  } while (size == SEGSIZE);
 
774
}
 
775
 
 
776
static void justquit(int signum)
 
777
{
 
778
  (void)signum;
 
779
  exit(0);
 
780
}
 
781
 
 
782
 
 
783
/*
 
784
 * Receive a file.
 
785
 */
 
786
static void recvtftp(struct testcase *test, struct formats *pf)
 
787
{
 
788
  struct tftphdr *dp;
 
789
  struct tftphdr *ap;    /* ack buffer */
 
790
  unsigned short block = 0;
 
791
  int n, size;
 
792
 
 
793
  mysignal(SIGALRM, timer);
 
794
  dp = w_init();
 
795
  ap = (struct tftphdr *)ackbuf;
 
796
  do {
 
797
    timeout = 0;
 
798
    ap->th_opcode = htons((u_short)ACK);
 
799
    ap->th_block = htons((u_short)block);
 
800
    block++;
 
801
    (void) sigsetjmp(timeoutbuf, 1);
 
802
send_ack:
 
803
    if (send(peer, ackbuf, 4, 0) != 4) {
 
804
      logmsg("write: fail\n");
 
805
      goto abort;
 
806
    }
 
807
    write_behind(test, pf->f_convert);
 
808
    for ( ; ; ) {
 
809
      alarm(rexmtval);
 
810
      n = recv(peer, dp, PKTSIZE, 0);
 
811
      alarm(0);
 
812
      if (n < 0) {                       /* really? */
 
813
        logmsg("read: fail\n");
 
814
        goto abort;
 
815
      }
 
816
      dp->th_opcode = ntohs((u_short)dp->th_opcode);
 
817
      dp->th_block = ntohs((u_short)dp->th_block);
 
818
      if (dp->th_opcode == ERROR)
 
819
        goto abort;
 
820
      if (dp->th_opcode == DATA) {
 
821
        if (dp->th_block == block) {
 
822
          break;                         /* normal */
 
823
        }
 
824
        /* Re-synchronize with the other side */
 
825
        (void) synchnet(peer);
 
826
        if (dp->th_block == (block-1))
 
827
          goto send_ack;                 /* rexmit */
 
828
      }
 
829
    }
 
830
 
 
831
    size = writeit(test, &dp, n - 4, pf->f_convert);
 
832
    if (size != (n-4)) {                 /* ahem */
 
833
      if (size < 0)
 
834
        nak(errno + 100);
 
835
      else
 
836
        nak(ENOSPACE);
 
837
      goto abort;
 
838
    }
 
839
  } while (size == SEGSIZE);
 
840
  write_behind(test, pf->f_convert);
 
841
 
 
842
  ap->th_opcode = htons((u_short)ACK);   /* send the "final" ack */
 
843
  ap->th_block = htons((u_short)(block));
 
844
  (void) send(peer, ackbuf, 4, 0);
 
845
 
 
846
  mysignal(SIGALRM, justquit);           /* just quit on timeout */
 
847
  alarm(rexmtval);
 
848
  n = recv(peer, buf, sizeof (buf), 0);  /* normally times out and quits */
 
849
  alarm(0);
 
850
  if (n >= 4 &&                          /* if read some data */
 
851
      dp->th_opcode == DATA &&           /* and got a data block */
 
852
      block == dp->th_block) {           /* then my last ack was lost */
 
853
    (void) send(peer, ackbuf, 4, 0);     /* resend final ack */
 
854
  }
 
855
abort:
 
856
  return;
 
857
}
 
858
 
 
859
struct errmsg {
 
860
  int e_code;
 
861
  const char *e_msg;
 
862
} errmsgs[] = {
 
863
  { EUNDEF,       "Undefined error code" },
 
864
  { ENOTFOUND,    "File not found" },
 
865
  { EACCESS,      "Access violation" },
 
866
  { ENOSPACE,     "Disk full or allocation exceeded" },
 
867
  { EBADOP,       "Illegal TFTP operation" },
 
868
  { EBADID,       "Unknown transfer ID" },
 
869
  { EEXISTS,      "File already exists" },
 
870
  { ENOUSER,      "No such user" },
 
871
  { -1,           0 }
 
872
};
 
873
 
 
874
/*
 
875
 * Send a nak packet (error message).  Error code passed in is one of the
 
876
 * standard TFTP codes, or a UNIX errno offset by 100.
 
877
 */
 
878
static void nak(int error)
 
879
{
 
880
  struct tftphdr *tp;
 
881
  int length;
 
882
  struct errmsg *pe;
 
883
 
 
884
  tp = (struct tftphdr *)buf;
 
885
  tp->th_opcode = htons((u_short)ERROR);
 
886
  tp->th_code = htons((u_short)error);
 
887
  for (pe = errmsgs; pe->e_code >= 0; pe++)
 
888
    if (pe->e_code == error)
 
889
      break;
 
890
  if (pe->e_code < 0) {
 
891
    pe->e_msg = strerror(error - 100);
 
892
    tp->th_code = EUNDEF;   /* set 'undef' errorcode */
 
893
  }
 
894
  strcpy(tp->th_msg, pe->e_msg);
 
895
  length = (int)strlen(pe->e_msg);
 
896
  tp->th_msg[length] = '\0';
 
897
  length += 5;
 
898
  if (send(peer, buf, length, 0) != length)
 
899
    logmsg("nak: fail\n");
 
900
}