1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2022, 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 https://curl.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 ***************************************************************************/
23 #include "curl_setup.h"
25 #ifndef CURL_DISABLE_TFTP
27 #ifdef HAVE_NETINET_IN_H
28 #include <netinet/in.h>
33 #ifdef HAVE_ARPA_INET_H
34 #include <arpa/inet.h>
39 #ifdef HAVE_SYS_IOCTL_H
40 #include <sys/ioctl.h>
43 #ifdef HAVE_SYS_PARAM_H
44 #include <sys/param.h>
48 #include <curl/curl.h>
55 #include "sockaddr.h" /* required for Curl_sockaddr_storage */
59 #include "speedcheck.h"
63 /* The last 3 #include files should be in this order */
64 #include "curl_printf.h"
65 #include "curl_memory.h"
68 /* RFC2348 allows the block size to be negotiated */
69 #define TFTP_BLKSIZE_DEFAULT 512
70 #define TFTP_BLKSIZE_MIN 8
71 #define TFTP_BLKSIZE_MAX 65464
72 #define TFTP_OPTION_BLKSIZE "blksize"
75 #define TFTP_OPTION_TSIZE "tsize"
76 #define TFTP_OPTION_INTERVAL "timeout"
79 TFTP_MODE_NETASCII = 0,
110 TFTP_ERR_NOSUCHUSER, /* This will never be triggered by this code */
112 /* The remaining error codes are internal to curl */
113 TFTP_ERR_NONE = -100,
122 struct tftp_state_data {
127 struct Curl_easy *data;
128 curl_socket_t sockfd;
133 struct Curl_sockaddr_storage local_addr;
134 struct Curl_sockaddr_storage remote_addr;
135 curl_socklen_t remote_addrlen;
139 int requested_blksize;
140 unsigned short block;
141 struct tftp_packet rpacket;
142 struct tftp_packet spacket;
146 /* Forward declarations */
147 static CURLcode tftp_rx(struct tftp_state_data *state, tftp_event_t event);
148 static CURLcode tftp_tx(struct tftp_state_data *state, tftp_event_t event);
149 static CURLcode tftp_connect(struct Curl_easy *data, bool *done);
150 static CURLcode tftp_disconnect(struct Curl_easy *data,
151 struct connectdata *conn,
152 bool dead_connection);
153 static CURLcode tftp_do(struct Curl_easy *data, bool *done);
154 static CURLcode tftp_done(struct Curl_easy *data,
155 CURLcode, bool premature);
156 static CURLcode tftp_setup_connection(struct Curl_easy *data,
157 struct connectdata *conn);
158 static CURLcode tftp_multi_statemach(struct Curl_easy *data, bool *done);
159 static CURLcode tftp_doing(struct Curl_easy *data, bool *dophase_done);
160 static int tftp_getsock(struct Curl_easy *data, struct connectdata *conn,
161 curl_socket_t *socks);
162 static CURLcode tftp_translate_code(tftp_error_t error);
166 * TFTP protocol handler.
169 const struct Curl_handler Curl_handler_tftp = {
171 tftp_setup_connection, /* setup_connection */
173 tftp_done, /* done */
174 ZERO_NULL, /* do_more */
175 tftp_connect, /* connect_it */
176 tftp_multi_statemach, /* connecting */
177 tftp_doing, /* doing */
178 tftp_getsock, /* proto_getsock */
179 tftp_getsock, /* doing_getsock */
180 ZERO_NULL, /* domore_getsock */
181 ZERO_NULL, /* perform_getsock */
182 tftp_disconnect, /* disconnect */
183 ZERO_NULL, /* readwrite */
184 ZERO_NULL, /* connection_check */
185 ZERO_NULL, /* attach connection */
186 PORT_TFTP, /* defport */
187 CURLPROTO_TFTP, /* protocol */
188 CURLPROTO_TFTP, /* family */
189 PROTOPT_NOTCPPROXY | PROTOPT_NOURLQUERY /* flags */
192 /**********************************************************
194 * tftp_set_timeouts -
196 * Set timeouts based on state machine state.
197 * Use user provided connect timeouts until DATA or ACK
198 * packet is received, then use user-provided transfer timeouts
201 **********************************************************/
202 static CURLcode tftp_set_timeouts(struct tftp_state_data *state)
204 time_t maxtime, timeout;
205 timediff_t timeout_ms;
206 bool start = (state->state == TFTP_STATE_START) ? TRUE : FALSE;
208 /* Compute drop-dead time */
209 timeout_ms = Curl_timeleft(state->data, NULL, start);
212 /* time-out, bail out, go home */
213 failf(state->data, "Connection time-out");
214 return CURLE_OPERATION_TIMEDOUT;
218 maxtime = (time_t)(timeout_ms + 500) / 1000;
220 maxtime = 3600; /* use for calculating block timeouts */
222 /* Set per-block timeout to total */
225 /* Average reposting an ACK after 5 seconds */
226 state->retry_max = (int)timeout/5;
228 /* But bound the total number */
229 if(state->retry_max<3)
230 state->retry_max = 3;
232 if(state->retry_max>50)
233 state->retry_max = 50;
235 /* Compute the re-ACK interval to suit the timeout */
236 state->retry_time = (int)(timeout/state->retry_max);
237 if(state->retry_time<1)
238 state->retry_time = 1;
241 "set timeouts for state %d; Total % " CURL_FORMAT_CURL_OFF_T
242 ", retry %d maxtry %d",
243 (int)state->state, timeout_ms, state->retry_time, state->retry_max);
246 time(&state->rx_time);
251 /**********************************************************
253 * tftp_set_send_first
255 * Event handler for the START state
257 **********************************************************/
259 static void setpacketevent(struct tftp_packet *packet, unsigned short num)
261 packet->data[0] = (unsigned char)(num >> 8);
262 packet->data[1] = (unsigned char)(num & 0xff);
266 static void setpacketblock(struct tftp_packet *packet, unsigned short num)
268 packet->data[2] = (unsigned char)(num >> 8);
269 packet->data[3] = (unsigned char)(num & 0xff);
272 static unsigned short getrpacketevent(const struct tftp_packet *packet)
274 return (unsigned short)((packet->data[0] << 8) | packet->data[1]);
277 static unsigned short getrpacketblock(const struct tftp_packet *packet)
279 return (unsigned short)((packet->data[2] << 8) | packet->data[3]);
282 static size_t tftp_strnlen(const char *string, size_t maxlen)
284 const char *end = memchr(string, '\0', maxlen);
285 return end ? (size_t) (end - string) : maxlen;
288 static const char *tftp_option_get(const char *buf, size_t len,
289 const char **option, const char **value)
293 loc = tftp_strnlen(buf, len);
294 loc++; /* NULL term */
300 loc += tftp_strnlen(buf + loc, len-loc);
301 loc++; /* NULL term */
305 *value = &buf[strlen(*option) + 1];
310 static CURLcode tftp_parse_option_ack(struct tftp_state_data *state,
311 const char *ptr, int len)
313 const char *tmp = ptr;
314 struct Curl_easy *data = state->data;
316 /* if OACK doesn't contain blksize option, the default (512) must be used */
317 state->blksize = TFTP_BLKSIZE_DEFAULT;
319 while(tmp < ptr + len) {
320 const char *option, *value;
322 tmp = tftp_option_get(tmp, ptr + len - tmp, &option, &value);
324 failf(data, "Malformed ACK packet, rejecting");
325 return CURLE_TFTP_ILLEGAL;
328 infof(data, "got option=(%s) value=(%s)", option, value);
330 if(checkprefix(TFTP_OPTION_BLKSIZE, option)) {
333 blksize = strtol(value, NULL, 10);
336 failf(data, "invalid blocksize value in OACK packet");
337 return CURLE_TFTP_ILLEGAL;
339 if(blksize > TFTP_BLKSIZE_MAX) {
340 failf(data, "%s (%d)", "blksize is larger than max supported",
342 return CURLE_TFTP_ILLEGAL;
344 else if(blksize < TFTP_BLKSIZE_MIN) {
345 failf(data, "%s (%d)", "blksize is smaller than min supported",
347 return CURLE_TFTP_ILLEGAL;
349 else if(blksize > state->requested_blksize) {
350 /* could realloc pkt buffers here, but the spec doesn't call out
351 * support for the server requesting a bigger blksize than the client
353 failf(data, "%s (%ld)",
354 "server requested blksize larger than allocated", blksize);
355 return CURLE_TFTP_ILLEGAL;
358 state->blksize = (int)blksize;
359 infof(data, "%s (%d) %s (%d)", "blksize parsed from OACK",
360 state->blksize, "requested", state->requested_blksize);
362 else if(checkprefix(TFTP_OPTION_TSIZE, option)) {
365 tsize = strtol(value, NULL, 10);
366 infof(data, "%s (%ld)", "tsize parsed from OACK", tsize);
368 /* tsize should be ignored on upload: Who cares about the size of the
370 if(!data->set.upload) {
372 failf(data, "invalid tsize -:%s:- value in OACK packet", value);
373 return CURLE_TFTP_ILLEGAL;
375 Curl_pgrsSetDownloadSize(data, tsize);
383 static CURLcode tftp_option_add(struct tftp_state_data *state, size_t *csize,
384 char *buf, const char *option)
386 if(( strlen(option) + *csize + 1) > (size_t)state->blksize)
387 return CURLE_TFTP_ILLEGAL;
389 *csize += strlen(option) + 1;
393 static CURLcode tftp_connect_for_tx(struct tftp_state_data *state,
397 #ifndef CURL_DISABLE_VERBOSE_STRINGS
398 struct Curl_easy *data = state->data;
400 infof(data, "%s", "Connected for transmit");
402 state->state = TFTP_STATE_TX;
403 result = tftp_set_timeouts(state);
406 return tftp_tx(state, event);
409 static CURLcode tftp_connect_for_rx(struct tftp_state_data *state,
413 #ifndef CURL_DISABLE_VERBOSE_STRINGS
414 struct Curl_easy *data = state->data;
416 infof(data, "%s", "Connected for receive");
418 state->state = TFTP_STATE_RX;
419 result = tftp_set_timeouts(state);
422 return tftp_rx(state, event);
425 static CURLcode tftp_send_first(struct tftp_state_data *state,
430 const char *mode = "octet";
432 struct Curl_easy *data = state->data;
433 CURLcode result = CURLE_OK;
435 /* Set ascii mode if -B flag was used */
436 if(data->state.prefer_ascii)
441 case TFTP_EVENT_INIT: /* Send the first packet out */
442 case TFTP_EVENT_TIMEOUT: /* Resend the first packet out */
443 /* Increment the retry counter, quit if over the limit */
445 if(state->retries>state->retry_max) {
446 state->error = TFTP_ERR_NORESPONSE;
447 state->state = TFTP_STATE_FIN;
451 if(data->set.upload) {
452 /* If we are uploading, send an WRQ */
453 setpacketevent(&state->spacket, TFTP_EVENT_WRQ);
454 state->data->req.upload_fromhere =
455 (char *)state->spacket.data + 4;
456 if(data->state.infilesize != -1)
457 Curl_pgrsSetUploadSize(data, data->state.infilesize);
460 /* If we are downloading, send an RRQ */
461 setpacketevent(&state->spacket, TFTP_EVENT_RRQ);
463 /* As RFC3617 describes the separator slash is not actually part of the
464 file name so we skip the always-present first letter of the path
466 result = Curl_urldecode(&state->data->state.up.path[1], 0,
467 &filename, NULL, REJECT_ZERO);
471 if(strlen(filename) > (state->blksize - strlen(mode) - 4)) {
472 failf(data, "TFTP file name too long");
474 return CURLE_TFTP_ILLEGAL; /* too long file name field */
477 msnprintf((char *)state->spacket.data + 2,
479 "%s%c%s%c", filename, '\0', mode, '\0');
480 sbytes = 4 + strlen(filename) + strlen(mode);
482 /* optional addition of TFTP options */
483 if(!data->set.tftp_no_options) {
485 /* add tsize option */
486 if(data->set.upload && (data->state.infilesize != -1))
487 msnprintf(buf, sizeof(buf), "%" CURL_FORMAT_CURL_OFF_T,
488 data->state.infilesize);
490 strcpy(buf, "0"); /* the destination is large enough */
492 result = tftp_option_add(state, &sbytes,
493 (char *)state->spacket.data + sbytes,
495 if(result == CURLE_OK)
496 result = tftp_option_add(state, &sbytes,
497 (char *)state->spacket.data + sbytes, buf);
499 /* add blksize option */
500 msnprintf(buf, sizeof(buf), "%d", state->requested_blksize);
501 if(result == CURLE_OK)
502 result = tftp_option_add(state, &sbytes,
503 (char *)state->spacket.data + sbytes,
504 TFTP_OPTION_BLKSIZE);
505 if(result == CURLE_OK)
506 result = tftp_option_add(state, &sbytes,
507 (char *)state->spacket.data + sbytes, buf);
509 /* add timeout option */
510 msnprintf(buf, sizeof(buf), "%d", state->retry_time);
511 if(result == CURLE_OK)
512 result = tftp_option_add(state, &sbytes,
513 (char *)state->spacket.data + sbytes,
514 TFTP_OPTION_INTERVAL);
515 if(result == CURLE_OK)
516 result = tftp_option_add(state, &sbytes,
517 (char *)state->spacket.data + sbytes, buf);
519 if(result != CURLE_OK) {
520 failf(data, "TFTP buffer too small for options");
522 return CURLE_TFTP_ILLEGAL;
526 /* the typecase for the 3rd argument is mostly for systems that do
527 not have a size_t argument, like older unixes that want an 'int' */
528 senddata = sendto(state->sockfd, (void *)state->spacket.data,
529 (SEND_TYPE_ARG3)sbytes, 0,
530 data->conn->ip_addr->ai_addr,
531 data->conn->ip_addr->ai_addrlen);
532 if(senddata != (ssize_t)sbytes) {
533 char buffer[STRERROR_LEN];
534 failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
539 case TFTP_EVENT_OACK:
540 if(data->set.upload) {
541 result = tftp_connect_for_tx(state, event);
544 result = tftp_connect_for_rx(state, event);
548 case TFTP_EVENT_ACK: /* Connected for transmit */
549 result = tftp_connect_for_tx(state, event);
552 case TFTP_EVENT_DATA: /* Connected for receive */
553 result = tftp_connect_for_rx(state, event);
556 case TFTP_EVENT_ERROR:
557 state->state = TFTP_STATE_FIN;
561 failf(state->data, "tftp_send_first: internal error");
568 /* the next blocknum is x + 1 but it needs to wrap at an unsigned 16bit
570 #define NEXT_BLOCKNUM(x) (((x) + 1)&0xffff)
572 /**********************************************************
576 * Event handler for the RX state
578 **********************************************************/
579 static CURLcode tftp_rx(struct tftp_state_data *state,
584 struct Curl_easy *data = state->data;
585 char buffer[STRERROR_LEN];
589 case TFTP_EVENT_DATA:
590 /* Is this the block we expect? */
591 rblock = getrpacketblock(&state->rpacket);
592 if(NEXT_BLOCKNUM(state->block) == rblock) {
593 /* This is the expected block. Reset counters and ACK it. */
596 else if(state->block == rblock) {
597 /* This is the last recently received block again. Log it and ACK it
599 infof(data, "Received last DATA packet block %d again.", rblock);
602 /* totally unexpected, just log it */
604 "Received unexpected DATA packet block %d, expecting block %d",
605 rblock, NEXT_BLOCKNUM(state->block));
609 /* ACK this block. */
610 state->block = (unsigned short)rblock;
611 setpacketevent(&state->spacket, TFTP_EVENT_ACK);
612 setpacketblock(&state->spacket, state->block);
613 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
615 (struct sockaddr *)&state->remote_addr,
616 state->remote_addrlen);
618 failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
619 return CURLE_SEND_ERROR;
622 /* Check if completed (That is, a less than full packet is received) */
623 if(state->rbytes < (ssize_t)state->blksize + 4) {
624 state->state = TFTP_STATE_FIN;
627 state->state = TFTP_STATE_RX;
629 time(&state->rx_time);
632 case TFTP_EVENT_OACK:
633 /* ACK option acknowledgement so we can move on to data */
636 setpacketevent(&state->spacket, TFTP_EVENT_ACK);
637 setpacketblock(&state->spacket, state->block);
638 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
640 (struct sockaddr *)&state->remote_addr,
641 state->remote_addrlen);
643 failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
644 return CURLE_SEND_ERROR;
647 /* we're ready to RX data */
648 state->state = TFTP_STATE_RX;
649 time(&state->rx_time);
652 case TFTP_EVENT_TIMEOUT:
653 /* Increment the retry count and fail if over the limit */
656 "Timeout waiting for block %d ACK. Retries = %d",
657 NEXT_BLOCKNUM(state->block), state->retries);
658 if(state->retries > state->retry_max) {
659 state->error = TFTP_ERR_TIMEOUT;
660 state->state = TFTP_STATE_FIN;
663 /* Resend the previous ACK */
664 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
666 (struct sockaddr *)&state->remote_addr,
667 state->remote_addrlen);
669 failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
670 return CURLE_SEND_ERROR;
675 case TFTP_EVENT_ERROR:
676 setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
677 setpacketblock(&state->spacket, state->block);
678 (void)sendto(state->sockfd, (void *)state->spacket.data,
680 (struct sockaddr *)&state->remote_addr,
681 state->remote_addrlen);
682 /* don't bother with the return code, but if the socket is still up we
683 * should be a good TFTP client and let the server know we're done */
684 state->state = TFTP_STATE_FIN;
688 failf(data, "%s", "tftp_rx: internal error");
689 return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for
695 /**********************************************************
699 * Event handler for the TX state
701 **********************************************************/
702 static CURLcode tftp_tx(struct tftp_state_data *state, tftp_event_t event)
704 struct Curl_easy *data = state->data;
706 CURLcode result = CURLE_OK;
707 struct SingleRequest *k = &data->req;
708 size_t cb; /* Bytes currently read */
709 char buffer[STRERROR_LEN];
714 case TFTP_EVENT_OACK:
715 if(event == TFTP_EVENT_ACK) {
717 int rblock = getrpacketblock(&state->rpacket);
719 if(rblock != state->block &&
720 /* There's a bug in tftpd-hpa that causes it to send us an ack for
721 * 65535 when the block number wraps to 0. So when we're expecting
722 * 0, also accept 65535. See
723 * https://www.syslinux.org/archives/2010-September/015612.html
725 !(state->block == 0 && rblock == 65535)) {
726 /* This isn't the expected block. Log it and up the retry counter */
727 infof(data, "Received ACK for block %d, expecting %d",
728 rblock, state->block);
730 /* Bail out if over the maximum */
731 if(state->retries>state->retry_max) {
732 failf(data, "tftp_tx: giving up waiting for block %d ack",
734 result = CURLE_SEND_ERROR;
737 /* Re-send the data packet */
738 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
739 4 + state->sbytes, SEND_4TH_ARG,
740 (struct sockaddr *)&state->remote_addr,
741 state->remote_addrlen);
742 /* Check all sbytes were sent */
744 failf(data, "%s", Curl_strerror(SOCKERRNO,
745 buffer, sizeof(buffer)));
746 result = CURLE_SEND_ERROR;
752 /* This is the expected packet. Reset the counters and send the next
754 time(&state->rx_time);
758 state->block = 1; /* first data block is 1 when using OACK */
761 setpacketevent(&state->spacket, TFTP_EVENT_DATA);
762 setpacketblock(&state->spacket, state->block);
763 if(state->block > 1 && state->sbytes < state->blksize) {
764 state->state = TFTP_STATE_FIN;
768 /* TFTP considers data block size < 512 bytes as an end of session. So
769 * in some cases we must wait for additional data to build full (512 bytes)
773 state->data->req.upload_fromhere = (char *)state->spacket.data + 4;
775 result = Curl_fillreadbuffer(data, state->blksize - state->sbytes, &cb);
778 state->sbytes += (int)cb;
779 state->data->req.upload_fromhere += cb;
780 } while(state->sbytes < state->blksize && cb);
782 sbytes = sendto(state->sockfd, (void *) state->spacket.data,
783 4 + state->sbytes, SEND_4TH_ARG,
784 (struct sockaddr *)&state->remote_addr,
785 state->remote_addrlen);
786 /* Check all sbytes were sent */
788 failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
789 return CURLE_SEND_ERROR;
791 /* Update the progress meter */
792 k->writebytecount += state->sbytes;
793 Curl_pgrsSetUploadCounter(data, k->writebytecount);
796 case TFTP_EVENT_TIMEOUT:
797 /* Increment the retry counter and log the timeout */
799 infof(data, "Timeout waiting for block %d ACK. "
800 " Retries = %d", NEXT_BLOCKNUM(state->block), state->retries);
801 /* Decide if we've had enough */
802 if(state->retries > state->retry_max) {
803 state->error = TFTP_ERR_TIMEOUT;
804 state->state = TFTP_STATE_FIN;
807 /* Re-send the data packet */
808 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
809 4 + state->sbytes, SEND_4TH_ARG,
810 (struct sockaddr *)&state->remote_addr,
811 state->remote_addrlen);
812 /* Check all sbytes were sent */
814 failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
815 return CURLE_SEND_ERROR;
817 /* since this was a re-send, we remain at the still byte position */
818 Curl_pgrsSetUploadCounter(data, k->writebytecount);
822 case TFTP_EVENT_ERROR:
823 state->state = TFTP_STATE_FIN;
824 setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
825 setpacketblock(&state->spacket, state->block);
826 (void)sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG,
827 (struct sockaddr *)&state->remote_addr,
828 state->remote_addrlen);
829 /* don't bother with the return code, but if the socket is still up we
830 * should be a good TFTP client and let the server know we're done */
831 state->state = TFTP_STATE_FIN;
835 failf(data, "tftp_tx: internal error, event: %i", (int)(event));
842 /**********************************************************
844 * tftp_translate_code
846 * Translate internal error codes to CURL error codes
848 **********************************************************/
849 static CURLcode tftp_translate_code(tftp_error_t error)
851 CURLcode result = CURLE_OK;
853 if(error != TFTP_ERR_NONE) {
855 case TFTP_ERR_NOTFOUND:
856 result = CURLE_TFTP_NOTFOUND;
859 result = CURLE_TFTP_PERM;
861 case TFTP_ERR_DISKFULL:
862 result = CURLE_REMOTE_DISK_FULL;
865 case TFTP_ERR_ILLEGAL:
866 result = CURLE_TFTP_ILLEGAL;
868 case TFTP_ERR_UNKNOWNID:
869 result = CURLE_TFTP_UNKNOWNID;
871 case TFTP_ERR_EXISTS:
872 result = CURLE_REMOTE_FILE_EXISTS;
874 case TFTP_ERR_NOSUCHUSER:
875 result = CURLE_TFTP_NOSUCHUSER;
877 case TFTP_ERR_TIMEOUT:
878 result = CURLE_OPERATION_TIMEDOUT;
880 case TFTP_ERR_NORESPONSE:
881 result = CURLE_COULDNT_CONNECT;
884 result = CURLE_ABORTED_BY_CALLBACK;
894 /**********************************************************
898 * The tftp state machine event dispatcher
900 **********************************************************/
901 static CURLcode tftp_state_machine(struct tftp_state_data *state,
904 CURLcode result = CURLE_OK;
905 struct Curl_easy *data = state->data;
907 switch(state->state) {
908 case TFTP_STATE_START:
909 DEBUGF(infof(data, "TFTP_STATE_START"));
910 result = tftp_send_first(state, event);
913 DEBUGF(infof(data, "TFTP_STATE_RX"));
914 result = tftp_rx(state, event);
917 DEBUGF(infof(data, "TFTP_STATE_TX"));
918 result = tftp_tx(state, event);
921 infof(data, "%s", "TFTP finished");
924 DEBUGF(infof(data, "STATE: %d", state->state));
925 failf(data, "%s", "Internal state machine error");
926 result = CURLE_TFTP_ILLEGAL;
933 /**********************************************************
937 * The disconnect callback
939 **********************************************************/
940 static CURLcode tftp_disconnect(struct Curl_easy *data,
941 struct connectdata *conn, bool dead_connection)
943 struct tftp_state_data *state = conn->proto.tftpc;
945 (void) dead_connection;
947 /* done, free dynamically allocated pkt buffers */
949 Curl_safefree(state->rpacket.data);
950 Curl_safefree(state->spacket.data);
957 /**********************************************************
961 * The connect callback
963 **********************************************************/
964 static CURLcode tftp_connect(struct Curl_easy *data, bool *done)
966 struct tftp_state_data *state;
969 struct connectdata *conn = data->conn;
971 blksize = TFTP_BLKSIZE_DEFAULT;
973 state = conn->proto.tftpc = calloc(1, sizeof(struct tftp_state_data));
975 return CURLE_OUT_OF_MEMORY;
977 /* alloc pkt buffers based on specified blksize */
978 if(data->set.tftp_blksize) {
979 blksize = (int)data->set.tftp_blksize;
980 if(blksize > TFTP_BLKSIZE_MAX || blksize < TFTP_BLKSIZE_MIN)
981 return CURLE_TFTP_ILLEGAL;
984 need_blksize = blksize;
985 /* default size is the fallback when no OACK is received */
986 if(need_blksize < TFTP_BLKSIZE_DEFAULT)
987 need_blksize = TFTP_BLKSIZE_DEFAULT;
989 if(!state->rpacket.data) {
990 state->rpacket.data = calloc(1, need_blksize + 2 + 2);
992 if(!state->rpacket.data)
993 return CURLE_OUT_OF_MEMORY;
996 if(!state->spacket.data) {
997 state->spacket.data = calloc(1, need_blksize + 2 + 2);
999 if(!state->spacket.data)
1000 return CURLE_OUT_OF_MEMORY;
1003 /* we don't keep TFTP connections up basically because there's none or very
1004 * little gain for UDP */
1005 connclose(conn, "TFTP");
1008 state->sockfd = conn->sock[FIRSTSOCKET];
1009 state->state = TFTP_STATE_START;
1010 state->error = TFTP_ERR_NONE;
1011 state->blksize = TFTP_BLKSIZE_DEFAULT; /* Unless updated by OACK response */
1012 state->requested_blksize = blksize;
1014 ((struct sockaddr *)&state->local_addr)->sa_family =
1015 (CURL_SA_FAMILY_T)(conn->ip_addr->ai_family);
1017 tftp_set_timeouts(state);
1019 if(!conn->bits.bound) {
1020 /* If not already bound, bind to any interface, random UDP port. If it is
1021 * reused or a custom local port was desired, this has already been done!
1023 * We once used the size of the local_addr struct as the third argument
1024 * for bind() to better work with IPv6 or whatever size the struct could
1025 * have, but we learned that at least Tru64, AIX and IRIX *requires* the
1026 * size of that argument to match the exact size of a 'sockaddr_in' struct
1027 * when running IPv4-only.
1029 * Therefore we use the size from the address we connected to, which we
1030 * assume uses the same IP version and thus hopefully this works for both
1033 int rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr,
1034 conn->ip_addr->ai_addrlen);
1036 char buffer[STRERROR_LEN];
1037 failf(data, "bind() failed; %s",
1038 Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
1039 return CURLE_COULDNT_CONNECT;
1041 conn->bits.bound = TRUE;
1044 Curl_pgrsStartNow(data);
1051 /**********************************************************
1057 **********************************************************/
1058 static CURLcode tftp_done(struct Curl_easy *data, CURLcode status,
1061 CURLcode result = CURLE_OK;
1062 struct connectdata *conn = data->conn;
1063 struct tftp_state_data *state = conn->proto.tftpc;
1065 (void)status; /* unused */
1066 (void)premature; /* not used */
1068 if(Curl_pgrsDone(data))
1069 return CURLE_ABORTED_BY_CALLBACK;
1071 /* If we have encountered an error */
1073 result = tftp_translate_code(state->error);
1078 /**********************************************************
1082 * The getsock callback
1084 **********************************************************/
1085 static int tftp_getsock(struct Curl_easy *data,
1086 struct connectdata *conn, curl_socket_t *socks)
1089 socks[0] = conn->sock[FIRSTSOCKET];
1090 return GETSOCK_READSOCK(0);
1093 /**********************************************************
1095 * tftp_receive_packet
1097 * Called once select fires and data is ready on the socket
1099 **********************************************************/
1100 static CURLcode tftp_receive_packet(struct Curl_easy *data)
1102 struct Curl_sockaddr_storage fromaddr;
1103 curl_socklen_t fromlen;
1104 CURLcode result = CURLE_OK;
1105 struct connectdata *conn = data->conn;
1106 struct tftp_state_data *state = conn->proto.tftpc;
1107 struct SingleRequest *k = &data->req;
1109 /* Receive the packet */
1110 fromlen = sizeof(fromaddr);
1111 state->rbytes = (int)recvfrom(state->sockfd,
1112 (void *)state->rpacket.data,
1115 (struct sockaddr *)&fromaddr,
1117 if(state->remote_addrlen == 0) {
1118 memcpy(&state->remote_addr, &fromaddr, fromlen);
1119 state->remote_addrlen = fromlen;
1122 /* Sanity check packet length */
1123 if(state->rbytes < 4) {
1124 failf(data, "Received too short packet");
1125 /* Not a timeout, but how best to handle it? */
1126 state->event = TFTP_EVENT_TIMEOUT;
1129 /* The event is given by the TFTP packet time */
1130 unsigned short event = getrpacketevent(&state->rpacket);
1131 state->event = (tftp_event_t)event;
1133 switch(state->event) {
1134 case TFTP_EVENT_DATA:
1135 /* Don't pass to the client empty or retransmitted packets */
1136 if(state->rbytes > 4 &&
1137 (NEXT_BLOCKNUM(state->block) == getrpacketblock(&state->rpacket))) {
1138 result = Curl_client_write(data, CLIENTWRITE_BODY,
1139 (char *)state->rpacket.data + 4,
1142 tftp_state_machine(state, TFTP_EVENT_ERROR);
1145 k->bytecount += state->rbytes-4;
1146 Curl_pgrsSetDownloadCounter(data, (curl_off_t) k->bytecount);
1149 case TFTP_EVENT_ERROR:
1151 unsigned short error = getrpacketblock(&state->rpacket);
1152 char *str = (char *)state->rpacket.data + 4;
1153 size_t strn = state->rbytes - 4;
1154 state->error = (tftp_error_t)error;
1155 if(tftp_strnlen(str, strn) < strn)
1156 infof(data, "TFTP error: %s", str);
1159 case TFTP_EVENT_ACK:
1161 case TFTP_EVENT_OACK:
1162 result = tftp_parse_option_ack(state,
1163 (const char *)state->rpacket.data + 2,
1168 case TFTP_EVENT_RRQ:
1169 case TFTP_EVENT_WRQ:
1171 failf(data, "%s", "Internal error: Unexpected packet");
1175 /* Update the progress meter */
1176 if(Curl_pgrsUpdate(data)) {
1177 tftp_state_machine(state, TFTP_EVENT_ERROR);
1178 return CURLE_ABORTED_BY_CALLBACK;
1184 /**********************************************************
1186 * tftp_state_timeout
1188 * Check if timeouts have been reached
1190 **********************************************************/
1191 static timediff_t tftp_state_timeout(struct Curl_easy *data,
1192 tftp_event_t *event)
1195 struct connectdata *conn = data->conn;
1196 struct tftp_state_data *state = conn->proto.tftpc;
1197 timediff_t timeout_ms;
1200 *event = TFTP_EVENT_NONE;
1202 timeout_ms = Curl_timeleft(state->data, NULL,
1203 (state->state == TFTP_STATE_START));
1204 if(timeout_ms < 0) {
1205 state->error = TFTP_ERR_TIMEOUT;
1206 state->state = TFTP_STATE_FIN;
1210 if(current > state->rx_time + state->retry_time) {
1212 *event = TFTP_EVENT_TIMEOUT;
1213 time(&state->rx_time); /* update even though we received nothing */
1219 /**********************************************************
1221 * tftp_multi_statemach
1223 * Handle single RX socket event and return
1225 **********************************************************/
1226 static CURLcode tftp_multi_statemach(struct Curl_easy *data, bool *done)
1229 CURLcode result = CURLE_OK;
1230 struct connectdata *conn = data->conn;
1231 struct tftp_state_data *state = conn->proto.tftpc;
1232 timediff_t timeout_ms = tftp_state_timeout(data, &event);
1236 if(timeout_ms < 0) {
1237 failf(data, "TFTP response timeout");
1238 return CURLE_OPERATION_TIMEDOUT;
1240 if(event != TFTP_EVENT_NONE) {
1241 result = tftp_state_machine(state, event);
1244 *done = (state->state == TFTP_STATE_FIN) ? TRUE : FALSE;
1246 /* Tell curl we're done */
1247 Curl_setup_transfer(data, -1, -1, FALSE, -1);
1250 /* no timeouts to handle, check our socket */
1251 int rc = SOCKET_READABLE(state->sockfd, 0);
1255 int error = SOCKERRNO;
1256 char buffer[STRERROR_LEN];
1257 failf(data, "%s", Curl_strerror(error, buffer, sizeof(buffer)));
1258 state->event = TFTP_EVENT_ERROR;
1261 result = tftp_receive_packet(data);
1264 result = tftp_state_machine(state, state->event);
1267 *done = (state->state == TFTP_STATE_FIN) ? TRUE : FALSE;
1269 /* Tell curl we're done */
1270 Curl_setup_transfer(data, -1, -1, FALSE, -1);
1272 /* if rc == 0, then select() timed out */
1278 /**********************************************************
1282 * Called from multi.c while DOing
1284 **********************************************************/
1285 static CURLcode tftp_doing(struct Curl_easy *data, bool *dophase_done)
1288 result = tftp_multi_statemach(data, dophase_done);
1291 DEBUGF(infof(data, "DO phase is complete"));
1294 /* The multi code doesn't have this logic for the DOING state so we
1295 provide it for TFTP since it may do the entire transfer in this
1297 if(Curl_pgrsUpdate(data))
1298 result = CURLE_ABORTED_BY_CALLBACK;
1300 result = Curl_speedcheck(data, Curl_now());
1305 /**********************************************************
1309 * Entry point for transfer from tftp_do, starts state mach
1311 **********************************************************/
1312 static CURLcode tftp_perform(struct Curl_easy *data, bool *dophase_done)
1314 CURLcode result = CURLE_OK;
1315 struct connectdata *conn = data->conn;
1316 struct tftp_state_data *state = conn->proto.tftpc;
1318 *dophase_done = FALSE;
1320 result = tftp_state_machine(state, TFTP_EVENT_INIT);
1322 if((state->state == TFTP_STATE_FIN) || result)
1325 tftp_multi_statemach(data, dophase_done);
1328 DEBUGF(infof(data, "DO phase is complete"));
1334 /**********************************************************
1340 * This callback initiates the TFTP transfer
1342 **********************************************************/
1344 static CURLcode tftp_do(struct Curl_easy *data, bool *done)
1346 struct tftp_state_data *state;
1348 struct connectdata *conn = data->conn;
1352 if(!conn->proto.tftpc) {
1353 result = tftp_connect(data, done);
1358 state = conn->proto.tftpc;
1360 return CURLE_TFTP_ILLEGAL;
1362 result = tftp_perform(data, done);
1364 /* If tftp_perform() returned an error, use that for return code. If it
1365 was OK, see if tftp_translate_code() has an error. */
1367 /* If we have encountered an internal tftp error, translate it. */
1368 result = tftp_translate_code(state->error);
1373 static CURLcode tftp_setup_connection(struct Curl_easy *data,
1374 struct connectdata *conn)
1378 conn->transport = TRNSPRT_UDP;
1380 /* TFTP URLs support an extension like ";mode=<typecode>" that
1381 * we'll try to get now! */
1382 type = strstr(data->state.up.path, ";mode=");
1385 type = strstr(conn->host.rawalloc, ";mode=");
1389 *type = 0; /* it was in the middle of the hostname */
1390 command = Curl_raw_toupper(type[6]);
1393 case 'A': /* ASCII mode */
1394 case 'N': /* NETASCII mode */
1395 data->state.prefer_ascii = TRUE;
1398 case 'O': /* octet mode */
1399 case 'I': /* binary mode */
1401 /* switch off ASCII */
1402 data->state.prefer_ascii = FALSE;