Git init
[external/curl.git] / lib / tftp.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2010, 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  ***************************************************************************/
22
23 #include "setup.h"
24
25 #ifndef CURL_DISABLE_TFTP
26 /* -- WIN32 approved -- */
27 #include <stdio.h>
28 #include <stdarg.h>
29 #include <stdlib.h>
30 #include <ctype.h>
31
32 #if defined(WIN32)
33 #include <time.h>
34 #include <io.h>
35 #else
36 #ifdef HAVE_SYS_SOCKET_H
37 #include <sys/socket.h>
38 #endif
39 #include <netinet/in.h>
40 #ifdef HAVE_SYS_TIME_H
41 #include <sys/time.h>
42 #endif
43 #ifdef HAVE_UNISTD_H
44 #include <unistd.h>
45 #endif
46 #include <netdb.h>
47 #ifdef HAVE_ARPA_INET_H
48 #include <arpa/inet.h>
49 #endif
50 #ifdef HAVE_NET_IF_H
51 #include <net/if.h>
52 #endif
53 #ifdef HAVE_SYS_IOCTL_H
54 #include <sys/ioctl.h>
55 #endif
56
57 #ifdef HAVE_SYS_PARAM_H
58 #include <sys/param.h>
59 #endif
60
61 #endif /* WIN32 */
62
63 #include "urldata.h"
64 #include <curl/curl.h>
65 #include "transfer.h"
66 #include "sendf.h"
67 #include "tftp.h"
68 #include "progress.h"
69 #include "connect.h"
70 #include "strerror.h"
71 #include "sockaddr.h" /* required for Curl_sockaddr_storage */
72 #include "multiif.h"
73 #include "url.h"
74 #include "rawstr.h"
75
76 #define _MPRINTF_REPLACE /* use our functions only */
77 #include <curl/mprintf.h>
78
79 #include "curl_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 */
86 #define TFTP_BLKSIZE_DEFAULT 512
87 #define TFTP_BLKSIZE_MIN 8
88 #define TFTP_BLKSIZE_MAX 65464
89 #define TFTP_OPTION_BLKSIZE "blksize"
90
91 /* from RFC2349: */
92 #define TFTP_OPTION_TSIZE    "tsize"
93 #define TFTP_OPTION_INTERVAL "timeout"
94
95 typedef enum {
96   TFTP_MODE_NETASCII=0,
97   TFTP_MODE_OCTET
98 } tftp_mode_t;
99
100 typedef enum {
101   TFTP_STATE_START=0,
102   TFTP_STATE_RX,
103   TFTP_STATE_TX,
104   TFTP_STATE_FIN
105 } tftp_state_t;
106
107 typedef enum {
108   TFTP_EVENT_NONE = -1,
109   TFTP_EVENT_INIT = 0,
110   TFTP_EVENT_RRQ = 1,
111   TFTP_EVENT_WRQ = 2,
112   TFTP_EVENT_DATA = 3,
113   TFTP_EVENT_ACK = 4,
114   TFTP_EVENT_ERROR = 5,
115   TFTP_EVENT_OACK = 6,
116   TFTP_EVENT_TIMEOUT
117 } tftp_event_t;
118
119 typedef enum {
120   TFTP_ERR_UNDEF=0,
121   TFTP_ERR_NOTFOUND,
122   TFTP_ERR_PERM,
123   TFTP_ERR_DISKFULL,
124   TFTP_ERR_ILLEGAL,
125   TFTP_ERR_UNKNOWNID,
126   TFTP_ERR_EXISTS,
127   TFTP_ERR_NOSUCHUSER,  /* This will never be triggered by this code */
128
129   /* The remaining error codes are internal to curl */
130   TFTP_ERR_NONE = -100,
131   TFTP_ERR_TIMEOUT,
132   TFTP_ERR_NORESPONSE
133 } tftp_error_t;
134
135 typedef struct tftp_packet {
136   unsigned char *data;
137 } tftp_packet_t;
138
139 typedef struct tftp_state_data {
140   tftp_state_t    state;
141   tftp_mode_t     mode;
142   tftp_error_t    error;
143   tftp_event_t    event;
144   struct connectdata      *conn;
145   curl_socket_t   sockfd;
146   int             retries;
147   int             retry_time;
148   int             retry_max;
149   time_t          start_time;
150   time_t          max_time;
151   time_t          rx_time;
152   unsigned short  block;
153   struct Curl_sockaddr_storage   local_addr;
154   struct Curl_sockaddr_storage   remote_addr;
155   curl_socklen_t  remote_addrlen;
156   int             rbytes;
157   int             sbytes;
158   int             blksize;
159   int             requested_blksize;
160   tftp_packet_t   rpacket;
161   tftp_packet_t   spacket;
162 } tftp_state_data_t;
163
164
165 /* Forward declarations */
166 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event) ;
167 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event) ;
168 static CURLcode tftp_connect(struct connectdata *conn, bool *done);
169 static CURLcode tftp_disconnect(struct connectdata *conn, bool dead_connection);
170 static CURLcode tftp_do(struct connectdata *conn, bool *done);
171 static CURLcode tftp_done(struct connectdata *conn,
172                           CURLcode, bool premature);
173 static CURLcode tftp_setup_connection(struct connectdata * conn);
174 static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done);
175 static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done);
176 static int tftp_getsock(struct connectdata *conn, curl_socket_t *socks,
177                         int numsocks);
178 static CURLcode tftp_translate_code(tftp_error_t error);
179
180
181 /*
182  * TFTP protocol handler.
183  */
184
185 const struct Curl_handler Curl_handler_tftp = {
186   "TFTP",                               /* scheme */
187   tftp_setup_connection,                /* setup_connection */
188   tftp_do,                              /* do_it */
189   tftp_done,                            /* done */
190   ZERO_NULL,                            /* do_more */
191   tftp_connect,                         /* connect_it */
192   tftp_multi_statemach,                 /* connecting */
193   tftp_doing,                           /* doing */
194   tftp_getsock,                         /* proto_getsock */
195   tftp_getsock,                         /* doing_getsock */
196   ZERO_NULL,                            /* perform_getsock */
197   tftp_disconnect,                      /* disconnect */
198   PORT_TFTP,                            /* defport */
199   PROT_TFTP                             /* protocol */
200 };
201
202 /**********************************************************
203  *
204  * tftp_set_timeouts -
205  *
206  * Set timeouts based on state machine state.
207  * Use user provided connect timeouts until DATA or ACK
208  * packet is received, then use user-provided transfer timeouts
209  *
210  *
211  **********************************************************/
212 static CURLcode tftp_set_timeouts(tftp_state_data_t *state)
213 {
214   time_t maxtime, timeout;
215   long timeout_ms;
216   bool start = (bool)(state->state == TFTP_STATE_START);
217
218   time(&state->start_time);
219
220   /* Compute drop-dead time */
221   timeout_ms = Curl_timeleft(state->conn, NULL, start);
222
223   if(timeout_ms < 0) {
224     /* time-out, bail out, go home */
225     failf(state->conn->data, "Connection time-out");
226     return CURLE_OPERATION_TIMEDOUT;
227   }
228
229   if(start) {
230
231     maxtime = (time_t)(timeout_ms + 500) / 1000;
232     state->max_time = state->start_time+maxtime;
233
234     /* Set per-block timeout to total */
235     timeout = maxtime ;
236
237     /* Average restart after 5 seconds */
238     state->retry_max = (int)timeout/5;
239
240     if(state->retry_max < 1)
241       /* avoid division by zero below */
242       state->retry_max = 1;
243
244     /* Compute the re-start interval to suit the timeout */
245     state->retry_time = (int)timeout/state->retry_max;
246     if(state->retry_time<1)
247       state->retry_time=1;
248
249   }
250   else {
251     if(timeout_ms > 0)
252       maxtime = (time_t)(timeout_ms + 500) / 1000;
253     else
254       maxtime = 3600;
255
256     state->max_time = state->start_time+maxtime;
257
258     /* Set per-block timeout to 10% of total */
259     timeout = maxtime/10 ;
260
261     /* Average reposting an ACK after 15 seconds */
262     state->retry_max = (int)timeout/15;
263   }
264   /* But bound the total number */
265   if(state->retry_max<3)
266     state->retry_max=3;
267
268   if(state->retry_max>50)
269     state->retry_max=50;
270
271   /* Compute the re-ACK interval to suit the timeout */
272   state->retry_time = (int)(timeout/state->retry_max);
273   if(state->retry_time<1)
274     state->retry_time=1;
275
276   infof(state->conn->data,
277         "set timeouts for state %d; Total %ld, retry %d maxtry %d\n",
278         (int)state->state, (long)(state->max_time-state->start_time),
279         state->retry_time, state->retry_max);
280
281   /* init RX time */
282   time(&state->rx_time);
283
284   return CURLE_OK;
285 }
286
287 /**********************************************************
288  *
289  * tftp_set_send_first
290  *
291  * Event handler for the START state
292  *
293  **********************************************************/
294
295 static void setpacketevent(tftp_packet_t *packet, unsigned short num)
296 {
297   packet->data[0] = (unsigned char)(num >> 8);
298   packet->data[1] = (unsigned char)(num & 0xff);
299 }
300
301
302 static void setpacketblock(tftp_packet_t *packet, unsigned short num)
303 {
304   packet->data[2] = (unsigned char)(num >> 8);
305   packet->data[3] = (unsigned char)(num & 0xff);
306 }
307
308 static unsigned short getrpacketevent(const tftp_packet_t *packet)
309 {
310   return (unsigned short)((packet->data[0] << 8) | packet->data[1]);
311 }
312
313 static unsigned short getrpacketblock(const tftp_packet_t *packet)
314 {
315   return (unsigned short)((packet->data[2] << 8) | packet->data[3]);
316 }
317
318 static size_t Curl_strnlen(const char *string, size_t maxlen)
319 {
320   const char *end = memchr (string, '\0', maxlen);
321   return end ? (size_t) (end - string) : maxlen;
322 }
323
324 static const char *tftp_option_get(const char *buf, size_t len,
325                                    const char **option, const char **value)
326 {
327   size_t loc;
328
329   loc = Curl_strnlen( buf, len );
330   loc++; /* NULL term */
331
332   if (loc >= len)
333     return NULL;
334   *option = buf;
335
336   loc += Curl_strnlen( buf+loc, len-loc );
337   loc++; /* NULL term */
338
339   if (loc > len)
340     return NULL;
341   *value = &buf[strlen(*option) + 1];
342
343   return &buf[loc];
344 }
345
346 static CURLcode tftp_parse_option_ack(tftp_state_data_t *state,
347                                       const char *ptr, int len)
348 {
349   const char *tmp = ptr;
350   struct SessionHandle *data = state->conn->data;
351
352   /* if OACK doesn't contain blksize option, the default (512) must be used */
353   state->blksize = TFTP_BLKSIZE_DEFAULT;
354
355   while (tmp < ptr + len) {
356     const char *option, *value;
357
358     tmp = tftp_option_get(tmp, ptr + len - tmp, &option, &value);
359     if(tmp == NULL) {
360       failf(data, "Malformed ACK packet, rejecting");
361       return CURLE_TFTP_ILLEGAL;
362     }
363
364     infof(data, "got option=(%s) value=(%s)\n", option, value);
365
366     if(checkprefix(option, TFTP_OPTION_BLKSIZE)) {
367       long blksize;
368
369       blksize = strtol( value, NULL, 10 );
370
371       if(!blksize) {
372         failf(data, "invalid blocksize value in OACK packet");
373         return CURLE_TFTP_ILLEGAL;
374       }
375       else if(blksize > TFTP_BLKSIZE_MAX) {
376         failf(data, "%s (%d)", "blksize is larger than max supported",
377               TFTP_BLKSIZE_MAX);
378         return CURLE_TFTP_ILLEGAL;
379       }
380       else if(blksize < TFTP_BLKSIZE_MIN) {
381         failf(data, "%s (%d)", "blksize is smaller than min supported",
382               TFTP_BLKSIZE_MIN);
383         return CURLE_TFTP_ILLEGAL;
384       }
385       else if (blksize > state->requested_blksize) {
386         /* could realloc pkt buffers here, but the spec doesn't call out
387          * support for the server requesting a bigger blksize than the client
388          * requests */
389         failf(data, "%s (%ld)",
390               "server requested blksize larger than allocated", blksize);
391         return CURLE_TFTP_ILLEGAL;
392       }
393
394       state->blksize = (int)blksize;
395       infof(data, "%s (%d) %s (%d)\n", "blksize parsed from OACK",
396             state->blksize, "requested", state->requested_blksize);
397     }
398     else if(checkprefix(option, TFTP_OPTION_TSIZE)) {
399       long tsize = 0;
400
401       tsize = strtol( value, NULL, 10 );
402       infof(data, "%s (%ld)\n", "tsize parsed from OACK", tsize);
403
404       /* tsize should be ignored on upload: Who cares about the size of the
405          remote file? */
406       if (!data->set.upload) {
407         if(!tsize) {
408           failf(data, "invalid tsize -:%s:- value in OACK packet", value);
409           return CURLE_TFTP_ILLEGAL;
410         }
411         Curl_pgrsSetDownloadSize(data, tsize);
412       }
413     }
414   }
415
416   return CURLE_OK;
417 }
418
419 static size_t tftp_option_add(tftp_state_data_t *state, size_t csize,
420                               char *buf, const char *option)
421 {
422   if( ( strlen(option) + csize + 1 ) > (size_t)state->blksize )
423     return 0;
424   strcpy(buf, option);
425   return( strlen(option) + 1 );
426 }
427
428 static CURLcode tftp_connect_for_tx(tftp_state_data_t *state,
429                                     tftp_event_t event)
430 {
431   CURLcode res;
432 #ifndef CURL_DISABLE_VERBOSE_STRINGS
433   struct SessionHandle *data = state->conn->data;
434
435   infof(data, "%s\n", "Connected for transmit");
436 #endif
437   state->state = TFTP_STATE_TX;
438   res = tftp_set_timeouts(state);
439   if(res != CURLE_OK)
440     return(res);
441   return tftp_tx(state, event);
442 }
443
444 static CURLcode tftp_connect_for_rx(tftp_state_data_t *state,
445                                     tftp_event_t event)
446 {
447   CURLcode res;
448 #ifndef CURL_DISABLE_VERBOSE_STRINGS
449   struct SessionHandle *data = state->conn->data;
450
451   infof(data, "%s\n", "Connected for receive");
452 #endif
453   state->state = TFTP_STATE_RX;
454   res = tftp_set_timeouts(state);
455   if(res != CURLE_OK)
456     return(res);
457   return tftp_rx(state, event);
458 }
459
460 static CURLcode tftp_send_first(tftp_state_data_t *state, tftp_event_t event)
461 {
462   size_t sbytes;
463   ssize_t senddata;
464   const char *mode = "octet";
465   char *filename;
466   char buf[64];
467   struct SessionHandle *data = state->conn->data;
468   CURLcode res = CURLE_OK;
469
470   /* Set ascii mode if -B flag was used */
471   if(data->set.prefer_ascii)
472     mode = "netascii";
473
474   switch(event) {
475
476   case TFTP_EVENT_INIT:    /* Send the first packet out */
477   case TFTP_EVENT_TIMEOUT: /* Resend the first packet out */
478     /* Increment the retry counter, quit if over the limit */
479     state->retries++;
480     if(state->retries>state->retry_max) {
481       state->error = TFTP_ERR_NORESPONSE;
482       state->state = TFTP_STATE_FIN;
483       return res;
484     }
485
486     if(data->set.upload) {
487       /* If we are uploading, send an WRQ */
488       setpacketevent(&state->spacket, TFTP_EVENT_WRQ);
489       state->conn->data->req.upload_fromhere =
490         (char *)state->spacket.data+4;
491       if(data->set.infilesize != -1)
492         Curl_pgrsSetUploadSize(data, data->set.infilesize);
493     }
494     else {
495       /* If we are downloading, send an RRQ */
496       setpacketevent(&state->spacket, TFTP_EVENT_RRQ);
497     }
498     /* As RFC3617 describes the separator slash is not actually part of the
499        file name so we skip the always-present first letter of the path
500        string. */
501     filename = curl_easy_unescape(data, &state->conn->data->state.path[1], 0,
502                                   NULL);
503     if(!filename)
504       return CURLE_OUT_OF_MEMORY;
505
506     snprintf((char *)state->spacket.data+2,
507              state->blksize,
508              "%s%c%s%c", filename, '\0',  mode, '\0');
509     sbytes = 4 + strlen(filename) + strlen(mode);
510
511     /* add tsize option */
512     if(data->set.upload && (data->set.infilesize != -1))
513       snprintf( buf, sizeof(buf), "%" FORMAT_OFF_T, data->set.infilesize );
514     else
515       strcpy(buf, "0"); /* the destination is large enough */
516
517     sbytes += tftp_option_add(state, sbytes,
518                               (char *)state->spacket.data+sbytes,
519                               TFTP_OPTION_TSIZE);
520     sbytes += tftp_option_add(state, sbytes,
521                               (char *)state->spacket.data+sbytes, buf);
522     /* add blksize option */
523     snprintf( buf, sizeof(buf), "%d", state->requested_blksize );
524     sbytes += tftp_option_add(state, sbytes,
525                               (char *)state->spacket.data+sbytes,
526                               TFTP_OPTION_BLKSIZE);
527     sbytes += tftp_option_add(state, sbytes,
528                               (char *)state->spacket.data+sbytes, buf );
529
530     /* add timeout option */
531     snprintf( buf, sizeof(buf), "%d", state->retry_time);
532     sbytes += tftp_option_add(state, sbytes,
533                               (char *)state->spacket.data+sbytes,
534                               TFTP_OPTION_INTERVAL);
535     sbytes += tftp_option_add(state, sbytes,
536                               (char *)state->spacket.data+sbytes, buf );
537
538     /* the typecase for the 3rd argument is mostly for systems that do
539        not have a size_t argument, like older unixes that want an 'int' */
540     senddata = sendto(state->sockfd, (void *)state->spacket.data,
541                       (SEND_TYPE_ARG3)sbytes, 0,
542                       state->conn->ip_addr->ai_addr,
543                       state->conn->ip_addr->ai_addrlen);
544     if(senddata != (ssize_t)sbytes) {
545       failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
546     }
547     Curl_safefree(filename);
548     break;
549
550   case TFTP_EVENT_OACK:
551     if(data->set.upload) {
552       res = tftp_connect_for_tx(state, event);
553     }
554     else {
555       res = tftp_connect_for_rx(state, event);
556     }
557     break;
558
559   case TFTP_EVENT_ACK: /* Connected for transmit */
560     res = tftp_connect_for_tx(state, event);
561     break;
562
563   case TFTP_EVENT_DATA: /* Connected for receive */
564     res = tftp_connect_for_rx(state, event);
565     break;
566
567   case TFTP_EVENT_ERROR:
568     state->state = TFTP_STATE_FIN;
569     break;
570
571   default:
572     failf(state->conn->data, "tftp_send_first: internal error");
573     break;
574   }
575   return res;
576 }
577
578 /* the next blocknum is x + 1 but it needs to wrap at an unsigned 16bit
579    boundary */
580 #define NEXT_BLOCKNUM(x) (((x)+1)&0xffff)
581
582 /**********************************************************
583  *
584  * tftp_rx
585  *
586  * Event handler for the RX state
587  *
588  **********************************************************/
589 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event)
590 {
591   ssize_t sbytes;
592   int rblock;
593   struct SessionHandle *data = state->conn->data;
594
595   switch(event) {
596
597   case TFTP_EVENT_DATA:
598     /* Is this the block we expect? */
599     rblock = getrpacketblock(&state->rpacket);
600     if(NEXT_BLOCKNUM(state->block) != rblock) {
601       /* No, log it, up the retry count and fail if over the limit */
602       infof(data,
603             "Received unexpected DATA packet block %d\n", rblock);
604       state->retries++;
605       if(state->retries > state->retry_max) {
606         failf(data, "tftp_rx: giving up waiting for block %d",
607               NEXT_BLOCKNUM(state->block));
608         return CURLE_TFTP_ILLEGAL;
609       }
610       break;
611     }
612     /* This is the expected block.  Reset counters and ACK it. */
613     state->block = (unsigned short)rblock;
614     state->retries = 0;
615     setpacketevent(&state->spacket, TFTP_EVENT_ACK);
616     setpacketblock(&state->spacket, state->block);
617     sbytes = sendto(state->sockfd, (void *)state->spacket.data,
618                     4, SEND_4TH_ARG,
619                     (struct sockaddr *)&state->remote_addr,
620                     state->remote_addrlen);
621     if(sbytes < 0) {
622       failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
623       return CURLE_SEND_ERROR;
624     }
625
626     /* Check if completed (That is, a less than full packet is received) */
627     if(state->rbytes < (ssize_t)state->blksize+4){
628       state->state = TFTP_STATE_FIN;
629     }
630     else {
631       state->state = TFTP_STATE_RX;
632     }
633     time(&state->rx_time);
634     break;
635
636   case TFTP_EVENT_OACK:
637     /* ACK option acknowledgement so we can move on to data */
638     state->block = 0;
639     state->retries = 0;
640     setpacketevent(&state->spacket, TFTP_EVENT_ACK);
641     setpacketblock(&state->spacket, state->block);
642     sbytes = sendto(state->sockfd, (void *)state->spacket.data,
643                     4, SEND_4TH_ARG,
644                     (struct sockaddr *)&state->remote_addr,
645                     state->remote_addrlen);
646     if(sbytes < 0) {
647       failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
648       return CURLE_SEND_ERROR;
649     }
650
651     /* we're ready to RX data */
652     state->state = TFTP_STATE_RX;
653     time(&state->rx_time);
654     break;
655
656   case TFTP_EVENT_TIMEOUT:
657     /* Increment the retry count and fail if over the limit */
658     state->retries++;
659     infof(data,
660           "Timeout waiting for block %d ACK.  Retries = %d\n",
661           NEXT_BLOCKNUM(state->block), state->retries);
662     if(state->retries > state->retry_max) {
663       state->error = TFTP_ERR_TIMEOUT;
664       state->state = TFTP_STATE_FIN;
665     }
666     else {
667       /* Resend the previous ACK */
668       sbytes = sendto(state->sockfd, (void *)state->spacket.data,
669                       4, SEND_4TH_ARG,
670                       (struct sockaddr *)&state->remote_addr,
671                       state->remote_addrlen);
672       if(sbytes<0) {
673         failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
674         return CURLE_SEND_ERROR;
675       }
676     }
677     break;
678
679   case TFTP_EVENT_ERROR:
680     setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
681     setpacketblock(&state->spacket, state->block);
682     (void)sendto(state->sockfd, (void *)state->spacket.data,
683                  4, SEND_4TH_ARG,
684                  (struct sockaddr *)&state->remote_addr,
685                  state->remote_addrlen);
686     /* don't bother with the return code, but if the socket is still up we
687      * should be a good TFTP client and let the server know we're done */
688     state->state = TFTP_STATE_FIN;
689     break;
690
691   default:
692     failf(data, "%s", "tftp_rx: internal error");
693     return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for
694                                   this */
695   }
696   return CURLE_OK;
697 }
698
699 /**********************************************************
700  *
701  * tftp_tx
702  *
703  * Event handler for the TX state
704  *
705  **********************************************************/
706 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event)
707 {
708   struct SessionHandle *data = state->conn->data;
709   ssize_t sbytes;
710   int rblock;
711   CURLcode res = CURLE_OK;
712   struct SingleRequest *k = &data->req;
713
714   switch(event) {
715
716   case TFTP_EVENT_ACK:
717   case TFTP_EVENT_OACK:
718     if (event == TFTP_EVENT_ACK) {
719       /* Ack the packet */
720       rblock = getrpacketblock(&state->rpacket);
721
722       if(rblock != state->block &&
723          /* There's a bug in tftpd-hpa that causes it to send us an ack for
724           * 65535 when the block number wraps to 0. So when we're expecting
725           * 0, also accept 65535. See
726           * http://syslinux.zytor.com/archives/2010-September/015253.html
727           * */
728          !(state->block == 0 && rblock == 65535)) {
729         /* This isn't the expected block.  Log it and up the retry counter */
730         infof(data, "Received ACK for block %d, expecting %d\n",
731               rblock, state->block);
732         state->retries++;
733         /* Bail out if over the maximum */
734         if(state->retries>state->retry_max) {
735           failf(data, "tftp_tx: giving up waiting for block %d ack",
736                 state->block);
737           res = CURLE_SEND_ERROR;
738         }
739         else {
740           /* Re-send the data packet */
741           sbytes = sendto(state->sockfd, (void *)&state->spacket.data,
742                           4+state->sbytes, SEND_4TH_ARG,
743                           (struct sockaddr *)&state->remote_addr,
744                           state->remote_addrlen);
745           /* Check all sbytes were sent */
746           if(sbytes<0) {
747             failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
748             res = CURLE_SEND_ERROR;
749           }
750         }
751         return res;
752       }
753       /* This is the expected packet.  Reset the counters and send the next
754          block */
755       time(&state->rx_time);
756       state->block++;
757     }
758     else
759       state->block = 1; /* first data block is 1 when using OACK */
760
761     state->retries = 0;
762     setpacketevent(&state->spacket, TFTP_EVENT_DATA);
763     setpacketblock(&state->spacket, state->block);
764     if(state->block > 1 && state->sbytes < (int)state->blksize) {
765       state->state = TFTP_STATE_FIN;
766       return CURLE_OK;
767     }
768     res = Curl_fillreadbuffer(state->conn, state->blksize, &state->sbytes);
769     if(res)
770       return res;
771     sbytes = sendto(state->sockfd, (void *)state->spacket.data,
772                     4+state->sbytes, SEND_4TH_ARG,
773                     (struct sockaddr *)&state->remote_addr,
774                     state->remote_addrlen);
775     /* Check all sbytes were sent */
776     if(sbytes<0) {
777       failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
778       return CURLE_SEND_ERROR;
779     }
780     /* Update the progress meter */
781     k->writebytecount += state->sbytes;
782     Curl_pgrsSetUploadCounter(data, k->writebytecount);
783     break;
784
785   case TFTP_EVENT_TIMEOUT:
786     /* Increment the retry counter and log the timeout */
787     state->retries++;
788     infof(data, "Timeout waiting for block %d ACK. "
789           " Retries = %d\n", NEXT_BLOCKNUM(state->block), state->retries);
790     /* Decide if we've had enough */
791     if(state->retries > state->retry_max) {
792       state->error = TFTP_ERR_TIMEOUT;
793       state->state = TFTP_STATE_FIN;
794     }
795     else {
796       /* Re-send the data packet */
797       sbytes = sendto(state->sockfd, (void *)state->spacket.data,
798                       4+state->sbytes, SEND_4TH_ARG,
799                       (struct sockaddr *)&state->remote_addr,
800                       state->remote_addrlen);
801       /* Check all sbytes were sent */
802       if(sbytes<0) {
803         failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
804         return CURLE_SEND_ERROR;
805       }
806       /* since this was a re-send, we remain at the still byte position */
807       Curl_pgrsSetUploadCounter(data, k->writebytecount);
808     }
809     break;
810
811   case TFTP_EVENT_ERROR:
812     state->state = TFTP_STATE_FIN;
813     setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
814     setpacketblock(&state->spacket, state->block);
815     (void)sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG,
816                  (struct sockaddr *)&state->remote_addr,
817                  state->remote_addrlen);
818     /* don't bother with the return code, but if the socket is still up we
819      * should be a good TFTP client and let the server know we're done */
820     state->state = TFTP_STATE_FIN;
821     break;
822
823   default:
824     failf(data, "tftp_tx: internal error, event: %i", (int)(event));
825     break;
826   }
827
828   return res;
829 }
830
831 /**********************************************************
832  *
833  * tftp_translate_code
834  *
835  * Translate internal error codes to CURL error codes
836  *
837  **********************************************************/
838 static CURLcode tftp_translate_code(tftp_error_t error)
839 {
840   CURLcode code = CURLE_OK;
841
842   if(error != TFTP_ERR_NONE) {
843     switch(error) {
844     case TFTP_ERR_NOTFOUND:
845       code = CURLE_TFTP_NOTFOUND;
846       break;
847     case TFTP_ERR_PERM:
848       code = CURLE_TFTP_PERM;
849       break;
850     case TFTP_ERR_DISKFULL:
851       code = CURLE_REMOTE_DISK_FULL;
852       break;
853     case TFTP_ERR_UNDEF:
854     case TFTP_ERR_ILLEGAL:
855       code = CURLE_TFTP_ILLEGAL;
856       break;
857     case TFTP_ERR_UNKNOWNID:
858       code = CURLE_TFTP_UNKNOWNID;
859       break;
860     case TFTP_ERR_EXISTS:
861       code = CURLE_REMOTE_FILE_EXISTS;
862       break;
863     case TFTP_ERR_NOSUCHUSER:
864       code = CURLE_TFTP_NOSUCHUSER;
865       break;
866     case TFTP_ERR_TIMEOUT:
867       code = CURLE_OPERATION_TIMEDOUT;
868       break;
869     case TFTP_ERR_NORESPONSE:
870       code = CURLE_COULDNT_CONNECT;
871       break;
872     default:
873       code= CURLE_ABORTED_BY_CALLBACK;
874       break;
875     }
876   }
877   else {
878     code = CURLE_OK;
879   }
880
881   return(code);
882 }
883
884 /**********************************************************
885  *
886  * tftp_state_machine
887  *
888  * The tftp state machine event dispatcher
889  *
890  **********************************************************/
891 static CURLcode tftp_state_machine(tftp_state_data_t *state,
892                                    tftp_event_t event)
893 {
894   CURLcode res = CURLE_OK;
895   struct SessionHandle *data = state->conn->data;
896   switch(state->state) {
897   case TFTP_STATE_START:
898     DEBUGF(infof(data, "TFTP_STATE_START\n"));
899     res = tftp_send_first(state, event);
900     break;
901   case TFTP_STATE_RX:
902     DEBUGF(infof(data, "TFTP_STATE_RX\n"));
903     res = tftp_rx(state, event);
904     break;
905   case TFTP_STATE_TX:
906     DEBUGF(infof(data, "TFTP_STATE_TX\n"));
907     res = tftp_tx(state, event);
908     break;
909   case TFTP_STATE_FIN:
910     infof(data, "%s\n", "TFTP finished");
911     break;
912   default:
913     DEBUGF(infof(data, "STATE: %d\n", state->state));
914     failf(data, "%s", "Internal state machine error");
915     res = CURLE_TFTP_ILLEGAL;
916     break;
917   }
918   return res;
919 }
920
921 /**********************************************************
922  *
923  * tftp_disconnect
924  *
925  * The disconnect callback
926  *
927  **********************************************************/
928 static CURLcode tftp_disconnect(struct connectdata *conn, bool dead_connection)
929 {
930   tftp_state_data_t *state = conn->proto.tftpc;
931   (void) dead_connection;
932
933   /* done, free dynamically allocated pkt buffers */
934   if(state) {
935     Curl_safefree(state->rpacket.data);
936     Curl_safefree(state->spacket.data);
937     free(state);
938   }
939
940   return CURLE_OK;
941 }
942
943 /**********************************************************
944  *
945  * tftp_connect
946  *
947  * The connect callback
948  *
949  **********************************************************/
950 static CURLcode tftp_connect(struct connectdata *conn, bool *done)
951 {
952   CURLcode code;
953   tftp_state_data_t *state;
954   int blksize, rc;
955
956   blksize = TFTP_BLKSIZE_DEFAULT;
957
958   /* If there already is a protocol-specific struct allocated for this
959      sessionhandle, deal with it */
960   Curl_reset_reqproto(conn);
961
962   state = conn->proto.tftpc = calloc(1, sizeof(tftp_state_data_t));
963   if(!state)
964     return CURLE_OUT_OF_MEMORY;
965
966   /* alloc pkt buffers based on specified blksize */
967   if(conn->data->set.tftp_blksize) {
968     blksize = (int)conn->data->set.tftp_blksize;
969     if(blksize > TFTP_BLKSIZE_MAX || blksize < TFTP_BLKSIZE_MIN )
970       return CURLE_TFTP_ILLEGAL;
971   }
972
973   if(!state->rpacket.data) {
974     state->rpacket.data = calloc(1, blksize + 2 + 2);
975
976     if(!state->rpacket.data)
977       return CURLE_OUT_OF_MEMORY;
978   }
979
980   if(!state->spacket.data) {
981     state->spacket.data = calloc(1, blksize + 2 + 2);
982
983     if(!state->spacket.data)
984       return CURLE_OUT_OF_MEMORY;
985   }
986
987   conn->bits.close = TRUE; /* we don't keep TFTP connections up bascially
988                               because there's none or very little gain for UDP
989                            */
990
991   state->conn = conn;
992   state->sockfd = state->conn->sock[FIRSTSOCKET];
993   state->state = TFTP_STATE_START;
994   state->error = TFTP_ERR_NONE;
995   state->blksize = TFTP_BLKSIZE_DEFAULT;
996   state->requested_blksize = blksize;
997
998   ((struct sockaddr *)&state->local_addr)->sa_family =
999     (unsigned short)(conn->ip_addr->ai_family);
1000
1001   tftp_set_timeouts(state);
1002
1003   if(!conn->bits.bound) {
1004     /* If not already bound, bind to any interface, random UDP port. If it is
1005      * reused or a custom local port was desired, this has already been done!
1006      *
1007      * We once used the size of the local_addr struct as the third argument
1008      * for bind() to better work with IPv6 or whatever size the struct could
1009      * have, but we learned that at least Tru64, AIX and IRIX *requires* the
1010      * size of that argument to match the exact size of a 'sockaddr_in' struct
1011      * when running IPv4-only.
1012      *
1013      * Therefore we use the size from the address we connected to, which we
1014      * assume uses the same IP version and thus hopefully this works for both
1015      * IPv4 and IPv6...
1016      */
1017     rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr,
1018               conn->ip_addr->ai_addrlen);
1019     if(rc) {
1020       failf(conn->data, "bind() failed; %s",
1021             Curl_strerror(conn, SOCKERRNO));
1022       return CURLE_COULDNT_CONNECT;
1023     }
1024     conn->bits.bound = TRUE;
1025   }
1026
1027   Curl_pgrsStartNow(conn->data);
1028
1029   *done = TRUE;
1030   code = CURLE_OK;
1031   return(code);
1032 }
1033
1034 /**********************************************************
1035  *
1036  * tftp_done
1037  *
1038  * The done callback
1039  *
1040  **********************************************************/
1041 static CURLcode tftp_done(struct connectdata *conn, CURLcode status,
1042                           bool premature)
1043 {
1044   CURLcode code = CURLE_OK;
1045   tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1046
1047   (void)status; /* unused */
1048   (void)premature; /* not used */
1049
1050   Curl_pgrsDone(conn);
1051
1052   /* If we have encountered an error */
1053   code = tftp_translate_code(state->error);
1054
1055   return code;
1056 }
1057
1058 /**********************************************************
1059  *
1060  * tftp_getsock
1061  *
1062  * The getsock callback
1063  *
1064  **********************************************************/
1065 static int tftp_getsock(struct connectdata *conn, curl_socket_t *socks,
1066                         int numsocks)
1067 {
1068   if(!numsocks)
1069     return GETSOCK_BLANK;
1070
1071   socks[0] = conn->sock[FIRSTSOCKET];
1072
1073   return GETSOCK_READSOCK(0);
1074 }
1075
1076 /**********************************************************
1077  *
1078  * tftp_receive_packet
1079  *
1080  * Called once select fires and data is ready on the socket
1081  *
1082  **********************************************************/
1083 static CURLcode tftp_receive_packet(struct connectdata *conn)
1084 {
1085   struct Curl_sockaddr_storage fromaddr;
1086   curl_socklen_t        fromlen;
1087   CURLcode              result = CURLE_OK;
1088   struct SessionHandle  *data = conn->data;
1089   tftp_state_data_t     *state = (tftp_state_data_t *)conn->proto.tftpc;
1090   struct SingleRequest  *k = &data->req;
1091
1092   /* Receive the packet */
1093   fromlen = sizeof(fromaddr);
1094   state->rbytes = (int)recvfrom(state->sockfd,
1095                                 (void *)state->rpacket.data,
1096                                 state->blksize+4,
1097                                 0,
1098                                 (struct sockaddr *)&fromaddr,
1099                                 &fromlen);
1100   if(state->remote_addrlen==0) {
1101     memcpy(&state->remote_addr, &fromaddr, fromlen);
1102     state->remote_addrlen = fromlen;
1103   }
1104
1105   /* Sanity check packet length */
1106   if(state->rbytes < 4) {
1107     failf(data, "Received too short packet");
1108     /* Not a timeout, but how best to handle it? */
1109     state->event = TFTP_EVENT_TIMEOUT;
1110   }
1111   else {
1112     /* The event is given by the TFTP packet time */
1113     state->event = (tftp_event_t)getrpacketevent(&state->rpacket);
1114
1115     switch(state->event) {
1116     case TFTP_EVENT_DATA:
1117       /* Don't pass to the client empty or retransmitted packets */
1118       if(state->rbytes > 4 &&
1119          (NEXT_BLOCKNUM(state->block) == getrpacketblock(&state->rpacket))) {
1120         result = Curl_client_write(conn, CLIENTWRITE_BODY,
1121                                    (char *)state->rpacket.data+4,
1122                                    state->rbytes-4);
1123         if(result) {
1124           tftp_state_machine(state, TFTP_EVENT_ERROR);
1125           return result;
1126         }
1127         k->bytecount += state->rbytes-4;
1128         Curl_pgrsSetDownloadCounter(data, (curl_off_t) k->bytecount);
1129       }
1130       break;
1131     case TFTP_EVENT_ERROR:
1132       state->error = (tftp_error_t)getrpacketblock(&state->rpacket);
1133       infof(data, "%s\n", (const char *)state->rpacket.data+4);
1134       break;
1135     case TFTP_EVENT_ACK:
1136       break;
1137     case TFTP_EVENT_OACK:
1138       result = tftp_parse_option_ack(state,
1139                                      (const char *)state->rpacket.data+2,
1140                                      state->rbytes-2);
1141       if(result)
1142         return result;
1143       break;
1144     case TFTP_EVENT_RRQ:
1145     case TFTP_EVENT_WRQ:
1146     default:
1147       failf(data, "%s", "Internal error: Unexpected packet");
1148       break;
1149     }
1150
1151     /* Update the progress meter */
1152     if(Curl_pgrsUpdate(conn)) {
1153       tftp_state_machine(state, TFTP_EVENT_ERROR);
1154       return CURLE_ABORTED_BY_CALLBACK;
1155     }
1156   }
1157   return result;
1158 }
1159
1160 /**********************************************************
1161  *
1162  * tftp_state_timeout
1163  *
1164  * Check if timeouts have been reached
1165  *
1166  **********************************************************/
1167 static long tftp_state_timeout(struct connectdata *conn, tftp_event_t *event)
1168 {
1169   time_t                current;
1170   tftp_state_data_t     *state = (tftp_state_data_t *)conn->proto.tftpc;
1171
1172   if (event)
1173     *event = TFTP_EVENT_NONE;
1174
1175   time(&current);
1176   if(current > state->max_time) {
1177     DEBUGF(infof(conn->data, "timeout: %ld > %ld\n",
1178                  (long)current, (long)state->max_time));
1179     state->error = TFTP_ERR_TIMEOUT;
1180     state->state = TFTP_STATE_FIN;
1181     return 0;
1182   }
1183   else if (current > state->rx_time+state->retry_time) {
1184     if (event)
1185       *event = TFTP_EVENT_TIMEOUT;
1186     time(&state->rx_time); /* update even though we received nothing */
1187   }
1188
1189   /* there's a typecast below here since 'time_t' may in fact be larger than
1190      'long', but we estimate that a 'long' will still be able to hold number
1191      of seconds even if "only" 32 bit */
1192   return (long)(state->max_time - current);
1193 }
1194
1195
1196 /**********************************************************
1197  *
1198  * tftp_easy_statemach
1199  *
1200  * Handle easy request until completion
1201  *
1202  **********************************************************/
1203 static CURLcode tftp_easy_statemach(struct connectdata *conn)
1204 {
1205   int                   rc;
1206   int                   check_time = 0;
1207   CURLcode              result = CURLE_OK;
1208   struct SessionHandle  *data = conn->data;
1209   tftp_state_data_t     *state = (tftp_state_data_t *)conn->proto.tftpc;
1210   curl_socket_t         fd_read;
1211   long                  timeout_ms;
1212   struct SingleRequest  *k = &data->req;
1213   struct timeval        transaction_start = Curl_tvnow();
1214
1215   k->start = transaction_start;
1216   k->now = transaction_start;
1217
1218   /* Run the TFTP State Machine */
1219   for(; (state->state != TFTP_STATE_FIN) && (result == CURLE_OK); ) {
1220
1221     timeout_ms = state->retry_time * 1000;
1222
1223     if (data->set.upload) {
1224       if (data->set.max_send_speed &&
1225           (data->progress.ulspeed > data->set.max_send_speed)) {
1226         fd_read = CURL_SOCKET_BAD;
1227         timeout_ms = Curl_sleep_time(data->set.max_send_speed,
1228                                      data->progress.ulspeed, state->blksize);
1229       }
1230       else {
1231         fd_read = state->sockfd;
1232       }
1233     }
1234     else {
1235       if (data->set.max_recv_speed &&
1236           (data->progress.dlspeed > data->set.max_recv_speed)) {
1237         fd_read = CURL_SOCKET_BAD;
1238         timeout_ms = Curl_sleep_time(data->set.max_recv_speed,
1239                                      data->progress.dlspeed, state->blksize);
1240       }
1241       else {
1242         fd_read = state->sockfd;
1243       }
1244     }
1245
1246     if(data->set.timeout) {
1247       timeout_ms = data->set.timeout - Curl_tvdiff(k->now, k->start);
1248       if (timeout_ms > state->retry_time * 1000)
1249         timeout_ms = state->retry_time * 1000;
1250       else if(timeout_ms < 0)
1251         timeout_ms = 0;
1252     }
1253
1254
1255     /* Wait until ready to read or timeout occurs */
1256     rc = Curl_socket_ready(fd_read, CURL_SOCKET_BAD, (int)(timeout_ms));
1257
1258     k->now = Curl_tvnow();
1259
1260     /* Force a progress callback if it's been too long */
1261     if (Curl_tvdiff(k->now, k->start) >= data->set.timeout) {
1262       if(Curl_pgrsUpdate(conn)) {
1263         tftp_state_machine(state, TFTP_EVENT_ERROR);
1264         return CURLE_ABORTED_BY_CALLBACK;
1265       }
1266       k->start = k->now;
1267     }
1268
1269     if(rc == -1) {
1270       /* bail out */
1271       int error = SOCKERRNO;
1272       failf(data, "%s", Curl_strerror(conn, error));
1273       state->event = TFTP_EVENT_ERROR;
1274     }
1275     else {
1276
1277       if(rc==0) {
1278         /* A timeout occured, but our timeout is variable, so maybe
1279            just continue? */
1280         long rtms = state->retry_time * 1000;
1281         if (Curl_tvdiff(k->now, transaction_start) > rtms) {
1282           state->event = TFTP_EVENT_TIMEOUT;
1283           /* Force a look at transfer timeouts */
1284           check_time = 1;
1285         }
1286         else {
1287           continue; /* skip state machine */
1288         }
1289       }
1290       else {
1291         result = tftp_receive_packet(conn);
1292         if (result == CURLE_OK)
1293           transaction_start = Curl_tvnow();
1294
1295         if(k->bytecountp)
1296           *k->bytecountp = k->bytecount; /* read count */
1297         if(k->writebytecountp)
1298           *k->writebytecountp = k->writebytecount; /* write count */
1299       }
1300     }
1301
1302     if(check_time) {
1303       tftp_state_timeout(conn, NULL);
1304       check_time = 0;
1305     }
1306
1307     if(result)
1308       return(result);
1309
1310     result = tftp_state_machine(state, state->event);
1311   }
1312
1313   /* Tell curl we're done */
1314   Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1315
1316   return(result);
1317 }
1318
1319 /**********************************************************
1320  *
1321  * tftp_multi_statemach
1322  *
1323  * Handle single RX socket event and return
1324  *
1325  **********************************************************/
1326 static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done)
1327 {
1328   int                   rc;
1329   tftp_event_t          event;
1330   CURLcode              result = CURLE_OK;
1331   struct SessionHandle  *data = conn->data;
1332   tftp_state_data_t     *state = (tftp_state_data_t *)conn->proto.tftpc;
1333   long                  timeout_ms = tftp_state_timeout(conn, &event);
1334
1335   *done = FALSE;
1336
1337   if(timeout_ms <= 0) {
1338     failf(data, "TFTP response timeout");
1339     return CURLE_OPERATION_TIMEDOUT;
1340   }
1341   else if (event != TFTP_EVENT_NONE) {
1342     result = tftp_state_machine(state, event);
1343     if(result != CURLE_OK)
1344       return(result);
1345     *done = (bool)(state->state == TFTP_STATE_FIN);
1346     if(*done)
1347       /* Tell curl we're done */
1348       Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1349   }
1350   else {
1351     /* no timeouts to handle, check our socket */
1352     rc = Curl_socket_ready(state->sockfd, CURL_SOCKET_BAD, 0);
1353
1354     if(rc == -1) {
1355       /* bail out */
1356       int error = SOCKERRNO;
1357       failf(data, "%s", Curl_strerror(conn, error));
1358       state->event = TFTP_EVENT_ERROR;
1359     }
1360     else if(rc != 0) {
1361       result = tftp_receive_packet(conn);
1362       if(result != CURLE_OK)
1363         return(result);
1364       result = tftp_state_machine(state, state->event);
1365       if(result != CURLE_OK)
1366         return(result);
1367       *done = (bool)(state->state == TFTP_STATE_FIN);
1368       if(*done)
1369         /* Tell curl we're done */
1370         Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1371     }
1372     /* if rc == 0, then select() timed out */
1373   }
1374
1375   return result;
1376 }
1377
1378 /**********************************************************
1379  *
1380  * tftp_doing
1381  *
1382  * Called from multi.c while DOing
1383  *
1384  **********************************************************/
1385 static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done)
1386 {
1387   CURLcode result;
1388   result = tftp_multi_statemach(conn, dophase_done);
1389
1390   if(*dophase_done) {
1391     DEBUGF(infof(conn->data, "DO phase is complete\n"));
1392   }
1393   return result;
1394 }
1395
1396 /**********************************************************
1397  *
1398  * tftp_peform
1399  *
1400  * Entry point for transfer from tftp_do, sarts state mach
1401  *
1402  **********************************************************/
1403 static CURLcode tftp_perform(struct connectdata *conn, bool *dophase_done)
1404 {
1405   CURLcode              result = CURLE_OK;
1406   tftp_state_data_t     *state = (tftp_state_data_t *)conn->proto.tftpc;
1407
1408   *dophase_done = FALSE;
1409
1410   result = tftp_state_machine(state, TFTP_EVENT_INIT);
1411
1412   if(state->state == TFTP_STATE_FIN || result != CURLE_OK)
1413     return(result);
1414
1415   if(conn->data->state.used_interface == Curl_if_multi)
1416     tftp_multi_statemach(conn, dophase_done);
1417   else {
1418     result = tftp_easy_statemach(conn);
1419     *dophase_done = TRUE; /* with the easy interface we are done here */
1420   }
1421
1422   if(*dophase_done)
1423     DEBUGF(infof(conn->data, "DO phase is complete\n"));
1424
1425   return result;
1426 }
1427
1428
1429 /**********************************************************
1430  *
1431  * tftp_do
1432  *
1433  * The do callback
1434  *
1435  * This callback initiates the TFTP transfer
1436  *
1437  **********************************************************/
1438
1439 static CURLcode tftp_do(struct connectdata *conn, bool *done)
1440 {
1441   tftp_state_data_t     *state;
1442   CURLcode              code;
1443
1444   *done = FALSE;
1445
1446   /*
1447     Since connections can be re-used between SessionHandles, this might be a
1448     connection already existing but on a fresh SessionHandle struct so we must
1449     make sure we have a good 'struct TFTP' to play with. For new connections,
1450     the struct TFTP is allocated and setup in the tftp_connect() function.
1451   */
1452   Curl_reset_reqproto(conn);
1453
1454   if(!conn->proto.tftpc) {
1455     code = tftp_connect(conn, done);
1456     if(code)
1457       return code;
1458   }
1459   state = (tftp_state_data_t *)conn->proto.tftpc;
1460
1461   code = tftp_perform(conn, done);
1462
1463   /* If tftp_perform() returned an error, use that for return code. If it
1464      was OK, see if tftp_translate_code() has an error. */
1465   if (code == CURLE_OK)
1466     /* If we have encountered an internal tftp error, translate it. */
1467     code = tftp_translate_code(state->error);
1468
1469   return code;
1470 }
1471
1472 static CURLcode tftp_setup_connection(struct connectdata * conn)
1473 {
1474   struct SessionHandle *data = conn->data;
1475   char * type;
1476   char command;
1477
1478   conn->socktype = SOCK_DGRAM;   /* UDP datagram based */
1479
1480   /* TFTP URLs support an extension like ";mode=<typecode>" that
1481    * we'll try to get now! */
1482   type = strstr(data->state.path, ";mode=");
1483
1484   if(!type)
1485     type = strstr(conn->host.rawalloc, ";mode=");
1486
1487   if(type) {
1488     *type = 0;                   /* it was in the middle of the hostname */
1489     command = Curl_raw_toupper(type[6]);
1490
1491     switch (command) {
1492     case 'A': /* ASCII mode */
1493     case 'N': /* NETASCII mode */
1494       data->set.prefer_ascii = TRUE;
1495       break;
1496
1497     case 'O': /* octet mode */
1498     case 'I': /* binary mode */
1499     default:
1500       /* switch off ASCII */
1501       data->set.prefer_ascii = FALSE;
1502       break;
1503     }
1504   }
1505
1506   return CURLE_OK;
1507 }
1508 #endif