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