Coverage Report

Created: 2025-07-18 07:19

/src/curl/lib/tftp.c
Line
Count
Source (jump to first uncovered line)
1
/***************************************************************************
2
 *                                  _   _ ____  _
3
 *  Project                     ___| | | |  _ \| |
4
 *                             / __| | | | |_) | |
5
 *                            | (__| |_| |  _ <| |___
6
 *                             \___|\___/|_| \_\_____|
7
 *
8
 * Copyright (C) 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 https://curl.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
 * SPDX-License-Identifier: curl
22
 *
23
 ***************************************************************************/
24
25
#include "curl_setup.h"
26
27
#ifndef CURL_DISABLE_TFTP
28
29
#ifdef HAVE_NETINET_IN_H
30
#include <netinet/in.h>
31
#endif
32
#ifdef HAVE_NETDB_H
33
#include <netdb.h>
34
#endif
35
#ifdef HAVE_ARPA_INET_H
36
#include <arpa/inet.h>
37
#endif
38
#ifdef HAVE_NET_IF_H
39
#include <net/if.h>
40
#endif
41
#ifdef HAVE_SYS_IOCTL_H
42
#include <sys/ioctl.h>
43
#endif
44
45
#ifdef HAVE_SYS_PARAM_H
46
#include <sys/param.h>
47
#endif
48
49
#include "urldata.h"
50
#include <curl/curl.h>
51
#include "cfilters.h"
52
#include "cf-socket.h"
53
#include "transfer.h"
54
#include "sendf.h"
55
#include "tftp.h"
56
#include "progress.h"
57
#include "connect.h"
58
#include "strerror.h"
59
#include "sockaddr.h" /* required for Curl_sockaddr_storage */
60
#include "multiif.h"
61
#include "url.h"
62
#include "strcase.h"
63
#include "speedcheck.h"
64
#include "select.h"
65
#include "escape.h"
66
#include "curlx/strparse.h"
67
68
/* The last 3 #include files should be in this order */
69
#include "curl_printf.h"
70
#include "curl_memory.h"
71
#include "memdebug.h"
72
73
/* RFC2348 allows the block size to be negotiated */
74
3.62k
#define TFTP_BLKSIZE_DEFAULT 512
75
679
#define TFTP_OPTION_BLKSIZE "blksize"
76
77
/* from RFC2349: */
78
681
#define TFTP_OPTION_TSIZE    "tsize"
79
677
#define TFTP_OPTION_INTERVAL "timeout"
80
81
typedef enum {
82
  TFTP_MODE_NETASCII = 0,
83
  TFTP_MODE_OCTET
84
} tftp_mode_t;
85
86
typedef enum {
87
  TFTP_STATE_START = 0,
88
  TFTP_STATE_RX,
89
  TFTP_STATE_TX,
90
  TFTP_STATE_FIN
91
} tftp_state_t;
92
93
typedef enum {
94
  TFTP_EVENT_NONE = -1,
95
  TFTP_EVENT_INIT = 0,
96
  TFTP_EVENT_RRQ = 1,
97
  TFTP_EVENT_WRQ = 2,
98
  TFTP_EVENT_DATA = 3,
99
  TFTP_EVENT_ACK = 4,
100
  TFTP_EVENT_ERROR = 5,
101
  TFTP_EVENT_OACK = 6,
102
  TFTP_EVENT_TIMEOUT
103
} tftp_event_t;
104
105
typedef enum {
106
  TFTP_ERR_UNDEF = 0,
107
  TFTP_ERR_NOTFOUND,
108
  TFTP_ERR_PERM,
109
  TFTP_ERR_DISKFULL,
110
  TFTP_ERR_ILLEGAL,
111
  TFTP_ERR_UNKNOWNID,
112
  TFTP_ERR_EXISTS,
113
  TFTP_ERR_NOSUCHUSER,  /* This will never be triggered by this code */
114
115
  /* The remaining error codes are internal to curl */
116
  TFTP_ERR_NONE = -100,
117
  TFTP_ERR_TIMEOUT,
118
  TFTP_ERR_NORESPONSE
119
} tftp_error_t;
120
121
struct tftp_packet {
122
  unsigned char *data;
123
};
124
125
/* meta key for storing protocol meta at connection */
126
7.70k
#define CURL_META_TFTP_CONN   "meta:proto:tftp:conn"
127
128
struct tftp_conn {
129
  tftp_state_t    state;
130
  tftp_mode_t     mode;
131
  tftp_error_t    error;
132
  tftp_event_t    event;
133
  struct Curl_easy *data;
134
  curl_socket_t   sockfd;
135
  int             retries;
136
  int             retry_time;
137
  int             retry_max;
138
  time_t          rx_time;
139
  struct Curl_sockaddr_storage   local_addr;
140
  struct Curl_sockaddr_storage   remote_addr;
141
  curl_socklen_t  remote_addrlen;
142
  int             rbytes;
143
  size_t          sbytes;
144
  unsigned int    blksize;
145
  unsigned int    requested_blksize;
146
  unsigned short  block;
147
  struct tftp_packet rpacket;
148
  struct tftp_packet spacket;
149
};
150
151
152
/* Forward declarations */
153
static CURLcode tftp_rx(struct tftp_conn *state, tftp_event_t event);
154
static CURLcode tftp_tx(struct tftp_conn *state, tftp_event_t event);
155
static CURLcode tftp_connect(struct Curl_easy *data, bool *done);
156
static CURLcode tftp_do(struct Curl_easy *data, bool *done);
157
static CURLcode tftp_done(struct Curl_easy *data,
158
                          CURLcode, bool premature);
159
static CURLcode tftp_setup_connection(struct Curl_easy *data,
160
                                      struct connectdata *conn);
161
static CURLcode tftp_multi_statemach(struct Curl_easy *data, bool *done);
162
static CURLcode tftp_doing(struct Curl_easy *data, bool *dophase_done);
163
static int tftp_getsock(struct Curl_easy *data, struct connectdata *conn,
164
                        curl_socket_t *socks);
165
static CURLcode tftp_translate_code(tftp_error_t error);
166
167
168
/*
169
 * TFTP protocol handler.
170
 */
171
172
const struct Curl_handler Curl_handler_tftp = {
173
  "tftp",                               /* scheme */
174
  tftp_setup_connection,                /* setup_connection */
175
  tftp_do,                              /* do_it */
176
  tftp_done,                            /* done */
177
  ZERO_NULL,                            /* do_more */
178
  tftp_connect,                         /* connect_it */
179
  tftp_multi_statemach,                 /* connecting */
180
  tftp_doing,                           /* doing */
181
  tftp_getsock,                         /* proto_getsock */
182
  tftp_getsock,                         /* doing_getsock */
183
  ZERO_NULL,                            /* domore_getsock */
184
  ZERO_NULL,                            /* perform_getsock */
185
  ZERO_NULL,                            /* disconnect */
186
  ZERO_NULL,                            /* write_resp */
187
  ZERO_NULL,                            /* write_resp_hd */
188
  ZERO_NULL,                            /* connection_check */
189
  ZERO_NULL,                            /* attach connection */
190
  ZERO_NULL,                            /* follow */
191
  PORT_TFTP,                            /* defport */
192
  CURLPROTO_TFTP,                       /* protocol */
193
  CURLPROTO_TFTP,                       /* family */
194
  PROTOPT_NOTCPPROXY | PROTOPT_NOURLQUERY /* flags */
195
};
196
197
/**********************************************************
198
 *
199
 * tftp_set_timeouts -
200
 *
201
 * Set timeouts based on state machine state.
202
 * Use user provided connect timeouts until DATA or ACK
203
 * packet is received, then use user-provided transfer timeouts
204
 *
205
 *
206
 **********************************************************/
207
static CURLcode tftp_set_timeouts(struct tftp_conn *state)
208
1.44k
{
209
1.44k
  time_t maxtime, timeout;
210
1.44k
  timediff_t timeout_ms;
211
1.44k
  bool start = (state->state == TFTP_STATE_START);
212
213
  /* Compute drop-dead time */
214
1.44k
  timeout_ms = Curl_timeleft(state->data, NULL, start);
215
216
1.44k
  if(timeout_ms < 0) {
217
    /* time-out, bail out, go home */
218
0
    failf(state->data, "Connection time-out");
219
0
    return CURLE_OPERATION_TIMEDOUT;
220
0
  }
221
222
1.44k
  if(timeout_ms > 0)
223
1.44k
    maxtime = (time_t)(timeout_ms + 500) / 1000;
224
0
  else
225
0
    maxtime = 3600; /* use for calculating block timeouts */
226
227
  /* Set per-block timeout to total */
228
1.44k
  timeout = maxtime;
229
230
  /* Average reposting an ACK after 5 seconds */
231
1.44k
  state->retry_max = (int)timeout/5;
232
233
  /* But bound the total number */
234
1.44k
  if(state->retry_max < 3)
235
1.44k
    state->retry_max = 3;
236
237
1.44k
  if(state->retry_max > 50)
238
0
    state->retry_max = 50;
239
240
  /* Compute the re-ACK interval to suit the timeout */
241
1.44k
  state->retry_time = (int)(timeout/state->retry_max);
242
1.44k
  if(state->retry_time < 1)
243
1.44k
    state->retry_time = 1;
244
245
1.44k
  infof(state->data,
246
1.44k
        "set timeouts for state %d; Total % " FMT_OFF_T ", retry %d maxtry %d",
247
1.44k
        (int)state->state, timeout_ms, state->retry_time, state->retry_max);
248
249
  /* init RX time */
250
1.44k
  state->rx_time = time(NULL);
251
252
1.44k
  return CURLE_OK;
253
1.44k
}
254
255
/**********************************************************
256
 *
257
 * tftp_set_send_first
258
 *
259
 * Event handler for the START state
260
 *
261
 **********************************************************/
262
263
static void setpacketevent(struct tftp_packet *packet, unsigned short num)
264
1.22k
{
265
1.22k
  packet->data[0] = (unsigned char)(num >> 8);
266
1.22k
  packet->data[1] = (unsigned char)(num & 0xff);
267
1.22k
}
268
269
270
static void setpacketblock(struct tftp_packet *packet, unsigned short num)
271
497
{
272
497
  packet->data[2] = (unsigned char)(num >> 8);
273
497
  packet->data[3] = (unsigned char)(num & 0xff);
274
497
}
275
276
static unsigned short getrpacketevent(const struct tftp_packet *packet)
277
3.19k
{
278
3.19k
  return (unsigned short)((packet->data[0] << 8) | packet->data[1]);
279
3.19k
}
280
281
static unsigned short getrpacketblock(const struct tftp_packet *packet)
282
742
{
283
742
  return (unsigned short)((packet->data[2] << 8) | packet->data[3]);
284
742
}
285
286
static size_t tftp_strnlen(const char *string, size_t maxlen)
287
46.4k
{
288
46.4k
  const char *end = memchr(string, '\0', maxlen);
289
46.4k
  return end ? (size_t) (end - string) : maxlen;
290
46.4k
}
291
292
static const char *tftp_option_get(const char *buf, size_t len,
293
                                   const char **option, const char **value)
294
23.2k
{
295
23.2k
  size_t loc;
296
297
23.2k
  loc = tftp_strnlen(buf, len);
298
23.2k
  loc++; /* NULL term */
299
300
23.2k
  if(loc >= len)
301
24
    return NULL;
302
23.2k
  *option = buf;
303
304
23.2k
  loc += tftp_strnlen(buf + loc, len-loc);
305
23.2k
  loc++; /* NULL term */
306
307
23.2k
  if(loc > len)
308
12
    return NULL;
309
23.2k
  *value = &buf[strlen(*option) + 1];
310
311
23.2k
  return &buf[loc];
312
23.2k
}
313
314
static CURLcode tftp_parse_option_ack(struct tftp_conn *state,
315
                                      const char *ptr, int len)
316
226
{
317
226
  const char *tmp = ptr;
318
226
  struct Curl_easy *data = state->data;
319
320
  /* if OACK does not contain blksize option, the default (512) must be used */
321
226
  state->blksize = TFTP_BLKSIZE_DEFAULT;
322
323
23.4k
  while(tmp < ptr + len) {
324
23.2k
    const char *option, *value;
325
326
23.2k
    tmp = tftp_option_get(tmp, ptr + len - tmp, &option, &value);
327
23.2k
    if(!tmp) {
328
36
      failf(data, "Malformed ACK packet, rejecting");
329
36
      return CURLE_TFTP_ILLEGAL;
330
36
    }
331
332
23.2k
    infof(data, "got option=(%s) value=(%s)", option, value);
333
334
23.2k
    if(checkprefix(TFTP_OPTION_BLKSIZE, option)) {
335
0
      curl_off_t blksize;
336
0
      if(curlx_str_number(&value, &blksize, TFTP_BLKSIZE_MAX)) {
337
0
        failf(data, "%s (%d)", "blksize is larger than max supported",
338
0
              TFTP_BLKSIZE_MAX);
339
0
        return CURLE_TFTP_ILLEGAL;
340
0
      }
341
0
      if(!blksize) {
342
0
        failf(data, "invalid blocksize value in OACK packet");
343
0
        return CURLE_TFTP_ILLEGAL;
344
0
      }
345
0
      else if(blksize < TFTP_BLKSIZE_MIN) {
346
0
        failf(data, "%s (%d)", "blksize is smaller than min supported",
347
0
              TFTP_BLKSIZE_MIN);
348
0
        return CURLE_TFTP_ILLEGAL;
349
0
      }
350
0
      else if(blksize > state->requested_blksize) {
351
        /* could realloc pkt buffers here, but the spec does not call out
352
         * support for the server requesting a bigger blksize than the client
353
         * requests */
354
0
        failf(data, "server requested blksize larger than allocated (%"
355
0
              CURL_FORMAT_CURL_OFF_T ")", blksize);
356
0
        return CURLE_TFTP_ILLEGAL;
357
0
      }
358
359
0
      state->blksize = (int)blksize;
360
0
      infof(data, "blksize parsed from OACK (%d) requested (%d)",
361
0
            state->blksize, state->requested_blksize);
362
0
    }
363
23.2k
    else if(checkprefix(TFTP_OPTION_TSIZE, option)) {
364
0
      curl_off_t tsize = 0;
365
      /* tsize should be ignored on upload: Who cares about the size of the
366
         remote file? */
367
0
      if(!data->state.upload &&
368
0
         !curlx_str_number(&value, &tsize, CURL_OFF_T_MAX)) {
369
0
        if(!tsize) {
370
0
          failf(data, "invalid tsize -:%s:- value in OACK packet", value);
371
0
          return CURLE_TFTP_ILLEGAL;
372
0
        }
373
0
        infof(data, "tsize parsed from OACK (%" CURL_FORMAT_CURL_OFF_T ")",
374
0
              tsize);
375
0
        Curl_pgrsSetDownloadSize(data, tsize);
376
0
      }
377
0
    }
378
23.2k
  }
379
380
190
  return CURLE_OK;
381
226
}
382
383
static CURLcode tftp_option_add(struct tftp_conn *state, size_t *csize,
384
                                char *buf, const char *option)
385
4.07k
{
386
4.07k
  if(( strlen(option) + *csize + 1) > (size_t)state->blksize)
387
4
    return CURLE_TFTP_ILLEGAL;
388
4.06k
  strcpy(buf, option);
389
4.06k
  *csize += strlen(option) + 1;
390
4.06k
  return CURLE_OK;
391
4.07k
}
392
393
static CURLcode tftp_connect_for_tx(struct tftp_conn *state,
394
                                    tftp_event_t event)
395
222
{
396
222
  CURLcode result;
397
222
#ifndef CURL_DISABLE_VERBOSE_STRINGS
398
222
  struct Curl_easy *data = state->data;
399
400
222
  infof(data, "%s", "Connected for transmit");
401
222
#endif
402
222
  state->state = TFTP_STATE_TX;
403
222
  result = tftp_set_timeouts(state);
404
222
  if(result)
405
0
    return result;
406
222
  return tftp_tx(state, event);
407
222
}
408
409
static CURLcode tftp_connect_for_rx(struct tftp_conn *state,
410
                                    tftp_event_t event)
411
93
{
412
93
  CURLcode result;
413
93
#ifndef CURL_DISABLE_VERBOSE_STRINGS
414
93
  struct Curl_easy *data = state->data;
415
416
93
  infof(data, "%s", "Connected for receive");
417
93
#endif
418
93
  state->state = TFTP_STATE_RX;
419
93
  result = tftp_set_timeouts(state);
420
93
  if(result)
421
0
    return result;
422
93
  return tftp_rx(state, event);
423
93
}
424
425
static CURLcode tftp_send_first(struct tftp_conn *state,
426
                                tftp_event_t event)
427
1.82k
{
428
1.82k
  size_t sbytes;
429
1.82k
  ssize_t senddata;
430
1.82k
  const char *mode = "octet";
431
1.82k
  char *filename;
432
1.82k
  struct Curl_easy *data = state->data;
433
1.82k
  const struct Curl_sockaddr_ex *remote_addr = NULL;
434
1.82k
  CURLcode result = CURLE_OK;
435
436
  /* Set ASCII mode if -B flag was used */
437
1.82k
  if(data->state.prefer_ascii)
438
559
    mode = "netascii";
439
440
1.82k
  switch(event) {
441
442
541
  case TFTP_EVENT_INIT:    /* Send the first packet out */
443
828
  case TFTP_EVENT_TIMEOUT: /* Resend the first packet out */
444
    /* Increment the retry counter, quit if over the limit */
445
828
    state->retries++;
446
828
    if(state->retries > state->retry_max) {
447
101
      state->error = TFTP_ERR_NORESPONSE;
448
101
      state->state = TFTP_STATE_FIN;
449
101
      return result;
450
101
    }
451
452
727
    if(data->state.upload) {
453
      /* If we are uploading, send an WRQ */
454
143
      setpacketevent(&state->spacket, TFTP_EVENT_WRQ);
455
143
      if(data->state.infilesize != -1)
456
143
        Curl_pgrsSetUploadSize(data, data->state.infilesize);
457
143
    }
458
584
    else {
459
      /* If we are downloading, send an RRQ */
460
584
      setpacketevent(&state->spacket, TFTP_EVENT_RRQ);
461
584
    }
462
    /* As RFC3617 describes the separator slash is not actually part of the
463
       filename so we skip the always-present first letter of the path
464
       string. */
465
727
    result = Curl_urldecode(&state->data->state.up.path[1], 0,
466
727
                            &filename, NULL, REJECT_ZERO);
467
727
    if(result)
468
1
      return result;
469
470
726
    if(strlen(filename) > (state->blksize - strlen(mode) - 4)) {
471
15
      failf(data, "TFTP filename too long");
472
15
      free(filename);
473
15
      return CURLE_TFTP_ILLEGAL; /* too long filename field */
474
15
    }
475
476
711
    msnprintf((char *)state->spacket.data + 2,
477
711
              state->blksize,
478
711
              "%s%c%s%c", filename, '\0',  mode, '\0');
479
711
    sbytes = 4 + strlen(filename) + strlen(mode);
480
481
    /* optional addition of TFTP options */
482
711
    if(!data->set.tftp_no_options) {
483
681
      char buf[64];
484
      /* add tsize option */
485
681
      msnprintf(buf, sizeof(buf), "%" FMT_OFF_T,
486
681
                data->state.upload && (data->state.infilesize != -1) ?
487
539
                data->state.infilesize : 0);
488
489
681
      result = tftp_option_add(state, &sbytes,
490
681
                               (char *)state->spacket.data + sbytes,
491
681
                               TFTP_OPTION_TSIZE);
492
681
      if(result == CURLE_OK)
493
680
        result = tftp_option_add(state, &sbytes,
494
680
                                 (char *)state->spacket.data + sbytes, buf);
495
496
      /* add blksize option */
497
681
      msnprintf(buf, sizeof(buf), "%d", state->requested_blksize);
498
681
      if(result == CURLE_OK)
499
679
        result = tftp_option_add(state, &sbytes,
500
679
                                 (char *)state->spacket.data + sbytes,
501
679
                                 TFTP_OPTION_BLKSIZE);
502
681
      if(result == CURLE_OK)
503
678
        result = tftp_option_add(state, &sbytes,
504
678
                                 (char *)state->spacket.data + sbytes, buf);
505
506
      /* add timeout option */
507
681
      msnprintf(buf, sizeof(buf), "%d", state->retry_time);
508
681
      if(result == CURLE_OK)
509
677
        result = tftp_option_add(state, &sbytes,
510
677
                                 (char *)state->spacket.data + sbytes,
511
677
                                 TFTP_OPTION_INTERVAL);
512
681
      if(result == CURLE_OK)
513
677
        result = tftp_option_add(state, &sbytes,
514
677
                                 (char *)state->spacket.data + sbytes, buf);
515
516
681
      if(result != CURLE_OK) {
517
4
        failf(data, "TFTP buffer too small for options");
518
4
        free(filename);
519
4
        return CURLE_TFTP_ILLEGAL;
520
4
      }
521
681
    }
522
523
    /* the typecase for the 3rd argument is mostly for systems that do
524
       not have a size_t argument, like older unixes that want an 'int' */
525
#ifdef __AMIGA__
526
#define CURL_SENDTO_ARG5(x) CURL_UNCONST(x)
527
#else
528
707
#define CURL_SENDTO_ARG5(x) (x)
529
707
#endif
530
707
    remote_addr = Curl_conn_get_remote_addr(data, FIRSTSOCKET);
531
707
    if(!remote_addr)
532
0
      return CURLE_FAILED_INIT;
533
534
707
    senddata = sendto(state->sockfd, (void *)state->spacket.data,
535
707
                      (SEND_TYPE_ARG3)sbytes, 0,
536
707
                      CURL_SENDTO_ARG5(&remote_addr->curl_sa_addr),
537
707
                      (curl_socklen_t)remote_addr->addrlen);
538
707
    if(senddata != (ssize_t)sbytes) {
539
707
      char buffer[STRERROR_LEN];
540
707
      failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
541
707
    }
542
707
    free(filename);
543
707
    break;
544
545
39
  case TFTP_EVENT_OACK:
546
39
    if(data->state.upload) {
547
15
      result = tftp_connect_for_tx(state, event);
548
15
    }
549
24
    else {
550
24
      result = tftp_connect_for_rx(state, event);
551
24
    }
552
39
    break;
553
554
207
  case TFTP_EVENT_ACK: /* Connected for transmit */
555
207
    result = tftp_connect_for_tx(state, event);
556
207
    break;
557
558
69
  case TFTP_EVENT_DATA: /* Connected for receive */
559
69
    result = tftp_connect_for_rx(state, event);
560
69
    break;
561
562
28
  case TFTP_EVENT_ERROR:
563
28
    state->state = TFTP_STATE_FIN;
564
28
    break;
565
566
649
  default:
567
649
    failf(state->data, "tftp_send_first: internal error");
568
649
    break;
569
1.82k
  }
570
571
1.69k
  return result;
572
1.82k
}
573
574
/* the next blocknum is x + 1 but it needs to wrap at an unsigned 16bit
575
   boundary */
576
403
#define NEXT_BLOCKNUM(x) (((x) + 1)&0xffff)
577
578
/**********************************************************
579
 *
580
 * tftp_rx
581
 *
582
 * Event handler for the RX state
583
 *
584
 **********************************************************/
585
static CURLcode tftp_rx(struct tftp_conn *state, tftp_event_t event)
586
303
{
587
303
  ssize_t sbytes;
588
303
  int rblock;
589
303
  struct Curl_easy *data = state->data;
590
303
  char buffer[STRERROR_LEN];
591
592
303
  switch(event) {
593
594
128
  case TFTP_EVENT_DATA:
595
    /* Is this the block we expect? */
596
128
    rblock = getrpacketblock(&state->rpacket);
597
128
    if(NEXT_BLOCKNUM(state->block) == rblock) {
598
      /* This is the expected block. Reset counters and ACK it. */
599
58
      state->retries = 0;
600
58
    }
601
70
    else if(state->block == rblock) {
602
      /* This is the last recently received block again. Log it and ACK it
603
         again. */
604
40
      infof(data, "Received last DATA packet block %d again.", rblock);
605
40
    }
606
30
    else {
607
      /* totally unexpected, just log it */
608
30
      infof(data,
609
30
            "Received unexpected DATA packet block %d, expecting block %d",
610
30
            rblock, NEXT_BLOCKNUM(state->block));
611
30
      break;
612
30
    }
613
614
    /* ACK this block. */
615
98
    state->block = (unsigned short)rblock;
616
98
    setpacketevent(&state->spacket, TFTP_EVENT_ACK);
617
98
    setpacketblock(&state->spacket, state->block);
618
98
    sbytes = sendto(state->sockfd, (void *)state->spacket.data,
619
98
                    4, SEND_4TH_ARG,
620
98
                    (struct sockaddr *)&state->remote_addr,
621
98
                    state->remote_addrlen);
622
98
    if(sbytes < 0) {
623
0
      failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
624
0
      return CURLE_SEND_ERROR;
625
0
    }
626
627
    /* Check if completed (That is, a less than full packet is received) */
628
98
    if(state->rbytes < (ssize_t)state->blksize + 4) {
629
46
      state->state = TFTP_STATE_FIN;
630
46
    }
631
52
    else {
632
52
      state->state = TFTP_STATE_RX;
633
52
    }
634
98
    state->rx_time = time(NULL);
635
98
    break;
636
637
69
  case TFTP_EVENT_OACK:
638
    /* ACK option acknowledgement so we can move on to data */
639
69
    state->block = 0;
640
69
    state->retries = 0;
641
69
    setpacketevent(&state->spacket, TFTP_EVENT_ACK);
642
69
    setpacketblock(&state->spacket, state->block);
643
69
    sbytes = sendto(state->sockfd, (void *)state->spacket.data,
644
69
                    4, SEND_4TH_ARG,
645
69
                    (struct sockaddr *)&state->remote_addr,
646
69
                    state->remote_addrlen);
647
69
    if(sbytes < 0) {
648
0
      failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
649
0
      return CURLE_SEND_ERROR;
650
0
    }
651
652
    /* we are ready to RX data */
653
69
    state->state = TFTP_STATE_RX;
654
69
    state->rx_time = time(NULL);
655
69
    break;
656
657
89
  case TFTP_EVENT_TIMEOUT:
658
    /* Increment the retry count and fail if over the limit */
659
89
    state->retries++;
660
89
    infof(data,
661
89
          "Timeout waiting for block %d ACK. Retries = %d",
662
89
          NEXT_BLOCKNUM(state->block), state->retries);
663
89
    if(state->retries > state->retry_max) {
664
26
      state->error = TFTP_ERR_TIMEOUT;
665
26
      state->state = TFTP_STATE_FIN;
666
26
    }
667
63
    else {
668
      /* Resend the previous ACK */
669
63
      sbytes = sendto(state->sockfd, (void *)state->spacket.data,
670
63
                      4, SEND_4TH_ARG,
671
63
                      (struct sockaddr *)&state->remote_addr,
672
63
                      state->remote_addrlen);
673
63
      if(sbytes < 0) {
674
0
        failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
675
0
        return CURLE_SEND_ERROR;
676
0
      }
677
63
    }
678
89
    break;
679
680
89
  case TFTP_EVENT_ERROR:
681
6
    setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
682
6
    setpacketblock(&state->spacket, state->block);
683
6
    (void)sendto(state->sockfd, (void *)state->spacket.data,
684
6
                 4, SEND_4TH_ARG,
685
6
                 (struct sockaddr *)&state->remote_addr,
686
6
                 state->remote_addrlen);
687
    /* do not bother with the return code, but if the socket is still up we
688
     * should be a good TFTP client and let the server know we are done */
689
6
    state->state = TFTP_STATE_FIN;
690
6
    break;
691
692
11
  default:
693
11
    failf(data, "%s", "tftp_rx: internal error");
694
11
    return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for
695
                                  this */
696
303
  }
697
292
  return CURLE_OK;
698
303
}
699
700
/**********************************************************
701
 *
702
 * tftp_tx
703
 *
704
 * Event handler for the TX state
705
 *
706
 **********************************************************/
707
static CURLcode tftp_tx(struct tftp_conn *state, tftp_event_t event)
708
2.86k
{
709
2.86k
  struct Curl_easy *data = state->data;
710
2.86k
  ssize_t sbytes;
711
2.86k
  CURLcode result = CURLE_OK;
712
2.86k
  struct SingleRequest *k = &data->req;
713
2.86k
  size_t cb; /* Bytes currently read */
714
2.86k
  char buffer[STRERROR_LEN];
715
2.86k
  char *bufptr;
716
2.86k
  bool eos;
717
718
2.86k
  switch(event) {
719
720
305
  case TFTP_EVENT_ACK:
721
426
  case TFTP_EVENT_OACK:
722
426
    if(event == TFTP_EVENT_ACK) {
723
      /* Ack the packet */
724
305
      int rblock = getrpacketblock(&state->rpacket);
725
726
305
      if(rblock != state->block &&
727
         /* There is a bug in tftpd-hpa that causes it to send us an ack for
728
          * 65535 when the block number wraps to 0. So when we are expecting
729
          * 0, also accept 65535. See
730
          * https://www.syslinux.org/archives/2010-September/015612.html
731
          * */
732
305
         !(state->block == 0 && rblock == 65535)) {
733
        /* This is not the expected block. Log it and up the retry counter */
734
109
        infof(data, "Received ACK for block %d, expecting %d",
735
109
              rblock, state->block);
736
109
        state->retries++;
737
        /* Bail out if over the maximum */
738
109
        if(state->retries > state->retry_max) {
739
2
          failf(data, "tftp_tx: giving up waiting for block %d ack",
740
2
                state->block);
741
2
          result = CURLE_SEND_ERROR;
742
2
        }
743
107
        else {
744
          /* Re-send the data packet */
745
107
          sbytes = sendto(state->sockfd, (void *)state->spacket.data,
746
107
                          4 + (SEND_TYPE_ARG3)state->sbytes, SEND_4TH_ARG,
747
107
                          (struct sockaddr *)&state->remote_addr,
748
107
                          state->remote_addrlen);
749
          /* Check all sbytes were sent */
750
107
          if(sbytes < 0) {
751
0
            failf(data, "%s", Curl_strerror(SOCKERRNO,
752
0
                                            buffer, sizeof(buffer)));
753
0
            result = CURLE_SEND_ERROR;
754
0
          }
755
107
        }
756
757
109
        return result;
758
109
      }
759
      /* This is the expected packet. Reset the counters and send the next
760
         block */
761
196
      state->rx_time = time(NULL);
762
196
      state->block++;
763
196
    }
764
121
    else
765
121
      state->block = 1; /* first data block is 1 when using OACK */
766
767
317
    state->retries = 0;
768
317
    setpacketevent(&state->spacket, TFTP_EVENT_DATA);
769
317
    setpacketblock(&state->spacket, state->block);
770
317
    if(state->block > 1 && state->sbytes < state->blksize) {
771
6
      state->state = TFTP_STATE_FIN;
772
6
      return CURLE_OK;
773
6
    }
774
775
    /* TFTP considers data block size < 512 bytes as an end of session. So
776
     * in some cases we must wait for additional data to build full (512 bytes)
777
     * data block.
778
     * */
779
311
    state->sbytes = 0;
780
311
    bufptr = (char *)state->spacket.data + 4;
781
471
    do {
782
471
      result = Curl_client_read(data, bufptr, state->blksize - state->sbytes,
783
471
                                &cb, &eos);
784
471
      if(result)
785
18
        return result;
786
453
      state->sbytes += cb;
787
453
      bufptr += cb;
788
453
    } while(state->sbytes < state->blksize && cb);
789
790
293
    sbytes = sendto(state->sockfd, (void *) state->spacket.data,
791
293
                    4 + (SEND_TYPE_ARG3)state->sbytes, SEND_4TH_ARG,
792
293
                    (struct sockaddr *)&state->remote_addr,
793
293
                    state->remote_addrlen);
794
    /* Check all sbytes were sent */
795
293
    if(sbytes < 0) {
796
0
      failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
797
0
      return CURLE_SEND_ERROR;
798
0
    }
799
    /* Update the progress meter */
800
293
    k->writebytecount += state->sbytes;
801
293
    Curl_pgrsSetUploadCounter(data, k->writebytecount);
802
293
    break;
803
804
633
  case TFTP_EVENT_TIMEOUT:
805
    /* Increment the retry counter and log the timeout */
806
633
    state->retries++;
807
633
    infof(data, "Timeout waiting for block %d ACK. "
808
633
          " Retries = %d", NEXT_BLOCKNUM(state->block), state->retries);
809
    /* Decide if we have had enough */
810
633
    if(state->retries > state->retry_max) {
811
182
      state->error = TFTP_ERR_TIMEOUT;
812
182
      state->state = TFTP_STATE_FIN;
813
182
    }
814
451
    else {
815
      /* Re-send the data packet */
816
451
      sbytes = sendto(state->sockfd, (void *)state->spacket.data,
817
451
                      4 + (SEND_TYPE_ARG3)state->sbytes, SEND_4TH_ARG,
818
451
                      (struct sockaddr *)&state->remote_addr,
819
451
                      state->remote_addrlen);
820
      /* Check all sbytes were sent */
821
451
      if(sbytes < 0) {
822
0
        failf(data, "%s", Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
823
0
        return CURLE_SEND_ERROR;
824
0
      }
825
      /* since this was a re-send, we remain at the still byte position */
826
451
      Curl_pgrsSetUploadCounter(data, k->writebytecount);
827
451
    }
828
633
    break;
829
830
633
  case TFTP_EVENT_ERROR:
831
7
    state->state = TFTP_STATE_FIN;
832
7
    setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
833
7
    setpacketblock(&state->spacket, state->block);
834
7
    (void)sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG,
835
7
                 (struct sockaddr *)&state->remote_addr,
836
7
                 state->remote_addrlen);
837
    /* do not bother with the return code, but if the socket is still up we
838
     * should be a good TFTP client and let the server know we are done */
839
7
    state->state = TFTP_STATE_FIN;
840
7
    break;
841
842
1.79k
  default:
843
1.79k
    failf(data, "tftp_tx: internal error, event: %i", (int)(event));
844
1.79k
    break;
845
2.86k
  }
846
847
2.72k
  return result;
848
2.86k
}
849
850
/**********************************************************
851
 *
852
 * tftp_translate_code
853
 *
854
 * Translate internal error codes to CURL error codes
855
 *
856
 **********************************************************/
857
static CURLcode tftp_translate_code(tftp_error_t error)
858
1.61k
{
859
1.61k
  CURLcode result = CURLE_OK;
860
861
1.61k
  if(error != TFTP_ERR_NONE) {
862
369
    switch(error) {
863
3
    case TFTP_ERR_NOTFOUND:
864
3
      result = CURLE_TFTP_NOTFOUND;
865
3
      break;
866
3
    case TFTP_ERR_PERM:
867
3
      result = CURLE_TFTP_PERM;
868
3
      break;
869
3
    case TFTP_ERR_DISKFULL:
870
3
      result = CURLE_REMOTE_DISK_FULL;
871
3
      break;
872
3
    case TFTP_ERR_UNDEF:
873
6
    case TFTP_ERR_ILLEGAL:
874
6
      result = CURLE_TFTP_ILLEGAL;
875
6
      break;
876
3
    case TFTP_ERR_UNKNOWNID:
877
3
      result = CURLE_TFTP_UNKNOWNID;
878
3
      break;
879
3
    case TFTP_ERR_EXISTS:
880
3
      result = CURLE_REMOTE_FILE_EXISTS;
881
3
      break;
882
3
    case TFTP_ERR_NOSUCHUSER:
883
3
      result = CURLE_TFTP_NOSUCHUSER;
884
3
      break;
885
211
    case TFTP_ERR_TIMEOUT:
886
211
      result = CURLE_OPERATION_TIMEDOUT;
887
211
      break;
888
101
    case TFTP_ERR_NORESPONSE:
889
101
      result = CURLE_COULDNT_CONNECT;
890
101
      break;
891
33
    default:
892
33
      result = CURLE_ABORTED_BY_CALLBACK;
893
33
      break;
894
369
    }
895
369
  }
896
1.24k
  else
897
1.24k
    result = CURLE_OK;
898
899
1.61k
  return result;
900
1.61k
}
901
902
/**********************************************************
903
 *
904
 * tftp_state_machine
905
 *
906
 * The tftp state machine event dispatcher
907
 *
908
 **********************************************************/
909
static CURLcode tftp_state_machine(struct tftp_conn *state,
910
                                   tftp_event_t event)
911
4.67k
{
912
4.67k
  CURLcode result = CURLE_OK;
913
4.67k
  struct Curl_easy *data = state->data;
914
915
4.67k
  switch(state->state) {
916
1.82k
  case TFTP_STATE_START:
917
1.82k
    DEBUGF(infof(data, "TFTP_STATE_START"));
918
1.82k
    result = tftp_send_first(state, event);
919
1.82k
    break;
920
210
  case TFTP_STATE_RX:
921
210
    DEBUGF(infof(data, "TFTP_STATE_RX"));
922
210
    result = tftp_rx(state, event);
923
210
    break;
924
2.63k
  case TFTP_STATE_TX:
925
2.63k
    DEBUGF(infof(data, "TFTP_STATE_TX"));
926
2.63k
    result = tftp_tx(state, event);
927
2.63k
    break;
928
3
  case TFTP_STATE_FIN:
929
3
    infof(data, "%s", "TFTP finished");
930
3
    break;
931
0
  default:
932
0
    DEBUGF(infof(data, "STATE: %d", state->state));
933
0
    failf(data, "%s", "Internal state machine error");
934
0
    result = CURLE_TFTP_ILLEGAL;
935
0
    break;
936
4.67k
  }
937
938
4.67k
  return result;
939
4.67k
}
940
941
static void tftp_conn_dtor(void *key, size_t klen, void *entry)
942
1.13k
{
943
1.13k
  struct tftp_conn *state = entry;
944
1.13k
  (void)key;
945
1.13k
  (void)klen;
946
1.13k
  Curl_safefree(state->rpacket.data);
947
1.13k
  Curl_safefree(state->spacket.data);
948
1.13k
  free(state);
949
1.13k
}
950
951
/**********************************************************
952
 *
953
 * tftp_connect
954
 *
955
 * The connect callback
956
 *
957
 **********************************************************/
958
static CURLcode tftp_connect(struct Curl_easy *data, bool *done)
959
1.13k
{
960
1.13k
  struct tftp_conn *state;
961
1.13k
  int blksize;
962
1.13k
  int need_blksize;
963
1.13k
  struct connectdata *conn = data->conn;
964
1.13k
  const struct Curl_sockaddr_ex *remote_addr = NULL;
965
966
1.13k
  blksize = TFTP_BLKSIZE_DEFAULT;
967
968
1.13k
  state = calloc(1, sizeof(*state));
969
1.13k
  if(!state ||
970
1.13k
     Curl_conn_meta_set(conn, CURL_META_TFTP_CONN, state, tftp_conn_dtor))
971
0
    return CURLE_OUT_OF_MEMORY;
972
973
  /* alloc pkt buffers based on specified blksize */
974
1.13k
  if(data->set.tftp_blksize)
975
    /* range checked when set */
976
14
    blksize = (int)data->set.tftp_blksize;
977
978
1.13k
  need_blksize = blksize;
979
  /* default size is the fallback when no OACK is received */
980
1.13k
  if(need_blksize < TFTP_BLKSIZE_DEFAULT)
981
6
    need_blksize = TFTP_BLKSIZE_DEFAULT;
982
983
1.13k
  if(!state->rpacket.data) {
984
1.13k
    state->rpacket.data = calloc(1, need_blksize + 2 + 2);
985
986
1.13k
    if(!state->rpacket.data)
987
0
      return CURLE_OUT_OF_MEMORY;
988
1.13k
  }
989
990
1.13k
  if(!state->spacket.data) {
991
1.13k
    state->spacket.data = calloc(1, need_blksize + 2 + 2);
992
993
1.13k
    if(!state->spacket.data)
994
0
      return CURLE_OUT_OF_MEMORY;
995
1.13k
  }
996
997
  /* we do not keep TFTP connections up basically because there is none or
998
   * little gain for UDP */
999
1.13k
  connclose(conn, "TFTP");
1000
1001
1.13k
  state->data = data;
1002
1.13k
  state->sockfd = conn->sock[FIRSTSOCKET];
1003
1.13k
  state->state = TFTP_STATE_START;
1004
1.13k
  state->error = TFTP_ERR_NONE;
1005
1.13k
  state->blksize = TFTP_BLKSIZE_DEFAULT; /* Unless updated by OACK response */
1006
1.13k
  state->requested_blksize = blksize;
1007
1008
1.13k
  remote_addr = Curl_conn_get_remote_addr(data, FIRSTSOCKET);
1009
1.13k
  DEBUGASSERT(remote_addr);
1010
1.13k
  if(!remote_addr)
1011
0
    return CURLE_FAILED_INIT;
1012
1013
1.13k
  ((struct sockaddr *)&state->local_addr)->sa_family =
1014
1.13k
    (CURL_SA_FAMILY_T)(remote_addr->family);
1015
1016
1.13k
  tftp_set_timeouts(state);
1017
1018
1.13k
  if(!conn->bits.bound) {
1019
    /* If not already bound, bind to any interface, random UDP port. If it is
1020
     * reused or a custom local port was desired, this has already been done!
1021
     *
1022
     * We once used the size of the local_addr struct as the third argument
1023
     * for bind() to better work with IPv6 or whatever size the struct could
1024
     * have, but we learned that at least Tru64, AIX and IRIX *requires* the
1025
     * size of that argument to match the exact size of a 'sockaddr_in' struct
1026
     * when running IPv4-only.
1027
     *
1028
     * Therefore we use the size from the address we connected to, which we
1029
     * assume uses the same IP version and thus hopefully this works for both
1030
     * IPv4 and IPv6...
1031
     */
1032
1.13k
    int rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr,
1033
1.13k
                  (curl_socklen_t)remote_addr->addrlen);
1034
1.13k
    if(rc) {
1035
629
      char buffer[STRERROR_LEN];
1036
629
      failf(data, "bind() failed; %s",
1037
629
            Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
1038
629
      return CURLE_COULDNT_CONNECT;
1039
629
    }
1040
503
    conn->bits.bound = TRUE;
1041
503
  }
1042
1043
503
  Curl_pgrsStartNow(data);
1044
1045
503
  *done = TRUE;
1046
1047
503
  return CURLE_OK;
1048
1.13k
}
1049
1050
/**********************************************************
1051
 *
1052
 * tftp_done
1053
 *
1054
 * The done callback
1055
 *
1056
 **********************************************************/
1057
static CURLcode tftp_done(struct Curl_easy *data, CURLcode status,
1058
                          bool premature)
1059
1.13k
{
1060
1.13k
  CURLcode result = CURLE_OK;
1061
1.13k
  struct connectdata *conn = data->conn;
1062
1.13k
  struct tftp_conn *state = Curl_conn_meta_get(conn, CURL_META_TFTP_CONN);
1063
1064
1.13k
  (void)status; /* unused */
1065
1.13k
  (void)premature; /* not used */
1066
1067
1.13k
  if(Curl_pgrsDone(data))
1068
0
    return CURLE_ABORTED_BY_CALLBACK;
1069
1070
  /* If we have encountered an error */
1071
1.13k
  if(state)
1072
1.13k
    result = tftp_translate_code(state->error);
1073
1074
1.13k
  return result;
1075
1.13k
}
1076
1077
/**********************************************************
1078
 *
1079
 * tftp_getsock
1080
 *
1081
 * The getsock callback
1082
 *
1083
 **********************************************************/
1084
static int tftp_getsock(struct Curl_easy *data,
1085
                        struct connectdata *conn, curl_socket_t *socks)
1086
3.57k
{
1087
3.57k
  (void)data;
1088
3.57k
  socks[0] = conn->sock[FIRSTSOCKET];
1089
3.57k
  return GETSOCK_READSOCK(0);
1090
3.57k
}
1091
1092
/**********************************************************
1093
 *
1094
 * tftp_receive_packet
1095
 *
1096
 * Called once select fires and data is ready on the socket
1097
 *
1098
 **********************************************************/
1099
static CURLcode tftp_receive_packet(struct Curl_easy *data,
1100
                                    struct tftp_conn *state)
1101
4.20k
{
1102
4.20k
  curl_socklen_t        fromlen;
1103
4.20k
  CURLcode              result = CURLE_OK;
1104
1105
  /* Receive the packet */
1106
4.20k
  fromlen = sizeof(state->remote_addr);
1107
4.20k
  state->rbytes = (int)recvfrom(state->sockfd,
1108
4.20k
                                (void *)state->rpacket.data,
1109
4.20k
                                (RECV_TYPE_ARG3)state->blksize + 4,
1110
4.20k
                                0,
1111
4.20k
                                (struct sockaddr *)&state->remote_addr,
1112
4.20k
                                &fromlen);
1113
4.20k
  state->remote_addrlen = fromlen;
1114
1115
  /* Sanity check packet length */
1116
4.20k
  if(state->rbytes < 4) {
1117
1.00k
    failf(data, "Received too short packet");
1118
    /* Not a timeout, but how best to handle it? */
1119
1.00k
    state->event = TFTP_EVENT_TIMEOUT;
1120
1.00k
  }
1121
3.19k
  else {
1122
    /* The event is given by the TFTP packet time */
1123
3.19k
    unsigned short event = getrpacketevent(&state->rpacket);
1124
3.19k
    state->event = (tftp_event_t)event;
1125
1126
3.19k
    switch(state->event) {
1127
286
    case TFTP_EVENT_DATA:
1128
      /* Do not pass to the client empty or retransmitted packets */
1129
286
      if(state->rbytes > 4 &&
1130
286
         (NEXT_BLOCKNUM(state->block) == getrpacketblock(&state->rpacket))) {
1131
214
        result = Curl_client_write(data, CLIENTWRITE_BODY,
1132
214
                                   (char *)state->rpacket.data + 4,
1133
214
                                   state->rbytes-4);
1134
214
        if(result) {
1135
7
          tftp_state_machine(state, TFTP_EVENT_ERROR);
1136
7
          return result;
1137
7
        }
1138
214
      }
1139
279
      break;
1140
279
    case TFTP_EVENT_ERROR:
1141
34
    {
1142
34
      unsigned short error = getrpacketblock(&state->rpacket);
1143
34
      char *str = (char *)state->rpacket.data + 4;
1144
34
      size_t strn = state->rbytes - 4;
1145
34
      state->error = (tftp_error_t)error;
1146
34
      if(tftp_strnlen(str, strn) < strn)
1147
2
        infof(data, "TFTP error: %s", str);
1148
34
      break;
1149
286
    }
1150
305
    case TFTP_EVENT_ACK:
1151
305
      break;
1152
226
    case TFTP_EVENT_OACK:
1153
226
      result = tftp_parse_option_ack(state,
1154
226
                                     (const char *)state->rpacket.data + 2,
1155
226
                                     state->rbytes-2);
1156
226
      if(result)
1157
36
        return result;
1158
190
      break;
1159
190
    case TFTP_EVENT_RRQ:
1160
6
    case TFTP_EVENT_WRQ:
1161
2.34k
    default:
1162
2.34k
      failf(data, "%s", "Internal error: Unexpected packet");
1163
2.34k
      break;
1164
3.19k
    }
1165
1166
    /* Update the progress meter */
1167
3.15k
    if(Curl_pgrsUpdate(data)) {
1168
0
      tftp_state_machine(state, TFTP_EVENT_ERROR);
1169
0
      return CURLE_ABORTED_BY_CALLBACK;
1170
0
    }
1171
3.15k
  }
1172
4.16k
  return result;
1173
4.20k
}
1174
1175
/**********************************************************
1176
 *
1177
 * tftp_state_timeout
1178
 *
1179
 * Check if timeouts have been reached
1180
 *
1181
 **********************************************************/
1182
static timediff_t tftp_state_timeout(struct tftp_conn *state,
1183
                                     tftp_event_t *event)
1184
4.43k
{
1185
4.43k
  time_t current;
1186
4.43k
  timediff_t timeout_ms;
1187
1188
4.43k
  if(event)
1189
4.43k
    *event = TFTP_EVENT_NONE;
1190
1191
4.43k
  timeout_ms = Curl_timeleft(state->data, NULL,
1192
4.43k
                             (state->state == TFTP_STATE_START));
1193
4.43k
  if(timeout_ms < 0) {
1194
3
    state->error = TFTP_ERR_TIMEOUT;
1195
3
    state->state = TFTP_STATE_FIN;
1196
3
    return 0;
1197
3
  }
1198
4.43k
  current = time(NULL);
1199
4.43k
  if(current > state->rx_time + state->retry_time) {
1200
0
    if(event)
1201
0
      *event = TFTP_EVENT_TIMEOUT;
1202
0
    state->rx_time = time(NULL); /* update even though we received nothing */
1203
0
  }
1204
1205
4.43k
  return timeout_ms;
1206
4.43k
}
1207
1208
/**********************************************************
1209
 *
1210
 * tftp_multi_statemach
1211
 *
1212
 * Handle single RX socket event and return
1213
 *
1214
 **********************************************************/
1215
static CURLcode tftp_multi_statemach(struct Curl_easy *data, bool *done)
1216
4.43k
{
1217
4.43k
  tftp_event_t event;
1218
4.43k
  CURLcode result = CURLE_OK;
1219
4.43k
  struct connectdata *conn = data->conn;
1220
4.43k
  struct tftp_conn *state = Curl_conn_meta_get(conn, CURL_META_TFTP_CONN);
1221
4.43k
  timediff_t timeout_ms;
1222
1223
4.43k
  *done = FALSE;
1224
4.43k
  if(!state)
1225
0
    return CURLE_FAILED_INIT;
1226
1227
4.43k
  timeout_ms = tftp_state_timeout(state, &event);
1228
4.43k
  if(timeout_ms < 0) {
1229
0
    failf(data, "TFTP response timeout");
1230
0
    return CURLE_OPERATION_TIMEDOUT;
1231
0
  }
1232
4.43k
  if(event != TFTP_EVENT_NONE) {
1233
0
    result = tftp_state_machine(state, event);
1234
0
    if(result)
1235
0
      return result;
1236
0
    *done = (state->state == TFTP_STATE_FIN);
1237
0
    if(*done)
1238
      /* Tell curl we are done */
1239
0
      Curl_xfer_setup_nop(data);
1240
0
  }
1241
4.43k
  else {
1242
    /* no timeouts to handle, check our socket */
1243
4.43k
    int rc = SOCKET_READABLE(state->sockfd, 0);
1244
1245
4.43k
    if(rc == -1) {
1246
      /* bail out */
1247
0
      int error = SOCKERRNO;
1248
0
      char buffer[STRERROR_LEN];
1249
0
      failf(data, "%s", Curl_strerror(error, buffer, sizeof(buffer)));
1250
0
      state->event = TFTP_EVENT_ERROR;
1251
0
    }
1252
4.43k
    else if(rc) {
1253
4.20k
      result = tftp_receive_packet(data, state);
1254
4.20k
      if(result)
1255
43
        return result;
1256
4.16k
      result = tftp_state_machine(state, state->event);
1257
4.16k
      if(result)
1258
31
        return result;
1259
4.13k
      *done = (state->state == TFTP_STATE_FIN);
1260
4.13k
      if(*done)
1261
        /* Tell curl we are done */
1262
398
        Curl_xfer_setup_nop(data);
1263
4.13k
    }
1264
    /* if rc == 0, then select() timed out */
1265
4.43k
  }
1266
1267
4.36k
  return result;
1268
4.43k
}
1269
1270
/**********************************************************
1271
 *
1272
 * tftp_doing
1273
 *
1274
 * Called from multi.c while DOing
1275
 *
1276
 **********************************************************/
1277
static CURLcode tftp_doing(struct Curl_easy *data, bool *dophase_done)
1278
3.95k
{
1279
3.95k
  CURLcode result;
1280
3.95k
  result = tftp_multi_statemach(data, dophase_done);
1281
1282
3.95k
  if(*dophase_done) {
1283
336
    DEBUGF(infof(data, "DO phase is complete"));
1284
336
  }
1285
3.61k
  else if(!result) {
1286
    /* The multi code does not have this logic for the DOING state so we
1287
       provide it for TFTP since it may do the entire transfer in this
1288
       state. */
1289
3.57k
    if(Curl_pgrsUpdate(data))
1290
0
      result = CURLE_ABORTED_BY_CALLBACK;
1291
3.57k
    else
1292
3.57k
      result = Curl_speedcheck(data, curlx_now());
1293
3.57k
  }
1294
3.95k
  return result;
1295
3.95k
}
1296
1297
/**********************************************************
1298
 *
1299
 * tftp_perform
1300
 *
1301
 * Entry point for transfer from tftp_do, starts state mach
1302
 *
1303
 **********************************************************/
1304
static CURLcode tftp_perform(struct Curl_easy *data, bool *dophase_done)
1305
501
{
1306
501
  CURLcode result = CURLE_OK;
1307
501
  struct connectdata *conn = data->conn;
1308
501
  struct tftp_conn *state = Curl_conn_meta_get(conn, CURL_META_TFTP_CONN);
1309
1310
501
  *dophase_done = FALSE;
1311
501
  if(!state)
1312
0
    return CURLE_FAILED_INIT;
1313
1314
501
  result = tftp_state_machine(state, TFTP_EVENT_INIT);
1315
1316
501
  if((state->state == TFTP_STATE_FIN) || result)
1317
20
    return result;
1318
1319
481
  tftp_multi_statemach(data, dophase_done);
1320
1321
481
  if(*dophase_done)
1322
62
    DEBUGF(infof(data, "DO phase is complete"));
1323
1324
481
  return result;
1325
501
}
1326
1327
1328
/**********************************************************
1329
 *
1330
 * tftp_do
1331
 *
1332
 * The do callback
1333
 *
1334
 * This callback initiates the TFTP transfer
1335
 *
1336
 **********************************************************/
1337
1338
static CURLcode tftp_do(struct Curl_easy *data, bool *done)
1339
501
{
1340
501
  struct connectdata *conn = data->conn;
1341
501
  struct tftp_conn *state = Curl_conn_meta_get(conn, CURL_META_TFTP_CONN);
1342
501
  CURLcode result;
1343
1344
501
  *done = FALSE;
1345
1346
501
  if(!state) {
1347
0
    result = tftp_connect(data, done);
1348
0
    if(result)
1349
0
      return result;
1350
1351
0
    state = Curl_conn_meta_get(conn, CURL_META_TFTP_CONN);
1352
0
    if(!state)
1353
0
      return CURLE_TFTP_ILLEGAL;
1354
0
  }
1355
1356
501
  result = tftp_perform(data, done);
1357
1358
  /* If tftp_perform() returned an error, use that for return code. If it
1359
     was OK, see if tftp_translate_code() has an error. */
1360
501
  if(!result)
1361
    /* If we have encountered an internal tftp error, translate it. */
1362
481
    result = tftp_translate_code(state->error);
1363
1364
501
  return result;
1365
501
}
1366
1367
static CURLcode tftp_setup_connection(struct Curl_easy *data,
1368
                                      struct connectdata *conn)
1369
4.49k
{
1370
4.49k
  char *type;
1371
1372
4.49k
  conn->transport_wanted = TRNSPRT_UDP;
1373
1374
  /* TFTP URLs support an extension like ";mode=<typecode>" that
1375
   * we will try to get now! */
1376
4.49k
  type = strstr(data->state.up.path, ";mode=");
1377
1378
4.49k
  if(!type)
1379
4.46k
    type = strstr(conn->host.rawalloc, ";mode=");
1380
1381
4.49k
  if(type) {
1382
31
    char command;
1383
31
    *type = 0;                   /* it was in the middle of the hostname */
1384
31
    command = Curl_raw_toupper(type[6]);
1385
1386
31
    switch(command) {
1387
4
    case 'A': /* ASCII mode */
1388
6
    case 'N': /* NETASCII mode */
1389
6
      data->state.prefer_ascii = TRUE;
1390
6
      break;
1391
1392
0
    case 'O': /* octet mode */
1393
0
    case 'I': /* binary mode */
1394
25
    default:
1395
      /* switch off ASCII */
1396
25
      data->state.prefer_ascii = FALSE;
1397
25
      break;
1398
31
    }
1399
31
  }
1400
1401
4.49k
  return CURLE_OK;
1402
4.49k
}
1403
#endif