1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2007, 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 #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 */
75 #define _MPRINTF_REPLACE /* use our functions only */
76 #include <curl/mprintf.h>
81 /* The last #include file should be: */
84 /* RFC2348 allows the block size to be negotiated, but we don't support that */
85 #define TFTP_BLOCKSIZE 512
105 TFTP_EVENT_ERROR = 5,
117 TFTP_ERR_NOSUCHUSER, /* This will never be triggered by this code */
119 /* The remaining error codes are internal to curl */
120 TFTP_ERR_NONE = -100,
125 typedef struct tftp_packet {
126 unsigned char data[2 + 2 + TFTP_BLOCKSIZE];
129 typedef struct tftp_state_data {
133 struct connectdata *conn;
134 curl_socket_t sockfd;
140 unsigned short block;
141 struct Curl_sockaddr_storage local_addr;
142 struct Curl_sockaddr_storage remote_addr;
143 socklen_t remote_addrlen;
146 tftp_packet_t rpacket;
147 tftp_packet_t spacket;
151 /* Forward declarations */
152 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event) ;
153 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event) ;
154 static CURLcode tftp_connect(struct connectdata *conn, bool *done);
155 static CURLcode tftp_do(struct connectdata *conn, bool *done);
156 static CURLcode tftp_done(struct connectdata *conn,
157 CURLcode, bool premature);
158 static CURLcode tftp_setup_connection(struct connectdata * conn);
162 * TFTP protocol handler.
165 const struct Curl_handler Curl_handler_tftp = {
167 tftp_setup_connection, /* setup_connection */
169 tftp_done, /* done */
170 ZERO_NULL, /* do_more */
171 tftp_connect, /* connect_it */
172 ZERO_NULL, /* connecting */
173 ZERO_NULL, /* doing */
174 ZERO_NULL, /* proto_getsock */
175 ZERO_NULL, /* doing_getsock */
176 ZERO_NULL, /* disconnect */
177 PORT_TFTP, /* defport */
178 PROT_TFTP /* protocol */
182 /**********************************************************
184 * tftp_set_timeouts -
186 * Set timeouts based on state machine state.
187 * Use user provided connect timeouts until DATA or ACK
188 * packet is received, then use user-provided transfer timeouts
191 **********************************************************/
192 static void tftp_set_timeouts(tftp_state_data_t *state)
195 struct SessionHandle *data = state->conn->data;
196 time_t maxtime, timeout;
198 time(&state->start_time);
199 if(state->state == TFTP_STATE_START) {
200 /* Compute drop-dead time */
201 maxtime = (time_t)(data->set.connecttimeout/1000L?
202 data->set.connecttimeout/1000L:30);
203 state->max_time = state->start_time+maxtime;
205 /* Set per-block timeout to total */
208 /* Average restart after 5 seconds */
209 state->retry_max = timeout/5;
211 if(state->retry_max < 1)
212 /* avoid division by zero below */
213 state->retry_max = 1;
215 /* Compute the re-start interval to suit the timeout */
216 state->retry_time = timeout/state->retry_max;
217 if(state->retry_time<1)
223 /* Compute drop-dead time */
224 maxtime = (time_t)(data->set.timeout/1000L?
225 data->set.timeout/1000L:3600);
226 state->max_time = state->start_time+maxtime;
228 /* Set per-block timeout to 10% of total */
229 timeout = maxtime/10 ;
231 /* Average reposting an ACK after 15 seconds */
232 state->retry_max = timeout/15;
234 /* But bound the total number */
235 if(state->retry_max<3)
238 if(state->retry_max>50)
241 /* Compute the re-ACK interval to suit the timeout */
242 state->retry_time = timeout/state->retry_max;
243 if(state->retry_time<1)
246 infof(data, "set timeouts for state %d; Total %d, retry %d maxtry %d\n",
247 state->state, (state->max_time-state->start_time),
248 state->retry_time, state->retry_max);
251 /**********************************************************
253 * tftp_set_send_first
255 * Event handler for the START state
257 **********************************************************/
259 static void setpacketevent(tftp_packet_t *packet, unsigned short num)
261 packet->data[0] = (unsigned char)(num >> 8);
262 packet->data[1] = (unsigned char)(num & 0xff);
266 static void setpacketblock(tftp_packet_t *packet, unsigned short num)
268 packet->data[2] = (unsigned char)(num >> 8);
269 packet->data[3] = (unsigned char)(num & 0xff);
272 static unsigned short getrpacketevent(const tftp_packet_t *packet)
274 return (unsigned short)((packet->data[0] << 8) | packet->data[1]);
277 static unsigned short getrpacketblock(const tftp_packet_t *packet)
279 return (unsigned short)((packet->data[2] << 8) | packet->data[3]);
282 static CURLcode tftp_send_first(tftp_state_data_t *state, tftp_event_t event)
285 const char *mode = "octet";
287 struct SessionHandle *data = state->conn->data;
288 CURLcode res = CURLE_OK;
290 /* Set ascii mode if -B flag was used */
291 if(data->set.prefer_ascii)
296 case TFTP_EVENT_INIT: /* Send the first packet out */
297 case TFTP_EVENT_TIMEOUT: /* Resend the first packet out */
298 /* Increment the retry counter, quit if over the limit */
300 if(state->retries>state->retry_max) {
301 state->error = TFTP_ERR_NORESPONSE;
302 state->state = TFTP_STATE_FIN;
306 if(data->set.upload) {
307 /* If we are uploading, send an WRQ */
308 setpacketevent(&state->spacket, TFTP_EVENT_WRQ);
309 state->conn->data->req.upload_fromhere =
310 (char *)&state->spacket.data[4];
311 if(data->set.infilesize != -1)
312 Curl_pgrsSetUploadSize(data, data->set.infilesize);
315 /* If we are downloading, send an RRQ */
316 setpacketevent(&state->spacket, TFTP_EVENT_RRQ);
318 /* As RFC3617 describes the separator slash is not actually part of the
319 file name so we skip the always-present first letter of the path string. */
320 filename = curl_easy_unescape(data, &state->conn->data->state.path[1], 0,
323 return CURLE_OUT_OF_MEMORY;
325 snprintf((char *)&state->spacket.data[2],
327 "%s%c%s%c", filename, '\0', mode, '\0');
328 sbytes = 4 + (int)strlen(filename) + (int)strlen(mode);
329 sbytes = sendto(state->sockfd, (void *)&state->spacket,
331 state->conn->ip_addr->ai_addr,
332 state->conn->ip_addr->ai_addrlen);
334 failf(data, "%s\n", Curl_strerror(state->conn, SOCKERRNO));
336 Curl_safefree(filename);
339 case TFTP_EVENT_ACK: /* Connected for transmit */
340 infof(data, "%s\n", "Connected for transmit");
341 state->state = TFTP_STATE_TX;
342 tftp_set_timeouts(state);
343 return tftp_tx(state, event);
345 case TFTP_EVENT_DATA: /* connected for receive */
346 infof(data, "%s\n", "Connected for receive");
347 state->state = TFTP_STATE_RX;
348 tftp_set_timeouts(state);
349 return tftp_rx(state, event);
351 case TFTP_EVENT_ERROR:
352 state->state = TFTP_STATE_FIN;
356 failf(state->conn->data, "tftp_send_first: internal error\n");
362 /**********************************************************
366 * Event handler for the RX state
368 **********************************************************/
369 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event)
373 struct SessionHandle *data = state->conn->data;
377 case TFTP_EVENT_DATA:
379 /* Is this the block we expect? */
380 rblock = getrpacketblock(&state->rpacket);
381 if((state->block+1) != rblock) {
382 /* No, log it, up the retry count and fail if over the limit */
384 "Received unexpected DATA packet block %d\n", rblock);
386 if(state->retries>state->retry_max) {
387 failf(data, "tftp_rx: giving up waiting for block %d\n",
389 return CURLE_TFTP_ILLEGAL;
392 /* This is the expected block. Reset counters and ACK it. */
393 state->block = (unsigned short)rblock;
395 setpacketevent(&state->spacket, TFTP_EVENT_ACK);
396 setpacketblock(&state->spacket, state->block);
397 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
399 (struct sockaddr *)&state->remote_addr,
400 state->remote_addrlen);
402 failf(data, "%s\n", Curl_strerror(state->conn, SOCKERRNO));
403 return CURLE_SEND_ERROR;
406 /* Check if completed (That is, a less than full packet is received) */
407 if(state->rbytes < (int)sizeof(state->spacket)){
408 state->state = TFTP_STATE_FIN;
411 state->state = TFTP_STATE_RX;
415 case TFTP_EVENT_TIMEOUT:
416 /* Increment the retry count and fail if over the limit */
419 "Timeout waiting for block %d ACK. Retries = %d\n", state->retries);
420 if(state->retries > state->retry_max) {
421 state->error = TFTP_ERR_TIMEOUT;
422 state->state = TFTP_STATE_FIN;
425 /* Resend the previous ACK */
426 sbytes = sendto(state->sockfd, (void *)&state->spacket,
428 (struct sockaddr *)&state->remote_addr,
429 state->remote_addrlen);
430 /* Check all sbytes were sent */
432 failf(data, "%s\n", Curl_strerror(state->conn, SOCKERRNO));
433 return CURLE_SEND_ERROR;
438 case TFTP_EVENT_ERROR:
439 state->state = TFTP_STATE_FIN;
443 failf(data, "%s\n", "tftp_rx: internal error");
444 return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for
450 /**********************************************************
454 * Event handler for the TX state
456 **********************************************************/
457 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event)
459 struct SessionHandle *data = state->conn->data;
462 CURLcode res = CURLE_OK;
463 struct SingleRequest *k = &data->req;
469 rblock = getrpacketblock(&state->rpacket);
471 if(rblock != state->block) {
472 /* This isn't the expected block. Log it and up the retry counter */
473 infof(data, "Received ACK for block %d, expecting %d\n",
474 rblock, state->block);
476 /* Bail out if over the maximum */
477 if(state->retries>state->retry_max) {
478 failf(data, "tftp_tx: giving up waiting for block %d ack",
480 res = CURLE_SEND_ERROR;
483 /* Re-send the data packet */
484 sbytes = sendto(state->sockfd, (void *)&state->spacket,
485 4+state->sbytes, SEND_4TH_ARG,
486 (struct sockaddr *)&state->remote_addr,
487 state->remote_addrlen);
488 /* Check all sbytes were sent */
490 failf(data, "%s\n", Curl_strerror(state->conn, SOCKERRNO));
491 res = CURLE_SEND_ERROR;
496 /* This is the expected packet. Reset the counters and send the next
500 setpacketevent(&state->spacket, TFTP_EVENT_DATA);
501 setpacketblock(&state->spacket, state->block);
502 if(state->block > 1 && state->sbytes < TFTP_BLOCKSIZE) {
503 state->state = TFTP_STATE_FIN;
506 res = Curl_fillreadbuffer(state->conn, TFTP_BLOCKSIZE, &state->sbytes);
509 sbytes = sendto(state->sockfd, (void *)state->spacket.data,
510 4+state->sbytes, SEND_4TH_ARG,
511 (struct sockaddr *)&state->remote_addr,
512 state->remote_addrlen);
513 /* Check all sbytes were sent */
515 failf(data, "%s\n", Curl_strerror(state->conn, SOCKERRNO));
516 return CURLE_SEND_ERROR;
518 /* Update the progress meter */
519 k->writebytecount += state->sbytes;
520 Curl_pgrsSetUploadCounter(data, k->writebytecount);
523 case TFTP_EVENT_TIMEOUT:
524 /* Increment the retry counter and log the timeout */
526 infof(data, "Timeout waiting for block %d ACK. "
527 " Retries = %d\n", state->retries);
528 /* Decide if we've had enough */
529 if(state->retries > state->retry_max) {
530 state->error = TFTP_ERR_TIMEOUT;
531 state->state = TFTP_STATE_FIN;
534 /* Re-send the data packet */
535 sbytes = sendto(state->sockfd, (void *)&state->spacket,
536 4+state->sbytes, SEND_4TH_ARG,
537 (struct sockaddr *)&state->remote_addr,
538 state->remote_addrlen);
539 /* Check all sbytes were sent */
541 failf(data, "%s\n", Curl_strerror(state->conn, SOCKERRNO));
542 return CURLE_SEND_ERROR;
544 /* since this was a re-send, we remain at the still byte position */
545 Curl_pgrsSetUploadCounter(data, k->writebytecount);
549 case TFTP_EVENT_ERROR:
550 state->state = TFTP_STATE_FIN;
554 failf(data, "%s\n", "tftp_tx: internal error");
561 /**********************************************************
565 * The tftp state machine event dispatcher
567 **********************************************************/
568 static CURLcode tftp_state_machine(tftp_state_data_t *state,
571 CURLcode res = CURLE_OK;
572 struct SessionHandle *data = state->conn->data;
573 switch(state->state) {
574 case TFTP_STATE_START:
575 DEBUGF(infof(data, "TFTP_STATE_START\n"));
576 res = tftp_send_first(state, event);
579 DEBUGF(infof(data, "TFTP_STATE_RX\n"));
580 res = tftp_rx(state, event);
583 DEBUGF(infof(data, "TFTP_STATE_TX\n"));
584 res = tftp_tx(state, event);
587 infof(data, "%s\n", "TFTP finished");
590 DEBUGF(infof(data, "STATE: %d\n", state->state));
591 failf(data, "%s\n", "Internal state machine error");
592 res = CURLE_TFTP_ILLEGAL;
599 /**********************************************************
603 * The connect callback
605 **********************************************************/
606 static CURLcode tftp_connect(struct connectdata *conn, bool *done)
609 tftp_state_data_t *state;
612 /* If there already is a protocol-specific struct allocated for this
613 sessionhandle, deal with it */
614 Curl_reset_reqproto(conn);
616 if(!(state = conn->data->state.proto.tftp)) {
617 state = conn->data->state.proto.tftp = calloc(sizeof(tftp_state_data_t),
620 return CURLE_OUT_OF_MEMORY;
623 conn->bits.close = FALSE; /* keep it open if possible */
626 state->sockfd = state->conn->sock[FIRSTSOCKET];
627 state->state = TFTP_STATE_START;
628 state->error = TFTP_ERR_NONE;
630 ((struct sockaddr *)&state->local_addr)->sa_family =
631 (unsigned short)(conn->ip_addr->ai_family);
633 tftp_set_timeouts(state);
635 if(!conn->bits.bound) {
636 /* If not already bound, bind to any interface, random UDP port. If it is
637 * reused or a custom local port was desired, this has already been done!
639 * We once used the size of the local_addr struct as the third argument for
640 * bind() to better work with IPv6 or whatever size the struct could have,
641 * but we learned that at least Tru64, AIX and IRIX *requires* the size of
642 * that argument to match the exact size of a 'sockaddr_in' struct when
645 * Therefore we use the size from the address we connected to, which we
646 * assume uses the same IP version and thus hopefully this works for both
649 rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr,
650 conn->ip_addr->ai_addrlen);
652 failf(conn->data, "bind() failed; %s\n",
653 Curl_strerror(conn, SOCKERRNO));
654 return CURLE_COULDNT_CONNECT;
656 conn->bits.bound = TRUE;
659 Curl_pgrsStartNow(conn->data);
666 /**********************************************************
672 **********************************************************/
673 static CURLcode tftp_done(struct connectdata *conn, CURLcode status,
676 (void)status; /* unused */
677 (void)premature; /* not used */
685 /**********************************************************
691 * This callback handles the entire TFTP transfer
693 **********************************************************/
695 static CURLcode tftp_do(struct connectdata *conn, bool *done)
697 struct SessionHandle *data = conn->data;
698 tftp_state_data_t *state;
702 struct Curl_sockaddr_storage fromaddr;
705 struct SingleRequest *k = &data->req;
710 Since connections can be re-used between SessionHandles, this might be a
711 connection already existing but on a fresh SessionHandle struct so we must
712 make sure we have a good 'struct TFTP' to play with. For new connections,
713 the struct TFTP is allocated and setup in the tftp_connect() function.
715 Curl_reset_reqproto(conn);
717 if(!data->state.proto.tftp) {
718 code = tftp_connect(conn, done);
722 state = (tftp_state_data_t *)data->state.proto.tftp;
724 /* Run the TFTP State Machine */
725 for(code=tftp_state_machine(state, TFTP_EVENT_INIT);
726 (state->state != TFTP_STATE_FIN) && (code == CURLE_OK);
727 code=tftp_state_machine(state, event) ) {
729 /* Wait until ready to read or timeout occurs */
730 rc=Curl_socket_ready(state->sockfd, CURL_SOCKET_BAD,
731 state->retry_time * 1000);
735 int error = SOCKERRNO;
736 failf(data, "%s\n", Curl_strerror(conn, error));
737 event = TFTP_EVENT_ERROR;
740 /* A timeout occured */
741 event = TFTP_EVENT_TIMEOUT;
743 /* Force a look at transfer timeouts */
749 /* Receive the packet */
750 fromlen=sizeof(fromaddr);
751 state->rbytes = recvfrom(state->sockfd,
752 (void *)&state->rpacket, sizeof(state->rpacket),
753 0, (struct sockaddr *)&fromaddr, &fromlen);
754 if(state->remote_addrlen==0) {
755 memcpy(&state->remote_addr, &fromaddr, fromlen);
756 state->remote_addrlen = fromlen;
759 /* Sanity check packet length */
760 if(state->rbytes < 4) {
761 failf(data, "Received too short packet\n");
762 /* Not a timeout, but how best to handle it? */
763 event = TFTP_EVENT_TIMEOUT;
767 /* The event is given by the TFTP packet time */
768 event = (tftp_event_t)getrpacketevent(&state->rpacket);
771 case TFTP_EVENT_DATA:
772 /* Don't pass to the client empty or retransmitted packets */
773 if(state->rbytes > 4 &&
774 ((state->block+1) == getrpacketblock(&state->rpacket))) {
775 code = Curl_client_write(conn, CLIENTWRITE_BODY,
776 (char *)&state->rpacket.data[4],
780 k->bytecount += state->rbytes-4;
781 Curl_pgrsSetDownloadCounter(data, (curl_off_t) k->bytecount);
784 case TFTP_EVENT_ERROR:
785 state->error = (tftp_error_t)getrpacketblock(&state->rpacket);
786 infof(data, "%s\n", (char *)&state->rpacket.data[4]);
793 failf(data, "%s\n", "Internal error: Unexpected packet");
797 /* Update the progress meter */
798 if(Curl_pgrsUpdate(conn))
799 return CURLE_ABORTED_BY_CALLBACK;
803 /* Check for transfer timeout every 10 blocks, or after timeout */
804 if(check_time%10==0) {
807 if(current>state->max_time) {
808 DEBUGF(infof(data, "timeout: %d > %d\n",
809 current, state->max_time));
810 state->error = TFTP_ERR_TIMEOUT;
811 state->state = TFTP_STATE_FIN;
819 /* Tell curl we're done */
820 code = Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
824 /* If we have encountered an error */
825 if(state->error != TFTP_ERR_NONE) {
827 /* Translate internal error codes to curl error codes */
828 switch(state->error) {
829 case TFTP_ERR_NOTFOUND:
830 code = CURLE_TFTP_NOTFOUND;
833 code = CURLE_TFTP_PERM;
835 case TFTP_ERR_DISKFULL:
836 code = CURLE_REMOTE_DISK_FULL;
839 case TFTP_ERR_ILLEGAL:
840 code = CURLE_TFTP_ILLEGAL;
842 case TFTP_ERR_UNKNOWNID:
843 code = CURLE_TFTP_UNKNOWNID;
845 case TFTP_ERR_EXISTS:
846 code = CURLE_REMOTE_FILE_EXISTS;
848 case TFTP_ERR_NOSUCHUSER:
849 code = CURLE_TFTP_NOSUCHUSER;
851 case TFTP_ERR_TIMEOUT:
852 code = CURLE_OPERATION_TIMEDOUT;
854 case TFTP_ERR_NORESPONSE:
855 code = CURLE_COULDNT_CONNECT;
858 code= CURLE_ABORTED_BY_CALLBACK;
867 static CURLcode tftp_setup_connection(struct connectdata * conn)
869 struct SessionHandle *data = conn->data;
873 conn->socktype = SOCK_DGRAM; /* UDP datagram based */
875 /* TFTP URLs support an extension like ";mode=<typecode>" that
876 * we'll try to get now! */
877 type = strstr(data->state.path, ";mode=");
880 type = strstr(conn->host.rawalloc, ";mode=");
883 *type = 0; /* it was in the middle of the hostname */
884 command = (char) toupper((int) type[6]);
887 case 'A': /* ASCII mode */
888 case 'N': /* NETASCII mode */
889 data->set.prefer_ascii = TRUE;
892 case 'O': /* octet mode */
893 case 'I': /* binary mode */
895 /* switch off ASCII */
896 data->set.prefer_ascii = FALSE;