Grant Erickson fixed timeouts for TFTP
[platform/upstream/curl.git] / lib / tftp.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2008, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at http://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  * $Id$
22  ***************************************************************************/
23
24 #include "setup.h"
25
26 #ifndef CURL_DISABLE_TFTP
27 /* -- WIN32 approved -- */
28 #include <stdio.h>
29 #include <string.h>
30 #include <stdarg.h>
31 #include <stdlib.h>
32 #include <ctype.h>
33
34 #if defined(WIN32)
35 #include <time.h>
36 #include <io.h>
37 #else
38 #ifdef HAVE_SYS_SOCKET_H
39 #include <sys/socket.h>
40 #endif
41 #include <netinet/in.h>
42 #ifdef HAVE_SYS_TIME_H
43 #include <sys/time.h>
44 #endif
45 #ifdef HAVE_UNISTD_H
46 #include <unistd.h>
47 #endif
48 #include <netdb.h>
49 #ifdef HAVE_ARPA_INET_H
50 #include <arpa/inet.h>
51 #endif
52 #ifdef HAVE_NET_IF_H
53 #include <net/if.h>
54 #endif
55 #ifdef HAVE_SYS_IOCTL_H
56 #include <sys/ioctl.h>
57 #endif
58
59 #ifdef HAVE_SYS_PARAM_H
60 #include <sys/param.h>
61 #endif
62
63 #endif /* WIN32 */
64
65 #include "urldata.h"
66 #include <curl/curl.h>
67 #include "transfer.h"
68 #include "sendf.h"
69 #include "tftp.h"
70 #include "progress.h"
71 #include "connect.h"
72 #include "strerror.h"
73 #include "sockaddr.h" /* required for Curl_sockaddr_storage */
74 #include "url.h"
75
76 #define _MPRINTF_REPLACE /* use our functions only */
77 #include <curl/mprintf.h>
78
79 #include "memory.h"
80 #include "select.h"
81
82 /* The last #include file should be: */
83 #include "memdebug.h"
84
85 /* RFC2348 allows the block size to be negotiated, but we don't support that */
86 #define TFTP_BLOCKSIZE 512
87
88 typedef enum {
89   TFTP_MODE_NETASCII=0,
90   TFTP_MODE_OCTET
91 } tftp_mode_t;
92
93 typedef enum {
94   TFTP_STATE_START=0,
95   TFTP_STATE_RX,
96   TFTP_STATE_TX,
97   TFTP_STATE_FIN
98 } tftp_state_t;
99
100 typedef enum {
101   TFTP_EVENT_INIT=0,
102   TFTP_EVENT_RRQ = 1,
103   TFTP_EVENT_WRQ = 2,
104   TFTP_EVENT_DATA = 3,
105   TFTP_EVENT_ACK = 4,
106   TFTP_EVENT_ERROR = 5,
107   TFTP_EVENT_TIMEOUT
108 } tftp_event_t;
109
110 typedef enum {
111   TFTP_ERR_UNDEF=0,
112   TFTP_ERR_NOTFOUND,
113   TFTP_ERR_PERM,
114   TFTP_ERR_DISKFULL,
115   TFTP_ERR_ILLEGAL,
116   TFTP_ERR_UNKNOWNID,
117   TFTP_ERR_EXISTS,
118   TFTP_ERR_NOSUCHUSER,  /* This will never be triggered by this code */
119
120   /* The remaining error codes are internal to curl */
121   TFTP_ERR_NONE = -100,
122   TFTP_ERR_TIMEOUT,
123   TFTP_ERR_NORESPONSE
124 } tftp_error_t;
125
126 typedef struct tftp_packet {
127   unsigned char data[2 + 2 + TFTP_BLOCKSIZE];
128 } tftp_packet_t;
129
130 typedef struct tftp_state_data {
131   tftp_state_t    state;
132   tftp_mode_t     mode;
133   tftp_error_t    error;
134   struct connectdata      *conn;
135   curl_socket_t   sockfd;
136   int             retries;
137   int             retry_time;
138   int             retry_max;
139   time_t          start_time;
140   time_t          max_time;
141   unsigned short  block;
142   struct Curl_sockaddr_storage   local_addr;
143   struct Curl_sockaddr_storage   remote_addr;
144   socklen_t       remote_addrlen;
145   ssize_t         rbytes;
146   int             sbytes;
147   tftp_packet_t   rpacket;
148   tftp_packet_t   spacket;
149 } tftp_state_data_t;
150
151
152 /* Forward declarations */
153 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event) ;
154 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event) ;
155 static CURLcode tftp_connect(struct connectdata *conn, bool *done);
156 static CURLcode tftp_do(struct connectdata *conn, bool *done);
157 static CURLcode tftp_done(struct connectdata *conn,
158                                CURLcode, bool premature);
159 static CURLcode tftp_setup_connection(struct connectdata * conn);
160
161
162 /*
163  * TFTP protocol handler.
164  */
165
166 const struct Curl_handler Curl_handler_tftp = {
167   "TFTP",                               /* scheme */
168   tftp_setup_connection,                /* setup_connection */
169   tftp_do,                              /* do_it */
170   tftp_done,                            /* done */
171   ZERO_NULL,                            /* do_more */
172   tftp_connect,                         /* connect_it */
173   ZERO_NULL,                            /* connecting */
174   ZERO_NULL,                            /* doing */
175   ZERO_NULL,                            /* proto_getsock */
176   ZERO_NULL,                            /* doing_getsock */
177   ZERO_NULL,                            /* perform_getsock */
178   ZERO_NULL,                            /* disconnect */
179   PORT_TFTP,                            /* defport */
180   PROT_TFTP                             /* protocol */
181 };
182
183
184 /**********************************************************
185  *
186  * tftp_set_timeouts -
187  *
188  * Set timeouts based on state machine state.
189  * Use user provided connect timeouts until DATA or ACK
190  * packet is received, then use user-provided transfer timeouts
191  *
192  *
193  **********************************************************/
194 static CURLcode tftp_set_timeouts(tftp_state_data_t *state)
195 {
196   time_t maxtime, timeout;
197   long timeout_ms;
198   const bool start = (state->state == TFTP_STATE_START);
199
200   time(&state->start_time);
201
202   /* Compute drop-dead time */
203   timeout_ms = Curl_timeleft(state->conn, NULL, start);
204
205   if(timeout_ms < 0) {
206     /* time-out, bail out, go home */
207     failf(state->conn->data, "Connection time-out");
208     return CURLE_OPERATION_TIMEDOUT;
209   }
210
211   if(start) {
212
213     maxtime = (time_t)(timeout_ms + 500) / 1000;
214     state->max_time = state->start_time+maxtime;
215
216     /* Set per-block timeout to total */
217     timeout = maxtime ;
218
219     /* Average restart after 5 seconds */
220     state->retry_max = timeout/5;
221
222     if(state->retry_max < 1)
223       /* avoid division by zero below */
224       state->retry_max = 1;
225
226     /* Compute the re-start interval to suit the timeout */
227     state->retry_time = timeout/state->retry_max;
228     if(state->retry_time<1)
229       state->retry_time=1;
230
231   }
232   else {
233     if(timeout_ms > 0)
234       maxtime = (time_t)(timeout_ms + 500) / 1000;
235     else
236       maxtime = 3600;
237
238     state->max_time = state->start_time+maxtime;
239
240     /* Set per-block timeout to 10% of total */
241     timeout = maxtime/10 ;
242
243     /* Average reposting an ACK after 15 seconds */
244     state->retry_max = timeout/15;
245   }
246   /* But bound the total number  */
247   if(state->retry_max<3)
248     state->retry_max=3;
249
250   if(state->retry_max>50)
251     state->retry_max=50;
252
253   /* Compute the re-ACK interval to suit the timeout */
254   state->retry_time = timeout/state->retry_max;
255   if(state->retry_time<1)
256     state->retry_time=1;
257
258   infof(state->conn->data,
259         "set timeouts for state %d; Total %d, retry %d maxtry %d\n",
260         state->state, (state->max_time-state->start_time),
261         state->retry_time, state->retry_max);
262
263   return CURLE_OK;
264 }
265
266 /**********************************************************
267  *
268  * tftp_set_send_first
269  *
270  * Event handler for the START state
271  *
272  **********************************************************/
273
274 static void setpacketevent(tftp_packet_t *packet, unsigned short num)
275 {
276   packet->data[0] = (unsigned char)(num >> 8);
277   packet->data[1] = (unsigned char)(num & 0xff);
278 }
279
280
281 static void setpacketblock(tftp_packet_t *packet, unsigned short num)
282 {
283   packet->data[2] = (unsigned char)(num >> 8);
284   packet->data[3] = (unsigned char)(num & 0xff);
285 }
286
287 static unsigned short getrpacketevent(const tftp_packet_t *packet)
288 {
289   return (unsigned short)((packet->data[0] << 8) | packet->data[1]);
290 }
291
292 static unsigned short getrpacketblock(const tftp_packet_t *packet)
293 {
294   return (unsigned short)((packet->data[2] << 8) | packet->data[3]);
295 }
296
297 static CURLcode tftp_send_first(tftp_state_data_t *state, tftp_event_t event)
298 {
299   int sbytes;
300   const char *mode = "octet";
301   char *filename;
302   struct SessionHandle *data = state->conn->data;
303   CURLcode res = CURLE_OK;
304
305   /* Set ascii mode if -B flag was used */
306   if(data->set.prefer_ascii)
307     mode = "netascii";
308
309   switch(event) {
310
311   case TFTP_EVENT_INIT:    /* Send the first packet out */
312   case TFTP_EVENT_TIMEOUT: /* Resend the first packet out */
313     /* Increment the retry counter, quit if over the limit */
314     state->retries++;
315     if(state->retries>state->retry_max) {
316       state->error = TFTP_ERR_NORESPONSE;
317       state->state = TFTP_STATE_FIN;
318       return res;
319     }
320
321     if(data->set.upload) {
322       /* If we are uploading, send an WRQ */
323       setpacketevent(&state->spacket, TFTP_EVENT_WRQ);
324       state->conn->data->req.upload_fromhere =
325         (char *)&state->spacket.data[4];
326       if(data->set.infilesize != -1)
327         Curl_pgrsSetUploadSize(data, data->set.infilesize);
328     }
329     else {
330       /* If we are downloading, send an RRQ */
331       setpacketevent(&state->spacket, TFTP_EVENT_RRQ);
332     }
333     /* As RFC3617 describes the separator slash is not actually part of the
334     file name so we skip the always-present first letter of the path string. */
335     filename = curl_easy_unescape(data, &state->conn->data->state.path[1], 0,
336                                   NULL);
337     if(!filename)
338       return CURLE_OUT_OF_MEMORY;
339
340     snprintf((char *)&state->spacket.data[2],
341              TFTP_BLOCKSIZE,
342              "%s%c%s%c", filename, '\0',  mode, '\0');
343     sbytes = 4 + (int)strlen(filename) + (int)strlen(mode);
344     sbytes = sendto(state->sockfd, (void *)&state->spacket,
345                     sbytes, 0,
346                     state->conn->ip_addr->ai_addr,
347                     state->conn->ip_addr->ai_addrlen);
348     if(sbytes < 0) {
349       failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
350     }
351     Curl_safefree(filename);
352     break;
353
354   case TFTP_EVENT_ACK: /* Connected for transmit */
355     infof(data, "%s\n", "Connected for transmit");
356     state->state = TFTP_STATE_TX;
357     res = tftp_set_timeouts(state);
358     if(res)
359       break;
360     return tftp_tx(state, event);
361
362   case TFTP_EVENT_DATA: /* connected for receive */
363     infof(data, "%s\n", "Connected for receive");
364     state->state = TFTP_STATE_RX;
365     res = tftp_set_timeouts(state);
366     if(res)
367       break;
368     return tftp_rx(state, event);
369
370   case TFTP_EVENT_ERROR:
371     state->state = TFTP_STATE_FIN;
372     break;
373
374   default:
375     failf(state->conn->data, "tftp_send_first: internal error");
376     break;
377   }
378   return res;
379 }
380
381 /**********************************************************
382  *
383  * tftp_rx
384  *
385  * Event handler for the RX state
386  *
387  **********************************************************/
388 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event)
389 {
390   int sbytes;
391   int rblock;
392   struct SessionHandle *data = state->conn->data;
393
394   switch(event) {
395
396   case TFTP_EVENT_DATA:
397
398     /* Is this the block we expect? */
399     rblock = getrpacketblock(&state->rpacket);
400     if((state->block+1) != rblock) {
401       /* No, log it, up the retry count and fail if over the limit */
402       infof(data,
403             "Received unexpected DATA packet block %d\n", rblock);
404       state->retries++;
405       if(state->retries>state->retry_max) {
406         failf(data, "tftp_rx: giving up waiting for block %d",
407               state->block+1);
408         return CURLE_TFTP_ILLEGAL;
409       }
410     }
411     /* This is the expected block.  Reset counters and ACK it. */
412     state->block = (unsigned short)rblock;
413     state->retries = 0;
414     setpacketevent(&state->spacket, TFTP_EVENT_ACK);
415     setpacketblock(&state->spacket, state->block);
416     sbytes = sendto(state->sockfd, (void *)state->spacket.data,
417                     4, SEND_4TH_ARG,
418                     (struct sockaddr *)&state->remote_addr,
419                     state->remote_addrlen);
420     if(sbytes < 0) {
421       failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
422       return CURLE_SEND_ERROR;
423     }
424
425     /* Check if completed (That is, a less than full packet is received) */
426     if(state->rbytes < (ssize_t)sizeof(state->spacket)){
427       state->state = TFTP_STATE_FIN;
428     }
429     else {
430       state->state = TFTP_STATE_RX;
431     }
432     break;
433
434   case TFTP_EVENT_TIMEOUT:
435     /* Increment the retry count and fail if over the limit */
436     state->retries++;
437     infof(data,
438           "Timeout waiting for block %d ACK.  Retries = %d\n", state->retries);
439     if(state->retries > state->retry_max) {
440       state->error = TFTP_ERR_TIMEOUT;
441       state->state = TFTP_STATE_FIN;
442     }
443     else {
444       /* Resend the previous ACK */
445       sbytes = sendto(state->sockfd, (void *)&state->spacket,
446                       4, SEND_4TH_ARG,
447                       (struct sockaddr *)&state->remote_addr,
448                       state->remote_addrlen);
449       /* Check all sbytes were sent */
450       if(sbytes<0) {
451         failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
452         return CURLE_SEND_ERROR;
453       }
454     }
455     break;
456
457   case TFTP_EVENT_ERROR:
458     state->state = TFTP_STATE_FIN;
459     break;
460
461   default:
462     failf(data, "%s", "tftp_rx: internal error");
463     return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for
464                                   this */
465   }
466   return CURLE_OK;
467 }
468
469 /**********************************************************
470  *
471  * tftp_tx
472  *
473  * Event handler for the TX state
474  *
475  **********************************************************/
476 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event)
477 {
478   struct SessionHandle *data = state->conn->data;
479   int sbytes;
480   int rblock;
481   CURLcode res = CURLE_OK;
482   struct SingleRequest *k = &data->req;
483
484   switch(event) {
485
486   case TFTP_EVENT_ACK:
487     /* Ack the packet */
488     rblock = getrpacketblock(&state->rpacket);
489
490     if(rblock != state->block) {
491       /* This isn't the expected block.  Log it and up the retry counter */
492       infof(data, "Received ACK for block %d, expecting %d\n",
493             rblock, state->block);
494       state->retries++;
495       /* Bail out if over the maximum */
496       if(state->retries>state->retry_max) {
497         failf(data, "tftp_tx: giving up waiting for block %d ack",
498               state->block);
499         res = CURLE_SEND_ERROR;
500       }
501       else {
502         /* Re-send the data packet */
503         sbytes = sendto(state->sockfd, (void *)&state->spacket,
504                         4+state->sbytes, SEND_4TH_ARG,
505                         (struct sockaddr *)&state->remote_addr,
506                         state->remote_addrlen);
507         /* Check all sbytes were sent */
508         if(sbytes<0) {
509           failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
510           res = CURLE_SEND_ERROR;
511         }
512       }
513       return res;
514     }
515     /* This is the expected packet.  Reset the counters and send the next
516        block */
517     state->block++;
518     state->retries = 0;
519     setpacketevent(&state->spacket, TFTP_EVENT_DATA);
520     setpacketblock(&state->spacket, state->block);
521     if(state->block > 1 && state->sbytes < TFTP_BLOCKSIZE) {
522       state->state = TFTP_STATE_FIN;
523       return CURLE_OK;
524     }
525     res = Curl_fillreadbuffer(state->conn, TFTP_BLOCKSIZE, &state->sbytes);
526     if(res)
527       return res;
528     sbytes = sendto(state->sockfd, (void *)state->spacket.data,
529                     4+state->sbytes, SEND_4TH_ARG,
530                     (struct sockaddr *)&state->remote_addr,
531                     state->remote_addrlen);
532     /* Check all sbytes were sent */
533     if(sbytes<0) {
534       failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
535       return CURLE_SEND_ERROR;
536     }
537     /* Update the progress meter */
538     k->writebytecount += state->sbytes;
539     Curl_pgrsSetUploadCounter(data, k->writebytecount);
540     break;
541
542   case TFTP_EVENT_TIMEOUT:
543     /* Increment the retry counter and log the timeout */
544     state->retries++;
545     infof(data, "Timeout waiting for block %d ACK. "
546           " Retries = %d\n", state->retries);
547     /* Decide if we've had enough */
548     if(state->retries > state->retry_max) {
549       state->error = TFTP_ERR_TIMEOUT;
550       state->state = TFTP_STATE_FIN;
551     }
552     else {
553       /* Re-send the data packet */
554       sbytes = sendto(state->sockfd, (void *)&state->spacket,
555                       4+state->sbytes, SEND_4TH_ARG,
556                       (struct sockaddr *)&state->remote_addr,
557                       state->remote_addrlen);
558       /* Check all sbytes were sent */
559       if(sbytes<0) {
560         failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
561         return CURLE_SEND_ERROR;
562       }
563       /* since this was a re-send, we remain at the still byte position */
564       Curl_pgrsSetUploadCounter(data, k->writebytecount);
565     }
566     break;
567
568   case TFTP_EVENT_ERROR:
569     state->state = TFTP_STATE_FIN;
570     break;
571
572   default:
573     failf(data, "%s", "tftp_tx: internal error");
574     break;
575   }
576
577   return res;
578 }
579
580 /**********************************************************
581  *
582  * tftp_state_machine
583  *
584  * The tftp state machine event dispatcher
585  *
586  **********************************************************/
587 static CURLcode tftp_state_machine(tftp_state_data_t *state,
588                                    tftp_event_t event)
589 {
590   CURLcode res = CURLE_OK;
591   struct SessionHandle *data = state->conn->data;
592   switch(state->state) {
593   case TFTP_STATE_START:
594     DEBUGF(infof(data, "TFTP_STATE_START\n"));
595     res = tftp_send_first(state, event);
596     break;
597   case TFTP_STATE_RX:
598     DEBUGF(infof(data, "TFTP_STATE_RX\n"));
599     res = tftp_rx(state, event);
600     break;
601   case TFTP_STATE_TX:
602     DEBUGF(infof(data, "TFTP_STATE_TX\n"));
603     res = tftp_tx(state, event);
604     break;
605   case TFTP_STATE_FIN:
606     infof(data, "%s\n", "TFTP finished");
607     break;
608   default:
609     DEBUGF(infof(data, "STATE: %d\n", state->state));
610     failf(data, "%s", "Internal state machine error");
611     res = CURLE_TFTP_ILLEGAL;
612     break;
613   }
614   return res;
615 }
616
617
618 /**********************************************************
619  *
620  * tftp_connect
621  *
622  * The connect callback
623  *
624  **********************************************************/
625 static CURLcode tftp_connect(struct connectdata *conn, bool *done)
626 {
627   CURLcode code;
628   tftp_state_data_t *state;
629   int rc;
630
631   /* If there already is a protocol-specific struct allocated for this
632      sessionhandle, deal with it */
633   Curl_reset_reqproto(conn);
634
635   state = conn->data->state.proto.tftp;
636   if(!state) {
637     state = conn->data->state.proto.tftp = calloc(sizeof(tftp_state_data_t),
638                                                   1);
639     if(!state)
640       return CURLE_OUT_OF_MEMORY;
641   }
642
643   conn->bits.close = FALSE; /* keep it open if possible */
644
645   state->conn = conn;
646   state->sockfd = state->conn->sock[FIRSTSOCKET];
647   state->state = TFTP_STATE_START;
648   state->error = TFTP_ERR_NONE;
649
650   ((struct sockaddr *)&state->local_addr)->sa_family =
651     (unsigned short)(conn->ip_addr->ai_family);
652
653   tftp_set_timeouts(state);
654
655   if(!conn->bits.bound) {
656     /* If not already bound, bind to any interface, random UDP port. If it is
657      * reused or a custom local port was desired, this has already been done!
658      *
659      * We once used the size of the local_addr struct as the third argument for
660      * bind() to better work with IPv6 or whatever size the struct could have,
661      * but we learned that at least Tru64, AIX and IRIX *requires* the size of
662      * that argument to match the exact size of a 'sockaddr_in' struct when
663      * running IPv4-only.
664      *
665      * Therefore we use the size from the address we connected to, which we
666      * assume uses the same IP version and thus hopefully this works for both
667      * IPv4 and IPv6...
668      */
669     rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr,
670               conn->ip_addr->ai_addrlen);
671     if(rc) {
672       failf(conn->data, "bind() failed; %s",
673             Curl_strerror(conn, SOCKERRNO));
674       return CURLE_COULDNT_CONNECT;
675     }
676     conn->bits.bound = TRUE;
677   }
678
679   Curl_pgrsStartNow(conn->data);
680
681   *done = TRUE;
682   code = CURLE_OK;
683   return(code);
684 }
685
686 /**********************************************************
687  *
688  * tftp_done
689  *
690  * The done callback
691  *
692  **********************************************************/
693 static CURLcode tftp_done(struct connectdata *conn, CURLcode status,
694                                bool premature)
695 {
696   (void)status; /* unused */
697   (void)premature; /* not used */
698
699   Curl_pgrsDone(conn);
700
701   return CURLE_OK;
702 }
703
704
705 /**********************************************************
706  *
707  * tftp
708  *
709  * The do callback
710  *
711  * This callback handles the entire TFTP transfer
712  *
713  **********************************************************/
714
715 static CURLcode tftp_do(struct connectdata *conn, bool *done)
716 {
717   struct SessionHandle  *data = conn->data;
718   tftp_state_data_t     *state;
719   tftp_event_t          event;
720   CURLcode              code;
721   int                   rc;
722   struct Curl_sockaddr_storage fromaddr;
723   socklen_t             fromlen;
724   int                   check_time = 0;
725   struct SingleRequest *k = &data->req;
726
727   *done = TRUE;
728
729   /*
730     Since connections can be re-used between SessionHandles, this might be a
731     connection already existing but on a fresh SessionHandle struct so we must
732     make sure we have a good 'struct TFTP' to play with. For new connections,
733     the struct TFTP is allocated and setup in the tftp_connect() function.
734   */
735   Curl_reset_reqproto(conn);
736
737   if(!data->state.proto.tftp) {
738     code = tftp_connect(conn, done);
739     if(code)
740       return code;
741   }
742   state = (tftp_state_data_t *)data->state.proto.tftp;
743
744   /* Run the TFTP State Machine */
745   for(code=tftp_state_machine(state, TFTP_EVENT_INIT);
746       (state->state != TFTP_STATE_FIN) && (code == CURLE_OK);
747       code=tftp_state_machine(state, event) ) {
748
749     /* Wait until ready to read or timeout occurs */
750     rc=Curl_socket_ready(state->sockfd, CURL_SOCKET_BAD,
751                          state->retry_time * 1000);
752
753     if(rc == -1) {
754       /* bail out */
755       int error = SOCKERRNO;
756       failf(data, "%s", Curl_strerror(conn, error));
757       event = TFTP_EVENT_ERROR;
758     }
759     else if(rc==0) {
760       /* A timeout occured */
761       event = TFTP_EVENT_TIMEOUT;
762
763       /* Force a look at transfer timeouts */
764       check_time = 0;
765
766     }
767     else {
768
769       /* Receive the packet */
770       fromlen = sizeof(fromaddr);
771       state->rbytes = (ssize_t)recvfrom(state->sockfd,
772                                         (void *)&state->rpacket,
773                                         sizeof(state->rpacket),
774                                         0,
775                                         (struct sockaddr *)&fromaddr,
776                                         &fromlen);
777       if(state->remote_addrlen==0) {
778         memcpy(&state->remote_addr, &fromaddr, fromlen);
779         state->remote_addrlen = fromlen;
780       }
781
782       /* Sanity check packet length */
783       if(state->rbytes < 4) {
784         failf(data, "Received too short packet");
785         /* Not a timeout, but how best to handle it? */
786         event = TFTP_EVENT_TIMEOUT;
787       }
788       else {
789
790         /* The event is given by the TFTP packet time */
791         event = (tftp_event_t)getrpacketevent(&state->rpacket);
792
793         switch(event) {
794         case TFTP_EVENT_DATA:
795           /* Don't pass to the client empty or retransmitted packets */
796           if(state->rbytes > 4 &&
797               ((state->block+1) == getrpacketblock(&state->rpacket))) {
798             code = Curl_client_write(conn, CLIENTWRITE_BODY,
799                                      (char *)&state->rpacket.data[4],
800                                      state->rbytes-4);
801             if(code)
802               return code;
803             k->bytecount += state->rbytes-4;
804             Curl_pgrsSetDownloadCounter(data, (curl_off_t) k->bytecount);
805           }
806           break;
807         case TFTP_EVENT_ERROR:
808           state->error = (tftp_error_t)getrpacketblock(&state->rpacket);
809           infof(data, "%s\n", (const char *)&state->rpacket.data[4]);
810           break;
811         case TFTP_EVENT_ACK:
812           break;
813         case TFTP_EVENT_RRQ:
814         case TFTP_EVENT_WRQ:
815         default:
816           failf(data, "%s", "Internal error: Unexpected packet");
817           break;
818         }
819
820         /* Update the progress meter */
821         if(Curl_pgrsUpdate(conn))
822           return CURLE_ABORTED_BY_CALLBACK;
823       }
824     }
825
826     /* Check for transfer timeout every 10 blocks, or after timeout */
827     if(check_time%10==0) {
828       time_t current;
829       time(&current);
830       if(current>state->max_time) {
831         DEBUGF(infof(data, "timeout: %d > %d\n",
832                      current, state->max_time));
833         state->error = TFTP_ERR_TIMEOUT;
834         state->state = TFTP_STATE_FIN;
835       }
836     }
837
838   }
839   if(code)
840     return code;
841
842   /* Tell curl we're done */
843   code = Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
844   if(code)
845     return code;
846
847   /* If we have encountered an error */
848   if(state->error != TFTP_ERR_NONE) {
849
850     /* Translate internal error codes to curl error codes */
851     switch(state->error) {
852     case TFTP_ERR_NOTFOUND:
853       code = CURLE_TFTP_NOTFOUND;
854       break;
855     case TFTP_ERR_PERM:
856       code = CURLE_TFTP_PERM;
857       break;
858     case TFTP_ERR_DISKFULL:
859       code = CURLE_REMOTE_DISK_FULL;
860       break;
861     case TFTP_ERR_UNDEF:
862     case TFTP_ERR_ILLEGAL:
863       code = CURLE_TFTP_ILLEGAL;
864       break;
865     case TFTP_ERR_UNKNOWNID:
866       code = CURLE_TFTP_UNKNOWNID;
867       break;
868     case TFTP_ERR_EXISTS:
869       code = CURLE_REMOTE_FILE_EXISTS;
870       break;
871     case TFTP_ERR_NOSUCHUSER:
872       code = CURLE_TFTP_NOSUCHUSER;
873       break;
874     case TFTP_ERR_TIMEOUT:
875       code = CURLE_OPERATION_TIMEDOUT;
876       break;
877     case TFTP_ERR_NORESPONSE:
878       code = CURLE_COULDNT_CONNECT;
879       break;
880     default:
881       code= CURLE_ABORTED_BY_CALLBACK;
882       break;
883     }
884   }
885   else
886     code = CURLE_OK;
887   return code;
888 }
889
890 static CURLcode tftp_setup_connection(struct connectdata * conn)
891 {
892   struct SessionHandle *data = conn->data;
893   char * type;
894   char command;
895
896   conn->socktype = SOCK_DGRAM;   /* UDP datagram based */
897
898   /* TFTP URLs support an extension like ";mode=<typecode>" that
899    * we'll try to get now! */
900   type = strstr(data->state.path, ";mode=");
901
902   if(!type)
903     type = strstr(conn->host.rawalloc, ";mode=");
904
905   if(type) {
906     *type = 0;                   /* it was in the middle of the hostname */
907     command = (char) toupper((int) type[6]);
908
909     switch (command) {
910     case 'A': /* ASCII mode */
911     case 'N': /* NETASCII mode */
912       data->set.prefer_ascii = TRUE;
913       break;
914
915     case 'O': /* octet mode */
916     case 'I': /* binary mode */
917     default:
918       /* switch off ASCII */
919       data->set.prefer_ascii = FALSE;
920       break;
921     }
922   }
923
924   return CURLE_OK;
925 }
926 #endif