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