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.
21 ***************************************************************************/
25 #ifndef CURL_DISABLE_TFTP
26 /* -- WIN32 approved -- */
36 #ifdef HAVE_SYS_SOCKET_H
37 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #ifdef HAVE_SYS_TIME_H
47 #ifdef HAVE_ARPA_INET_H
48 #include <arpa/inet.h>
53 #ifdef HAVE_SYS_IOCTL_H
54 #include <sys/ioctl.h>
57 #ifdef HAVE_SYS_PARAM_H
58 #include <sys/param.h>
64 #include <curl/curl.h>
71 #include "sockaddr.h" /* required for Curl_sockaddr_storage */
76 #define _MPRINTF_REPLACE /* use our functions only */
77 #include <curl/mprintf.h>
79 #include "curl_memory.h"
82 /* The last #include file should be: */
85 /* RFC2348 allows the block size to be negotiated */
86 #define TFTP_BLKSIZE_DEFAULT 512
87 #define TFTP_BLKSIZE_MIN 8
88 #define TFTP_BLKSIZE_MAX 65464
89 #define TFTP_OPTION_BLKSIZE "blksize"
92 #define TFTP_OPTION_TSIZE "tsize"
93 #define TFTP_OPTION_INTERVAL "timeout"
108 TFTP_EVENT_NONE = -1,
114 TFTP_EVENT_ERROR = 5,
127 TFTP_ERR_NOSUCHUSER, /* This will never be triggered by this code */
129 /* The remaining error codes are internal to curl */
130 TFTP_ERR_NONE = -100,
135 typedef struct tftp_packet {
139 typedef struct tftp_state_data {
144 struct connectdata *conn;
145 curl_socket_t sockfd;
152 unsigned short block;
153 struct Curl_sockaddr_storage local_addr;
154 struct Curl_sockaddr_storage remote_addr;
155 curl_socklen_t remote_addrlen;
159 int requested_blksize;
160 tftp_packet_t rpacket;
161 tftp_packet_t spacket;
165 /* Forward declarations */
166 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event) ;
167 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event) ;
168 static CURLcode tftp_connect(struct connectdata *conn, bool *done);
169 static CURLcode tftp_disconnect(struct connectdata *conn);
170 static CURLcode tftp_do(struct connectdata *conn, bool *done);
171 static CURLcode tftp_done(struct connectdata *conn,
172 CURLcode, bool premature);
173 static CURLcode tftp_setup_connection(struct connectdata * conn);
174 static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done);
175 static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done);
176 static int tftp_getsock(struct connectdata *conn, curl_socket_t *socks,
178 static CURLcode tftp_translate_code(tftp_error_t error);
182 * TFTP protocol handler.
185 const struct Curl_handler Curl_handler_tftp = {
187 tftp_setup_connection, /* setup_connection */
189 tftp_done, /* done */
190 ZERO_NULL, /* do_more */
191 tftp_connect, /* connect_it */
192 tftp_multi_statemach, /* connecting */
193 tftp_doing, /* doing */
194 tftp_getsock, /* proto_getsock */
195 tftp_getsock, /* doing_getsock */
196 ZERO_NULL, /* perform_getsock */
197 tftp_disconnect, /* disconnect */
198 PORT_TFTP, /* defport */
199 PROT_TFTP /* protocol */
202 /**********************************************************
204 * tftp_set_timeouts -
206 * Set timeouts based on state machine state.
207 * Use user provided connect timeouts until DATA or ACK
208 * packet is received, then use user-provided transfer timeouts
211 **********************************************************/
212 static CURLcode tftp_set_timeouts(tftp_state_data_t *state)
214 time_t maxtime, timeout;
216 bool start = (bool)(state->state == TFTP_STATE_START);
218 time(&state->start_time);
220 /* Compute drop-dead time */
221 timeout_ms = Curl_timeleft(state->conn, NULL, start);
224 /* time-out, bail out, go home */
225 failf(state->conn->data, "Connection time-out");
226 return CURLE_OPERATION_TIMEDOUT;
231 maxtime = (time_t)(timeout_ms + 500) / 1000;
232 state->max_time = state->start_time+maxtime;
234 /* Set per-block timeout to total */
237 /* Average restart after 5 seconds */
238 state->retry_max = (int)timeout/5;
240 if(state->retry_max < 1)
241 /* avoid division by zero below */
242 state->retry_max = 1;
244 /* Compute the re-start interval to suit the timeout */
245 state->retry_time = (int)timeout/state->retry_max;
246 if(state->retry_time<1)
252 maxtime = (time_t)(timeout_ms + 500) / 1000;
256 state->max_time = state->start_time+maxtime;
258 /* Set per-block timeout to 10% of total */
259 timeout = maxtime/10 ;
261 /* Average reposting an ACK after 15 seconds */
262 state->retry_max = (int)timeout/15;
264 /* But bound the total number */
265 if(state->retry_max<3)
268 if(state->retry_max>50)
271 /* Compute the re-ACK interval to suit the timeout */
272 state->retry_time = (int)(timeout/state->retry_max);
273 if(state->retry_time<1)
276 infof(state->conn->data,
277 "set timeouts for state %d; Total %ld, retry %d maxtry %d\n",
278 (int)state->state, (long)(state->max_time-state->start_time),
279 state->retry_time, state->retry_max);
282 time(&state->rx_time);
287 /**********************************************************
289 * tftp_set_send_first
291 * Event handler for the START state
293 **********************************************************/
295 static void setpacketevent(tftp_packet_t *packet, unsigned short num)
297 packet->data[0] = (unsigned char)(num >> 8);
298 packet->data[1] = (unsigned char)(num & 0xff);
302 static void setpacketblock(tftp_packet_t *packet, unsigned short num)
304 packet->data[2] = (unsigned char)(num >> 8);
305 packet->data[3] = (unsigned char)(num & 0xff);
308 static unsigned short getrpacketevent(const tftp_packet_t *packet)
310 return (unsigned short)((packet->data[0] << 8) | packet->data[1]);
313 static unsigned short getrpacketblock(const tftp_packet_t *packet)
315 return (unsigned short)((packet->data[2] << 8) | packet->data[3]);
318 static size_t Curl_strnlen(const char *string, size_t maxlen)
320 const char *end = memchr (string, '\0', maxlen);
321 return end ? (size_t) (end - string) : maxlen;
324 static const char *tftp_option_get(const char *buf, size_t len,
325 const char **option, const char **value)
329 loc = Curl_strnlen( buf, len );
330 loc++; /* NULL term */
336 loc += Curl_strnlen( buf+loc, len-loc );
337 loc++; /* NULL term */
341 *value = &buf[strlen(*option) + 1];
346 static CURLcode tftp_parse_option_ack(tftp_state_data_t *state,
347 const char *ptr, int len)
349 const char *tmp = ptr;
350 struct SessionHandle *data = state->conn->data;
352 /* if OACK doesn't contain blksize option, the default (512) must be used */
353 state->blksize = TFTP_BLKSIZE_DEFAULT;
355 while (tmp < ptr + len) {
356 const char *option, *value;
358 tmp = tftp_option_get(tmp, ptr + len - tmp, &option, &value);
360 failf(data, "Malformed ACK packet, rejecting");
361 return CURLE_TFTP_ILLEGAL;
364 infof(data, "got option=(%s) value=(%s)\n", option, value);
366 if(checkprefix(option, TFTP_OPTION_BLKSIZE)) {
369 blksize = strtol( value, NULL, 10 );
372 failf(data, "invalid blocksize value in OACK packet");
373 return CURLE_TFTP_ILLEGAL;
375 else if(blksize > TFTP_BLKSIZE_MAX) {
376 failf(data, "%s (%d)", "blksize is larger than max supported",
378 return CURLE_TFTP_ILLEGAL;
380 else if(blksize < TFTP_BLKSIZE_MIN) {
381 failf(data, "%s (%d)", "blksize is smaller than min supported",
383 return CURLE_TFTP_ILLEGAL;
385 else if (blksize > state->requested_blksize) {
386 /* could realloc pkt buffers here, but the spec doesn't call out
387 * support for the server requesting a bigger blksize than the client
389 failf(data, "%s (%ld)",
390 "server requested blksize larger than allocated", blksize);
391 return CURLE_TFTP_ILLEGAL;
394 state->blksize = (int)blksize;
395 infof(data, "%s (%d) %s (%d)\n", "blksize parsed from OACK",
396 state->blksize, "requested", state->requested_blksize);
398 else if(checkprefix(option, TFTP_OPTION_TSIZE)) {
401 tsize = strtol( value, NULL, 10 );
402 infof(data, "%s (%ld)\n", "tsize parsed from OACK", tsize);
404 /* tsize should be ignored on upload: Who cares about the size of the
406 if (!data->set.upload) {
408 failf(data, "invalid tsize -:%s:- value in OACK packet", value);
409 return CURLE_TFTP_ILLEGAL;
411 Curl_pgrsSetDownloadSize(data, tsize);
419 static size_t tftp_option_add(tftp_state_data_t *state, size_t csize,
420 char *buf, const char *option)
422 if( ( strlen(option) + csize + 1 ) > (size_t)state->blksize )
425 return( strlen(option) + 1 );
428 static CURLcode tftp_connect_for_tx(tftp_state_data_t *state,
432 #ifndef CURL_DISABLE_VERBOSE_STRINGS
433 struct SessionHandle *data = state->conn->data;
435 infof(data, "%s\n", "Connected for transmit");
437 state->state = TFTP_STATE_TX;
438 res = tftp_set_timeouts(state);
441 return tftp_tx(state, event);
444 static CURLcode tftp_connect_for_rx(tftp_state_data_t *state,
448 #ifndef CURL_DISABLE_VERBOSE_STRINGS
449 struct SessionHandle *data = state->conn->data;
451 infof(data, "%s\n", "Connected for receive");
453 state->state = TFTP_STATE_RX;
454 res = tftp_set_timeouts(state);
457 return tftp_rx(state, event);
460 static CURLcode tftp_send_first(tftp_state_data_t *state, tftp_event_t event)
464 const char *mode = "octet";
467 struct SessionHandle *data = state->conn->data;
468 CURLcode res = CURLE_OK;
470 /* Set ascii mode if -B flag was used */
471 if(data->set.prefer_ascii)
476 case TFTP_EVENT_INIT: /* Send the first packet out */
477 case TFTP_EVENT_TIMEOUT: /* Resend the first packet out */
478 /* Increment the retry counter, quit if over the limit */
480 if(state->retries>state->retry_max) {
481 state->error = TFTP_ERR_NORESPONSE;
482 state->state = TFTP_STATE_FIN;
486 if(data->set.upload) {
487 /* If we are uploading, send an WRQ */
488 setpacketevent(&state->spacket, TFTP_EVENT_WRQ);
489 state->conn->data->req.upload_fromhere =
490 (char *)state->spacket.data+4;
491 if(data->set.infilesize != -1)
492 Curl_pgrsSetUploadSize(data, data->set.infilesize);
495 /* If we are downloading, send an RRQ */
496 setpacketevent(&state->spacket, TFTP_EVENT_RRQ);
498 /* As RFC3617 describes the separator slash is not actually part of the
499 file name so we skip the always-present first letter of the path
501 filename = curl_easy_unescape(data, &state->conn->data->state.path[1], 0,
504 return CURLE_OUT_OF_MEMORY;
506 snprintf((char *)state->spacket.data+2,
508 "%s%c%s%c", filename, '\0', mode, '\0');
509 sbytes = 4 + strlen(filename) + strlen(mode);
511 /* add tsize option */
512 if(data->set.upload && (data->set.infilesize != -1))
513 snprintf( buf, sizeof(buf), "%" FORMAT_OFF_T, data->set.infilesize );
515 strcpy(buf, "0"); /* the destination is large enough */
517 sbytes += tftp_option_add(state, sbytes,
518 (char *)state->spacket.data+sbytes,
520 sbytes += tftp_option_add(state, sbytes,
521 (char *)state->spacket.data+sbytes, buf);
522 /* add blksize option */
523 snprintf( buf, sizeof(buf), "%d", state->requested_blksize );
524 sbytes += tftp_option_add(state, sbytes,
525 (char *)state->spacket.data+sbytes,
526 TFTP_OPTION_BLKSIZE);
527 sbytes += tftp_option_add(state, sbytes,
528 (char *)state->spacket.data+sbytes, buf );
529 /* add timeout option, this is the max time the session may live */
530 snprintf( buf, sizeof(buf), "%d", state->retry_time*state->retry_max );
531 sbytes += tftp_option_add(state, sbytes,
532 (char *)state->spacket.data+sbytes,
533 TFTP_OPTION_INTERVAL);
534 sbytes += tftp_option_add(state, sbytes,
535 (char *)state->spacket.data+sbytes, buf );
537 senddata = sendto(state->sockfd, (void *)state->spacket.data,
539 state->conn->ip_addr->ai_addr,
540 state->conn->ip_addr->ai_addrlen);
541 if(senddata != (ssize_t)sbytes) {
542 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
544 Curl_safefree(filename);
547 case TFTP_EVENT_OACK:
548 if(data->set.upload) {
549 res = tftp_connect_for_tx(state, event);
552 res = tftp_connect_for_rx(state, event);
556 case TFTP_EVENT_ACK: /* Connected for transmit */
557 res = tftp_connect_for_tx(state, event);
560 case TFTP_EVENT_DATA: /* Connected for receive */
561 res = tftp_connect_for_rx(state, event);
564 case TFTP_EVENT_ERROR:
565 state->state = TFTP_STATE_FIN;
569 failf(state->conn->data, "tftp_send_first: internal error");
575 /* the next blocknum is x + 1 but it needs to wrap at an unsigned 16bit
577 #define NEXT_BLOCKNUM(x) (((x)+1)&0xffff)
579 /**********************************************************
583 * Event handler for the RX state
585 **********************************************************/
586 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event)
590 struct SessionHandle *data = state->conn->data;
594 case TFTP_EVENT_DATA:
595 /* Is this the block we expect? */
596 rblock = getrpacketblock(&state->rpacket);
597 if(NEXT_BLOCKNUM(state->block) != rblock) {
598 /* No, log it, up the retry count and fail if over the limit */
600 "Received unexpected DATA packet block %d\n", rblock);
602 if(state->retries > state->retry_max) {
603 failf(data, "tftp_rx: giving up waiting for block %d",
604 NEXT_BLOCKNUM(state->block));
605 return CURLE_TFTP_ILLEGAL;
609 /* This is the expected block. Reset counters and ACK it. */
610 state->block = (unsigned short)rblock;
612 setpacketevent(&state->spacket, TFTP_EVENT_ACK);
613 setpacketblock(&state->spacket, state->block);
614 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
616 (struct sockaddr *)&state->remote_addr,
617 state->remote_addrlen);
619 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
620 return CURLE_SEND_ERROR;
623 /* Check if completed (That is, a less than full packet is received) */
624 if(state->rbytes < (ssize_t)state->blksize+4){
625 state->state = TFTP_STATE_FIN;
628 state->state = TFTP_STATE_RX;
630 time(&state->rx_time);
633 case TFTP_EVENT_OACK:
634 /* ACK option acknowledgement so we can move on to data */
637 setpacketevent(&state->spacket, TFTP_EVENT_ACK);
638 setpacketblock(&state->spacket, state->block);
639 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
641 (struct sockaddr *)&state->remote_addr,
642 state->remote_addrlen);
644 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
645 return CURLE_SEND_ERROR;
648 /* we're ready to RX data */
649 state->state = TFTP_STATE_RX;
650 time(&state->rx_time);
653 case TFTP_EVENT_TIMEOUT:
654 /* Increment the retry count and fail if over the limit */
657 "Timeout waiting for block %d ACK. Retries = %d\n",
658 NEXT_BLOCKNUM(state->block), state->retries);
659 if(state->retries > state->retry_max) {
660 state->error = TFTP_ERR_TIMEOUT;
661 state->state = TFTP_STATE_FIN;
664 /* Resend the previous ACK */
665 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
667 (struct sockaddr *)&state->remote_addr,
668 state->remote_addrlen);
670 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
671 return CURLE_SEND_ERROR;
676 case TFTP_EVENT_ERROR:
677 setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
678 setpacketblock(&state->spacket, state->block);
679 (void)sendto(state->sockfd, (void *)state->spacket.data,
681 (struct sockaddr *)&state->remote_addr,
682 state->remote_addrlen);
683 /* don't bother with the return code, but if the socket is still up we
684 * should be a good TFTP client and let the server know we're done */
685 state->state = TFTP_STATE_FIN;
689 failf(data, "%s", "tftp_rx: internal error");
690 return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for
696 /**********************************************************
700 * Event handler for the TX state
702 **********************************************************/
703 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event)
705 struct SessionHandle *data = state->conn->data;
708 CURLcode res = CURLE_OK;
709 struct SingleRequest *k = &data->req;
714 case TFTP_EVENT_OACK:
715 if (event == TFTP_EVENT_ACK) {
717 rblock = getrpacketblock(&state->rpacket);
719 if(rblock != state->block) {
720 /* This isn't the expected block. Log it and up the retry counter */
721 infof(data, "Received ACK for block %d, expecting %d\n",
722 rblock, state->block);
724 /* Bail out if over the maximum */
725 if(state->retries>state->retry_max) {
726 failf(data, "tftp_tx: giving up waiting for block %d ack",
728 res = CURLE_SEND_ERROR;
731 /* Re-send the data packet */
732 sbytes = sendto(state->sockfd, (void *)&state->spacket,
733 4+state->sbytes, SEND_4TH_ARG,
734 (struct sockaddr *)&state->remote_addr,
735 state->remote_addrlen);
736 /* Check all sbytes were sent */
738 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
739 res = CURLE_SEND_ERROR;
744 /* This is the expected packet. Reset the counters and send the next
746 time(&state->rx_time);
750 state->block = 1; /* first data block is 1 when using OACK */
753 setpacketevent(&state->spacket, TFTP_EVENT_DATA);
754 setpacketblock(&state->spacket, state->block);
755 if(state->block > 1 && state->sbytes < (int)state->blksize) {
756 state->state = TFTP_STATE_FIN;
759 res = Curl_fillreadbuffer(state->conn, (size_t)state->blksize,
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)
922 tftp_state_data_t *state = conn->proto.tftpc;
924 /* done, free dynamically allocated pkt buffers */
926 Curl_safefree(state->rpacket.data);
927 Curl_safefree(state->spacket.data);
934 /**********************************************************
938 * The connect callback
940 **********************************************************/
941 static CURLcode tftp_connect(struct connectdata *conn, bool *done)
944 tftp_state_data_t *state;
947 blksize = TFTP_BLKSIZE_DEFAULT;
949 /* If there already is a protocol-specific struct allocated for this
950 sessionhandle, deal with it */
951 Curl_reset_reqproto(conn);
953 state = conn->proto.tftpc = calloc(1, sizeof(tftp_state_data_t));
955 return CURLE_OUT_OF_MEMORY;
957 /* alloc pkt buffers based on specified blksize */
958 if(conn->data->set.tftp_blksize) {
959 blksize = (int)conn->data->set.tftp_blksize;
960 if(blksize > TFTP_BLKSIZE_MAX || blksize < TFTP_BLKSIZE_MIN )
961 return CURLE_TFTP_ILLEGAL;
964 if(!state->rpacket.data) {
965 state->rpacket.data = calloc(1, blksize + 2 + 2);
967 if(!state->rpacket.data)
968 return CURLE_OUT_OF_MEMORY;
971 if(!state->spacket.data) {
972 state->spacket.data = calloc(1, blksize + 2 + 2);
974 if(!state->spacket.data)
975 return CURLE_OUT_OF_MEMORY;
978 conn->bits.close = TRUE; /* we don't keep TFTP connections up bascially
979 because there's none or very little gain for UDP
983 state->sockfd = state->conn->sock[FIRSTSOCKET];
984 state->state = TFTP_STATE_START;
985 state->error = TFTP_ERR_NONE;
986 state->blksize = TFTP_BLKSIZE_DEFAULT;
987 state->requested_blksize = blksize;
989 ((struct sockaddr *)&state->local_addr)->sa_family =
990 (unsigned short)(conn->ip_addr->ai_family);
992 tftp_set_timeouts(state);
994 if(!conn->bits.bound) {
995 /* If not already bound, bind to any interface, random UDP port. If it is
996 * reused or a custom local port was desired, this has already been done!
998 * We once used the size of the local_addr struct as the third argument
999 * for bind() to better work with IPv6 or whatever size the struct could
1000 * have, but we learned that at least Tru64, AIX and IRIX *requires* the
1001 * size of that argument to match the exact size of a 'sockaddr_in' struct
1002 * when running IPv4-only.
1004 * Therefore we use the size from the address we connected to, which we
1005 * assume uses the same IP version and thus hopefully this works for both
1008 rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr,
1009 conn->ip_addr->ai_addrlen);
1011 failf(conn->data, "bind() failed; %s",
1012 Curl_strerror(conn, SOCKERRNO));
1013 return CURLE_COULDNT_CONNECT;
1015 conn->bits.bound = TRUE;
1018 Curl_pgrsStartNow(conn->data);
1025 /**********************************************************
1031 **********************************************************/
1032 static CURLcode tftp_done(struct connectdata *conn, CURLcode status,
1035 CURLcode code = CURLE_OK;
1036 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1038 (void)status; /* unused */
1039 (void)premature; /* not used */
1041 Curl_pgrsDone(conn);
1043 /* If we have encountered an error */
1044 code = tftp_translate_code(state->error);
1049 /**********************************************************
1053 * The getsock callback
1055 **********************************************************/
1056 static int tftp_getsock(struct connectdata *conn, curl_socket_t *socks,
1060 return GETSOCK_BLANK;
1062 socks[0] = conn->sock[FIRSTSOCKET];
1064 return GETSOCK_READSOCK(0);
1067 /**********************************************************
1069 * tftp_receive_packet
1071 * Called once select fires and data is ready on the socket
1073 **********************************************************/
1074 static CURLcode tftp_receive_packet(struct connectdata *conn)
1076 struct Curl_sockaddr_storage fromaddr;
1077 curl_socklen_t fromlen;
1078 CURLcode result = CURLE_OK;
1079 struct SessionHandle *data = conn->data;
1080 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1081 struct SingleRequest *k = &data->req;
1083 /* Receive the packet */
1084 fromlen = sizeof(fromaddr);
1085 state->rbytes = (int)recvfrom(state->sockfd,
1086 (void *)state->rpacket.data,
1089 (struct sockaddr *)&fromaddr,
1091 if(state->remote_addrlen==0) {
1092 memcpy(&state->remote_addr, &fromaddr, fromlen);
1093 state->remote_addrlen = fromlen;
1096 /* Sanity check packet length */
1097 if(state->rbytes < 4) {
1098 failf(data, "Received too short packet");
1099 /* Not a timeout, but how best to handle it? */
1100 state->event = TFTP_EVENT_TIMEOUT;
1103 /* The event is given by the TFTP packet time */
1104 state->event = (tftp_event_t)getrpacketevent(&state->rpacket);
1106 switch(state->event) {
1107 case TFTP_EVENT_DATA:
1108 /* Don't pass to the client empty or retransmitted packets */
1109 if(state->rbytes > 4 &&
1110 (NEXT_BLOCKNUM(state->block) == getrpacketblock(&state->rpacket))) {
1111 result = Curl_client_write(conn, CLIENTWRITE_BODY,
1112 (char *)state->rpacket.data+4,
1115 tftp_state_machine(state, TFTP_EVENT_ERROR);
1118 k->bytecount += state->rbytes-4;
1119 Curl_pgrsSetDownloadCounter(data, (curl_off_t) k->bytecount);
1122 case TFTP_EVENT_ERROR:
1123 state->error = (tftp_error_t)getrpacketblock(&state->rpacket);
1124 infof(data, "%s\n", (const char *)state->rpacket.data+4);
1126 case TFTP_EVENT_ACK:
1128 case TFTP_EVENT_OACK:
1129 result = tftp_parse_option_ack(state,
1130 (const char *)state->rpacket.data+2,
1135 case TFTP_EVENT_RRQ:
1136 case TFTP_EVENT_WRQ:
1138 failf(data, "%s", "Internal error: Unexpected packet");
1142 /* Update the progress meter */
1143 if(Curl_pgrsUpdate(conn)) {
1144 tftp_state_machine(state, TFTP_EVENT_ERROR);
1145 return CURLE_ABORTED_BY_CALLBACK;
1151 /**********************************************************
1153 * tftp_state_timeout
1155 * Check if timeouts have been reached
1157 **********************************************************/
1158 static long tftp_state_timeout(struct connectdata *conn, tftp_event_t *event)
1161 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1164 *event = TFTP_EVENT_NONE;
1167 if(current > state->max_time) {
1168 DEBUGF(infof(conn->data, "timeout: %ld > %ld\n",
1169 (long)current, (long)state->max_time));
1170 state->error = TFTP_ERR_TIMEOUT;
1171 state->state = TFTP_STATE_FIN;
1174 else if (current > state->rx_time+state->retry_time) {
1176 *event = TFTP_EVENT_TIMEOUT;
1177 time(&state->rx_time); /* update even though we received nothing */
1178 return(state->max_time-current);
1181 return(state->max_time-current);
1186 /**********************************************************
1188 * tftp_easy_statemach
1190 * Handle easy request until completion
1192 **********************************************************/
1193 static CURLcode tftp_easy_statemach(struct connectdata *conn)
1197 CURLcode result = CURLE_OK;
1198 struct SessionHandle *data = conn->data;
1199 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1202 struct SingleRequest *k = &data->req;
1203 struct timeval transaction_start = Curl_tvnow();
1205 k->start = transaction_start;
1206 k->now = transaction_start;
1208 /* Run the TFTP State Machine */
1209 for(; (state->state != TFTP_STATE_FIN) && (result == CURLE_OK); ) {
1211 timeout_ms = state->retry_time * 1000;
1213 if (data->set.upload) {
1214 if (data->set.max_send_speed &&
1215 (data->progress.ulspeed > data->set.max_send_speed)) {
1216 fd_read = CURL_SOCKET_BAD;
1217 timeout_ms = Curl_sleep_time(data->set.max_send_speed,
1218 data->progress.ulspeed, state->blksize);
1221 fd_read = state->sockfd;
1225 if (data->set.max_recv_speed &&
1226 (data->progress.dlspeed > data->set.max_recv_speed)) {
1227 fd_read = CURL_SOCKET_BAD;
1228 timeout_ms = Curl_sleep_time(data->set.max_recv_speed,
1229 data->progress.dlspeed, state->blksize);
1232 fd_read = state->sockfd;
1236 if(data->set.timeout) {
1237 timeout_ms = data->set.timeout - Curl_tvdiff(k->now, k->start);
1238 if (timeout_ms > state->retry_time * 1000)
1239 timeout_ms = state->retry_time * 1000;
1240 else if(timeout_ms < 0)
1245 /* Wait until ready to read or timeout occurs */
1246 rc = Curl_socket_ready(fd_read, CURL_SOCKET_BAD, (int)(timeout_ms));
1248 k->now = Curl_tvnow();
1250 /* Force a progress callback if it's been too long */
1251 if (Curl_tvdiff(k->now, k->start) >= data->set.timeout) {
1252 if(Curl_pgrsUpdate(conn)) {
1253 tftp_state_machine(state, TFTP_EVENT_ERROR);
1254 return CURLE_ABORTED_BY_CALLBACK;
1261 int error = SOCKERRNO;
1262 failf(data, "%s", Curl_strerror(conn, error));
1263 state->event = TFTP_EVENT_ERROR;
1268 /* A timeout occured, but our timeout is variable, so maybe
1270 long rtms = state->retry_time * 1000;
1271 if (Curl_tvdiff(k->now, transaction_start) > rtms) {
1272 state->event = TFTP_EVENT_TIMEOUT;
1273 /* Force a look at transfer timeouts */
1277 continue; /* skip state machine */
1281 result = tftp_receive_packet(conn);
1282 if (result == CURLE_OK)
1283 transaction_start = Curl_tvnow();
1286 *k->bytecountp = k->bytecount; /* read count */
1287 if(k->writebytecountp)
1288 *k->writebytecountp = k->writebytecount; /* write count */
1293 tftp_state_timeout(conn, NULL);
1300 result = tftp_state_machine(state, state->event);
1303 /* Tell curl we're done */
1304 Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1309 /**********************************************************
1311 * tftp_multi_statemach
1313 * Handle single RX socket event and return
1315 **********************************************************/
1316 static CURLcode tftp_multi_statemach(struct connectdata *conn, bool *done)
1320 CURLcode result = CURLE_OK;
1321 struct SessionHandle *data = conn->data;
1322 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1323 long timeout_ms = tftp_state_timeout(conn, &event);
1327 if(timeout_ms <= 0) {
1328 failf(data, "TFTP response timeout");
1329 return CURLE_OPERATION_TIMEDOUT;
1331 else if (event != TFTP_EVENT_NONE) {
1332 result = tftp_state_machine(state, event);
1333 if(result != CURLE_OK)
1335 *done = (bool)(state->state == TFTP_STATE_FIN);
1337 /* Tell curl we're done */
1338 Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1341 /* no timeouts to handle, check our socket */
1342 rc = Curl_socket_ready(state->sockfd, CURL_SOCKET_BAD, 0);
1346 int error = SOCKERRNO;
1347 failf(data, "%s", Curl_strerror(conn, error));
1348 state->event = TFTP_EVENT_ERROR;
1351 result = tftp_receive_packet(conn);
1352 if(result != CURLE_OK)
1354 result = tftp_state_machine(state, state->event);
1355 if(result != CURLE_OK)
1357 *done = (bool)(state->state == TFTP_STATE_FIN);
1359 /* Tell curl we're done */
1360 Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1362 /* if rc == 0, then select() timed out */
1368 /**********************************************************
1372 * Called from multi.c while DOing
1374 **********************************************************/
1375 static CURLcode tftp_doing(struct connectdata *conn, bool *dophase_done)
1378 result = tftp_multi_statemach(conn, dophase_done);
1381 DEBUGF(infof(conn->data, "DO phase is complete\n"));
1386 /**********************************************************
1390 * Entry point for transfer from tftp_do, sarts state mach
1392 **********************************************************/
1393 static CURLcode tftp_perform(struct connectdata *conn, bool *dophase_done)
1395 CURLcode result = CURLE_OK;
1396 tftp_state_data_t *state = (tftp_state_data_t *)conn->proto.tftpc;
1398 *dophase_done = FALSE;
1400 result = tftp_state_machine(state, TFTP_EVENT_INIT);
1402 if(state->state == TFTP_STATE_FIN || result != CURLE_OK)
1405 if(conn->data->state.used_interface == Curl_if_multi)
1406 tftp_multi_statemach(conn, dophase_done);
1408 result = tftp_easy_statemach(conn);
1409 *dophase_done = TRUE; /* with the easy interface we are done here */
1413 DEBUGF(infof(conn->data, "DO phase is complete\n"));
1419 /**********************************************************
1425 * This callback initiates the TFTP transfer
1427 **********************************************************/
1429 static CURLcode tftp_do(struct connectdata *conn, bool *done)
1431 tftp_state_data_t *state;
1437 Since connections can be re-used between SessionHandles, this might be a
1438 connection already existing but on a fresh SessionHandle struct so we must
1439 make sure we have a good 'struct TFTP' to play with. For new connections,
1440 the struct TFTP is allocated and setup in the tftp_connect() function.
1442 Curl_reset_reqproto(conn);
1444 if(!conn->proto.tftpc) {
1445 code = tftp_connect(conn, done);
1449 state = (tftp_state_data_t *)conn->proto.tftpc;
1451 code = tftp_perform(conn, done);
1453 /* If tftp_perform() returned an error, use that for return code. If it
1454 was OK, see if tftp_translate_code() has an error. */
1455 if (code == CURLE_OK)
1456 /* If we have encountered an internal tftp error, translate it. */
1457 code = tftp_translate_code(state->error);
1462 static CURLcode tftp_setup_connection(struct connectdata * conn)
1464 struct SessionHandle *data = conn->data;
1468 conn->socktype = SOCK_DGRAM; /* UDP datagram based */
1470 /* TFTP URLs support an extension like ";mode=<typecode>" that
1471 * we'll try to get now! */
1472 type = strstr(data->state.path, ";mode=");
1475 type = strstr(conn->host.rawalloc, ";mode=");
1478 *type = 0; /* it was in the middle of the hostname */
1479 command = Curl_raw_toupper(type[6]);
1482 case 'A': /* ASCII mode */
1483 case 'N': /* NETASCII mode */
1484 data->set.prefer_ascii = TRUE;
1487 case 'O': /* octet mode */
1488 case 'I': /* binary mode */
1490 /* switch off ASCII */
1491 data->set.prefer_ascii = FALSE;