1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2010, 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 static 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 %ld, retry %d maxtry %d\n",
277 (int)state->state, (long)(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 (%ld)",
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 (%ld)\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",
647 state->block+1, state->retries);
648 if(state->retries > state->retry_max) {
649 state->error = TFTP_ERR_TIMEOUT;
650 state->state = TFTP_STATE_FIN;
653 /* Resend the previous ACK */
654 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
656 (struct sockaddr *)&state->remote_addr,
657 state->remote_addrlen);
658 /* Check all sbytes were sent */
660 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
661 return CURLE_SEND_ERROR;
666 case TFTP_EVENT_ERROR:
667 setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
668 setpacketblock(&state->spacket, state->block);
669 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
671 (struct sockaddr *)&state->remote_addr,
672 state->remote_addrlen);
673 /* don't bother with the return code, but if the socket is still up we
674 * should be a good TFTP client and let the server know we're done */
675 state->state = TFTP_STATE_FIN;
679 failf(data, "%s", "tftp_rx: internal error");
680 return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for
686 /**********************************************************
690 * Event handler for the TX state
692 **********************************************************/
693 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event)
695 struct SessionHandle *data = state->conn->data;
698 CURLcode res = CURLE_OK;
699 struct SingleRequest *k = &data->req;
705 rblock = getrpacketblock(&state->rpacket);
707 if(rblock != state->block) {
708 /* This isn't the expected block. Log it and up the retry counter */
709 infof(data, "Received ACK for block %d, expecting %d\n",
710 rblock, state->block);
712 /* Bail out if over the maximum */
713 if(state->retries>state->retry_max) {
714 failf(data, "tftp_tx: giving up waiting for block %d ack",
716 res = CURLE_SEND_ERROR;
719 /* Re-send the data packet */
720 sbytes = sendto(state->sockfd, (void *)&state->spacket,
721 4+state->sbytes, SEND_4TH_ARG,
722 (struct sockaddr *)&state->remote_addr,
723 state->remote_addrlen);
724 /* Check all sbytes were sent */
726 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
727 res = CURLE_SEND_ERROR;
732 /* This is the expected packet. Reset the counters and send the next
734 time(&state->rx_time);
737 setpacketevent(&state->spacket, TFTP_EVENT_DATA);
738 setpacketblock(&state->spacket, state->block);
739 if(state->block > 1 && state->sbytes < (int)state->blksize) {
740 state->state = TFTP_STATE_FIN;
743 res = Curl_fillreadbuffer(state->conn, (size_t)state->blksize,
747 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
748 4+state->sbytes, SEND_4TH_ARG,
749 (struct sockaddr *)&state->remote_addr,
750 state->remote_addrlen);
751 /* Check all sbytes were sent */
753 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
754 return CURLE_SEND_ERROR;
756 /* Update the progress meter */
757 k->writebytecount += state->sbytes;
758 Curl_pgrsSetUploadCounter(data, k->writebytecount);
761 case TFTP_EVENT_TIMEOUT:
762 /* Increment the retry counter and log the timeout */
764 infof(data, "Timeout waiting for block %d ACK. "
765 " Retries = %d\n", state->block+1, state->retries);
766 /* Decide if we've had enough */
767 if(state->retries > state->retry_max) {
768 state->error = TFTP_ERR_TIMEOUT;
769 state->state = TFTP_STATE_FIN;
772 /* Re-send the data packet */
773 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
774 4+state->sbytes, SEND_4TH_ARG,
775 (struct sockaddr *)&state->remote_addr,
776 state->remote_addrlen);
777 /* Check all sbytes were sent */
779 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
780 return CURLE_SEND_ERROR;
782 /* since this was a re-send, we remain at the still byte position */
783 Curl_pgrsSetUploadCounter(data, k->writebytecount);
787 case TFTP_EVENT_ERROR:
788 state->state = TFTP_STATE_FIN;
789 setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
790 setpacketblock(&state->spacket, state->block);
791 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
793 (struct sockaddr *)&state->remote_addr,
794 state->remote_addrlen);
795 /* don't bother with the return code, but if the socket is still up we
796 * should be a good TFTP client and let the server know we're done */
797 state->state = TFTP_STATE_FIN;
801 failf(data, "%s", "tftp_tx: internal error");
808 /**********************************************************
810 * tftp_translate_code
812 * Translate internal error codes to CURL error codes
814 **********************************************************/
815 static CURLcode tftp_translate_code(tftp_error_t error)
817 CURLcode code = CURLE_OK;
819 if(error != TFTP_ERR_NONE) {
821 case TFTP_ERR_NOTFOUND:
822 code = CURLE_TFTP_NOTFOUND;
825 code = CURLE_TFTP_PERM;
827 case TFTP_ERR_DISKFULL:
828 code = CURLE_REMOTE_DISK_FULL;
831 case TFTP_ERR_ILLEGAL:
832 code = CURLE_TFTP_ILLEGAL;
834 case TFTP_ERR_UNKNOWNID:
835 code = CURLE_TFTP_UNKNOWNID;
837 case TFTP_ERR_EXISTS:
838 code = CURLE_REMOTE_FILE_EXISTS;
840 case TFTP_ERR_NOSUCHUSER:
841 code = CURLE_TFTP_NOSUCHUSER;
843 case TFTP_ERR_TIMEOUT:
844 code = CURLE_OPERATION_TIMEDOUT;
846 case TFTP_ERR_NORESPONSE:
847 code = CURLE_COULDNT_CONNECT;
850 code= CURLE_ABORTED_BY_CALLBACK;
861 /**********************************************************
865 * The tftp state machine event dispatcher
867 **********************************************************/
868 static CURLcode tftp_state_machine(tftp_state_data_t *state,
871 CURLcode res = CURLE_OK;
872 struct SessionHandle *data = state->conn->data;
873 switch(state->state) {
874 case TFTP_STATE_START:
875 DEBUGF(infof(data, "TFTP_STATE_START\n"));
876 res = tftp_send_first(state, event);
879 DEBUGF(infof(data, "TFTP_STATE_RX\n"));
880 res = tftp_rx(state, event);
883 DEBUGF(infof(data, "TFTP_STATE_TX\n"));
884 res = tftp_tx(state, event);
887 infof(data, "%s\n", "TFTP finished");
890 DEBUGF(infof(data, "STATE: %d\n", state->state));
891 failf(data, "%s", "Internal state machine error");
892 res = CURLE_TFTP_ILLEGAL;
898 /**********************************************************
902 * The disconnect callback
904 **********************************************************/
905 static CURLcode tftp_disconnect(struct connectdata *conn)
907 tftp_state_data_t *state = conn->proto.tftpc;
909 /* done, free dynamically allocated pkt buffers */
911 Curl_safefree(state->rpacket.data);
912 Curl_safefree(state->spacket.data);
919 /**********************************************************
923 * The connect callback
925 **********************************************************/
926 static CURLcode tftp_connect(struct connectdata *conn, bool *done)
929 tftp_state_data_t *state;
932 blksize = TFTP_BLKSIZE_DEFAULT;
934 /* If there already is a protocol-specific struct allocated for this
935 sessionhandle, deal with it */
936 Curl_reset_reqproto(conn);
938 state = conn->proto.tftpc = calloc(1, sizeof(tftp_state_data_t));
940 return CURLE_OUT_OF_MEMORY;
942 /* alloc pkt buffers based on specified blksize */
943 if(conn->data->set.tftp_blksize) {
944 blksize = (int)conn->data->set.tftp_blksize;
945 if(blksize > TFTP_BLKSIZE_MAX || blksize < TFTP_BLKSIZE_MIN )
946 return CURLE_TFTP_ILLEGAL;
949 if(!state->rpacket.data) {
950 state->rpacket.data = calloc(1, blksize + 2 + 2);
952 if(!state->rpacket.data)
953 return CURLE_OUT_OF_MEMORY;
956 if(!state->spacket.data) {
957 state->spacket.data = calloc(1, blksize + 2 + 2);
959 if(!state->spacket.data)
960 return CURLE_OUT_OF_MEMORY;
963 conn->bits.close = TRUE; /* we don't keep TFTP connections up bascially
964 because there's none or very little gain for UDP
968 state->sockfd = state->conn->sock[FIRSTSOCKET];
969 state->state = TFTP_STATE_START;
970 state->error = TFTP_ERR_NONE;
971 state->blksize = TFTP_BLKSIZE_DEFAULT;
972 state->requested_blksize = blksize;
974 ((struct sockaddr *)&state->local_addr)->sa_family =
975 (unsigned short)(conn->ip_addr->ai_family);
977 tftp_set_timeouts(state);
979 if(!conn->bits.bound) {
980 /* If not already bound, bind to any interface, random UDP port. If it is
981 * reused or a custom local port was desired, this has already been done!
983 * We once used the size of the local_addr struct as the third argument
984 * for bind() to better work with IPv6 or whatever size the struct could
985 * have, but we learned that at least Tru64, AIX and IRIX *requires* the
986 * size of that argument to match the exact size of a 'sockaddr_in' struct
987 * when running IPv4-only.
989 * Therefore we use the size from the address we connected to, which we
990 * assume uses the same IP version and thus hopefully this works for both
993 rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr,
994 conn->ip_addr->ai_addrlen);
996 failf(conn->data, "bind() failed; %s",
997 Curl_strerror(conn, SOCKERRNO));
998 return CURLE_COULDNT_CONNECT;
1000 conn->bits.bound = TRUE;
1003 Curl_pgrsStartNow(conn->data);
1010 /**********************************************************
1016 **********************************************************/
1017 static CURLcode tftp_done(struct connectdata *conn, CURLcode status,
1020 CURLcode code = CURLE_OK;
1021 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1023 (void)status; /* unused */
1024 (void)premature; /* not used */
1026 Curl_pgrsDone(conn);
1028 /* If we have encountered an error */
1029 code = tftp_translate_code(state->error);
1034 /**********************************************************
1038 * The getsock callback
1040 **********************************************************/
1041 static int tftp_getsock(struct connectdata *conn, curl_socket_t *socks,
1045 return GETSOCK_BLANK;
1047 socks[0] = conn->sock[FIRSTSOCKET];
1049 return GETSOCK_READSOCK(0);
1052 /**********************************************************
1054 * tftp_receive_packet
1056 * Called once select fires and data is ready on the socket
1058 **********************************************************/
1059 static CURLcode tftp_receive_packet(struct connectdata *conn)
1061 struct Curl_sockaddr_storage fromaddr;
1062 curl_socklen_t fromlen;
1063 CURLcode result = CURLE_OK;
1064 struct SessionHandle *data = conn->data;
1065 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1066 struct SingleRequest *k = &data->req;
1068 /* Receive the packet */
1069 fromlen = sizeof(fromaddr);
1070 state->rbytes = (int)recvfrom(state->sockfd,
1071 (void *)state->rpacket.data,
1074 (struct sockaddr *)&fromaddr,
1076 if(state->remote_addrlen==0) {
1077 memcpy(&state->remote_addr, &fromaddr, fromlen);
1078 state->remote_addrlen = fromlen;
1081 /* Sanity check packet length */
1082 if(state->rbytes < 4) {
1083 failf(data, "Received too short packet");
1084 /* Not a timeout, but how best to handle it? */
1085 state->event = TFTP_EVENT_TIMEOUT;
1088 /* The event is given by the TFTP packet time */
1089 state->event = (tftp_event_t)getrpacketevent(&state->rpacket);
1091 switch(state->event) {
1092 case TFTP_EVENT_DATA:
1093 /* Don't pass to the client empty or retransmitted packets */
1094 if(state->rbytes > 4 &&
1095 ((state->block+1) == getrpacketblock(&state->rpacket))) {
1096 result = Curl_client_write(conn, CLIENTWRITE_BODY,
1097 (char *)state->rpacket.data+4,
1100 tftp_state_machine(state, TFTP_EVENT_ERROR);
1103 k->bytecount += state->rbytes-4;
1104 Curl_pgrsSetDownloadCounter(data, (curl_off_t) k->bytecount);
1107 case TFTP_EVENT_ERROR:
1108 state->error = (tftp_error_t)getrpacketblock(&state->rpacket);
1109 infof(data, "%s\n", (const char *)state->rpacket.data+4);
1111 case TFTP_EVENT_ACK:
1113 case TFTP_EVENT_OACK:
1114 result = tftp_parse_option_ack(state,
1115 (const char *)state->rpacket.data+2,
1120 case TFTP_EVENT_RRQ:
1121 case TFTP_EVENT_WRQ:
1123 failf(data, "%s", "Internal error: Unexpected packet");
1127 /* Update the progress meter */
1128 if(Curl_pgrsUpdate(conn)) {
1129 tftp_state_machine(state, TFTP_EVENT_ERROR);
1130 return CURLE_ABORTED_BY_CALLBACK;
1136 /**********************************************************
1138 * tftp_state_timeout
1140 * Check if timeouts have been reached
1142 **********************************************************/
1143 static long tftp_state_timeout(struct connectdata *conn, tftp_event_t *event)
1146 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1149 *event = TFTP_EVENT_NONE;
1152 if(current > state->max_time) {
1153 DEBUGF(infof(conn->data, "timeout: %ld > %ld\n",
1154 (long)current, (long)state->max_time));
1155 state->error = TFTP_ERR_TIMEOUT;
1156 state->state = TFTP_STATE_FIN;
1159 else if (current > state->rx_time+state->retry_time) {
1161 *event = TFTP_EVENT_TIMEOUT;
1162 time(&state->rx_time); /* update even though we received nothing */
1163 return(state->max_time-current);
1166 return(state->max_time-current);
1170 /**********************************************************
1172 * tftp_easy_statemach
1174 * Handle easy request until completion
1176 **********************************************************/
1177 static CURLcode tftp_easy_statemach(struct connectdata *conn)
1181 CURLcode result = CURLE_OK;
1182 struct SessionHandle *data = conn->data;
1183 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1185 /* Run the TFTP State Machine */
1187 (state->state != TFTP_STATE_FIN) && (result == CURLE_OK);
1188 result=tftp_state_machine(state, state->event) ) {
1190 /* Wait until ready to read or timeout occurs */
1191 rc=Curl_socket_ready(state->sockfd, CURL_SOCKET_BAD,
1192 state->retry_time * 1000);
1196 int error = SOCKERRNO;
1197 failf(data, "%s", Curl_strerror(conn, error));
1198 state->event = TFTP_EVENT_ERROR;
1201 /* A timeout occured */
1202 state->event = TFTP_EVENT_TIMEOUT;
1204 /* Force a look at transfer timeouts */
1209 result = tftp_receive_packet(conn);
1212 /* Check for transfer timeout every 10 blocks, or after timeout */
1213 if(check_time%10==0) {
1214 /* ignore the event here as Curl_socket_ready() handles
1215 * retransmission timeouts inside the easy state mach */
1216 tftp_state_timeout(conn, NULL);
1223 /* Tell curl we're done */
1224 result = Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1229 /**********************************************************
1231 * tftp_multi_statemach
1233 * Handle single RX socket event and return
1235 **********************************************************/
1236 static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done)
1240 CURLcode result = CURLE_OK;
1241 struct SessionHandle *data = conn->data;
1242 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1243 long timeout_ms = tftp_state_timeout(conn, &event);
1247 if(timeout_ms <= 0) {
1248 failf(data, "TFTP response timeout");
1249 return CURLE_OPERATION_TIMEDOUT;
1251 else if (event != TFTP_EVENT_NONE) {
1252 result = tftp_state_machine(state, event);
1253 if(result != CURLE_OK)
1255 *done = (bool)(state->state == TFTP_STATE_FIN);
1257 /* Tell curl we're done */
1258 result = Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1261 /* no timeouts to handle, check our socket */
1262 rc = Curl_socket_ready(state->sockfd, CURL_SOCKET_BAD, 0);
1266 int error = SOCKERRNO;
1267 failf(data, "%s", Curl_strerror(conn, error));
1268 state->event = TFTP_EVENT_ERROR;
1271 result = tftp_receive_packet(conn);
1272 if(result != CURLE_OK)
1274 result = tftp_state_machine(state, state->event);
1275 if(result != CURLE_OK)
1277 *done = (bool)(state->state == TFTP_STATE_FIN);
1279 /* Tell curl we're done */
1280 result = Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1282 /* if rc == 0, then select() timed out */
1288 /**********************************************************
1292 * Called from multi.c while DOing
1294 **********************************************************/
1295 static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done)
1298 result = tftp_multi_statemach(conn, dophase_done);
1301 DEBUGF(infof(conn->data, "DO phase is complete\n"));
1306 /**********************************************************
1310 * Entry point for transfer from tftp_do, sarts state mach
1312 **********************************************************/
1313 static CURLcode tftp_perform(struct connectdata *conn, bool *dophase_done)
1315 CURLcode result = CURLE_OK;
1316 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1318 *dophase_done = FALSE;
1320 result = tftp_state_machine(state, TFTP_EVENT_INIT);
1322 if(state->state == TFTP_STATE_FIN || result != CURLE_OK)
1325 if(conn->data->state.used_interface == Curl_if_multi)
1326 tftp_multi_statemach(conn, dophase_done);
1328 result = tftp_easy_statemach(conn);
1329 *dophase_done = TRUE; /* with the easy interface we are done here */
1333 DEBUGF(infof(conn->data, "DO phase is complete\n"));
1339 /**********************************************************
1345 * This callback initiates the TFTP transfer
1347 **********************************************************/
1349 static CURLcode tftp_do(struct connectdata *conn, bool *done)
1351 tftp_state_data_t *state;
1357 Since connections can be re-used between SessionHandles, this might be a
1358 connection already existing but on a fresh SessionHandle struct so we must
1359 make sure we have a good 'struct TFTP' to play with. For new connections,
1360 the struct TFTP is allocated and setup in the tftp_connect() function.
1362 Curl_reset_reqproto(conn);
1364 if(!conn->proto.tftpc) {
1365 code = tftp_connect(conn, done);
1369 state = (tftp_state_data_t *)conn->proto.tftpc;
1371 code = tftp_perform(conn, done);
1373 /* If we have encountered an error */
1374 code = tftp_translate_code(state->error);
1379 static CURLcode tftp_setup_connection(struct connectdata * conn)
1381 struct SessionHandle *data = conn->data;
1385 conn->socktype = SOCK_DGRAM; /* UDP datagram based */
1387 /* TFTP URLs support an extension like ";mode=<typecode>" that
1388 * we'll try to get now! */
1389 type = strstr(data->state.path, ";mode=");
1392 type = strstr(conn->host.rawalloc, ";mode=");
1395 *type = 0; /* it was in the middle of the hostname */
1396 command = Curl_raw_toupper(type[6]);
1399 case 'A': /* ASCII mode */
1400 case 'N': /* NETASCII mode */
1401 data->set.prefer_ascii = TRUE;
1404 case 'O': /* octet mode */
1405 case 'I': /* binary mode */
1407 /* switch off ASCII */
1408 data->set.prefer_ascii = FALSE;