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