1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2009, Daniel Stenberg, <daniel@haxx.se>, et al.
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.
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.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
22 ***************************************************************************/
26 #ifndef CURL_DISABLE_TFTP
27 /* -- WIN32 approved -- */
37 #ifdef HAVE_SYS_SOCKET_H
38 #include <sys/socket.h>
40 #include <netinet/in.h>
41 #ifdef HAVE_SYS_TIME_H
48 #ifdef HAVE_ARPA_INET_H
49 #include <arpa/inet.h>
54 #ifdef HAVE_SYS_IOCTL_H
55 #include <sys/ioctl.h>
58 #ifdef HAVE_SYS_PARAM_H
59 #include <sys/param.h>
65 #include <curl/curl.h>
72 #include "sockaddr.h" /* required for Curl_sockaddr_storage */
76 #define _MPRINTF_REPLACE /* use our functions only */
77 #include <curl/mprintf.h>
79 #include "curl_memory.h"
82 /* The last #include file should be: */
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"
111 TFTP_EVENT_ERROR = 5,
124 TFTP_ERR_NOSUCHUSER, /* This will never be triggered by this code */
126 /* The remaining error codes are internal to curl */
127 TFTP_ERR_NONE = -100,
132 typedef struct tftp_packet {
136 typedef struct tftp_state_data {
140 struct connectdata *conn;
141 curl_socket_t sockfd;
147 unsigned short block;
148 struct Curl_sockaddr_storage local_addr;
149 struct Curl_sockaddr_storage remote_addr;
150 curl_socklen_t remote_addrlen;
154 int requested_blksize;
155 tftp_packet_t rpacket;
156 tftp_packet_t spacket;
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);
172 * TFTP protocol handler.
175 const struct Curl_handler Curl_handler_tftp = {
177 tftp_setup_connection, /* setup_connection */
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 */
193 /**********************************************************
195 * tftp_set_timeouts -
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
202 **********************************************************/
203 static CURLcode tftp_set_timeouts(tftp_state_data_t *state)
205 time_t maxtime, timeout;
207 bool start = (bool)(state->state == TFTP_STATE_START);
209 time(&state->start_time);
211 /* Compute drop-dead time */
212 timeout_ms = Curl_timeleft(state->conn, NULL, start);
215 /* time-out, bail out, go home */
216 failf(state->conn->data, "Connection time-out");
217 return CURLE_OPERATION_TIMEDOUT;
222 maxtime = (time_t)(timeout_ms + 500) / 1000;
223 state->max_time = state->start_time+maxtime;
225 /* Set per-block timeout to total */
228 /* Average restart after 5 seconds */
229 state->retry_max = timeout/5;
231 if(state->retry_max < 1)
232 /* avoid division by zero below */
233 state->retry_max = 1;
235 /* Compute the re-start interval to suit the timeout */
236 state->retry_time = timeout/state->retry_max;
237 if(state->retry_time<1)
243 maxtime = (time_t)(timeout_ms + 500) / 1000;
247 state->max_time = state->start_time+maxtime;
249 /* Set per-block timeout to 10% of total */
250 timeout = maxtime/10 ;
252 /* Average reposting an ACK after 15 seconds */
253 state->retry_max = timeout/15;
255 /* But bound the total number */
256 if(state->retry_max<3)
259 if(state->retry_max>50)
262 /* Compute the re-ACK interval to suit the timeout */
263 state->retry_time = timeout/state->retry_max;
264 if(state->retry_time<1)
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);
275 /**********************************************************
277 * tftp_set_send_first
279 * Event handler for the START state
281 **********************************************************/
283 static void setpacketevent(tftp_packet_t *packet, unsigned short num)
285 packet->data[0] = (unsigned char)(num >> 8);
286 packet->data[1] = (unsigned char)(num & 0xff);
290 static void setpacketblock(tftp_packet_t *packet, unsigned short num)
292 packet->data[2] = (unsigned char)(num >> 8);
293 packet->data[3] = (unsigned char)(num & 0xff);
296 static unsigned short getrpacketevent(const tftp_packet_t *packet)
298 return (unsigned short)((packet->data[0] << 8) | packet->data[1]);
301 static unsigned short getrpacketblock(const tftp_packet_t *packet)
303 return (unsigned short)((packet->data[2] << 8) | packet->data[3]);
306 static size_t Curl_strnlen(const char *string, size_t maxlen)
308 const char *end = memchr (string, '\0', maxlen);
309 return end ? (size_t) (end - string) : maxlen;
312 static const char *tftp_option_get(const char *buf, size_t len,
313 const char **option, const char **value)
317 loc = Curl_strnlen( buf, len );
318 loc++; /* NULL term */
324 loc += Curl_strnlen( buf+loc, len-loc );
325 loc++; /* NULL term */
329 *value = &buf[strlen(*option) + 1];
334 static CURLcode tftp_parse_option_ack(tftp_state_data_t *state,
335 const char *ptr, int len)
337 const char *tmp = ptr;
338 struct SessionHandle *data = state->conn->data;
340 /* if OACK doesn't contain blksize option, the default (512) must be used */
341 state->blksize = TFTP_BLKSIZE_DEFAULT;
343 while (tmp < ptr + len) {
344 const char *option, *value;
346 tmp = tftp_option_get(tmp, ptr + len - tmp, &option, &value);
348 failf(data, "Malformed ACK packet, rejecting");
349 return CURLE_TFTP_ILLEGAL;
352 infof(data, "got option=(%s) value=(%s)\n", option, value);
354 if(checkprefix(option, TFTP_OPTION_BLKSIZE)) {
357 blksize = (int)strtol( value, NULL, 10 );
360 failf(data, "invalid blocksize value in OACK packet");
361 return CURLE_TFTP_ILLEGAL;
363 else if(blksize > TFTP_BLKSIZE_MAX) {
364 failf(data, "%s (%d)", "blksize is larger than max supported",
366 return CURLE_TFTP_ILLEGAL;
368 else if(blksize < TFTP_BLKSIZE_MIN) {
369 failf(data, "%s (%d)", "blksize is smaller than min supported",
371 return CURLE_TFTP_ILLEGAL;
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
377 failf(data, "%s (%d)",
378 "server requested blksize larger than allocated", blksize);
379 return CURLE_TFTP_ILLEGAL;
382 state->blksize = blksize;
383 infof(data, "%s (%d) %s (%d)\n", "blksize parsed from OACK",
384 state->blksize, "requested", state->requested_blksize);
386 else if(checkprefix(option, TFTP_OPTION_TSIZE)) {
389 tsize = strtol( value, NULL, 10 );
391 failf(data, "invalid tsize value in OACK packet");
392 return CURLE_TFTP_ILLEGAL;
394 Curl_pgrsSetDownloadSize(data, tsize);
395 infof(data, "%s (%d)\n", "tsize parsed from OACK", tsize);
402 static size_t tftp_option_add(tftp_state_data_t *state, size_t csize,
403 char *buf, const char *option)
405 if( ( strlen(option) + csize + 1U ) > state->blksize )
408 return( strlen(option) + 1 );
411 static CURLcode tftp_connect_for_tx(tftp_state_data_t *state, tftp_event_t event)
414 #ifndef CURL_DISABLE_VERBOSE_STRINGS
415 struct SessionHandle *data = state->conn->data;
417 infof(data, "%s\n", "Connected for transmit");
419 state->state = TFTP_STATE_TX;
420 res = tftp_set_timeouts(state);
423 return tftp_tx(state, event);
426 static CURLcode tftp_connect_for_rx(tftp_state_data_t *state, tftp_event_t event)
429 #ifndef CURL_DISABLE_VERBOSE_STRINGS
430 struct SessionHandle *data = state->conn->data;
432 infof(data, "%s\n", "Connected for receive");
434 state->state = TFTP_STATE_RX;
435 res = tftp_set_timeouts(state);
438 return tftp_rx(state, event);
441 static CURLcode tftp_send_first(tftp_state_data_t *state, tftp_event_t event)
444 const char *mode = "octet";
447 struct SessionHandle *data = state->conn->data;
448 CURLcode res = CURLE_OK;
450 /* Set ascii mode if -B flag was used */
451 if(data->set.prefer_ascii)
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 */
460 if(state->retries>state->retry_max) {
461 state->error = TFTP_ERR_NORESPONSE;
462 state->state = TFTP_STATE_FIN;
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);
475 /* If we are downloading, send an RRQ */
476 setpacketevent(&state->spacket, TFTP_EVENT_RRQ);
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
481 filename = curl_easy_unescape(data, &state->conn->data->state.path[1], 0,
484 return CURLE_OUT_OF_MEMORY;
486 snprintf((char *)state->spacket.data+2,
488 "%s%c%s%c", filename, '\0', mode, '\0');
489 sbytes = 4 + strlen(filename) + strlen(mode);
491 /* add tsize option */
492 if(data->set.upload && (data->set.infilesize != -1))
493 snprintf( buf, sizeof(buf), "%" FORMAT_OFF_T, data->set.infilesize );
495 strcpy(buf, "0"); /* the destination is large enough */
497 sbytes += tftp_option_add(state, sbytes,
498 (char *)state->spacket.data+sbytes,
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 );
517 if (sendto(state->sockfd, (void *)state->spacket.data,
519 state->conn->ip_addr->ai_addr,
520 state->conn->ip_addr->ai_addrlen) < 0) {
521 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
523 Curl_safefree(filename);
526 case TFTP_EVENT_OACK:
527 if(data->set.upload) {
528 res = tftp_connect_for_tx(state, event);
531 res = tftp_connect_for_rx(state, event);
535 case TFTP_EVENT_ACK: /* Connected for transmit */
536 res = tftp_connect_for_tx(state, event);
539 case TFTP_EVENT_DATA: /* Connected for receive */
540 res = tftp_connect_for_rx(state, event);
543 case TFTP_EVENT_ERROR:
544 state->state = TFTP_STATE_FIN;
548 failf(state->conn->data, "tftp_send_first: internal error");
554 /**********************************************************
558 * Event handler for the RX state
560 **********************************************************/
561 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event)
564 struct SessionHandle *data = state->conn->data;
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 */
574 "Received unexpected DATA packet block %d\n", rblock);
576 if(state->retries>state->retry_max) {
577 failf(data, "tftp_rx: giving up waiting for block %d",
579 return CURLE_TFTP_ILLEGAL;
582 /* This is the expected block. Reset counters and ACK it. */
583 state->block = (unsigned short)rblock;
585 setpacketevent(&state->spacket, TFTP_EVENT_ACK);
586 setpacketblock(&state->spacket, state->block);
587 if(sendto(state->sockfd, (void *)state->spacket.data,
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;
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;
600 state->state = TFTP_STATE_RX;
604 case TFTP_EVENT_OACK:
605 /* ACK option acknowledgement so we can move on to data */
608 setpacketevent(&state->spacket, TFTP_EVENT_ACK);
609 setpacketblock(&state->spacket, state->block);
610 if(sendto(state->sockfd, (void *)state->spacket.data,
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;
618 /* we're ready to RX data */
619 state->state = TFTP_STATE_RX;
622 case TFTP_EVENT_TIMEOUT:
623 /* Increment the retry count and fail if over the limit */
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;
632 /* Resend the previous ACK and check all sbytes were sent */
633 if(sendto(state->sockfd, (void *)state->spacket.data,
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;
643 case TFTP_EVENT_ERROR:
644 state->state = TFTP_STATE_FIN;
648 failf(data, "%s", "tftp_rx: internal error");
649 return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for
655 /**********************************************************
659 * Event handler for the TX state
661 **********************************************************/
662 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event)
664 struct SessionHandle *data = state->conn->data;
667 CURLcode res = CURLE_OK;
668 struct SingleRequest *k = &data->req;
674 rblock = getrpacketblock(&state->rpacket);
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);
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",
685 res = CURLE_SEND_ERROR;
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;
700 case TFTP_EVENT_OACK:
701 /* This is the expected packet. Reset the counters and send the next
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;
711 res = Curl_fillreadbuffer(state->conn, (int)state->blksize, &readcount);
712 state->sbytes = readcount;
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;
723 /* Update the progress meter */
724 k->writebytecount += state->sbytes;
725 Curl_pgrsSetUploadCounter(data, k->writebytecount);
728 case TFTP_EVENT_TIMEOUT:
729 /* Increment the retry counter and log the timeout */
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;
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;
747 /* since this was a re-send, we remain at the still byte position */
748 Curl_pgrsSetUploadCounter(data, k->writebytecount);
752 case TFTP_EVENT_ERROR:
753 state->state = TFTP_STATE_FIN;
757 failf(data, "%s", "tftp_tx: internal error");
764 /**********************************************************
768 * The tftp state machine event dispatcher
770 **********************************************************/
771 static CURLcode tftp_state_machine(tftp_state_data_t *state,
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);
782 DEBUGF(infof(data, "TFTP_STATE_RX\n"));
783 res = tftp_rx(state, event);
786 DEBUGF(infof(data, "TFTP_STATE_TX\n"));
787 res = tftp_tx(state, event);
790 infof(data, "%s\n", "TFTP finished");
793 DEBUGF(infof(data, "STATE: %d\n", state->state));
794 failf(data, "%s", "Internal state machine error");
795 res = CURLE_TFTP_ILLEGAL;
801 /**********************************************************
805 * The disconnect callback
807 **********************************************************/
808 static CURLcode tftp_disconnect(struct connectdata *conn)
810 tftp_state_data_t *state = conn->proto.tftpc;
812 /* done, free dynamically allocated pkt buffers */
814 Curl_safefree(state->rpacket.data);
815 Curl_safefree(state->spacket.data);
822 /**********************************************************
826 * The connect callback
828 **********************************************************/
829 static CURLcode tftp_connect(struct connectdata *conn, bool *done)
832 tftp_state_data_t *state;
835 blksize = TFTP_BLKSIZE_DEFAULT;
837 /* If there already is a protocol-specific struct allocated for this
838 sessionhandle, deal with it */
839 Curl_reset_reqproto(conn);
841 state = conn->proto.tftpc = calloc(1, sizeof(tftp_state_data_t));
843 return CURLE_OUT_OF_MEMORY;
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;
852 if(!state->rpacket.data) {
853 state->rpacket.data = calloc(1, blksize + 2 + 2);
855 if(!state->rpacket.data)
856 return CURLE_OUT_OF_MEMORY;
859 if(!state->spacket.data) {
860 state->spacket.data = calloc(1, blksize + 2 + 2);
862 if(!state->spacket.data)
863 return CURLE_OUT_OF_MEMORY;
866 conn->bits.close = TRUE; /* we don't keep TFTP connections up bascially
867 because there's none or very little gain for UDP
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;
877 ((struct sockaddr *)&state->local_addr)->sa_family =
878 (unsigned short)(conn->ip_addr->ai_family);
880 tftp_set_timeouts(state);
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!
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
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
896 rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr,
897 conn->ip_addr->ai_addrlen);
899 failf(conn->data, "bind() failed; %s",
900 Curl_strerror(conn, SOCKERRNO));
901 return CURLE_COULDNT_CONNECT;
903 conn->bits.bound = TRUE;
906 Curl_pgrsStartNow(conn->data);
913 /**********************************************************
919 **********************************************************/
920 static CURLcode tftp_done(struct connectdata *conn, CURLcode status,
923 (void)status; /* unused */
924 (void)premature; /* not used */
932 /**********************************************************
938 * This callback handles the entire TFTP transfer
940 **********************************************************/
942 static CURLcode tftp_do(struct connectdata *conn, bool *done)
944 struct SessionHandle *data = conn->data;
945 tftp_state_data_t *state;
949 struct Curl_sockaddr_storage fromaddr;
950 curl_socklen_t fromlen;
952 struct SingleRequest *k = &data->req;
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.
962 Curl_reset_reqproto(conn);
964 if(!conn->proto.tftpc) {
965 code = tftp_connect(conn, done);
969 state = (tftp_state_data_t *)conn->proto.tftpc;
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) ) {
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));
982 int error = SOCKERRNO;
983 failf(data, "%s", Curl_strerror(conn, error));
984 event = TFTP_EVENT_ERROR;
987 /* A timeout occured */
988 event = TFTP_EVENT_TIMEOUT;
990 /* Force a look at transfer timeouts */
996 /* Receive the packet */
997 fromlen = sizeof(fromaddr);
998 state->rbytes = (ssize_t)recvfrom(state->sockfd,
999 (void *)state->rpacket.data,
1002 (struct sockaddr *)&fromaddr,
1004 if(state->remote_addrlen==0) {
1005 memcpy(&state->remote_addr, &fromaddr, fromlen);
1006 state->remote_addrlen = fromlen;
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;
1017 /* The event is given by the TFTP packet time */
1018 event = (tftp_event_t)getrpacketevent(&state->rpacket);
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,
1030 k->bytecount += state->rbytes-4;
1031 Curl_pgrsSetDownloadCounter(data, (curl_off_t) k->bytecount);
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);
1038 case TFTP_EVENT_ACK:
1040 case TFTP_EVENT_OACK:
1041 code = tftp_parse_option_ack(state,
1042 (const char *)state->rpacket.data+2,
1043 (int)state->rbytes-2);
1047 case TFTP_EVENT_RRQ:
1048 case TFTP_EVENT_WRQ:
1050 failf(data, "%s", "Internal error: Unexpected packet");
1054 /* Update the progress meter */
1055 if(Curl_pgrsUpdate(conn))
1056 return CURLE_ABORTED_BY_CALLBACK;
1060 /* Check for transfer timeout every 10 blocks, or after timeout */
1061 if(check_time%10==0) {
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;
1076 /* Tell curl we're done */
1077 code = Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1081 /* If we have encountered an error */
1082 if(state->error != TFTP_ERR_NONE) {
1084 /* Translate internal error codes to curl error codes */
1085 switch(state->error) {
1086 case TFTP_ERR_NOTFOUND:
1087 code = CURLE_TFTP_NOTFOUND;
1090 code = CURLE_TFTP_PERM;
1092 case TFTP_ERR_DISKFULL:
1093 code = CURLE_REMOTE_DISK_FULL;
1095 case TFTP_ERR_UNDEF:
1096 case TFTP_ERR_ILLEGAL:
1097 code = CURLE_TFTP_ILLEGAL;
1099 case TFTP_ERR_UNKNOWNID:
1100 code = CURLE_TFTP_UNKNOWNID;
1102 case TFTP_ERR_EXISTS:
1103 code = CURLE_REMOTE_FILE_EXISTS;
1105 case TFTP_ERR_NOSUCHUSER:
1106 code = CURLE_TFTP_NOSUCHUSER;
1108 case TFTP_ERR_TIMEOUT:
1109 code = CURLE_OPERATION_TIMEDOUT;
1111 case TFTP_ERR_NORESPONSE:
1112 code = CURLE_COULDNT_CONNECT;
1115 code= CURLE_ABORTED_BY_CALLBACK;
1124 static CURLcode tftp_setup_connection(struct connectdata * conn)
1126 struct SessionHandle *data = conn->data;
1130 conn->socktype = SOCK_DGRAM; /* UDP datagram based */
1132 /* TFTP URLs support an extension like ";mode=<typecode>" that
1133 * we'll try to get now! */
1134 type = strstr(data->state.path, ";mode=");
1137 type = strstr(conn->host.rawalloc, ";mode=");
1140 *type = 0; /* it was in the middle of the hostname */
1141 command = Curl_raw_toupper(type[6]);
1144 case 'A': /* ASCII mode */
1145 case 'N': /* NETASCII mode */
1146 data->set.prefer_ascii = TRUE;
1149 case 'O': /* octet mode */
1150 case 'I': /* binary mode */
1152 /* switch off ASCII */
1153 data->set.prefer_ascii = FALSE;