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
26 /* -- WIN32 approved -- */
36 #ifdef HAVE_SYS_SOCKET_H
37 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #ifdef HAVE_SYS_TIME_H
47 #ifdef HAVE_ARPA_INET_H
48 #include <arpa/inet.h>
53 #ifdef HAVE_SYS_IOCTL_H
54 #include <sys/ioctl.h>
57 #ifdef HAVE_SYS_PARAM_H
58 #include <sys/param.h>
64 #include <curl/curl.h>
71 #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"
92 #define TFTP_OPTION_TSIZE "tsize"
93 #define TFTP_OPTION_INTERVAL "timeout"
108 TFTP_EVENT_NONE = -1,
114 TFTP_EVENT_ERROR = 5,
127 TFTP_ERR_NOSUCHUSER, /* This will never be triggered by this code */
129 /* The remaining error codes are internal to curl */
130 TFTP_ERR_NONE = -100,
135 typedef struct tftp_packet {
139 typedef struct tftp_state_data {
144 struct connectdata *conn;
145 curl_socket_t sockfd;
152 unsigned short block;
153 struct Curl_sockaddr_storage local_addr;
154 struct Curl_sockaddr_storage remote_addr;
155 curl_socklen_t remote_addrlen;
159 int requested_blksize;
160 tftp_packet_t rpacket;
161 tftp_packet_t spacket;
165 /* Forward declarations */
166 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event) ;
167 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event) ;
168 static CURLcode tftp_connect(struct connectdata *conn, bool *done);
169 static CURLcode tftp_disconnect(struct connectdata *conn, bool dead_connection);
170 static CURLcode tftp_do(struct connectdata *conn, bool *done);
171 static CURLcode tftp_done(struct connectdata *conn,
172 CURLcode, bool premature);
173 static CURLcode tftp_setup_connection(struct connectdata * conn);
174 static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done);
175 static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done);
176 static int tftp_getsock(struct connectdata *conn, curl_socket_t *socks,
178 static CURLcode tftp_translate_code(tftp_error_t error);
182 * TFTP protocol handler.
185 const struct Curl_handler Curl_handler_tftp = {
187 tftp_setup_connection, /* setup_connection */
189 tftp_done, /* done */
190 ZERO_NULL, /* do_more */
191 tftp_connect, /* connect_it */
192 tftp_multi_statemach, /* connecting */
193 tftp_doing, /* doing */
194 tftp_getsock, /* proto_getsock */
195 tftp_getsock, /* doing_getsock */
196 ZERO_NULL, /* perform_getsock */
197 tftp_disconnect, /* disconnect */
198 PORT_TFTP, /* defport */
199 CURLPROTO_TFTP, /* protocol */
200 PROTOPT_NONE /* flags */
203 /**********************************************************
205 * tftp_set_timeouts -
207 * Set timeouts based on state machine state.
208 * Use user provided connect timeouts until DATA or ACK
209 * packet is received, then use user-provided transfer timeouts
212 **********************************************************/
213 static CURLcode tftp_set_timeouts(tftp_state_data_t *state)
215 time_t maxtime, timeout;
217 bool start = (bool)(state->state == TFTP_STATE_START);
219 time(&state->start_time);
221 /* Compute drop-dead time */
222 timeout_ms = Curl_timeleft(state->conn->data, NULL, start);
225 /* time-out, bail out, go home */
226 failf(state->conn->data, "Connection time-out");
227 return CURLE_OPERATION_TIMEDOUT;
232 maxtime = (time_t)(timeout_ms + 500) / 1000;
233 state->max_time = state->start_time+maxtime;
235 /* Set per-block timeout to total */
238 /* Average restart after 5 seconds */
239 state->retry_max = (int)timeout/5;
241 if(state->retry_max < 1)
242 /* avoid division by zero below */
243 state->retry_max = 1;
245 /* Compute the re-start interval to suit the timeout */
246 state->retry_time = (int)timeout/state->retry_max;
247 if(state->retry_time<1)
253 maxtime = (time_t)(timeout_ms + 500) / 1000;
257 state->max_time = state->start_time+maxtime;
259 /* Set per-block timeout to 10% of total */
260 timeout = maxtime/10 ;
262 /* Average reposting an ACK after 15 seconds */
263 state->retry_max = (int)timeout/15;
265 /* But bound the total number */
266 if(state->retry_max<3)
269 if(state->retry_max>50)
272 /* Compute the re-ACK interval to suit the timeout */
273 state->retry_time = (int)(timeout/state->retry_max);
274 if(state->retry_time<1)
277 infof(state->conn->data,
278 "set timeouts for state %d; Total %ld, retry %d maxtry %d\n",
279 (int)state->state, (long)(state->max_time-state->start_time),
280 state->retry_time, state->retry_max);
283 time(&state->rx_time);
288 /**********************************************************
290 * tftp_set_send_first
292 * Event handler for the START state
294 **********************************************************/
296 static void setpacketevent(tftp_packet_t *packet, unsigned short num)
298 packet->data[0] = (unsigned char)(num >> 8);
299 packet->data[1] = (unsigned char)(num & 0xff);
303 static void setpacketblock(tftp_packet_t *packet, unsigned short num)
305 packet->data[2] = (unsigned char)(num >> 8);
306 packet->data[3] = (unsigned char)(num & 0xff);
309 static unsigned short getrpacketevent(const tftp_packet_t *packet)
311 return (unsigned short)((packet->data[0] << 8) | packet->data[1]);
314 static unsigned short getrpacketblock(const tftp_packet_t *packet)
316 return (unsigned short)((packet->data[2] << 8) | packet->data[3]);
319 static size_t Curl_strnlen(const char *string, size_t maxlen)
321 const char *end = memchr (string, '\0', maxlen);
322 return end ? (size_t) (end - string) : maxlen;
325 static const char *tftp_option_get(const char *buf, size_t len,
326 const char **option, const char **value)
330 loc = Curl_strnlen( buf, len );
331 loc++; /* NULL term */
337 loc += Curl_strnlen( buf+loc, len-loc );
338 loc++; /* NULL term */
342 *value = &buf[strlen(*option) + 1];
347 static CURLcode tftp_parse_option_ack(tftp_state_data_t *state,
348 const char *ptr, int len)
350 const char *tmp = ptr;
351 struct SessionHandle *data = state->conn->data;
353 /* if OACK doesn't contain blksize option, the default (512) must be used */
354 state->blksize = TFTP_BLKSIZE_DEFAULT;
356 while (tmp < ptr + len) {
357 const char *option, *value;
359 tmp = tftp_option_get(tmp, ptr + len - tmp, &option, &value);
361 failf(data, "Malformed ACK packet, rejecting");
362 return CURLE_TFTP_ILLEGAL;
365 infof(data, "got option=(%s) value=(%s)\n", option, value);
367 if(checkprefix(option, TFTP_OPTION_BLKSIZE)) {
370 blksize = strtol( value, NULL, 10 );
373 failf(data, "invalid blocksize value in OACK packet");
374 return CURLE_TFTP_ILLEGAL;
376 else if(blksize > TFTP_BLKSIZE_MAX) {
377 failf(data, "%s (%d)", "blksize is larger than max supported",
379 return CURLE_TFTP_ILLEGAL;
381 else if(blksize < TFTP_BLKSIZE_MIN) {
382 failf(data, "%s (%d)", "blksize is smaller than min supported",
384 return CURLE_TFTP_ILLEGAL;
386 else if (blksize > state->requested_blksize) {
387 /* could realloc pkt buffers here, but the spec doesn't call out
388 * support for the server requesting a bigger blksize than the client
390 failf(data, "%s (%ld)",
391 "server requested blksize larger than allocated", blksize);
392 return CURLE_TFTP_ILLEGAL;
395 state->blksize = (int)blksize;
396 infof(data, "%s (%d) %s (%d)\n", "blksize parsed from OACK",
397 state->blksize, "requested", state->requested_blksize);
399 else if(checkprefix(option, TFTP_OPTION_TSIZE)) {
402 tsize = strtol( value, NULL, 10 );
403 infof(data, "%s (%ld)\n", "tsize parsed from OACK", tsize);
405 /* tsize should be ignored on upload: Who cares about the size of the
407 if (!data->set.upload) {
409 failf(data, "invalid tsize -:%s:- value in OACK packet", value);
410 return CURLE_TFTP_ILLEGAL;
412 Curl_pgrsSetDownloadSize(data, tsize);
420 static size_t tftp_option_add(tftp_state_data_t *state, size_t csize,
421 char *buf, const char *option)
423 if( ( strlen(option) + csize + 1 ) > (size_t)state->blksize )
426 return( strlen(option) + 1 );
429 static CURLcode tftp_connect_for_tx(tftp_state_data_t *state,
433 #ifndef CURL_DISABLE_VERBOSE_STRINGS
434 struct SessionHandle *data = state->conn->data;
436 infof(data, "%s\n", "Connected for transmit");
438 state->state = TFTP_STATE_TX;
439 res = tftp_set_timeouts(state);
442 return tftp_tx(state, event);
445 static CURLcode tftp_connect_for_rx(tftp_state_data_t *state,
449 #ifndef CURL_DISABLE_VERBOSE_STRINGS
450 struct SessionHandle *data = state->conn->data;
452 infof(data, "%s\n", "Connected for receive");
454 state->state = TFTP_STATE_RX;
455 res = tftp_set_timeouts(state);
458 return tftp_rx(state, event);
461 static CURLcode tftp_send_first(tftp_state_data_t *state, tftp_event_t event)
465 const char *mode = "octet";
468 struct SessionHandle *data = state->conn->data;
469 CURLcode res = CURLE_OK;
471 /* Set ascii mode if -B flag was used */
472 if(data->set.prefer_ascii)
477 case TFTP_EVENT_INIT: /* Send the first packet out */
478 case TFTP_EVENT_TIMEOUT: /* Resend the first packet out */
479 /* Increment the retry counter, quit if over the limit */
481 if(state->retries>state->retry_max) {
482 state->error = TFTP_ERR_NORESPONSE;
483 state->state = TFTP_STATE_FIN;
487 if(data->set.upload) {
488 /* If we are uploading, send an WRQ */
489 setpacketevent(&state->spacket, TFTP_EVENT_WRQ);
490 state->conn->data->req.upload_fromhere =
491 (char *)state->spacket.data+4;
492 if(data->set.infilesize != -1)
493 Curl_pgrsSetUploadSize(data, data->set.infilesize);
496 /* If we are downloading, send an RRQ */
497 setpacketevent(&state->spacket, TFTP_EVENT_RRQ);
499 /* As RFC3617 describes the separator slash is not actually part of the
500 file name so we skip the always-present first letter of the path
502 filename = curl_easy_unescape(data, &state->conn->data->state.path[1], 0,
505 return CURLE_OUT_OF_MEMORY;
507 snprintf((char *)state->spacket.data+2,
509 "%s%c%s%c", filename, '\0', mode, '\0');
510 sbytes = 4 + strlen(filename) + strlen(mode);
512 /* add tsize option */
513 if(data->set.upload && (data->set.infilesize != -1))
514 snprintf( buf, sizeof(buf), "%" FORMAT_OFF_T, data->set.infilesize );
516 strcpy(buf, "0"); /* the destination is large enough */
518 sbytes += tftp_option_add(state, sbytes,
519 (char *)state->spacket.data+sbytes,
521 sbytes += tftp_option_add(state, sbytes,
522 (char *)state->spacket.data+sbytes, buf);
523 /* add blksize option */
524 snprintf( buf, sizeof(buf), "%d", state->requested_blksize );
525 sbytes += tftp_option_add(state, sbytes,
526 (char *)state->spacket.data+sbytes,
527 TFTP_OPTION_BLKSIZE);
528 sbytes += tftp_option_add(state, sbytes,
529 (char *)state->spacket.data+sbytes, buf );
531 /* add timeout option */
532 snprintf( buf, sizeof(buf), "%d", state->retry_time);
533 sbytes += tftp_option_add(state, sbytes,
534 (char *)state->spacket.data+sbytes,
535 TFTP_OPTION_INTERVAL);
536 sbytes += tftp_option_add(state, sbytes,
537 (char *)state->spacket.data+sbytes, buf );
539 /* the typecase for the 3rd argument is mostly for systems that do
540 not have a size_t argument, like older unixes that want an 'int' */
541 senddata = sendto(state->sockfd, (void *)state->spacket.data,
542 (SEND_TYPE_ARG3)sbytes, 0,
543 state->conn->ip_addr->ai_addr,
544 state->conn->ip_addr->ai_addrlen);
545 if(senddata != (ssize_t)sbytes) {
546 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
548 Curl_safefree(filename);
551 case TFTP_EVENT_OACK:
552 if(data->set.upload) {
553 res = tftp_connect_for_tx(state, event);
556 res = tftp_connect_for_rx(state, event);
560 case TFTP_EVENT_ACK: /* Connected for transmit */
561 res = tftp_connect_for_tx(state, event);
564 case TFTP_EVENT_DATA: /* Connected for receive */
565 res = tftp_connect_for_rx(state, event);
568 case TFTP_EVENT_ERROR:
569 state->state = TFTP_STATE_FIN;
573 failf(state->conn->data, "tftp_send_first: internal error");
579 /* the next blocknum is x + 1 but it needs to wrap at an unsigned 16bit
581 #define NEXT_BLOCKNUM(x) (((x)+1)&0xffff)
583 /**********************************************************
587 * Event handler for the RX state
589 **********************************************************/
590 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event)
594 struct SessionHandle *data = state->conn->data;
598 case TFTP_EVENT_DATA:
599 /* Is this the block we expect? */
600 rblock = getrpacketblock(&state->rpacket);
601 if(NEXT_BLOCKNUM(state->block) != rblock) {
602 /* No, log it, up the retry count and fail if over the limit */
604 "Received unexpected DATA packet block %d\n", rblock);
606 if(state->retries > state->retry_max) {
607 failf(data, "tftp_rx: giving up waiting for block %d",
608 NEXT_BLOCKNUM(state->block));
609 return CURLE_TFTP_ILLEGAL;
613 /* This is the expected block. Reset counters and ACK it. */
614 state->block = (unsigned short)rblock;
616 setpacketevent(&state->spacket, TFTP_EVENT_ACK);
617 setpacketblock(&state->spacket, state->block);
618 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
620 (struct sockaddr *)&state->remote_addr,
621 state->remote_addrlen);
623 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
624 return CURLE_SEND_ERROR;
627 /* Check if completed (That is, a less than full packet is received) */
628 if(state->rbytes < (ssize_t)state->blksize+4){
629 state->state = TFTP_STATE_FIN;
632 state->state = TFTP_STATE_RX;
634 time(&state->rx_time);
637 case TFTP_EVENT_OACK:
638 /* ACK option acknowledgement so we can move on to data */
641 setpacketevent(&state->spacket, TFTP_EVENT_ACK);
642 setpacketblock(&state->spacket, state->block);
643 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
645 (struct sockaddr *)&state->remote_addr,
646 state->remote_addrlen);
648 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
649 return CURLE_SEND_ERROR;
652 /* we're ready to RX data */
653 state->state = TFTP_STATE_RX;
654 time(&state->rx_time);
657 case TFTP_EVENT_TIMEOUT:
658 /* Increment the retry count and fail if over the limit */
661 "Timeout waiting for block %d ACK. Retries = %d\n",
662 NEXT_BLOCKNUM(state->block), state->retries);
663 if(state->retries > state->retry_max) {
664 state->error = TFTP_ERR_TIMEOUT;
665 state->state = TFTP_STATE_FIN;
668 /* Resend the previous ACK */
669 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
671 (struct sockaddr *)&state->remote_addr,
672 state->remote_addrlen);
674 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
675 return CURLE_SEND_ERROR;
680 case TFTP_EVENT_ERROR:
681 setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
682 setpacketblock(&state->spacket, state->block);
683 (void)sendto(state->sockfd, (void *)state->spacket.data,
685 (struct sockaddr *)&state->remote_addr,
686 state->remote_addrlen);
687 /* don't bother with the return code, but if the socket is still up we
688 * should be a good TFTP client and let the server know we're done */
689 state->state = TFTP_STATE_FIN;
693 failf(data, "%s", "tftp_rx: internal error");
694 return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for
700 /**********************************************************
704 * Event handler for the TX state
706 **********************************************************/
707 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event)
709 struct SessionHandle *data = state->conn->data;
712 CURLcode res = CURLE_OK;
713 struct SingleRequest *k = &data->req;
718 case TFTP_EVENT_OACK:
719 if (event == TFTP_EVENT_ACK) {
721 rblock = getrpacketblock(&state->rpacket);
723 if(rblock != state->block &&
724 /* There's a bug in tftpd-hpa that causes it to send us an ack for
725 * 65535 when the block number wraps to 0. So when we're expecting
726 * 0, also accept 65535. See
727 * http://syslinux.zytor.com/archives/2010-September/015253.html
729 !(state->block == 0 && rblock == 65535)) {
730 /* This isn't the expected block. Log it and up the retry counter */
731 infof(data, "Received ACK for block %d, expecting %d\n",
732 rblock, state->block);
734 /* Bail out if over the maximum */
735 if(state->retries>state->retry_max) {
736 failf(data, "tftp_tx: giving up waiting for block %d ack",
738 res = CURLE_SEND_ERROR;
741 /* Re-send the data packet */
742 sbytes = sendto(state->sockfd, (void *)&state->spacket.data,
743 4+state->sbytes, SEND_4TH_ARG,
744 (struct sockaddr *)&state->remote_addr,
745 state->remote_addrlen);
746 /* Check all sbytes were sent */
748 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
749 res = CURLE_SEND_ERROR;
754 /* This is the expected packet. Reset the counters and send the next
756 time(&state->rx_time);
760 state->block = 1; /* first data block is 1 when using OACK */
763 setpacketevent(&state->spacket, TFTP_EVENT_DATA);
764 setpacketblock(&state->spacket, state->block);
765 if(state->block > 1 && state->sbytes < (int)state->blksize) {
766 state->state = TFTP_STATE_FIN;
769 res = Curl_fillreadbuffer(state->conn, state->blksize, &state->sbytes);
772 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
773 4+state->sbytes, SEND_4TH_ARG,
774 (struct sockaddr *)&state->remote_addr,
775 state->remote_addrlen);
776 /* Check all sbytes were sent */
778 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
779 return CURLE_SEND_ERROR;
781 /* Update the progress meter */
782 k->writebytecount += state->sbytes;
783 Curl_pgrsSetUploadCounter(data, k->writebytecount);
786 case TFTP_EVENT_TIMEOUT:
787 /* Increment the retry counter and log the timeout */
789 infof(data, "Timeout waiting for block %d ACK. "
790 " Retries = %d\n", NEXT_BLOCKNUM(state->block), state->retries);
791 /* Decide if we've had enough */
792 if(state->retries > state->retry_max) {
793 state->error = TFTP_ERR_TIMEOUT;
794 state->state = TFTP_STATE_FIN;
797 /* Re-send the data packet */
798 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
799 4+state->sbytes, SEND_4TH_ARG,
800 (struct sockaddr *)&state->remote_addr,
801 state->remote_addrlen);
802 /* Check all sbytes were sent */
804 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
805 return CURLE_SEND_ERROR;
807 /* since this was a re-send, we remain at the still byte position */
808 Curl_pgrsSetUploadCounter(data, k->writebytecount);
812 case TFTP_EVENT_ERROR:
813 state->state = TFTP_STATE_FIN;
814 setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
815 setpacketblock(&state->spacket, state->block);
816 (void)sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG,
817 (struct sockaddr *)&state->remote_addr,
818 state->remote_addrlen);
819 /* don't bother with the return code, but if the socket is still up we
820 * should be a good TFTP client and let the server know we're done */
821 state->state = TFTP_STATE_FIN;
825 failf(data, "tftp_tx: internal error, event: %i", (int)(event));
832 /**********************************************************
834 * tftp_translate_code
836 * Translate internal error codes to CURL error codes
838 **********************************************************/
839 static CURLcode tftp_translate_code(tftp_error_t error)
841 CURLcode code = CURLE_OK;
843 if(error != TFTP_ERR_NONE) {
845 case TFTP_ERR_NOTFOUND:
846 code = CURLE_TFTP_NOTFOUND;
849 code = CURLE_TFTP_PERM;
851 case TFTP_ERR_DISKFULL:
852 code = CURLE_REMOTE_DISK_FULL;
855 case TFTP_ERR_ILLEGAL:
856 code = CURLE_TFTP_ILLEGAL;
858 case TFTP_ERR_UNKNOWNID:
859 code = CURLE_TFTP_UNKNOWNID;
861 case TFTP_ERR_EXISTS:
862 code = CURLE_REMOTE_FILE_EXISTS;
864 case TFTP_ERR_NOSUCHUSER:
865 code = CURLE_TFTP_NOSUCHUSER;
867 case TFTP_ERR_TIMEOUT:
868 code = CURLE_OPERATION_TIMEDOUT;
870 case TFTP_ERR_NORESPONSE:
871 code = CURLE_COULDNT_CONNECT;
874 code= CURLE_ABORTED_BY_CALLBACK;
885 /**********************************************************
889 * The tftp state machine event dispatcher
891 **********************************************************/
892 static CURLcode tftp_state_machine(tftp_state_data_t *state,
895 CURLcode res = CURLE_OK;
896 struct SessionHandle *data = state->conn->data;
897 switch(state->state) {
898 case TFTP_STATE_START:
899 DEBUGF(infof(data, "TFTP_STATE_START\n"));
900 res = tftp_send_first(state, event);
903 DEBUGF(infof(data, "TFTP_STATE_RX\n"));
904 res = tftp_rx(state, event);
907 DEBUGF(infof(data, "TFTP_STATE_TX\n"));
908 res = tftp_tx(state, event);
911 infof(data, "%s\n", "TFTP finished");
914 DEBUGF(infof(data, "STATE: %d\n", state->state));
915 failf(data, "%s", "Internal state machine error");
916 res = CURLE_TFTP_ILLEGAL;
922 /**********************************************************
926 * The disconnect callback
928 **********************************************************/
929 static CURLcode tftp_disconnect(struct connectdata *conn, bool dead_connection)
931 tftp_state_data_t *state = conn->proto.tftpc;
932 (void) dead_connection;
934 /* done, free dynamically allocated pkt buffers */
936 Curl_safefree(state->rpacket.data);
937 Curl_safefree(state->spacket.data);
944 /**********************************************************
948 * The connect callback
950 **********************************************************/
951 static CURLcode tftp_connect(struct connectdata *conn, bool *done)
954 tftp_state_data_t *state;
957 blksize = TFTP_BLKSIZE_DEFAULT;
959 /* If there already is a protocol-specific struct allocated for this
960 sessionhandle, deal with it */
961 Curl_reset_reqproto(conn);
963 state = conn->proto.tftpc = calloc(1, sizeof(tftp_state_data_t));
965 return CURLE_OUT_OF_MEMORY;
967 /* alloc pkt buffers based on specified blksize */
968 if(conn->data->set.tftp_blksize) {
969 blksize = (int)conn->data->set.tftp_blksize;
970 if(blksize > TFTP_BLKSIZE_MAX || blksize < TFTP_BLKSIZE_MIN )
971 return CURLE_TFTP_ILLEGAL;
974 if(!state->rpacket.data) {
975 state->rpacket.data = calloc(1, blksize + 2 + 2);
977 if(!state->rpacket.data)
978 return CURLE_OUT_OF_MEMORY;
981 if(!state->spacket.data) {
982 state->spacket.data = calloc(1, blksize + 2 + 2);
984 if(!state->spacket.data)
985 return CURLE_OUT_OF_MEMORY;
988 conn->bits.close = TRUE; /* we don't keep TFTP connections up bascially
989 because there's none or very little gain for UDP
993 state->sockfd = state->conn->sock[FIRSTSOCKET];
994 state->state = TFTP_STATE_START;
995 state->error = TFTP_ERR_NONE;
996 state->blksize = TFTP_BLKSIZE_DEFAULT;
997 state->requested_blksize = blksize;
999 ((struct sockaddr *)&state->local_addr)->sa_family =
1000 (unsigned short)(conn->ip_addr->ai_family);
1002 tftp_set_timeouts(state);
1004 if(!conn->bits.bound) {
1005 /* If not already bound, bind to any interface, random UDP port. If it is
1006 * reused or a custom local port was desired, this has already been done!
1008 * We once used the size of the local_addr struct as the third argument
1009 * for bind() to better work with IPv6 or whatever size the struct could
1010 * have, but we learned that at least Tru64, AIX and IRIX *requires* the
1011 * size of that argument to match the exact size of a 'sockaddr_in' struct
1012 * when running IPv4-only.
1014 * Therefore we use the size from the address we connected to, which we
1015 * assume uses the same IP version and thus hopefully this works for both
1018 rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr,
1019 conn->ip_addr->ai_addrlen);
1021 failf(conn->data, "bind() failed; %s",
1022 Curl_strerror(conn, SOCKERRNO));
1023 return CURLE_COULDNT_CONNECT;
1025 conn->bits.bound = TRUE;
1028 Curl_pgrsStartNow(conn->data);
1035 /**********************************************************
1041 **********************************************************/
1042 static CURLcode tftp_done(struct connectdata *conn, CURLcode status,
1045 CURLcode code = CURLE_OK;
1046 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1048 (void)status; /* unused */
1049 (void)premature; /* not used */
1051 Curl_pgrsDone(conn);
1053 /* If we have encountered an error */
1054 code = tftp_translate_code(state->error);
1059 /**********************************************************
1063 * The getsock callback
1065 **********************************************************/
1066 static int tftp_getsock(struct connectdata *conn, curl_socket_t *socks,
1070 return GETSOCK_BLANK;
1072 socks[0] = conn->sock[FIRSTSOCKET];
1074 return GETSOCK_READSOCK(0);
1077 /**********************************************************
1079 * tftp_receive_packet
1081 * Called once select fires and data is ready on the socket
1083 **********************************************************/
1084 static CURLcode tftp_receive_packet(struct connectdata *conn)
1086 struct Curl_sockaddr_storage fromaddr;
1087 curl_socklen_t fromlen;
1088 CURLcode result = CURLE_OK;
1089 struct SessionHandle *data = conn->data;
1090 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1091 struct SingleRequest *k = &data->req;
1093 /* Receive the packet */
1094 fromlen = sizeof(fromaddr);
1095 state->rbytes = (int)recvfrom(state->sockfd,
1096 (void *)state->rpacket.data,
1099 (struct sockaddr *)&fromaddr,
1101 if(state->remote_addrlen==0) {
1102 memcpy(&state->remote_addr, &fromaddr, fromlen);
1103 state->remote_addrlen = fromlen;
1106 /* Sanity check packet length */
1107 if(state->rbytes < 4) {
1108 failf(data, "Received too short packet");
1109 /* Not a timeout, but how best to handle it? */
1110 state->event = TFTP_EVENT_TIMEOUT;
1113 /* The event is given by the TFTP packet time */
1114 state->event = (tftp_event_t)getrpacketevent(&state->rpacket);
1116 switch(state->event) {
1117 case TFTP_EVENT_DATA:
1118 /* Don't pass to the client empty or retransmitted packets */
1119 if(state->rbytes > 4 &&
1120 (NEXT_BLOCKNUM(state->block) == getrpacketblock(&state->rpacket))) {
1121 result = Curl_client_write(conn, CLIENTWRITE_BODY,
1122 (char *)state->rpacket.data+4,
1125 tftp_state_machine(state, TFTP_EVENT_ERROR);
1128 k->bytecount += state->rbytes-4;
1129 Curl_pgrsSetDownloadCounter(data, (curl_off_t) k->bytecount);
1132 case TFTP_EVENT_ERROR:
1133 state->error = (tftp_error_t)getrpacketblock(&state->rpacket);
1134 infof(data, "%s\n", (const char *)state->rpacket.data+4);
1136 case TFTP_EVENT_ACK:
1138 case TFTP_EVENT_OACK:
1139 result = tftp_parse_option_ack(state,
1140 (const char *)state->rpacket.data+2,
1145 case TFTP_EVENT_RRQ:
1146 case TFTP_EVENT_WRQ:
1148 failf(data, "%s", "Internal error: Unexpected packet");
1152 /* Update the progress meter */
1153 if(Curl_pgrsUpdate(conn)) {
1154 tftp_state_machine(state, TFTP_EVENT_ERROR);
1155 return CURLE_ABORTED_BY_CALLBACK;
1161 /**********************************************************
1163 * tftp_state_timeout
1165 * Check if timeouts have been reached
1167 **********************************************************/
1168 static long tftp_state_timeout(struct connectdata *conn, tftp_event_t *event)
1171 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1174 *event = TFTP_EVENT_NONE;
1177 if(current > state->max_time) {
1178 DEBUGF(infof(conn->data, "timeout: %ld > %ld\n",
1179 (long)current, (long)state->max_time));
1180 state->error = TFTP_ERR_TIMEOUT;
1181 state->state = TFTP_STATE_FIN;
1184 else if (current > state->rx_time+state->retry_time) {
1186 *event = TFTP_EVENT_TIMEOUT;
1187 time(&state->rx_time); /* update even though we received nothing */
1190 /* there's a typecast below here since 'time_t' may in fact be larger than
1191 'long', but we estimate that a 'long' will still be able to hold number
1192 of seconds even if "only" 32 bit */
1193 return (long)(state->max_time - current);
1197 /**********************************************************
1199 * tftp_easy_statemach
1201 * Handle easy request until completion
1203 **********************************************************/
1204 static CURLcode tftp_easy_statemach(struct connectdata *conn)
1208 CURLcode result = CURLE_OK;
1209 struct SessionHandle *data = conn->data;
1210 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1211 curl_socket_t fd_read;
1213 struct SingleRequest *k = &data->req;
1214 struct timeval transaction_start = Curl_tvnow();
1216 k->start = transaction_start;
1217 k->now = transaction_start;
1219 /* Run the TFTP State Machine */
1220 for(; (state->state != TFTP_STATE_FIN) && (result == CURLE_OK); ) {
1222 timeout_ms = state->retry_time * 1000;
1224 if (data->set.upload) {
1225 if (data->set.max_send_speed &&
1226 (data->progress.ulspeed > data->set.max_send_speed)) {
1227 fd_read = CURL_SOCKET_BAD;
1228 timeout_ms = Curl_sleep_time(data->set.max_send_speed,
1229 data->progress.ulspeed, state->blksize);
1232 fd_read = state->sockfd;
1236 if (data->set.max_recv_speed &&
1237 (data->progress.dlspeed > data->set.max_recv_speed)) {
1238 fd_read = CURL_SOCKET_BAD;
1239 timeout_ms = Curl_sleep_time(data->set.max_recv_speed,
1240 data->progress.dlspeed, state->blksize);
1243 fd_read = state->sockfd;
1247 if(data->set.timeout) {
1248 timeout_ms = data->set.timeout - Curl_tvdiff(k->now, k->start);
1249 if (timeout_ms > state->retry_time * 1000)
1250 timeout_ms = state->retry_time * 1000;
1251 else if(timeout_ms < 0)
1256 /* Wait until ready to read or timeout occurs */
1257 rc = Curl_socket_ready(fd_read, CURL_SOCKET_BAD, (int)(timeout_ms));
1259 k->now = Curl_tvnow();
1261 /* Force a progress callback if it's been too long */
1262 if (Curl_tvdiff(k->now, k->start) >= data->set.timeout) {
1263 if(Curl_pgrsUpdate(conn)) {
1264 tftp_state_machine(state, TFTP_EVENT_ERROR);
1265 return CURLE_ABORTED_BY_CALLBACK;
1272 int error = SOCKERRNO;
1273 failf(data, "%s", Curl_strerror(conn, error));
1274 state->event = TFTP_EVENT_ERROR;
1279 /* A timeout occured, but our timeout is variable, so maybe
1281 long rtms = state->retry_time * 1000;
1282 if (Curl_tvdiff(k->now, transaction_start) > rtms) {
1283 state->event = TFTP_EVENT_TIMEOUT;
1284 /* Force a look at transfer timeouts */
1288 continue; /* skip state machine */
1292 result = tftp_receive_packet(conn);
1293 if (result == CURLE_OK)
1294 transaction_start = Curl_tvnow();
1297 *k->bytecountp = k->bytecount; /* read count */
1298 if(k->writebytecountp)
1299 *k->writebytecountp = k->writebytecount; /* write count */
1304 tftp_state_timeout(conn, NULL);
1311 result = tftp_state_machine(state, state->event);
1314 /* Tell curl we're done */
1315 Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1320 /**********************************************************
1322 * tftp_multi_statemach
1324 * Handle single RX socket event and return
1326 **********************************************************/
1327 static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done)
1331 CURLcode result = CURLE_OK;
1332 struct SessionHandle *data = conn->data;
1333 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1334 long timeout_ms = tftp_state_timeout(conn, &event);
1338 if(timeout_ms <= 0) {
1339 failf(data, "TFTP response timeout");
1340 return CURLE_OPERATION_TIMEDOUT;
1342 else if (event != TFTP_EVENT_NONE) {
1343 result = tftp_state_machine(state, event);
1344 if(result != CURLE_OK)
1346 *done = (bool)(state->state == TFTP_STATE_FIN);
1348 /* Tell curl we're done */
1349 Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1352 /* no timeouts to handle, check our socket */
1353 rc = Curl_socket_ready(state->sockfd, CURL_SOCKET_BAD, 0);
1357 int error = SOCKERRNO;
1358 failf(data, "%s", Curl_strerror(conn, error));
1359 state->event = TFTP_EVENT_ERROR;
1362 result = tftp_receive_packet(conn);
1363 if(result != CURLE_OK)
1365 result = tftp_state_machine(state, state->event);
1366 if(result != CURLE_OK)
1368 *done = (bool)(state->state == TFTP_STATE_FIN);
1370 /* Tell curl we're done */
1371 Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1373 /* if rc == 0, then select() timed out */
1379 /**********************************************************
1383 * Called from multi.c while DOing
1385 **********************************************************/
1386 static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done)
1389 result = tftp_multi_statemach(conn, dophase_done);
1392 DEBUGF(infof(conn->data, "DO phase is complete\n"));
1397 /**********************************************************
1401 * Entry point for transfer from tftp_do, sarts state mach
1403 **********************************************************/
1404 static CURLcode tftp_perform(struct connectdata *conn, bool *dophase_done)
1406 CURLcode result = CURLE_OK;
1407 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1409 *dophase_done = FALSE;
1411 result = tftp_state_machine(state, TFTP_EVENT_INIT);
1413 if(state->state == TFTP_STATE_FIN || result != CURLE_OK)
1416 if(conn->data->state.used_interface == Curl_if_multi)
1417 tftp_multi_statemach(conn, dophase_done);
1419 result = tftp_easy_statemach(conn);
1420 *dophase_done = TRUE; /* with the easy interface we are done here */
1424 DEBUGF(infof(conn->data, "DO phase is complete\n"));
1430 /**********************************************************
1436 * This callback initiates the TFTP transfer
1438 **********************************************************/
1440 static CURLcode tftp_do(struct connectdata *conn, bool *done)
1442 tftp_state_data_t *state;
1448 Since connections can be re-used between SessionHandles, this might be a
1449 connection already existing but on a fresh SessionHandle struct so we must
1450 make sure we have a good 'struct TFTP' to play with. For new connections,
1451 the struct TFTP is allocated and setup in the tftp_connect() function.
1453 Curl_reset_reqproto(conn);
1455 if(!conn->proto.tftpc) {
1456 code = tftp_connect(conn, done);
1460 state = (tftp_state_data_t *)conn->proto.tftpc;
1462 code = tftp_perform(conn, done);
1464 /* If tftp_perform() returned an error, use that for return code. If it
1465 was OK, see if tftp_translate_code() has an error. */
1466 if (code == CURLE_OK)
1467 /* If we have encountered an internal tftp error, translate it. */
1468 code = tftp_translate_code(state->error);
1473 static CURLcode tftp_setup_connection(struct connectdata * conn)
1475 struct SessionHandle *data = conn->data;
1479 conn->socktype = SOCK_DGRAM; /* UDP datagram based */
1481 /* TFTP URLs support an extension like ";mode=<typecode>" that
1482 * we'll try to get now! */
1483 type = strstr(data->state.path, ";mode=");
1486 type = strstr(conn->host.rawalloc, ";mode=");
1489 *type = 0; /* it was in the middle of the hostname */
1490 command = Curl_raw_toupper(type[6]);
1493 case 'A': /* ASCII mode */
1494 case 'N': /* NETASCII mode */
1495 data->set.prefer_ascii = TRUE;
1498 case 'O': /* octet mode */
1499 case 'I': /* binary mode */
1501 /* switch off ASCII */
1502 data->set.prefer_ascii = FALSE;