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 * SPDX-License-Identifier: curl
23 ***************************************************************************/
25 #include "curl_setup.h"
27 #ifndef CURL_DISABLE_TFTP
29 #ifdef HAVE_NETINET_IN_H
30 #include <netinet/in.h>
35 #ifdef HAVE_ARPA_INET_H
36 #include <arpa/inet.h>
41 #ifdef HAVE_SYS_IOCTL_H
42 #include <sys/ioctl.h>
45 #ifdef HAVE_SYS_PARAM_H
46 #include <sys/param.h>
50 #include <curl/curl.h>
57 #include "sockaddr.h" /* required for Curl_sockaddr_storage */
61 #include "speedcheck.h"
65 /* The last 3 #include files should be in this order */
66 #include "curl_printf.h"
67 #include "curl_memory.h"
70 /* RFC2348 allows the block size to be negotiated */
71 #define TFTP_BLKSIZE_DEFAULT 512
72 #define TFTP_BLKSIZE_MIN 8
73 #define TFTP_BLKSIZE_MAX 65464
74 #define TFTP_OPTION_BLKSIZE "blksize"
77 #define TFTP_OPTION_TSIZE "tsize"
78 #define TFTP_OPTION_INTERVAL "timeout"
81 TFTP_MODE_NETASCII = 0,
112 TFTP_ERR_NOSUCHUSER, /* This will never be triggered by this code */
114 /* The remaining error codes are internal to curl */
115 TFTP_ERR_NONE = -100,
124 struct tftp_state_data {
129 struct Curl_easy *data;
130 curl_socket_t sockfd;
135 struct Curl_sockaddr_storage local_addr;
136 struct Curl_sockaddr_storage remote_addr;
137 curl_socklen_t remote_addrlen;
141 int requested_blksize;
142 unsigned short block;
143 struct tftp_packet rpacket;
144 struct tftp_packet spacket;
148 /* Forward declarations */
149 static CURLcode tftp_rx(struct tftp_state_data *state, tftp_event_t event);
150 static CURLcode tftp_tx(struct tftp_state_data *state, tftp_event_t event);
151 static CURLcode tftp_connect(struct Curl_easy *data, bool *done);
152 static CURLcode tftp_disconnect(struct Curl_easy *data,
153 struct connectdata *conn,
154 bool dead_connection);
155 static CURLcode tftp_do(struct Curl_easy *data, bool *done);
156 static CURLcode tftp_done(struct Curl_easy *data,
157 CURLcode, bool premature);
158 static CURLcode tftp_setup_connection(struct Curl_easy *data,
159 struct connectdata *conn);
160 static CURLcode tftp_multi_statemach(struct Curl_easy *data, bool *done);
161 static CURLcode tftp_doing(struct Curl_easy *data, bool *dophase_done);
162 static int tftp_getsock(struct Curl_easy *data, struct connectdata *conn,
163 curl_socket_t *socks);
164 static CURLcode tftp_translate_code(tftp_error_t error);
168 * TFTP protocol handler.
171 const struct Curl_handler Curl_handler_tftp = {
173 tftp_setup_connection, /* setup_connection */
175 tftp_done, /* done */
176 ZERO_NULL, /* do_more */
177 tftp_connect, /* connect_it */
178 tftp_multi_statemach, /* connecting */
179 tftp_doing, /* doing */
180 tftp_getsock, /* proto_getsock */
181 tftp_getsock, /* doing_getsock */
182 ZERO_NULL, /* domore_getsock */
183 ZERO_NULL, /* perform_getsock */
184 tftp_disconnect, /* disconnect */
185 ZERO_NULL, /* readwrite */
186 ZERO_NULL, /* connection_check */
187 ZERO_NULL, /* attach connection */
188 PORT_TFTP, /* defport */
189 CURLPROTO_TFTP, /* protocol */
190 CURLPROTO_TFTP, /* family */
191 PROTOPT_NOTCPPROXY | PROTOPT_NOURLQUERY /* flags */
194 /**********************************************************
196 * tftp_set_timeouts -
198 * Set timeouts based on state machine state.
199 * Use user provided connect timeouts until DATA or ACK
200 * packet is received, then use user-provided transfer timeouts
203 **********************************************************/
204 static CURLcode tftp_set_timeouts(struct tftp_state_data *state)
206 time_t maxtime, timeout;
207 timediff_t timeout_ms;
208 bool start = (state->state == TFTP_STATE_START) ? TRUE : FALSE;
210 /* Compute drop-dead time */
211 timeout_ms = Curl_timeleft(state->data, NULL, start);
214 /* time-out, bail out, go home */
215 failf(state->data, "Connection time-out");
216 return CURLE_OPERATION_TIMEDOUT;
220 maxtime = (time_t)(timeout_ms + 500) / 1000;
222 maxtime = 3600; /* use for calculating block timeouts */
224 /* Set per-block timeout to total */
227 /* Average reposting an ACK after 5 seconds */
228 state->retry_max = (int)timeout/5;
230 /* But bound the total number */
231 if(state->retry_max<3)
232 state->retry_max = 3;
234 if(state->retry_max>50)
235 state->retry_max = 50;
237 /* Compute the re-ACK interval to suit the timeout */
238 state->retry_time = (int)(timeout/state->retry_max);
239 if(state->retry_time<1)
240 state->retry_time = 1;
243 "set timeouts for state %d; Total % " CURL_FORMAT_CURL_OFF_T
244 ", retry %d maxtry %d",
245 (int)state->state, timeout_ms, state->retry_time, state->retry_max);
248 time(&state->rx_time);
253 /**********************************************************
255 * tftp_set_send_first
257 * Event handler for the START state
259 **********************************************************/
261 static void setpacketevent(struct tftp_packet *packet, unsigned short num)
263 packet->data[0] = (unsigned char)(num >> 8);
264 packet->data[1] = (unsigned char)(num & 0xff);
268 static void setpacketblock(struct tftp_packet *packet, unsigned short num)
270 packet->data[2] = (unsigned char)(num >> 8);
271 packet->data[3] = (unsigned char)(num & 0xff);
274 static unsigned short getrpacketevent(const struct tftp_packet *packet)
276 return (unsigned short)((packet->data[0] << 8) | packet->data[1]);
279 static unsigned short getrpacketblock(const struct tftp_packet *packet)
281 return (unsigned short)((packet->data[2] << 8) | packet->data[3]);
284 static size_t tftp_strnlen(const char *string, size_t maxlen)
286 const char *end = memchr(string, '\0', maxlen);
287 return end ? (size_t) (end - string) : maxlen;
290 static const char *tftp_option_get(const char *buf, size_t len,
291 const char **option, const char **value)
295 loc = tftp_strnlen(buf, len);
296 loc++; /* NULL term */
302 loc += tftp_strnlen(buf + loc, len-loc);
303 loc++; /* NULL term */
307 *value = &buf[strlen(*option) + 1];
312 static CURLcode tftp_parse_option_ack(struct tftp_state_data *state,
313 const char *ptr, int len)
315 const char *tmp = ptr;
316 struct Curl_easy *data = state->data;
318 /* if OACK doesn't contain blksize option, the default (512) must be used */
319 state->blksize = TFTP_BLKSIZE_DEFAULT;
321 while(tmp < ptr + len) {
322 const char *option, *value;
324 tmp = tftp_option_get(tmp, ptr + len - tmp, &option, &value);
326 failf(data, "Malformed ACK packet, rejecting");
327 return CURLE_TFTP_ILLEGAL;
330 infof(data, "got option=(%s) value=(%s)", option, value);
332 if(checkprefix(TFTP_OPTION_BLKSIZE, option)) {
335 blksize = strtol(value, NULL, 10);
338 failf(data, "invalid blocksize value in OACK packet");
339 return CURLE_TFTP_ILLEGAL;
341 if(blksize > TFTP_BLKSIZE_MAX) {
342 failf(data, "%s (%d)", "blksize is larger than max supported",
344 return CURLE_TFTP_ILLEGAL;
346 else if(blksize < TFTP_BLKSIZE_MIN) {
347 failf(data, "%s (%d)", "blksize is smaller than min supported",
349 return CURLE_TFTP_ILLEGAL;
351 else if(blksize > state->requested_blksize) {
352 /* could realloc pkt buffers here, but the spec doesn't call out
353 * support for the server requesting a bigger blksize than the client
355 failf(data, "%s (%ld)",
356 "server requested blksize larger than allocated", blksize);
357 return CURLE_TFTP_ILLEGAL;
360 state->blksize = (int)blksize;
361 infof(data, "%s (%d) %s (%d)", "blksize parsed from OACK",
362 state->blksize, "requested", state->requested_blksize);
364 else if(checkprefix(TFTP_OPTION_TSIZE, option)) {
367 tsize = strtol(value, NULL, 10);
368 infof(data, "%s (%ld)", "tsize parsed from OACK", tsize);
370 /* tsize should be ignored on upload: Who cares about the size of the
372 if(!data->set.upload) {
374 failf(data, "invalid tsize -:%s:- value in OACK packet", value);
375 return CURLE_TFTP_ILLEGAL;
377 Curl_pgrsSetDownloadSize(data, tsize);
385 static CURLcode tftp_option_add(struct tftp_state_data *state, size_t *csize,
386 char *buf, const char *option)
388 if(( strlen(option) + *csize + 1) > (size_t)state->blksize)
389 return CURLE_TFTP_ILLEGAL;
391 *csize += strlen(option) + 1;
395 static CURLcode tftp_connect_for_tx(struct tftp_state_data *state,
399 #ifndef CURL_DISABLE_VERBOSE_STRINGS
400 struct Curl_easy *data = state->data;
402 infof(data, "%s", "Connected for transmit");
404 state->state = TFTP_STATE_TX;
405 result = tftp_set_timeouts(state);
408 return tftp_tx(state, event);
411 static CURLcode tftp_connect_for_rx(struct tftp_state_data *state,
415 #ifndef CURL_DISABLE_VERBOSE_STRINGS
416 struct Curl_easy *data = state->data;
418 infof(data, "%s", "Connected for receive");
420 state->state = TFTP_STATE_RX;
421 result = tftp_set_timeouts(state);
424 return tftp_rx(state, event);
427 static CURLcode tftp_send_first(struct tftp_state_data *state,
432 const char *mode = "octet";
434 struct Curl_easy *data = state->data;
435 CURLcode result = CURLE_OK;
437 /* Set ascii mode if -B flag was used */
438 if(data->state.prefer_ascii)
443 case TFTP_EVENT_INIT: /* Send the first packet out */
444 case TFTP_EVENT_TIMEOUT: /* Resend the first packet out */
445 /* Increment the retry counter, quit if over the limit */
447 if(state->retries>state->retry_max) {
448 state->error = TFTP_ERR_NORESPONSE;
449 state->state = TFTP_STATE_FIN;
453 if(data->set.upload) {
454 /* If we are uploading, send an WRQ */
455 setpacketevent(&state->spacket, TFTP_EVENT_WRQ);
456 state->data->req.upload_fromhere =
457 (char *)state->spacket.data + 4;
458 if(data->state.infilesize != -1)
459 Curl_pgrsSetUploadSize(data, data->state.infilesize);
462 /* If we are downloading, send an RRQ */
463 setpacketevent(&state->spacket, TFTP_EVENT_RRQ);
465 /* As RFC3617 describes the separator slash is not actually part of the
466 file name so we skip the always-present first letter of the path
468 result = Curl_urldecode(&state->data->state.up.path[1], 0,
469 &filename, NULL, REJECT_ZERO);
473 if(strlen(filename) > (state->blksize - strlen(mode) - 4)) {
474 failf(data, "TFTP file name too long");
476 return CURLE_TFTP_ILLEGAL; /* too long file name field */
479 msnprintf((char *)state->spacket.data + 2,
481 "%s%c%s%c", filename, '\0', mode, '\0');
482 sbytes = 4 + strlen(filename) + strlen(mode);
484 /* optional addition of TFTP options */
485 if(!data->set.tftp_no_options) {
487 /* add tsize option */
488 if(data->set.upload && (data->state.infilesize != -1))
489 msnprintf(buf, sizeof(buf), "%" CURL_FORMAT_CURL_OFF_T,
490 data->state.infilesize);
492 strcpy(buf, "0"); /* the destination is large enough */
494 result = tftp_option_add(state, &sbytes,
495 (char *)state->spacket.data + sbytes,
497 if(result == CURLE_OK)
498 result = tftp_option_add(state, &sbytes,
499 (char *)state->spacket.data + sbytes, buf);
501 /* add blksize option */
502 msnprintf(buf, sizeof(buf), "%d", state->requested_blksize);
503 if(result == CURLE_OK)
504 result = tftp_option_add(state, &sbytes,
505 (char *)state->spacket.data + sbytes,
506 TFTP_OPTION_BLKSIZE);
507 if(result == CURLE_OK)
508 result = tftp_option_add(state, &sbytes,
509 (char *)state->spacket.data + sbytes, buf);
511 /* add timeout option */
512 msnprintf(buf, sizeof(buf), "%d", state->retry_time);
513 if(result == CURLE_OK)
514 result = tftp_option_add(state, &sbytes,
515 (char *)state->spacket.data + sbytes,
516 TFTP_OPTION_INTERVAL);
517 if(result == CURLE_OK)
518 result = tftp_option_add(state, &sbytes,
519 (char *)state->spacket.data + sbytes, buf);
521 if(result != CURLE_OK) {
522 failf(data, "TFTP buffer too small for options");
524 return CURLE_TFTP_ILLEGAL;
528 /* the typecase for the 3rd argument is mostly for systems that do
529 not have a size_t argument, like older unixes that want an 'int' */
530 senddata = sendto(state->sockfd, (void *)state->spacket.data,
531 (SEND_TYPE_ARG3)sbytes, 0,
532 data->conn->ip_addr->ai_addr,
533 data->conn->ip_addr->ai_addrlen);
534 if(senddata != (ssize_t)sbytes) {
535 char buffer[STRERROR_LEN];
536 failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
541 case TFTP_EVENT_OACK:
542 if(data->set.upload) {
543 result = tftp_connect_for_tx(state, event);
546 result = tftp_connect_for_rx(state, event);
550 case TFTP_EVENT_ACK: /* Connected for transmit */
551 result = tftp_connect_for_tx(state, event);
554 case TFTP_EVENT_DATA: /* Connected for receive */
555 result = tftp_connect_for_rx(state, event);
558 case TFTP_EVENT_ERROR:
559 state->state = TFTP_STATE_FIN;
563 failf(state->data, "tftp_send_first: internal error");
570 /* the next blocknum is x + 1 but it needs to wrap at an unsigned 16bit
572 #define NEXT_BLOCKNUM(x) (((x) + 1)&0xffff)
574 /**********************************************************
578 * Event handler for the RX state
580 **********************************************************/
581 static CURLcode tftp_rx(struct tftp_state_data *state,
586 struct Curl_easy *data = state->data;
587 char buffer[STRERROR_LEN];
591 case TFTP_EVENT_DATA:
592 /* Is this the block we expect? */
593 rblock = getrpacketblock(&state->rpacket);
594 if(NEXT_BLOCKNUM(state->block) == rblock) {
595 /* This is the expected block. Reset counters and ACK it. */
598 else if(state->block == rblock) {
599 /* This is the last recently received block again. Log it and ACK it
601 infof(data, "Received last DATA packet block %d again.", rblock);
604 /* totally unexpected, just log it */
606 "Received unexpected DATA packet block %d, expecting block %d",
607 rblock, NEXT_BLOCKNUM(state->block));
611 /* ACK this block. */
612 state->block = (unsigned short)rblock;
613 setpacketevent(&state->spacket, TFTP_EVENT_ACK);
614 setpacketblock(&state->spacket, state->block);
615 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
617 (struct sockaddr *)&state->remote_addr,
618 state->remote_addrlen);
620 failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
621 return CURLE_SEND_ERROR;
624 /* Check if completed (That is, a less than full packet is received) */
625 if(state->rbytes < (ssize_t)state->blksize + 4) {
626 state->state = TFTP_STATE_FIN;
629 state->state = TFTP_STATE_RX;
631 time(&state->rx_time);
634 case TFTP_EVENT_OACK:
635 /* ACK option acknowledgement so we can move on to data */
638 setpacketevent(&state->spacket, TFTP_EVENT_ACK);
639 setpacketblock(&state->spacket, state->block);
640 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
642 (struct sockaddr *)&state->remote_addr,
643 state->remote_addrlen);
645 failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
646 return CURLE_SEND_ERROR;
649 /* we're ready to RX data */
650 state->state = TFTP_STATE_RX;
651 time(&state->rx_time);
654 case TFTP_EVENT_TIMEOUT:
655 /* Increment the retry count and fail if over the limit */
658 "Timeout waiting for block %d ACK. Retries = %d",
659 NEXT_BLOCKNUM(state->block), state->retries);
660 if(state->retries > state->retry_max) {
661 state->error = TFTP_ERR_TIMEOUT;
662 state->state = TFTP_STATE_FIN;
665 /* Resend the previous ACK */
666 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
668 (struct sockaddr *)&state->remote_addr,
669 state->remote_addrlen);
671 failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
672 return CURLE_SEND_ERROR;
677 case TFTP_EVENT_ERROR:
678 setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
679 setpacketblock(&state->spacket, state->block);
680 (void)sendto(state->sockfd, (void *)state->spacket.data,
682 (struct sockaddr *)&state->remote_addr,
683 state->remote_addrlen);
684 /* don't bother with the return code, but if the socket is still up we
685 * should be a good TFTP client and let the server know we're done */
686 state->state = TFTP_STATE_FIN;
690 failf(data, "%s", "tftp_rx: internal error");
691 return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for
697 /**********************************************************
701 * Event handler for the TX state
703 **********************************************************/
704 static CURLcode tftp_tx(struct tftp_state_data *state, tftp_event_t event)
706 struct Curl_easy *data = state->data;
708 CURLcode result = CURLE_OK;
709 struct SingleRequest *k = &data->req;
710 size_t cb; /* Bytes currently read */
711 char buffer[STRERROR_LEN];
716 case TFTP_EVENT_OACK:
717 if(event == TFTP_EVENT_ACK) {
719 int rblock = getrpacketblock(&state->rpacket);
721 if(rblock != state->block &&
722 /* There's a bug in tftpd-hpa that causes it to send us an ack for
723 * 65535 when the block number wraps to 0. So when we're expecting
724 * 0, also accept 65535. See
725 * https://www.syslinux.org/archives/2010-September/015612.html
727 !(state->block == 0 && rblock == 65535)) {
728 /* This isn't the expected block. Log it and up the retry counter */
729 infof(data, "Received ACK for block %d, expecting %d",
730 rblock, state->block);
732 /* Bail out if over the maximum */
733 if(state->retries>state->retry_max) {
734 failf(data, "tftp_tx: giving up waiting for block %d ack",
736 result = CURLE_SEND_ERROR;
739 /* Re-send the data packet */
740 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
741 4 + state->sbytes, SEND_4TH_ARG,
742 (struct sockaddr *)&state->remote_addr,
743 state->remote_addrlen);
744 /* Check all sbytes were sent */
746 failf(data, "%s", Curl_strerror(SOCKERRNO,
747 buffer, sizeof(buffer)));
748 result = 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 < state->blksize) {
766 state->state = TFTP_STATE_FIN;
770 /* TFTP considers data block size < 512 bytes as an end of session. So
771 * in some cases we must wait for additional data to build full (512 bytes)
775 state->data->req.upload_fromhere = (char *)state->spacket.data + 4;
777 result = Curl_fillreadbuffer(data, state->blksize - state->sbytes, &cb);
780 state->sbytes += (int)cb;
781 state->data->req.upload_fromhere += cb;
782 } while(state->sbytes < state->blksize && cb);
784 sbytes = sendto(state->sockfd, (void *) state->spacket.data,
785 4 + state->sbytes, SEND_4TH_ARG,
786 (struct sockaddr *)&state->remote_addr,
787 state->remote_addrlen);
788 /* Check all sbytes were sent */
790 failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
791 return CURLE_SEND_ERROR;
793 /* Update the progress meter */
794 k->writebytecount += state->sbytes;
795 Curl_pgrsSetUploadCounter(data, k->writebytecount);
798 case TFTP_EVENT_TIMEOUT:
799 /* Increment the retry counter and log the timeout */
801 infof(data, "Timeout waiting for block %d ACK. "
802 " Retries = %d", NEXT_BLOCKNUM(state->block), state->retries);
803 /* Decide if we've had enough */
804 if(state->retries > state->retry_max) {
805 state->error = TFTP_ERR_TIMEOUT;
806 state->state = TFTP_STATE_FIN;
809 /* Re-send the data packet */
810 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
811 4 + state->sbytes, SEND_4TH_ARG,
812 (struct sockaddr *)&state->remote_addr,
813 state->remote_addrlen);
814 /* Check all sbytes were sent */
816 failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
817 return CURLE_SEND_ERROR;
819 /* since this was a re-send, we remain at the still byte position */
820 Curl_pgrsSetUploadCounter(data, k->writebytecount);
824 case TFTP_EVENT_ERROR:
825 state->state = TFTP_STATE_FIN;
826 setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
827 setpacketblock(&state->spacket, state->block);
828 (void)sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG,
829 (struct sockaddr *)&state->remote_addr,
830 state->remote_addrlen);
831 /* don't bother with the return code, but if the socket is still up we
832 * should be a good TFTP client and let the server know we're done */
833 state->state = TFTP_STATE_FIN;
837 failf(data, "tftp_tx: internal error, event: %i", (int)(event));
844 /**********************************************************
846 * tftp_translate_code
848 * Translate internal error codes to CURL error codes
850 **********************************************************/
851 static CURLcode tftp_translate_code(tftp_error_t error)
853 CURLcode result = CURLE_OK;
855 if(error != TFTP_ERR_NONE) {
857 case TFTP_ERR_NOTFOUND:
858 result = CURLE_TFTP_NOTFOUND;
861 result = CURLE_TFTP_PERM;
863 case TFTP_ERR_DISKFULL:
864 result = CURLE_REMOTE_DISK_FULL;
867 case TFTP_ERR_ILLEGAL:
868 result = CURLE_TFTP_ILLEGAL;
870 case TFTP_ERR_UNKNOWNID:
871 result = CURLE_TFTP_UNKNOWNID;
873 case TFTP_ERR_EXISTS:
874 result = CURLE_REMOTE_FILE_EXISTS;
876 case TFTP_ERR_NOSUCHUSER:
877 result = CURLE_TFTP_NOSUCHUSER;
879 case TFTP_ERR_TIMEOUT:
880 result = CURLE_OPERATION_TIMEDOUT;
882 case TFTP_ERR_NORESPONSE:
883 result = CURLE_COULDNT_CONNECT;
886 result = CURLE_ABORTED_BY_CALLBACK;
896 /**********************************************************
900 * The tftp state machine event dispatcher
902 **********************************************************/
903 static CURLcode tftp_state_machine(struct tftp_state_data *state,
906 CURLcode result = CURLE_OK;
907 struct Curl_easy *data = state->data;
909 switch(state->state) {
910 case TFTP_STATE_START:
911 DEBUGF(infof(data, "TFTP_STATE_START"));
912 result = tftp_send_first(state, event);
915 DEBUGF(infof(data, "TFTP_STATE_RX"));
916 result = tftp_rx(state, event);
919 DEBUGF(infof(data, "TFTP_STATE_TX"));
920 result = tftp_tx(state, event);
923 infof(data, "%s", "TFTP finished");
926 DEBUGF(infof(data, "STATE: %d", state->state));
927 failf(data, "%s", "Internal state machine error");
928 result = CURLE_TFTP_ILLEGAL;
935 /**********************************************************
939 * The disconnect callback
941 **********************************************************/
942 static CURLcode tftp_disconnect(struct Curl_easy *data,
943 struct connectdata *conn, bool dead_connection)
945 struct tftp_state_data *state = conn->proto.tftpc;
947 (void) dead_connection;
949 /* done, free dynamically allocated pkt buffers */
951 Curl_safefree(state->rpacket.data);
952 Curl_safefree(state->spacket.data);
959 /**********************************************************
963 * The connect callback
965 **********************************************************/
966 static CURLcode tftp_connect(struct Curl_easy *data, bool *done)
968 struct tftp_state_data *state;
971 struct connectdata *conn = data->conn;
973 blksize = TFTP_BLKSIZE_DEFAULT;
975 state = conn->proto.tftpc = calloc(1, sizeof(struct tftp_state_data));
977 return CURLE_OUT_OF_MEMORY;
979 /* alloc pkt buffers based on specified blksize */
980 if(data->set.tftp_blksize) {
981 blksize = (int)data->set.tftp_blksize;
982 if(blksize > TFTP_BLKSIZE_MAX || blksize < TFTP_BLKSIZE_MIN)
983 return CURLE_TFTP_ILLEGAL;
986 need_blksize = blksize;
987 /* default size is the fallback when no OACK is received */
988 if(need_blksize < TFTP_BLKSIZE_DEFAULT)
989 need_blksize = TFTP_BLKSIZE_DEFAULT;
991 if(!state->rpacket.data) {
992 state->rpacket.data = calloc(1, need_blksize + 2 + 2);
994 if(!state->rpacket.data)
995 return CURLE_OUT_OF_MEMORY;
998 if(!state->spacket.data) {
999 state->spacket.data = calloc(1, need_blksize + 2 + 2);
1001 if(!state->spacket.data)
1002 return CURLE_OUT_OF_MEMORY;
1005 /* we don't keep TFTP connections up basically because there's none or very
1006 * little gain for UDP */
1007 connclose(conn, "TFTP");
1010 state->sockfd = conn->sock[FIRSTSOCKET];
1011 state->state = TFTP_STATE_START;
1012 state->error = TFTP_ERR_NONE;
1013 state->blksize = TFTP_BLKSIZE_DEFAULT; /* Unless updated by OACK response */
1014 state->requested_blksize = blksize;
1016 ((struct sockaddr *)&state->local_addr)->sa_family =
1017 (CURL_SA_FAMILY_T)(conn->ip_addr->ai_family);
1019 tftp_set_timeouts(state);
1021 if(!conn->bits.bound) {
1022 /* If not already bound, bind to any interface, random UDP port. If it is
1023 * reused or a custom local port was desired, this has already been done!
1025 * We once used the size of the local_addr struct as the third argument
1026 * for bind() to better work with IPv6 or whatever size the struct could
1027 * have, but we learned that at least Tru64, AIX and IRIX *requires* the
1028 * size of that argument to match the exact size of a 'sockaddr_in' struct
1029 * when running IPv4-only.
1031 * Therefore we use the size from the address we connected to, which we
1032 * assume uses the same IP version and thus hopefully this works for both
1035 int rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr,
1036 conn->ip_addr->ai_addrlen);
1038 char buffer[STRERROR_LEN];
1039 failf(data, "bind() failed; %s",
1040 Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
1041 return CURLE_COULDNT_CONNECT;
1043 conn->bits.bound = TRUE;
1046 Curl_pgrsStartNow(data);
1053 /**********************************************************
1059 **********************************************************/
1060 static CURLcode tftp_done(struct Curl_easy *data, CURLcode status,
1063 CURLcode result = CURLE_OK;
1064 struct connectdata *conn = data->conn;
1065 struct tftp_state_data *state = conn->proto.tftpc;
1067 (void)status; /* unused */
1068 (void)premature; /* not used */
1070 if(Curl_pgrsDone(data))
1071 return CURLE_ABORTED_BY_CALLBACK;
1073 /* If we have encountered an error */
1075 result = tftp_translate_code(state->error);
1080 /**********************************************************
1084 * The getsock callback
1086 **********************************************************/
1087 static int tftp_getsock(struct Curl_easy *data,
1088 struct connectdata *conn, curl_socket_t *socks)
1091 socks[0] = conn->sock[FIRSTSOCKET];
1092 return GETSOCK_READSOCK(0);
1095 /**********************************************************
1097 * tftp_receive_packet
1099 * Called once select fires and data is ready on the socket
1101 **********************************************************/
1102 static CURLcode tftp_receive_packet(struct Curl_easy *data)
1104 struct Curl_sockaddr_storage fromaddr;
1105 curl_socklen_t fromlen;
1106 CURLcode result = CURLE_OK;
1107 struct connectdata *conn = data->conn;
1108 struct tftp_state_data *state = conn->proto.tftpc;
1109 struct SingleRequest *k = &data->req;
1111 /* Receive the packet */
1112 fromlen = sizeof(fromaddr);
1113 state->rbytes = (int)recvfrom(state->sockfd,
1114 (void *)state->rpacket.data,
1117 (struct sockaddr *)&fromaddr,
1119 if(state->remote_addrlen == 0) {
1120 memcpy(&state->remote_addr, &fromaddr, fromlen);
1121 state->remote_addrlen = fromlen;
1124 /* Sanity check packet length */
1125 if(state->rbytes < 4) {
1126 failf(data, "Received too short packet");
1127 /* Not a timeout, but how best to handle it? */
1128 state->event = TFTP_EVENT_TIMEOUT;
1131 /* The event is given by the TFTP packet time */
1132 unsigned short event = getrpacketevent(&state->rpacket);
1133 state->event = (tftp_event_t)event;
1135 switch(state->event) {
1136 case TFTP_EVENT_DATA:
1137 /* Don't pass to the client empty or retransmitted packets */
1138 if(state->rbytes > 4 &&
1139 (NEXT_BLOCKNUM(state->block) == getrpacketblock(&state->rpacket))) {
1140 result = Curl_client_write(data, CLIENTWRITE_BODY,
1141 (char *)state->rpacket.data + 4,
1144 tftp_state_machine(state, TFTP_EVENT_ERROR);
1147 k->bytecount += state->rbytes-4;
1148 Curl_pgrsSetDownloadCounter(data, (curl_off_t) k->bytecount);
1151 case TFTP_EVENT_ERROR:
1153 unsigned short error = getrpacketblock(&state->rpacket);
1154 char *str = (char *)state->rpacket.data + 4;
1155 size_t strn = state->rbytes - 4;
1156 state->error = (tftp_error_t)error;
1157 if(tftp_strnlen(str, strn) < strn)
1158 infof(data, "TFTP error: %s", str);
1161 case TFTP_EVENT_ACK:
1163 case TFTP_EVENT_OACK:
1164 result = tftp_parse_option_ack(state,
1165 (const char *)state->rpacket.data + 2,
1170 case TFTP_EVENT_RRQ:
1171 case TFTP_EVENT_WRQ:
1173 failf(data, "%s", "Internal error: Unexpected packet");
1177 /* Update the progress meter */
1178 if(Curl_pgrsUpdate(data)) {
1179 tftp_state_machine(state, TFTP_EVENT_ERROR);
1180 return CURLE_ABORTED_BY_CALLBACK;
1186 /**********************************************************
1188 * tftp_state_timeout
1190 * Check if timeouts have been reached
1192 **********************************************************/
1193 static timediff_t tftp_state_timeout(struct Curl_easy *data,
1194 tftp_event_t *event)
1197 struct connectdata *conn = data->conn;
1198 struct tftp_state_data *state = conn->proto.tftpc;
1199 timediff_t timeout_ms;
1202 *event = TFTP_EVENT_NONE;
1204 timeout_ms = Curl_timeleft(state->data, NULL,
1205 (state->state == TFTP_STATE_START));
1206 if(timeout_ms < 0) {
1207 state->error = TFTP_ERR_TIMEOUT;
1208 state->state = TFTP_STATE_FIN;
1212 if(current > state->rx_time + state->retry_time) {
1214 *event = TFTP_EVENT_TIMEOUT;
1215 time(&state->rx_time); /* update even though we received nothing */
1221 /**********************************************************
1223 * tftp_multi_statemach
1225 * Handle single RX socket event and return
1227 **********************************************************/
1228 static CURLcode tftp_multi_statemach(struct Curl_easy *data, bool *done)
1231 CURLcode result = CURLE_OK;
1232 struct connectdata *conn = data->conn;
1233 struct tftp_state_data *state = conn->proto.tftpc;
1234 timediff_t timeout_ms = tftp_state_timeout(data, &event);
1238 if(timeout_ms < 0) {
1239 failf(data, "TFTP response timeout");
1240 return CURLE_OPERATION_TIMEDOUT;
1242 if(event != TFTP_EVENT_NONE) {
1243 result = tftp_state_machine(state, event);
1246 *done = (state->state == TFTP_STATE_FIN) ? TRUE : FALSE;
1248 /* Tell curl we're done */
1249 Curl_setup_transfer(data, -1, -1, FALSE, -1);
1252 /* no timeouts to handle, check our socket */
1253 int rc = SOCKET_READABLE(state->sockfd, 0);
1257 int error = SOCKERRNO;
1258 char buffer[STRERROR_LEN];
1259 failf(data, "%s", Curl_strerror(error, buffer, sizeof(buffer)));
1260 state->event = TFTP_EVENT_ERROR;
1263 result = tftp_receive_packet(data);
1266 result = tftp_state_machine(state, state->event);
1269 *done = (state->state == TFTP_STATE_FIN) ? TRUE : FALSE;
1271 /* Tell curl we're done */
1272 Curl_setup_transfer(data, -1, -1, FALSE, -1);
1274 /* if rc == 0, then select() timed out */
1280 /**********************************************************
1284 * Called from multi.c while DOing
1286 **********************************************************/
1287 static CURLcode tftp_doing(struct Curl_easy *data, bool *dophase_done)
1290 result = tftp_multi_statemach(data, dophase_done);
1293 DEBUGF(infof(data, "DO phase is complete"));
1296 /* The multi code doesn't have this logic for the DOING state so we
1297 provide it for TFTP since it may do the entire transfer in this
1299 if(Curl_pgrsUpdate(data))
1300 result = CURLE_ABORTED_BY_CALLBACK;
1302 result = Curl_speedcheck(data, Curl_now());
1307 /**********************************************************
1311 * Entry point for transfer from tftp_do, starts state mach
1313 **********************************************************/
1314 static CURLcode tftp_perform(struct Curl_easy *data, bool *dophase_done)
1316 CURLcode result = CURLE_OK;
1317 struct connectdata *conn = data->conn;
1318 struct tftp_state_data *state = conn->proto.tftpc;
1320 *dophase_done = FALSE;
1322 result = tftp_state_machine(state, TFTP_EVENT_INIT);
1324 if((state->state == TFTP_STATE_FIN) || result)
1327 tftp_multi_statemach(data, dophase_done);
1330 DEBUGF(infof(data, "DO phase is complete"));
1336 /**********************************************************
1342 * This callback initiates the TFTP transfer
1344 **********************************************************/
1346 static CURLcode tftp_do(struct Curl_easy *data, bool *done)
1348 struct tftp_state_data *state;
1350 struct connectdata *conn = data->conn;
1354 if(!conn->proto.tftpc) {
1355 result = tftp_connect(data, done);
1360 state = conn->proto.tftpc;
1362 return CURLE_TFTP_ILLEGAL;
1364 result = tftp_perform(data, done);
1366 /* If tftp_perform() returned an error, use that for return code. If it
1367 was OK, see if tftp_translate_code() has an error. */
1369 /* If we have encountered an internal tftp error, translate it. */
1370 result = tftp_translate_code(state->error);
1375 static CURLcode tftp_setup_connection(struct Curl_easy *data,
1376 struct connectdata *conn)
1380 conn->transport = TRNSPRT_UDP;
1382 /* TFTP URLs support an extension like ";mode=<typecode>" that
1383 * we'll try to get now! */
1384 type = strstr(data->state.up.path, ";mode=");
1387 type = strstr(conn->host.rawalloc, ";mode=");
1391 *type = 0; /* it was in the middle of the hostname */
1392 command = Curl_raw_toupper(type[6]);
1395 case 'A': /* ASCII mode */
1396 case 'N': /* NETASCII mode */
1397 data->state.prefer_ascii = TRUE;
1400 case 'O': /* octet mode */
1401 case 'I': /* binary mode */
1403 /* switch off ASCII */
1404 data->state.prefer_ascii = FALSE;