1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2009, 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.
22 ***************************************************************************/
26 #ifndef CURL_DISABLE_TFTP
27 /* -- WIN32 approved -- */
37 #ifdef HAVE_SYS_SOCKET_H
38 #include <sys/socket.h>
40 #include <netinet/in.h>
41 #ifdef HAVE_SYS_TIME_H
48 #ifdef HAVE_ARPA_INET_H
49 #include <arpa/inet.h>
54 #ifdef HAVE_SYS_IOCTL_H
55 #include <sys/ioctl.h>
58 #ifdef HAVE_SYS_PARAM_H
59 #include <sys/param.h>
65 #include <curl/curl.h>
72 #include "sockaddr.h" /* required for Curl_sockaddr_storage */
77 #define _MPRINTF_REPLACE /* use our functions only */
78 #include <curl/mprintf.h>
80 #include "curl_memory.h"
83 /* The last #include file should be: */
86 /* RFC2348 allows the block size to be negotiated */
87 #define TFTP_BLKSIZE_DEFAULT 512
88 #define TFTP_BLKSIZE_MIN 8
89 #define TFTP_BLKSIZE_MAX 65464
90 #define TFTP_OPTION_BLKSIZE "blksize"
91 #define TFTP_OPTION_TSIZE "tsize"
92 #define TFTP_OPTION_INTERVAL "interval"
107 TFTP_EVENT_NONE = -1,
113 TFTP_EVENT_ERROR = 5,
126 TFTP_ERR_NOSUCHUSER, /* This will never be triggered by this code */
128 /* The remaining error codes are internal to curl */
129 TFTP_ERR_NONE = -100,
134 typedef struct tftp_packet {
138 typedef struct tftp_state_data {
143 struct connectdata *conn;
144 curl_socket_t sockfd;
151 unsigned short block;
152 struct Curl_sockaddr_storage local_addr;
153 struct Curl_sockaddr_storage remote_addr;
154 curl_socklen_t remote_addrlen;
158 int requested_blksize;
159 tftp_packet_t rpacket;
160 tftp_packet_t spacket;
164 /* Forward declarations */
165 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event) ;
166 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event) ;
167 static CURLcode tftp_connect(struct connectdata *conn, bool *done);
168 static CURLcode tftp_disconnect(struct connectdata *conn);
169 static CURLcode tftp_do(struct connectdata *conn, bool *done);
170 static CURLcode tftp_done(struct connectdata *conn,
171 CURLcode, bool premature);
172 static CURLcode tftp_setup_connection(struct connectdata * conn);
173 static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done);
174 static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done);
175 static int tftp_getsock(struct connectdata *conn, curl_socket_t *socks,
177 CURLcode tftp_translate_code(tftp_error_t error);
181 * TFTP protocol handler.
184 const struct Curl_handler Curl_handler_tftp = {
186 tftp_setup_connection, /* setup_connection */
188 tftp_done, /* done */
189 ZERO_NULL, /* do_more */
190 tftp_connect, /* connect_it */
191 tftp_multi_statemach, /* connecting */
192 tftp_doing, /* doing */
193 tftp_getsock, /* proto_getsock */
194 tftp_getsock, /* doing_getsock */
195 ZERO_NULL, /* perform_getsock */
196 tftp_disconnect, /* disconnect */
197 PORT_TFTP, /* defport */
198 PROT_TFTP /* protocol */
201 /**********************************************************
203 * tftp_set_timeouts -
205 * Set timeouts based on state machine state.
206 * Use user provided connect timeouts until DATA or ACK
207 * packet is received, then use user-provided transfer timeouts
210 **********************************************************/
211 static CURLcode tftp_set_timeouts(tftp_state_data_t *state)
213 time_t maxtime, timeout;
215 bool start = (bool)(state->state == TFTP_STATE_START);
217 time(&state->start_time);
219 /* Compute drop-dead time */
220 timeout_ms = Curl_timeleft(state->conn, NULL, start);
223 /* time-out, bail out, go home */
224 failf(state->conn->data, "Connection time-out");
225 return CURLE_OPERATION_TIMEDOUT;
230 maxtime = (time_t)(timeout_ms + 500) / 1000;
231 state->max_time = state->start_time+maxtime;
233 /* Set per-block timeout to total */
236 /* Average restart after 5 seconds */
237 state->retry_max = (int)timeout/5;
239 if(state->retry_max < 1)
240 /* avoid division by zero below */
241 state->retry_max = 1;
243 /* Compute the re-start interval to suit the timeout */
244 state->retry_time = (int)timeout/state->retry_max;
245 if(state->retry_time<1)
251 maxtime = (time_t)(timeout_ms + 500) / 1000;
255 state->max_time = state->start_time+maxtime;
257 /* Set per-block timeout to 10% of total */
258 timeout = maxtime/10 ;
260 /* Average reposting an ACK after 15 seconds */
261 state->retry_max = (int)timeout/15;
263 /* But bound the total number */
264 if(state->retry_max<3)
267 if(state->retry_max>50)
270 /* Compute the re-ACK interval to suit the timeout */
271 state->retry_time = timeout/state->retry_max;
272 if(state->retry_time<1)
275 infof(state->conn->data,
276 "set timeouts for state %d; Total %d, retry %d maxtry %d\n",
277 state->state, (state->max_time-state->start_time),
278 state->retry_time, state->retry_max);
281 time(&state->rx_time);
286 /**********************************************************
288 * tftp_set_send_first
290 * Event handler for the START state
292 **********************************************************/
294 static void setpacketevent(tftp_packet_t *packet, unsigned short num)
296 packet->data[0] = (unsigned char)(num >> 8);
297 packet->data[1] = (unsigned char)(num & 0xff);
301 static void setpacketblock(tftp_packet_t *packet, unsigned short num)
303 packet->data[2] = (unsigned char)(num >> 8);
304 packet->data[3] = (unsigned char)(num & 0xff);
307 static unsigned short getrpacketevent(const tftp_packet_t *packet)
309 return (unsigned short)((packet->data[0] << 8) | packet->data[1]);
312 static unsigned short getrpacketblock(const tftp_packet_t *packet)
314 return (unsigned short)((packet->data[2] << 8) | packet->data[3]);
317 static size_t Curl_strnlen(const char *string, size_t maxlen)
319 const char *end = memchr (string, '\0', maxlen);
320 return end ? (size_t) (end - string) : maxlen;
323 static const char *tftp_option_get(const char *buf, size_t len,
324 const char **option, const char **value)
328 loc = Curl_strnlen( buf, len );
329 loc++; /* NULL term */
335 loc += Curl_strnlen( buf+loc, len-loc );
336 loc++; /* NULL term */
340 *value = &buf[strlen(*option) + 1];
345 static CURLcode tftp_parse_option_ack(tftp_state_data_t *state,
346 const char *ptr, int len)
348 const char *tmp = ptr;
349 struct SessionHandle *data = state->conn->data;
351 /* if OACK doesn't contain blksize option, the default (512) must be used */
352 state->blksize = TFTP_BLKSIZE_DEFAULT;
354 while (tmp < ptr + len) {
355 const char *option, *value;
357 tmp = tftp_option_get(tmp, ptr + len - tmp, &option, &value);
359 failf(data, "Malformed ACK packet, rejecting");
360 return CURLE_TFTP_ILLEGAL;
363 infof(data, "got option=(%s) value=(%s)\n", option, value);
365 if(checkprefix(option, TFTP_OPTION_BLKSIZE)) {
368 blksize = strtol( value, NULL, 10 );
371 failf(data, "invalid blocksize value in OACK packet");
372 return CURLE_TFTP_ILLEGAL;
374 else if(blksize > TFTP_BLKSIZE_MAX) {
375 failf(data, "%s (%d)", "blksize is larger than max supported",
377 return CURLE_TFTP_ILLEGAL;
379 else if(blksize < TFTP_BLKSIZE_MIN) {
380 failf(data, "%s (%d)", "blksize is smaller than min supported",
382 return CURLE_TFTP_ILLEGAL;
384 else if (blksize > state->requested_blksize) {
385 /* could realloc pkt buffers here, but the spec doesn't call out
386 * support for the server requesting a bigger blksize than the client
388 failf(data, "%s (%d)",
389 "server requested blksize larger than allocated", blksize);
390 return CURLE_TFTP_ILLEGAL;
393 state->blksize = (int)blksize;
394 infof(data, "%s (%d) %s (%d)\n", "blksize parsed from OACK",
395 state->blksize, "requested", state->requested_blksize);
397 else if(checkprefix(option, TFTP_OPTION_TSIZE)) {
400 tsize = strtol( value, NULL, 10 );
402 failf(data, "invalid tsize value in OACK packet");
403 return CURLE_TFTP_ILLEGAL;
405 Curl_pgrsSetDownloadSize(data, tsize);
406 infof(data, "%s (%d)\n", "tsize parsed from OACK", tsize);
413 static size_t tftp_option_add(tftp_state_data_t *state, size_t csize,
414 char *buf, const char *option)
416 if( ( strlen(option) + csize + 1 ) > (size_t)state->blksize )
419 return( strlen(option) + 1 );
422 static CURLcode tftp_connect_for_tx(tftp_state_data_t *state,
426 #ifndef CURL_DISABLE_VERBOSE_STRINGS
427 struct SessionHandle *data = state->conn->data;
429 infof(data, "%s\n", "Connected for transmit");
431 state->state = TFTP_STATE_TX;
432 res = tftp_set_timeouts(state);
435 return tftp_tx(state, event);
438 static CURLcode tftp_connect_for_rx(tftp_state_data_t *state,
442 #ifndef CURL_DISABLE_VERBOSE_STRINGS
443 struct SessionHandle *data = state->conn->data;
445 infof(data, "%s\n", "Connected for receive");
447 state->state = TFTP_STATE_RX;
448 res = tftp_set_timeouts(state);
451 return tftp_rx(state, event);
454 static CURLcode tftp_send_first(tftp_state_data_t *state, tftp_event_t event)
458 const char *mode = "octet";
461 struct SessionHandle *data = state->conn->data;
462 CURLcode res = CURLE_OK;
464 /* Set ascii mode if -B flag was used */
465 if(data->set.prefer_ascii)
470 case TFTP_EVENT_INIT: /* Send the first packet out */
471 case TFTP_EVENT_TIMEOUT: /* Resend the first packet out */
472 /* Increment the retry counter, quit if over the limit */
474 if(state->retries>state->retry_max) {
475 state->error = TFTP_ERR_NORESPONSE;
476 state->state = TFTP_STATE_FIN;
480 if(data->set.upload) {
481 /* If we are uploading, send an WRQ */
482 setpacketevent(&state->spacket, TFTP_EVENT_WRQ);
483 state->conn->data->req.upload_fromhere =
484 (char *)state->spacket.data+4;
485 if(data->set.infilesize != -1)
486 Curl_pgrsSetUploadSize(data, data->set.infilesize);
489 /* If we are downloading, send an RRQ */
490 setpacketevent(&state->spacket, TFTP_EVENT_RRQ);
492 /* As RFC3617 describes the separator slash is not actually part of the
493 file name so we skip the always-present first letter of the path
495 filename = curl_easy_unescape(data, &state->conn->data->state.path[1], 0,
498 return CURLE_OUT_OF_MEMORY;
500 snprintf((char *)state->spacket.data+2,
502 "%s%c%s%c", filename, '\0', mode, '\0');
503 sbytes = 4 + strlen(filename) + strlen(mode);
505 /* add tsize option */
506 if(data->set.upload && (data->set.infilesize != -1))
507 snprintf( buf, sizeof(buf), "%" FORMAT_OFF_T, data->set.infilesize );
509 strcpy(buf, "0"); /* the destination is large enough */
511 sbytes += tftp_option_add(state, sbytes,
512 (char *)state->spacket.data+sbytes,
514 sbytes += tftp_option_add(state, sbytes,
515 (char *)state->spacket.data+sbytes, buf);
516 /* add blksize option */
517 snprintf( buf, sizeof(buf), "%d", state->requested_blksize );
518 sbytes += tftp_option_add(state, sbytes,
519 (char *)state->spacket.data+sbytes,
520 TFTP_OPTION_BLKSIZE);
521 sbytes += tftp_option_add(state, sbytes,
522 (char *)state->spacket.data+sbytes, buf );
523 /* add timeout option, this is the max time the session may live */
524 snprintf( buf, sizeof(buf), "%d", state->retry_time*state->retry_max );
525 sbytes += tftp_option_add(state, sbytes,
526 (char *)state->spacket.data+sbytes,
527 TFTP_OPTION_INTERVAL);
528 sbytes += tftp_option_add(state, sbytes,
529 (char *)state->spacket.data+sbytes, buf );
531 senddata = sendto(state->sockfd, (void *)state->spacket.data,
533 state->conn->ip_addr->ai_addr,
534 state->conn->ip_addr->ai_addrlen);
535 if(senddata != (ssize_t)sbytes) {
536 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
538 Curl_safefree(filename);
541 case TFTP_EVENT_OACK:
542 if(data->set.upload) {
543 res = tftp_connect_for_tx(state, event);
546 res = tftp_connect_for_rx(state, event);
550 case TFTP_EVENT_ACK: /* Connected for transmit */
551 res = tftp_connect_for_tx(state, event);
554 case TFTP_EVENT_DATA: /* Connected for receive */
555 res = tftp_connect_for_rx(state, event);
558 case TFTP_EVENT_ERROR:
559 state->state = TFTP_STATE_FIN;
563 failf(state->conn->data, "tftp_send_first: internal error");
569 /**********************************************************
573 * Event handler for the RX state
575 **********************************************************/
576 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event)
580 struct SessionHandle *data = state->conn->data;
584 case TFTP_EVENT_DATA:
585 /* Is this the block we expect? */
586 rblock = getrpacketblock(&state->rpacket);
587 if((state->block+1) != rblock) {
588 /* No, log it, up the retry count and fail if over the limit */
590 "Received unexpected DATA packet block %d\n", rblock);
592 if(state->retries>state->retry_max) {
593 failf(data, "tftp_rx: giving up waiting for block %d",
595 return CURLE_TFTP_ILLEGAL;
598 /* This is the expected block. Reset counters and ACK it. */
599 state->block = (unsigned short)rblock;
601 setpacketevent(&state->spacket, TFTP_EVENT_ACK);
602 setpacketblock(&state->spacket, state->block);
603 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
605 (struct sockaddr *)&state->remote_addr,
606 state->remote_addrlen);
608 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
609 return CURLE_SEND_ERROR;
612 /* Check if completed (That is, a less than full packet is received) */
613 if(state->rbytes < (ssize_t)state->blksize+4){
614 state->state = TFTP_STATE_FIN;
617 state->state = TFTP_STATE_RX;
619 time(&state->rx_time);
622 case TFTP_EVENT_OACK:
623 /* ACK option acknowledgement so we can move on to data */
626 setpacketevent(&state->spacket, TFTP_EVENT_ACK);
627 setpacketblock(&state->spacket, state->block);
628 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
630 (struct sockaddr *)&state->remote_addr,
631 state->remote_addrlen);
633 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
634 return CURLE_SEND_ERROR;
637 /* we're ready to RX data */
638 state->state = TFTP_STATE_RX;
639 time(&state->rx_time);
642 case TFTP_EVENT_TIMEOUT:
643 /* Increment the retry count and fail if over the limit */
646 "Timeout waiting for block %d ACK. Retries = %d\n", state->retries);
647 if(state->retries > state->retry_max) {
648 state->error = TFTP_ERR_TIMEOUT;
649 state->state = TFTP_STATE_FIN;
652 /* Resend the previous ACK */
653 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
655 (struct sockaddr *)&state->remote_addr,
656 state->remote_addrlen);
657 /* Check all sbytes were sent */
659 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
660 return CURLE_SEND_ERROR;
665 case TFTP_EVENT_ERROR:
666 setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
667 setpacketblock(&state->spacket, state->block);
668 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
670 (struct sockaddr *)&state->remote_addr,
671 state->remote_addrlen);
672 /* don't bother with the return code, but if the socket is still up we
673 * should be a good TFTP client and let the server know we're done */
674 state->state = TFTP_STATE_FIN;
678 failf(data, "%s", "tftp_rx: internal error");
679 return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for
685 /**********************************************************
689 * Event handler for the TX state
691 **********************************************************/
692 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event)
694 struct SessionHandle *data = state->conn->data;
697 CURLcode res = CURLE_OK;
698 struct SingleRequest *k = &data->req;
704 rblock = getrpacketblock(&state->rpacket);
706 if(rblock != state->block) {
707 /* This isn't the expected block. Log it and up the retry counter */
708 infof(data, "Received ACK for block %d, expecting %d\n",
709 rblock, state->block);
711 /* Bail out if over the maximum */
712 if(state->retries>state->retry_max) {
713 failf(data, "tftp_tx: giving up waiting for block %d ack",
715 res = CURLE_SEND_ERROR;
718 /* Re-send the data packet */
719 sbytes = sendto(state->sockfd, (void *)&state->spacket,
720 4+state->sbytes, SEND_4TH_ARG,
721 (struct sockaddr *)&state->remote_addr,
722 state->remote_addrlen);
723 /* Check all sbytes were sent */
725 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
726 res = CURLE_SEND_ERROR;
731 /* This is the expected packet. Reset the counters and send the next
733 time(&state->rx_time);
736 setpacketevent(&state->spacket, TFTP_EVENT_DATA);
737 setpacketblock(&state->spacket, state->block);
738 if(state->block > 1 && state->sbytes < (int)state->blksize) {
739 state->state = TFTP_STATE_FIN;
742 res = Curl_fillreadbuffer(state->conn, (size_t)state->blksize,
746 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
747 4+state->sbytes, SEND_4TH_ARG,
748 (struct sockaddr *)&state->remote_addr,
749 state->remote_addrlen);
750 /* Check all sbytes were sent */
752 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
753 return CURLE_SEND_ERROR;
755 /* Update the progress meter */
756 k->writebytecount += state->sbytes;
757 Curl_pgrsSetUploadCounter(data, k->writebytecount);
760 case TFTP_EVENT_TIMEOUT:
761 /* Increment the retry counter and log the timeout */
763 infof(data, "Timeout waiting for block %d ACK. "
764 " Retries = %d\n", state->retries);
765 /* Decide if we've had enough */
766 if(state->retries > state->retry_max) {
767 state->error = TFTP_ERR_TIMEOUT;
768 state->state = TFTP_STATE_FIN;
771 /* Re-send the data packet */
772 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
773 4+state->sbytes, SEND_4TH_ARG,
774 (struct sockaddr *)&state->remote_addr,
775 state->remote_addrlen);
776 /* Check all sbytes were sent */
778 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
779 return CURLE_SEND_ERROR;
781 /* since this was a re-send, we remain at the still byte position */
782 Curl_pgrsSetUploadCounter(data, k->writebytecount);
786 case TFTP_EVENT_ERROR:
787 state->state = TFTP_STATE_FIN;
788 setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
789 setpacketblock(&state->spacket, state->block);
790 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
792 (struct sockaddr *)&state->remote_addr,
793 state->remote_addrlen);
794 /* don't bother with the return code, but if the socket is still up we
795 * should be a good TFTP client and let the server know we're done */
796 state->state = TFTP_STATE_FIN;
800 failf(data, "%s", "tftp_tx: internal error");
807 /**********************************************************
809 * tftp_translate_code
811 * Translate internal error codes to CURL error codes
813 **********************************************************/
814 CURLcode tftp_translate_code(tftp_error_t error)
816 CURLcode code = CURLE_OK;
818 if(error != TFTP_ERR_NONE) {
820 case TFTP_ERR_NOTFOUND:
821 code = CURLE_TFTP_NOTFOUND;
824 code = CURLE_TFTP_PERM;
826 case TFTP_ERR_DISKFULL:
827 code = CURLE_REMOTE_DISK_FULL;
830 case TFTP_ERR_ILLEGAL:
831 code = CURLE_TFTP_ILLEGAL;
833 case TFTP_ERR_UNKNOWNID:
834 code = CURLE_TFTP_UNKNOWNID;
836 case TFTP_ERR_EXISTS:
837 code = CURLE_REMOTE_FILE_EXISTS;
839 case TFTP_ERR_NOSUCHUSER:
840 code = CURLE_TFTP_NOSUCHUSER;
842 case TFTP_ERR_TIMEOUT:
843 code = CURLE_OPERATION_TIMEDOUT;
845 case TFTP_ERR_NORESPONSE:
846 code = CURLE_COULDNT_CONNECT;
849 code= CURLE_ABORTED_BY_CALLBACK;
860 /**********************************************************
864 * The tftp state machine event dispatcher
866 **********************************************************/
867 static CURLcode tftp_state_machine(tftp_state_data_t *state,
870 CURLcode res = CURLE_OK;
871 struct SessionHandle *data = state->conn->data;
872 switch(state->state) {
873 case TFTP_STATE_START:
874 DEBUGF(infof(data, "TFTP_STATE_START\n"));
875 res = tftp_send_first(state, event);
878 DEBUGF(infof(data, "TFTP_STATE_RX\n"));
879 res = tftp_rx(state, event);
882 DEBUGF(infof(data, "TFTP_STATE_TX\n"));
883 res = tftp_tx(state, event);
886 infof(data, "%s\n", "TFTP finished");
889 DEBUGF(infof(data, "STATE: %d\n", state->state));
890 failf(data, "%s", "Internal state machine error");
891 res = CURLE_TFTP_ILLEGAL;
897 /**********************************************************
901 * The disconnect callback
903 **********************************************************/
904 static CURLcode tftp_disconnect(struct connectdata *conn)
906 tftp_state_data_t *state = conn->proto.tftpc;
908 /* done, free dynamically allocated pkt buffers */
910 Curl_safefree(state->rpacket.data);
911 Curl_safefree(state->spacket.data);
918 /**********************************************************
922 * The connect callback
924 **********************************************************/
925 static CURLcode tftp_connect(struct connectdata *conn, bool *done)
928 tftp_state_data_t *state;
931 blksize = TFTP_BLKSIZE_DEFAULT;
933 /* If there already is a protocol-specific struct allocated for this
934 sessionhandle, deal with it */
935 Curl_reset_reqproto(conn);
937 state = conn->proto.tftpc = calloc(1, sizeof(tftp_state_data_t));
939 return CURLE_OUT_OF_MEMORY;
941 /* alloc pkt buffers based on specified blksize */
942 if(conn->data->set.tftp_blksize) {
943 blksize = (int)conn->data->set.tftp_blksize;
944 if(blksize > TFTP_BLKSIZE_MAX || blksize < TFTP_BLKSIZE_MIN )
945 return CURLE_TFTP_ILLEGAL;
948 if(!state->rpacket.data) {
949 state->rpacket.data = calloc(1, blksize + 2 + 2);
951 if(!state->rpacket.data)
952 return CURLE_OUT_OF_MEMORY;
955 if(!state->spacket.data) {
956 state->spacket.data = calloc(1, blksize + 2 + 2);
958 if(!state->spacket.data)
959 return CURLE_OUT_OF_MEMORY;
962 conn->bits.close = TRUE; /* we don't keep TFTP connections up bascially
963 because there's none or very little gain for UDP
967 state->sockfd = state->conn->sock[FIRSTSOCKET];
968 state->state = TFTP_STATE_START;
969 state->error = TFTP_ERR_NONE;
970 state->blksize = TFTP_BLKSIZE_DEFAULT;
971 state->requested_blksize = blksize;
973 ((struct sockaddr *)&state->local_addr)->sa_family =
974 (unsigned short)(conn->ip_addr->ai_family);
976 tftp_set_timeouts(state);
978 if(!conn->bits.bound) {
979 /* If not already bound, bind to any interface, random UDP port. If it is
980 * reused or a custom local port was desired, this has already been done!
982 * We once used the size of the local_addr struct as the third argument
983 * for bind() to better work with IPv6 or whatever size the struct could
984 * have, but we learned that at least Tru64, AIX and IRIX *requires* the
985 * size of that argument to match the exact size of a 'sockaddr_in' struct
986 * when running IPv4-only.
988 * Therefore we use the size from the address we connected to, which we
989 * assume uses the same IP version and thus hopefully this works for both
992 rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr,
993 conn->ip_addr->ai_addrlen);
995 failf(conn->data, "bind() failed; %s",
996 Curl_strerror(conn, SOCKERRNO));
997 return CURLE_COULDNT_CONNECT;
999 conn->bits.bound = TRUE;
1002 Curl_pgrsStartNow(conn->data);
1009 /**********************************************************
1015 **********************************************************/
1016 static CURLcode tftp_done(struct connectdata *conn, CURLcode status,
1019 CURLcode code = CURLE_OK;
1020 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1022 (void)status; /* unused */
1023 (void)premature; /* not used */
1025 Curl_pgrsDone(conn);
1027 /* If we have encountered an error */
1028 code = tftp_translate_code(state->error);
1033 /**********************************************************
1037 * The getsock callback
1039 **********************************************************/
1040 static int tftp_getsock(struct connectdata *conn, curl_socket_t *socks,
1044 return GETSOCK_BLANK;
1046 socks[0] = conn->sock[FIRSTSOCKET];
1048 return GETSOCK_READSOCK(0);
1051 /**********************************************************
1053 * tftp_receive_packet
1055 * Called once select fires and data is ready on the socket
1057 **********************************************************/
1058 static CURLcode tftp_receive_packet(struct connectdata *conn)
1060 struct Curl_sockaddr_storage fromaddr;
1061 curl_socklen_t fromlen;
1062 CURLcode result = CURLE_OK;
1063 struct SessionHandle *data = conn->data;
1064 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1065 struct SingleRequest *k = &data->req;
1067 /* Receive the packet */
1068 fromlen = sizeof(fromaddr);
1069 state->rbytes = (int)recvfrom(state->sockfd,
1070 (void *)state->rpacket.data,
1073 (struct sockaddr *)&fromaddr,
1075 if(state->remote_addrlen==0) {
1076 memcpy(&state->remote_addr, &fromaddr, fromlen);
1077 state->remote_addrlen = fromlen;
1080 /* Sanity check packet length */
1081 if(state->rbytes < 4) {
1082 failf(data, "Received too short packet");
1083 /* Not a timeout, but how best to handle it? */
1084 state->event = TFTP_EVENT_TIMEOUT;
1087 /* The event is given by the TFTP packet time */
1088 state->event = (tftp_event_t)getrpacketevent(&state->rpacket);
1090 switch(state->event) {
1091 case TFTP_EVENT_DATA:
1092 /* Don't pass to the client empty or retransmitted packets */
1093 if(state->rbytes > 4 &&
1094 ((state->block+1) == getrpacketblock(&state->rpacket))) {
1095 result = Curl_client_write(conn, CLIENTWRITE_BODY,
1096 (char *)state->rpacket.data+4,
1099 tftp_state_machine(state, TFTP_EVENT_ERROR);
1102 k->bytecount += state->rbytes-4;
1103 Curl_pgrsSetDownloadCounter(data, (curl_off_t) k->bytecount);
1106 case TFTP_EVENT_ERROR:
1107 state->error = (tftp_error_t)getrpacketblock(&state->rpacket);
1108 infof(data, "%s\n", (const char *)state->rpacket.data+4);
1110 case TFTP_EVENT_ACK:
1112 case TFTP_EVENT_OACK:
1113 result = tftp_parse_option_ack(state,
1114 (const char *)state->rpacket.data+2,
1119 case TFTP_EVENT_RRQ:
1120 case TFTP_EVENT_WRQ:
1122 failf(data, "%s", "Internal error: Unexpected packet");
1126 /* Update the progress meter */
1127 if(Curl_pgrsUpdate(conn)) {
1128 tftp_state_machine(state, TFTP_EVENT_ERROR);
1129 return CURLE_ABORTED_BY_CALLBACK;
1135 /**********************************************************
1137 * tftp_state_timeout
1139 * Check if timeouts have been reached
1141 **********************************************************/
1142 static long tftp_state_timeout(struct connectdata *conn, tftp_event_t *event)
1145 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1148 *event = TFTP_EVENT_NONE;
1151 if(current > state->max_time) {
1152 DEBUGF(infof(conn->data, "timeout: %d > %d\n",
1153 current, state->max_time));
1154 state->error = TFTP_ERR_TIMEOUT;
1155 state->state = TFTP_STATE_FIN;
1158 else if (current > state->rx_time+state->retry_time) {
1160 *event = TFTP_EVENT_TIMEOUT;
1161 time(&state->rx_time); /* update even though we received nothing */
1162 return(state->max_time-current);
1165 return(state->max_time-current);
1169 /**********************************************************
1171 * tftp_easy_statemach
1173 * Handle easy request until completion
1175 **********************************************************/
1176 static CURLcode tftp_easy_statemach(struct connectdata *conn)
1180 CURLcode result = CURLE_OK;
1181 struct SessionHandle *data = conn->data;
1182 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1184 /* Run the TFTP State Machine */
1186 (state->state != TFTP_STATE_FIN) && (result == CURLE_OK);
1187 result=tftp_state_machine(state, state->event) ) {
1189 /* Wait until ready to read or timeout occurs */
1190 rc=Curl_socket_ready(state->sockfd, CURL_SOCKET_BAD,
1191 state->retry_time * 1000);
1195 int error = SOCKERRNO;
1196 failf(data, "%s", Curl_strerror(conn, error));
1197 state->event = TFTP_EVENT_ERROR;
1200 /* A timeout occured */
1201 state->event = TFTP_EVENT_TIMEOUT;
1203 /* Force a look at transfer timeouts */
1208 result = tftp_receive_packet(conn);
1211 /* Check for transfer timeout every 10 blocks, or after timeout */
1212 if(check_time%10==0) {
1213 /* ignore the event here as Curl_socket_ready() handles
1214 * retransmission timeouts inside the easy state mach */
1215 tftp_state_timeout(conn, NULL);
1222 /* Tell curl we're done */
1223 result = Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1228 /**********************************************************
1230 * tftp_multi_statemach
1232 * Handle single RX socket event and return
1234 **********************************************************/
1235 static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done)
1239 CURLcode result = CURLE_OK;
1240 struct SessionHandle *data = conn->data;
1241 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1242 long timeout_ms = tftp_state_timeout(conn, &event);
1246 if(timeout_ms <= 0) {
1247 failf(data, "TFTP response timeout");
1248 return CURLE_OPERATION_TIMEDOUT;
1250 else if (event != TFTP_EVENT_NONE) {
1251 result = tftp_state_machine(state, event);
1252 if(result != CURLE_OK)
1254 *done = (bool)(state->state == TFTP_STATE_FIN);
1256 /* Tell curl we're done */
1257 result = Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1260 /* no timeouts to handle, check our socket */
1261 rc = Curl_socket_ready(state->sockfd, CURL_SOCKET_BAD, 0);
1265 int error = SOCKERRNO;
1266 failf(data, "%s", Curl_strerror(conn, error));
1267 state->event = TFTP_EVENT_ERROR;
1270 result = tftp_receive_packet(conn);
1271 if(result != CURLE_OK)
1273 result = tftp_state_machine(state, state->event);
1274 if(result != CURLE_OK)
1276 *done = (bool)(state->state == TFTP_STATE_FIN);
1278 /* Tell curl we're done */
1279 result = Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1281 /* if rc == 0, then select() timed out */
1287 /**********************************************************
1291 * Called from multi.c while DOing
1293 **********************************************************/
1294 static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done)
1297 result = tftp_multi_statemach(conn, dophase_done);
1300 DEBUGF(infof(conn->data, "DO phase is complete\n"));
1305 /**********************************************************
1309 * Entry point for transfer from tftp_do, sarts state mach
1311 **********************************************************/
1312 static CURLcode tftp_perform(struct connectdata *conn, bool *dophase_done)
1314 CURLcode result = CURLE_OK;
1315 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1317 *dophase_done = FALSE;
1319 result = tftp_state_machine(state, TFTP_EVENT_INIT);
1321 if(state->state == TFTP_STATE_FIN || result != CURLE_OK)
1324 if(conn->data->state.used_interface == Curl_if_multi)
1325 tftp_multi_statemach(conn, dophase_done);
1327 result = tftp_easy_statemach(conn);
1328 *dophase_done = TRUE; /* with the easy interface we are done here */
1332 DEBUGF(infof(conn->data, "DO phase is complete\n"));
1338 /**********************************************************
1344 * This callback initiates the TFTP transfer
1346 **********************************************************/
1348 static CURLcode tftp_do(struct connectdata *conn, bool *done)
1350 tftp_state_data_t *state;
1356 Since connections can be re-used between SessionHandles, this might be a
1357 connection already existing but on a fresh SessionHandle struct so we must
1358 make sure we have a good 'struct TFTP' to play with. For new connections,
1359 the struct TFTP is allocated and setup in the tftp_connect() function.
1361 Curl_reset_reqproto(conn);
1363 if(!conn->proto.tftpc) {
1364 code = tftp_connect(conn, done);
1368 state = (tftp_state_data_t *)conn->proto.tftpc;
1370 code = tftp_perform(conn, done);
1372 /* If we have encountered an error */
1373 code = tftp_translate_code(state->error);
1378 static CURLcode tftp_setup_connection(struct connectdata * conn)
1380 struct SessionHandle *data = conn->data;
1384 conn->socktype = SOCK_DGRAM; /* UDP datagram based */
1386 /* TFTP URLs support an extension like ";mode=<typecode>" that
1387 * we'll try to get now! */
1388 type = strstr(data->state.path, ";mode=");
1391 type = strstr(conn->host.rawalloc, ";mode=");
1394 *type = 0; /* it was in the middle of the hostname */
1395 command = Curl_raw_toupper(type[6]);
1398 case 'A': /* ASCII mode */
1399 case 'N': /* NETASCII mode */
1400 data->set.prefer_ascii = TRUE;
1403 case 'O': /* octet mode */
1404 case 'I': /* binary mode */
1406 /* switch off ASCII */
1407 data->set.prefer_ascii = FALSE;