1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2016, 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"
62 /* The last 3 #include files should be in this order */
63 #include "curl_printf.h"
64 #include "curl_memory.h"
67 /* RFC2348 allows the block size to be negotiated */
68 #define TFTP_BLKSIZE_DEFAULT 512
69 #define TFTP_BLKSIZE_MIN 8
70 #define TFTP_BLKSIZE_MAX 65464
71 #define TFTP_OPTION_BLKSIZE "blksize"
74 #define TFTP_OPTION_TSIZE "tsize"
75 #define TFTP_OPTION_INTERVAL "timeout"
109 TFTP_ERR_NOSUCHUSER, /* This will never be triggered by this code */
111 /* The remaining error codes are internal to curl */
112 TFTP_ERR_NONE = -100,
117 typedef struct tftp_packet {
121 typedef struct tftp_state_data {
126 struct connectdata *conn;
127 curl_socket_t sockfd;
134 unsigned short block;
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 tftp_packet_t rpacket;
143 tftp_packet_t spacket;
147 /* Forward declarations */
148 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event);
149 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event);
150 static CURLcode tftp_connect(struct connectdata *conn, bool *done);
151 static CURLcode tftp_disconnect(struct connectdata *conn,
152 bool dead_connection);
153 static CURLcode tftp_do(struct connectdata *conn, bool *done);
154 static CURLcode tftp_done(struct connectdata *conn,
155 CURLcode, bool premature);
156 static CURLcode tftp_setup_connection(struct connectdata * conn);
157 static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done);
158 static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done);
159 static int tftp_getsock(struct connectdata *conn, curl_socket_t *socks,
161 static CURLcode tftp_translate_code(tftp_error_t error);
165 * TFTP protocol handler.
168 const struct Curl_handler Curl_handler_tftp = {
170 tftp_setup_connection, /* setup_connection */
172 tftp_done, /* done */
173 ZERO_NULL, /* do_more */
174 tftp_connect, /* connect_it */
175 tftp_multi_statemach, /* connecting */
176 tftp_doing, /* doing */
177 tftp_getsock, /* proto_getsock */
178 tftp_getsock, /* doing_getsock */
179 ZERO_NULL, /* domore_getsock */
180 ZERO_NULL, /* perform_getsock */
181 tftp_disconnect, /* disconnect */
182 ZERO_NULL, /* readwrite */
183 PORT_TFTP, /* defport */
184 CURLPROTO_TFTP, /* protocol */
185 PROTOPT_NONE | PROTOPT_NOURLQUERY /* flags */
188 /**********************************************************
190 * tftp_set_timeouts -
192 * Set timeouts based on state machine state.
193 * Use user provided connect timeouts until DATA or ACK
194 * packet is received, then use user-provided transfer timeouts
197 **********************************************************/
198 static CURLcode tftp_set_timeouts(tftp_state_data_t *state)
200 time_t maxtime, timeout;
202 bool start = (state->state == TFTP_STATE_START) ? TRUE : FALSE;
204 time(&state->start_time);
206 /* Compute drop-dead time */
207 timeout_ms = Curl_timeleft(state->conn->data, NULL, start);
210 /* time-out, bail out, go home */
211 failf(state->conn->data, "Connection time-out");
212 return CURLE_OPERATION_TIMEDOUT;
217 maxtime = (time_t)(timeout_ms + 500) / 1000;
218 state->max_time = state->start_time+maxtime;
220 /* Set per-block timeout to total */
223 /* Average restart after 5 seconds */
224 state->retry_max = (int)timeout/5;
226 if(state->retry_max < 1)
227 /* avoid division by zero below */
228 state->retry_max = 1;
230 /* Compute the re-start interval to suit the timeout */
231 state->retry_time = (int)timeout/state->retry_max;
232 if(state->retry_time<1)
238 maxtime = (time_t)(timeout_ms + 500) / 1000;
242 state->max_time = state->start_time+maxtime;
244 /* Set per-block timeout to total */
247 /* Average reposting an ACK after 5 seconds */
248 state->retry_max = (int)timeout/5;
250 /* But bound the total number */
251 if(state->retry_max<3)
254 if(state->retry_max>50)
257 /* Compute the re-ACK interval to suit the timeout */
258 state->retry_time = (int)(timeout/state->retry_max);
259 if(state->retry_time<1)
262 infof(state->conn->data,
263 "set timeouts for state %d; Total %ld, retry %d maxtry %d\n",
264 (int)state->state, (long)(state->max_time-state->start_time),
265 state->retry_time, state->retry_max);
268 time(&state->rx_time);
273 /**********************************************************
275 * tftp_set_send_first
277 * Event handler for the START state
279 **********************************************************/
281 static void setpacketevent(tftp_packet_t *packet, unsigned short num)
283 packet->data[0] = (unsigned char)(num >> 8);
284 packet->data[1] = (unsigned char)(num & 0xff);
288 static void setpacketblock(tftp_packet_t *packet, unsigned short num)
290 packet->data[2] = (unsigned char)(num >> 8);
291 packet->data[3] = (unsigned char)(num & 0xff);
294 static unsigned short getrpacketevent(const tftp_packet_t *packet)
296 return (unsigned short)((packet->data[0] << 8) | packet->data[1]);
299 static unsigned short getrpacketblock(const tftp_packet_t *packet)
301 return (unsigned short)((packet->data[2] << 8) | packet->data[3]);
304 static size_t Curl_strnlen(const char *string, size_t maxlen)
306 const char *end = memchr (string, '\0', maxlen);
307 return end ? (size_t) (end - string) : maxlen;
310 static const char *tftp_option_get(const char *buf, size_t len,
311 const char **option, const char **value)
315 loc = Curl_strnlen(buf, len);
316 loc++; /* NULL term */
322 loc += Curl_strnlen(buf+loc, len-loc);
323 loc++; /* NULL term */
327 *value = &buf[strlen(*option) + 1];
332 static CURLcode tftp_parse_option_ack(tftp_state_data_t *state,
333 const char *ptr, int len)
335 const char *tmp = ptr;
336 struct Curl_easy *data = state->conn->data;
338 /* if OACK doesn't contain blksize option, the default (512) must be used */
339 state->blksize = TFTP_BLKSIZE_DEFAULT;
341 while(tmp < ptr + len) {
342 const char *option, *value;
344 tmp = tftp_option_get(tmp, ptr + len - tmp, &option, &value);
346 failf(data, "Malformed ACK packet, rejecting");
347 return CURLE_TFTP_ILLEGAL;
350 infof(data, "got option=(%s) value=(%s)\n", option, value);
352 if(checkprefix(option, TFTP_OPTION_BLKSIZE)) {
355 blksize = strtol(value, NULL, 10);
358 failf(data, "invalid blocksize value in OACK packet");
359 return CURLE_TFTP_ILLEGAL;
361 else if(blksize > TFTP_BLKSIZE_MAX) {
362 failf(data, "%s (%d)", "blksize is larger than max supported",
364 return CURLE_TFTP_ILLEGAL;
366 else if(blksize < TFTP_BLKSIZE_MIN) {
367 failf(data, "%s (%d)", "blksize is smaller than min supported",
369 return CURLE_TFTP_ILLEGAL;
371 else if(blksize > state->requested_blksize) {
372 /* could realloc pkt buffers here, but the spec doesn't call out
373 * support for the server requesting a bigger blksize than the client
375 failf(data, "%s (%ld)",
376 "server requested blksize larger than allocated", blksize);
377 return CURLE_TFTP_ILLEGAL;
380 state->blksize = (int)blksize;
381 infof(data, "%s (%d) %s (%d)\n", "blksize parsed from OACK",
382 state->blksize, "requested", state->requested_blksize);
384 else if(checkprefix(option, TFTP_OPTION_TSIZE)) {
387 tsize = strtol(value, NULL, 10);
388 infof(data, "%s (%ld)\n", "tsize parsed from OACK", tsize);
390 /* tsize should be ignored on upload: Who cares about the size of the
392 if(!data->set.upload) {
394 failf(data, "invalid tsize -:%s:- value in OACK packet", value);
395 return CURLE_TFTP_ILLEGAL;
397 Curl_pgrsSetDownloadSize(data, tsize);
405 static size_t tftp_option_add(tftp_state_data_t *state, size_t csize,
406 char *buf, const char *option)
408 if(( strlen(option) + csize + 1) > (size_t)state->blksize)
411 return strlen(option) + 1;
414 static CURLcode tftp_connect_for_tx(tftp_state_data_t *state,
418 #ifndef CURL_DISABLE_VERBOSE_STRINGS
419 struct Curl_easy *data = state->conn->data;
421 infof(data, "%s\n", "Connected for transmit");
423 state->state = TFTP_STATE_TX;
424 result = tftp_set_timeouts(state);
427 return tftp_tx(state, event);
430 static CURLcode tftp_connect_for_rx(tftp_state_data_t *state,
434 #ifndef CURL_DISABLE_VERBOSE_STRINGS
435 struct Curl_easy *data = state->conn->data;
437 infof(data, "%s\n", "Connected for receive");
439 state->state = TFTP_STATE_RX;
440 result = tftp_set_timeouts(state);
443 return tftp_rx(state, event);
446 static CURLcode tftp_send_first(tftp_state_data_t *state, tftp_event_t event)
450 const char *mode = "octet";
453 struct Curl_easy *data = state->conn->data;
454 CURLcode result = CURLE_OK;
456 /* Set ascii mode if -B flag was used */
457 if(data->set.prefer_ascii)
462 case TFTP_EVENT_INIT: /* Send the first packet out */
463 case TFTP_EVENT_TIMEOUT: /* Resend the first packet out */
464 /* Increment the retry counter, quit if over the limit */
466 if(state->retries>state->retry_max) {
467 state->error = TFTP_ERR_NORESPONSE;
468 state->state = TFTP_STATE_FIN;
472 if(data->set.upload) {
473 /* If we are uploading, send an WRQ */
474 setpacketevent(&state->spacket, TFTP_EVENT_WRQ);
475 state->conn->data->req.upload_fromhere =
476 (char *)state->spacket.data+4;
477 if(data->state.infilesize != -1)
478 Curl_pgrsSetUploadSize(data, data->state.infilesize);
481 /* If we are downloading, send an RRQ */
482 setpacketevent(&state->spacket, TFTP_EVENT_RRQ);
484 /* As RFC3617 describes the separator slash is not actually part of the
485 file name so we skip the always-present first letter of the path
487 filename = curl_easy_unescape(data, &state->conn->data->state.path[1], 0,
490 return CURLE_OUT_OF_MEMORY;
492 snprintf((char *)state->spacket.data+2,
494 "%s%c%s%c", filename, '\0', mode, '\0');
495 sbytes = 4 + strlen(filename) + strlen(mode);
497 /* optional addition of TFTP options */
498 if(!data->set.tftp_no_options) {
499 /* add tsize option */
500 if(data->set.upload && (data->state.infilesize != -1))
501 snprintf(buf, sizeof(buf), "%" CURL_FORMAT_CURL_OFF_T,
502 data->state.infilesize);
504 strcpy(buf, "0"); /* the destination is large enough */
506 sbytes += tftp_option_add(state, sbytes,
507 (char *)state->spacket.data+sbytes,
509 sbytes += tftp_option_add(state, sbytes,
510 (char *)state->spacket.data+sbytes, buf);
511 /* add blksize option */
512 snprintf(buf, sizeof(buf), "%d", state->requested_blksize);
513 sbytes += tftp_option_add(state, sbytes,
514 (char *)state->spacket.data+sbytes,
515 TFTP_OPTION_BLKSIZE);
516 sbytes += tftp_option_add(state, sbytes,
517 (char *)state->spacket.data+sbytes, buf);
519 /* add timeout option */
520 snprintf(buf, sizeof(buf), "%d", state->retry_time);
521 sbytes += tftp_option_add(state, sbytes,
522 (char *)state->spacket.data+sbytes,
523 TFTP_OPTION_INTERVAL);
524 sbytes += tftp_option_add(state, sbytes,
525 (char *)state->spacket.data+sbytes, buf);
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 state->conn->ip_addr->ai_addr,
533 state->conn->ip_addr->ai_addrlen);
534 if(senddata != (ssize_t)sbytes) {
535 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
540 case TFTP_EVENT_OACK:
541 if(data->set.upload) {
542 result = tftp_connect_for_tx(state, event);
545 result = tftp_connect_for_rx(state, event);
549 case TFTP_EVENT_ACK: /* Connected for transmit */
550 result = tftp_connect_for_tx(state, event);
553 case TFTP_EVENT_DATA: /* Connected for receive */
554 result = tftp_connect_for_rx(state, event);
557 case TFTP_EVENT_ERROR:
558 state->state = TFTP_STATE_FIN;
562 failf(state->conn->data, "tftp_send_first: internal error");
569 /* the next blocknum is x + 1 but it needs to wrap at an unsigned 16bit
571 #define NEXT_BLOCKNUM(x) (((x)+1)&0xffff)
573 /**********************************************************
577 * Event handler for the RX state
579 **********************************************************/
580 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event)
584 struct Curl_easy *data = state->conn->data;
588 case TFTP_EVENT_DATA:
589 /* Is this the block we expect? */
590 rblock = getrpacketblock(&state->rpacket);
591 if(NEXT_BLOCKNUM(state->block) == rblock) {
592 /* This is the expected block. Reset counters and ACK it. */
595 else if(state->block == rblock) {
596 /* This is the last recently received block again. Log it and ACK it
598 infof(data, "Received last DATA packet block %d again.\n", rblock);
601 /* totally unexpected, just log it */
603 "Received unexpected DATA packet block %d, expecting block %d\n",
604 rblock, NEXT_BLOCKNUM(state->block));
608 /* ACK this block. */
609 state->block = (unsigned short)rblock;
610 setpacketevent(&state->spacket, TFTP_EVENT_ACK);
611 setpacketblock(&state->spacket, state->block);
612 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
614 (struct sockaddr *)&state->remote_addr,
615 state->remote_addrlen);
617 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
618 return CURLE_SEND_ERROR;
621 /* Check if completed (That is, a less than full packet is received) */
622 if(state->rbytes < (ssize_t)state->blksize+4) {
623 state->state = TFTP_STATE_FIN;
626 state->state = TFTP_STATE_RX;
628 time(&state->rx_time);
631 case TFTP_EVENT_OACK:
632 /* ACK option acknowledgement so we can move on to data */
635 setpacketevent(&state->spacket, TFTP_EVENT_ACK);
636 setpacketblock(&state->spacket, state->block);
637 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
639 (struct sockaddr *)&state->remote_addr,
640 state->remote_addrlen);
642 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
643 return CURLE_SEND_ERROR;
646 /* we're ready to RX data */
647 state->state = TFTP_STATE_RX;
648 time(&state->rx_time);
651 case TFTP_EVENT_TIMEOUT:
652 /* Increment the retry count and fail if over the limit */
655 "Timeout waiting for block %d ACK. Retries = %d\n",
656 NEXT_BLOCKNUM(state->block), state->retries);
657 if(state->retries > state->retry_max) {
658 state->error = TFTP_ERR_TIMEOUT;
659 state->state = TFTP_STATE_FIN;
662 /* Resend the previous ACK */
663 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
665 (struct sockaddr *)&state->remote_addr,
666 state->remote_addrlen);
668 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
669 return CURLE_SEND_ERROR;
674 case TFTP_EVENT_ERROR:
675 setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
676 setpacketblock(&state->spacket, state->block);
677 (void)sendto(state->sockfd, (void *)state->spacket.data,
679 (struct sockaddr *)&state->remote_addr,
680 state->remote_addrlen);
681 /* don't bother with the return code, but if the socket is still up we
682 * should be a good TFTP client and let the server know we're done */
683 state->state = TFTP_STATE_FIN;
687 failf(data, "%s", "tftp_rx: internal error");
688 return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for
694 /**********************************************************
698 * Event handler for the TX state
700 **********************************************************/
701 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event)
703 struct Curl_easy *data = state->conn->data;
706 CURLcode result = CURLE_OK;
707 struct SingleRequest *k = &data->req;
708 int cb; /* Bytes currently read */
713 case TFTP_EVENT_OACK:
714 if(event == TFTP_EVENT_ACK) {
716 rblock = getrpacketblock(&state->rpacket);
718 if(rblock != state->block &&
719 /* There's a bug in tftpd-hpa that causes it to send us an ack for
720 * 65535 when the block number wraps to 0. So when we're expecting
721 * 0, also accept 65535. See
722 * http://syslinux.zytor.com/archives/2010-September/015253.html
724 !(state->block == 0 && rblock == 65535)) {
725 /* This isn't the expected block. Log it and up the retry counter */
726 infof(data, "Received ACK for block %d, expecting %d\n",
727 rblock, state->block);
729 /* Bail out if over the maximum */
730 if(state->retries>state->retry_max) {
731 failf(data, "tftp_tx: giving up waiting for block %d ack",
733 result = CURLE_SEND_ERROR;
736 /* Re-send the data packet */
737 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
738 4+state->sbytes, SEND_4TH_ARG,
739 (struct sockaddr *)&state->remote_addr,
740 state->remote_addrlen);
741 /* Check all sbytes were sent */
743 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
744 result = CURLE_SEND_ERROR;
750 /* This is the expected packet. Reset the counters and send the next
752 time(&state->rx_time);
756 state->block = 1; /* first data block is 1 when using OACK */
759 setpacketevent(&state->spacket, TFTP_EVENT_DATA);
760 setpacketblock(&state->spacket, state->block);
761 if(state->block > 1 && state->sbytes < (int)state->blksize) {
762 state->state = TFTP_STATE_FIN;
766 /* TFTP considers data block size < 512 bytes as an end of session. So
767 * in some cases we must wait for additional data to build full (512 bytes)
771 state->conn->data->req.upload_fromhere = (char *)state->spacket.data+4;
773 result = Curl_fillreadbuffer(state->conn, state->blksize - state->sbytes,
778 state->conn->data->req.upload_fromhere += cb;
779 } while(state->sbytes < state->blksize && cb != 0);
781 sbytes = sendto(state->sockfd, (void *) state->spacket.data,
782 4 + state->sbytes, SEND_4TH_ARG,
783 (struct sockaddr *)&state->remote_addr,
784 state->remote_addrlen);
785 /* Check all sbytes were sent */
787 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
788 return CURLE_SEND_ERROR;
790 /* Update the progress meter */
791 k->writebytecount += state->sbytes;
792 Curl_pgrsSetUploadCounter(data, k->writebytecount);
795 case TFTP_EVENT_TIMEOUT:
796 /* Increment the retry counter and log the timeout */
798 infof(data, "Timeout waiting for block %d ACK. "
799 " Retries = %d\n", NEXT_BLOCKNUM(state->block), state->retries);
800 /* Decide if we've had enough */
801 if(state->retries > state->retry_max) {
802 state->error = TFTP_ERR_TIMEOUT;
803 state->state = TFTP_STATE_FIN;
806 /* Re-send the data packet */
807 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
808 4+state->sbytes, SEND_4TH_ARG,
809 (struct sockaddr *)&state->remote_addr,
810 state->remote_addrlen);
811 /* Check all sbytes were sent */
813 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
814 return CURLE_SEND_ERROR;
816 /* since this was a re-send, we remain at the still byte position */
817 Curl_pgrsSetUploadCounter(data, k->writebytecount);
821 case TFTP_EVENT_ERROR:
822 state->state = TFTP_STATE_FIN;
823 setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
824 setpacketblock(&state->spacket, state->block);
825 (void)sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG,
826 (struct sockaddr *)&state->remote_addr,
827 state->remote_addrlen);
828 /* don't bother with the return code, but if the socket is still up we
829 * should be a good TFTP client and let the server know we're done */
830 state->state = TFTP_STATE_FIN;
834 failf(data, "tftp_tx: internal error, event: %i", (int)(event));
841 /**********************************************************
843 * tftp_translate_code
845 * Translate internal error codes to CURL error codes
847 **********************************************************/
848 static CURLcode tftp_translate_code(tftp_error_t error)
850 CURLcode result = CURLE_OK;
852 if(error != TFTP_ERR_NONE) {
854 case TFTP_ERR_NOTFOUND:
855 result = CURLE_TFTP_NOTFOUND;
858 result = CURLE_TFTP_PERM;
860 case TFTP_ERR_DISKFULL:
861 result = CURLE_REMOTE_DISK_FULL;
864 case TFTP_ERR_ILLEGAL:
865 result = CURLE_TFTP_ILLEGAL;
867 case TFTP_ERR_UNKNOWNID:
868 result = CURLE_TFTP_UNKNOWNID;
870 case TFTP_ERR_EXISTS:
871 result = CURLE_REMOTE_FILE_EXISTS;
873 case TFTP_ERR_NOSUCHUSER:
874 result = CURLE_TFTP_NOSUCHUSER;
876 case TFTP_ERR_TIMEOUT:
877 result = CURLE_OPERATION_TIMEDOUT;
879 case TFTP_ERR_NORESPONSE:
880 result = CURLE_COULDNT_CONNECT;
883 result = CURLE_ABORTED_BY_CALLBACK;
893 /**********************************************************
897 * The tftp state machine event dispatcher
899 **********************************************************/
900 static CURLcode tftp_state_machine(tftp_state_data_t *state,
903 CURLcode result = CURLE_OK;
904 struct Curl_easy *data = state->conn->data;
906 switch(state->state) {
907 case TFTP_STATE_START:
908 DEBUGF(infof(data, "TFTP_STATE_START\n"));
909 result = tftp_send_first(state, event);
912 DEBUGF(infof(data, "TFTP_STATE_RX\n"));
913 result = tftp_rx(state, event);
916 DEBUGF(infof(data, "TFTP_STATE_TX\n"));
917 result = tftp_tx(state, event);
920 infof(data, "%s\n", "TFTP finished");
923 DEBUGF(infof(data, "STATE: %d\n", state->state));
924 failf(data, "%s", "Internal state machine error");
925 result = CURLE_TFTP_ILLEGAL;
932 /**********************************************************
936 * The disconnect callback
938 **********************************************************/
939 static CURLcode tftp_disconnect(struct connectdata *conn, bool dead_connection)
941 tftp_state_data_t *state = conn->proto.tftpc;
942 (void) dead_connection;
944 /* done, free dynamically allocated pkt buffers */
946 Curl_safefree(state->rpacket.data);
947 Curl_safefree(state->spacket.data);
954 /**********************************************************
958 * The connect callback
960 **********************************************************/
961 static CURLcode tftp_connect(struct connectdata *conn, bool *done)
963 tftp_state_data_t *state;
966 blksize = TFTP_BLKSIZE_DEFAULT;
968 state = conn->proto.tftpc = calloc(1, sizeof(tftp_state_data_t));
970 return CURLE_OUT_OF_MEMORY;
972 /* alloc pkt buffers based on specified blksize */
973 if(conn->data->set.tftp_blksize) {
974 blksize = (int)conn->data->set.tftp_blksize;
975 if(blksize > TFTP_BLKSIZE_MAX || blksize < TFTP_BLKSIZE_MIN)
976 return CURLE_TFTP_ILLEGAL;
979 if(!state->rpacket.data) {
980 state->rpacket.data = calloc(1, blksize + 2 + 2);
982 if(!state->rpacket.data)
983 return CURLE_OUT_OF_MEMORY;
986 if(!state->spacket.data) {
987 state->spacket.data = calloc(1, blksize + 2 + 2);
989 if(!state->spacket.data)
990 return CURLE_OUT_OF_MEMORY;
993 /* we don't keep TFTP connections up basically because there's none or very
994 * little gain for UDP */
995 connclose(conn, "TFTP");
998 state->sockfd = state->conn->sock[FIRSTSOCKET];
999 state->state = TFTP_STATE_START;
1000 state->error = TFTP_ERR_NONE;
1001 state->blksize = TFTP_BLKSIZE_DEFAULT;
1002 state->requested_blksize = blksize;
1004 ((struct sockaddr *)&state->local_addr)->sa_family =
1005 (unsigned short)(conn->ip_addr->ai_family);
1007 tftp_set_timeouts(state);
1009 if(!conn->bits.bound) {
1010 /* If not already bound, bind to any interface, random UDP port. If it is
1011 * reused or a custom local port was desired, this has already been done!
1013 * We once used the size of the local_addr struct as the third argument
1014 * for bind() to better work with IPv6 or whatever size the struct could
1015 * have, but we learned that at least Tru64, AIX and IRIX *requires* the
1016 * size of that argument to match the exact size of a 'sockaddr_in' struct
1017 * when running IPv4-only.
1019 * Therefore we use the size from the address we connected to, which we
1020 * assume uses the same IP version and thus hopefully this works for both
1023 rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr,
1024 conn->ip_addr->ai_addrlen);
1026 failf(conn->data, "bind() failed; %s",
1027 Curl_strerror(conn, SOCKERRNO));
1028 return CURLE_COULDNT_CONNECT;
1030 conn->bits.bound = TRUE;
1033 Curl_pgrsStartNow(conn->data);
1040 /**********************************************************
1046 **********************************************************/
1047 static CURLcode tftp_done(struct connectdata *conn, CURLcode status,
1050 CURLcode result = CURLE_OK;
1051 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1053 (void)status; /* unused */
1054 (void)premature; /* not used */
1056 if(Curl_pgrsDone(conn))
1057 return CURLE_ABORTED_BY_CALLBACK;
1059 /* If we have encountered an error */
1061 result = tftp_translate_code(state->error);
1066 /**********************************************************
1070 * The getsock callback
1072 **********************************************************/
1073 static int tftp_getsock(struct connectdata *conn, curl_socket_t *socks,
1077 return GETSOCK_BLANK;
1079 socks[0] = conn->sock[FIRSTSOCKET];
1081 return GETSOCK_READSOCK(0);
1084 /**********************************************************
1086 * tftp_receive_packet
1088 * Called once select fires and data is ready on the socket
1090 **********************************************************/
1091 static CURLcode tftp_receive_packet(struct connectdata *conn)
1093 struct Curl_sockaddr_storage fromaddr;
1094 curl_socklen_t fromlen;
1095 CURLcode result = CURLE_OK;
1096 struct Curl_easy *data = conn->data;
1097 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1098 struct SingleRequest *k = &data->req;
1100 /* Receive the packet */
1101 fromlen = sizeof(fromaddr);
1102 state->rbytes = (int)recvfrom(state->sockfd,
1103 (void *)state->rpacket.data,
1106 (struct sockaddr *)&fromaddr,
1108 if(state->remote_addrlen==0) {
1109 memcpy(&state->remote_addr, &fromaddr, fromlen);
1110 state->remote_addrlen = fromlen;
1113 /* Sanity check packet length */
1114 if(state->rbytes < 4) {
1115 failf(data, "Received too short packet");
1116 /* Not a timeout, but how best to handle it? */
1117 state->event = TFTP_EVENT_TIMEOUT;
1120 /* The event is given by the TFTP packet time */
1121 state->event = (tftp_event_t)getrpacketevent(&state->rpacket);
1123 switch(state->event) {
1124 case TFTP_EVENT_DATA:
1125 /* Don't pass to the client empty or retransmitted packets */
1126 if(state->rbytes > 4 &&
1127 (NEXT_BLOCKNUM(state->block) == getrpacketblock(&state->rpacket))) {
1128 result = Curl_client_write(conn, CLIENTWRITE_BODY,
1129 (char *)state->rpacket.data+4,
1132 tftp_state_machine(state, TFTP_EVENT_ERROR);
1135 k->bytecount += state->rbytes-4;
1136 Curl_pgrsSetDownloadCounter(data, (curl_off_t) k->bytecount);
1139 case TFTP_EVENT_ERROR:
1140 state->error = (tftp_error_t)getrpacketblock(&state->rpacket);
1141 infof(data, "%s\n", (const char *)state->rpacket.data+4);
1143 case TFTP_EVENT_ACK:
1145 case TFTP_EVENT_OACK:
1146 result = tftp_parse_option_ack(state,
1147 (const char *)state->rpacket.data+2,
1152 case TFTP_EVENT_RRQ:
1153 case TFTP_EVENT_WRQ:
1155 failf(data, "%s", "Internal error: Unexpected packet");
1159 /* Update the progress meter */
1160 if(Curl_pgrsUpdate(conn)) {
1161 tftp_state_machine(state, TFTP_EVENT_ERROR);
1162 return CURLE_ABORTED_BY_CALLBACK;
1168 /**********************************************************
1170 * tftp_state_timeout
1172 * Check if timeouts have been reached
1174 **********************************************************/
1175 static long tftp_state_timeout(struct connectdata *conn, tftp_event_t *event)
1178 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1181 *event = TFTP_EVENT_NONE;
1184 if(current > state->max_time) {
1185 DEBUGF(infof(conn->data, "timeout: %ld > %ld\n",
1186 (long)current, (long)state->max_time));
1187 state->error = TFTP_ERR_TIMEOUT;
1188 state->state = TFTP_STATE_FIN;
1191 else if(current > state->rx_time+state->retry_time) {
1193 *event = TFTP_EVENT_TIMEOUT;
1194 time(&state->rx_time); /* update even though we received nothing */
1197 /* there's a typecast below here since 'time_t' may in fact be larger than
1198 'long', but we estimate that a 'long' will still be able to hold number
1199 of seconds even if "only" 32 bit */
1200 return (long)(state->max_time - current);
1203 /**********************************************************
1205 * tftp_multi_statemach
1207 * Handle single RX socket event and return
1209 **********************************************************/
1210 static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done)
1214 CURLcode result = CURLE_OK;
1215 struct Curl_easy *data = conn->data;
1216 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1217 long timeout_ms = tftp_state_timeout(conn, &event);
1221 if(timeout_ms <= 0) {
1222 failf(data, "TFTP response timeout");
1223 return CURLE_OPERATION_TIMEDOUT;
1225 else if(event != TFTP_EVENT_NONE) {
1226 result = tftp_state_machine(state, event);
1229 *done = (state->state == TFTP_STATE_FIN) ? TRUE : FALSE;
1231 /* Tell curl we're done */
1232 Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1235 /* no timeouts to handle, check our socket */
1236 rc = Curl_socket_ready(state->sockfd, CURL_SOCKET_BAD, 0);
1240 int error = SOCKERRNO;
1241 failf(data, "%s", Curl_strerror(conn, error));
1242 state->event = TFTP_EVENT_ERROR;
1245 result = tftp_receive_packet(conn);
1248 result = tftp_state_machine(state, state->event);
1251 *done = (state->state == TFTP_STATE_FIN) ? TRUE : FALSE;
1253 /* Tell curl we're done */
1254 Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1256 /* if rc == 0, then select() timed out */
1262 /**********************************************************
1266 * Called from multi.c while DOing
1268 **********************************************************/
1269 static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done)
1272 result = tftp_multi_statemach(conn, dophase_done);
1275 DEBUGF(infof(conn->data, "DO phase is complete\n"));
1278 /* The multi code doesn't have this logic for the DOING state so we
1279 provide it for TFTP since it may do the entire transfer in this
1281 if(Curl_pgrsUpdate(conn))
1282 result = CURLE_ABORTED_BY_CALLBACK;
1284 result = Curl_speedcheck(conn->data, Curl_tvnow());
1289 /**********************************************************
1293 * Entry point for transfer from tftp_do, sarts state mach
1295 **********************************************************/
1296 static CURLcode tftp_perform(struct connectdata *conn, bool *dophase_done)
1298 CURLcode result = CURLE_OK;
1299 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1301 *dophase_done = FALSE;
1303 result = tftp_state_machine(state, TFTP_EVENT_INIT);
1305 if((state->state == TFTP_STATE_FIN) || result)
1308 tftp_multi_statemach(conn, dophase_done);
1311 DEBUGF(infof(conn->data, "DO phase is complete\n"));
1317 /**********************************************************
1323 * This callback initiates the TFTP transfer
1325 **********************************************************/
1327 static CURLcode tftp_do(struct connectdata *conn, bool *done)
1329 tftp_state_data_t *state;
1334 if(!conn->proto.tftpc) {
1335 result = tftp_connect(conn, done);
1340 state = (tftp_state_data_t *)conn->proto.tftpc;
1342 return CURLE_BAD_CALLING_ORDER;
1344 result = tftp_perform(conn, done);
1346 /* If tftp_perform() returned an error, use that for return code. If it
1347 was OK, see if tftp_translate_code() has an error. */
1349 /* If we have encountered an internal tftp error, translate it. */
1350 result = tftp_translate_code(state->error);
1355 static CURLcode tftp_setup_connection(struct connectdata * conn)
1357 struct Curl_easy *data = conn->data;
1361 conn->socktype = SOCK_DGRAM; /* UDP datagram based */
1363 /* TFTP URLs support an extension like ";mode=<typecode>" that
1364 * we'll try to get now! */
1365 type = strstr(data->state.path, ";mode=");
1368 type = strstr(conn->host.rawalloc, ";mode=");
1371 *type = 0; /* it was in the middle of the hostname */
1372 command = Curl_raw_toupper(type[6]);
1375 case 'A': /* ASCII mode */
1376 case 'N': /* NETASCII mode */
1377 data->set.prefer_ascii = TRUE;
1380 case 'O': /* octet mode */
1381 case 'I': /* binary mode */
1383 /* switch off ASCII */
1384 data->set.prefer_ascii = FALSE;