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