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