1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2008, 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 -- */
38 #ifdef HAVE_SYS_SOCKET_H
39 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #ifdef HAVE_SYS_TIME_H
49 #ifdef HAVE_ARPA_INET_H
50 #include <arpa/inet.h>
55 #ifdef HAVE_SYS_IOCTL_H
56 #include <sys/ioctl.h>
59 #ifdef HAVE_SYS_PARAM_H
60 #include <sys/param.h>
66 #include <curl/curl.h>
73 #include "sockaddr.h" /* required for Curl_sockaddr_storage */
76 #define _MPRINTF_REPLACE /* use our functions only */
77 #include <curl/mprintf.h>
82 /* The last #include file should be: */
85 /* RFC2348 allows the block size to be negotiated, but we don't support that */
86 #define TFTP_BLOCKSIZE 512
106 TFTP_EVENT_ERROR = 5,
118 TFTP_ERR_NOSUCHUSER, /* This will never be triggered by this code */
120 /* The remaining error codes are internal to curl */
121 TFTP_ERR_NONE = -100,
126 typedef struct tftp_packet {
127 unsigned char data[2 + 2 + TFTP_BLOCKSIZE];
130 typedef struct tftp_state_data {
134 struct connectdata *conn;
135 curl_socket_t sockfd;
141 unsigned short block;
142 struct Curl_sockaddr_storage local_addr;
143 struct Curl_sockaddr_storage remote_addr;
144 socklen_t remote_addrlen;
147 tftp_packet_t rpacket;
148 tftp_packet_t spacket;
152 /* Forward declarations */
153 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event) ;
154 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event) ;
155 static CURLcode tftp_connect(struct connectdata *conn, bool *done);
156 static CURLcode tftp_do(struct connectdata *conn, bool *done);
157 static CURLcode tftp_done(struct connectdata *conn,
158 CURLcode, bool premature);
159 static CURLcode tftp_setup_connection(struct connectdata * conn);
163 * TFTP protocol handler.
166 const struct Curl_handler Curl_handler_tftp = {
168 tftp_setup_connection, /* setup_connection */
170 tftp_done, /* done */
171 ZERO_NULL, /* do_more */
172 tftp_connect, /* connect_it */
173 ZERO_NULL, /* connecting */
174 ZERO_NULL, /* doing */
175 ZERO_NULL, /* proto_getsock */
176 ZERO_NULL, /* doing_getsock */
177 ZERO_NULL, /* perform_getsock */
178 ZERO_NULL, /* disconnect */
179 PORT_TFTP, /* defport */
180 PROT_TFTP /* protocol */
184 /**********************************************************
186 * tftp_set_timeouts -
188 * Set timeouts based on state machine state.
189 * Use user provided connect timeouts until DATA or ACK
190 * packet is received, then use user-provided transfer timeouts
193 **********************************************************/
194 static CURLcode tftp_set_timeouts(tftp_state_data_t *state)
196 time_t maxtime, timeout;
198 const bool start = (state->state == TFTP_STATE_START);
200 time(&state->start_time);
202 /* Compute drop-dead time */
203 timeout_ms = Curl_timeleft(state->conn, NULL, start);
206 /* time-out, bail out, go home */
207 failf(state->conn->data, "Connection time-out");
208 return CURLE_OPERATION_TIMEDOUT;
213 maxtime = (time_t)(timeout_ms + 500) / 1000;
214 state->max_time = state->start_time+maxtime;
216 /* Set per-block timeout to total */
219 /* Average restart after 5 seconds */
220 state->retry_max = timeout/5;
222 if(state->retry_max < 1)
223 /* avoid division by zero below */
224 state->retry_max = 1;
226 /* Compute the re-start interval to suit the timeout */
227 state->retry_time = timeout/state->retry_max;
228 if(state->retry_time<1)
234 maxtime = (time_t)(timeout_ms + 500) / 1000;
238 state->max_time = state->start_time+maxtime;
240 /* Set per-block timeout to 10% of total */
241 timeout = maxtime/10 ;
243 /* Average reposting an ACK after 15 seconds */
244 state->retry_max = timeout/15;
246 /* But bound the total number */
247 if(state->retry_max<3)
250 if(state->retry_max>50)
253 /* Compute the re-ACK interval to suit the timeout */
254 state->retry_time = timeout/state->retry_max;
255 if(state->retry_time<1)
258 infof(state->conn->data,
259 "set timeouts for state %d; Total %d, retry %d maxtry %d\n",
260 state->state, (state->max_time-state->start_time),
261 state->retry_time, state->retry_max);
266 /**********************************************************
268 * tftp_set_send_first
270 * Event handler for the START state
272 **********************************************************/
274 static void setpacketevent(tftp_packet_t *packet, unsigned short num)
276 packet->data[0] = (unsigned char)(num >> 8);
277 packet->data[1] = (unsigned char)(num & 0xff);
281 static void setpacketblock(tftp_packet_t *packet, unsigned short num)
283 packet->data[2] = (unsigned char)(num >> 8);
284 packet->data[3] = (unsigned char)(num & 0xff);
287 static unsigned short getrpacketevent(const tftp_packet_t *packet)
289 return (unsigned short)((packet->data[0] << 8) | packet->data[1]);
292 static unsigned short getrpacketblock(const tftp_packet_t *packet)
294 return (unsigned short)((packet->data[2] << 8) | packet->data[3]);
297 static CURLcode tftp_send_first(tftp_state_data_t *state, tftp_event_t event)
300 const char *mode = "octet";
302 struct SessionHandle *data = state->conn->data;
303 CURLcode res = CURLE_OK;
305 /* Set ascii mode if -B flag was used */
306 if(data->set.prefer_ascii)
311 case TFTP_EVENT_INIT: /* Send the first packet out */
312 case TFTP_EVENT_TIMEOUT: /* Resend the first packet out */
313 /* Increment the retry counter, quit if over the limit */
315 if(state->retries>state->retry_max) {
316 state->error = TFTP_ERR_NORESPONSE;
317 state->state = TFTP_STATE_FIN;
321 if(data->set.upload) {
322 /* If we are uploading, send an WRQ */
323 setpacketevent(&state->spacket, TFTP_EVENT_WRQ);
324 state->conn->data->req.upload_fromhere =
325 (char *)&state->spacket.data[4];
326 if(data->set.infilesize != -1)
327 Curl_pgrsSetUploadSize(data, data->set.infilesize);
330 /* If we are downloading, send an RRQ */
331 setpacketevent(&state->spacket, TFTP_EVENT_RRQ);
333 /* As RFC3617 describes the separator slash is not actually part of the
334 file name so we skip the always-present first letter of the path string. */
335 filename = curl_easy_unescape(data, &state->conn->data->state.path[1], 0,
338 return CURLE_OUT_OF_MEMORY;
340 snprintf((char *)&state->spacket.data[2],
342 "%s%c%s%c", filename, '\0', mode, '\0');
343 sbytes = 4 + (int)strlen(filename) + (int)strlen(mode);
344 sbytes = sendto(state->sockfd, (void *)&state->spacket,
346 state->conn->ip_addr->ai_addr,
347 state->conn->ip_addr->ai_addrlen);
349 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
351 Curl_safefree(filename);
354 case TFTP_EVENT_ACK: /* Connected for transmit */
355 infof(data, "%s\n", "Connected for transmit");
356 state->state = TFTP_STATE_TX;
357 res = tftp_set_timeouts(state);
360 return tftp_tx(state, event);
362 case TFTP_EVENT_DATA: /* connected for receive */
363 infof(data, "%s\n", "Connected for receive");
364 state->state = TFTP_STATE_RX;
365 res = tftp_set_timeouts(state);
368 return tftp_rx(state, event);
370 case TFTP_EVENT_ERROR:
371 state->state = TFTP_STATE_FIN;
375 failf(state->conn->data, "tftp_send_first: internal error");
381 /**********************************************************
385 * Event handler for the RX state
387 **********************************************************/
388 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event)
392 struct SessionHandle *data = state->conn->data;
396 case TFTP_EVENT_DATA:
398 /* Is this the block we expect? */
399 rblock = getrpacketblock(&state->rpacket);
400 if((state->block+1) != rblock) {
401 /* No, log it, up the retry count and fail if over the limit */
403 "Received unexpected DATA packet block %d\n", rblock);
405 if(state->retries>state->retry_max) {
406 failf(data, "tftp_rx: giving up waiting for block %d",
408 return CURLE_TFTP_ILLEGAL;
411 /* This is the expected block. Reset counters and ACK it. */
412 state->block = (unsigned short)rblock;
414 setpacketevent(&state->spacket, TFTP_EVENT_ACK);
415 setpacketblock(&state->spacket, state->block);
416 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
418 (struct sockaddr *)&state->remote_addr,
419 state->remote_addrlen);
421 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
422 return CURLE_SEND_ERROR;
425 /* Check if completed (That is, a less than full packet is received) */
426 if(state->rbytes < (ssize_t)sizeof(state->spacket)){
427 state->state = TFTP_STATE_FIN;
430 state->state = TFTP_STATE_RX;
434 case TFTP_EVENT_TIMEOUT:
435 /* Increment the retry count and fail if over the limit */
438 "Timeout waiting for block %d ACK. Retries = %d\n", state->retries);
439 if(state->retries > state->retry_max) {
440 state->error = TFTP_ERR_TIMEOUT;
441 state->state = TFTP_STATE_FIN;
444 /* Resend the previous ACK */
445 sbytes = sendto(state->sockfd, (void *)&state->spacket,
447 (struct sockaddr *)&state->remote_addr,
448 state->remote_addrlen);
449 /* Check all sbytes were sent */
451 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
452 return CURLE_SEND_ERROR;
457 case TFTP_EVENT_ERROR:
458 state->state = TFTP_STATE_FIN;
462 failf(data, "%s", "tftp_rx: internal error");
463 return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for
469 /**********************************************************
473 * Event handler for the TX state
475 **********************************************************/
476 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event)
478 struct SessionHandle *data = state->conn->data;
481 CURLcode res = CURLE_OK;
482 struct SingleRequest *k = &data->req;
488 rblock = getrpacketblock(&state->rpacket);
490 if(rblock != state->block) {
491 /* This isn't the expected block. Log it and up the retry counter */
492 infof(data, "Received ACK for block %d, expecting %d\n",
493 rblock, state->block);
495 /* Bail out if over the maximum */
496 if(state->retries>state->retry_max) {
497 failf(data, "tftp_tx: giving up waiting for block %d ack",
499 res = CURLE_SEND_ERROR;
502 /* Re-send the data packet */
503 sbytes = sendto(state->sockfd, (void *)&state->spacket,
504 4+state->sbytes, SEND_4TH_ARG,
505 (struct sockaddr *)&state->remote_addr,
506 state->remote_addrlen);
507 /* Check all sbytes were sent */
509 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
510 res = CURLE_SEND_ERROR;
515 /* This is the expected packet. Reset the counters and send the next
519 setpacketevent(&state->spacket, TFTP_EVENT_DATA);
520 setpacketblock(&state->spacket, state->block);
521 if(state->block > 1 && state->sbytes < TFTP_BLOCKSIZE) {
522 state->state = TFTP_STATE_FIN;
525 res = Curl_fillreadbuffer(state->conn, TFTP_BLOCKSIZE, &state->sbytes);
528 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
529 4+state->sbytes, SEND_4TH_ARG,
530 (struct sockaddr *)&state->remote_addr,
531 state->remote_addrlen);
532 /* Check all sbytes were sent */
534 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
535 return CURLE_SEND_ERROR;
537 /* Update the progress meter */
538 k->writebytecount += state->sbytes;
539 Curl_pgrsSetUploadCounter(data, k->writebytecount);
542 case TFTP_EVENT_TIMEOUT:
543 /* Increment the retry counter and log the timeout */
545 infof(data, "Timeout waiting for block %d ACK. "
546 " Retries = %d\n", state->retries);
547 /* Decide if we've had enough */
548 if(state->retries > state->retry_max) {
549 state->error = TFTP_ERR_TIMEOUT;
550 state->state = TFTP_STATE_FIN;
553 /* Re-send the data packet */
554 sbytes = sendto(state->sockfd, (void *)&state->spacket,
555 4+state->sbytes, SEND_4TH_ARG,
556 (struct sockaddr *)&state->remote_addr,
557 state->remote_addrlen);
558 /* Check all sbytes were sent */
560 failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
561 return CURLE_SEND_ERROR;
563 /* since this was a re-send, we remain at the still byte position */
564 Curl_pgrsSetUploadCounter(data, k->writebytecount);
568 case TFTP_EVENT_ERROR:
569 state->state = TFTP_STATE_FIN;
573 failf(data, "%s", "tftp_tx: internal error");
580 /**********************************************************
584 * The tftp state machine event dispatcher
586 **********************************************************/
587 static CURLcode tftp_state_machine(tftp_state_data_t *state,
590 CURLcode res = CURLE_OK;
591 struct SessionHandle *data = state->conn->data;
592 switch(state->state) {
593 case TFTP_STATE_START:
594 DEBUGF(infof(data, "TFTP_STATE_START\n"));
595 res = tftp_send_first(state, event);
598 DEBUGF(infof(data, "TFTP_STATE_RX\n"));
599 res = tftp_rx(state, event);
602 DEBUGF(infof(data, "TFTP_STATE_TX\n"));
603 res = tftp_tx(state, event);
606 infof(data, "%s\n", "TFTP finished");
609 DEBUGF(infof(data, "STATE: %d\n", state->state));
610 failf(data, "%s", "Internal state machine error");
611 res = CURLE_TFTP_ILLEGAL;
618 /**********************************************************
622 * The connect callback
624 **********************************************************/
625 static CURLcode tftp_connect(struct connectdata *conn, bool *done)
628 tftp_state_data_t *state;
631 /* If there already is a protocol-specific struct allocated for this
632 sessionhandle, deal with it */
633 Curl_reset_reqproto(conn);
635 state = conn->data->state.proto.tftp;
637 state = conn->data->state.proto.tftp = calloc(sizeof(tftp_state_data_t),
640 return CURLE_OUT_OF_MEMORY;
643 conn->bits.close = FALSE; /* keep it open if possible */
646 state->sockfd = state->conn->sock[FIRSTSOCKET];
647 state->state = TFTP_STATE_START;
648 state->error = TFTP_ERR_NONE;
650 ((struct sockaddr *)&state->local_addr)->sa_family =
651 (unsigned short)(conn->ip_addr->ai_family);
653 tftp_set_timeouts(state);
655 if(!conn->bits.bound) {
656 /* If not already bound, bind to any interface, random UDP port. If it is
657 * reused or a custom local port was desired, this has already been done!
659 * We once used the size of the local_addr struct as the third argument for
660 * bind() to better work with IPv6 or whatever size the struct could have,
661 * but we learned that at least Tru64, AIX and IRIX *requires* the size of
662 * that argument to match the exact size of a 'sockaddr_in' struct when
665 * Therefore we use the size from the address we connected to, which we
666 * assume uses the same IP version and thus hopefully this works for both
669 rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr,
670 conn->ip_addr->ai_addrlen);
672 failf(conn->data, "bind() failed; %s",
673 Curl_strerror(conn, SOCKERRNO));
674 return CURLE_COULDNT_CONNECT;
676 conn->bits.bound = TRUE;
679 Curl_pgrsStartNow(conn->data);
686 /**********************************************************
692 **********************************************************/
693 static CURLcode tftp_done(struct connectdata *conn, CURLcode status,
696 (void)status; /* unused */
697 (void)premature; /* not used */
705 /**********************************************************
711 * This callback handles the entire TFTP transfer
713 **********************************************************/
715 static CURLcode tftp_do(struct connectdata *conn, bool *done)
717 struct SessionHandle *data = conn->data;
718 tftp_state_data_t *state;
722 struct Curl_sockaddr_storage fromaddr;
725 struct SingleRequest *k = &data->req;
730 Since connections can be re-used between SessionHandles, this might be a
731 connection already existing but on a fresh SessionHandle struct so we must
732 make sure we have a good 'struct TFTP' to play with. For new connections,
733 the struct TFTP is allocated and setup in the tftp_connect() function.
735 Curl_reset_reqproto(conn);
737 if(!data->state.proto.tftp) {
738 code = tftp_connect(conn, done);
742 state = (tftp_state_data_t *)data->state.proto.tftp;
744 /* Run the TFTP State Machine */
745 for(code=tftp_state_machine(state, TFTP_EVENT_INIT);
746 (state->state != TFTP_STATE_FIN) && (code == CURLE_OK);
747 code=tftp_state_machine(state, event) ) {
749 /* Wait until ready to read or timeout occurs */
750 rc=Curl_socket_ready(state->sockfd, CURL_SOCKET_BAD,
751 state->retry_time * 1000);
755 int error = SOCKERRNO;
756 failf(data, "%s", Curl_strerror(conn, error));
757 event = TFTP_EVENT_ERROR;
760 /* A timeout occured */
761 event = TFTP_EVENT_TIMEOUT;
763 /* Force a look at transfer timeouts */
769 /* Receive the packet */
770 fromlen = sizeof(fromaddr);
771 state->rbytes = (ssize_t)recvfrom(state->sockfd,
772 (void *)&state->rpacket,
773 sizeof(state->rpacket),
775 (struct sockaddr *)&fromaddr,
777 if(state->remote_addrlen==0) {
778 memcpy(&state->remote_addr, &fromaddr, fromlen);
779 state->remote_addrlen = fromlen;
782 /* Sanity check packet length */
783 if(state->rbytes < 4) {
784 failf(data, "Received too short packet");
785 /* Not a timeout, but how best to handle it? */
786 event = TFTP_EVENT_TIMEOUT;
790 /* The event is given by the TFTP packet time */
791 event = (tftp_event_t)getrpacketevent(&state->rpacket);
794 case TFTP_EVENT_DATA:
795 /* Don't pass to the client empty or retransmitted packets */
796 if(state->rbytes > 4 &&
797 ((state->block+1) == getrpacketblock(&state->rpacket))) {
798 code = Curl_client_write(conn, CLIENTWRITE_BODY,
799 (char *)&state->rpacket.data[4],
803 k->bytecount += state->rbytes-4;
804 Curl_pgrsSetDownloadCounter(data, (curl_off_t) k->bytecount);
807 case TFTP_EVENT_ERROR:
808 state->error = (tftp_error_t)getrpacketblock(&state->rpacket);
809 infof(data, "%s\n", (const char *)&state->rpacket.data[4]);
816 failf(data, "%s", "Internal error: Unexpected packet");
820 /* Update the progress meter */
821 if(Curl_pgrsUpdate(conn))
822 return CURLE_ABORTED_BY_CALLBACK;
826 /* Check for transfer timeout every 10 blocks, or after timeout */
827 if(check_time%10==0) {
830 if(current>state->max_time) {
831 DEBUGF(infof(data, "timeout: %d > %d\n",
832 current, state->max_time));
833 state->error = TFTP_ERR_TIMEOUT;
834 state->state = TFTP_STATE_FIN;
842 /* Tell curl we're done */
843 code = Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
847 /* If we have encountered an error */
848 if(state->error != TFTP_ERR_NONE) {
850 /* Translate internal error codes to curl error codes */
851 switch(state->error) {
852 case TFTP_ERR_NOTFOUND:
853 code = CURLE_TFTP_NOTFOUND;
856 code = CURLE_TFTP_PERM;
858 case TFTP_ERR_DISKFULL:
859 code = CURLE_REMOTE_DISK_FULL;
862 case TFTP_ERR_ILLEGAL:
863 code = CURLE_TFTP_ILLEGAL;
865 case TFTP_ERR_UNKNOWNID:
866 code = CURLE_TFTP_UNKNOWNID;
868 case TFTP_ERR_EXISTS:
869 code = CURLE_REMOTE_FILE_EXISTS;
871 case TFTP_ERR_NOSUCHUSER:
872 code = CURLE_TFTP_NOSUCHUSER;
874 case TFTP_ERR_TIMEOUT:
875 code = CURLE_OPERATION_TIMEDOUT;
877 case TFTP_ERR_NORESPONSE:
878 code = CURLE_COULDNT_CONNECT;
881 code= CURLE_ABORTED_BY_CALLBACK;
890 static CURLcode tftp_setup_connection(struct connectdata * conn)
892 struct SessionHandle *data = conn->data;
896 conn->socktype = SOCK_DGRAM; /* UDP datagram based */
898 /* TFTP URLs support an extension like ";mode=<typecode>" that
899 * we'll try to get now! */
900 type = strstr(data->state.path, ";mode=");
903 type = strstr(conn->host.rawalloc, ";mode=");
906 *type = 0; /* it was in the middle of the hostname */
907 command = (char) toupper((int) type[6]);
910 case 'A': /* ASCII mode */
911 case 'N': /* NETASCII mode */
912 data->set.prefer_ascii = TRUE;
915 case 'O': /* octet mode */
916 case 'I': /* binary mode */
918 /* switch off ASCII */
919 data->set.prefer_ascii = FALSE;