1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2013, Daniel Stenberg, <daniel@haxx.se>, et al.
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at http://curl.haxx.se/docs/copyright.html.
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
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 */
60 #define _MPRINTF_REPLACE /* use our functions only */
61 #include <curl/mprintf.h>
63 #include "curl_memory.h"
66 /* The last #include file should be: */
69 /* RFC2348 allows the block size to be negotiated */
70 #define TFTP_BLKSIZE_DEFAULT 512
71 #define TFTP_BLKSIZE_MIN 8
72 #define TFTP_BLKSIZE_MAX 65464
73 #define TFTP_OPTION_BLKSIZE "blksize"
76 #define TFTP_OPTION_TSIZE "tsize"
77 #define TFTP_OPTION_INTERVAL "timeout"
111 TFTP_ERR_NOSUCHUSER, /* This will never be triggered by this code */
113 /* The remaining error codes are internal to curl */
114 TFTP_ERR_NONE = -100,
119 typedef struct tftp_packet {
123 typedef struct tftp_state_data {
128 struct connectdata *conn;
129 curl_socket_t sockfd;
136 unsigned short block;
137 struct Curl_sockaddr_storage local_addr;
138 struct Curl_sockaddr_storage remote_addr;
139 curl_socklen_t remote_addrlen;
143 int requested_blksize;
144 tftp_packet_t rpacket;
145 tftp_packet_t spacket;
149 /* Forward declarations */
150 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event) ;
151 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event) ;
152 static CURLcode tftp_connect(struct connectdata *conn, bool *done);
153 static CURLcode tftp_disconnect(struct connectdata *conn,
154 bool dead_connection);
155 static CURLcode tftp_do(struct connectdata *conn, bool *done);
156 static CURLcode tftp_done(struct connectdata *conn,
157 CURLcode, bool premature);
158 static CURLcode tftp_setup_connection(struct connectdata * conn);
159 static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done);
160 static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done);
161 static int tftp_getsock(struct connectdata *conn, curl_socket_t *socks,
163 static CURLcode tftp_translate_code(tftp_error_t error);
167 * TFTP protocol handler.
170 const struct Curl_handler Curl_handler_tftp = {
172 tftp_setup_connection, /* setup_connection */
174 tftp_done, /* done */
175 ZERO_NULL, /* do_more */
176 tftp_connect, /* connect_it */
177 tftp_multi_statemach, /* connecting */
178 tftp_doing, /* doing */
179 tftp_getsock, /* proto_getsock */
180 tftp_getsock, /* doing_getsock */
181 ZERO_NULL, /* domore_getsock */
182 ZERO_NULL, /* perform_getsock */
183 tftp_disconnect, /* disconnect */
184 ZERO_NULL, /* readwrite */
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;
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)
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)
256 if(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)
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 SessionHandle *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 else 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 SessionHandle *data = state->conn->data;
423 infof(data, "%s\n", "Connected for transmit");
425 state->state = TFTP_STATE_TX;
426 res = 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 SessionHandle *data = state->conn->data;
439 infof(data, "%s\n", "Connected for receive");
441 state->state = TFTP_STATE_RX;
442 res = 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";
455 struct SessionHandle *data = state->conn->data;
456 CURLcode res = CURLE_OK;
458 /* Set ascii mode if -B flag was used */
459 if(data->set.prefer_ascii)
464 case TFTP_EVENT_INIT: /* Send the first packet out */
465 case TFTP_EVENT_TIMEOUT: /* Resend the first packet out */
466 /* Increment the retry counter, quit if over the limit */
468 if(state->retries>state->retry_max) {
469 state->error = TFTP_ERR_NORESPONSE;
470 state->state = TFTP_STATE_FIN;
474 if(data->set.upload) {
475 /* If we are uploading, send an WRQ */
476 setpacketevent(&state->spacket, TFTP_EVENT_WRQ);
477 state->conn->data->req.upload_fromhere =
478 (char *)state->spacket.data+4;
479 if(data->set.infilesize != -1)
480 Curl_pgrsSetUploadSize(data, data->set.infilesize);
483 /* If we are downloading, send an RRQ */
484 setpacketevent(&state->spacket, TFTP_EVENT_RRQ);
486 /* As RFC3617 describes the separator slash is not actually part of the
487 file name so we skip the always-present first letter of the path
489 filename = curl_easy_unescape(data, &state->conn->data->state.path[1], 0,
492 return CURLE_OUT_OF_MEMORY;
494 snprintf((char *)state->spacket.data+2,
496 "%s%c%s%c", filename, '\0', mode, '\0');
497 sbytes = 4 + strlen(filename) + strlen(mode);
499 /* add tsize option */
500 if(data->set.upload && (data->set.infilesize != -1))
501 snprintf( buf, sizeof(buf), "%" FORMAT_OFF_T, data->set.infilesize );
503 strcpy(buf, "0"); /* the destination is large enough */
505 sbytes += tftp_option_add(state, sbytes,
506 (char *)state->spacket.data+sbytes,
508 sbytes += tftp_option_add(state, sbytes,
509 (char *)state->spacket.data+sbytes, buf);
510 /* add blksize option */
511 snprintf( buf, sizeof(buf), "%d", state->requested_blksize );
512 sbytes += tftp_option_add(state, sbytes,
513 (char *)state->spacket.data+sbytes,
514 TFTP_OPTION_BLKSIZE);
515 sbytes += tftp_option_add(state, sbytes,
516 (char *)state->spacket.data+sbytes, buf );
518 /* add timeout option */
519 snprintf( buf, sizeof(buf), "%d", state->retry_time);
520 sbytes += tftp_option_add(state, sbytes,
521 (char *)state->spacket.data+sbytes,
522 TFTP_OPTION_INTERVAL);
523 sbytes += tftp_option_add(state, sbytes,
524 (char *)state->spacket.data+sbytes, buf );
526 /* the typecase for the 3rd argument is mostly for systems that do
527 not have a size_t argument, like older unixes that want an 'int' */
528 senddata = sendto(state->sockfd, (void *)state->spacket.data,
529 (SEND_TYPE_ARG3)sbytes, 0,
530 state->conn->ip_addr->ai_addr,
531 state->conn->ip_addr->ai_addrlen);
532 if(senddata != (ssize_t)sbytes) {
533 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
535 Curl_safefree(filename);
538 case TFTP_EVENT_OACK:
539 if(data->set.upload) {
540 res = tftp_connect_for_tx(state, event);
543 res = tftp_connect_for_rx(state, event);
547 case TFTP_EVENT_ACK: /* Connected for transmit */
548 res = tftp_connect_for_tx(state, event);
551 case TFTP_EVENT_DATA: /* Connected for receive */
552 res = tftp_connect_for_rx(state, event);
555 case TFTP_EVENT_ERROR:
556 state->state = TFTP_STATE_FIN;
560 failf(state->conn->data, "tftp_send_first: internal error");
566 /* the next blocknum is x + 1 but it needs to wrap at an unsigned 16bit
568 #define NEXT_BLOCKNUM(x) (((x)+1)&0xffff)
570 /**********************************************************
574 * Event handler for the RX state
576 **********************************************************/
577 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event)
581 struct SessionHandle *data = state->conn->data;
585 case TFTP_EVENT_DATA:
586 /* Is this the block we expect? */
587 rblock = getrpacketblock(&state->rpacket);
588 if(NEXT_BLOCKNUM(state->block) == rblock) {
589 /* This is the expected block. Reset counters and ACK it. */
592 else if(state->block == rblock) {
593 /* This is the last recently received block again. Log it and ACK it
595 infof(data, "Received last DATA packet block %d again.\n", rblock);
598 /* totally unexpected, just log it */
600 "Received unexpected DATA packet block %d, expecting block %d\n",
601 rblock, NEXT_BLOCKNUM(state->block));
605 /* ACK this block. */
606 state->block = (unsigned short)rblock;
607 setpacketevent(&state->spacket, TFTP_EVENT_ACK);
608 setpacketblock(&state->spacket, state->block);
609 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
611 (struct sockaddr *)&state->remote_addr,
612 state->remote_addrlen);
614 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
615 return CURLE_SEND_ERROR;
618 /* Check if completed (That is, a less than full packet is received) */
619 if(state->rbytes < (ssize_t)state->blksize+4) {
620 state->state = TFTP_STATE_FIN;
623 state->state = TFTP_STATE_RX;
625 time(&state->rx_time);
628 case TFTP_EVENT_OACK:
629 /* ACK option acknowledgement so we can move on to data */
632 setpacketevent(&state->spacket, TFTP_EVENT_ACK);
633 setpacketblock(&state->spacket, state->block);
634 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
636 (struct sockaddr *)&state->remote_addr,
637 state->remote_addrlen);
639 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
640 return CURLE_SEND_ERROR;
643 /* we're ready to RX data */
644 state->state = TFTP_STATE_RX;
645 time(&state->rx_time);
648 case TFTP_EVENT_TIMEOUT:
649 /* Increment the retry count and fail if over the limit */
652 "Timeout waiting for block %d ACK. Retries = %d\n",
653 NEXT_BLOCKNUM(state->block), state->retries);
654 if(state->retries > state->retry_max) {
655 state->error = TFTP_ERR_TIMEOUT;
656 state->state = TFTP_STATE_FIN;
659 /* Resend the previous ACK */
660 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
662 (struct sockaddr *)&state->remote_addr,
663 state->remote_addrlen);
665 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
666 return CURLE_SEND_ERROR;
671 case TFTP_EVENT_ERROR:
672 setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
673 setpacketblock(&state->spacket, state->block);
674 (void)sendto(state->sockfd, (void *)state->spacket.data,
676 (struct sockaddr *)&state->remote_addr,
677 state->remote_addrlen);
678 /* don't bother with the return code, but if the socket is still up we
679 * should be a good TFTP client and let the server know we're done */
680 state->state = TFTP_STATE_FIN;
684 failf(data, "%s", "tftp_rx: internal error");
685 return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for
691 /**********************************************************
695 * Event handler for the TX state
697 **********************************************************/
698 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event)
700 struct SessionHandle *data = state->conn->data;
703 CURLcode res = CURLE_OK;
704 struct SingleRequest *k = &data->req;
709 case TFTP_EVENT_OACK:
710 if(event == TFTP_EVENT_ACK) {
712 rblock = getrpacketblock(&state->rpacket);
714 if(rblock != state->block &&
715 /* There's a bug in tftpd-hpa that causes it to send us an ack for
716 * 65535 when the block number wraps to 0. So when we're expecting
717 * 0, also accept 65535. See
718 * http://syslinux.zytor.com/archives/2010-September/015253.html
720 !(state->block == 0 && rblock == 65535)) {
721 /* This isn't the expected block. Log it and up the retry counter */
722 infof(data, "Received ACK for block %d, expecting %d\n",
723 rblock, state->block);
725 /* Bail out if over the maximum */
726 if(state->retries>state->retry_max) {
727 failf(data, "tftp_tx: giving up waiting for block %d ack",
729 res = CURLE_SEND_ERROR;
732 /* Re-send the data packet */
733 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
734 4+state->sbytes, SEND_4TH_ARG,
735 (struct sockaddr *)&state->remote_addr,
736 state->remote_addrlen);
737 /* Check all sbytes were sent */
739 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
740 res = CURLE_SEND_ERROR;
745 /* This is the expected packet. Reset the counters and send the next
747 time(&state->rx_time);
751 state->block = 1; /* first data block is 1 when using OACK */
754 setpacketevent(&state->spacket, TFTP_EVENT_DATA);
755 setpacketblock(&state->spacket, state->block);
756 if(state->block > 1 && state->sbytes < (int)state->blksize) {
757 state->state = TFTP_STATE_FIN;
760 res = Curl_fillreadbuffer(state->conn, state->blksize, &state->sbytes);
763 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
764 4+state->sbytes, SEND_4TH_ARG,
765 (struct sockaddr *)&state->remote_addr,
766 state->remote_addrlen);
767 /* Check all sbytes were sent */
769 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
770 return CURLE_SEND_ERROR;
772 /* Update the progress meter */
773 k->writebytecount += state->sbytes;
774 Curl_pgrsSetUploadCounter(data, k->writebytecount);
777 case TFTP_EVENT_TIMEOUT:
778 /* Increment the retry counter and log the timeout */
780 infof(data, "Timeout waiting for block %d ACK. "
781 " Retries = %d\n", NEXT_BLOCKNUM(state->block), state->retries);
782 /* Decide if we've had enough */
783 if(state->retries > state->retry_max) {
784 state->error = TFTP_ERR_TIMEOUT;
785 state->state = TFTP_STATE_FIN;
788 /* Re-send the data packet */
789 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
790 4+state->sbytes, SEND_4TH_ARG,
791 (struct sockaddr *)&state->remote_addr,
792 state->remote_addrlen);
793 /* Check all sbytes were sent */
795 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
796 return CURLE_SEND_ERROR;
798 /* since this was a re-send, we remain at the still byte position */
799 Curl_pgrsSetUploadCounter(data, k->writebytecount);
803 case TFTP_EVENT_ERROR:
804 state->state = TFTP_STATE_FIN;
805 setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
806 setpacketblock(&state->spacket, state->block);
807 (void)sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG,
808 (struct sockaddr *)&state->remote_addr,
809 state->remote_addrlen);
810 /* don't bother with the return code, but if the socket is still up we
811 * should be a good TFTP client and let the server know we're done */
812 state->state = TFTP_STATE_FIN;
816 failf(data, "tftp_tx: internal error, event: %i", (int)(event));
823 /**********************************************************
825 * tftp_translate_code
827 * Translate internal error codes to CURL error codes
829 **********************************************************/
830 static CURLcode tftp_translate_code(tftp_error_t error)
832 CURLcode code = CURLE_OK;
834 if(error != TFTP_ERR_NONE) {
836 case TFTP_ERR_NOTFOUND:
837 code = CURLE_TFTP_NOTFOUND;
840 code = CURLE_TFTP_PERM;
842 case TFTP_ERR_DISKFULL:
843 code = CURLE_REMOTE_DISK_FULL;
846 case TFTP_ERR_ILLEGAL:
847 code = CURLE_TFTP_ILLEGAL;
849 case TFTP_ERR_UNKNOWNID:
850 code = CURLE_TFTP_UNKNOWNID;
852 case TFTP_ERR_EXISTS:
853 code = CURLE_REMOTE_FILE_EXISTS;
855 case TFTP_ERR_NOSUCHUSER:
856 code = CURLE_TFTP_NOSUCHUSER;
858 case TFTP_ERR_TIMEOUT:
859 code = CURLE_OPERATION_TIMEDOUT;
861 case TFTP_ERR_NORESPONSE:
862 code = CURLE_COULDNT_CONNECT;
865 code= CURLE_ABORTED_BY_CALLBACK;
876 /**********************************************************
880 * The tftp state machine event dispatcher
882 **********************************************************/
883 static CURLcode tftp_state_machine(tftp_state_data_t *state,
886 CURLcode res = CURLE_OK;
887 struct SessionHandle *data = state->conn->data;
888 switch(state->state) {
889 case TFTP_STATE_START:
890 DEBUGF(infof(data, "TFTP_STATE_START\n"));
891 res = tftp_send_first(state, event);
894 DEBUGF(infof(data, "TFTP_STATE_RX\n"));
895 res = tftp_rx(state, event);
898 DEBUGF(infof(data, "TFTP_STATE_TX\n"));
899 res = tftp_tx(state, event);
902 infof(data, "%s\n", "TFTP finished");
905 DEBUGF(infof(data, "STATE: %d\n", state->state));
906 failf(data, "%s", "Internal state machine error");
907 res = CURLE_TFTP_ILLEGAL;
913 /**********************************************************
917 * The disconnect callback
919 **********************************************************/
920 static CURLcode tftp_disconnect(struct connectdata *conn, bool dead_connection)
922 tftp_state_data_t *state = conn->proto.tftpc;
923 (void) dead_connection;
925 /* done, free dynamically allocated pkt buffers */
927 Curl_safefree(state->rpacket.data);
928 Curl_safefree(state->spacket.data);
935 /**********************************************************
939 * The connect callback
941 **********************************************************/
942 static CURLcode tftp_connect(struct connectdata *conn, bool *done)
945 tftp_state_data_t *state;
948 blksize = TFTP_BLKSIZE_DEFAULT;
950 /* If there already is a protocol-specific struct allocated for this
951 sessionhandle, deal with it */
952 Curl_reset_reqproto(conn);
954 state = conn->proto.tftpc = calloc(1, sizeof(tftp_state_data_t));
956 return CURLE_OUT_OF_MEMORY;
958 /* alloc pkt buffers based on specified blksize */
959 if(conn->data->set.tftp_blksize) {
960 blksize = (int)conn->data->set.tftp_blksize;
961 if(blksize > TFTP_BLKSIZE_MAX || blksize < TFTP_BLKSIZE_MIN )
962 return CURLE_TFTP_ILLEGAL;
965 if(!state->rpacket.data) {
966 state->rpacket.data = calloc(1, blksize + 2 + 2);
968 if(!state->rpacket.data)
969 return CURLE_OUT_OF_MEMORY;
972 if(!state->spacket.data) {
973 state->spacket.data = calloc(1, blksize + 2 + 2);
975 if(!state->spacket.data)
976 return CURLE_OUT_OF_MEMORY;
979 conn->bits.close = TRUE; /* we don't keep TFTP connections up bascially
980 because there's none or very little gain for UDP
984 state->sockfd = state->conn->sock[FIRSTSOCKET];
985 state->state = TFTP_STATE_START;
986 state->error = TFTP_ERR_NONE;
987 state->blksize = TFTP_BLKSIZE_DEFAULT;
988 state->requested_blksize = blksize;
990 ((struct sockaddr *)&state->local_addr)->sa_family =
991 (unsigned short)(conn->ip_addr->ai_family);
993 tftp_set_timeouts(state);
995 if(!conn->bits.bound) {
996 /* If not already bound, bind to any interface, random UDP port. If it is
997 * reused or a custom local port was desired, this has already been done!
999 * We once used the size of the local_addr struct as the third argument
1000 * for bind() to better work with IPv6 or whatever size the struct could
1001 * have, but we learned that at least Tru64, AIX and IRIX *requires* the
1002 * size of that argument to match the exact size of a 'sockaddr_in' struct
1003 * when running IPv4-only.
1005 * Therefore we use the size from the address we connected to, which we
1006 * assume uses the same IP version and thus hopefully this works for both
1009 rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr,
1010 conn->ip_addr->ai_addrlen);
1012 failf(conn->data, "bind() failed; %s",
1013 Curl_strerror(conn, SOCKERRNO));
1014 return CURLE_COULDNT_CONNECT;
1016 conn->bits.bound = TRUE;
1019 Curl_pgrsStartNow(conn->data);
1026 /**********************************************************
1032 **********************************************************/
1033 static CURLcode tftp_done(struct connectdata *conn, CURLcode status,
1036 CURLcode code = CURLE_OK;
1037 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1039 (void)status; /* unused */
1040 (void)premature; /* not used */
1042 if(Curl_pgrsDone(conn))
1043 return CURLE_ABORTED_BY_CALLBACK;
1045 /* If we have encountered an error */
1046 code = tftp_translate_code(state->error);
1051 /**********************************************************
1055 * The getsock callback
1057 **********************************************************/
1058 static int tftp_getsock(struct connectdata *conn, curl_socket_t *socks,
1062 return GETSOCK_BLANK;
1064 socks[0] = conn->sock[FIRSTSOCKET];
1066 return GETSOCK_READSOCK(0);
1069 /**********************************************************
1071 * tftp_receive_packet
1073 * Called once select fires and data is ready on the socket
1075 **********************************************************/
1076 static CURLcode tftp_receive_packet(struct connectdata *conn)
1078 struct Curl_sockaddr_storage fromaddr;
1079 curl_socklen_t fromlen;
1080 CURLcode result = CURLE_OK;
1081 struct SessionHandle *data = conn->data;
1082 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1083 struct SingleRequest *k = &data->req;
1085 /* Receive the packet */
1086 fromlen = sizeof(fromaddr);
1087 state->rbytes = (int)recvfrom(state->sockfd,
1088 (void *)state->rpacket.data,
1091 (struct sockaddr *)&fromaddr,
1093 if(state->remote_addrlen==0) {
1094 memcpy(&state->remote_addr, &fromaddr, fromlen);
1095 state->remote_addrlen = fromlen;
1098 /* Sanity check packet length */
1099 if(state->rbytes < 4) {
1100 failf(data, "Received too short packet");
1101 /* Not a timeout, but how best to handle it? */
1102 state->event = TFTP_EVENT_TIMEOUT;
1105 /* The event is given by the TFTP packet time */
1106 state->event = (tftp_event_t)getrpacketevent(&state->rpacket);
1108 switch(state->event) {
1109 case TFTP_EVENT_DATA:
1110 /* Don't pass to the client empty or retransmitted packets */
1111 if(state->rbytes > 4 &&
1112 (NEXT_BLOCKNUM(state->block) == getrpacketblock(&state->rpacket))) {
1113 result = Curl_client_write(conn, CLIENTWRITE_BODY,
1114 (char *)state->rpacket.data+4,
1117 tftp_state_machine(state, TFTP_EVENT_ERROR);
1120 k->bytecount += state->rbytes-4;
1121 Curl_pgrsSetDownloadCounter(data, (curl_off_t) k->bytecount);
1124 case TFTP_EVENT_ERROR:
1125 state->error = (tftp_error_t)getrpacketblock(&state->rpacket);
1126 infof(data, "%s\n", (const char *)state->rpacket.data+4);
1128 case TFTP_EVENT_ACK:
1130 case TFTP_EVENT_OACK:
1131 result = tftp_parse_option_ack(state,
1132 (const char *)state->rpacket.data+2,
1137 case TFTP_EVENT_RRQ:
1138 case TFTP_EVENT_WRQ:
1140 failf(data, "%s", "Internal error: Unexpected packet");
1144 /* Update the progress meter */
1145 if(Curl_pgrsUpdate(conn)) {
1146 tftp_state_machine(state, TFTP_EVENT_ERROR);
1147 return CURLE_ABORTED_BY_CALLBACK;
1153 /**********************************************************
1155 * tftp_state_timeout
1157 * Check if timeouts have been reached
1159 **********************************************************/
1160 static long tftp_state_timeout(struct connectdata *conn, tftp_event_t *event)
1163 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1166 *event = TFTP_EVENT_NONE;
1169 if(current > state->max_time) {
1170 DEBUGF(infof(conn->data, "timeout: %ld > %ld\n",
1171 (long)current, (long)state->max_time));
1172 state->error = TFTP_ERR_TIMEOUT;
1173 state->state = TFTP_STATE_FIN;
1176 else if(current > state->rx_time+state->retry_time) {
1178 *event = TFTP_EVENT_TIMEOUT;
1179 time(&state->rx_time); /* update even though we received nothing */
1182 /* there's a typecast below here since 'time_t' may in fact be larger than
1183 'long', but we estimate that a 'long' will still be able to hold number
1184 of seconds even if "only" 32 bit */
1185 return (long)(state->max_time - current);
1188 /**********************************************************
1190 * tftp_multi_statemach
1192 * Handle single RX socket event and return
1194 **********************************************************/
1195 static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done)
1199 CURLcode result = CURLE_OK;
1200 struct SessionHandle *data = conn->data;
1201 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1202 long timeout_ms = tftp_state_timeout(conn, &event);
1206 if(timeout_ms <= 0) {
1207 failf(data, "TFTP response timeout");
1208 return CURLE_OPERATION_TIMEDOUT;
1210 else if(event != TFTP_EVENT_NONE) {
1211 result = tftp_state_machine(state, event);
1212 if(result != CURLE_OK)
1214 *done = (state->state == TFTP_STATE_FIN) ? TRUE : FALSE;
1216 /* Tell curl we're done */
1217 Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1220 /* no timeouts to handle, check our socket */
1221 rc = Curl_socket_ready(state->sockfd, CURL_SOCKET_BAD, 0);
1225 int error = SOCKERRNO;
1226 failf(data, "%s", Curl_strerror(conn, error));
1227 state->event = TFTP_EVENT_ERROR;
1230 result = tftp_receive_packet(conn);
1231 if(result != CURLE_OK)
1233 result = tftp_state_machine(state, state->event);
1234 if(result != CURLE_OK)
1236 *done = (state->state == TFTP_STATE_FIN) ? TRUE : FALSE;
1238 /* Tell curl we're done */
1239 Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1241 /* if rc == 0, then select() timed out */
1247 /**********************************************************
1251 * Called from multi.c while DOing
1253 **********************************************************/
1254 static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done)
1257 result = tftp_multi_statemach(conn, dophase_done);
1260 DEBUGF(infof(conn->data, "DO phase is complete\n"));
1265 /**********************************************************
1269 * Entry point for transfer from tftp_do, sarts state mach
1271 **********************************************************/
1272 static CURLcode tftp_perform(struct connectdata *conn, bool *dophase_done)
1274 CURLcode result = CURLE_OK;
1275 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1277 *dophase_done = FALSE;
1279 result = tftp_state_machine(state, TFTP_EVENT_INIT);
1281 if(state->state == TFTP_STATE_FIN || result != CURLE_OK)
1284 tftp_multi_statemach(conn, dophase_done);
1287 DEBUGF(infof(conn->data, "DO phase is complete\n"));
1293 /**********************************************************
1299 * This callback initiates the TFTP transfer
1301 **********************************************************/
1303 static CURLcode tftp_do(struct connectdata *conn, bool *done)
1305 tftp_state_data_t *state;
1311 Since connections can be re-used between SessionHandles, this might be a
1312 connection already existing but on a fresh SessionHandle struct so we must
1313 make sure we have a good 'struct TFTP' to play with. For new connections,
1314 the struct TFTP is allocated and setup in the tftp_connect() function.
1316 Curl_reset_reqproto(conn);
1318 if(!conn->proto.tftpc) {
1319 code = tftp_connect(conn, done);
1323 state = (tftp_state_data_t *)conn->proto.tftpc;
1325 code = tftp_perform(conn, done);
1327 /* If tftp_perform() returned an error, use that for return code. If it
1328 was OK, see if tftp_translate_code() has an error. */
1329 if(code == CURLE_OK)
1330 /* If we have encountered an internal tftp error, translate it. */
1331 code = tftp_translate_code(state->error);
1336 static CURLcode tftp_setup_connection(struct connectdata * conn)
1338 struct SessionHandle *data = conn->data;
1342 conn->socktype = SOCK_DGRAM; /* UDP datagram based */
1344 /* TFTP URLs support an extension like ";mode=<typecode>" that
1345 * we'll try to get now! */
1346 type = strstr(data->state.path, ";mode=");
1349 type = strstr(conn->host.rawalloc, ";mode=");
1352 *type = 0; /* it was in the middle of the hostname */
1353 command = Curl_raw_toupper(type[6]);
1356 case 'A': /* ASCII mode */
1357 case 'N': /* NETASCII mode */
1358 data->set.prefer_ascii = TRUE;
1361 case 'O': /* octet mode */
1362 case 'I': /* binary mode */
1364 /* switch off ASCII */
1365 data->set.prefer_ascii = FALSE;