1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2011, 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.
21 ***************************************************************************/
25 #ifndef CURL_DISABLE_TFTP
27 #ifdef HAVE_SYS_SOCKET_H
28 #include <sys/socket.h>
30 #ifdef HAVE_NETINET_IN_H
31 #include <netinet/in.h>
39 #ifdef HAVE_ARPA_INET_H
40 #include <arpa/inet.h>
45 #ifdef HAVE_SYS_IOCTL_H
46 #include <sys/ioctl.h>
49 #ifdef HAVE_SYS_PARAM_H
50 #include <sys/param.h>
54 #include <curl/curl.h>
61 #include "sockaddr.h" /* required for Curl_sockaddr_storage */
66 #define _MPRINTF_REPLACE /* use our functions only */
67 #include <curl/mprintf.h>
69 #include "curl_memory.h"
72 /* The last #include file should be: */
75 /* RFC2348 allows the block size to be negotiated */
76 #define TFTP_BLKSIZE_DEFAULT 512
77 #define TFTP_BLKSIZE_MIN 8
78 #define TFTP_BLKSIZE_MAX 65464
79 #define TFTP_OPTION_BLKSIZE "blksize"
82 #define TFTP_OPTION_TSIZE "tsize"
83 #define TFTP_OPTION_INTERVAL "timeout"
104 TFTP_EVENT_ERROR = 5,
117 TFTP_ERR_NOSUCHUSER, /* This will never be triggered by this code */
119 /* The remaining error codes are internal to curl */
120 TFTP_ERR_NONE = -100,
125 typedef struct tftp_packet {
129 typedef struct tftp_state_data {
134 struct connectdata *conn;
135 curl_socket_t sockfd;
142 unsigned short block;
143 struct Curl_sockaddr_storage local_addr;
144 struct Curl_sockaddr_storage remote_addr;
145 curl_socklen_t remote_addrlen;
149 int requested_blksize;
150 tftp_packet_t rpacket;
151 tftp_packet_t spacket;
155 /* Forward declarations */
156 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event) ;
157 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event) ;
158 static CURLcode tftp_connect(struct connectdata *conn, bool *done);
159 static CURLcode tftp_disconnect(struct connectdata *conn,
160 bool dead_connection);
161 static CURLcode tftp_do(struct connectdata *conn, bool *done);
162 static CURLcode tftp_done(struct connectdata *conn,
163 CURLcode, bool premature);
164 static CURLcode tftp_setup_connection(struct connectdata * conn);
165 static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done);
166 static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done);
167 static int tftp_getsock(struct connectdata *conn, curl_socket_t *socks,
169 static CURLcode tftp_translate_code(tftp_error_t error);
173 * TFTP protocol handler.
176 const struct Curl_handler Curl_handler_tftp = {
178 tftp_setup_connection, /* setup_connection */
180 tftp_done, /* done */
181 ZERO_NULL, /* do_more */
182 tftp_connect, /* connect_it */
183 tftp_multi_statemach, /* connecting */
184 tftp_doing, /* doing */
185 tftp_getsock, /* proto_getsock */
186 tftp_getsock, /* doing_getsock */
187 ZERO_NULL, /* domore_getsock */
188 ZERO_NULL, /* perform_getsock */
189 tftp_disconnect, /* disconnect */
190 ZERO_NULL, /* readwrite */
191 PORT_TFTP, /* defport */
192 CURLPROTO_TFTP, /* protocol */
193 PROTOPT_NONE /* flags */
196 /**********************************************************
198 * tftp_set_timeouts -
200 * Set timeouts based on state machine state.
201 * Use user provided connect timeouts until DATA or ACK
202 * packet is received, then use user-provided transfer timeouts
205 **********************************************************/
206 static CURLcode tftp_set_timeouts(tftp_state_data_t *state)
208 time_t maxtime, timeout;
210 bool start = (state->state == TFTP_STATE_START) ? TRUE : FALSE;
212 time(&state->start_time);
214 /* Compute drop-dead time */
215 timeout_ms = Curl_timeleft(state->conn->data, NULL, start);
218 /* time-out, bail out, go home */
219 failf(state->conn->data, "Connection time-out");
220 return CURLE_OPERATION_TIMEDOUT;
225 maxtime = (time_t)(timeout_ms + 500) / 1000;
226 state->max_time = state->start_time+maxtime;
228 /* Set per-block timeout to total */
231 /* Average restart after 5 seconds */
232 state->retry_max = (int)timeout/5;
234 if(state->retry_max < 1)
235 /* avoid division by zero below */
236 state->retry_max = 1;
238 /* Compute the re-start interval to suit the timeout */
239 state->retry_time = (int)timeout/state->retry_max;
240 if(state->retry_time<1)
246 maxtime = (time_t)(timeout_ms + 500) / 1000;
250 state->max_time = state->start_time+maxtime;
252 /* Set per-block timeout to total */
255 /* Average reposting an ACK after 5 seconds */
256 state->retry_max = (int)timeout/5;
258 /* But bound the total number */
259 if(state->retry_max<3)
262 if(state->retry_max>50)
265 /* Compute the re-ACK interval to suit the timeout */
266 state->retry_time = (int)(timeout/state->retry_max);
267 if(state->retry_time<1)
270 infof(state->conn->data,
271 "set timeouts for state %d; Total %ld, retry %d maxtry %d\n",
272 (int)state->state, (long)(state->max_time-state->start_time),
273 state->retry_time, state->retry_max);
276 time(&state->rx_time);
281 /**********************************************************
283 * tftp_set_send_first
285 * Event handler for the START state
287 **********************************************************/
289 static void setpacketevent(tftp_packet_t *packet, unsigned short num)
291 packet->data[0] = (unsigned char)(num >> 8);
292 packet->data[1] = (unsigned char)(num & 0xff);
296 static void setpacketblock(tftp_packet_t *packet, unsigned short num)
298 packet->data[2] = (unsigned char)(num >> 8);
299 packet->data[3] = (unsigned char)(num & 0xff);
302 static unsigned short getrpacketevent(const tftp_packet_t *packet)
304 return (unsigned short)((packet->data[0] << 8) | packet->data[1]);
307 static unsigned short getrpacketblock(const tftp_packet_t *packet)
309 return (unsigned short)((packet->data[2] << 8) | packet->data[3]);
312 static size_t Curl_strnlen(const char *string, size_t maxlen)
314 const char *end = memchr (string, '\0', maxlen);
315 return end ? (size_t) (end - string) : maxlen;
318 static const char *tftp_option_get(const char *buf, size_t len,
319 const char **option, const char **value)
323 loc = Curl_strnlen( buf, len );
324 loc++; /* NULL term */
330 loc += Curl_strnlen( buf+loc, len-loc );
331 loc++; /* NULL term */
335 *value = &buf[strlen(*option) + 1];
340 static CURLcode tftp_parse_option_ack(tftp_state_data_t *state,
341 const char *ptr, int len)
343 const char *tmp = ptr;
344 struct SessionHandle *data = state->conn->data;
346 /* if OACK doesn't contain blksize option, the default (512) must be used */
347 state->blksize = TFTP_BLKSIZE_DEFAULT;
349 while(tmp < ptr + len) {
350 const char *option, *value;
352 tmp = tftp_option_get(tmp, ptr + len - tmp, &option, &value);
354 failf(data, "Malformed ACK packet, rejecting");
355 return CURLE_TFTP_ILLEGAL;
358 infof(data, "got option=(%s) value=(%s)\n", option, value);
360 if(checkprefix(option, TFTP_OPTION_BLKSIZE)) {
363 blksize = strtol( value, NULL, 10 );
366 failf(data, "invalid blocksize value in OACK packet");
367 return CURLE_TFTP_ILLEGAL;
369 else if(blksize > TFTP_BLKSIZE_MAX) {
370 failf(data, "%s (%d)", "blksize is larger than max supported",
372 return CURLE_TFTP_ILLEGAL;
374 else if(blksize < TFTP_BLKSIZE_MIN) {
375 failf(data, "%s (%d)", "blksize is smaller than min supported",
377 return CURLE_TFTP_ILLEGAL;
379 else if(blksize > state->requested_blksize) {
380 /* could realloc pkt buffers here, but the spec doesn't call out
381 * support for the server requesting a bigger blksize than the client
383 failf(data, "%s (%ld)",
384 "server requested blksize larger than allocated", blksize);
385 return CURLE_TFTP_ILLEGAL;
388 state->blksize = (int)blksize;
389 infof(data, "%s (%d) %s (%d)\n", "blksize parsed from OACK",
390 state->blksize, "requested", state->requested_blksize);
392 else if(checkprefix(option, TFTP_OPTION_TSIZE)) {
395 tsize = strtol( value, NULL, 10 );
396 infof(data, "%s (%ld)\n", "tsize parsed from OACK", tsize);
398 /* tsize should be ignored on upload: Who cares about the size of the
400 if(!data->set.upload) {
402 failf(data, "invalid tsize -:%s:- value in OACK packet", value);
403 return CURLE_TFTP_ILLEGAL;
405 Curl_pgrsSetDownloadSize(data, tsize);
413 static size_t tftp_option_add(tftp_state_data_t *state, size_t csize,
414 char *buf, const char *option)
416 if(( strlen(option) + csize + 1 ) > (size_t)state->blksize)
419 return( strlen(option) + 1 );
422 static CURLcode tftp_connect_for_tx(tftp_state_data_t *state,
426 #ifndef CURL_DISABLE_VERBOSE_STRINGS
427 struct SessionHandle *data = state->conn->data;
429 infof(data, "%s\n", "Connected for transmit");
431 state->state = TFTP_STATE_TX;
432 res = tftp_set_timeouts(state);
435 return tftp_tx(state, event);
438 static CURLcode tftp_connect_for_rx(tftp_state_data_t *state,
442 #ifndef CURL_DISABLE_VERBOSE_STRINGS
443 struct SessionHandle *data = state->conn->data;
445 infof(data, "%s\n", "Connected for receive");
447 state->state = TFTP_STATE_RX;
448 res = tftp_set_timeouts(state);
451 return tftp_rx(state, event);
454 static CURLcode tftp_send_first(tftp_state_data_t *state, tftp_event_t event)
458 const char *mode = "octet";
461 struct SessionHandle *data = state->conn->data;
462 CURLcode res = CURLE_OK;
464 /* Set ascii mode if -B flag was used */
465 if(data->set.prefer_ascii)
470 case TFTP_EVENT_INIT: /* Send the first packet out */
471 case TFTP_EVENT_TIMEOUT: /* Resend the first packet out */
472 /* Increment the retry counter, quit if over the limit */
474 if(state->retries>state->retry_max) {
475 state->error = TFTP_ERR_NORESPONSE;
476 state->state = TFTP_STATE_FIN;
480 if(data->set.upload) {
481 /* If we are uploading, send an WRQ */
482 setpacketevent(&state->spacket, TFTP_EVENT_WRQ);
483 state->conn->data->req.upload_fromhere =
484 (char *)state->spacket.data+4;
485 if(data->set.infilesize != -1)
486 Curl_pgrsSetUploadSize(data, data->set.infilesize);
489 /* If we are downloading, send an RRQ */
490 setpacketevent(&state->spacket, TFTP_EVENT_RRQ);
492 /* As RFC3617 describes the separator slash is not actually part of the
493 file name so we skip the always-present first letter of the path
495 filename = curl_easy_unescape(data, &state->conn->data->state.path[1], 0,
498 return CURLE_OUT_OF_MEMORY;
500 snprintf((char *)state->spacket.data+2,
502 "%s%c%s%c", filename, '\0', mode, '\0');
503 sbytes = 4 + strlen(filename) + strlen(mode);
505 /* add tsize option */
506 if(data->set.upload && (data->set.infilesize != -1))
507 snprintf( buf, sizeof(buf), "%" FORMAT_OFF_T, data->set.infilesize );
509 strcpy(buf, "0"); /* the destination is large enough */
511 sbytes += tftp_option_add(state, sbytes,
512 (char *)state->spacket.data+sbytes,
514 sbytes += tftp_option_add(state, sbytes,
515 (char *)state->spacket.data+sbytes, buf);
516 /* add blksize option */
517 snprintf( buf, sizeof(buf), "%d", state->requested_blksize );
518 sbytes += tftp_option_add(state, sbytes,
519 (char *)state->spacket.data+sbytes,
520 TFTP_OPTION_BLKSIZE);
521 sbytes += tftp_option_add(state, sbytes,
522 (char *)state->spacket.data+sbytes, buf );
524 /* add timeout option */
525 snprintf( buf, sizeof(buf), "%d", state->retry_time);
526 sbytes += tftp_option_add(state, sbytes,
527 (char *)state->spacket.data+sbytes,
528 TFTP_OPTION_INTERVAL);
529 sbytes += tftp_option_add(state, sbytes,
530 (char *)state->spacket.data+sbytes, buf );
532 /* the typecase for the 3rd argument is mostly for systems that do
533 not have a size_t argument, like older unixes that want an 'int' */
534 senddata = sendto(state->sockfd, (void *)state->spacket.data,
535 (SEND_TYPE_ARG3)sbytes, 0,
536 state->conn->ip_addr->ai_addr,
537 state->conn->ip_addr->ai_addrlen);
538 if(senddata != (ssize_t)sbytes) {
539 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
541 Curl_safefree(filename);
544 case TFTP_EVENT_OACK:
545 if(data->set.upload) {
546 res = tftp_connect_for_tx(state, event);
549 res = tftp_connect_for_rx(state, event);
553 case TFTP_EVENT_ACK: /* Connected for transmit */
554 res = tftp_connect_for_tx(state, event);
557 case TFTP_EVENT_DATA: /* Connected for receive */
558 res = tftp_connect_for_rx(state, event);
561 case TFTP_EVENT_ERROR:
562 state->state = TFTP_STATE_FIN;
566 failf(state->conn->data, "tftp_send_first: internal error");
572 /* the next blocknum is x + 1 but it needs to wrap at an unsigned 16bit
574 #define NEXT_BLOCKNUM(x) (((x)+1)&0xffff)
576 /**********************************************************
580 * Event handler for the RX state
582 **********************************************************/
583 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event)
587 struct SessionHandle *data = state->conn->data;
591 case TFTP_EVENT_DATA:
592 /* Is this the block we expect? */
593 rblock = getrpacketblock(&state->rpacket);
594 if(NEXT_BLOCKNUM(state->block) != rblock) {
597 "Received unexpected DATA packet block %d, expecting block %d\n",
598 rblock, NEXT_BLOCKNUM(state->block));
601 /* This is the expected block. Reset counters and ACK it. */
602 state->block = (unsigned short)rblock;
604 setpacketevent(&state->spacket, TFTP_EVENT_ACK);
605 setpacketblock(&state->spacket, state->block);
606 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
608 (struct sockaddr *)&state->remote_addr,
609 state->remote_addrlen);
611 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
612 return CURLE_SEND_ERROR;
615 /* Check if completed (That is, a less than full packet is received) */
616 if(state->rbytes < (ssize_t)state->blksize+4) {
617 state->state = TFTP_STATE_FIN;
620 state->state = TFTP_STATE_RX;
622 time(&state->rx_time);
625 case TFTP_EVENT_OACK:
626 /* ACK option acknowledgement so we can move on to data */
629 setpacketevent(&state->spacket, TFTP_EVENT_ACK);
630 setpacketblock(&state->spacket, state->block);
631 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
633 (struct sockaddr *)&state->remote_addr,
634 state->remote_addrlen);
636 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
637 return CURLE_SEND_ERROR;
640 /* we're ready to RX data */
641 state->state = TFTP_STATE_RX;
642 time(&state->rx_time);
645 case TFTP_EVENT_TIMEOUT:
646 /* Increment the retry count and fail if over the limit */
649 "Timeout waiting for block %d ACK. Retries = %d\n",
650 NEXT_BLOCKNUM(state->block), state->retries);
651 if(state->retries > state->retry_max) {
652 state->error = TFTP_ERR_TIMEOUT;
653 state->state = TFTP_STATE_FIN;
656 /* Resend the previous ACK */
657 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
659 (struct sockaddr *)&state->remote_addr,
660 state->remote_addrlen);
662 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
663 return CURLE_SEND_ERROR;
668 case TFTP_EVENT_ERROR:
669 setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
670 setpacketblock(&state->spacket, state->block);
671 (void)sendto(state->sockfd, (void *)state->spacket.data,
673 (struct sockaddr *)&state->remote_addr,
674 state->remote_addrlen);
675 /* don't bother with the return code, but if the socket is still up we
676 * should be a good TFTP client and let the server know we're done */
677 state->state = TFTP_STATE_FIN;
681 failf(data, "%s", "tftp_rx: internal error");
682 return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for
688 /**********************************************************
692 * Event handler for the TX state
694 **********************************************************/
695 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event)
697 struct SessionHandle *data = state->conn->data;
700 CURLcode res = CURLE_OK;
701 struct SingleRequest *k = &data->req;
706 case TFTP_EVENT_OACK:
707 if(event == TFTP_EVENT_ACK) {
709 rblock = getrpacketblock(&state->rpacket);
711 if(rblock != state->block &&
712 /* There's a bug in tftpd-hpa that causes it to send us an ack for
713 * 65535 when the block number wraps to 0. So when we're expecting
714 * 0, also accept 65535. See
715 * http://syslinux.zytor.com/archives/2010-September/015253.html
717 !(state->block == 0 && rblock == 65535)) {
718 /* This isn't the expected block. Log it and up the retry counter */
719 infof(data, "Received ACK for block %d, expecting %d\n",
720 rblock, state->block);
722 /* Bail out if over the maximum */
723 if(state->retries>state->retry_max) {
724 failf(data, "tftp_tx: giving up waiting for block %d ack",
726 res = CURLE_SEND_ERROR;
729 /* Re-send the data packet */
730 sbytes = sendto(state->sockfd, (void *)&state->spacket.data,
731 4+state->sbytes, SEND_4TH_ARG,
732 (struct sockaddr *)&state->remote_addr,
733 state->remote_addrlen);
734 /* Check all sbytes were sent */
736 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
737 res = CURLE_SEND_ERROR;
742 /* This is the expected packet. Reset the counters and send the next
744 time(&state->rx_time);
748 state->block = 1; /* first data block is 1 when using OACK */
751 setpacketevent(&state->spacket, TFTP_EVENT_DATA);
752 setpacketblock(&state->spacket, state->block);
753 if(state->block > 1 && state->sbytes < (int)state->blksize) {
754 state->state = TFTP_STATE_FIN;
757 res = Curl_fillreadbuffer(state->conn, state->blksize, &state->sbytes);
760 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
761 4+state->sbytes, SEND_4TH_ARG,
762 (struct sockaddr *)&state->remote_addr,
763 state->remote_addrlen);
764 /* Check all sbytes were sent */
766 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
767 return CURLE_SEND_ERROR;
769 /* Update the progress meter */
770 k->writebytecount += state->sbytes;
771 Curl_pgrsSetUploadCounter(data, k->writebytecount);
774 case TFTP_EVENT_TIMEOUT:
775 /* Increment the retry counter and log the timeout */
777 infof(data, "Timeout waiting for block %d ACK. "
778 " Retries = %d\n", NEXT_BLOCKNUM(state->block), state->retries);
779 /* Decide if we've had enough */
780 if(state->retries > state->retry_max) {
781 state->error = TFTP_ERR_TIMEOUT;
782 state->state = TFTP_STATE_FIN;
785 /* Re-send the data packet */
786 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
787 4+state->sbytes, SEND_4TH_ARG,
788 (struct sockaddr *)&state->remote_addr,
789 state->remote_addrlen);
790 /* Check all sbytes were sent */
792 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
793 return CURLE_SEND_ERROR;
795 /* since this was a re-send, we remain at the still byte position */
796 Curl_pgrsSetUploadCounter(data, k->writebytecount);
800 case TFTP_EVENT_ERROR:
801 state->state = TFTP_STATE_FIN;
802 setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
803 setpacketblock(&state->spacket, state->block);
804 (void)sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG,
805 (struct sockaddr *)&state->remote_addr,
806 state->remote_addrlen);
807 /* don't bother with the return code, but if the socket is still up we
808 * should be a good TFTP client and let the server know we're done */
809 state->state = TFTP_STATE_FIN;
813 failf(data, "tftp_tx: internal error, event: %i", (int)(event));
820 /**********************************************************
822 * tftp_translate_code
824 * Translate internal error codes to CURL error codes
826 **********************************************************/
827 static CURLcode tftp_translate_code(tftp_error_t error)
829 CURLcode code = CURLE_OK;
831 if(error != TFTP_ERR_NONE) {
833 case TFTP_ERR_NOTFOUND:
834 code = CURLE_TFTP_NOTFOUND;
837 code = CURLE_TFTP_PERM;
839 case TFTP_ERR_DISKFULL:
840 code = CURLE_REMOTE_DISK_FULL;
843 case TFTP_ERR_ILLEGAL:
844 code = CURLE_TFTP_ILLEGAL;
846 case TFTP_ERR_UNKNOWNID:
847 code = CURLE_TFTP_UNKNOWNID;
849 case TFTP_ERR_EXISTS:
850 code = CURLE_REMOTE_FILE_EXISTS;
852 case TFTP_ERR_NOSUCHUSER:
853 code = CURLE_TFTP_NOSUCHUSER;
855 case TFTP_ERR_TIMEOUT:
856 code = CURLE_OPERATION_TIMEDOUT;
858 case TFTP_ERR_NORESPONSE:
859 code = CURLE_COULDNT_CONNECT;
862 code= CURLE_ABORTED_BY_CALLBACK;
873 /**********************************************************
877 * The tftp state machine event dispatcher
879 **********************************************************/
880 static CURLcode tftp_state_machine(tftp_state_data_t *state,
883 CURLcode res = CURLE_OK;
884 struct SessionHandle *data = state->conn->data;
885 switch(state->state) {
886 case TFTP_STATE_START:
887 DEBUGF(infof(data, "TFTP_STATE_START\n"));
888 res = tftp_send_first(state, event);
891 DEBUGF(infof(data, "TFTP_STATE_RX\n"));
892 res = tftp_rx(state, event);
895 DEBUGF(infof(data, "TFTP_STATE_TX\n"));
896 res = tftp_tx(state, event);
899 infof(data, "%s\n", "TFTP finished");
902 DEBUGF(infof(data, "STATE: %d\n", state->state));
903 failf(data, "%s", "Internal state machine error");
904 res = CURLE_TFTP_ILLEGAL;
910 /**********************************************************
914 * The disconnect callback
916 **********************************************************/
917 static CURLcode tftp_disconnect(struct connectdata *conn, bool dead_connection)
919 tftp_state_data_t *state = conn->proto.tftpc;
920 (void) dead_connection;
922 /* done, free dynamically allocated pkt buffers */
924 Curl_safefree(state->rpacket.data);
925 Curl_safefree(state->spacket.data);
932 /**********************************************************
936 * The connect callback
938 **********************************************************/
939 static CURLcode tftp_connect(struct connectdata *conn, bool *done)
942 tftp_state_data_t *state;
945 blksize = TFTP_BLKSIZE_DEFAULT;
947 /* If there already is a protocol-specific struct allocated for this
948 sessionhandle, deal with it */
949 Curl_reset_reqproto(conn);
951 state = conn->proto.tftpc = calloc(1, sizeof(tftp_state_data_t));
953 return CURLE_OUT_OF_MEMORY;
955 /* alloc pkt buffers based on specified blksize */
956 if(conn->data->set.tftp_blksize) {
957 blksize = (int)conn->data->set.tftp_blksize;
958 if(blksize > TFTP_BLKSIZE_MAX || blksize < TFTP_BLKSIZE_MIN )
959 return CURLE_TFTP_ILLEGAL;
962 if(!state->rpacket.data) {
963 state->rpacket.data = calloc(1, blksize + 2 + 2);
965 if(!state->rpacket.data)
966 return CURLE_OUT_OF_MEMORY;
969 if(!state->spacket.data) {
970 state->spacket.data = calloc(1, blksize + 2 + 2);
972 if(!state->spacket.data)
973 return CURLE_OUT_OF_MEMORY;
976 conn->bits.close = TRUE; /* we don't keep TFTP connections up bascially
977 because there's none or very little gain for UDP
981 state->sockfd = state->conn->sock[FIRSTSOCKET];
982 state->state = TFTP_STATE_START;
983 state->error = TFTP_ERR_NONE;
984 state->blksize = TFTP_BLKSIZE_DEFAULT;
985 state->requested_blksize = blksize;
987 ((struct sockaddr *)&state->local_addr)->sa_family =
988 (unsigned short)(conn->ip_addr->ai_family);
990 tftp_set_timeouts(state);
992 if(!conn->bits.bound) {
993 /* If not already bound, bind to any interface, random UDP port. If it is
994 * reused or a custom local port was desired, this has already been done!
996 * We once used the size of the local_addr struct as the third argument
997 * for bind() to better work with IPv6 or whatever size the struct could
998 * have, but we learned that at least Tru64, AIX and IRIX *requires* the
999 * size of that argument to match the exact size of a 'sockaddr_in' struct
1000 * when running IPv4-only.
1002 * Therefore we use the size from the address we connected to, which we
1003 * assume uses the same IP version and thus hopefully this works for both
1006 rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr,
1007 conn->ip_addr->ai_addrlen);
1009 failf(conn->data, "bind() failed; %s",
1010 Curl_strerror(conn, SOCKERRNO));
1011 return CURLE_COULDNT_CONNECT;
1013 conn->bits.bound = TRUE;
1016 Curl_pgrsStartNow(conn->data);
1023 /**********************************************************
1029 **********************************************************/
1030 static CURLcode tftp_done(struct connectdata *conn, CURLcode status,
1033 CURLcode code = CURLE_OK;
1034 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1036 (void)status; /* unused */
1037 (void)premature; /* not used */
1039 Curl_pgrsDone(conn);
1041 /* If we have encountered an error */
1042 code = tftp_translate_code(state->error);
1047 /**********************************************************
1051 * The getsock callback
1053 **********************************************************/
1054 static int tftp_getsock(struct connectdata *conn, curl_socket_t *socks,
1058 return GETSOCK_BLANK;
1060 socks[0] = conn->sock[FIRSTSOCKET];
1062 return GETSOCK_READSOCK(0);
1065 /**********************************************************
1067 * tftp_receive_packet
1069 * Called once select fires and data is ready on the socket
1071 **********************************************************/
1072 static CURLcode tftp_receive_packet(struct connectdata *conn)
1074 struct Curl_sockaddr_storage fromaddr;
1075 curl_socklen_t fromlen;
1076 CURLcode result = CURLE_OK;
1077 struct SessionHandle *data = conn->data;
1078 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1079 struct SingleRequest *k = &data->req;
1081 /* Receive the packet */
1082 fromlen = sizeof(fromaddr);
1083 state->rbytes = (int)recvfrom(state->sockfd,
1084 (void *)state->rpacket.data,
1087 (struct sockaddr *)&fromaddr,
1089 if(state->remote_addrlen==0) {
1090 memcpy(&state->remote_addr, &fromaddr, fromlen);
1091 state->remote_addrlen = fromlen;
1094 /* Sanity check packet length */
1095 if(state->rbytes < 4) {
1096 failf(data, "Received too short packet");
1097 /* Not a timeout, but how best to handle it? */
1098 state->event = TFTP_EVENT_TIMEOUT;
1101 /* The event is given by the TFTP packet time */
1102 state->event = (tftp_event_t)getrpacketevent(&state->rpacket);
1104 switch(state->event) {
1105 case TFTP_EVENT_DATA:
1106 /* Don't pass to the client empty or retransmitted packets */
1107 if(state->rbytes > 4 &&
1108 (NEXT_BLOCKNUM(state->block) == getrpacketblock(&state->rpacket))) {
1109 result = Curl_client_write(conn, CLIENTWRITE_BODY,
1110 (char *)state->rpacket.data+4,
1113 tftp_state_machine(state, TFTP_EVENT_ERROR);
1116 k->bytecount += state->rbytes-4;
1117 Curl_pgrsSetDownloadCounter(data, (curl_off_t) k->bytecount);
1120 case TFTP_EVENT_ERROR:
1121 state->error = (tftp_error_t)getrpacketblock(&state->rpacket);
1122 infof(data, "%s\n", (const char *)state->rpacket.data+4);
1124 case TFTP_EVENT_ACK:
1126 case TFTP_EVENT_OACK:
1127 result = tftp_parse_option_ack(state,
1128 (const char *)state->rpacket.data+2,
1133 case TFTP_EVENT_RRQ:
1134 case TFTP_EVENT_WRQ:
1136 failf(data, "%s", "Internal error: Unexpected packet");
1140 /* Update the progress meter */
1141 if(Curl_pgrsUpdate(conn)) {
1142 tftp_state_machine(state, TFTP_EVENT_ERROR);
1143 return CURLE_ABORTED_BY_CALLBACK;
1149 /**********************************************************
1151 * tftp_state_timeout
1153 * Check if timeouts have been reached
1155 **********************************************************/
1156 static long tftp_state_timeout(struct connectdata *conn, tftp_event_t *event)
1159 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1162 *event = TFTP_EVENT_NONE;
1165 if(current > state->max_time) {
1166 DEBUGF(infof(conn->data, "timeout: %ld > %ld\n",
1167 (long)current, (long)state->max_time));
1168 state->error = TFTP_ERR_TIMEOUT;
1169 state->state = TFTP_STATE_FIN;
1172 else if(current > state->rx_time+state->retry_time) {
1174 *event = TFTP_EVENT_TIMEOUT;
1175 time(&state->rx_time); /* update even though we received nothing */
1178 /* there's a typecast below here since 'time_t' may in fact be larger than
1179 'long', but we estimate that a 'long' will still be able to hold number
1180 of seconds even if "only" 32 bit */
1181 return (long)(state->max_time - current);
1185 /**********************************************************
1187 * tftp_easy_statemach
1189 * Handle easy request until completion
1191 **********************************************************/
1192 static CURLcode tftp_easy_statemach(struct connectdata *conn)
1196 CURLcode result = CURLE_OK;
1197 struct SessionHandle *data = conn->data;
1198 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1199 curl_socket_t fd_read;
1201 struct SingleRequest *k = &data->req;
1202 struct timeval transaction_start = Curl_tvnow();
1204 k->start = transaction_start;
1205 k->now = transaction_start;
1207 /* Run the TFTP State Machine */
1208 for(; (state->state != TFTP_STATE_FIN) && (result == CURLE_OK); ) {
1210 timeout_ms = state->retry_time * 1000;
1212 if(data->set.upload) {
1213 if(data->set.max_send_speed &&
1214 (data->progress.ulspeed > data->set.max_send_speed)) {
1215 fd_read = CURL_SOCKET_BAD;
1216 timeout_ms = Curl_sleep_time(data->set.max_send_speed,
1217 data->progress.ulspeed, state->blksize);
1220 fd_read = state->sockfd;
1224 if(data->set.max_recv_speed &&
1225 (data->progress.dlspeed > data->set.max_recv_speed)) {
1226 fd_read = CURL_SOCKET_BAD;
1227 timeout_ms = Curl_sleep_time(data->set.max_recv_speed,
1228 data->progress.dlspeed, state->blksize);
1231 fd_read = state->sockfd;
1234 if(data->set.timeout) {
1235 timeout_ms = data->set.timeout - Curl_tvdiff(k->now, k->start);
1236 if(timeout_ms > state->retry_time * 1000)
1237 timeout_ms = state->retry_time * 1000;
1238 else if(timeout_ms < 0)
1243 /* Wait until ready to read or timeout occurs */
1244 rc = Curl_socket_ready(fd_read, CURL_SOCKET_BAD, timeout_ms);
1246 k->now = Curl_tvnow();
1248 /* Force a progress callback if it's been too long */
1249 if(Curl_tvdiff(k->now, k->start) >= data->set.timeout) {
1250 if(Curl_pgrsUpdate(conn)) {
1251 tftp_state_machine(state, TFTP_EVENT_ERROR);
1252 return CURLE_ABORTED_BY_CALLBACK;
1259 int error = SOCKERRNO;
1260 failf(data, "%s", Curl_strerror(conn, error));
1261 state->event = TFTP_EVENT_ERROR;
1266 /* A timeout occurred, but our timeout is variable, so maybe
1268 long rtms = state->retry_time * 1000;
1269 if(Curl_tvdiff(k->now, transaction_start) > rtms) {
1270 state->event = TFTP_EVENT_TIMEOUT;
1271 /* Force a look at transfer timeouts */
1275 continue; /* skip state machine */
1279 result = tftp_receive_packet(conn);
1280 if(result == CURLE_OK)
1281 transaction_start = Curl_tvnow();
1284 *k->bytecountp = k->bytecount; /* read count */
1285 if(k->writebytecountp)
1286 *k->writebytecountp = k->writebytecount; /* write count */
1291 tftp_state_timeout(conn, NULL);
1298 result = tftp_state_machine(state, state->event);
1301 /* Tell curl we're done */
1302 Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1307 /**********************************************************
1309 * tftp_multi_statemach
1311 * Handle single RX socket event and return
1313 **********************************************************/
1314 static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done)
1318 CURLcode result = CURLE_OK;
1319 struct SessionHandle *data = conn->data;
1320 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1321 long timeout_ms = tftp_state_timeout(conn, &event);
1325 if(timeout_ms <= 0) {
1326 failf(data, "TFTP response timeout");
1327 return CURLE_OPERATION_TIMEDOUT;
1329 else if(event != TFTP_EVENT_NONE) {
1330 result = tftp_state_machine(state, event);
1331 if(result != CURLE_OK)
1333 *done = (state->state == TFTP_STATE_FIN) ? TRUE : FALSE;
1335 /* Tell curl we're done */
1336 Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1339 /* no timeouts to handle, check our socket */
1340 rc = Curl_socket_ready(state->sockfd, CURL_SOCKET_BAD, 0);
1344 int error = SOCKERRNO;
1345 failf(data, "%s", Curl_strerror(conn, error));
1346 state->event = TFTP_EVENT_ERROR;
1349 result = tftp_receive_packet(conn);
1350 if(result != CURLE_OK)
1352 result = tftp_state_machine(state, state->event);
1353 if(result != CURLE_OK)
1355 *done = (state->state == TFTP_STATE_FIN) ? TRUE : FALSE;
1357 /* Tell curl we're done */
1358 Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1360 /* if rc == 0, then select() timed out */
1366 /**********************************************************
1370 * Called from multi.c while DOing
1372 **********************************************************/
1373 static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done)
1376 result = tftp_multi_statemach(conn, dophase_done);
1379 DEBUGF(infof(conn->data, "DO phase is complete\n"));
1384 /**********************************************************
1388 * Entry point for transfer from tftp_do, sarts state mach
1390 **********************************************************/
1391 static CURLcode tftp_perform(struct connectdata *conn, bool *dophase_done)
1393 CURLcode result = CURLE_OK;
1394 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1396 *dophase_done = FALSE;
1398 result = tftp_state_machine(state, TFTP_EVENT_INIT);
1400 if(state->state == TFTP_STATE_FIN || result != CURLE_OK)
1403 if(conn->data->state.used_interface == Curl_if_multi)
1404 tftp_multi_statemach(conn, dophase_done);
1406 result = tftp_easy_statemach(conn);
1407 *dophase_done = TRUE; /* with the easy interface we are done here */
1411 DEBUGF(infof(conn->data, "DO phase is complete\n"));
1417 /**********************************************************
1423 * This callback initiates the TFTP transfer
1425 **********************************************************/
1427 static CURLcode tftp_do(struct connectdata *conn, bool *done)
1429 tftp_state_data_t *state;
1435 Since connections can be re-used between SessionHandles, this might be a
1436 connection already existing but on a fresh SessionHandle struct so we must
1437 make sure we have a good 'struct TFTP' to play with. For new connections,
1438 the struct TFTP is allocated and setup in the tftp_connect() function.
1440 Curl_reset_reqproto(conn);
1442 if(!conn->proto.tftpc) {
1443 code = tftp_connect(conn, done);
1447 state = (tftp_state_data_t *)conn->proto.tftpc;
1449 code = tftp_perform(conn, done);
1451 /* If tftp_perform() returned an error, use that for return code. If it
1452 was OK, see if tftp_translate_code() has an error. */
1453 if(code == CURLE_OK)
1454 /* If we have encountered an internal tftp error, translate it. */
1455 code = tftp_translate_code(state->error);
1460 static CURLcode tftp_setup_connection(struct connectdata * conn)
1462 struct SessionHandle *data = conn->data;
1466 conn->socktype = SOCK_DGRAM; /* UDP datagram based */
1468 /* TFTP URLs support an extension like ";mode=<typecode>" that
1469 * we'll try to get now! */
1470 type = strstr(data->state.path, ";mode=");
1473 type = strstr(conn->host.rawalloc, ";mode=");
1476 *type = 0; /* it was in the middle of the hostname */
1477 command = Curl_raw_toupper(type[6]);
1480 case 'A': /* ASCII mode */
1481 case 'N': /* NETASCII mode */
1482 data->set.prefer_ascii = TRUE;
1485 case 'O': /* octet mode */
1486 case 'I': /* binary mode */
1488 /* switch off ASCII */
1489 data->set.prefer_ascii = FALSE;