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