1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2018, 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.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 ***************************************************************************/
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,
118 typedef struct tftp_packet {
122 typedef struct tftp_state_data {
127 struct connectdata *conn;
128 curl_socket_t sockfd;
135 unsigned short block;
136 struct Curl_sockaddr_storage local_addr;
137 struct Curl_sockaddr_storage remote_addr;
138 curl_socklen_t remote_addrlen;
142 int requested_blksize;
143 tftp_packet_t rpacket;
144 tftp_packet_t spacket;
148 /* Forward declarations */
149 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event);
150 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event);
151 static CURLcode tftp_connect(struct connectdata *conn, bool *done);
152 static CURLcode tftp_disconnect(struct connectdata *conn,
153 bool dead_connection);
154 static CURLcode tftp_do(struct connectdata *conn, bool *done);
155 static CURLcode tftp_done(struct connectdata *conn,
156 CURLcode, bool premature);
157 static CURLcode tftp_setup_connection(struct connectdata * conn);
158 static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done);
159 static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done);
160 static int tftp_getsock(struct connectdata *conn, 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 PORT_TFTP, /* defport */
186 CURLPROTO_TFTP, /* protocol */
187 PROTOPT_NONE | PROTOPT_NOURLQUERY /* flags */
190 /**********************************************************
192 * tftp_set_timeouts -
194 * Set timeouts based on state machine state.
195 * Use user provided connect timeouts until DATA or ACK
196 * packet is received, then use user-provided transfer timeouts
199 **********************************************************/
200 static CURLcode tftp_set_timeouts(tftp_state_data_t *state)
202 time_t maxtime, timeout;
203 timediff_t timeout_ms;
204 bool start = (state->state == TFTP_STATE_START) ? TRUE : FALSE;
206 time(&state->start_time);
208 /* Compute drop-dead time */
209 timeout_ms = Curl_timeleft(state->conn->data, NULL, start);
212 /* time-out, bail out, go home */
213 failf(state->conn->data, "Connection time-out");
214 return CURLE_OPERATION_TIMEDOUT;
219 maxtime = (time_t)(timeout_ms + 500) / 1000;
220 state->max_time = state->start_time + maxtime;
222 /* Set per-block timeout to total */
225 /* Average restart after 5 seconds */
226 state->retry_max = (int)timeout/5;
228 if(state->retry_max < 1)
229 /* avoid division by zero below */
230 state->retry_max = 1;
232 /* Compute the re-start interval to suit the timeout */
233 state->retry_time = (int)timeout/state->retry_max;
234 if(state->retry_time<1)
235 state->retry_time = 1;
240 maxtime = (time_t)(timeout_ms + 500) / 1000;
244 state->max_time = state->start_time + maxtime;
246 /* Set per-block timeout to total */
249 /* Average reposting an ACK after 5 seconds */
250 state->retry_max = (int)timeout/5;
252 /* But bound the total number */
253 if(state->retry_max<3)
254 state->retry_max = 3;
256 if(state->retry_max>50)
257 state->retry_max = 50;
259 /* Compute the re-ACK interval to suit the timeout */
260 state->retry_time = (int)(timeout/state->retry_max);
261 if(state->retry_time<1)
262 state->retry_time = 1;
264 infof(state->conn->data,
265 "set timeouts for state %d; Total %ld, retry %d maxtry %d\n",
266 (int)state->state, (long)(state->max_time-state->start_time),
267 state->retry_time, state->retry_max);
270 time(&state->rx_time);
275 /**********************************************************
277 * tftp_set_send_first
279 * Event handler for the START state
281 **********************************************************/
283 static void setpacketevent(tftp_packet_t *packet, unsigned short num)
285 packet->data[0] = (unsigned char)(num >> 8);
286 packet->data[1] = (unsigned char)(num & 0xff);
290 static void setpacketblock(tftp_packet_t *packet, unsigned short num)
292 packet->data[2] = (unsigned char)(num >> 8);
293 packet->data[3] = (unsigned char)(num & 0xff);
296 static unsigned short getrpacketevent(const tftp_packet_t *packet)
298 return (unsigned short)((packet->data[0] << 8) | packet->data[1]);
301 static unsigned short getrpacketblock(const tftp_packet_t *packet)
303 return (unsigned short)((packet->data[2] << 8) | packet->data[3]);
306 static size_t Curl_strnlen(const char *string, size_t maxlen)
308 const char *end = memchr(string, '\0', maxlen);
309 return end ? (size_t) (end - string) : maxlen;
312 static const char *tftp_option_get(const char *buf, size_t len,
313 const char **option, const char **value)
317 loc = Curl_strnlen(buf, len);
318 loc++; /* NULL term */
324 loc += Curl_strnlen(buf + loc, len-loc);
325 loc++; /* NULL term */
329 *value = &buf[strlen(*option) + 1];
334 static CURLcode tftp_parse_option_ack(tftp_state_data_t *state,
335 const char *ptr, int len)
337 const char *tmp = ptr;
338 struct Curl_easy *data = state->conn->data;
340 /* if OACK doesn't contain blksize option, the default (512) must be used */
341 state->blksize = TFTP_BLKSIZE_DEFAULT;
343 while(tmp < ptr + len) {
344 const char *option, *value;
346 tmp = tftp_option_get(tmp, ptr + len - tmp, &option, &value);
348 failf(data, "Malformed ACK packet, rejecting");
349 return CURLE_TFTP_ILLEGAL;
352 infof(data, "got option=(%s) value=(%s)\n", option, value);
354 if(checkprefix(option, TFTP_OPTION_BLKSIZE)) {
357 blksize = strtol(value, NULL, 10);
360 failf(data, "invalid blocksize value in OACK packet");
361 return CURLE_TFTP_ILLEGAL;
363 if(blksize > TFTP_BLKSIZE_MAX) {
364 failf(data, "%s (%d)", "blksize is larger than max supported",
366 return CURLE_TFTP_ILLEGAL;
368 else if(blksize < TFTP_BLKSIZE_MIN) {
369 failf(data, "%s (%d)", "blksize is smaller than min supported",
371 return CURLE_TFTP_ILLEGAL;
373 else if(blksize > state->requested_blksize) {
374 /* could realloc pkt buffers here, but the spec doesn't call out
375 * support for the server requesting a bigger blksize than the client
377 failf(data, "%s (%ld)",
378 "server requested blksize larger than allocated", blksize);
379 return CURLE_TFTP_ILLEGAL;
382 state->blksize = (int)blksize;
383 infof(data, "%s (%d) %s (%d)\n", "blksize parsed from OACK",
384 state->blksize, "requested", state->requested_blksize);
386 else if(checkprefix(option, TFTP_OPTION_TSIZE)) {
389 tsize = strtol(value, NULL, 10);
390 infof(data, "%s (%ld)\n", "tsize parsed from OACK", tsize);
392 /* tsize should be ignored on upload: Who cares about the size of the
394 if(!data->set.upload) {
396 failf(data, "invalid tsize -:%s:- value in OACK packet", value);
397 return CURLE_TFTP_ILLEGAL;
399 Curl_pgrsSetDownloadSize(data, tsize);
407 static size_t tftp_option_add(tftp_state_data_t *state, size_t csize,
408 char *buf, const char *option)
410 if(( strlen(option) + csize + 1) > (size_t)state->blksize)
413 return strlen(option) + 1;
416 static CURLcode tftp_connect_for_tx(tftp_state_data_t *state,
420 #ifndef CURL_DISABLE_VERBOSE_STRINGS
421 struct Curl_easy *data = state->conn->data;
423 infof(data, "%s\n", "Connected for transmit");
425 state->state = TFTP_STATE_TX;
426 result = tftp_set_timeouts(state);
429 return tftp_tx(state, event);
432 static CURLcode tftp_connect_for_rx(tftp_state_data_t *state,
436 #ifndef CURL_DISABLE_VERBOSE_STRINGS
437 struct Curl_easy *data = state->conn->data;
439 infof(data, "%s\n", "Connected for receive");
441 state->state = TFTP_STATE_RX;
442 result = tftp_set_timeouts(state);
445 return tftp_rx(state, event);
448 static CURLcode tftp_send_first(tftp_state_data_t *state, tftp_event_t event)
452 const char *mode = "octet";
454 struct Curl_easy *data = state->conn->data;
455 CURLcode result = CURLE_OK;
457 /* Set ascii mode if -B flag was used */
458 if(data->set.prefer_ascii)
463 case TFTP_EVENT_INIT: /* Send the first packet out */
464 case TFTP_EVENT_TIMEOUT: /* Resend the first packet out */
465 /* Increment the retry counter, quit if over the limit */
467 if(state->retries>state->retry_max) {
468 state->error = TFTP_ERR_NORESPONSE;
469 state->state = TFTP_STATE_FIN;
473 if(data->set.upload) {
474 /* If we are uploading, send an WRQ */
475 setpacketevent(&state->spacket, TFTP_EVENT_WRQ);
476 state->conn->data->req.upload_fromhere =
477 (char *)state->spacket.data + 4;
478 if(data->state.infilesize != -1)
479 Curl_pgrsSetUploadSize(data, data->state.infilesize);
482 /* If we are downloading, send an RRQ */
483 setpacketevent(&state->spacket, TFTP_EVENT_RRQ);
485 /* As RFC3617 describes the separator slash is not actually part of the
486 file name so we skip the always-present first letter of the path
488 result = Curl_urldecode(data, &state->conn->data->state.up.path[1], 0,
489 &filename, NULL, FALSE);
493 if(strlen(filename) > (state->blksize - strlen(mode) - 4)) {
494 failf(data, "TFTP file name too long\n");
496 return CURLE_TFTP_ILLEGAL; /* too long file name field */
499 snprintf((char *)state->spacket.data + 2,
501 "%s%c%s%c", filename, '\0', mode, '\0');
502 sbytes = 4 + strlen(filename) + strlen(mode);
504 /* optional addition of TFTP options */
505 if(!data->set.tftp_no_options) {
507 /* add tsize option */
508 if(data->set.upload && (data->state.infilesize != -1))
509 snprintf(buf, sizeof(buf), "%" CURL_FORMAT_CURL_OFF_T,
510 data->state.infilesize);
512 strcpy(buf, "0"); /* the destination is large enough */
514 sbytes += tftp_option_add(state, sbytes,
515 (char *)state->spacket.data + sbytes,
517 sbytes += tftp_option_add(state, sbytes,
518 (char *)state->spacket.data + sbytes, buf);
519 /* add blksize option */
520 snprintf(buf, sizeof(buf), "%d", state->requested_blksize);
521 sbytes += tftp_option_add(state, sbytes,
522 (char *)state->spacket.data + sbytes,
523 TFTP_OPTION_BLKSIZE);
524 sbytes += tftp_option_add(state, sbytes,
525 (char *)state->spacket.data + sbytes, buf);
527 /* add timeout option */
528 snprintf(buf, sizeof(buf), "%d", state->retry_time);
529 sbytes += tftp_option_add(state, sbytes,
530 (char *)state->spacket.data + sbytes,
531 TFTP_OPTION_INTERVAL);
532 sbytes += tftp_option_add(state, sbytes,
533 (char *)state->spacket.data + sbytes, buf);
536 /* the typecase for the 3rd argument is mostly for systems that do
537 not have a size_t argument, like older unixes that want an 'int' */
538 senddata = sendto(state->sockfd, (void *)state->spacket.data,
539 (SEND_TYPE_ARG3)sbytes, 0,
540 state->conn->ip_addr->ai_addr,
541 state->conn->ip_addr->ai_addrlen);
542 if(senddata != (ssize_t)sbytes) {
543 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
548 case TFTP_EVENT_OACK:
549 if(data->set.upload) {
550 result = tftp_connect_for_tx(state, event);
553 result = tftp_connect_for_rx(state, event);
557 case TFTP_EVENT_ACK: /* Connected for transmit */
558 result = tftp_connect_for_tx(state, event);
561 case TFTP_EVENT_DATA: /* Connected for receive */
562 result = tftp_connect_for_rx(state, event);
565 case TFTP_EVENT_ERROR:
566 state->state = TFTP_STATE_FIN;
570 failf(state->conn->data, "tftp_send_first: internal error");
577 /* the next blocknum is x + 1 but it needs to wrap at an unsigned 16bit
579 #define NEXT_BLOCKNUM(x) (((x) + 1)&0xffff)
581 /**********************************************************
585 * Event handler for the RX state
587 **********************************************************/
588 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event)
592 struct Curl_easy *data = state->conn->data;
596 case TFTP_EVENT_DATA:
597 /* Is this the block we expect? */
598 rblock = getrpacketblock(&state->rpacket);
599 if(NEXT_BLOCKNUM(state->block) == rblock) {
600 /* This is the expected block. Reset counters and ACK it. */
603 else if(state->block == rblock) {
604 /* This is the last recently received block again. Log it and ACK it
606 infof(data, "Received last DATA packet block %d again.\n", rblock);
609 /* totally unexpected, just log it */
611 "Received unexpected DATA packet block %d, expecting block %d\n",
612 rblock, NEXT_BLOCKNUM(state->block));
616 /* ACK this block. */
617 state->block = (unsigned short)rblock;
618 setpacketevent(&state->spacket, TFTP_EVENT_ACK);
619 setpacketblock(&state->spacket, state->block);
620 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
622 (struct sockaddr *)&state->remote_addr,
623 state->remote_addrlen);
625 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
626 return CURLE_SEND_ERROR;
629 /* Check if completed (That is, a less than full packet is received) */
630 if(state->rbytes < (ssize_t)state->blksize + 4) {
631 state->state = TFTP_STATE_FIN;
634 state->state = TFTP_STATE_RX;
636 time(&state->rx_time);
639 case TFTP_EVENT_OACK:
640 /* ACK option acknowledgement so we can move on to data */
643 setpacketevent(&state->spacket, TFTP_EVENT_ACK);
644 setpacketblock(&state->spacket, state->block);
645 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
647 (struct sockaddr *)&state->remote_addr,
648 state->remote_addrlen);
650 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
651 return CURLE_SEND_ERROR;
654 /* we're ready to RX data */
655 state->state = TFTP_STATE_RX;
656 time(&state->rx_time);
659 case TFTP_EVENT_TIMEOUT:
660 /* Increment the retry count and fail if over the limit */
663 "Timeout waiting for block %d ACK. Retries = %d\n",
664 NEXT_BLOCKNUM(state->block), state->retries);
665 if(state->retries > state->retry_max) {
666 state->error = TFTP_ERR_TIMEOUT;
667 state->state = TFTP_STATE_FIN;
670 /* Resend the previous ACK */
671 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
673 (struct sockaddr *)&state->remote_addr,
674 state->remote_addrlen);
676 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
677 return CURLE_SEND_ERROR;
682 case TFTP_EVENT_ERROR:
683 setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
684 setpacketblock(&state->spacket, state->block);
685 (void)sendto(state->sockfd, (void *)state->spacket.data,
687 (struct sockaddr *)&state->remote_addr,
688 state->remote_addrlen);
689 /* don't bother with the return code, but if the socket is still up we
690 * should be a good TFTP client and let the server know we're done */
691 state->state = TFTP_STATE_FIN;
695 failf(data, "%s", "tftp_rx: internal error");
696 return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for
702 /**********************************************************
706 * Event handler for the TX state
708 **********************************************************/
709 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event)
711 struct Curl_easy *data = state->conn->data;
713 CURLcode result = CURLE_OK;
714 struct SingleRequest *k = &data->req;
715 size_t cb; /* Bytes currently read */
720 case TFTP_EVENT_OACK:
721 if(event == TFTP_EVENT_ACK) {
723 int rblock = getrpacketblock(&state->rpacket);
725 if(rblock != state->block &&
726 /* There's a bug in tftpd-hpa that causes it to send us an ack for
727 * 65535 when the block number wraps to 0. So when we're expecting
728 * 0, also accept 65535. See
729 * http://syslinux.zytor.com/archives/2010-September/015253.html
731 !(state->block == 0 && rblock == 65535)) {
732 /* This isn't the expected block. Log it and up the retry counter */
733 infof(data, "Received ACK for block %d, expecting %d\n",
734 rblock, state->block);
736 /* Bail out if over the maximum */
737 if(state->retries>state->retry_max) {
738 failf(data, "tftp_tx: giving up waiting for block %d ack",
740 result = CURLE_SEND_ERROR;
743 /* Re-send the data packet */
744 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
745 4 + state->sbytes, SEND_4TH_ARG,
746 (struct sockaddr *)&state->remote_addr,
747 state->remote_addrlen);
748 /* Check all sbytes were sent */
750 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
751 result = CURLE_SEND_ERROR;
757 /* This is the expected packet. Reset the counters and send the next
759 time(&state->rx_time);
763 state->block = 1; /* first data block is 1 when using OACK */
766 setpacketevent(&state->spacket, TFTP_EVENT_DATA);
767 setpacketblock(&state->spacket, state->block);
768 if(state->block > 1 && state->sbytes < state->blksize) {
769 state->state = TFTP_STATE_FIN;
773 /* TFTP considers data block size < 512 bytes as an end of session. So
774 * in some cases we must wait for additional data to build full (512 bytes)
778 state->conn->data->req.upload_fromhere = (char *)state->spacket.data + 4;
780 result = Curl_fillreadbuffer(state->conn, state->blksize - state->sbytes,
784 state->sbytes += (int)cb;
785 state->conn->data->req.upload_fromhere += cb;
786 } while(state->sbytes < state->blksize && cb != 0);
788 sbytes = sendto(state->sockfd, (void *) state->spacket.data,
789 4 + state->sbytes, SEND_4TH_ARG,
790 (struct sockaddr *)&state->remote_addr,
791 state->remote_addrlen);
792 /* Check all sbytes were sent */
794 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
795 return CURLE_SEND_ERROR;
797 /* Update the progress meter */
798 k->writebytecount += state->sbytes;
799 Curl_pgrsSetUploadCounter(data, k->writebytecount);
802 case TFTP_EVENT_TIMEOUT:
803 /* Increment the retry counter and log the timeout */
805 infof(data, "Timeout waiting for block %d ACK. "
806 " Retries = %d\n", NEXT_BLOCKNUM(state->block), state->retries);
807 /* Decide if we've had enough */
808 if(state->retries > state->retry_max) {
809 state->error = TFTP_ERR_TIMEOUT;
810 state->state = TFTP_STATE_FIN;
813 /* Re-send the data packet */
814 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
815 4 + state->sbytes, SEND_4TH_ARG,
816 (struct sockaddr *)&state->remote_addr,
817 state->remote_addrlen);
818 /* Check all sbytes were sent */
820 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
821 return CURLE_SEND_ERROR;
823 /* since this was a re-send, we remain at the still byte position */
824 Curl_pgrsSetUploadCounter(data, k->writebytecount);
828 case TFTP_EVENT_ERROR:
829 state->state = TFTP_STATE_FIN;
830 setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
831 setpacketblock(&state->spacket, state->block);
832 (void)sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG,
833 (struct sockaddr *)&state->remote_addr,
834 state->remote_addrlen);
835 /* don't bother with the return code, but if the socket is still up we
836 * should be a good TFTP client and let the server know we're done */
837 state->state = TFTP_STATE_FIN;
841 failf(data, "tftp_tx: internal error, event: %i", (int)(event));
848 /**********************************************************
850 * tftp_translate_code
852 * Translate internal error codes to CURL error codes
854 **********************************************************/
855 static CURLcode tftp_translate_code(tftp_error_t error)
857 CURLcode result = CURLE_OK;
859 if(error != TFTP_ERR_NONE) {
861 case TFTP_ERR_NOTFOUND:
862 result = CURLE_TFTP_NOTFOUND;
865 result = CURLE_TFTP_PERM;
867 case TFTP_ERR_DISKFULL:
868 result = CURLE_REMOTE_DISK_FULL;
871 case TFTP_ERR_ILLEGAL:
872 result = CURLE_TFTP_ILLEGAL;
874 case TFTP_ERR_UNKNOWNID:
875 result = CURLE_TFTP_UNKNOWNID;
877 case TFTP_ERR_EXISTS:
878 result = CURLE_REMOTE_FILE_EXISTS;
880 case TFTP_ERR_NOSUCHUSER:
881 result = CURLE_TFTP_NOSUCHUSER;
883 case TFTP_ERR_TIMEOUT:
884 result = CURLE_OPERATION_TIMEDOUT;
886 case TFTP_ERR_NORESPONSE:
887 result = CURLE_COULDNT_CONNECT;
890 result = CURLE_ABORTED_BY_CALLBACK;
900 /**********************************************************
904 * The tftp state machine event dispatcher
906 **********************************************************/
907 static CURLcode tftp_state_machine(tftp_state_data_t *state,
910 CURLcode result = CURLE_OK;
911 struct Curl_easy *data = state->conn->data;
913 switch(state->state) {
914 case TFTP_STATE_START:
915 DEBUGF(infof(data, "TFTP_STATE_START\n"));
916 result = tftp_send_first(state, event);
919 DEBUGF(infof(data, "TFTP_STATE_RX\n"));
920 result = tftp_rx(state, event);
923 DEBUGF(infof(data, "TFTP_STATE_TX\n"));
924 result = tftp_tx(state, event);
927 infof(data, "%s\n", "TFTP finished");
930 DEBUGF(infof(data, "STATE: %d\n", state->state));
931 failf(data, "%s", "Internal state machine error");
932 result = CURLE_TFTP_ILLEGAL;
939 /**********************************************************
943 * The disconnect callback
945 **********************************************************/
946 static CURLcode tftp_disconnect(struct connectdata *conn, bool dead_connection)
948 tftp_state_data_t *state = conn->proto.tftpc;
949 (void) dead_connection;
951 /* done, free dynamically allocated pkt buffers */
953 Curl_safefree(state->rpacket.data);
954 Curl_safefree(state->spacket.data);
961 /**********************************************************
965 * The connect callback
967 **********************************************************/
968 static CURLcode tftp_connect(struct connectdata *conn, bool *done)
970 tftp_state_data_t *state;
973 blksize = TFTP_BLKSIZE_DEFAULT;
975 state = conn->proto.tftpc = calloc(1, sizeof(tftp_state_data_t));
977 return CURLE_OUT_OF_MEMORY;
979 /* alloc pkt buffers based on specified blksize */
980 if(conn->data->set.tftp_blksize) {
981 blksize = (int)conn->data->set.tftp_blksize;
982 if(blksize > TFTP_BLKSIZE_MAX || blksize < TFTP_BLKSIZE_MIN)
983 return CURLE_TFTP_ILLEGAL;
986 if(!state->rpacket.data) {
987 state->rpacket.data = calloc(1, blksize + 2 + 2);
989 if(!state->rpacket.data)
990 return CURLE_OUT_OF_MEMORY;
993 if(!state->spacket.data) {
994 state->spacket.data = calloc(1, blksize + 2 + 2);
996 if(!state->spacket.data)
997 return CURLE_OUT_OF_MEMORY;
1000 /* we don't keep TFTP connections up basically because there's none or very
1001 * little gain for UDP */
1002 connclose(conn, "TFTP");
1005 state->sockfd = state->conn->sock[FIRSTSOCKET];
1006 state->state = TFTP_STATE_START;
1007 state->error = TFTP_ERR_NONE;
1008 state->blksize = blksize;
1009 state->requested_blksize = blksize;
1011 ((struct sockaddr *)&state->local_addr)->sa_family =
1012 (CURL_SA_FAMILY_T)(conn->ip_addr->ai_family);
1014 tftp_set_timeouts(state);
1016 if(!conn->bits.bound) {
1017 /* If not already bound, bind to any interface, random UDP port. If it is
1018 * reused or a custom local port was desired, this has already been done!
1020 * We once used the size of the local_addr struct as the third argument
1021 * for bind() to better work with IPv6 or whatever size the struct could
1022 * have, but we learned that at least Tru64, AIX and IRIX *requires* the
1023 * size of that argument to match the exact size of a 'sockaddr_in' struct
1024 * when running IPv4-only.
1026 * Therefore we use the size from the address we connected to, which we
1027 * assume uses the same IP version and thus hopefully this works for both
1030 int rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr,
1031 conn->ip_addr->ai_addrlen);
1033 failf(conn->data, "bind() failed; %s",
1034 Curl_strerror(conn, SOCKERRNO));
1035 return CURLE_COULDNT_CONNECT;
1037 conn->bits.bound = TRUE;
1040 Curl_pgrsStartNow(conn->data);
1047 /**********************************************************
1053 **********************************************************/
1054 static CURLcode tftp_done(struct connectdata *conn, CURLcode status,
1057 CURLcode result = CURLE_OK;
1058 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1060 (void)status; /* unused */
1061 (void)premature; /* not used */
1063 if(Curl_pgrsDone(conn))
1064 return CURLE_ABORTED_BY_CALLBACK;
1066 /* If we have encountered an error */
1068 result = tftp_translate_code(state->error);
1073 /**********************************************************
1077 * The getsock callback
1079 **********************************************************/
1080 static int tftp_getsock(struct connectdata *conn, curl_socket_t *socks,
1084 return GETSOCK_BLANK;
1086 socks[0] = conn->sock[FIRSTSOCKET];
1088 return GETSOCK_READSOCK(0);
1091 /**********************************************************
1093 * tftp_receive_packet
1095 * Called once select fires and data is ready on the socket
1097 **********************************************************/
1098 static CURLcode tftp_receive_packet(struct connectdata *conn)
1100 struct Curl_sockaddr_storage fromaddr;
1101 curl_socklen_t fromlen;
1102 CURLcode result = CURLE_OK;
1103 struct Curl_easy *data = conn->data;
1104 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1105 struct SingleRequest *k = &data->req;
1107 /* Receive the packet */
1108 fromlen = sizeof(fromaddr);
1109 state->rbytes = (int)recvfrom(state->sockfd,
1110 (void *)state->rpacket.data,
1113 (struct sockaddr *)&fromaddr,
1115 if(state->remote_addrlen == 0) {
1116 memcpy(&state->remote_addr, &fromaddr, fromlen);
1117 state->remote_addrlen = fromlen;
1120 /* Sanity check packet length */
1121 if(state->rbytes < 4) {
1122 failf(data, "Received too short packet");
1123 /* Not a timeout, but how best to handle it? */
1124 state->event = TFTP_EVENT_TIMEOUT;
1127 /* The event is given by the TFTP packet time */
1128 unsigned short event = getrpacketevent(&state->rpacket);
1129 state->event = (tftp_event_t)event;
1131 switch(state->event) {
1132 case TFTP_EVENT_DATA:
1133 /* Don't pass to the client empty or retransmitted packets */
1134 if(state->rbytes > 4 &&
1135 (NEXT_BLOCKNUM(state->block) == getrpacketblock(&state->rpacket))) {
1136 result = Curl_client_write(conn, CLIENTWRITE_BODY,
1137 (char *)state->rpacket.data + 4,
1140 tftp_state_machine(state, TFTP_EVENT_ERROR);
1143 k->bytecount += state->rbytes-4;
1144 Curl_pgrsSetDownloadCounter(data, (curl_off_t) k->bytecount);
1147 case TFTP_EVENT_ERROR:
1149 unsigned short error = getrpacketblock(&state->rpacket);
1150 char *str = (char *)state->rpacket.data + 4;
1151 size_t strn = state->rbytes - 4;
1152 state->error = (tftp_error_t)error;
1153 if(Curl_strnlen(str, strn) < strn)
1154 infof(data, "TFTP error: %s\n", str);
1157 case TFTP_EVENT_ACK:
1159 case TFTP_EVENT_OACK:
1160 result = tftp_parse_option_ack(state,
1161 (const char *)state->rpacket.data + 2,
1166 case TFTP_EVENT_RRQ:
1167 case TFTP_EVENT_WRQ:
1169 failf(data, "%s", "Internal error: Unexpected packet");
1173 /* Update the progress meter */
1174 if(Curl_pgrsUpdate(conn)) {
1175 tftp_state_machine(state, TFTP_EVENT_ERROR);
1176 return CURLE_ABORTED_BY_CALLBACK;
1182 /**********************************************************
1184 * tftp_state_timeout
1186 * Check if timeouts have been reached
1188 **********************************************************/
1189 static long tftp_state_timeout(struct connectdata *conn, tftp_event_t *event)
1192 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1195 *event = TFTP_EVENT_NONE;
1198 if(current > state->max_time) {
1199 DEBUGF(infof(conn->data, "timeout: %ld > %ld\n",
1200 (long)current, (long)state->max_time));
1201 state->error = TFTP_ERR_TIMEOUT;
1202 state->state = TFTP_STATE_FIN;
1205 if(current > state->rx_time + state->retry_time) {
1207 *event = TFTP_EVENT_TIMEOUT;
1208 time(&state->rx_time); /* update even though we received nothing */
1211 /* there's a typecast below here since 'time_t' may in fact be larger than
1212 'long', but we estimate that a 'long' will still be able to hold number
1213 of seconds even if "only" 32 bit */
1214 return (long)(state->max_time - current);
1217 /**********************************************************
1219 * tftp_multi_statemach
1221 * Handle single RX socket event and return
1223 **********************************************************/
1224 static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done)
1227 CURLcode result = CURLE_OK;
1228 struct Curl_easy *data = conn->data;
1229 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1230 long timeout_ms = tftp_state_timeout(conn, &event);
1234 if(timeout_ms <= 0) {
1235 failf(data, "TFTP response timeout");
1236 return CURLE_OPERATION_TIMEDOUT;
1238 if(event != TFTP_EVENT_NONE) {
1239 result = tftp_state_machine(state, event);
1242 *done = (state->state == TFTP_STATE_FIN) ? TRUE : FALSE;
1244 /* Tell curl we're done */
1245 Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1248 /* no timeouts to handle, check our socket */
1249 int rc = SOCKET_READABLE(state->sockfd, 0);
1253 int error = SOCKERRNO;
1254 failf(data, "%s", Curl_strerror(conn, error));
1255 state->event = TFTP_EVENT_ERROR;
1258 result = tftp_receive_packet(conn);
1261 result = tftp_state_machine(state, state->event);
1264 *done = (state->state == TFTP_STATE_FIN) ? TRUE : FALSE;
1266 /* Tell curl we're done */
1267 Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1269 /* if rc == 0, then select() timed out */
1275 /**********************************************************
1279 * Called from multi.c while DOing
1281 **********************************************************/
1282 static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done)
1285 result = tftp_multi_statemach(conn, dophase_done);
1288 DEBUGF(infof(conn->data, "DO phase is complete\n"));
1291 /* The multi code doesn't have this logic for the DOING state so we
1292 provide it for TFTP since it may do the entire transfer in this
1294 if(Curl_pgrsUpdate(conn))
1295 result = CURLE_ABORTED_BY_CALLBACK;
1297 result = Curl_speedcheck(conn->data, Curl_now());
1302 /**********************************************************
1306 * Entry point for transfer from tftp_do, sarts state mach
1308 **********************************************************/
1309 static CURLcode tftp_perform(struct connectdata *conn, bool *dophase_done)
1311 CURLcode result = CURLE_OK;
1312 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1314 *dophase_done = FALSE;
1316 result = tftp_state_machine(state, TFTP_EVENT_INIT);
1318 if((state->state == TFTP_STATE_FIN) || result)
1321 tftp_multi_statemach(conn, dophase_done);
1324 DEBUGF(infof(conn->data, "DO phase is complete\n"));
1330 /**********************************************************
1336 * This callback initiates the TFTP transfer
1338 **********************************************************/
1340 static CURLcode tftp_do(struct connectdata *conn, bool *done)
1342 tftp_state_data_t *state;
1347 if(!conn->proto.tftpc) {
1348 result = tftp_connect(conn, done);
1353 state = (tftp_state_data_t *)conn->proto.tftpc;
1355 return CURLE_TFTP_ILLEGAL;
1357 result = tftp_perform(conn, done);
1359 /* If tftp_perform() returned an error, use that for return code. If it
1360 was OK, see if tftp_translate_code() has an error. */
1362 /* If we have encountered an internal tftp error, translate it. */
1363 result = tftp_translate_code(state->error);
1368 static CURLcode tftp_setup_connection(struct connectdata * conn)
1370 struct Curl_easy *data = conn->data;
1373 conn->socktype = SOCK_DGRAM; /* UDP datagram based */
1375 /* TFTP URLs support an extension like ";mode=<typecode>" that
1376 * we'll try to get now! */
1377 type = strstr(data->state.up.path, ";mode=");
1380 type = strstr(conn->host.rawalloc, ";mode=");
1384 *type = 0; /* it was in the middle of the hostname */
1385 command = Curl_raw_toupper(type[6]);
1388 case 'A': /* ASCII mode */
1389 case 'N': /* NETASCII mode */
1390 data->set.prefer_ascii = TRUE;
1393 case 'O': /* octet mode */
1394 case 'I': /* binary mode */
1396 /* switch off ASCII */
1397 data->set.prefer_ascii = FALSE;