1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2009, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
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.
13  *
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.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  * $Id: tftp.c,v 1.81 2009-02-14 13:43:18 giva Exp $
22  ***************************************************************************/
23 
24 #include "setup.h"
25 
26 #ifndef CURL_DISABLE_TFTP
27 /* -- WIN32 approved -- */
28 #include <stdio.h>
29 #include <stdarg.h>
30 #include <stdlib.h>
31 #include <ctype.h>
32 
33 #if defined(WIN32)
34 #include <time.h>
35 #include <io.h>
36 #else
37 #ifdef HAVE_SYS_SOCKET_H
38 #include <sys/socket.h>
39 #endif
40 #include <netinet/in.h>
41 #ifdef HAVE_SYS_TIME_H
42 #include <sys/time.h>
43 #endif
44 #ifdef HAVE_UNISTD_H
45 #include <unistd.h>
46 #endif
47 #include <netdb.h>
48 #ifdef HAVE_ARPA_INET_H
49 #include <arpa/inet.h>
50 #endif
51 #ifdef HAVE_NET_IF_H
52 #include <net/if.h>
53 #endif
54 #ifdef HAVE_SYS_IOCTL_H
55 #include <sys/ioctl.h>
56 #endif
57 
58 #ifdef HAVE_SYS_PARAM_H
59 #include <sys/param.h>
60 #endif
61 
62 #endif /* WIN32 */
63 
64 #include "urldata.h"
65 #include <curl/curl.h>
66 #include "transfer.h"
67 #include "sendf.h"
68 #include "tftp.h"
69 #include "progress.h"
70 #include "connect.h"
71 #include "strerror.h"
72 #include "sockaddr.h" /* required for Curl_sockaddr_storage */
73 #include "url.h"
74 #include "rawstr.h"
75 
76 #define _MPRINTF_REPLACE /* use our functions only */
77 #include <curl/mprintf.h>
78 
79 #include "memory.h"
80 #include "select.h"
81 
82 /* The last #include file should be: */
83 #include "memdebug.h"
84 
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"
90 #define TFTP_OPTION_TSIZE "tsize"
91 #define TFTP_OPTION_INTERVAL "interval"
92 
93 typedef enum {
94   TFTP_MODE_NETASCII=0,
95   TFTP_MODE_OCTET
96 } tftp_mode_t;
97 
98 typedef enum {
99   TFTP_STATE_START=0,
100   TFTP_STATE_RX,
101   TFTP_STATE_TX,
102   TFTP_STATE_FIN
103 } tftp_state_t;
104 
105 typedef enum {
106   TFTP_EVENT_INIT=0,
107   TFTP_EVENT_RRQ = 1,
108   TFTP_EVENT_WRQ = 2,
109   TFTP_EVENT_DATA = 3,
110   TFTP_EVENT_ACK = 4,
111   TFTP_EVENT_ERROR = 5,
112   TFTP_EVENT_OACK = 6,
113   TFTP_EVENT_TIMEOUT
114 } tftp_event_t;
115 
116 typedef enum {
117   TFTP_ERR_UNDEF=0,
118   TFTP_ERR_NOTFOUND,
119   TFTP_ERR_PERM,
120   TFTP_ERR_DISKFULL,
121   TFTP_ERR_ILLEGAL,
122   TFTP_ERR_UNKNOWNID,
123   TFTP_ERR_EXISTS,
124   TFTP_ERR_NOSUCHUSER,  /* This will never be triggered by this code */
125 
126   /* The remaining error codes are internal to curl */
127   TFTP_ERR_NONE = -100,
128   TFTP_ERR_TIMEOUT,
129   TFTP_ERR_NORESPONSE
130 } tftp_error_t;
131 
132 typedef struct tftp_packet {
133   unsigned char *data;
134 } tftp_packet_t;
135 
136 typedef struct tftp_state_data {
137   tftp_state_t    state;
138   tftp_mode_t     mode;
139   tftp_error_t    error;
140   struct connectdata      *conn;
141   curl_socket_t   sockfd;
142   int             retries;
143   time_t          retry_time;
144   time_t          retry_max;
145   time_t          start_time;
146   time_t          max_time;
147   unsigned short  block;
148   struct Curl_sockaddr_storage   local_addr;
149   struct Curl_sockaddr_storage   remote_addr;
150   socklen_t       remote_addrlen;
151   ssize_t         rbytes;
152   size_t          sbytes;
153   size_t          blksize;
154   int             requested_blksize;
155   tftp_packet_t   rpacket;
156   tftp_packet_t   spacket;
157 } tftp_state_data_t;
158 
159 
160 /* Forward declarations */
161 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event) ;
162 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event) ;
163 static CURLcode tftp_connect(struct connectdata *conn, bool *done);
164 static CURLcode tftp_disconnect(struct connectdata *conn);
165 static CURLcode tftp_do(struct connectdata *conn, bool *done);
166 static CURLcode tftp_done(struct connectdata *conn,
167                                CURLcode, bool premature);
168 static CURLcode tftp_setup_connection(struct connectdata * conn);
169 
170 
171 /*
172  * TFTP protocol handler.
173  */
174 
175 const struct Curl_handler Curl_handler_tftp = {
176   "TFTP",                               /* scheme */
177   tftp_setup_connection,                /* setup_connection */
178   tftp_do,                              /* do_it */
179   tftp_done,                            /* done */
180   ZERO_NULL,                            /* do_more */
181   tftp_connect,                         /* connect_it */
182   ZERO_NULL,                            /* connecting */
183   ZERO_NULL,                            /* doing */
184   ZERO_NULL,                            /* proto_getsock */
185   ZERO_NULL,                            /* doing_getsock */
186   ZERO_NULL,                            /* perform_getsock */
187   tftp_disconnect,                      /* disconnect */
188   PORT_TFTP,                            /* defport */
189   PROT_TFTP                             /* protocol */
190 };
191 
192 
193 /**********************************************************
194  *
195  * tftp_set_timeouts -
196  *
197  * Set timeouts based on state machine state.
198  * Use user provided connect timeouts until DATA or ACK
199  * packet is received, then use user-provided transfer timeouts
200  *
201  *
202  **********************************************************/
tftp_set_timeouts(tftp_state_data_t * state)203 static CURLcode tftp_set_timeouts(tftp_state_data_t *state)
204 {
205   time_t maxtime, timeout;
206   long timeout_ms;
207   bool start = (bool)(state->state == TFTP_STATE_START);
208 
209   time(&state->start_time);
210 
211   /* Compute drop-dead time */
212   timeout_ms = Curl_timeleft(state->conn, NULL, start);
213 
214   if(timeout_ms < 0) {
215     /* time-out, bail out, go home */
216     failf(state->conn->data, "Connection time-out");
217     return CURLE_OPERATION_TIMEDOUT;
218   }
219 
220   if(start) {
221 
222     maxtime = (time_t)(timeout_ms + 500) / 1000;
223     state->max_time = state->start_time+maxtime;
224 
225     /* Set per-block timeout to total */
226     timeout = maxtime ;
227 
228     /* Average restart after 5 seconds */
229     state->retry_max = timeout/5;
230 
231     if(state->retry_max < 1)
232       /* avoid division by zero below */
233       state->retry_max = 1;
234 
235     /* Compute the re-start interval to suit the timeout */
236     state->retry_time = timeout/state->retry_max;
237     if(state->retry_time<1)
238       state->retry_time=1;
239 
240   }
241   else {
242     if(timeout_ms > 0)
243       maxtime = (time_t)(timeout_ms + 500) / 1000;
244     else
245       maxtime = 3600;
246 
247     state->max_time = state->start_time+maxtime;
248 
249     /* Set per-block timeout to 10% of total */
250     timeout = maxtime/10 ;
251 
252     /* Average reposting an ACK after 15 seconds */
253     state->retry_max = timeout/15;
254   }
255   /* But bound the total number  */
256   if(state->retry_max<3)
257     state->retry_max=3;
258 
259   if(state->retry_max>50)
260     state->retry_max=50;
261 
262   /* Compute the re-ACK interval to suit the timeout */
263   state->retry_time = timeout/state->retry_max;
264   if(state->retry_time<1)
265     state->retry_time=1;
266 
267   infof(state->conn->data,
268         "set timeouts for state %d; Total %d, retry %d maxtry %d\n",
269         state->state, (state->max_time-state->start_time),
270         state->retry_time, state->retry_max);
271 
272   return CURLE_OK;
273 }
274 
275 /**********************************************************
276  *
277  * tftp_set_send_first
278  *
279  * Event handler for the START state
280  *
281  **********************************************************/
282 
setpacketevent(tftp_packet_t * packet,unsigned short num)283 static void setpacketevent(tftp_packet_t *packet, unsigned short num)
284 {
285   packet->data[0] = (unsigned char)(num >> 8);
286   packet->data[1] = (unsigned char)(num & 0xff);
287 }
288 
289 
setpacketblock(tftp_packet_t * packet,unsigned short num)290 static void setpacketblock(tftp_packet_t *packet, unsigned short num)
291 {
292   packet->data[2] = (unsigned char)(num >> 8);
293   packet->data[3] = (unsigned char)(num & 0xff);
294 }
295 
getrpacketevent(const tftp_packet_t * packet)296 static unsigned short getrpacketevent(const tftp_packet_t *packet)
297 {
298   return (unsigned short)((packet->data[0] << 8) | packet->data[1]);
299 }
300 
getrpacketblock(const tftp_packet_t * packet)301 static unsigned short getrpacketblock(const tftp_packet_t *packet)
302 {
303   return (unsigned short)((packet->data[2] << 8) | packet->data[3]);
304 }
305 
Curl_strnlen(const char * string,size_t maxlen)306 static size_t Curl_strnlen(const char *string, size_t maxlen)
307 {
308   const char *end = memchr (string, '\0', maxlen);
309   return end ? (size_t) (end - string) : maxlen;
310 }
311 
tftp_option_get(const char * buf,size_t len,const char ** option,const char ** value)312 static const char *tftp_option_get(const char *buf, size_t len,
313                                    const char **option, const char **value)
314 {
315   size_t loc;
316 
317   loc = Curl_strnlen( buf, len );
318   loc++; /* NULL term */
319 
320   if (loc >= len)
321     return NULL;
322   *option = buf;
323 
324   loc += Curl_strnlen( buf+loc, len-loc );
325   loc++; /* NULL term */
326 
327   if (loc > len)
328     return NULL;
329   *value = &buf[strlen(*option) + 1];
330 
331   return &buf[loc];
332 }
333 
tftp_parse_option_ack(tftp_state_data_t * state,const char * ptr,int len)334 static CURLcode tftp_parse_option_ack(tftp_state_data_t *state,
335                                       const char *ptr, int len)
336 {
337   const char *tmp = ptr;
338   struct SessionHandle *data = state->conn->data;
339 
340   /* if OACK doesn't contain blksize option, the default (512) must be used */
341   state->blksize = TFTP_BLKSIZE_DEFAULT;
342 
343   while (tmp < ptr + len) {
344     const char *option, *value;
345 
346     tmp = tftp_option_get(tmp, ptr + len - tmp, &option, &value);
347     if(tmp == NULL) {
348       failf(data, "Malformed ACK packet, rejecting");
349       return CURLE_TFTP_ILLEGAL;
350     }
351 
352     infof(data, "got option=(%s) value=(%s)\n", option, value);
353 
354     if(checkprefix(option, TFTP_OPTION_BLKSIZE)) {
355       int blksize;
356 
357       blksize = strtol( value, NULL, 10 );
358 
359       if(!blksize) {
360         failf(data, "invalid blocksize value in OACK packet");
361         return CURLE_TFTP_ILLEGAL;
362       }
363       else if(blksize > TFTP_BLKSIZE_MAX) {
364         failf(data, "%s (%d)", "blksize is larger than max supported",
365                 TFTP_BLKSIZE_MAX);
366         return CURLE_TFTP_ILLEGAL;
367       }
368       else if(blksize < TFTP_BLKSIZE_MIN) {
369         failf(data, "%s (%d)", "blksize is smaller than min supported",
370                 TFTP_BLKSIZE_MIN);
371         return CURLE_TFTP_ILLEGAL;
372       }
373       else if (blksize > state->requested_blksize) {
374         /* could realloc pkt buffers here, but the spec doesn't call out
375          * support for the server requesting a bigger blksize than the client
376          * requests */
377         failf(data, "%s (%d)",
378                 "server requested blksize larger than allocated", blksize);
379         return CURLE_TFTP_ILLEGAL;
380       }
381 
382       state->blksize = blksize;
383       infof(data, "%s (%d) %s (%d)\n", "blksize parsed from OACK",
384         state->blksize, "requested", state->requested_blksize);
385     }
386     else if(checkprefix(option, TFTP_OPTION_TSIZE)) {
387       long tsize = 0;
388 
389       tsize = strtol( value, NULL, 10 );
390       if(!tsize) {
391         failf(data, "invalid tsize value in OACK packet");
392         return CURLE_TFTP_ILLEGAL;
393       }
394       Curl_pgrsSetDownloadSize(data, tsize);
395       infof(data, "%s (%d)\n", "tsize parsed from OACK", tsize);
396     }
397   }
398 
399   return CURLE_OK;
400 }
401 
tftp_option_add(tftp_state_data_t * state,size_t csize,char * buf,const char * option)402 static size_t tftp_option_add(tftp_state_data_t *state, size_t csize,
403                               char *buf, const char *option)
404 {
405   if( ( strlen(option) + csize + 1U ) > state->blksize )
406         return 0;
407   strcpy(buf, option);
408   return( strlen(option) + 1 );
409 }
410 
tftp_connect_for_tx(tftp_state_data_t * state,tftp_event_t event)411 static CURLcode tftp_connect_for_tx(tftp_state_data_t *state, tftp_event_t event)
412 {
413   CURLcode res;
414   struct SessionHandle *data = state->conn->data;
415 
416   infof(data, "%s\n", "Connected for transmit");
417   state->state = TFTP_STATE_TX;
418   res = tftp_set_timeouts(state);
419   if(res != CURLE_OK)
420     return(res);
421   return tftp_tx(state, event);
422 }
423 
tftp_connect_for_rx(tftp_state_data_t * state,tftp_event_t event)424 static CURLcode tftp_connect_for_rx(tftp_state_data_t *state, tftp_event_t event)
425 {
426   CURLcode res;
427   struct SessionHandle *data = state->conn->data;
428 
429   infof(data, "%s\n", "Connected for receive");
430   state->state = TFTP_STATE_RX;
431   res = tftp_set_timeouts(state);
432   if(res != CURLE_OK)
433     return(res);
434   return tftp_rx(state, event);
435 }
436 
tftp_send_first(tftp_state_data_t * state,tftp_event_t event)437 static CURLcode tftp_send_first(tftp_state_data_t *state, tftp_event_t event)
438 {
439   int sbytes;
440   const char *mode = "octet";
441   char *filename;
442   char buf[8];
443   struct SessionHandle *data = state->conn->data;
444   CURLcode res = CURLE_OK;
445 
446   /* Set ascii mode if -B flag was used */
447   if(data->set.prefer_ascii)
448     mode = "netascii";
449 
450   switch(event) {
451 
452   case TFTP_EVENT_INIT:    /* Send the first packet out */
453   case TFTP_EVENT_TIMEOUT: /* Resend the first packet out */
454     /* Increment the retry counter, quit if over the limit */
455     state->retries++;
456     if(state->retries>state->retry_max) {
457       state->error = TFTP_ERR_NORESPONSE;
458       state->state = TFTP_STATE_FIN;
459       return res;
460     }
461 
462     if(data->set.upload) {
463       /* If we are uploading, send an WRQ */
464       setpacketevent(&state->spacket, TFTP_EVENT_WRQ);
465       state->conn->data->req.upload_fromhere =
466         (char *)state->spacket.data+4;
467       if(data->set.infilesize != -1)
468         Curl_pgrsSetUploadSize(data, data->set.infilesize);
469     }
470     else {
471       /* If we are downloading, send an RRQ */
472       setpacketevent(&state->spacket, TFTP_EVENT_RRQ);
473     }
474     /* As RFC3617 describes the separator slash is not actually part of the
475        file name so we skip the always-present first letter of the path
476        string. */
477     filename = curl_easy_unescape(data, &state->conn->data->state.path[1], 0,
478                                   NULL);
479     if(!filename)
480       return CURLE_OUT_OF_MEMORY;
481 
482     snprintf((char *)state->spacket.data+2,
483              state->blksize,
484              "%s%c%s%c", filename, '\0',  mode, '\0');
485     sbytes = 4 + strlen(filename) + strlen(mode);
486 
487     /* add tsize option */
488     sbytes += tftp_option_add(state, sbytes,
489                               (char *)state->spacket.data+sbytes,
490                               TFTP_OPTION_TSIZE);
491     sbytes += tftp_option_add(state, sbytes,
492                               (char *)state->spacket.data+sbytes, "0");
493     /* add blksize option */
494     snprintf( buf, sizeof(buf), "%d", state->requested_blksize );
495     sbytes += tftp_option_add(state, sbytes,
496                               (char *)state->spacket.data+sbytes,
497                               TFTP_OPTION_BLKSIZE);
498     sbytes += tftp_option_add(state, sbytes,
499                               (char *)state->spacket.data+sbytes, buf );
500     /* add timeout option */
501     snprintf( buf, sizeof(buf), "%d", state->retry_time );
502     sbytes += tftp_option_add(state, sbytes,
503                               (char *)state->spacket.data+sbytes,
504                               TFTP_OPTION_INTERVAL);
505     sbytes += tftp_option_add(state, sbytes,
506                               (char *)state->spacket.data+sbytes, buf );
507 
508     sbytes = sendto(state->sockfd, (void *)state->spacket.data,
509                     sbytes, 0,
510                     state->conn->ip_addr->ai_addr,
511                     state->conn->ip_addr->ai_addrlen);
512     if(sbytes < 0) {
513       failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
514     }
515     Curl_safefree(filename);
516     break;
517 
518   case TFTP_EVENT_OACK:
519     if(data->set.upload) {
520       res = tftp_connect_for_tx(state, event);
521     }
522     else {
523       res = tftp_connect_for_rx(state, event);
524     }
525     break;
526 
527   case TFTP_EVENT_ACK: /* Connected for transmit */
528     res = tftp_connect_for_tx(state, event);
529     break;
530 
531   case TFTP_EVENT_DATA: /* Connected for receive */
532     res = tftp_connect_for_rx(state, event);
533     break;
534 
535   case TFTP_EVENT_ERROR:
536     state->state = TFTP_STATE_FIN;
537     break;
538 
539   default:
540     failf(state->conn->data, "tftp_send_first: internal error");
541     break;
542   }
543   return res;
544 }
545 
546 /**********************************************************
547  *
548  * tftp_rx
549  *
550  * Event handler for the RX state
551  *
552  **********************************************************/
tftp_rx(tftp_state_data_t * state,tftp_event_t event)553 static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event)
554 {
555   int sbytes;
556   int rblock;
557   struct SessionHandle *data = state->conn->data;
558 
559   switch(event) {
560 
561   case TFTP_EVENT_DATA:
562     /* Is this the block we expect? */
563     rblock = getrpacketblock(&state->rpacket);
564     if((state->block+1) != rblock) {
565       /* No, log it, up the retry count and fail if over the limit */
566       infof(data,
567             "Received unexpected DATA packet block %d\n", rblock);
568       state->retries++;
569       if(state->retries>state->retry_max) {
570         failf(data, "tftp_rx: giving up waiting for block %d",
571               state->block+1);
572         return CURLE_TFTP_ILLEGAL;
573       }
574     }
575     /* This is the expected block.  Reset counters and ACK it. */
576     state->block = (unsigned short)rblock;
577     state->retries = 0;
578     setpacketevent(&state->spacket, TFTP_EVENT_ACK);
579     setpacketblock(&state->spacket, state->block);
580     sbytes = sendto(state->sockfd, (void *)state->spacket.data,
581                     4, SEND_4TH_ARG,
582                     (struct sockaddr *)&state->remote_addr,
583                     state->remote_addrlen);
584     if(sbytes < 0) {
585       failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
586       return CURLE_SEND_ERROR;
587     }
588 
589     /* Check if completed (That is, a less than full packet is received) */
590     if(state->rbytes < (ssize_t)state->blksize+4){
591       state->state = TFTP_STATE_FIN;
592     }
593     else {
594       state->state = TFTP_STATE_RX;
595     }
596     break;
597 
598   case TFTP_EVENT_OACK:
599     /* ACK option acknowledgement so we can move on to data */
600     state->block = 0;
601     state->retries = 0;
602     setpacketevent(&state->spacket, TFTP_EVENT_ACK);
603     setpacketblock(&state->spacket, state->block);
604     sbytes = sendto(state->sockfd, (void *)state->spacket.data,
605                     4, SEND_4TH_ARG,
606                     (struct sockaddr *)&state->remote_addr,
607                     state->remote_addrlen);
608     if(sbytes < 0) {
609       failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
610       return CURLE_SEND_ERROR;
611     }
612 
613     /* we're ready to RX data */
614     state->state = TFTP_STATE_RX;
615     break;
616 
617   case TFTP_EVENT_TIMEOUT:
618     /* Increment the retry count and fail if over the limit */
619     state->retries++;
620     infof(data,
621           "Timeout waiting for block %d ACK.  Retries = %d\n", state->retries);
622     if(state->retries > state->retry_max) {
623       state->error = TFTP_ERR_TIMEOUT;
624       state->state = TFTP_STATE_FIN;
625     }
626     else {
627       /* Resend the previous ACK */
628       sbytes = sendto(state->sockfd, (void *)state->spacket.data,
629                       4, SEND_4TH_ARG,
630                       (struct sockaddr *)&state->remote_addr,
631                       state->remote_addrlen);
632       /* Check all sbytes were sent */
633       if(sbytes<0) {
634         failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
635         return CURLE_SEND_ERROR;
636       }
637     }
638     break;
639 
640   case TFTP_EVENT_ERROR:
641     state->state = TFTP_STATE_FIN;
642     break;
643 
644   default:
645     failf(data, "%s", "tftp_rx: internal error");
646     return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for
647                                   this */
648   }
649   return CURLE_OK;
650 }
651 
652 /**********************************************************
653  *
654  * tftp_tx
655  *
656  * Event handler for the TX state
657  *
658  **********************************************************/
tftp_tx(tftp_state_data_t * state,tftp_event_t event)659 static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event)
660 {
661   struct SessionHandle *data = state->conn->data;
662   int sbytes;
663   int rblock;
664   CURLcode res = CURLE_OK;
665   struct SingleRequest *k = &data->req;
666 
667   switch(event) {
668 
669   case TFTP_EVENT_ACK:
670     /* Ack the packet */
671     rblock = getrpacketblock(&state->rpacket);
672 
673     if(rblock != state->block) {
674       /* This isn't the expected block.  Log it and up the retry counter */
675       infof(data, "Received ACK for block %d, expecting %d\n",
676             rblock, state->block);
677       state->retries++;
678       /* Bail out if over the maximum */
679       if(state->retries>state->retry_max) {
680         failf(data, "tftp_tx: giving up waiting for block %d ack",
681               state->block);
682         res = CURLE_SEND_ERROR;
683       }
684       else {
685         /* Re-send the data packet */
686         sbytes = sendto(state->sockfd, (void *)&state->spacket,
687                         4+state->sbytes, SEND_4TH_ARG,
688                         (struct sockaddr *)&state->remote_addr,
689                         state->remote_addrlen);
690         /* Check all sbytes were sent */
691         if(sbytes<0) {
692           failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
693           res = CURLE_SEND_ERROR;
694         }
695       }
696       return res;
697     }
698     /* This is the expected packet.  Reset the counters and send the next
699        block */
700     state->block++;
701     state->retries = 0;
702     setpacketevent(&state->spacket, TFTP_EVENT_DATA);
703     setpacketblock(&state->spacket, state->block);
704     if(state->block > 1 && state->sbytes < state->blksize) {
705       state->state = TFTP_STATE_FIN;
706       return CURLE_OK;
707     }
708     res = Curl_fillreadbuffer(state->conn, state->blksize,
709                               (int *)&state->sbytes);
710     if(res)
711       return res;
712     sbytes = sendto(state->sockfd, (void *)state->spacket.data,
713                     4+state->sbytes, SEND_4TH_ARG,
714                     (struct sockaddr *)&state->remote_addr,
715                     state->remote_addrlen);
716     /* Check all sbytes were sent */
717     if(sbytes<0) {
718       failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
719       return CURLE_SEND_ERROR;
720     }
721     /* Update the progress meter */
722     k->writebytecount += state->sbytes;
723     Curl_pgrsSetUploadCounter(data, k->writebytecount);
724     break;
725 
726   case TFTP_EVENT_TIMEOUT:
727     /* Increment the retry counter and log the timeout */
728     state->retries++;
729     infof(data, "Timeout waiting for block %d ACK. "
730           " Retries = %d\n", state->retries);
731     /* Decide if we've had enough */
732     if(state->retries > state->retry_max) {
733       state->error = TFTP_ERR_TIMEOUT;
734       state->state = TFTP_STATE_FIN;
735     }
736     else {
737       /* Re-send the data packet */
738       sbytes = sendto(state->sockfd, (void *)state->spacket.data,
739                       4+state->sbytes, SEND_4TH_ARG,
740                       (struct sockaddr *)&state->remote_addr,
741                       state->remote_addrlen);
742       /* Check all sbytes were sent */
743       if(sbytes<0) {
744         failf(data, "%s", Curl_strerror(state->conn, SOCKERRNO));
745         return CURLE_SEND_ERROR;
746       }
747       /* since this was a re-send, we remain at the still byte position */
748       Curl_pgrsSetUploadCounter(data, k->writebytecount);
749     }
750     break;
751 
752   case TFTP_EVENT_ERROR:
753     state->state = TFTP_STATE_FIN;
754     break;
755 
756   default:
757     failf(data, "%s", "tftp_tx: internal error");
758     break;
759   }
760 
761   return res;
762 }
763 
764 /**********************************************************
765  *
766  * tftp_state_machine
767  *
768  * The tftp state machine event dispatcher
769  *
770  **********************************************************/
tftp_state_machine(tftp_state_data_t * state,tftp_event_t event)771 static CURLcode tftp_state_machine(tftp_state_data_t *state,
772                                    tftp_event_t event)
773 {
774   CURLcode res = CURLE_OK;
775   struct SessionHandle *data = state->conn->data;
776   switch(state->state) {
777   case TFTP_STATE_START:
778     DEBUGF(infof(data, "TFTP_STATE_START\n"));
779     res = tftp_send_first(state, event);
780     break;
781   case TFTP_STATE_RX:
782     DEBUGF(infof(data, "TFTP_STATE_RX\n"));
783     res = tftp_rx(state, event);
784     break;
785   case TFTP_STATE_TX:
786     DEBUGF(infof(data, "TFTP_STATE_TX\n"));
787     res = tftp_tx(state, event);
788     break;
789   case TFTP_STATE_FIN:
790     infof(data, "%s\n", "TFTP finished");
791     break;
792   default:
793     DEBUGF(infof(data, "STATE: %d\n", state->state));
794     failf(data, "%s", "Internal state machine error");
795     res = CURLE_TFTP_ILLEGAL;
796     break;
797   }
798   return res;
799 }
800 
801 /**********************************************************
802  *
803  * tftp_disconnect
804  *
805  * The disconnect callback
806  *
807  **********************************************************/
tftp_disconnect(struct connectdata * conn)808 static CURLcode tftp_disconnect(struct connectdata *conn)
809 {
810   tftp_state_data_t *state = conn->proto.tftpc;
811 
812   /* done, free dynamically allocated pkt buffers */
813   if(state) {
814     Curl_safefree(state->rpacket.data);
815     Curl_safefree(state->spacket.data);
816     free(state);
817   }
818 
819   return CURLE_OK;
820 }
821 
822 /**********************************************************
823  *
824  * tftp_connect
825  *
826  * The connect callback
827  *
828  **********************************************************/
tftp_connect(struct connectdata * conn,bool * done)829 static CURLcode tftp_connect(struct connectdata *conn, bool *done)
830 {
831   CURLcode code;
832   tftp_state_data_t *state;
833   int blksize, rc;
834 
835   blksize = TFTP_BLKSIZE_DEFAULT;
836 
837   /* If there already is a protocol-specific struct allocated for this
838      sessionhandle, deal with it */
839   Curl_reset_reqproto(conn);
840 
841   state = conn->proto.tftpc = calloc(sizeof(tftp_state_data_t), 1);
842   if(!state)
843     return CURLE_OUT_OF_MEMORY;
844 
845   /* alloc pkt buffers based on specified blksize */
846   if(conn->data->set.tftp_blksize) {
847     blksize = conn->data->set.tftp_blksize;
848     if(blksize > TFTP_BLKSIZE_MAX || blksize < TFTP_BLKSIZE_MIN )
849       return CURLE_TFTP_ILLEGAL;
850   }
851 
852   if(!state->rpacket.data) {
853     state->rpacket.data = calloc(1, blksize + 2 + 2);
854 
855     if(!state->rpacket.data)
856       return CURLE_OUT_OF_MEMORY;
857   }
858 
859   if(!state->spacket.data) {
860     state->spacket.data = calloc(1, blksize + 2 + 2);
861 
862     if(!state->spacket.data)
863       return CURLE_OUT_OF_MEMORY;
864   }
865 
866   conn->bits.close = FALSE; /* keep it open if possible */
867 
868   state->conn = conn;
869   state->sockfd = state->conn->sock[FIRSTSOCKET];
870   state->state = TFTP_STATE_START;
871   state->error = TFTP_ERR_NONE;
872   state->blksize = TFTP_BLKSIZE_DEFAULT;
873   state->requested_blksize = blksize;
874 
875   ((struct sockaddr *)&state->local_addr)->sa_family =
876     (unsigned short)(conn->ip_addr->ai_family);
877 
878   tftp_set_timeouts(state);
879 
880   if(!conn->bits.bound) {
881     /* If not already bound, bind to any interface, random UDP port. If it is
882      * reused or a custom local port was desired, this has already been done!
883      *
884      * We once used the size of the local_addr struct as the third argument for
885      * bind() to better work with IPv6 or whatever size the struct could have,
886      * but we learned that at least Tru64, AIX and IRIX *requires* the size of
887      * that argument to match the exact size of a 'sockaddr_in' struct when
888      * running IPv4-only.
889      *
890      * Therefore we use the size from the address we connected to, which we
891      * assume uses the same IP version and thus hopefully this works for both
892      * IPv4 and IPv6...
893      */
894     rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr,
895               conn->ip_addr->ai_addrlen);
896     if(rc) {
897       failf(conn->data, "bind() failed; %s",
898             Curl_strerror(conn, SOCKERRNO));
899       return CURLE_COULDNT_CONNECT;
900     }
901     conn->bits.bound = TRUE;
902   }
903 
904   Curl_pgrsStartNow(conn->data);
905 
906   *done = TRUE;
907   code = CURLE_OK;
908   return(code);
909 }
910 
911 /**********************************************************
912  *
913  * tftp_done
914  *
915  * The done callback
916  *
917  **********************************************************/
tftp_done(struct connectdata * conn,CURLcode status,bool premature)918 static CURLcode tftp_done(struct connectdata *conn, CURLcode status,
919                                bool premature)
920 {
921   (void)status; /* unused */
922   (void)premature; /* not used */
923 
924   Curl_pgrsDone(conn);
925 
926   return CURLE_OK;
927 }
928 
929 
930 /**********************************************************
931  *
932  * tftp
933  *
934  * The do callback
935  *
936  * This callback handles the entire TFTP transfer
937  *
938  **********************************************************/
939 
tftp_do(struct connectdata * conn,bool * done)940 static CURLcode tftp_do(struct connectdata *conn, bool *done)
941 {
942   struct SessionHandle  *data = conn->data;
943   tftp_state_data_t     *state;
944   tftp_event_t          event;
945   CURLcode              code;
946   int                   rc;
947   struct Curl_sockaddr_storage fromaddr;
948   socklen_t             fromlen;
949   int                   check_time = 0;
950   struct SingleRequest *k = &data->req;
951 
952   *done = TRUE;
953 
954   /*
955     Since connections can be re-used between SessionHandles, this might be a
956     connection already existing but on a fresh SessionHandle struct so we must
957     make sure we have a good 'struct TFTP' to play with. For new connections,
958     the struct TFTP is allocated and setup in the tftp_connect() function.
959   */
960   Curl_reset_reqproto(conn);
961 
962   if(!conn->proto.tftpc) {
963     code = tftp_connect(conn, done);
964     if(code)
965       return code;
966   }
967   state = (tftp_state_data_t *)conn->proto.tftpc;
968 
969   /* Run the TFTP State Machine */
970   for(code=tftp_state_machine(state, TFTP_EVENT_INIT);
971       (state->state != TFTP_STATE_FIN) && (code == CURLE_OK);
972       code=tftp_state_machine(state, event) ) {
973 
974     /* Wait until ready to read or timeout occurs */
975     rc=Curl_socket_ready(state->sockfd, CURL_SOCKET_BAD,
976                          (int)(state->retry_time * 1000));
977 
978     if(rc == -1) {
979       /* bail out */
980       int error = SOCKERRNO;
981       failf(data, "%s", Curl_strerror(conn, error));
982       event = TFTP_EVENT_ERROR;
983     }
984     else if(rc==0) {
985       /* A timeout occured */
986       event = TFTP_EVENT_TIMEOUT;
987 
988       /* Force a look at transfer timeouts */
989       check_time = 0;
990 
991     }
992     else {
993 
994       /* Receive the packet */
995       fromlen = sizeof(fromaddr);
996       state->rbytes = (ssize_t)recvfrom(state->sockfd,
997                                         (void *)state->rpacket.data,
998                                         state->blksize+4,
999                                         0,
1000                                         (struct sockaddr *)&fromaddr,
1001                                         &fromlen);
1002       if(state->remote_addrlen==0) {
1003         memcpy(&state->remote_addr, &fromaddr, fromlen);
1004         state->remote_addrlen = fromlen;
1005       }
1006 
1007       /* Sanity check packet length */
1008       if(state->rbytes < 4) {
1009         failf(data, "Received too short packet");
1010         /* Not a timeout, but how best to handle it? */
1011         event = TFTP_EVENT_TIMEOUT;
1012       }
1013       else {
1014 
1015         /* The event is given by the TFTP packet time */
1016         event = (tftp_event_t)getrpacketevent(&state->rpacket);
1017 
1018         switch(event) {
1019         case TFTP_EVENT_DATA:
1020           /* Don't pass to the client empty or retransmitted packets */
1021           if(state->rbytes > 4 &&
1022               ((state->block+1) == getrpacketblock(&state->rpacket))) {
1023             code = Curl_client_write(conn, CLIENTWRITE_BODY,
1024                                      (char *)state->rpacket.data+4,
1025                                      state->rbytes-4);
1026             if(code)
1027               return code;
1028             k->bytecount += state->rbytes-4;
1029             Curl_pgrsSetDownloadCounter(data, (curl_off_t) k->bytecount);
1030           }
1031           break;
1032         case TFTP_EVENT_ERROR:
1033           state->error = (tftp_error_t)getrpacketblock(&state->rpacket);
1034           infof(data, "%s\n", (const char *)state->rpacket.data+4);
1035           break;
1036         case TFTP_EVENT_ACK:
1037           break;
1038         case TFTP_EVENT_OACK:
1039           code = tftp_parse_option_ack(state,
1040                                        (const char *)state->rpacket.data+2,
1041                                        state->rbytes-2);
1042           if(code)
1043             return code;
1044           break;
1045         case TFTP_EVENT_RRQ:
1046         case TFTP_EVENT_WRQ:
1047         default:
1048           failf(data, "%s", "Internal error: Unexpected packet");
1049           break;
1050         }
1051 
1052         /* Update the progress meter */
1053         if(Curl_pgrsUpdate(conn))
1054           return CURLE_ABORTED_BY_CALLBACK;
1055       }
1056     }
1057 
1058     /* Check for transfer timeout every 10 blocks, or after timeout */
1059     if(check_time%10==0) {
1060       time_t current;
1061       time(&current);
1062       if(current>state->max_time) {
1063         DEBUGF(infof(data, "timeout: %d > %d\n",
1064                      current, state->max_time));
1065         state->error = TFTP_ERR_TIMEOUT;
1066         state->state = TFTP_STATE_FIN;
1067       }
1068     }
1069 
1070   }
1071   if(code)
1072     return code;
1073 
1074   /* Tell curl we're done */
1075   code = Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1076   if(code)
1077     return code;
1078 
1079   /* If we have encountered an error */
1080   if(state->error != TFTP_ERR_NONE) {
1081 
1082     /* Translate internal error codes to curl error codes */
1083     switch(state->error) {
1084     case TFTP_ERR_NOTFOUND:
1085       code = CURLE_TFTP_NOTFOUND;
1086       break;
1087     case TFTP_ERR_PERM:
1088       code = CURLE_TFTP_PERM;
1089       break;
1090     case TFTP_ERR_DISKFULL:
1091       code = CURLE_REMOTE_DISK_FULL;
1092       break;
1093     case TFTP_ERR_UNDEF:
1094     case TFTP_ERR_ILLEGAL:
1095       code = CURLE_TFTP_ILLEGAL;
1096       break;
1097     case TFTP_ERR_UNKNOWNID:
1098       code = CURLE_TFTP_UNKNOWNID;
1099       break;
1100     case TFTP_ERR_EXISTS:
1101       code = CURLE_REMOTE_FILE_EXISTS;
1102       break;
1103     case TFTP_ERR_NOSUCHUSER:
1104       code = CURLE_TFTP_NOSUCHUSER;
1105       break;
1106     case TFTP_ERR_TIMEOUT:
1107       code = CURLE_OPERATION_TIMEDOUT;
1108       break;
1109     case TFTP_ERR_NORESPONSE:
1110       code = CURLE_COULDNT_CONNECT;
1111       break;
1112     default:
1113       code= CURLE_ABORTED_BY_CALLBACK;
1114       break;
1115     }
1116   }
1117   else
1118     code = CURLE_OK;
1119   return code;
1120 }
1121 
tftp_setup_connection(struct connectdata * conn)1122 static CURLcode tftp_setup_connection(struct connectdata * conn)
1123 {
1124   struct SessionHandle *data = conn->data;
1125   char * type;
1126   char command;
1127 
1128   conn->socktype = SOCK_DGRAM;   /* UDP datagram based */
1129 
1130   /* TFTP URLs support an extension like ";mode=<typecode>" that
1131    * we'll try to get now! */
1132   type = strstr(data->state.path, ";mode=");
1133 
1134   if(!type)
1135     type = strstr(conn->host.rawalloc, ";mode=");
1136 
1137   if(type) {
1138     *type = 0;                   /* it was in the middle of the hostname */
1139     command = Curl_raw_toupper(type[6]);
1140 
1141     switch (command) {
1142     case 'A': /* ASCII mode */
1143     case 'N': /* NETASCII mode */
1144       data->set.prefer_ascii = TRUE;
1145       break;
1146 
1147     case 'O': /* octet mode */
1148     case 'I': /* binary mode */
1149     default:
1150       /* switch off ASCII */
1151       data->set.prefer_ascii = FALSE;
1152       break;
1153     }
1154   }
1155 
1156   return CURLE_OK;
1157 }
1158 #endif
1159