Coverage Report

Created: 2025-11-23 06:22

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