Coverage Report

Created: 2025-10-13 06:59

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/PROJ/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
0
#define TFTP_BLKSIZE_DEFAULT 512
74
0
#define TFTP_OPTION_BLKSIZE "blksize"
75
76
/* from RFC2349: */
77
0
#define TFTP_OPTION_TSIZE    "tsize"
78
0
#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
0
#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
0
{
209
0
  time_t timeout;
210
0
  timediff_t timeout_ms;
211
0
  bool start = (state->state == TFTP_STATE_START);
212
213
  /* Compute drop-dead time */
214
0
  timeout_ms = Curl_timeleft(state->data, NULL, start);
215
216
0
  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
0
  if(timeout_ms > 0)
224
0
    timeout = (time_t)(timeout_ms + 500) / 1000;
225
0
  else
226
0
    timeout = 15;
227
228
  /* Average reposting an ACK after 5 seconds */
229
0
  state->retry_max = (int)timeout/5;
230
231
  /* But bound the total number */
232
0
  if(state->retry_max < 3)
233
0
    state->retry_max = 3;
234
235
0
  if(state->retry_max > 50)
236
0
    state->retry_max = 50;
237
238
  /* Compute the re-ACK interval to suit the timeout */
239
0
  state->retry_time = (int)(timeout/state->retry_max);
240
0
  if(state->retry_time < 1)
241
0
    state->retry_time = 1;
242
243
0
  infof(state->data,
244
0
        "set timeouts for state %d; Total % " FMT_OFF_T ", retry %d maxtry %d",
245
0
        (int)state->state, timeout_ms, state->retry_time, state->retry_max);
246
247
  /* init RX time */
248
0
  state->rx_time = time(NULL);
249
250
0
  return CURLE_OK;
251
0
}
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
0
{
263
0
  packet->data[0] = (unsigned char)(num >> 8);
264
0
  packet->data[1] = (unsigned char)(num & 0xff);
265
0
}
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
0
{
384
0
  if(( strlen(option) + *csize + 1) > (size_t)state->blksize)
385
0
    return CURLE_TFTP_ILLEGAL;
386
0
  strcpy(buf, option);
387
0
  *csize += strlen(option) + 1;
388
0
  return CURLE_OK;
389
0
}
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
0
{
426
0
  size_t sbytes;
427
0
  ssize_t senddata;
428
0
  const char *mode = "octet";
429
0
  char *filename;
430
0
  struct Curl_easy *data = state->data;
431
0
  const struct Curl_sockaddr_ex *remote_addr = NULL;
432
0
  CURLcode result = CURLE_OK;
433
434
  /* Set ASCII mode if -B flag was used */
435
0
  if(data->state.prefer_ascii)
436
0
    mode = "netascii";
437
438
0
  switch(event) {
439
440
0
  case TFTP_EVENT_INIT:    /* Send the first packet out */
441
0
  case TFTP_EVENT_TIMEOUT: /* Resend the first packet out */
442
    /* Increment the retry counter, quit if over the limit */
443
0
    state->retries++;
444
0
    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
0
    if(data->state.upload) {
451
      /* If we are uploading, send an WRQ */
452
0
      setpacketevent(&state->spacket, TFTP_EVENT_WRQ);
453
0
      if(data->state.infilesize != -1)
454
0
        Curl_pgrsSetUploadSize(data, data->state.infilesize);
455
0
    }
456
0
    else {
457
      /* If we are downloading, send an RRQ */
458
0
      setpacketevent(&state->spacket, TFTP_EVENT_RRQ);
459
0
    }
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
0
    if(!state->data->state.up.path[1]) {
464
0
      failf(data, "Missing filename");
465
0
      return CURLE_TFTP_ILLEGAL;
466
0
    }
467
0
    result = Curl_urldecode(&state->data->state.up.path[1], 0,
468
0
                            &filename, NULL, REJECT_ZERO);
469
0
    if(result)
470
0
      return result;
471
472
0
    if(strlen(filename) > (state->blksize - strlen(mode) - 4)) {
473
0
      failf(data, "TFTP filename too long");
474
0
      free(filename);
475
0
      return CURLE_TFTP_ILLEGAL; /* too long filename field */
476
0
    }
477
478
0
    curl_msnprintf((char *)state->spacket.data + 2,
479
0
                   state->blksize,
480
0
                   "%s%c%s%c", filename, '\0',  mode, '\0');
481
0
    sbytes = 4 + strlen(filename) + strlen(mode);
482
483
    /* optional addition of TFTP options */
484
0
    if(!data->set.tftp_no_options) {
485
0
      char buf[64];
486
      /* add tsize option */
487
0
      curl_msnprintf(buf, sizeof(buf), "%" FMT_OFF_T,
488
0
                     data->state.upload && (data->state.infilesize != -1) ?
489
0
                     data->state.infilesize : 0);
490
491
0
      result = tftp_option_add(state, &sbytes,
492
0
                               (char *)state->spacket.data + sbytes,
493
0
                               TFTP_OPTION_TSIZE);
494
0
      if(result == CURLE_OK)
495
0
        result = tftp_option_add(state, &sbytes,
496
0
                                 (char *)state->spacket.data + sbytes, buf);
497
498
      /* add blksize option */
499
0
      curl_msnprintf(buf, sizeof(buf), "%d", state->requested_blksize);
500
0
      if(result == CURLE_OK)
501
0
        result = tftp_option_add(state, &sbytes,
502
0
                                 (char *)state->spacket.data + sbytes,
503
0
                                 TFTP_OPTION_BLKSIZE);
504
0
      if(result == CURLE_OK)
505
0
        result = tftp_option_add(state, &sbytes,
506
0
                                 (char *)state->spacket.data + sbytes, buf);
507
508
      /* add timeout option */
509
0
      curl_msnprintf(buf, sizeof(buf), "%d", state->retry_time);
510
0
      if(result == CURLE_OK)
511
0
        result = tftp_option_add(state, &sbytes,
512
0
                                 (char *)state->spacket.data + sbytes,
513
0
                                 TFTP_OPTION_INTERVAL);
514
0
      if(result == CURLE_OK)
515
0
        result = tftp_option_add(state, &sbytes,
516
0
                                 (char *)state->spacket.data + sbytes, buf);
517
518
0
      if(result != CURLE_OK) {
519
0
        failf(data, "TFTP buffer too small for options");
520
0
        free(filename);
521
0
        return CURLE_TFTP_ILLEGAL;
522
0
      }
523
0
    }
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
0
#define CURL_SENDTO_ARG5(x) (x)
531
0
#endif
532
0
    remote_addr = Curl_conn_get_remote_addr(data, FIRSTSOCKET);
533
0
    if(!remote_addr)
534
0
      return CURLE_FAILED_INIT;
535
536
0
    senddata = sendto(state->sockfd, (void *)state->spacket.data,
537
0
                      (SEND_TYPE_ARG3)sbytes, 0,
538
0
                      CURL_SENDTO_ARG5(&remote_addr->curl_sa_addr),
539
0
                      (curl_socklen_t)remote_addr->addrlen);
540
0
    free(filename);
541
0
    if(senddata != (ssize_t)sbytes) {
542
0
      char buffer[STRERROR_LEN];
543
0
      failf(data, "%s", curlx_strerror(SOCKERRNO, buffer, sizeof(buffer)));
544
0
      return CURLE_SEND_ERROR;
545
0
    }
546
0
    break;
547
548
0
  case TFTP_EVENT_OACK:
549
0
    if(data->state.upload) {
550
0
      result = tftp_connect_for_tx(state, event);
551
0
    }
552
0
    else {
553
0
      result = tftp_connect_for_rx(state, event);
554
0
    }
555
0
    break;
556
557
0
  case TFTP_EVENT_ACK: /* Connected for transmit */
558
0
    result = tftp_connect_for_tx(state, event);
559
0
    break;
560
561
0
  case TFTP_EVENT_DATA: /* Connected for receive */
562
0
    result = tftp_connect_for_rx(state, event);
563
0
    break;
564
565
0
  case TFTP_EVENT_ERROR:
566
0
    state->state = TFTP_STATE_FIN;
567
0
    break;
568
569
0
  default:
570
0
    failf(state->data, "tftp_send_first: internal error");
571
0
    return CURLE_TFTP_ILLEGAL;
572
0
  }
573
574
0
  return result;
575
0
}
576
577
/* the next blocknum is x + 1 but it needs to wrap at an unsigned 16bit
578
   boundary */
579
0
#define NEXT_BLOCKNUM(x) (((x) + 1)&0xffff)
580
581
/**********************************************************
582
 *
583
 * tftp_rx
584
 *
585
 * Event handler for the RX state
586
 *
587
 **********************************************************/
588
static CURLcode tftp_rx(struct tftp_conn *state, tftp_event_t event)
589
0
{
590
0
  ssize_t sbytes;
591
0
  int rblock;
592
0
  struct Curl_easy *data = state->data;
593
0
  char buffer[STRERROR_LEN];
594
595
0
  switch(event) {
596
597
0
  case TFTP_EVENT_DATA:
598
    /* Is this the block we expect? */
599
0
    rblock = getrpacketblock(&state->rpacket);
600
0
    if(NEXT_BLOCKNUM(state->block) == rblock) {
601
      /* This is the expected block. Reset counters and ACK it. */
602
0
      state->retries = 0;
603
0
    }
604
0
    else if(state->block == rblock) {
605
      /* This is the last recently received block again. Log it and ACK it
606
         again. */
607
0
      infof(data, "Received last DATA packet block %d again.", rblock);
608
0
    }
609
0
    else {
610
      /* totally unexpected, just log it */
611
0
      infof(data,
612
0
            "Received unexpected DATA packet block %d, expecting block %d",
613
0
            rblock, NEXT_BLOCKNUM(state->block));
614
0
      break;
615
0
    }
616
617
    /* ACK this block. */
618
0
    state->block = (unsigned short)rblock;
619
0
    setpacketevent(&state->spacket, TFTP_EVENT_ACK);
620
0
    setpacketblock(&state->spacket, state->block);
621
0
    sbytes = sendto(state->sockfd, (void *)state->spacket.data,
622
0
                    4, SEND_4TH_ARG,
623
0
                    (struct sockaddr *)&state->remote_addr,
624
0
                    state->remote_addrlen);
625
0
    if(sbytes < 0) {
626
0
      failf(data, "%s", curlx_strerror(SOCKERRNO, buffer, sizeof(buffer)));
627
0
      return CURLE_SEND_ERROR;
628
0
    }
629
630
    /* Check if completed (That is, a less than full packet is received) */
631
0
    if(state->rbytes < (ssize_t)state->blksize + 4) {
632
0
      state->state = TFTP_STATE_FIN;
633
0
    }
634
0
    else {
635
0
      state->state = TFTP_STATE_RX;
636
0
    }
637
0
    state->rx_time = time(NULL);
638
0
    break;
639
640
0
  case TFTP_EVENT_OACK:
641
    /* ACK option acknowledgement so we can move on to data */
642
0
    state->block = 0;
643
0
    state->retries = 0;
644
0
    setpacketevent(&state->spacket, TFTP_EVENT_ACK);
645
0
    setpacketblock(&state->spacket, state->block);
646
0
    sbytes = sendto(state->sockfd, (void *)state->spacket.data,
647
0
                    4, SEND_4TH_ARG,
648
0
                    (struct sockaddr *)&state->remote_addr,
649
0
                    state->remote_addrlen);
650
0
    if(sbytes < 0) {
651
0
      failf(data, "%s", curlx_strerror(SOCKERRNO, buffer, sizeof(buffer)));
652
0
      return CURLE_SEND_ERROR;
653
0
    }
654
655
    /* we are ready to RX data */
656
0
    state->state = TFTP_STATE_RX;
657
0
    state->rx_time = time(NULL);
658
0
    break;
659
660
0
  case TFTP_EVENT_TIMEOUT:
661
    /* Increment the retry count and fail if over the limit */
662
0
    state->retries++;
663
0
    infof(data,
664
0
          "Timeout waiting for block %d ACK. Retries = %d",
665
0
          NEXT_BLOCKNUM(state->block), state->retries);
666
0
    if(state->retries > state->retry_max) {
667
0
      state->error = TFTP_ERR_TIMEOUT;
668
0
      state->state = TFTP_STATE_FIN;
669
0
    }
670
0
    else {
671
      /* Resend the previous ACK */
672
0
      sbytes = sendto(state->sockfd, (void *)state->spacket.data,
673
0
                      4, SEND_4TH_ARG,
674
0
                      (struct sockaddr *)&state->remote_addr,
675
0
                      state->remote_addrlen);
676
0
      if(sbytes < 0) {
677
0
        failf(data, "%s", curlx_strerror(SOCKERRNO, buffer, sizeof(buffer)));
678
0
        return CURLE_SEND_ERROR;
679
0
      }
680
0
    }
681
0
    break;
682
683
0
  case TFTP_EVENT_ERROR:
684
0
    setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
685
0
    setpacketblock(&state->spacket, state->block);
686
0
    (void)sendto(state->sockfd, (void *)state->spacket.data,
687
0
                 4, SEND_4TH_ARG,
688
0
                 (struct sockaddr *)&state->remote_addr,
689
0
                 state->remote_addrlen);
690
    /* do not bother with the return code, but if the socket is still up we
691
     * should be a good TFTP client and let the server know we are done */
692
0
    state->state = TFTP_STATE_FIN;
693
0
    break;
694
695
0
  default:
696
0
    failf(data, "%s", "tftp_rx: internal error");
697
0
    return CURLE_TFTP_ILLEGAL; /* not really the perfect return code for
698
                                  this */
699
0
  }
700
0
  return CURLE_OK;
701
0
}
702
703
/**********************************************************
704
 *
705
 * tftp_tx
706
 *
707
 * Event handler for the TX state
708
 *
709
 **********************************************************/
710
static CURLcode tftp_tx(struct tftp_conn *state, tftp_event_t event)
711
0
{
712
0
  struct Curl_easy *data = state->data;
713
0
  ssize_t sbytes;
714
0
  CURLcode result = CURLE_OK;
715
0
  struct SingleRequest *k = &data->req;
716
0
  size_t cb; /* Bytes currently read */
717
0
  char buffer[STRERROR_LEN];
718
0
  char *bufptr;
719
0
  bool eos;
720
721
0
  switch(event) {
722
723
0
  case TFTP_EVENT_ACK:
724
0
  case TFTP_EVENT_OACK:
725
0
    if(event == TFTP_EVENT_ACK) {
726
      /* Ack the packet */
727
0
      int rblock = getrpacketblock(&state->rpacket);
728
729
0
      if(rblock != state->block &&
730
         /* There is a bug in tftpd-hpa that causes it to send us an ack for
731
          * 65535 when the block number wraps to 0. So when we are expecting
732
          * 0, also accept 65535. See
733
          * https://www.syslinux.org/archives/2010-September/015612.html
734
          * */
735
0
         !(state->block == 0 && rblock == 65535)) {
736
        /* This is not the expected block. Log it and up the retry counter */
737
0
        infof(data, "Received ACK for block %d, expecting %d",
738
0
              rblock, state->block);
739
0
        state->retries++;
740
        /* Bail out if over the maximum */
741
0
        if(state->retries > state->retry_max) {
742
0
          failf(data, "tftp_tx: giving up waiting for block %d ack",
743
0
                state->block);
744
0
          result = CURLE_SEND_ERROR;
745
0
        }
746
0
        else {
747
          /* Re-send the data packet */
748
0
          sbytes = sendto(state->sockfd, (void *)state->spacket.data,
749
0
                          4 + (SEND_TYPE_ARG3)state->sbytes, SEND_4TH_ARG,
750
0
                          (struct sockaddr *)&state->remote_addr,
751
0
                          state->remote_addrlen);
752
          /* Check all sbytes were sent */
753
0
          if(sbytes < 0) {
754
0
            failf(data, "%s",
755
0
                  curlx_strerror(SOCKERRNO, buffer, sizeof(buffer)));
756
0
            result = CURLE_SEND_ERROR;
757
0
          }
758
0
        }
759
760
0
        return result;
761
0
      }
762
      /* This is the expected packet. Reset the counters and send the next
763
         block */
764
0
      state->rx_time = time(NULL);
765
0
      state->block++;
766
0
    }
767
0
    else
768
0
      state->block = 1; /* first data block is 1 when using OACK */
769
770
0
    state->retries = 0;
771
0
    setpacketevent(&state->spacket, TFTP_EVENT_DATA);
772
0
    setpacketblock(&state->spacket, state->block);
773
0
    if(state->block > 1 && state->sbytes < state->blksize) {
774
0
      state->state = TFTP_STATE_FIN;
775
0
      return CURLE_OK;
776
0
    }
777
778
    /* TFTP considers data block size < 512 bytes as an end of session. So
779
     * in some cases we must wait for additional data to build full (512 bytes)
780
     * data block.
781
     * */
782
0
    state->sbytes = 0;
783
0
    bufptr = (char *)state->spacket.data + 4;
784
0
    do {
785
0
      result = Curl_client_read(data, bufptr, state->blksize - state->sbytes,
786
0
                                &cb, &eos);
787
0
      if(result)
788
0
        return result;
789
0
      state->sbytes += cb;
790
0
      bufptr += cb;
791
0
    } while(state->sbytes < state->blksize && cb);
792
793
0
    sbytes = sendto(state->sockfd, (void *) state->spacket.data,
794
0
                    4 + (SEND_TYPE_ARG3)state->sbytes, SEND_4TH_ARG,
795
0
                    (struct sockaddr *)&state->remote_addr,
796
0
                    state->remote_addrlen);
797
    /* Check all sbytes were sent */
798
0
    if(sbytes < 0) {
799
0
      failf(data, "%s", curlx_strerror(SOCKERRNO, buffer, sizeof(buffer)));
800
0
      return CURLE_SEND_ERROR;
801
0
    }
802
    /* Update the progress meter */
803
0
    k->writebytecount += state->sbytes;
804
0
    Curl_pgrsSetUploadCounter(data, k->writebytecount);
805
0
    break;
806
807
0
  case TFTP_EVENT_TIMEOUT:
808
    /* Increment the retry counter and log the timeout */
809
0
    state->retries++;
810
0
    infof(data, "Timeout waiting for block %d ACK. "
811
0
          " Retries = %d", NEXT_BLOCKNUM(state->block), state->retries);
812
    /* Decide if we have had enough */
813
0
    if(state->retries > state->retry_max) {
814
0
      state->error = TFTP_ERR_TIMEOUT;
815
0
      state->state = TFTP_STATE_FIN;
816
0
    }
817
0
    else {
818
      /* Re-send the data packet */
819
0
      sbytes = sendto(state->sockfd, (void *)state->spacket.data,
820
0
                      4 + (SEND_TYPE_ARG3)state->sbytes, SEND_4TH_ARG,
821
0
                      (struct sockaddr *)&state->remote_addr,
822
0
                      state->remote_addrlen);
823
      /* Check all sbytes were sent */
824
0
      if(sbytes < 0) {
825
0
        failf(data, "%s", curlx_strerror(SOCKERRNO, buffer, sizeof(buffer)));
826
0
        return CURLE_SEND_ERROR;
827
0
      }
828
      /* since this was a re-send, we remain at the still byte position */
829
0
      Curl_pgrsSetUploadCounter(data, k->writebytecount);
830
0
    }
831
0
    break;
832
833
0
  case TFTP_EVENT_ERROR:
834
0
    state->state = TFTP_STATE_FIN;
835
0
    setpacketevent(&state->spacket, TFTP_EVENT_ERROR);
836
0
    setpacketblock(&state->spacket, state->block);
837
0
    (void)sendto(state->sockfd, (void *)state->spacket.data, 4, SEND_4TH_ARG,
838
0
                 (struct sockaddr *)&state->remote_addr,
839
0
                 state->remote_addrlen);
840
    /* do not bother with the return code, but if the socket is still up we
841
     * should be a good TFTP client and let the server know we are done */
842
0
    state->state = TFTP_STATE_FIN;
843
0
    break;
844
845
0
  default:
846
0
    failf(data, "tftp_tx: internal error, event: %i", (int)(event));
847
0
    break;
848
0
  }
849
850
0
  return result;
851
0
}
852
853
/**********************************************************
854
 *
855
 * tftp_translate_code
856
 *
857
 * Translate internal error codes to CURL error codes
858
 *
859
 **********************************************************/
860
static CURLcode tftp_translate_code(tftp_error_t error)
861
0
{
862
0
  CURLcode result = CURLE_OK;
863
864
0
  if(error != TFTP_ERR_NONE) {
865
0
    switch(error) {
866
0
    case TFTP_ERR_NOTFOUND:
867
0
      result = CURLE_TFTP_NOTFOUND;
868
0
      break;
869
0
    case TFTP_ERR_PERM:
870
0
      result = CURLE_TFTP_PERM;
871
0
      break;
872
0
    case TFTP_ERR_DISKFULL:
873
0
      result = CURLE_REMOTE_DISK_FULL;
874
0
      break;
875
0
    case TFTP_ERR_UNDEF:
876
0
    case TFTP_ERR_ILLEGAL:
877
0
      result = CURLE_TFTP_ILLEGAL;
878
0
      break;
879
0
    case TFTP_ERR_UNKNOWNID:
880
0
      result = CURLE_TFTP_UNKNOWNID;
881
0
      break;
882
0
    case TFTP_ERR_EXISTS:
883
0
      result = CURLE_REMOTE_FILE_EXISTS;
884
0
      break;
885
0
    case TFTP_ERR_NOSUCHUSER:
886
0
      result = CURLE_TFTP_NOSUCHUSER;
887
0
      break;
888
0
    case TFTP_ERR_TIMEOUT:
889
0
      result = CURLE_OPERATION_TIMEDOUT;
890
0
      break;
891
0
    case TFTP_ERR_NORESPONSE:
892
0
      result = CURLE_COULDNT_CONNECT;
893
0
      break;
894
0
    default:
895
0
      result = CURLE_ABORTED_BY_CALLBACK;
896
0
      break;
897
0
    }
898
0
  }
899
0
  else
900
0
    result = CURLE_OK;
901
902
0
  return result;
903
0
}
904
905
/**********************************************************
906
 *
907
 * tftp_state_machine
908
 *
909
 * The tftp state machine event dispatcher
910
 *
911
 **********************************************************/
912
static CURLcode tftp_state_machine(struct tftp_conn *state,
913
                                   tftp_event_t event)
914
0
{
915
0
  CURLcode result = CURLE_OK;
916
0
  struct Curl_easy *data = state->data;
917
918
0
  switch(state->state) {
919
0
  case TFTP_STATE_START:
920
0
    DEBUGF(infof(data, "TFTP_STATE_START"));
921
0
    result = tftp_send_first(state, event);
922
0
    break;
923
0
  case TFTP_STATE_RX:
924
0
    DEBUGF(infof(data, "TFTP_STATE_RX"));
925
0
    result = tftp_rx(state, event);
926
0
    break;
927
0
  case TFTP_STATE_TX:
928
0
    DEBUGF(infof(data, "TFTP_STATE_TX"));
929
0
    result = tftp_tx(state, event);
930
0
    break;
931
0
  case TFTP_STATE_FIN:
932
0
    infof(data, "%s", "TFTP finished");
933
0
    break;
934
0
  default:
935
0
    DEBUGF(infof(data, "STATE: %d", state->state));
936
0
    failf(data, "%s", "Internal state machine error");
937
0
    result = CURLE_TFTP_ILLEGAL;
938
0
    break;
939
0
  }
940
941
0
  return result;
942
0
}
943
944
static void tftp_conn_dtor(void *key, size_t klen, void *entry)
945
0
{
946
0
  struct tftp_conn *state = entry;
947
0
  (void)key;
948
0
  (void)klen;
949
0
  Curl_safefree(state->rpacket.data);
950
0
  Curl_safefree(state->spacket.data);
951
0
  free(state);
952
0
}
953
954
/**********************************************************
955
 *
956
 * tftp_connect
957
 *
958
 * The connect callback
959
 *
960
 **********************************************************/
961
static CURLcode tftp_connect(struct Curl_easy *data, bool *done)
962
0
{
963
0
  struct tftp_conn *state;
964
0
  int blksize;
965
0
  int need_blksize;
966
0
  struct connectdata *conn = data->conn;
967
0
  const struct Curl_sockaddr_ex *remote_addr = NULL;
968
0
  CURLcode result;
969
970
0
  blksize = TFTP_BLKSIZE_DEFAULT;
971
972
0
  state = calloc(1, sizeof(*state));
973
0
  if(!state ||
974
0
     Curl_conn_meta_set(conn, CURL_META_TFTP_CONN, state, tftp_conn_dtor))
975
0
    return CURLE_OUT_OF_MEMORY;
976
977
  /* alloc pkt buffers based on specified blksize */
978
0
  if(data->set.tftp_blksize)
979
    /* range checked when set */
980
0
    blksize = (int)data->set.tftp_blksize;
981
982
0
  need_blksize = blksize;
983
  /* default size is the fallback when no OACK is received */
984
0
  if(need_blksize < TFTP_BLKSIZE_DEFAULT)
985
0
    need_blksize = TFTP_BLKSIZE_DEFAULT;
986
987
0
  if(!state->rpacket.data) {
988
0
    state->rpacket.data = calloc(1, need_blksize + 2 + 2);
989
990
0
    if(!state->rpacket.data)
991
0
      return CURLE_OUT_OF_MEMORY;
992
0
  }
993
994
0
  if(!state->spacket.data) {
995
0
    state->spacket.data = calloc(1, need_blksize + 2 + 2);
996
997
0
    if(!state->spacket.data)
998
0
      return CURLE_OUT_OF_MEMORY;
999
0
  }
1000
1001
  /* we do not keep TFTP connections up basically because there is none or
1002
   * little gain for UDP */
1003
0
  connclose(conn, "TFTP");
1004
1005
0
  state->data = data;
1006
0
  state->sockfd = conn->sock[FIRSTSOCKET];
1007
0
  state->state = TFTP_STATE_START;
1008
0
  state->error = TFTP_ERR_NONE;
1009
0
  state->blksize = TFTP_BLKSIZE_DEFAULT; /* Unless updated by OACK response */
1010
0
  state->requested_blksize = blksize;
1011
1012
0
  remote_addr = Curl_conn_get_remote_addr(data, FIRSTSOCKET);
1013
0
  DEBUGASSERT(remote_addr);
1014
0
  if(!remote_addr)
1015
0
    return CURLE_FAILED_INIT;
1016
1017
0
  ((struct sockaddr *)&state->local_addr)->sa_family =
1018
0
    (CURL_SA_FAMILY_T)(remote_addr->family);
1019
1020
0
  result = tftp_set_timeouts(state);
1021
0
  if(result)
1022
0
    return result;
1023
1024
0
  if(!conn->bits.bound) {
1025
    /* If not already bound, bind to any interface, random UDP port. If it is
1026
     * reused or a custom local port was desired, this has already been done!
1027
     *
1028
     * We once used the size of the local_addr struct as the third argument
1029
     * for bind() to better work with IPv6 or whatever size the struct could
1030
     * have, but we learned that at least Tru64, AIX and IRIX *requires* the
1031
     * size of that argument to match the exact size of a 'sockaddr_in' struct
1032
     * when running IPv4-only.
1033
     *
1034
     * Therefore we use the size from the address we connected to, which we
1035
     * assume uses the same IP version and thus hopefully this works for both
1036
     * IPv4 and IPv6...
1037
     */
1038
0
    int rc = bind(state->sockfd, (struct sockaddr *)&state->local_addr,
1039
0
                  (curl_socklen_t)remote_addr->addrlen);
1040
0
    if(rc) {
1041
0
      char buffer[STRERROR_LEN];
1042
0
      failf(data, "bind() failed; %s",
1043
0
            curlx_strerror(SOCKERRNO, buffer, sizeof(buffer)));
1044
0
      return CURLE_COULDNT_CONNECT;
1045
0
    }
1046
0
    conn->bits.bound = TRUE;
1047
0
  }
1048
1049
0
  Curl_pgrsStartNow(data);
1050
1051
0
  *done = TRUE;
1052
1053
0
  return CURLE_OK;
1054
0
}
1055
1056
/**********************************************************
1057
 *
1058
 * tftp_done
1059
 *
1060
 * The done callback
1061
 *
1062
 **********************************************************/
1063
static CURLcode tftp_done(struct Curl_easy *data, CURLcode status,
1064
                          bool premature)
1065
0
{
1066
0
  CURLcode result = CURLE_OK;
1067
0
  struct connectdata *conn = data->conn;
1068
0
  struct tftp_conn *state = Curl_conn_meta_get(conn, CURL_META_TFTP_CONN);
1069
1070
0
  (void)status;
1071
0
  (void)premature;
1072
1073
0
  if(Curl_pgrsDone(data))
1074
0
    return CURLE_ABORTED_BY_CALLBACK;
1075
1076
  /* If we have encountered an error */
1077
0
  if(state)
1078
0
    result = tftp_translate_code(state->error);
1079
1080
0
  return result;
1081
0
}
1082
1083
static CURLcode tftp_pollset(struct Curl_easy *data,
1084
                             struct easy_pollset *ps)
1085
0
{
1086
0
  return Curl_pollset_add_in(data, ps, data->conn->sock[FIRSTSOCKET]);
1087
0
}
1088
1089
/**********************************************************
1090
 *
1091
 * tftp_receive_packet
1092
 *
1093
 * Called once select fires and data is ready on the socket
1094
 *
1095
 **********************************************************/
1096
static CURLcode tftp_receive_packet(struct Curl_easy *data,
1097
                                    struct tftp_conn *state)
1098
0
{
1099
0
  CURLcode result = CURLE_OK;
1100
0
  struct Curl_sockaddr_storage remote_addr;
1101
0
  curl_socklen_t fromlen = sizeof(remote_addr);
1102
1103
  /* Receive the packet */
1104
0
  state->rbytes = (int)recvfrom(state->sockfd,
1105
0
                                (void *)state->rpacket.data,
1106
0
                                (RECV_TYPE_ARG3)state->blksize + 4,
1107
0
                                0,
1108
0
                                (struct sockaddr *)&remote_addr,
1109
0
                                &fromlen);
1110
0
  if((state->rbytes >= 0) && fromlen) {
1111
0
    if(state->remote_pinned) {
1112
      /* pinned, verify that it comes from the same address */
1113
0
      if((state->remote_addrlen != fromlen) ||
1114
0
         memcmp(&remote_addr, &state->remote_addr, fromlen)) {
1115
0
        failf(data, "Data received from another address");
1116
0
        return CURLE_RECV_ERROR;
1117
0
      }
1118
0
    }
1119
0
    else {
1120
      /* pin address on first use */
1121
0
      state->remote_pinned = TRUE;
1122
0
      state->remote_addrlen = fromlen;
1123
0
      memcpy(&state->remote_addr, &remote_addr, fromlen);
1124
0
    }
1125
0
  }
1126
1127
  /* Sanity check packet length */
1128
0
  if(state->rbytes < 4) {
1129
0
    failf(data, "Received too short packet");
1130
    /* Not a timeout, but how best to handle it? */
1131
0
    state->event = TFTP_EVENT_TIMEOUT;
1132
0
  }
1133
0
  else {
1134
    /* The event is given by the TFTP packet time */
1135
0
    unsigned short event = getrpacketevent(&state->rpacket);
1136
0
    state->event = (tftp_event_t)event;
1137
1138
0
    switch(state->event) {
1139
0
    case TFTP_EVENT_DATA:
1140
      /* Do not pass to the client empty or retransmitted packets */
1141
0
      if(state->rbytes > 4 &&
1142
0
         (NEXT_BLOCKNUM(state->block) == getrpacketblock(&state->rpacket))) {
1143
0
        result = Curl_client_write(data, CLIENTWRITE_BODY,
1144
0
                                   (char *)state->rpacket.data + 4,
1145
0
                                   state->rbytes-4);
1146
0
        if(result) {
1147
0
          tftp_state_machine(state, TFTP_EVENT_ERROR);
1148
0
          return result;
1149
0
        }
1150
0
      }
1151
0
      break;
1152
0
    case TFTP_EVENT_ERROR:
1153
0
    {
1154
0
      unsigned short error = getrpacketblock(&state->rpacket);
1155
0
      char *str = (char *)state->rpacket.data + 4;
1156
0
      size_t strn = state->rbytes - 4;
1157
0
      state->error = (tftp_error_t)error;
1158
0
      if(tftp_strnlen(str, strn) < strn)
1159
0
        infof(data, "TFTP error: %s", str);
1160
0
      break;
1161
0
    }
1162
0
    case TFTP_EVENT_ACK:
1163
0
      break;
1164
0
    case TFTP_EVENT_OACK:
1165
0
      result = tftp_parse_option_ack(state,
1166
0
                                     (const char *)state->rpacket.data + 2,
1167
0
                                     state->rbytes-2);
1168
0
      if(result)
1169
0
        return result;
1170
0
      break;
1171
0
    case TFTP_EVENT_RRQ:
1172
0
    case TFTP_EVENT_WRQ:
1173
0
    default:
1174
0
      failf(data, "%s", "Internal error: Unexpected packet");
1175
0
      break;
1176
0
    }
1177
1178
    /* Update the progress meter */
1179
0
    if(Curl_pgrsUpdate(data)) {
1180
0
      tftp_state_machine(state, TFTP_EVENT_ERROR);
1181
0
      return CURLE_ABORTED_BY_CALLBACK;
1182
0
    }
1183
0
  }
1184
0
  return result;
1185
0
}
1186
1187
/**********************************************************
1188
 *
1189
 * tftp_state_timeout
1190
 *
1191
 * Check if timeouts have been reached
1192
 *
1193
 **********************************************************/
1194
static timediff_t tftp_state_timeout(struct tftp_conn *state,
1195
                                     tftp_event_t *event)
1196
0
{
1197
0
  time_t current;
1198
0
  timediff_t timeout_ms;
1199
1200
0
  if(event)
1201
0
    *event = TFTP_EVENT_NONE;
1202
1203
0
  timeout_ms = Curl_timeleft(state->data, NULL,
1204
0
                             (state->state == TFTP_STATE_START));
1205
0
  if(timeout_ms < 0) {
1206
0
    state->error = TFTP_ERR_TIMEOUT;
1207
0
    state->state = TFTP_STATE_FIN;
1208
0
    return timeout_ms;
1209
0
  }
1210
0
  current = time(NULL);
1211
0
  if(current > state->rx_time + state->retry_time) {
1212
0
    if(event)
1213
0
      *event = TFTP_EVENT_TIMEOUT;
1214
0
    state->rx_time = time(NULL); /* update even though we received nothing */
1215
0
  }
1216
1217
0
  return timeout_ms;
1218
0
}
1219
1220
/**********************************************************
1221
 *
1222
 * tftp_multi_statemach
1223
 *
1224
 * Handle single RX socket event and return
1225
 *
1226
 **********************************************************/
1227
static CURLcode tftp_multi_statemach(struct Curl_easy *data, bool *done)
1228
0
{
1229
0
  tftp_event_t event;
1230
0
  CURLcode result = CURLE_OK;
1231
0
  struct connectdata *conn = data->conn;
1232
0
  struct tftp_conn *state = Curl_conn_meta_get(conn, CURL_META_TFTP_CONN);
1233
0
  timediff_t timeout_ms;
1234
1235
0
  *done = FALSE;
1236
0
  if(!state)
1237
0
    return CURLE_FAILED_INIT;
1238
1239
0
  timeout_ms = tftp_state_timeout(state, &event);
1240
0
  if(timeout_ms < 0) {
1241
0
    failf(data, "TFTP response timeout");
1242
0
    return CURLE_OPERATION_TIMEDOUT;
1243
0
  }
1244
0
  if(event != TFTP_EVENT_NONE) {
1245
0
    result = tftp_state_machine(state, event);
1246
0
    if(result)
1247
0
      return result;
1248
0
    *done = (state->state == TFTP_STATE_FIN);
1249
0
    if(*done)
1250
      /* Tell curl we are done */
1251
0
      Curl_xfer_setup_nop(data);
1252
0
  }
1253
0
  else {
1254
    /* no timeouts to handle, check our socket */
1255
0
    int rc = SOCKET_READABLE(state->sockfd, 0);
1256
1257
0
    if(rc == -1) {
1258
      /* bail out */
1259
0
      int error = SOCKERRNO;
1260
0
      char buffer[STRERROR_LEN];
1261
0
      failf(data, "%s", curlx_strerror(error, buffer, sizeof(buffer)));
1262
0
      state->event = TFTP_EVENT_ERROR;
1263
0
    }
1264
0
    else if(rc) {
1265
0
      result = tftp_receive_packet(data, state);
1266
0
      if(result)
1267
0
        return result;
1268
0
      result = tftp_state_machine(state, state->event);
1269
0
      if(result)
1270
0
        return result;
1271
0
      *done = (state->state == TFTP_STATE_FIN);
1272
0
      if(*done)
1273
        /* Tell curl we are done */
1274
0
        Curl_xfer_setup_nop(data);
1275
0
    }
1276
    /* if rc == 0, then select() timed out */
1277
0
  }
1278
1279
0
  return result;
1280
0
}
1281
1282
/**********************************************************
1283
 *
1284
 * tftp_doing
1285
 *
1286
 * Called from multi.c while DOing
1287
 *
1288
 **********************************************************/
1289
static CURLcode tftp_doing(struct Curl_easy *data, bool *dophase_done)
1290
0
{
1291
0
  CURLcode result;
1292
0
  result = tftp_multi_statemach(data, dophase_done);
1293
1294
0
  if(*dophase_done) {
1295
0
    DEBUGF(infof(data, "DO phase is complete"));
1296
0
  }
1297
0
  else if(!result) {
1298
    /* The multi code does not have this logic for the DOING state so we
1299
       provide it for TFTP since it may do the entire transfer in this
1300
       state. */
1301
0
    if(Curl_pgrsUpdate(data))
1302
0
      result = CURLE_ABORTED_BY_CALLBACK;
1303
0
    else
1304
0
      result = Curl_speedcheck(data, curlx_now());
1305
0
  }
1306
0
  return result;
1307
0
}
1308
1309
/**********************************************************
1310
 *
1311
 * tftp_perform
1312
 *
1313
 * Entry point for transfer from tftp_do, starts state mach
1314
 *
1315
 **********************************************************/
1316
static CURLcode tftp_perform(struct Curl_easy *data, bool *dophase_done)
1317
0
{
1318
0
  CURLcode result = CURLE_OK;
1319
0
  struct connectdata *conn = data->conn;
1320
0
  struct tftp_conn *state = Curl_conn_meta_get(conn, CURL_META_TFTP_CONN);
1321
1322
0
  *dophase_done = FALSE;
1323
0
  if(!state)
1324
0
    return CURLE_FAILED_INIT;
1325
1326
0
  result = tftp_state_machine(state, TFTP_EVENT_INIT);
1327
1328
0
  if((state->state == TFTP_STATE_FIN) || result)
1329
0
    return result;
1330
1331
0
  result = tftp_multi_statemach(data, dophase_done);
1332
1333
0
  if(*dophase_done)
1334
0
    DEBUGF(infof(data, "DO phase is complete"));
1335
1336
0
  return result;
1337
0
}
1338
1339
1340
/**********************************************************
1341
 *
1342
 * tftp_do
1343
 *
1344
 * The do callback
1345
 *
1346
 * This callback initiates the TFTP transfer
1347
 *
1348
 **********************************************************/
1349
1350
static CURLcode tftp_do(struct Curl_easy *data, bool *done)
1351
0
{
1352
0
  struct connectdata *conn = data->conn;
1353
0
  struct tftp_conn *state = Curl_conn_meta_get(conn, CURL_META_TFTP_CONN);
1354
0
  CURLcode result;
1355
1356
0
  *done = FALSE;
1357
1358
0
  if(!state) {
1359
0
    result = tftp_connect(data, done);
1360
0
    if(result)
1361
0
      return result;
1362
1363
0
    state = Curl_conn_meta_get(conn, CURL_META_TFTP_CONN);
1364
0
    if(!state)
1365
0
      return CURLE_TFTP_ILLEGAL;
1366
0
  }
1367
1368
0
  result = tftp_perform(data, done);
1369
1370
  /* If tftp_perform() returned an error, use that for return code. If it
1371
     was OK, see if tftp_translate_code() has an error. */
1372
0
  if(!result)
1373
    /* If we have encountered an internal tftp error, translate it. */
1374
0
    result = tftp_translate_code(state->error);
1375
1376
0
  return result;
1377
0
}
1378
1379
static CURLcode tftp_setup_connection(struct Curl_easy *data,
1380
                                      struct connectdata *conn)
1381
0
{
1382
0
  char *type;
1383
1384
0
  conn->transport_wanted = TRNSPRT_UDP;
1385
1386
  /* TFTP URLs support an extension like ";mode=<typecode>" that
1387
   * we will try to get now! */
1388
0
  type = strstr(data->state.up.path, ";mode=");
1389
1390
0
  if(!type)
1391
0
    type = strstr(conn->host.rawalloc, ";mode=");
1392
1393
0
  if(type) {
1394
0
    char command;
1395
0
    *type = 0;                   /* it was in the middle of the hostname */
1396
0
    command = Curl_raw_toupper(type[6]);
1397
1398
0
    switch(command) {
1399
0
    case 'A': /* ASCII mode */
1400
0
    case 'N': /* NETASCII mode */
1401
0
      data->state.prefer_ascii = TRUE;
1402
0
      break;
1403
1404
0
    case 'O': /* octet mode */
1405
0
    case 'I': /* binary mode */
1406
0
    default:
1407
      /* switch off ASCII */
1408
0
      data->state.prefer_ascii = FALSE;
1409
0
      break;
1410
0
    }
1411
0
  }
1412
1413
0
  return CURLE_OK;
1414
0
}
1415
#endif