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