Coverage Report

Created: 2026-10-15 06:25

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