Coverage Report

Created: 2026-01-09 07:14

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