Coverage Report

Created: 2026-12-01 06:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl/lib/ftp.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
27
#ifndef CURL_DISABLE_FTP
28
29
#ifdef HAVE_NETINET_IN_H
30
#include <netinet/in.h>
31
#endif
32
#ifdef HAVE_ARPA_INET_H
33
#include <arpa/inet.h>
34
#endif
35
#ifdef HAVE_NETDB_H
36
#include <netdb.h>
37
#endif
38
#ifdef __VMS
39
#include <in.h>
40
#include <inet.h>
41
#endif
42
43
#include "sendf.h"
44
#include "curl_addrinfo.h"
45
#include "curl_trc.h"
46
#include "if2ip.h"
47
#include "progress.h"
48
#include "transfer.h"
49
#include "escape.h"
50
#include "ftp.h"
51
#include "ftp-int.h"
52
#include "ftplistparser.h"
53
#include "curl_range.h"
54
#include "strcase.h"
55
#include "vtls/vtls.h"
56
#include "cfilters.h"
57
#include "cf-socket.h"
58
#include "connect.h"
59
#include "curlx/inet_ntop.h"
60
#include "curlx/inet_pton.h"
61
#include "select.h"
62
#include "parsedate.h" /* for the week day and month names */
63
#include "sockaddr.h" /* required for Curl_sockaddr_storage */
64
#include "multiif.h"
65
#include "url.h"
66
#include "http_proxy.h"
67
#include "vdns/hostip.h"
68
#include "curlx/strdup.h"
69
#include "curlx/strerr.h"
70
#include "curlx/strparse.h"
71
#include "curl_ctype.h"
72
73
#ifndef NI_MAXHOST
74
#define NI_MAXHOST 1025
75
#endif
76
#ifndef INET_ADDRSTRLEN
77
#define INET_ADDRSTRLEN 16
78
#endif
79
80
/* macro to check for a three-digit ftp status code at the start of the
81
   given string */
82
#define STATUSCODE(line) \
83
0
  (ISDIGIT((line)[0]) && ISDIGIT((line)[1]) && ISDIGIT((line)[2]))
84
85
/* macro to check for the last line in an FTP server response */
86
0
#define LASTLINE(line) (STATUSCODE(line) && (' ' == (line)[3]))
87
88
#ifdef CURLVERBOSE
89
/* for tracing purposes */
90
static const char * const ftp_state_names[] = {
91
  "STOP",
92
  "WAIT220",
93
  "AUTH",
94
  "USER",
95
  "PASS",
96
  "ACCT",
97
  "PBSZ",
98
  "PROT",
99
  "CCC",
100
  "PWD",
101
  "SYST",
102
  "NAMEFMT",
103
  "QUOTE",
104
  "RETR_PREQUOTE",
105
  "STOR_PREQUOTE",
106
  "LIST_PREQUOTE",
107
  "POSTQUOTE",
108
  "CWD",
109
  "MKD",
110
  "MDTM",
111
  "TYPE",
112
  "LIST_TYPE",
113
  "RETR_LIST_TYPE",
114
  "RETR_TYPE",
115
  "STOR_TYPE",
116
  "SIZE",
117
  "RETR_SIZE",
118
  "STOR_SIZE",
119
  "REST",
120
  "RETR_REST",
121
  "PORT",
122
  "PRET",
123
  "PASV",
124
  "LIST",
125
  "RETR",
126
  "STOR"
127
};
128
#define FTP_CSTATE(ftpc)   ((ftpc) ? ftp_state_names[(ftpc)->state] : "???")
129
130
#endif /* CURLVERBOSE */
131
132
#if defined(CURL_HAVE_DIAG) && !defined(__clang__)
133
/* GCC sometimes gets confused about the ftp_state_names[] access */
134
#pragma GCC diagnostic push
135
#pragma GCC diagnostic ignored "-Warray-bounds"
136
#endif
137
138
/* This is the ONLY way to change FTP state! */
139
static void ftp_state_low(struct Curl_easy *data,
140
                          struct cf_ftp_ctx *ftpc,
141
                          ftpstate newstate
142
#ifdef DEBUGBUILD
143
                          , int lineno
144
#endif
145
  )
146
0
{
147
0
  if(ftpc->state != newstate) {
148
0
#ifdef DEBUGBUILD
149
0
    NOVERBOSE((void)lineno);
150
0
    CURL_TRC_FTP(data, "[%s] -> [%s] (line %d)", FTP_CSTATE(ftpc),
151
0
                 ftp_state_names[newstate], lineno);
152
#else
153
    CURL_TRC_FTP(data, "[%s] -> [%s]", FTP_CSTATE(ftpc),
154
                 ftp_state_names[newstate]);
155
#endif
156
0
  }
157
0
  ftpc->state = newstate;
158
0
}
159
160
#if defined(CURL_HAVE_DIAG) && !defined(__clang__)
161
#pragma GCC diagnostic pop
162
#endif
163
164
/* Local API functions */
165
#ifndef DEBUGBUILD
166
#define ftp_state(x, y, z) ftp_state_low(x, y, z)
167
#else /* !DEBUGBUILD */
168
0
#define ftp_state(x, y, z) ftp_state_low(x, y, z, __LINE__)
169
#endif /* DEBUGBUILD */
170
171
static struct cf_ftp_ctx *ftp_get_cf_ctx(struct connectdata *conn);
172
static CURLcode ftp_state_mdtm(struct Curl_easy *data,
173
                               struct cf_ftp_ctx *ftpc,
174
                               struct FTP *ftp);
175
static CURLcode ftp_state_quote(struct Curl_easy *data,
176
                                struct cf_ftp_ctx *ftpc,
177
                                struct FTP *ftp,
178
                                bool init, ftpstate instate);
179
static CURLcode ftp_nb_type(struct Curl_easy *data,
180
                            struct cf_ftp_ctx *ftpc,
181
                            struct FTP *ftp,
182
                            bool ascii, ftpstate newstate);
183
static CURLcode getftpresponse(struct Curl_easy *data, size_t *nreadp,
184
                               int *ftpcodep);
185
186
static void freedirs(struct cf_ftp_ctx *ftpc)
187
0
{
188
0
  curlx_safefree(ftpc->dirs);
189
0
  ftpc->dirdepth = 0;
190
0
  curlx_safefree(ftpc->rawpath);
191
0
  ftpc->file = NULL;
192
0
}
193
194
static size_t numof_slashes(const char *str)
195
0
{
196
0
  const char *slashPos;
197
0
  size_t num = 0;
198
0
  do {
199
0
    slashPos = strchr(str, '/');
200
0
    if(slashPos) {
201
0
      ++num;
202
0
      str = slashPos + 1;
203
0
    }
204
0
  } while(slashPos);
205
0
  return num;
206
0
}
207
208
0
#define FTP_MAX_DIR_DEPTH 1000
209
210
/***********************************************************************
211
 *
212
 * ftp_parse_url_path()
213
 *
214
 * Parse the URL path into separate path components.
215
 *
216
 */
217
static CURLcode ftp_parse_url_path(struct Curl_easy *data,
218
                                   struct cf_ftp_ctx *ftpc,
219
                                   struct FTP *ftp)
220
0
{
221
0
  const char *slashPos = NULL;
222
0
  const char *fileName = NULL;
223
0
  CURLcode result = CURLE_OK;
224
0
  const char *rawPath = NULL; /* URL-decoded "raw" path */
225
0
  size_t pathLen = 0;
226
227
0
  ftpc->cwdfail = FALSE;
228
229
0
  if(ftpc->rawpath)
230
0
    freedirs(ftpc);
231
  /* URL-decode ftp path before further evaluation */
232
0
  result = Curl_urldecode(ftp->path, 0, &ftpc->rawpath, &pathLen, REJECT_CTRL);
233
0
  if(result) {
234
0
    failf(data, "path contains control characters");
235
0
    return result;
236
0
  }
237
0
  rawPath = ftpc->rawpath;
238
239
0
  switch(data->set.ftp_filemethod) {
240
0
  case FTPFILE_NOCWD: /* fastest, but less standard-compliant */
241
242
0
    if((pathLen > 0) && (rawPath[pathLen - 1] != '/'))
243
0
      fileName = rawPath;  /* this is a full file path */
244
    /* else: ftpc->file is not used anywhere other than for operations on
245
             a file. In other words, never for directory operations,
246
             so we can safely leave filename as NULL here and use it as a
247
             argument in dir/file decisions. */
248
0
    break;
249
250
0
  case FTPFILE_SINGLECWD:
251
0
    slashPos = strrchr(rawPath, '/');
252
0
    if(slashPos) {
253
      /* get path before last slash, except for / */
254
0
      size_t dirlen = slashPos - rawPath;
255
0
      if(dirlen == 0)
256
0
        dirlen = 1;
257
258
0
      ftpc->dirs = curlx_calloc(1, sizeof(ftpc->dirs[0]));
259
0
      if(!ftpc->dirs)
260
0
        return CURLE_OUT_OF_MEMORY;
261
262
0
      ftpc->dirs[0].start = 0;
263
0
      ftpc->dirs[0].len = (int)dirlen;
264
0
      ftpc->dirdepth = 1; /* we consider it to be a single directory */
265
0
      fileName = slashPos + 1; /* rest is filename */
266
0
    }
267
0
    else
268
0
      fileName = rawPath; /* filename only (or empty) */
269
0
    break;
270
271
0
  default: /* allow pretty much anything */
272
0
  case FTPFILE_MULTICWD: {
273
    /* current position: begin of next path component */
274
0
    const char *curPos = rawPath;
275
276
    /* number of entries to allocate for the 'dirs' array */
277
0
    size_t dirAlloc = numof_slashes(rawPath);
278
279
0
    if(dirAlloc >= FTP_MAX_DIR_DEPTH)
280
      /* suspiciously deep directory hierarchy */
281
0
      return CURLE_URL_MALFORMAT;
282
283
0
    if(dirAlloc) {
284
0
      ftpc->dirs = curlx_calloc(dirAlloc, sizeof(ftpc->dirs[0]));
285
0
      if(!ftpc->dirs)
286
0
        return CURLE_OUT_OF_MEMORY;
287
288
      /* parse the URL path into separate path components */
289
0
      while(dirAlloc--) {
290
0
        const char *spos = strchr(curPos, '/');
291
0
        size_t clen = spos - curPos;
292
293
        /* path starts with a slash: add that as a directory */
294
0
        if(!clen && (ftpc->dirdepth == 0))
295
0
          ++clen;
296
297
        /* we skip empty path components, like "x//y" since the FTP command
298
           CWD requires a parameter and a non-existent parameter a) does not
299
           work on many servers and b) has no effect on the others. */
300
0
        if(clen) {
301
0
          ftpc->dirs[ftpc->dirdepth].start = (int)(curPos - rawPath);
302
0
          ftpc->dirs[ftpc->dirdepth].len = (int)clen;
303
0
          ftpc->dirdepth++;
304
0
        }
305
0
        curPos = spos + 1;
306
0
      }
307
0
    }
308
0
    fileName = curPos; /* the rest is the filename (or empty) */
309
0
  }
310
0
    break;
311
0
  } /* switch */
312
313
0
  if(fileName && *fileName)
314
0
    ftpc->file = fileName;
315
0
  else
316
0
    ftpc->file = NULL; /* instead of point to a NUL byte,
317
                          we make it a NULL pointer */
318
319
0
  if(data->state.upload && !ftpc->file && (ftp->transfer == PPTRANSFER_BODY)) {
320
    /* We need a filename when uploading. Return error! */
321
0
    failf(data, "Uploading to a URL without a filename");
322
0
    return CURLE_URL_MALFORMAT;
323
0
  }
324
325
0
  ftpc->cwddone = FALSE; /* default to not done */
326
327
0
  if((data->set.ftp_filemethod == FTPFILE_NOCWD) && (rawPath[0] == '/'))
328
0
    ftpc->cwddone = TRUE; /* skip CWD for absolute paths */
329
0
  else { /* newly created FTP connections are already in entry path */
330
0
    const char *oldPath = data->conn->bits.reuse ? ftpc->prevpath : "";
331
0
    if(oldPath) {
332
0
      size_t n = pathLen;
333
0
      if(data->set.ftp_filemethod == FTPFILE_NOCWD)
334
0
        n = 0; /* CWD to entry for relative paths */
335
0
      else
336
0
        n -= ftpc->file ? strlen(ftpc->file) : 0;
337
338
0
      if((strlen(oldPath) == n) && rawPath && !strncmp(rawPath, oldPath, n)) {
339
0
        infof(data, "Request has same path as previous transfer");
340
0
        ftpc->cwddone = TRUE;
341
0
      }
342
0
    }
343
0
  }
344
345
0
  return CURLE_OK;
346
0
}
347
348
/***********************************************************************
349
 *
350
 * ftp_need_type()
351
 *
352
 * Returns TRUE if we in the current situation should send TYPE
353
 */
354
static int ftp_need_type(struct cf_ftp_ctx *ftpc,
355
                         bool ascii_wanted)
356
0
{
357
0
  return ftpc->transfertype != (ascii_wanted ? 'A' : 'I');
358
0
}
359
360
static void ftp_close_chain_data(struct Curl_easy *data,
361
                                 struct cf_ftp_ctx *ftpc)
362
0
{
363
0
  CURL_TRC_FTP(data, "[%s] closing DATA connection", FTP_CSTATE(ftpc));
364
0
  Curl_cfchain_reset(&ftpc->chain_data, data);
365
0
}
366
367
#ifdef CURL_PREFER_LF_LINEENDS
368
/*
369
 * Lineend Conversions
370
 * On ASCII transfers, e.g. directory listings, we might get lines
371
 * ending in '\r\n' and we prefer '\n'.
372
 * We might also get a lonely '\r' which we convert into a '\n'.
373
 */
374
struct ftp_cw_lc_ctx {
375
  struct Curl_cwriter super;
376
  bool newline_pending;
377
};
378
379
static CURLcode ftp_cw_lc_write(struct Curl_easy *data,
380
                                struct Curl_cwriter *writer, int type,
381
                                const char *buf, size_t blen)
382
0
{
383
0
  static const char nl = '\n';
384
0
  struct ftp_cw_lc_ctx *ctx = writer->ctx;
385
0
  struct cf_ftp_ctx *ftpc = ftp_get_cf_ctx(data->conn);
386
387
0
  if(!ftpc)
388
0
    return CURLE_FAILED_INIT;
389
390
0
  if(!(type & CLIENTWRITE_BODY) || ftpc->transfertype != 'A')
391
0
    return Curl_cwriter_write(data, writer->next, type, buf, blen);
392
393
  /* ASCII mode BODY data, convert lineends */
394
0
  while(blen) {
395
    /* do not pass EOS when writing parts */
396
0
    int chunk_type = (type & ~CLIENTWRITE_EOS);
397
0
    const char *cp;
398
0
    size_t chunk_len;
399
0
    CURLcode result;
400
401
0
    if(ctx->newline_pending) {
402
0
      if(buf[0] != '\n') {
403
        /* previous chunk ended in '\r' and we do not see a '\n' in this one,
404
         * need to write a newline. */
405
0
        result = Curl_cwriter_write(data, writer->next, chunk_type, &nl, 1);
406
0
        if(result)
407
0
          return result;
408
0
      }
409
      /* either we wrote the newline or it is part of the next chunk of bytes
410
       * we write. */
411
0
      ctx->newline_pending = FALSE;
412
0
    }
413
414
0
    cp = memchr(buf, '\r', blen);
415
0
    if(!cp)
416
0
      break;
417
418
    /* write the bytes before the '\r', excluding the '\r' */
419
0
    chunk_len = cp - buf;
420
0
    if(chunk_len) {
421
0
      result = Curl_cwriter_write(data, writer->next, chunk_type,
422
0
                                  buf, chunk_len);
423
0
      if(result)
424
0
        return result;
425
0
    }
426
    /* skip the '\r', we now have a newline pending */
427
0
    buf = cp + 1;
428
0
    blen = blen - chunk_len - 1;
429
0
    ctx->newline_pending = TRUE;
430
0
  }
431
432
  /* Any remaining data does not contain a '\r' */
433
0
  if(blen) {
434
0
    DEBUGASSERT(!ctx->newline_pending);
435
0
    return Curl_cwriter_write(data, writer->next, type, buf, blen);
436
0
  }
437
0
  else if(type & CLIENTWRITE_EOS) {
438
    /* EndOfStream, if we have a trailing cr, now is the time to write it */
439
0
    if(ctx->newline_pending) {
440
0
      ctx->newline_pending = FALSE;
441
0
      return Curl_cwriter_write(data, writer->next, type, &nl, 1);
442
0
    }
443
    /* Always pass on the EOS type indicator */
444
0
    return Curl_cwriter_write(data, writer->next, type, buf, 0);
445
0
  }
446
0
  return CURLE_OK;
447
0
}
448
449
static const struct Curl_cwtype ftp_cw_lc = {
450
  "ftp-lineconv",
451
  NULL,
452
  0,
453
  Curl_cwriter_def_init,
454
  ftp_cw_lc_write,
455
  Curl_cwriter_def_flush,
456
  Curl_cwriter_def_close,
457
  sizeof(struct ftp_cw_lc_ctx)
458
};
459
460
#endif /* CURL_PREFER_LF_LINEENDS */
461
462
/***********************************************************************
463
 *
464
 * ftp_check_ctrl_on_data_wait()
465
 *
466
 */
467
static CURLcode ftp_check_ctrl_on_data_wait(struct Curl_easy *data,
468
                                            struct cf_ftp_ctx *ftpc)
469
0
{
470
0
  struct connectdata *conn = data->conn;
471
0
  curl_socket_t ctrl_sock = conn->chain.sock;
472
0
  struct pingpong *pp = &ftpc->pp;
473
0
  size_t nread;
474
0
  int ftpcode;
475
0
  bool response = FALSE;
476
477
  /* First check whether there is a cached response from server */
478
0
  if(curlx_dyn_len(&pp->recvbuf)) {
479
0
    const char *l = curlx_dyn_ptr(&pp->recvbuf);
480
0
    if(!ISDIGIT(*l) || (*l > '3')) {
481
      /* Data connection could not be established, let's return */
482
0
      infof(data, "There is negative response in cache while serv connect");
483
0
      (void)getftpresponse(data, &nread, &ftpcode);
484
0
      return CURLE_FTP_ACCEPT_FAILED;
485
0
    }
486
0
  }
487
488
0
  if(pp->overflow)
489
    /* there is pending control data still in the buffer to read */
490
0
    response = TRUE;
491
0
  else {
492
0
    int socketstate = SOCKET_READABLE(ctrl_sock, 0);
493
    /* see if the connection request is already here */
494
0
    switch(socketstate) {
495
0
    case -1: /* error */
496
      /* let's die here */
497
0
      failf(data, "Error while waiting for server connect");
498
0
      return CURLE_FTP_ACCEPT_FAILED;
499
0
    default:
500
0
      if(socketstate & CURL_CSELECT_IN)
501
0
        response = TRUE;
502
0
      break;
503
0
    }
504
0
  }
505
506
0
  if(response) {
507
0
    infof(data, "Ctrl conn has data while waiting for data conn");
508
0
    if(pp->overflow > 3) {
509
0
      const char *r = curlx_dyn_ptr(&pp->recvbuf);
510
0
      size_t len = curlx_dyn_len(&pp->recvbuf);
511
512
0
      DEBUGASSERT((pp->overflow + pp->nfinal) <= curlx_dyn_len(&pp->recvbuf));
513
      /* move over the most recently handled response line */
514
0
      r += pp->nfinal;
515
0
      len -= pp->nfinal;
516
517
0
      if((len > 3) && LASTLINE(r)) {
518
0
        curl_off_t status;
519
0
        if(!curlx_str_number(&r, &status, 999) && (status == 226)) {
520
          /* funny timing situation where we get the final message on the
521
             control connection before traffic on the data connection has been
522
             noticed. Leave the 226 in there and use this as a trigger to read
523
             the data socket. */
524
0
          infof(data, "Got 226 before data activity");
525
0
          return CURLE_OK;
526
0
        }
527
0
      }
528
0
    }
529
530
0
    (void)getftpresponse(data, &nread, &ftpcode);
531
532
0
    infof(data, "FTP code: %03d", ftpcode);
533
534
0
    if(ftpcode / 100 > 3)
535
0
      return CURLE_FTP_ACCEPT_FAILED;
536
537
0
    return CURLE_WEIRD_SERVER_REPLY;
538
0
  }
539
540
0
  return CURLE_OK;
541
0
}
542
543
/***********************************************************************
544
 *
545
 * ftp_initiate_transfer()
546
 *
547
 * After connection from server is accepted this function is called to
548
 * setup transfer parameters and initiate the data transfer.
549
 *
550
 */
551
static CURLcode ftp_initiate_transfer(struct Curl_easy *data,
552
                                      struct cf_ftp_ctx *ftpc)
553
0
{
554
0
  CURLcode result = CURLE_OK;
555
0
  bool connected;
556
557
0
  CURL_TRC_FTP(data, "ftp_initiate_transfer()");
558
0
  result = Curl_cfchain_connect(data, &ftpc->chain_data, TRUE,
559
0
                                &connected);
560
0
  if(result || !connected)
561
0
    return result;
562
563
0
  if(data->state.upload) {
564
    /* When we know we are uploading a specified file, we can get the file
565
       size prior to the actual upload. */
566
0
    Curl_pgrsSetUploadSize(data, data->state.infilesize);
567
568
    /* FTP upload, shutdown DATA, ignore shutdown errors, as we rely
569
     * on the server response on the CONTROL connection. */
570
0
    Curl_xfer_setup_send(data);
571
0
  }
572
0
  else {
573
    /* FTP download, shutdown, do not ignore errors */
574
0
    Curl_xfer_setup_recv(data, data->req.size);
575
0
  }
576
577
0
  ftpc->pp.pending_resp = TRUE; /* expect server response */
578
0
  ftpc->data_shutdown = FALSE;
579
0
  ftp_state(data, ftpc, FTP_STOP);
580
0
  return CURLE_OK;
581
0
}
582
583
static bool ftp_endofresp(struct Curl_easy *data, struct connectdata *conn,
584
                          const char *line, size_t len, int *code)
585
0
{
586
0
  curl_off_t status;
587
0
  (void)data;
588
0
  (void)conn;
589
590
0
  if((len > 3) && LASTLINE(line) && !curlx_str_number(&line, &status, 999)) {
591
0
    *code = (int)status;
592
0
    return TRUE;
593
0
  }
594
595
0
  return FALSE;
596
0
}
597
598
static CURLcode ftp_readresp(struct Curl_easy *data,
599
                             struct cf_ftp_ctx *ftpc,
600
                             struct pingpong *pp,
601
                             int *ftpcodep, /* return the ftp-code if done */
602
                             size_t *size) /* size of the response */
603
0
{
604
0
  int code;
605
0
  CURLcode result = Curl_pp_readresp(data, pp, &code, size);
606
0
  DEBUGASSERT(ftpcodep);
607
608
  /* store the latest code for later retrieval, except during shutdown */
609
0
  if(!ftpc->sent_quit)
610
0
    data->info.httpcode = code;
611
612
0
  *ftpcodep = code;
613
614
0
  if(code == 421) {
615
    /* 421 means "Service not available, closing control connection." and FTP
616
     * servers use it to signal that idle session timeout has been exceeded.
617
     * If we ignored the response, it could end up hanging in some cases.
618
     *
619
     * This response code can come at any point so having it treated
620
     * generically is a good idea.
621
     */
622
0
    infof(data, "We got a 421 - timeout");
623
0
    ftp_state(data, ftpc, FTP_STOP);
624
0
    return CURLE_OPERATION_TIMEDOUT;
625
0
  }
626
627
0
  return result;
628
0
}
629
630
/* --- parse FTP server responses --- */
631
632
/*
633
 * getftpresponse() is a BLOCKING function to read the full response from a
634
 * server after a command.
635
 *
636
 */
637
static CURLcode getftpresponse(struct Curl_easy *data,
638
                               size_t *nreadp, /* return number of bytes
639
                                                  read */
640
                               int *ftpcodep) /* return the ftp-code */
641
0
{
642
  /*
643
   * We cannot read one byte per read() and then go back to select() as the
644
   * OpenSSL read() does not grok that properly.
645
   *
646
   * Alas, read as much as possible, split up into lines, use the ending
647
   * line in a response or continue reading. */
648
649
0
  struct connectdata *conn = data->conn;
650
0
  curl_socket_t sockfd = conn->chain.sock;
651
0
  CURLcode result = CURLE_OK;
652
0
  struct cf_ftp_ctx *ftpc = ftp_get_cf_ctx(data->conn);
653
0
  struct pingpong *pp = &ftpc->pp;
654
0
  size_t nread;
655
0
  int cache_skip = 0;
656
0
  DEBUGASSERT(ftpcodep);
657
658
0
  CURL_TRC_FTP(data, "getftpresponse start");
659
0
  *nreadp = 0;
660
0
  *ftpcodep = 0; /* 0 for errors */
661
662
0
  if(!ftpc)
663
0
    return CURLE_FAILED_INIT;
664
665
0
  while(!*ftpcodep && !result) {
666
    /* check and reset timeout value every lap */
667
0
    timediff_t timeout = Curl_pp_state_timeleft_ms(data, pp);
668
0
    timediff_t interval_ms;
669
670
0
    if(timeout <= 0) {
671
0
      failf(data, "FTP response timeout");
672
0
      return CURLE_OPERATION_TIMEDOUT; /* already too little time */
673
0
    }
674
675
0
    interval_ms = 1000;  /* use 1 second timeout intervals */
676
0
    if(timeout < interval_ms)
677
0
      interval_ms = timeout;
678
679
    /*
680
     * Since this function is blocking, we need to wait here for input on the
681
     * connection and only then we call the response reading function. We do
682
     * timeout at least every second to make the timeout check run.
683
     *
684
     * A caution here is that the ftp_readresp() function has a cache that may
685
     * contain pieces of a response from the previous invoke and we need to
686
     * make sure we do not wait for input while there is unhandled data in
687
     * that cache. Also, if the cache is there, we call ftp_readresp() and
688
     * the cache was not good enough to continue we must not busy-loop around
689
     * this function.
690
     *
691
     */
692
693
0
    if(curlx_dyn_len(&pp->recvbuf) && (cache_skip < 2)) {
694
      /*
695
       * There is a cache left since before. We then skipping the wait for
696
       * socket action, unless this is the same cache like the previous round
697
       * as then the cache was deemed not enough to act on and we then need to
698
       * wait for more data anyway.
699
       */
700
0
    }
701
0
    else if(!Curl_conn_data_pending(data)) {
702
0
      curl_socket_t wsock = Curl_pp_needs_flush(data, pp) ?
703
0
        sockfd : CURL_SOCKET_BAD;
704
0
      int ev = Curl_socket_check(sockfd, wsock, interval_ms);
705
0
      if(ev < 0) {
706
0
        failf(data, "FTP response aborted due to select/poll error: %d",
707
0
              SOCKERRNO);
708
0
        return CURLE_RECV_ERROR;
709
0
      }
710
0
      else if(ev == 0) {
711
0
        result = Curl_pgrsUpdate(data);
712
0
        continue; /* continue in our loop for the timeout duration */
713
0
      }
714
0
    }
715
716
0
    if(Curl_pp_needs_flush(data, pp)) {
717
0
      result = Curl_pp_flushsend(data, pp);
718
0
      if(result)
719
0
        break;
720
0
    }
721
722
0
    result = ftp_readresp(data, ftpc, pp, ftpcodep, &nread);
723
0
    if(result)
724
0
      break;
725
726
0
    if(!nread && curlx_dyn_len(&pp->recvbuf))
727
      /* bump cache skip counter as on repeated skips we must wait for more
728
         data */
729
0
      cache_skip++;
730
0
    else
731
      /* when we got data or there is no cache left, we reset the cache skip
732
         counter */
733
0
      cache_skip = 0;
734
735
0
    *nreadp += nread;
736
737
0
  } /* while there is buffer left and loop is requested */
738
739
0
  pp->pending_resp = FALSE;
740
0
  CURL_TRC_FTP(data, "getftpresponse -> result=%d, nread=%zu, ftpcode=%d",
741
0
               (int)result, *nreadp, *ftpcodep);
742
743
0
  return result;
744
0
}
745
746
static CURLcode ftp_state_user(struct Curl_easy *data,
747
                               struct cf_ftp_ctx *ftpc,
748
                               struct connectdata *conn)
749
0
{
750
0
  CURLcode result = Curl_pp_sendf(data, &ftpc->pp, "USER %s",
751
0
                                  Curl_creds_user(conn->creds));
752
0
  if(!result) {
753
0
    ftpc->ftp_trying_alternative = FALSE;
754
0
    ftp_state(data, ftpc, FTP_USER);
755
0
  }
756
0
  return result;
757
0
}
758
759
static CURLcode ftp_state_pwd(struct Curl_easy *data,
760
                              struct cf_ftp_ctx *ftpc)
761
0
{
762
0
  CURLcode result;
763
0
#ifdef DEBUGBUILD
764
0
  if(!data->id && getenv("CURL_FTP_PWD_STOP"))
765
0
    return CURLE_OK;
766
0
#endif
767
0
  result = Curl_pp_sendf(data, &ftpc->pp, "%s", "PWD");
768
0
  if(!result)
769
0
    ftp_state(data, ftpc, FTP_PWD);
770
771
0
  return result;
772
0
}
773
774
static int pathlen(struct cf_ftp_ctx *ftpc, int num)
775
0
{
776
0
  DEBUGASSERT(ftpc->dirs);
777
0
  DEBUGASSERT(ftpc->dirdepth > num);
778
0
  return ftpc->dirs[num].len;
779
0
}
780
781
static const char *pathpiece(struct cf_ftp_ctx *ftpc, int num)
782
0
{
783
0
  DEBUGASSERT(ftpc->dirs);
784
0
  DEBUGASSERT(ftpc->dirdepth > num);
785
0
  return &ftpc->rawpath[ftpc->dirs[num].start];
786
0
}
787
788
/* This is called after the FTP_QUOTE state is passed.
789
790
   ftp_state_cwd() sends the range of CWD commands to the server to change to
791
   the correct directory. It may also need to send MKD commands to create
792
   missing ones, if that option is enabled. */
793
static CURLcode ftp_state_cwd(struct Curl_easy *data,
794
                              struct cf_ftp_ctx *ftpc,
795
                              struct FTP *ftp)
796
0
{
797
0
  CURLcode result = CURLE_OK;
798
799
0
  if(ftpc->cwddone)
800
    /* already done and fine */
801
0
    result = ftp_state_mdtm(data, ftpc, ftp);
802
0
  else {
803
    /* FTPFILE_NOCWD with full path: expect ftpc->cwddone! */
804
0
    DEBUGASSERT((data->set.ftp_filemethod != FTPFILE_NOCWD) ||
805
0
                !(ftpc->dirdepth && ftpc->rawpath[0] == '/'));
806
807
0
    ftpc->count2 = 0; /* count2 counts failed CWDs */
808
809
0
    if(data->conn->bits.reuse && ftpc->entrypath &&
810
       /* no need to go to entrypath when we have an absolute path */
811
0
       !(ftpc->dirdepth && ftpc->rawpath[0] == '/')) {
812
      /* This is a reused connection. Since we change directory to where the
813
         transfer is taking place, we must first get back to the original dir
814
         where we ended up after login: */
815
0
      ftpc->cwdcount = 0; /* we count this as the first path, then we add one
816
                             for all upcoming ones in the ftp->dirs[] array */
817
0
      result = Curl_pp_sendf(data, &ftpc->pp, "CWD %s", ftpc->entrypath);
818
0
      if(!result)
819
0
        ftp_state(data, ftpc, FTP_CWD);
820
0
    }
821
0
    else {
822
0
      if(ftpc->dirdepth) {
823
0
        ftpc->cwdcount = 1;
824
        /* issue the first CWD, the rest is sent when the CWD responses are
825
           received... */
826
0
        result = Curl_pp_sendf(data, &ftpc->pp, "CWD %.*s",
827
0
                               pathlen(ftpc, 0), pathpiece(ftpc, 0));
828
0
        if(!result)
829
0
          ftp_state(data, ftpc, FTP_CWD);
830
0
      }
831
0
      else {
832
        /* No CWD necessary */
833
0
        result = ftp_state_mdtm(data, ftpc, ftp);
834
0
      }
835
0
    }
836
0
  }
837
0
  return result;
838
0
}
839
840
typedef enum {
841
  EPRT,
842
  PORT,
843
  DONE
844
} ftpport;
845
846
/*
847
 * Parse the CURLOPT_FTPPORT string
848
 * "(ipv4|ipv6|domain|interface)?(:port(-range)?)?"
849
 * and extract addr/addrlen and port_min/port_max.
850
 */
851
static CURLcode ftp_port_parse_string(struct Curl_easy *data,
852
                                      struct connectdata *conn,
853
                                      const char *string_ftpport,
854
                                      struct Curl_sockaddr_storage *ss,
855
                                      unsigned short *port_minp,
856
                                      unsigned short *port_maxp,
857
                                      const char **hostp,
858
                                      char *hbuf, size_t hbuflen)
859
0
{
860
0
  const char *ip_end = NULL;
861
0
  const char *addr = NULL;
862
0
  size_t addrlen = 0;
863
0
  unsigned short port_min = 0;
864
0
  unsigned short port_max = 0;
865
0
  char ipstr[50];
866
#ifndef USE_IPV6
867
  (void)conn;
868
  (void)ss;
869
#endif
870
871
  /* default to nothing */
872
0
  *hostp = NULL;
873
0
  *port_minp = *port_maxp = 0;
874
875
0
  if(!string_ftpport || (strlen(string_ftpport) <= 1))
876
0
    goto done;
877
878
0
#ifdef USE_IPV6
879
0
  if(*string_ftpport == '[') {
880
    /* [ipv6]:port(-range) */
881
0
    const char *ip_start = string_ftpport + 1;
882
0
    ip_end = strchr(ip_start, ']');
883
0
    if(ip_end) {
884
0
      addrlen = ip_end - ip_start;
885
0
      addr = ip_start;
886
0
    }
887
0
  }
888
0
  else
889
0
#endif
890
0
    if(*string_ftpport == ':') {
891
      /* :port */
892
0
      ip_end = string_ftpport;
893
0
    }
894
0
    else {
895
0
      ip_end = strchr(string_ftpport, ':');
896
0
      addr = string_ftpport;
897
0
      if(ip_end) {
898
0
#ifdef USE_IPV6
899
0
        struct sockaddr_in6 * const sa6 = (void *)ss;
900
0
#endif
901
        /* either IPv6 or (ipv4|domain|interface):port(-range) */
902
0
        addrlen = ip_end - string_ftpport;
903
0
#ifdef USE_IPV6
904
0
        if(curlx_inet_pton(AF_INET6, string_ftpport, &sa6->sin6_addr) == 1) {
905
          /* IPv6 */
906
0
          addrlen = strlen(string_ftpport);
907
0
          ip_end = NULL; /* this got no port ! */
908
0
        }
909
0
#endif
910
0
      }
911
0
      else
912
        /* ipv4|interface */
913
0
        addrlen = strlen(string_ftpport);
914
0
    }
915
916
  /* parse the port */
917
0
  if(ip_end) {
918
0
    const char *portp = strchr(ip_end, ':');
919
0
    if(portp) {
920
0
      curl_off_t start;
921
0
      curl_off_t end;
922
0
      portp++;
923
0
      if(!curlx_str_number(&portp, &start, 0xffff)) {
924
0
        port_min = (unsigned short)start;
925
0
        if(!curlx_str_single(&portp, '-') &&
926
0
           !curlx_str_number(&portp, &end, 0xffff))
927
0
          port_max = (unsigned short)end;
928
0
        else
929
0
          port_max = port_min;
930
0
      }
931
0
    }
932
0
  }
933
934
  /* correct errors like :1234-1230 or :-4711 */
935
0
  if(port_min > port_max)
936
0
    port_min = port_max = 0;
937
938
0
  if(addrlen) {
939
0
    const struct Curl_sockaddr_ex *remote_addr =
940
0
      Curl_conn_get_remote_addr(data);
941
942
0
    DEBUGASSERT(remote_addr);
943
0
    DEBUGASSERT(addr);
944
0
    if(!remote_addr || (addrlen >= sizeof(ipstr)) || (addrlen >= hbuflen))
945
0
      return CURLE_FTP_PORT_FAILED;
946
0
    memcpy(ipstr, addr, addrlen);
947
0
    ipstr[addrlen] = 0;
948
949
    /* attempt to get the address of the given interface name */
950
0
    switch(Curl_if2ip(remote_addr->family,
951
0
#ifdef USE_IPV6
952
0
                      Curl_ipv6_scope(&remote_addr->curl_sa_addr),
953
0
                      conn->scope_id,
954
0
#endif
955
0
                      ipstr, hbuf, hbuflen)) {
956
0
    case IF2IP_NOT_FOUND:
957
      /* not an interface, use the string as hostname instead */
958
0
      memcpy(hbuf, addr, addrlen);
959
0
      hbuf[addrlen] = 0;
960
0
      *hostp = hbuf;
961
0
      break;
962
0
    case IF2IP_AF_NOT_SUPPORTED:
963
0
      return CURLE_FTP_PORT_FAILED;
964
0
    case IF2IP_FOUND:
965
0
      *hostp = hbuf; /* use the hbuf for hostname */
966
0
      break;
967
0
    }
968
0
  }
969
  /* else: only a port(-range) given, leave host as NULL */
970
971
0
done:
972
0
  *port_minp = port_min;
973
0
  *port_maxp = port_max;
974
0
  return CURLE_OK;
975
0
}
976
977
/*
978
 * If no host was derived from the FTPPORT string, fall back to the IP address
979
 * of the control connection's local socket.
980
 */
981
static CURLcode ftp_port_default_host(struct Curl_easy *data,
982
                                      struct connectdata *conn,
983
                                      struct Curl_sockaddr_storage *ss,
984
                                      curl_socklen_t *sslenp,
985
                                      const char **hostp,
986
                                      char *hbuf, size_t hbuflen,
987
                                      bool *non_localp)
988
0
{
989
0
  struct sockaddr *sa = (struct sockaddr *)ss;
990
0
  struct sockaddr_in * const sa4 = (void *)sa;
991
0
#ifdef USE_IPV6
992
0
  struct sockaddr_in6 * const sa6 = (void *)sa;
993
0
#endif
994
0
  char buffer[STRERROR_LEN];
995
0
  CURLcode result;
996
997
0
  *sslenp = sizeof(*ss);
998
0
  if(getsockname(conn->chain.sock, sa, sslenp)) {
999
0
    failf(data, "getsockname() failed: %s",
1000
0
          curlx_strerror(SOCKERRNO, buffer, sizeof(buffer)));
1001
0
    return CURLE_FTP_PORT_FAILED;
1002
0
  }
1003
0
  switch(sa->sa_family) {
1004
0
#ifdef USE_IPV6
1005
0
  case AF_INET6:
1006
0
    result = curlx_inet_ntop(sa->sa_family, &sa6->sin6_addr, hbuf, hbuflen);
1007
0
    break;
1008
0
#endif
1009
0
  default:
1010
0
    result = curlx_inet_ntop(sa->sa_family, &sa4->sin_addr, hbuf, hbuflen);
1011
0
    break;
1012
0
  }
1013
0
  if(result)
1014
0
    return CURLE_FTP_PORT_FAILED;
1015
1016
0
  *hostp = hbuf;
1017
0
  *non_localp = FALSE; /* we know it is local now */
1018
0
  return CURLE_OK;
1019
0
}
1020
1021
/*
1022
 * Resolve the host string to a list of addresses.
1023
 */
1024
static CURLcode ftp_port_resolve_host(struct Curl_easy *data,
1025
                                      struct connectdata *conn,
1026
                                      const char *host,
1027
                                      struct Curl_dns_entry **dns_entryp,
1028
                                      const struct Curl_addrinfo **resp)
1029
0
{
1030
0
  CURLcode result;
1031
1032
0
  *resp = NULL;
1033
0
  result = Curl_resolv_blocking(
1034
0
    data, Curl_resolv_dns_queries(data, conn->ip_version),
1035
0
    host, 0, Curl_conn_get_transport(data, conn), dns_entryp);
1036
0
  if(result)
1037
0
    failf(data, "failed to resolve the address provided to PORT: %s", host);
1038
0
  else {
1039
0
    DEBUGASSERT(*dns_entryp);
1040
0
    *resp = (*dns_entryp)->addr;
1041
0
  }
1042
0
  return result;
1043
0
}
1044
1045
/*
1046
 * Open a TCP socket for the resolved address family.
1047
 */
1048
static CURLcode ftp_port_open_socket(struct Curl_easy *data,
1049
                                     struct connectdata *conn,
1050
                                     const struct Curl_addrinfo *res,
1051
                                     const struct Curl_addrinfo **aip,
1052
                                     curl_socket_t *portsockp)
1053
0
{
1054
0
  char buffer[STRERROR_LEN];
1055
0
  int sockerr = 0;
1056
0
  const struct Curl_addrinfo *ai;
1057
0
  CURLcode result = CURLE_FTP_PORT_FAILED;
1058
1059
0
  for(ai = res; ai; ai = ai->ai_next) {
1060
0
    result =
1061
0
      Curl_socket_open(data, ai, NULL,
1062
0
                       Curl_conn_get_transport(data, conn), portsockp);
1063
0
    if(result) {
1064
0
      if(result == CURLE_OUT_OF_MEMORY)
1065
0
        return result;
1066
0
      result = CURLE_FTP_PORT_FAILED;
1067
0
      sockerr = SOCKERRNO;
1068
0
      continue;
1069
0
    }
1070
0
    break;
1071
0
  }
1072
0
  if(!ai) {
1073
0
    failf(data, "socket failure: %s",
1074
0
          curlx_strerror(sockerr, buffer, sizeof(buffer)));
1075
0
    return CURLE_FTP_PORT_FAILED;
1076
0
  }
1077
0
  *aip = ai;
1078
0
  return result;
1079
0
}
1080
1081
/*
1082
 * Bind the socket to a local address and port within the requested range.
1083
 * Falls back to the control-connection address if the user-requested address
1084
 * is non-local.
1085
 */
1086
static CURLcode ftp_port_bind_socket(struct Curl_easy *data,
1087
                                     struct connectdata *conn,
1088
                                     curl_socket_t portsock,
1089
                                     const struct Curl_addrinfo *ai,
1090
                                     struct Curl_sockaddr_storage *ss,
1091
                                     curl_socklen_t *sslen_io,
1092
                                     unsigned short port_min,
1093
                                     unsigned short port_max,
1094
                                     bool non_local)
1095
0
{
1096
0
  struct sockaddr *sa = (struct sockaddr *)ss;
1097
0
  struct sockaddr_in * const sa4 = (void *)sa;
1098
0
#ifdef USE_IPV6
1099
0
  struct sockaddr_in6 * const sa6 = (void *)sa;
1100
0
#endif
1101
0
  char buffer[STRERROR_LEN];
1102
0
  unsigned short port;
1103
0
  int sockerr;
1104
1105
0
  memcpy(sa, ai->ai_addr, ai->ai_addrlen);
1106
0
  *sslen_io = ai->ai_addrlen;
1107
1108
0
  for(port = port_min; port <= port_max;) {
1109
0
    if(sa->sa_family == AF_INET)
1110
0
      sa4->sin_port = htons(port);
1111
0
#ifdef USE_IPV6
1112
0
    else
1113
0
      sa6->sin6_port = htons(port);
1114
0
#endif
1115
0
    if(bind(portsock, sa, *sslen_io)) {
1116
0
      sockerr = SOCKERRNO;
1117
0
      if(non_local && (sockerr == SOCKEADDRNOTAVAIL)) {
1118
        /* The requested bind address is not local. Use the address used for
1119
         * the control connection instead and restart the port loop.
1120
         */
1121
0
        infof(data, "bind(port=%hu) on non-local address failed: %s", port,
1122
0
              curlx_strerror(sockerr, buffer, sizeof(buffer)));
1123
1124
0
        *sslen_io = sizeof(*ss);
1125
0
        if(getsockname(conn->chain.sock, sa, sslen_io)) {
1126
0
          failf(data, "getsockname() failed: %s",
1127
0
                curlx_strerror(SOCKERRNO, buffer, sizeof(buffer)));
1128
0
          return CURLE_FTP_PORT_FAILED;
1129
0
        }
1130
0
        port = port_min;
1131
0
        non_local = FALSE; /* do not try this again */
1132
0
        continue;
1133
0
      }
1134
0
      if(sockerr != SOCKEADDRINUSE && sockerr != SOCKEACCES) {
1135
0
        failf(data, "bind(port=%hu) failed: %s", port,
1136
0
              curlx_strerror(sockerr, buffer, sizeof(buffer)));
1137
0
        return CURLE_FTP_PORT_FAILED;
1138
0
      }
1139
0
    }
1140
0
    else
1141
0
      break;
1142
1143
    /* check if port is the maximum value here, because it might be 0xffff
1144
       and then the increment below will wrap the 16-bit counter */
1145
0
    if(port == port_max) {
1146
0
      failf(data, "bind() failed, ran out of ports");
1147
0
      return CURLE_FTP_PORT_FAILED;
1148
0
    }
1149
0
    port++;
1150
0
  }
1151
1152
  /* re-read the name so we can extract the actual port chosen */
1153
0
  *sslen_io = sizeof(*ss);
1154
0
  if(getsockname(portsock, sa, sslen_io)) {
1155
0
    failf(data, "getsockname() failed: %s",
1156
0
          curlx_strerror(SOCKERRNO, buffer, sizeof(buffer)));
1157
0
    return CURLE_FTP_PORT_FAILED;
1158
0
  }
1159
0
  CURL_TRC_FTP(data, "ftp_port_bind_socket(), socket bound to port %d", port);
1160
0
  return CURLE_OK;
1161
0
}
1162
1163
/*
1164
 * Start listening on the data socket.
1165
 */
1166
static CURLcode ftp_port_listen(struct Curl_easy *data, curl_socket_t portsock)
1167
0
{
1168
0
  char buffer[STRERROR_LEN];
1169
1170
0
  if(listen(portsock, 1)) {
1171
0
    failf(data, "socket failure: %s",
1172
0
          curlx_strerror(SOCKERRNO, buffer, sizeof(buffer)));
1173
0
    return CURLE_FTP_PORT_FAILED;
1174
0
  }
1175
0
  CURL_TRC_FTP(data, "ftp_port_listen(), listening on port");
1176
0
  return CURLE_OK;
1177
0
}
1178
1179
/*
1180
 * Send the EPRT or PORT command to the server.
1181
 */
1182
static CURLcode ftp_port_send_command(struct Curl_easy *data,
1183
                                      struct cf_ftp_ctx *ftpc,
1184
                                      struct connectdata *conn,
1185
                                      struct Curl_sockaddr_storage *ss,
1186
                                      const struct Curl_addrinfo *ai,
1187
                                      ftpport fcmd)
1188
0
{
1189
0
  static const char mode[][5] = { "EPRT", "PORT" };
1190
0
  struct sockaddr *sa = (struct sockaddr *)ss;
1191
0
  struct sockaddr_in * const sa4 = (void *)sa;
1192
0
#ifdef USE_IPV6
1193
0
  struct sockaddr_in6 * const sa6 = (void *)sa;
1194
0
#endif
1195
0
  char myhost[MAX_IPADR_LEN + 1] = "";
1196
0
  unsigned short port;
1197
0
  CURLcode result;
1198
1199
  /* Get a plain printable version of the numerical address to work with. This
1200
     logic uses the address provided by the FTPPORT option, which at times
1201
     might differ from the address in 'ss' used to bind to: when a user asks
1202
     the server to connect to a specific address knowing that it works, but
1203
     curl instead selects to listen to the local address because it cannot use
1204
     the provided address. FTP is strange. */
1205
0
  Curl_printable_address(ai, myhost, sizeof(myhost));
1206
1207
0
#ifdef USE_IPV6
1208
0
  if(!conn->bits.ftp_use_eprt && conn->chain.ipv6)
1209
    /* EPRT is disabled but we are connected to an IPv6 host, so we ignore the
1210
       request and enable EPRT again! */
1211
0
    conn->bits.ftp_use_eprt = TRUE;
1212
0
#endif
1213
1214
0
  for(; fcmd != DONE; fcmd++) {
1215
1216
0
    if(!conn->bits.ftp_use_eprt && (EPRT == fcmd))
1217
      /* if disabled, goto next */
1218
0
      continue;
1219
1220
0
    if((PORT == fcmd) && sa->sa_family != AF_INET)
1221
      /* PORT is IPv4 only */
1222
0
      continue;
1223
1224
0
    switch(sa->sa_family) {
1225
0
    case AF_INET:
1226
0
      port = ntohs(sa4->sin_port);
1227
0
      break;
1228
0
#ifdef USE_IPV6
1229
0
    case AF_INET6:
1230
0
      port = ntohs(sa6->sin6_port);
1231
0
      break;
1232
0
#endif
1233
0
    default:
1234
0
      continue; /* might as well skip this */
1235
0
    }
1236
1237
0
    if(EPRT == fcmd) {
1238
      /*
1239
       * Two fine examples from RFC2428;
1240
       *
1241
       * EPRT |1|132.235.1.2|6275|
1242
       *
1243
       * EPRT |2|1080::8:800:200C:417A|5282|
1244
       */
1245
0
      result = Curl_pp_sendf(data, &ftpc->pp, "%s |%d|%s|%hu|", mode[fcmd],
1246
0
                             sa->sa_family == AF_INET ? 1 : 2, myhost, port);
1247
0
      if(result) {
1248
0
        failf(data, "Failure sending EPRT command: %s",
1249
0
              curl_easy_strerror(result));
1250
0
        return result;
1251
0
      }
1252
0
      break;
1253
0
    }
1254
0
    if(PORT == fcmd) {
1255
      /* large enough for [IP address],[num],[num] */
1256
0
      char target[sizeof(myhost) + 20];
1257
0
      const char *source = myhost;
1258
0
      char *dest = target;
1259
1260
      /* translate x.x.x.x to x,x,x,x */
1261
0
      while(*source) {
1262
0
        if(*source == '.')
1263
0
          *dest = ',';
1264
0
        else
1265
0
          *dest = *source;
1266
0
        dest++;
1267
0
        source++;
1268
0
      }
1269
0
      *dest = 0;
1270
0
      curl_msnprintf(dest, 20, ",%d,%d", (int)(port >> 8), (int)(port & 0xff));
1271
1272
0
      result = Curl_pp_sendf(data, &ftpc->pp, "%s %s", mode[fcmd], target);
1273
0
      if(result) {
1274
0
        failf(data, "Failure sending PORT command: %s",
1275
0
              curl_easy_strerror(result));
1276
0
        return result;
1277
0
      }
1278
0
      break;
1279
0
    }
1280
0
  }
1281
1282
  /* store which command was sent */
1283
0
  ftpc->count1 = fcmd;
1284
0
  ftp_state(data, ftpc, FTP_PORT);
1285
0
  return CURLE_OK;
1286
0
}
1287
1288
/*
1289
 * ftp_state_use_port()
1290
 *
1291
 * Set up an active-mode FTP data connection (using PORT or EPRT) and start
1292
 * listening for the server's incoming connection on SECONDARYSOCKET.
1293
 */
1294
static CURLcode ftp_state_use_port(struct Curl_easy *data,
1295
                                   struct cf_ftp_ctx *ftpc,
1296
                                   ftpport fcmd) /* start with this */
1297
0
{
1298
0
  CURLcode result = CURLE_FTP_PORT_FAILED;
1299
0
  struct connectdata *conn = data->conn;
1300
0
  curl_socket_t portsock = CURL_SOCKET_BAD;
1301
1302
0
  struct Curl_sockaddr_storage ss;
1303
0
  curl_socklen_t sslen;
1304
0
  char hbuf[NI_MAXHOST];
1305
0
  const char *host = NULL;
1306
0
  const char *string_ftpport = CURL_EASY_STR(data, STRING_FTPPORT);
1307
0
  struct Curl_dns_entry *dns_entry = NULL;
1308
0
  const struct Curl_addrinfo *res = NULL;
1309
0
  const struct Curl_addrinfo *ai = NULL;
1310
0
  unsigned short port_min = 0;
1311
0
  unsigned short port_max = 0;
1312
0
  bool non_local = TRUE;
1313
1314
  /* parse the FTPPORT string for address and port range */
1315
0
  result = ftp_port_parse_string(data, conn, string_ftpport,
1316
0
                                 &ss, &port_min, &port_max,
1317
0
                                 &host, hbuf, sizeof(hbuf));
1318
0
  if(!result && !host)
1319
    /* if no host was specified, use the control connection's local IP */
1320
0
    result = ftp_port_default_host(data, conn, &ss, &sslen, &host,
1321
0
                                   hbuf, sizeof(hbuf), &non_local);
1322
1323
  /* resolve host string to address list */
1324
0
  if(!result)
1325
0
    result = ftp_port_resolve_host(data, conn, host, &dns_entry, &res);
1326
1327
  /* Open a TCP socket for the data connection */
1328
0
  if(!result)
1329
0
    result = ftp_port_open_socket(data, conn, res, &ai, &portsock);
1330
0
  if(!result) {
1331
0
    CURL_TRC_FTP(data, "[%s] ftp_state_use_port(), opened socket",
1332
0
                 FTP_CSTATE(ftpc));
1333
1334
    /* bind to a suitable local address / port */
1335
0
    result = ftp_port_bind_socket(data, conn, portsock, ai, &ss, &sslen,
1336
0
                                  port_min, port_max, non_local);
1337
0
  }
1338
1339
  /* listen */
1340
0
  if(!result)
1341
0
    result = ftp_port_listen(data, portsock);
1342
1343
  /* send the PORT / EPRT command */
1344
0
  if(!result)
1345
0
    result = ftp_port_send_command(data, ftpc, conn, &ss, ai, fcmd);
1346
1347
  /* replace any filter on SECONDARY with one listening on this socket */
1348
0
  if(!result)
1349
0
    result = Curl_conn_tcp_listen_set(data, &ftpc->chain_data, &portsock);
1350
1351
0
  if(!result)
1352
0
    portsock = CURL_SOCKET_BAD; /* now held in filter */
1353
1354
  /* cleanup */
1355
1356
0
  if(dns_entry)
1357
0
    Curl_dns_entry_unlink(data, &dns_entry);
1358
0
  if(result) {
1359
0
    ftp_state(data, ftpc, FTP_STOP);
1360
0
  }
1361
0
  else {
1362
    /* successfully set up the listen socket filter. SSL needed?
1363
     * Use the control connections origin for cert verification. */
1364
0
    if(conn->bits.ftp_use_data_ssl && data->set.ftp_use_port &&
1365
0
       !Curl_cfchain_is_ssl(&ftpc->chain_data)) {
1366
0
      result = Curl_ssl_cfilter_add(data, Curl_conn_get_origin(conn),
1367
0
                                    &ftpc->chain_data);
1368
0
    }
1369
0
    conn->bits.do_more = FALSE;
1370
0
    Curl_expire(data, (data->set.accepttimeout > 0) ?
1371
0
                data->set.accepttimeout: DEFAULT_ACCEPT_TIMEOUT,
1372
0
                EXPIRE_FTP_ACCEPT);
1373
0
  }
1374
0
  if(portsock != CURL_SOCKET_BAD)
1375
0
    Curl_socket_close(data, conn, portsock);
1376
0
  return result;
1377
0
}
1378
1379
static CURLcode ftp_state_use_pasv(struct Curl_easy *data,
1380
                                   struct cf_ftp_ctx *ftpc,
1381
                                   struct connectdata *conn)
1382
0
{
1383
0
  CURLcode result = CURLE_OK;
1384
  /* Here's the executive summary on what to do:
1385
1386
     PASV is RFC959, expect:
1387
     227 Entering Passive Mode (a1,a2,a3,a4,p1,p2)
1388
1389
     LPSV is RFC1639, expect:
1390
     228 Entering Long Passive Mode (4,4,a1,a2,a3,a4,2,p1,p2)
1391
1392
     EPSV is RFC2428, expect:
1393
     229 Entering Extended Passive Mode (|||port|)
1394
   */
1395
1396
0
  static const char mode[][5] = { "EPSV", "PASV" };
1397
0
  int modeoff;
1398
1399
0
#ifdef PF_INET6
1400
0
  if(!conn->bits.ftp_use_epsv && conn->chain.ipv6)
1401
    /* EPSV is disabled but we are connected to an IPv6 host, so we ignore the
1402
       request and enable EPSV again! */
1403
0
    conn->bits.ftp_use_epsv = TRUE;
1404
0
#endif
1405
1406
0
  modeoff = conn->bits.ftp_use_epsv ? 0 : 1;
1407
1408
0
  result = Curl_pp_sendf(data, &ftpc->pp, "%s", mode[modeoff]);
1409
0
  if(!result) {
1410
0
    ftpc->count1 = modeoff;
1411
0
    ftp_state(data, ftpc, FTP_PASV);
1412
0
    infof(data, "Connect data stream passively");
1413
0
  }
1414
0
  return result;
1415
0
}
1416
1417
/*
1418
 * ftp_state_prepare_transfer() starts PORT, PASV or PRET etc.
1419
 *
1420
 * REST is the last command in the chain of commands when a "head"-like
1421
 * request is made. Thus, if an actual transfer is to be made this is where we
1422
 * take off for real.
1423
 */
1424
static CURLcode ftp_state_prepare_transfer(struct Curl_easy *data,
1425
                                           struct cf_ftp_ctx *ftpc,
1426
                                           struct FTP *ftp)
1427
0
{
1428
0
  CURLcode result = CURLE_OK;
1429
0
  struct connectdata *conn = data->conn;
1430
1431
0
  if(ftp->transfer != PPTRANSFER_BODY) {
1432
    /* does not transfer any data */
1433
1434
    /* still possibly do PRE QUOTE jobs */
1435
0
    ftp_state(data, ftpc, FTP_RETR_PREQUOTE);
1436
0
    result = ftp_state_quote(data, ftpc, ftp, TRUE, FTP_RETR_PREQUOTE);
1437
0
  }
1438
0
  else if(data->set.ftp_use_port) {
1439
    /* We have chosen to use the PORT (or similar) command */
1440
0
    result = ftp_state_use_port(data, ftpc, EPRT);
1441
0
  }
1442
0
  else {
1443
    /* We have chosen (this is default) to use the PASV (or similar) command */
1444
0
    if(data->set.ftp_use_pret) {
1445
      /* The user has requested that we send a PRET command
1446
         to prepare the server for the upcoming PASV */
1447
0
      if(!ftpc->file)
1448
0
        result = Curl_pp_sendf(data, &ftpc->pp, "PRET %s",
1449
0
                               CURL_EASY_STR(data, STRING_CUSTOMREQUEST) ?
1450
0
                               CURL_EASY_STR(data, STRING_CUSTOMREQUEST) :
1451
0
                               (data->state.list_only ? "NLST" : "LIST"));
1452
0
      else if(data->state.upload)
1453
0
        result = Curl_pp_sendf(data, &ftpc->pp, "PRET STOR %s", ftpc->file);
1454
0
      else
1455
0
        result = Curl_pp_sendf(data, &ftpc->pp, "PRET RETR %s", ftpc->file);
1456
0
      if(!result)
1457
0
        ftp_state(data, ftpc, FTP_PRET);
1458
0
    }
1459
0
    else
1460
0
      result = ftp_state_use_pasv(data, ftpc, conn);
1461
0
  }
1462
0
  return result;
1463
0
}
1464
1465
static CURLcode ftp_state_rest(struct Curl_easy *data,
1466
                               struct cf_ftp_ctx *ftpc,
1467
                               struct FTP *ftp)
1468
0
{
1469
0
  CURLcode result = CURLE_OK;
1470
1471
0
  if((ftp->transfer != PPTRANSFER_BODY) && ftpc->file) {
1472
    /* if a "head"-like request is being made (on a file) */
1473
1474
    /* Determine if server can respond to REST command and therefore
1475
       whether it supports range */
1476
0
    result = Curl_pp_sendf(data, &ftpc->pp, "REST %d", 0);
1477
0
    if(!result)
1478
0
      ftp_state(data, ftpc, FTP_REST);
1479
0
  }
1480
0
  else
1481
0
    result = ftp_state_prepare_transfer(data, ftpc, ftp);
1482
1483
0
  return result;
1484
0
}
1485
1486
static CURLcode ftp_state_size(struct Curl_easy *data,
1487
                               struct cf_ftp_ctx *ftpc,
1488
                               struct FTP *ftp)
1489
0
{
1490
0
  CURLcode result = CURLE_OK;
1491
1492
0
  if((ftp->transfer == PPTRANSFER_INFO) && ftpc->file) {
1493
    /* if a "head"-like request is being made (on a file) */
1494
1495
    /* we know ftpc->file is a valid pointer to a filename */
1496
0
    result = Curl_pp_sendf(data, &ftpc->pp, "SIZE %s", ftpc->file);
1497
0
    if(!result)
1498
0
      ftp_state(data, ftpc, FTP_SIZE);
1499
0
  }
1500
0
  else
1501
0
    result = ftp_state_rest(data, ftpc, ftp);
1502
1503
0
  return result;
1504
0
}
1505
1506
static CURLcode ftp_state_list(struct Curl_easy *data,
1507
                               struct cf_ftp_ctx *ftpc,
1508
                               struct FTP *ftp)
1509
0
{
1510
0
  CURLcode result = CURLE_OK;
1511
1512
  /* If this output is to be machine-parsed, the NLST command might be better
1513
     to use, since the LIST command output is not specified or standard in any
1514
     way. It has turned out that the NLST list output is not the same on all
1515
     servers either... */
1516
1517
  /* if FTPFILE_NOCWD was specified, we should add the path
1518
     as argument for the LIST / NLST / or custom command.
1519
     Whether the server will support this, is uncertain.
1520
1521
     The other ftp_filemethods will CWD into dir/dir/ first and
1522
     then do LIST (in that case: nothing to do here) */
1523
0
  const char *lstArg = NULL;
1524
0
  int lstArglen = 0;
1525
0
  char *cmd;
1526
1527
0
  if((data->set.ftp_filemethod == FTPFILE_NOCWD) && ftp->path) {
1528
    /* URL-decode before evaluation: e.g. paths starting/ending with %2f */
1529
0
    const char *rawPath = ftpc->rawpath;
1530
0
    const char *slashPos = strrchr(rawPath, '/');
1531
0
    if(slashPos) {
1532
      /* chop off the file part if format is dir/file otherwise remove
1533
         the trailing slash for dir/dir/ except for absolute path / */
1534
0
      size_t n = slashPos - rawPath;
1535
0
      if(n == 0)
1536
0
        ++n;
1537
1538
0
      lstArg = rawPath;
1539
0
      lstArglen = (int)n;
1540
0
    }
1541
0
  }
1542
1543
0
  cmd = curl_maprintf("%s%s%.*s",
1544
0
                      CURL_EASY_STR(data, STRING_CUSTOMREQUEST) ?
1545
0
                      CURL_EASY_STR(data, STRING_CUSTOMREQUEST) :
1546
0
                      (data->state.list_only ? "NLST" : "LIST"),
1547
0
                      lstArg ? " " : "",
1548
0
                      lstArglen, lstArg ? lstArg : "");
1549
1550
0
  if(!cmd)
1551
0
    return CURLE_OUT_OF_MEMORY;
1552
1553
0
  result = Curl_pp_sendf(data, &ftpc->pp, "%s", cmd);
1554
0
  curlx_free(cmd);
1555
1556
0
  if(!result)
1557
0
    ftp_state(data, ftpc, FTP_LIST);
1558
1559
0
  return result;
1560
0
}
1561
1562
static CURLcode ftp_state_list_prequote(struct Curl_easy *data,
1563
                                        struct cf_ftp_ctx *ftpc,
1564
                                        struct FTP *ftp)
1565
0
{
1566
  /* We have sent the TYPE, now we must send the list of prequote strings */
1567
0
  return ftp_state_quote(data, ftpc, ftp, TRUE, FTP_LIST_PREQUOTE);
1568
0
}
1569
1570
static CURLcode ftp_state_retr_prequote(struct Curl_easy *data,
1571
                                        struct cf_ftp_ctx *ftpc,
1572
                                        struct FTP *ftp)
1573
0
{
1574
  /* We have sent the TYPE, now we must send the list of prequote strings */
1575
0
  return ftp_state_quote(data, ftpc, ftp, TRUE, FTP_RETR_PREQUOTE);
1576
0
}
1577
1578
static CURLcode ftp_state_stor_prequote(struct Curl_easy *data,
1579
                                        struct cf_ftp_ctx *ftpc,
1580
                                        struct FTP *ftp)
1581
0
{
1582
  /* We have sent the TYPE, now we must send the list of prequote strings */
1583
0
  return ftp_state_quote(data, ftpc, ftp, TRUE, FTP_STOR_PREQUOTE);
1584
0
}
1585
1586
static CURLcode ftp_state_type(struct Curl_easy *data,
1587
                               struct cf_ftp_ctx *ftpc,
1588
                               struct FTP *ftp)
1589
0
{
1590
0
  CURLcode result = CURLE_OK;
1591
1592
  /* If we have selected NOBODY and HEADER, it means that we only want file
1593
     information. Which in FTP cannot be much more than the file size and
1594
     date. */
1595
0
  if(data->req.no_body && ftpc->file &&
1596
0
     ftp_need_type(ftpc, (bool)data->state.prefer_ascii)) {
1597
    /* The SIZE command is _not_ RFC 959 specified, and therefore many servers
1598
       may not support it! It is however the only way we have to get a file's
1599
       size! */
1600
1601
0
    ftp->transfer = PPTRANSFER_INFO;
1602
    /* this means no actual transfer will be made */
1603
1604
    /* Some servers return different sizes for different modes, and thus we
1605
       must set the proper type before we check the size */
1606
0
    result = ftp_nb_type(data, ftpc, ftp, (bool)data->state.prefer_ascii,
1607
0
                         FTP_TYPE);
1608
0
    if(result)
1609
0
      return result;
1610
0
  }
1611
0
  else
1612
0
    result = ftp_state_size(data, ftpc, ftp);
1613
1614
0
  return result;
1615
0
}
1616
1617
/* This is called after the CWD commands have been done in the beginning of
1618
   the DO phase */
1619
static CURLcode ftp_state_mdtm(struct Curl_easy *data,
1620
                               struct cf_ftp_ctx *ftpc,
1621
                               struct FTP *ftp)
1622
0
{
1623
0
  CURLcode result = CURLE_OK;
1624
1625
  /* Requested time of file or time-depended transfer? */
1626
0
  if((data->set.get_filetime || data->set.timecondition) && ftpc->file) {
1627
1628
    /* we have requested to get the modified-time of the file, this is a white
1629
       spot as the MDTM is not mentioned in RFC959 */
1630
0
    result = Curl_pp_sendf(data, &ftpc->pp, "MDTM %s", ftpc->file);
1631
1632
0
    if(!result)
1633
0
      ftp_state(data, ftpc, FTP_MDTM);
1634
0
  }
1635
0
  else
1636
0
    result = ftp_state_type(data, ftpc, ftp);
1637
1638
0
  return result;
1639
0
}
1640
1641
/* This is called after the TYPE and possible quote commands have been sent */
1642
static CURLcode ftp_state_ul_setup(struct Curl_easy *data,
1643
                                   struct cf_ftp_ctx *ftpc,
1644
                                   struct FTP *ftp,
1645
                                   bool sizechecked)
1646
0
{
1647
0
  CURLcode result = CURLE_OK;
1648
0
  curl_bit append = data->set.remote_append;
1649
1650
0
  if((data->state.resume_from && !sizechecked) ||
1651
0
     ((data->state.resume_from > 0) && sizechecked)) {
1652
    /* we are about to continue the uploading of a file
1653
       1. get already existing file's size. We use the SIZE command for this
1654
          which may not exist in the server!  The SIZE command is not in
1655
          RFC959.
1656
1657
       2. This used to set REST, but since we can do append, we issue no
1658
          another ftp command. Skip the source file offset and APPEND the rest
1659
          on the file instead
1660
1661
       3. pass file-size number of bytes in the source file
1662
       4. lower the infilesize counter */
1663
    /* => transfer as usual */
1664
0
    int seekerr = CURL_SEEKFUNC_OK;
1665
1666
0
    if(data->state.resume_from < 0) {
1667
      /* Got no given size to start from, figure it out */
1668
0
      result = Curl_pp_sendf(data, &ftpc->pp, "SIZE %s", ftpc->file);
1669
0
      if(!result)
1670
0
        ftp_state(data, ftpc, FTP_STOR_SIZE);
1671
0
      return result;
1672
0
    }
1673
1674
    /* enable append */
1675
0
    append = TRUE;
1676
1677
    /* Let's read off the proper amount of bytes from the input. */
1678
0
    if(data->set.seek_func) {
1679
0
      struct Curl_mapi_guard guard;
1680
0
      CURL_CBAPI_START(&guard, data, easy_seek_func);
1681
0
      seekerr = data->set.seek_func(data->set.seek_client,
1682
0
                                    data->state.resume_from, SEEK_SET);
1683
0
      CURL_CBAPI_END(&guard);
1684
0
    }
1685
1686
0
    if(seekerr != CURL_SEEKFUNC_OK) {
1687
0
      curl_off_t passed = 0;
1688
0
      if(seekerr != CURL_SEEKFUNC_CANTSEEK) {
1689
0
        failf(data, "Could not seek stream");
1690
0
        return CURLE_FTP_COULDNT_USE_REST;
1691
0
      }
1692
      /* seekerr == CURL_SEEKFUNC_CANTSEEK (cannot seek to offset) */
1693
0
      do {
1694
0
        char scratch[4 * 1024];
1695
0
        size_t readthisamountnow =
1696
0
          (data->state.resume_from - passed > (curl_off_t)sizeof(scratch)) ?
1697
0
          sizeof(scratch) :
1698
0
          curlx_sotouz(data->state.resume_from - passed);
1699
1700
0
        size_t actuallyread =
1701
0
          data->state.fread_func(scratch, 1, readthisamountnow,
1702
0
                                 data->state.in);
1703
1704
0
        passed += actuallyread;
1705
0
        if((actuallyread == 0) || (actuallyread > readthisamountnow)) {
1706
          /* this checks for greater-than only to make sure that the
1707
             CURL_READFUNC_ABORT return code still aborts */
1708
0
          failf(data, "Failed to read data");
1709
0
          return CURLE_FTP_COULDNT_USE_REST;
1710
0
        }
1711
0
      } while(passed < data->state.resume_from);
1712
0
    }
1713
    /* now, decrease the size of the read */
1714
0
    if(data->state.infilesize > 0) {
1715
0
      data->state.infilesize -= data->state.resume_from;
1716
1717
0
      if(data->state.infilesize <= 0) {
1718
0
        infof(data, "File already completely uploaded");
1719
1720
        /* no data to transfer */
1721
0
        Curl_xfer_setup_nop(data);
1722
1723
        /* Set ->transfer so that we will not get any error in
1724
         * ftp_done() because we did not transfer anything! */
1725
0
        ftp->transfer = PPTRANSFER_NONE;
1726
1727
0
        ftp_state(data, ftpc, FTP_STOP);
1728
0
        return CURLE_OK;
1729
0
      }
1730
0
    }
1731
    /* we have passed, proceed as normal */
1732
0
  } /* resume_from */
1733
1734
0
  result = Curl_pp_sendf(data, &ftpc->pp, append ? "APPE %s" : "STOR %s",
1735
0
                         ftpc->file);
1736
0
  if(!result)
1737
0
    ftp_state(data, ftpc, FTP_STOR);
1738
1739
0
  return result;
1740
0
}
1741
1742
static CURLcode ftp_state_retr(struct Curl_easy *data,
1743
                               struct cf_ftp_ctx *ftpc,
1744
                               struct FTP *ftp,
1745
                               curl_off_t filesize)
1746
0
{
1747
0
  CURLcode result = CURLE_OK;
1748
1749
0
  CURL_TRC_FTP(data, "[%s] ftp_state_retr()", FTP_CSTATE(ftpc));
1750
0
  if(data->set.max_filesize && (filesize > data->set.max_filesize)) {
1751
0
    failf(data, "Maximum file size exceeded");
1752
0
    return CURLE_FILESIZE_EXCEEDED;
1753
0
  }
1754
0
  ftp->downloadsize = filesize;
1755
1756
0
  if(data->state.resume_from) {
1757
    /* We always (attempt to) get the size of downloads, so it is done before
1758
       this even when not doing resumes. */
1759
0
    if(filesize == -1) {
1760
0
      infof(data, "ftp server does not support SIZE");
1761
      /* We could not get the size and therefore we cannot know if there
1762
         really is a part of the file left to get, although the server will
1763
         close the connection when we start the connection so it will not
1764
         cause us any harm, not make us exit as nicely. */
1765
0
    }
1766
0
    else {
1767
      /* We got a file size report, so we check that there actually is a
1768
         part of the file left to get, or else we go home. */
1769
0
      if(data->state.resume_from < 0) {
1770
        /* We are supposed to download the last abs(from) bytes */
1771
0
        if(filesize < -data->state.resume_from) {
1772
0
          failf(data, "Offset (%" FMT_OFF_T
1773
0
                ") was beyond file size (%" FMT_OFF_T ")",
1774
0
                data->state.resume_from, filesize);
1775
0
          return CURLE_BAD_DOWNLOAD_RESUME;
1776
0
        }
1777
        /* convert to size to download */
1778
0
        ftp->downloadsize = -data->state.resume_from;
1779
        /* download from where? */
1780
0
        data->state.resume_from = filesize - ftp->downloadsize;
1781
0
      }
1782
0
      else {
1783
0
        if(filesize < data->state.resume_from) {
1784
0
          failf(data, "Offset (%" FMT_OFF_T
1785
0
                ") was beyond file size (%" FMT_OFF_T ")",
1786
0
                data->state.resume_from, filesize);
1787
0
          return CURLE_BAD_DOWNLOAD_RESUME;
1788
0
        }
1789
        /* Now store the number of bytes we are expected to download */
1790
0
        ftp->downloadsize = filesize - data->state.resume_from;
1791
0
      }
1792
0
    }
1793
1794
0
    if(ftp->downloadsize == 0) {
1795
      /* no data to transfer */
1796
0
      Curl_xfer_setup_nop(data);
1797
0
      infof(data, "File already completely downloaded");
1798
1799
      /* Set ->transfer so that we will not get any error in ftp_done()
1800
       * because we did not transfer the any file */
1801
0
      ftp->transfer = PPTRANSFER_NONE;
1802
0
      ftp_state(data, ftpc, FTP_STOP);
1803
0
      return CURLE_OK;
1804
0
    }
1805
1806
    /* Set resume file transfer offset */
1807
0
    infof(data, "Instructs server to resume from offset %" FMT_OFF_T,
1808
0
          data->state.resume_from);
1809
1810
0
    result = Curl_pp_sendf(data, &ftpc->pp, "REST %" FMT_OFF_T,
1811
0
                           data->state.resume_from);
1812
0
    if(!result)
1813
0
      ftp_state(data, ftpc, FTP_RETR_REST);
1814
0
  }
1815
0
  else {
1816
    /* no resume */
1817
0
    result = Curl_pp_sendf(data, &ftpc->pp, "RETR %s", ftpc->file);
1818
0
    if(!result)
1819
0
      ftp_state(data, ftpc, FTP_RETR);
1820
0
  }
1821
1822
0
  return result;
1823
0
}
1824
1825
static CURLcode ftp_state_quote(struct Curl_easy *data,
1826
                                struct cf_ftp_ctx *ftpc,
1827
                                struct FTP *ftp,
1828
                                bool init,
1829
                                ftpstate instate)
1830
0
{
1831
0
  struct Curl_frzn_strs *fstrs = NULL;
1832
0
  CURLcode result = CURLE_OK;
1833
0
  bool quote = FALSE;
1834
1835
0
  switch(instate) {
1836
0
  case FTP_QUOTE:
1837
0
  default:
1838
0
    fstrs = data->set.a.quote;
1839
0
    break;
1840
0
  case FTP_RETR_PREQUOTE:
1841
0
  case FTP_STOR_PREQUOTE:
1842
0
  case FTP_LIST_PREQUOTE:
1843
0
    fstrs = data->set.a.prequote;
1844
0
    break;
1845
0
  case FTP_POSTQUOTE:
1846
0
    fstrs = data->set.a.postquote;
1847
0
    break;
1848
0
  }
1849
1850
  /*
1851
   * This state uses:
1852
   * 'count1' to iterate over the commands to send
1853
   * 'count2' to store whether to allow commands to fail
1854
   */
1855
1856
0
  if(init)
1857
0
    ftpc->count1 = 0;
1858
0
  else
1859
0
    ftpc->count1++;
1860
1861
0
  if(fstrs && (ftpc->count1 >= 0)) {
1862
0
    const char *cmd = Curl_frzn_strs_get_str(fstrs, (size_t)ftpc->count1);
1863
0
    if(cmd) {
1864
0
      if(cmd[0] == '*') {
1865
0
        cmd++;
1866
0
        ftpc->count2 = 1; /* the sent command is allowed to fail */
1867
0
      }
1868
0
      else
1869
0
        ftpc->count2 = 0; /* failure means cancel operation */
1870
1871
0
      result = Curl_pp_sendf(data, &ftpc->pp, "%s", cmd);
1872
0
      if(result)
1873
0
        return result;
1874
0
      ftp_state(data, ftpc, instate);
1875
0
      quote = TRUE;
1876
0
    }
1877
0
  }
1878
1879
0
  if(!quote) {
1880
    /* No more quote to send, continue to ... */
1881
0
    switch(instate) {
1882
0
    case FTP_QUOTE:
1883
0
    default:
1884
0
      result = ftp_state_cwd(data, ftpc, ftp);
1885
0
      break;
1886
0
    case FTP_RETR_PREQUOTE:
1887
0
      if(ftp->transfer != PPTRANSFER_BODY)
1888
0
        ftp_state(data, ftpc, FTP_STOP);
1889
0
      else {
1890
0
        if(ftpc->known_filesize != -1) {
1891
0
          Curl_pgrsSetDownloadSize(data, ftpc->known_filesize);
1892
0
          result = ftp_state_retr(data, ftpc, ftp, ftpc->known_filesize);
1893
0
        }
1894
0
        else {
1895
0
          if(data->set.ignorecl || data->state.prefer_ascii) {
1896
            /* 'ignorecl' is used to support download of growing files. It
1897
               prevents the state machine from requesting the file size from
1898
               the server. With an unknown file size the download continues
1899
               until the server terminates it, otherwise the client stops if
1900
               the received byte count exceeds the reported file size. Set
1901
               option CURLOPT_IGNORE_CONTENT_LENGTH to 1 to enable this
1902
               behavior.
1903
1904
               In addition: asking for the size for 'TYPE A' transfers is not
1905
               constructive since servers do not report the converted size.
1906
               Thus, skip it. */
1907
0
            result = Curl_pp_sendf(data, &ftpc->pp, "RETR %s", ftpc->file);
1908
0
            if(!result)
1909
0
              ftp_state(data, ftpc, FTP_RETR);
1910
0
          }
1911
0
          else {
1912
0
            result = Curl_pp_sendf(data, &ftpc->pp, "SIZE %s", ftpc->file);
1913
0
            if(!result)
1914
0
              ftp_state(data, ftpc, FTP_RETR_SIZE);
1915
0
          }
1916
0
        }
1917
0
      }
1918
0
      break;
1919
0
    case FTP_STOR_PREQUOTE:
1920
0
      result = ftp_state_ul_setup(data, ftpc, ftp, FALSE);
1921
0
      break;
1922
0
    case FTP_POSTQUOTE:
1923
0
      break;
1924
0
    case FTP_LIST_PREQUOTE:
1925
0
      ftp_state(data, ftpc, FTP_LIST_TYPE);
1926
0
      result = ftp_state_list(data, ftpc, ftp);
1927
0
      break;
1928
0
    }
1929
0
  }
1930
1931
0
  return result;
1932
0
}
1933
1934
/* called from ftp_state_pasv_resp to switch to PASV in case of EPSV
1935
   problems */
1936
static CURLcode ftp_epsv_disable(struct Curl_easy *data,
1937
                                 struct cf_ftp_ctx *ftpc,
1938
                                 struct connectdata *conn)
1939
0
{
1940
0
  CURLcode result = CURLE_OK;
1941
1942
0
  if(conn->chain.ipv6 && !Curl_conn_is_tunneling(conn)) {
1943
    /* We cannot disable EPSV when doing IPv6, so this is instead a fail */
1944
0
    failf(data, "Failed EPSV attempt, exiting");
1945
0
    return CURLE_WEIRD_SERVER_REPLY;
1946
0
  }
1947
1948
0
  infof(data, "Failed EPSV attempt. Disabling EPSV");
1949
  /* disable it for next transfer */
1950
0
  conn->bits.ftp_use_epsv = FALSE;
1951
0
  ftp_close_chain_data(data, ftpc);
1952
0
  data->state.errorbuf = FALSE; /* allow error message to get
1953
                                         rewritten */
1954
0
  result = Curl_pp_sendf(data, &ftpc->pp, "%s", "PASV");
1955
0
  if(!result) {
1956
0
    ftpc->count1++;
1957
    /* remain in/go to the FTP_PASV state */
1958
0
    ftp_state(data, ftpc, FTP_PASV);
1959
0
  }
1960
0
  return result;
1961
0
}
1962
1963
static CURLcode ftp_control_addr_dup(struct Curl_easy *data, char **newhostp)
1964
0
{
1965
0
  struct connectdata *conn = data->conn;
1966
0
  struct ip_quadruple ipquad;
1967
0
  bool is_ipv6;
1968
1969
  /* Returns the control connection IP address.
1970
     If a proxy tunnel is used, returns the original hostname instead, because
1971
     the effective control connection address is the proxy address,
1972
     not the ftp host. */
1973
0
#ifndef CURL_DISABLE_PROXY
1974
0
  if(Curl_conn_is_tunneling(conn))
1975
0
    *newhostp = curlx_strdup(conn->origin->hostname);
1976
0
  else
1977
0
#endif
1978
0
  if(!Curl_conn_get_ip_info(data, conn, &is_ipv6, &ipquad) &&
1979
0
     *ipquad.remote_ip)
1980
0
    *newhostp = curlx_strdup(ipquad.remote_ip);
1981
0
  else {
1982
    /* failed to get the remote_ip of the DATA connection */
1983
0
    failf(data, "unable to get peername of DATA connection");
1984
0
    *newhostp = NULL;
1985
0
    return CURLE_FTP_CANT_GET_HOST;
1986
0
  }
1987
0
  return *newhostp ? CURLE_OK : CURLE_OUT_OF_MEMORY;
1988
0
}
1989
1990
static bool match_pasv_6nums(const char *p,
1991
                             unsigned int *array) /* 6 numbers */
1992
0
{
1993
0
  int i;
1994
0
  for(i = 0; i < 6; i++) {
1995
0
    curl_off_t num;
1996
0
    if(i) {
1997
0
      if(*p != ',')
1998
0
        return FALSE;
1999
0
      p++;
2000
0
    }
2001
0
    if(curlx_str_number(&p, &num, 0xff))
2002
0
      return FALSE;
2003
0
    array[i] = (unsigned int)num;
2004
0
  }
2005
0
  return TRUE;
2006
0
}
2007
2008
static CURLcode ftp_state_pasv_resp(struct Curl_easy *data,
2009
                                    struct cf_ftp_ctx *ftpc,
2010
                                    int ftpcode)
2011
0
{
2012
0
  struct connectdata *conn = data->conn;
2013
0
  CURLcode result;
2014
0
  const struct pingpong *pp = &ftpc->pp;
2015
0
  char *newhost = NULL;
2016
0
  unsigned short newport = 0;
2017
0
  const char *str = curlx_dyn_ptr(&pp->recvbuf) + 4; /* start on the first
2018
                                                        letter */
2019
0
  if((ftpc->count1 == 0) &&
2020
0
     (ftpcode == 229)) {
2021
    /* positive EPSV response */
2022
0
    const char *ptr = strchr(str, '(');
2023
0
    if(ptr) {
2024
0
      char sep;
2025
0
      ptr++;
2026
      /* |||12345| */
2027
0
      sep = ptr[0];
2028
0
      if(sep && (ptr[1] == sep) && (ptr[2] == sep) && ISDIGIT(ptr[3])) {
2029
0
        const char *p = &ptr[3];
2030
0
        curl_off_t num;
2031
0
        if(curlx_str_number(&p, &num, 0xffff) || (*p != sep)) {
2032
0
          failf(data, "Illegal port number in EPSV reply");
2033
0
          return CURLE_FTP_WEIRD_PASV_REPLY;
2034
0
        }
2035
0
        newport = (unsigned short)num;
2036
0
        result = ftp_control_addr_dup(data, &newhost);
2037
0
        if(result)
2038
0
          return result;
2039
0
      }
2040
0
      else
2041
0
        ptr = NULL;
2042
0
    }
2043
0
    if(!ptr) {
2044
0
      failf(data, "Weirdly formatted EPSV reply");
2045
0
      return CURLE_FTP_WEIRD_PASV_REPLY;
2046
0
    }
2047
0
  }
2048
0
  else if((ftpc->count1 == 1) &&
2049
0
          (ftpcode == 227)) {
2050
    /* positive PASV response */
2051
0
    unsigned int ip[6];
2052
2053
    /*
2054
     * Scan for a sequence of six comma-separated numbers and use them as
2055
     * IP+port indicators.
2056
     *
2057
     * Found reply-strings include:
2058
     * "227 Entering Passive Mode (127,0,0,1,4,51)"
2059
     * "227 Data transfer will passively listen to 127,0,0,1,4,51"
2060
     * "227 Entering passive mode. 127,0,0,1,4,51"
2061
     */
2062
0
    while(*str) {
2063
0
      if(match_pasv_6nums(str, ip))
2064
0
        break;
2065
0
      str++;
2066
0
    }
2067
2068
0
    if(!*str) {
2069
0
      failf(data, "Could not interpret the 227-response");
2070
0
      return CURLE_FTP_WEIRD_227_FORMAT;
2071
0
    }
2072
2073
    /* we got OK from server */
2074
0
    if(data->set.ftp_skip_ip) {
2075
      /* told to ignore the remotely given IP but instead use the host we used
2076
         for the control connection */
2077
0
      infof(data, "Skip %u.%u.%u.%u for data connection, reuse %s instead",
2078
0
            ip[0], ip[1], ip[2], ip[3], conn->origin->hostname);
2079
0
      result = ftp_control_addr_dup(data, &newhost);
2080
0
      if(result)
2081
0
        return result;
2082
0
    }
2083
0
    else
2084
0
      newhost = curl_maprintf("%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]);
2085
2086
0
    if(!newhost)
2087
0
      return CURLE_OUT_OF_MEMORY;
2088
2089
0
    newport = (unsigned short)(((ip[4] << 8) + ip[5]) & 0xffff);
2090
0
  }
2091
0
  else if(ftpc->count1 == 0) {
2092
    /* EPSV failed, move on to PASV */
2093
0
    return ftp_epsv_disable(data, ftpc, conn);
2094
0
  }
2095
0
  else {
2096
0
    failf(data, "Bad PASV/EPSV response: %03d", ftpcode);
2097
0
    return CURLE_FTP_WEIRD_PASV_REPLY;
2098
0
  }
2099
2100
0
  DEBUGASSERT(newhost);
2101
0
  Curl_peer_unlink(&conn->origin2);
2102
0
  result = Curl_peer_create(data, conn->scheme, newhost, newport,
2103
0
                            &conn->origin2);
2104
0
  if(result)
2105
0
    goto error;
2106
2107
  /* If connection goes via another peer, DATA chain needs as well,
2108
   * but with its new port. */
2109
0
  if(conn->via_peer) {
2110
0
    Curl_peer_unlink(&conn->via_peer2);
2111
0
    result = Curl_peer_create(data, conn->via_peer->scheme,
2112
0
                              conn->via_peer->hostname, newport,
2113
0
                              &conn->via_peer2);
2114
0
    if(result)
2115
0
      goto error;
2116
0
  }
2117
2118
0
  result = Curl_conn_setup(data, conn, &ftpc->chain_data,
2119
0
                           conn->bits.ftp_use_data_ssl ?
2120
0
                           CURL_CF_SSL_ENABLE : CURL_CF_SSL_DISABLE);
2121
2122
0
  if(result) {
2123
0
    if((result != CURLE_OUT_OF_MEMORY) &&
2124
0
       (ftpc->count1 == 0) && (ftpcode == 229)) {
2125
0
      result = ftp_epsv_disable(data, ftpc, conn);
2126
0
    }
2127
0
    goto error;
2128
0
  }
2129
2130
  /*
2131
   * When this is used from the multi interface, this might have returned with
2132
   * the 'connected' set to FALSE and thus we are now awaiting a non-blocking
2133
   * connect to connect.
2134
   */
2135
2136
0
#ifdef CURLVERBOSE
2137
0
  if(data->set.verbose) {
2138
    /* Dump information about this second connection when we have issued
2139
     * a PASV command. */
2140
0
    infof(data, "Connecting to %s port %d",
2141
0
          conn->origin2->hostname, conn->origin2->port);
2142
0
  }
2143
0
#endif
2144
0
  if(FALSE) {
2145
0
    bool done;
2146
0
    result = Curl_cfchain_connect(data, &ftpc->chain_data, FALSE, &done);
2147
0
  }
2148
0
  conn->bits.do_more = TRUE;
2149
0
  ftp_state(data, ftpc, FTP_STOP); /* this phase is completed */
2150
2151
0
error:
2152
0
  curlx_free(newhost);
2153
0
  return result;
2154
0
}
2155
2156
/* called repeatedly until done from multi.c */
2157
static CURLcode ftp_statemach(struct Curl_easy *data,
2158
                              struct cf_ftp_ctx *ftpc,
2159
                              bool *done)
2160
0
{
2161
0
  CURLcode result = Curl_pp_statemach(data, &ftpc->pp, FALSE);
2162
2163
  /* Check for the state outside of the Curl_socket_check() return code checks
2164
     since at times we are in fact already in this state when this function
2165
     gets called. */
2166
0
  *done = (ftpc->state == FTP_STOP);
2167
2168
0
  return result;
2169
0
}
2170
2171
/*
2172
 * ftp_do_more()
2173
 *
2174
 * This function shall be called when the second FTP (data) connection is
2175
 * connected.
2176
 *
2177
 * 'more' can return DOMORE_INCOMPLETE, DOMORE_DONE or DOMORE_GOBACK
2178
 * (which is for when PASV is being sent to retry a failed EPSV).
2179
 */
2180
static CURLcode ftp_do_more(struct Curl_easy *data, domore *more)
2181
0
{
2182
0
  struct connectdata *conn = data->conn;
2183
0
  struct cf_ftp_ctx *ftpc = ftp_get_cf_ctx(data->conn);
2184
0
  struct FTP *ftp = Curl_meta_get(data, CURL_META_FTP_EASY);
2185
0
  CURLcode result = CURLE_OK;
2186
0
  bool connected = FALSE;
2187
0
  bool complete = FALSE;
2188
  /* the ftp struct is inited in ftp_connect(). If we are connecting to an HTTP
2189
   * proxy then the state will not be valid until after that connection is
2190
   * complete */
2191
2192
0
  if(!ftpc || !ftp)
2193
0
    return CURLE_FAILED_INIT;
2194
2195
0
  *more = DOMORE_INCOMPLETE; /* default to stay in the state */
2196
2197
  /* if the second connection has been set up, try to connect it fully
2198
   * to the remote host. This may not complete at this time, for several
2199
   * reasons:
2200
   * - we do EPTR and the server will not connect to our listen socket
2201
   *   until we send more FTP commands
2202
   * - an SSL filter is in place and the server will not start the TLS
2203
   *   handshake until we send more FTP commands
2204
   */
2205
0
  if(ftpc->chain_data.cf) {
2206
0
    bool is_eptr = Curl_cfchain_is_tcp_listen(&ftpc->chain_data);
2207
2208
0
    result = Curl_cfchain_connect(data, &ftpc->chain_data, FALSE, &connected);
2209
0
    if(result == CURLE_OUT_OF_MEMORY)
2210
0
      return result;
2211
0
    if(result || (!connected && !is_eptr &&
2212
0
                  !Curl_cfchain_is_ip_connected(&ftpc->chain_data))) {
2213
0
      if(result && !is_eptr && (ftpc->count1 == 0)) {
2214
0
        *more = DOMORE_GOBACK; /* go back to DOING please */
2215
        /* this is a EPSV connect failing, try PASV instead */
2216
0
        return ftp_epsv_disable(data, ftpc, conn);
2217
0
      }
2218
0
      return result;
2219
0
    }
2220
0
  }
2221
2222
0
  if(ftpc->state) {
2223
    /* already in a state so skip the initial commands.
2224
       They are only done to kickstart the do_more state */
2225
0
    result = ftp_statemach(data, ftpc, &complete);
2226
2227
0
    if(complete)
2228
0
      *more = DOMORE_DONE;
2229
2230
    /* if we got an error or if we do not wait for a data connection return
2231
       immediately */
2232
0
    if(result || !ftpc->wait_data_conn)
2233
0
      return result;
2234
2235
    /* if we reach the end of the FTP state machine here, *complete will be
2236
       TRUE but so is ftpc->wait_data_conn, which says we need to wait for the
2237
       data connection and therefore we are not actually complete */
2238
0
    *more = DOMORE_INCOMPLETE;
2239
0
  }
2240
2241
0
  if(ftp->transfer <= PPTRANSFER_INFO) {
2242
    /* a transfer is about to take place, or if not a filename was given so we
2243
       will do a SIZE on it later and then we need the right TYPE first */
2244
2245
0
    if(ftpc->wait_data_conn) {
2246
0
      bool serv_conned;
2247
2248
0
      result = Curl_cfchain_connect(
2249
0
        data, &ftpc->chain_data, FALSE, &serv_conned);
2250
0
      if(result)
2251
0
        return result; /* Failed to accept data connection */
2252
2253
0
      if(serv_conned) {
2254
        /* It looks data connection is established */
2255
0
        ftpc->wait_data_conn = FALSE;
2256
0
        result = ftp_initiate_transfer(data, ftpc);
2257
2258
0
        if(result)
2259
0
          return result;
2260
2261
0
        *more = DOMORE_DONE; /* this state is now complete when the server has
2262
                                connected back to us */
2263
0
      }
2264
0
      else {
2265
0
        result = ftp_check_ctrl_on_data_wait(data, ftpc);
2266
0
        if(result)
2267
0
          return result;
2268
0
      }
2269
0
    }
2270
0
    else if(data->state.upload) {
2271
0
      result = ftp_nb_type(data, ftpc, ftp, (bool)data->state.prefer_ascii,
2272
0
                           FTP_STOR_TYPE);
2273
0
      if(result)
2274
0
        return result;
2275
2276
0
      result = ftp_statemach(data, ftpc, &complete);
2277
      /* ftp_nb_type() might have skipped sending `TYPE A|I` when not
2278
       * deemed necessary and directly sent `STORE name`. If this was
2279
       * then complete, but we are still waiting on the data connection,
2280
       * the transfer has not been initiated yet. */
2281
0
      *more = (!ftpc->wait_data_conn && complete) ?
2282
0
        DOMORE_DONE : DOMORE_INCOMPLETE;
2283
0
    }
2284
0
    else {
2285
      /* download */
2286
0
      ftp->downloadsize = -1; /* unknown as of yet */
2287
2288
0
      result = Curl_range(data);
2289
2290
0
      if(result == CURLE_OK && data->req.maxdownload >= 0) {
2291
        /* Do not check for successful transfer */
2292
0
        ftpc->dont_check = TRUE;
2293
0
      }
2294
2295
0
      if(result)
2296
0
        return result;
2297
2298
0
      if((data->state.list_only || !ftpc->file) &&
2299
0
         !data->set.a.prequote) {
2300
        /* The specified path ends with a slash, and therefore we think this
2301
           is a directory that is requested, use LIST. Before that, we also
2302
           need to set ASCII transfer mode. */
2303
2304
        /* Only if a body transfer was requested. */
2305
0
        if(ftp->transfer == PPTRANSFER_BODY) {
2306
0
          result = ftp_nb_type(data, ftpc, ftp, TRUE, FTP_LIST_TYPE);
2307
0
          if(result)
2308
0
            return result;
2309
0
        }
2310
        /* otherwise fall through */
2311
0
      }
2312
0
      else {
2313
0
        if(data->set.a.prequote && !ftpc->file) {
2314
0
          result = ftp_nb_type(data, ftpc, ftp, TRUE,
2315
0
                               FTP_RETR_LIST_TYPE);
2316
0
        }
2317
0
        else {
2318
0
          result = ftp_nb_type(data, ftpc, ftp, (bool)data->state.prefer_ascii,
2319
0
                               FTP_RETR_TYPE);
2320
0
        }
2321
0
        if(result)
2322
0
          return result;
2323
0
      }
2324
2325
0
      result = ftp_statemach(data, ftpc, &complete);
2326
0
      if(complete)
2327
0
        *more = DOMORE_DONE;
2328
0
    }
2329
0
    return result;
2330
0
  }
2331
2332
  /* no data to transfer */
2333
0
  Curl_xfer_setup_nop(data);
2334
2335
0
  if(!ftpc->wait_data_conn) {
2336
    /* no waiting for the data connection so this is now complete */
2337
0
    *more = DOMORE_DONE;
2338
0
    CURL_TRC_FTP(data, "[%s] DO-MORE phase ends with %d", FTP_CSTATE(ftpc),
2339
0
                 (int)result);
2340
0
  }
2341
2342
0
  return result;
2343
0
}
2344
2345
/* call this when the DO phase has completed */
2346
static CURLcode ftp_dophase_done(struct Curl_easy *data,
2347
                                 struct cf_ftp_ctx *ftpc,
2348
                                 struct FTP *ftp,
2349
                                 bool connected)
2350
0
{
2351
0
  if(connected) {
2352
0
    domore completed;
2353
0
    CURLcode result = ftp_do_more(data, &completed);
2354
2355
0
    if(result) {
2356
0
      ftp_close_chain_data(data, ftpc);
2357
0
      return result;
2358
0
    }
2359
0
  }
2360
2361
0
  if(ftp->transfer != PPTRANSFER_BODY)
2362
    /* no data to transfer */
2363
0
    Curl_xfer_setup_nop(data);
2364
0
  else if(!connected)
2365
    /* since we did not connect now, we want do_more to get called */
2366
0
    data->conn->bits.do_more = TRUE;
2367
2368
0
  return CURLE_OK;
2369
0
}
2370
2371
static CURLcode ftp_state_port_resp(struct Curl_easy *data,
2372
                                    struct cf_ftp_ctx *ftpc,
2373
                                    struct FTP *ftp,
2374
                                    int ftpcode)
2375
0
{
2376
0
  struct connectdata *conn = data->conn;
2377
0
  ftpport fcmd = (ftpport)ftpc->count1;
2378
0
  CURLcode result = CURLE_OK;
2379
2380
  /* The FTP spec tells a positive response should have code 200.
2381
     Be more permissive here to tolerate deviant servers. */
2382
0
  if(ftpcode / 100 != 2) {
2383
    /* the command failed */
2384
2385
0
    if(EPRT == fcmd) {
2386
0
      infof(data, "disabling EPRT usage");
2387
0
      conn->bits.ftp_use_eprt = FALSE;
2388
0
    }
2389
0
    fcmd++;
2390
2391
0
    if(fcmd == DONE) {
2392
0
      failf(data, "Failed to do PORT");
2393
0
      result = CURLE_FTP_PORT_FAILED;
2394
0
    }
2395
0
    else
2396
      /* try next */
2397
0
      result = ftp_state_use_port(data, ftpc, fcmd);
2398
0
  }
2399
0
  else {
2400
0
    infof(data, "Connect data stream actively");
2401
0
    ftp_state(data, ftpc, FTP_STOP); /* end of DO phase */
2402
0
    result = ftp_dophase_done(data, ftpc, ftp, FALSE);
2403
0
  }
2404
2405
0
  return result;
2406
0
}
2407
2408
/* return TRUE on error, FALSE on success */
2409
static bool twodigit(const char *p, int *val)
2410
0
{
2411
0
  if(!ISDIGIT(p[0]) || !ISDIGIT(p[1]))
2412
0
    return TRUE;
2413
  /* curlx_hexval() works fine here since we make sure it is decimal above */
2414
0
  *val = (curlx_hexval(p[0]) * 10) + curlx_hexval(p[1]);
2415
0
  return FALSE;
2416
0
}
2417
2418
/*
2419
 * @unittest 1668
2420
 */
2421
UNITTEST bool ftp_213_date(const char *p, int *year, int *month, int *day,
2422
                           int *hour, int *minute, int *second);
2423
UNITTEST bool ftp_213_date(const char *p, int *year, int *month, int *day,
2424
                           int *hour, int *minute, int *second)
2425
0
{
2426
0
  int century;
2427
0
  if((strlen(p) < 14) || twodigit(&p[0], &century) || twodigit(&p[2], year) ||
2428
0
     twodigit(&p[4], month) || twodigit(&p[6], day) ||
2429
0
     twodigit(&p[8], hour) || twodigit(&p[10], minute) ||
2430
0
     twodigit(&p[12], second))
2431
0
    return FALSE;
2432
2433
0
  *year += century * 100;
2434
0
  if((*month > 12) || (*day > 31) || (*hour > 23) || (*minute > 59) ||
2435
0
     (*second > 60))
2436
0
    return FALSE;
2437
0
  return TRUE;
2438
0
}
2439
2440
static CURLcode client_write_header(struct Curl_easy *data,
2441
                                    char *buf, size_t blen)
2442
0
{
2443
  /* Some replies from an FTP server are written to the client
2444
   * as CLIENTWRITE_HEADER, formatted as if they came from a
2445
   * HTTP conversation.
2446
   * In all protocols, CLIENTWRITE_HEADER data is only passed to
2447
   * the body write callback when data->set.include_header is set
2448
   * via CURLOPT_HEADER.
2449
   * For historic reasons, FTP never played this game and expects
2450
   * all its headers to do that always. Set that flag during the
2451
   * call to Curl_client_write() so it does the right thing.
2452
   *
2453
   * Notice that we cannot enable this flag for FTP in general,
2454
   * as an FTP transfer might involve an HTTP proxy connection and
2455
   * headers from CONNECT should not automatically be part of the
2456
   * output. */
2457
0
  CURLcode result;
2458
0
  bool save = (bool)data->set.include_header;
2459
0
  data->set.include_header = TRUE;
2460
0
  result = Curl_client_write(data, CLIENTWRITE_HEADER, buf, blen);
2461
0
  data->set.include_header = save;
2462
0
  return result;
2463
0
}
2464
2465
static CURLcode ftp_state_mdtm_resp(struct Curl_easy *data,
2466
                                    struct cf_ftp_ctx *ftpc,
2467
                                    struct FTP *ftp,
2468
                                    int ftpcode)
2469
0
{
2470
0
  CURLcode result = CURLE_OK;
2471
2472
0
  switch(ftpcode) {
2473
0
  case 213: {
2474
    /* we got a time. Format should be: "YYYYMMDDHHMMSS[.sss]" where the
2475
       last .sss part is optional and means fractions of a second */
2476
0
    int year, month, day, hour, minute, second;
2477
0
    struct pingpong *pp = &ftpc->pp;
2478
0
    const char *resp = curlx_dyn_ptr(&pp->recvbuf) + 4;
2479
0
    bool showtime = FALSE;
2480
0
    if(ftp_213_date(resp, &year, &month, &day, &hour, &minute, &second)) {
2481
      /* we have a time, reformat it */
2482
0
      char timebuf[24];
2483
0
      curl_msnprintf(timebuf, sizeof(timebuf),
2484
0
                     "%04d%02d%02d %02d:%02d:%02d GMT",
2485
0
                     year, month, day, hour, minute, second);
2486
      /* now, convert this into a time() value: */
2487
0
      if(!Curl_getdate_capped(timebuf, &data->info.filetime))
2488
0
        showtime = TRUE;
2489
0
    }
2490
2491
    /* If we asked for a time of the file and we actually got one as well,
2492
       we "emulate" an HTTP-style header in our output. */
2493
2494
#if defined(CURL_HAVE_DIAG) && (defined(__DJGPP__) || defined(__AMIGA__))
2495
#pragma GCC diagnostic push
2496
/* 'time_t' is unsigned in MSDOS and AmigaOS. Silence:
2497
   warning: comparison of unsigned expression in '>= 0' is always true */
2498
#pragma GCC diagnostic ignored "-Wtype-limits"
2499
#endif
2500
0
    if(data->req.no_body && ftpc->file &&
2501
0
       data->set.get_filetime && showtime) {
2502
#if defined(CURL_HAVE_DIAG) && (defined(__DJGPP__) || defined(__AMIGA__))
2503
#pragma GCC diagnostic pop
2504
#endif
2505
0
      char headerbuf[128];
2506
0
      int headerbuflen;
2507
0
      time_t filetime = data->info.filetime;
2508
0
      struct tm buffer;
2509
0
      const struct tm *tm = &buffer;
2510
2511
0
      result = curlx_gmtime(filetime, &buffer);
2512
0
      if(result)
2513
0
        return result;
2514
2515
      /* format: "Tue, 15 Nov 1994 12:45:26" */
2516
0
      headerbuflen =
2517
0
        curl_msnprintf(headerbuf, sizeof(headerbuf),
2518
0
                       "Last-Modified: %s, %02d %s %4d %02d:%02d:%02d "
2519
0
                       "GMT\r\n",
2520
0
                       Curl_wkday[tm->tm_wday ? tm->tm_wday-1 : 6],
2521
0
                       tm->tm_mday,
2522
0
                       Curl_month[tm->tm_mon],
2523
0
                       tm->tm_year + 1900,
2524
0
                       tm->tm_hour,
2525
0
                       tm->tm_min,
2526
0
                       tm->tm_sec);
2527
0
      result = client_write_header(data, headerbuf, headerbuflen);
2528
0
      if(result)
2529
0
        return result;
2530
0
    } /* end of a ridiculous amount of conditionals */
2531
0
  }
2532
0
    break;
2533
0
  default:
2534
0
    infof(data, "unsupported MDTM reply format");
2535
0
    break;
2536
0
  case 550: /* 550 is used for several different problems, e.g.
2537
               "No such file or directory" or "Permission denied".
2538
               It does not mean that the file does not exist at all. */
2539
0
    infof(data, "MDTM failed: file does not exist or permission problem,"
2540
0
          " continuing");
2541
0
    break;
2542
0
  }
2543
2544
0
  if(data->set.timecondition) {
2545
0
    if((data->info.filetime > 0) && (data->set.timevalue > 0)) {
2546
0
      switch(data->set.timecondition) {
2547
0
      case CURL_TIMECOND_IFMODSINCE:
2548
0
      default:
2549
0
        if(data->info.filetime <= data->set.timevalue) {
2550
0
          infof(data, "The requested document is not new enough");
2551
0
          ftp->transfer = PPTRANSFER_NONE; /* mark to not transfer data */
2552
0
          data->info.timecond = TRUE;
2553
0
          ftp_state(data, ftpc, FTP_STOP);
2554
0
          return CURLE_OK;
2555
0
        }
2556
0
        break;
2557
0
      case CURL_TIMECOND_IFUNMODSINCE:
2558
0
        if(data->info.filetime > data->set.timevalue) {
2559
0
          infof(data, "The requested document is not old enough");
2560
0
          ftp->transfer = PPTRANSFER_NONE; /* mark to not transfer data */
2561
0
          data->info.timecond = TRUE;
2562
0
          ftp_state(data, ftpc, FTP_STOP);
2563
0
          return CURLE_OK;
2564
0
        }
2565
0
        break;
2566
0
      } /* switch */
2567
0
    }
2568
0
    else {
2569
0
      infof(data, "Skipping time comparison");
2570
0
    }
2571
0
  }
2572
2573
0
  if(!result)
2574
0
    result = ftp_state_type(data, ftpc, ftp);
2575
2576
0
  return result;
2577
0
}
2578
2579
static CURLcode ftp_state_type_resp(struct Curl_easy *data,
2580
                                    struct cf_ftp_ctx *ftpc,
2581
                                    struct FTP *ftp,
2582
                                    int ftpcode,
2583
                                    ftpstate instate)
2584
0
{
2585
0
  CURLcode result = CURLE_OK;
2586
2587
0
  if(ftpcode / 100 != 2) {
2588
    /* "sasserftpd" and "(u)r(x)bot ftpd" both responds with 226 after a
2589
       successful 'TYPE I'. While that is not as RFC959 says, it is still a
2590
       positive response code and we allow that. */
2591
0
    failf(data, "Could not set desired mode");
2592
0
    return CURLE_FTP_COULDNT_SET_TYPE;
2593
0
  }
2594
0
  if(ftpcode != 200)
2595
0
    infof(data, "Got a %03d response code instead of the assumed 200",
2596
0
          ftpcode);
2597
2598
0
  if(instate == FTP_TYPE)
2599
0
    result = ftp_state_size(data, ftpc, ftp);
2600
0
  else if(instate == FTP_LIST_TYPE)
2601
0
    result = ftp_state_list(data, ftpc, ftp);
2602
0
  else if(instate == FTP_RETR_TYPE)
2603
0
    result = ftp_state_retr_prequote(data, ftpc, ftp);
2604
0
  else if(instate == FTP_STOR_TYPE)
2605
0
    result = ftp_state_stor_prequote(data, ftpc, ftp);
2606
0
  else if(instate == FTP_RETR_LIST_TYPE)
2607
0
    result = ftp_state_list_prequote(data, ftpc, ftp);
2608
2609
0
  return result;
2610
0
}
2611
2612
static CURLcode ftp_state_size_resp(struct Curl_easy *data,
2613
                                    struct cf_ftp_ctx *ftpc,
2614
                                    struct FTP *ftp,
2615
                                    int ftpcode,
2616
                                    ftpstate instate)
2617
0
{
2618
0
  CURLcode result = CURLE_OK;
2619
0
  curl_off_t filesize = -1;
2620
0
  const char *buf = curlx_dyn_ptr(&ftpc->pp.recvbuf);
2621
0
  size_t len = ftpc->pp.nfinal;
2622
2623
  /* get the size from the ascii string: */
2624
0
  if(ftpcode == 213) {
2625
    /* To allow servers to prepend "rubbish" in the response string, we scan
2626
       for all the digits at the end of the response and parse only those as a
2627
       number. */
2628
0
    const char *start = &buf[4];
2629
0
    const char *fdigit = memchr(start, '\r', len - 4);
2630
0
    if(fdigit) {
2631
0
      fdigit--;
2632
0
      if(*fdigit == '\n')
2633
0
        fdigit--;
2634
0
      while(ISDIGIT(fdigit[-1]) && (fdigit > start))
2635
0
        fdigit--;
2636
0
    }
2637
0
    else
2638
0
      fdigit = start;
2639
0
    if(curlx_str_number(&fdigit, &filesize, CURL_OFF_T_MAX))
2640
0
      filesize = -1; /* size remain unknown */
2641
0
  }
2642
0
  else if(ftpcode == 550 && /* "No such file or directory" */
2643
          /* allow a SIZE failure for (resumed) uploads, when probing what
2644
             command to use */
2645
0
          instate != FTP_STOR_SIZE) {
2646
0
    failf(data, "The file does not exist");
2647
0
    return CURLE_REMOTE_FILE_NOT_FOUND;
2648
0
  }
2649
2650
0
  if(instate == FTP_SIZE) {
2651
0
    if(filesize != -1) {
2652
0
      char clbuf[128];
2653
0
      int clbuflen = curl_msnprintf(clbuf, sizeof(clbuf),
2654
0
                                    "Content-Length: %" FMT_OFF_T "\r\n",
2655
0
                                    filesize);
2656
0
      result = client_write_header(data, clbuf, clbuflen);
2657
0
      if(result)
2658
0
        return result;
2659
0
    }
2660
0
    Curl_pgrsSetDownloadSize(data, filesize);
2661
0
    result = ftp_state_rest(data, ftpc, ftp);
2662
0
  }
2663
0
  else if(instate == FTP_RETR_SIZE) {
2664
0
    Curl_pgrsSetDownloadSize(data, filesize);
2665
0
    result = ftp_state_retr(data, ftpc, ftp, filesize);
2666
0
  }
2667
0
  else if(instate == FTP_STOR_SIZE) {
2668
0
    data->state.resume_from = filesize;
2669
0
    result = ftp_state_ul_setup(data, ftpc, ftp, TRUE);
2670
0
  }
2671
2672
0
  return result;
2673
0
}
2674
2675
static CURLcode ftp_state_rest_resp(struct Curl_easy *data,
2676
                                    struct cf_ftp_ctx *ftpc,
2677
                                    struct FTP *ftp,
2678
                                    int ftpcode,
2679
                                    ftpstate instate)
2680
0
{
2681
0
  CURLcode result = CURLE_OK;
2682
2683
0
  switch(instate) {
2684
0
  case FTP_REST:
2685
0
  default:
2686
0
    if(ftpcode == 350) {
2687
0
      char buffer[24] = { "Accept-ranges: bytes\r\n" };
2688
0
      result = client_write_header(data, buffer, strlen(buffer));
2689
0
      if(result)
2690
0
        return result;
2691
0
    }
2692
0
    result = ftp_state_prepare_transfer(data, ftpc, ftp);
2693
0
    break;
2694
2695
0
  case FTP_RETR_REST:
2696
0
    if(ftpcode != 350) {
2697
0
      failf(data, "Could not use REST");
2698
0
      result = CURLE_FTP_COULDNT_USE_REST;
2699
0
    }
2700
0
    else {
2701
0
      result = Curl_pp_sendf(data, &ftpc->pp, "RETR %s", ftpc->file);
2702
0
      if(!result)
2703
0
        ftp_state(data, ftpc, FTP_RETR);
2704
0
    }
2705
0
    break;
2706
0
  }
2707
2708
0
  return result;
2709
0
}
2710
2711
static CURLcode ftp_state_stor_resp(struct Curl_easy *data,
2712
                                    struct cf_ftp_ctx *ftpc,
2713
                                    int ftpcode)
2714
0
{
2715
0
  CURLcode result = CURLE_OK;
2716
2717
0
  if(ftpcode >= 400) {
2718
0
    failf(data, "Failed FTP upload: %0d", ftpcode);
2719
0
    ftp_state(data, ftpc, FTP_STOP);
2720
0
    return CURLE_UPLOAD_FAILED;
2721
0
  }
2722
2723
  /* PORT means we are now awaiting the server to connect to us. */
2724
0
  if(data->set.ftp_use_port) {
2725
0
    bool connected;
2726
2727
0
    ftp_state(data, ftpc, FTP_STOP); /* no longer in STOR state */
2728
2729
0
    result = Curl_cfchain_connect(
2730
0
      data, &ftpc->chain_data, FALSE, &connected);
2731
0
    if(result)
2732
0
      return result;
2733
2734
0
    if(!connected) {
2735
0
      infof(data, "Data conn was not available immediately");
2736
0
      ftpc->wait_data_conn = TRUE;
2737
0
      return ftp_check_ctrl_on_data_wait(data, ftpc);
2738
0
    }
2739
0
    ftpc->wait_data_conn = FALSE;
2740
0
  }
2741
0
  return ftp_initiate_transfer(data, ftpc);
2742
0
}
2743
2744
/* for LIST and RETR responses */
2745
static CURLcode ftp_state_get_resp(struct Curl_easy *data,
2746
                                   struct cf_ftp_ctx *ftpc,
2747
                                   struct FTP *ftp,
2748
                                   int ftpcode,
2749
                                   ftpstate instate)
2750
0
{
2751
0
  CURLcode result = CURLE_OK;
2752
2753
0
  if((ftpcode == 150) || (ftpcode == 125)) {
2754
2755
    /*
2756
      A;
2757
      150 Opening BINARY mode data connection for /etc/passwd (2241
2758
      bytes).  (ok, the file is being transferred)
2759
2760
      B:
2761
      150 Opening ASCII mode data connection for /bin/ls
2762
2763
      C:
2764
      150 ASCII data connection for /bin/ls (137.167.104.91,37445) (0 bytes).
2765
2766
      D:
2767
      150 Opening ASCII mode data connection for [file] (0.0.0.0,0) (545 bytes)
2768
2769
      E:
2770
      125 Data connection already open; Transfer starting. */
2771
2772
0
    data->req.size = -1; /* default unknown size */
2773
2774
    /*
2775
     * It appears that there are FTP-servers that return size 0 for files when
2776
     * SIZE is used on the file while being in BINARY mode. To work around
2777
     * that (stupid) behavior, we attempt to parse the RETR response even if
2778
     * the SIZE returned size zero.
2779
     *
2780
     * Debugging help from Salvatore Sorrentino on February 26, 2003.
2781
     */
2782
2783
0
    if((instate != FTP_LIST) &&
2784
0
       !data->state.prefer_ascii &&
2785
0
       !data->set.ignorecl &&
2786
0
       (ftp->downloadsize < 1)) {
2787
      /*
2788
       * It seems directory listings either do not show the size or often uses
2789
       * size 0 anyway. ASCII transfers may cause that the transferred amount
2790
       * of data is not the same as this line tells, why using this number in
2791
       * those cases only confuses us.
2792
       *
2793
       * Example D above makes this parsing a little tricky */
2794
0
      size_t len = curlx_dyn_len(&ftpc->pp.recvbuf);
2795
0
      if(len >= 7) { /* "1 bytes" is 7 characters */
2796
0
        size_t i;
2797
0
        for(i = 0; i < len - 7; i++) {
2798
0
          curl_off_t what;
2799
0
          const char *buf = curlx_dyn_ptr(&ftpc->pp.recvbuf);
2800
0
          const char *c = &buf[i];
2801
0
          if(!curlx_str_number(&c, &what, CURL_OFF_T_MAX) &&
2802
0
             !curlx_str_single(&c, ' ') &&
2803
0
             !strncmp(c, "bytes", 5)) {
2804
0
            data->req.size = what;
2805
0
            break;
2806
0
          }
2807
0
        }
2808
0
      }
2809
0
    }
2810
0
    else if(ftp->downloadsize > -1)
2811
0
      data->req.size = ftp->downloadsize;
2812
2813
0
    if(data->req.size > data->req.maxdownload && data->req.maxdownload > 0)
2814
0
      data->req.size = data->req.maxdownload;
2815
0
    else if((instate != FTP_LIST) && data->state.prefer_ascii)
2816
0
      data->req.size = -1; /* for servers that understate ASCII mode file
2817
                              size */
2818
2819
0
    infof(data, "Maxdownload = %" FMT_OFF_T, data->req.maxdownload);
2820
2821
0
    if(instate != FTP_LIST)
2822
0
      infof(data, "Getting file with size: %" FMT_OFF_T, data->req.size);
2823
2824
0
    if(data->set.ftp_use_port) {
2825
0
      bool connected;
2826
2827
0
      result = Curl_cfchain_connect(
2828
0
        data, &ftpc->chain_data, FALSE, &connected);
2829
0
      if(result)
2830
0
        return result;
2831
2832
0
      if(!connected) {
2833
0
        infof(data, "Data conn was not available immediately");
2834
0
        ftp_state(data, ftpc, FTP_STOP);
2835
0
        ftpc->wait_data_conn = TRUE;
2836
0
        return ftp_check_ctrl_on_data_wait(data, ftpc);
2837
0
      }
2838
0
      ftpc->wait_data_conn = FALSE;
2839
0
    }
2840
0
    return ftp_initiate_transfer(data, ftpc);
2841
0
  }
2842
0
  else {
2843
0
    if((instate == FTP_LIST) && (ftpcode == 450)) {
2844
      /* no matching files in the directory listing */
2845
0
      ftp->transfer = PPTRANSFER_NONE; /* do not download anything */
2846
0
      ftp_state(data, ftpc, FTP_STOP); /* this phase is over */
2847
0
    }
2848
0
    else {
2849
0
      failf(data, "RETR response: %03d", ftpcode);
2850
0
      return instate == FTP_RETR && ftpcode == 550 ?
2851
0
        CURLE_REMOTE_FILE_NOT_FOUND :
2852
0
        CURLE_FTP_COULDNT_RETR_FILE;
2853
0
    }
2854
0
  }
2855
2856
0
  return result;
2857
0
}
2858
2859
/* after USER, PASS and ACCT */
2860
static CURLcode ftp_state_loggedin(struct Curl_easy *data,
2861
                                   struct cf_ftp_ctx *ftpc)
2862
0
{
2863
0
  CURLcode result = CURLE_OK;
2864
2865
0
  if(Curl_conn_is_ssl(data->conn)) {
2866
    /* PBSZ = PROTECTION BUFFER SIZE.
2867
2868
    The 'draft-murray-auth-ftp-ssl' (draft 12, page 7) says:
2869
2870
    Specifically, the PROT command MUST be preceded by a PBSZ
2871
    command and a PBSZ command MUST be preceded by a successful
2872
    security data exchange (the TLS negotiation in this case)
2873
2874
    ... (and on page 8):
2875
2876
    Thus the PBSZ command must still be issued, but must have a
2877
    parameter of '0' to indicate that no buffering is taking place
2878
    and the data connection should not be encapsulated.
2879
    */
2880
0
    result = Curl_pp_sendf(data, &ftpc->pp, "PBSZ %d", 0);
2881
0
    if(!result)
2882
0
      ftp_state(data, ftpc, FTP_PBSZ);
2883
0
  }
2884
0
  else {
2885
0
    result = ftp_state_pwd(data, ftpc);
2886
0
  }
2887
0
  return result;
2888
0
}
2889
2890
/* A value that becomes part of an FTP control command must not carry a
2891
   control byte: a CR or LF would end the command line and let a second
2892
   command be smuggled onto the control connection. */
2893
static bool ftp_has_ctrl(const char *string)
2894
0
{
2895
0
  const unsigned char *s = (const unsigned char *)string;
2896
0
  while(*s) {
2897
0
    if(*s < 0x20)
2898
0
      return TRUE;
2899
0
    s++;
2900
0
  }
2901
0
  return FALSE;
2902
0
}
2903
2904
/* for USER and PASS responses */
2905
static CURLcode ftp_state_user_resp(struct Curl_easy *data,
2906
                                    struct cf_ftp_ctx *ftpc,
2907
                                    int ftpcode)
2908
0
{
2909
0
  CURLcode result = CURLE_OK;
2910
2911
  /* some need password anyway, and others return 2xx ignored */
2912
0
  if((ftpcode == 331) && (ftpc->state == FTP_USER)) {
2913
    /* 331 Password required for ...
2914
       (the server requires to send the user's password too) */
2915
0
    result = Curl_pp_sendf(data, &ftpc->pp, "PASS %s",
2916
0
                           Curl_creds_passwd(data->conn->creds));
2917
0
    if(!result)
2918
0
      ftp_state(data, ftpc, FTP_PASS);
2919
0
  }
2920
0
  else if(ftpcode / 100 == 2) {
2921
    /* 230 User ... logged in.
2922
       (the user logged in with or without password) */
2923
0
    result = ftp_state_loggedin(data, ftpc);
2924
0
  }
2925
0
  else if(ftpcode == 332) {
2926
0
    const char *account = CURL_EASY_STR(data, STRING_FTP_ACCOUNT);
2927
0
    if(!account) {
2928
0
      failf(data, "ACCT requested but none available");
2929
0
      result = CURLE_LOGIN_DENIED;
2930
0
    }
2931
0
    else if(ftp_has_ctrl(account)) {
2932
0
      failf(data, "Control byte in FTP account");
2933
0
      result = CURLE_BAD_FUNCTION_ARGUMENT;
2934
0
    }
2935
0
    else {
2936
0
      result = Curl_pp_sendf(data, &ftpc->pp, "ACCT %s", account);
2937
0
      if(!result)
2938
0
        ftp_state(data, ftpc, FTP_ACCT);
2939
0
    }
2940
0
  }
2941
0
  else {
2942
    /* All other response codes, like:
2943
2944
    530 User ... access denied
2945
    (the server denies to log the specified user) */
2946
2947
0
    const char *alt = CURL_EASY_STR(data, STRING_FTP_ALTERNATIVE_TO_USER);
2948
0
    if(alt && !ftpc->ftp_trying_alternative) {
2949
      /* Ok, USER failed. Let's try the supplied command. */
2950
0
      if(ftp_has_ctrl(alt)) {
2951
0
        failf(data, "Control byte in FTP alternative-to-user command");
2952
0
        result = CURLE_BAD_FUNCTION_ARGUMENT;
2953
0
      }
2954
0
      else {
2955
0
        result = Curl_pp_sendf(data, &ftpc->pp, "%s", alt);
2956
0
        if(!result) {
2957
0
          ftpc->ftp_trying_alternative = TRUE;
2958
0
          ftp_state(data, ftpc, FTP_USER);
2959
0
        }
2960
0
      }
2961
0
    }
2962
0
    else {
2963
0
      failf(data, "Access denied: %03d", ftpcode);
2964
0
      result = CURLE_LOGIN_DENIED;
2965
0
    }
2966
0
  }
2967
0
  return result;
2968
0
}
2969
2970
/* for ACCT response */
2971
static CURLcode ftp_state_acct_resp(struct Curl_easy *data,
2972
                                    struct cf_ftp_ctx *ftpc,
2973
                                    int ftpcode)
2974
0
{
2975
0
  CURLcode result = CURLE_OK;
2976
0
  if(ftpcode != 230) {
2977
0
    failf(data, "ACCT rejected by server: %03d", ftpcode);
2978
0
    result = CURLE_FTP_WEIRD_PASS_REPLY; /* FIX */
2979
0
  }
2980
0
  else
2981
0
    result = ftp_state_loggedin(data, ftpc);
2982
2983
0
  return result;
2984
0
}
2985
2986
static CURLcode ftp_pwd_resp(struct Curl_easy *data,
2987
                             struct cf_ftp_ctx *ftpc,
2988
                             int ftpcode)
2989
0
{
2990
0
  struct pingpong *pp = &ftpc->pp;
2991
0
  CURLcode result;
2992
2993
0
  if(ftpcode == 257) {
2994
0
    const char *ptr = curlx_dyn_ptr(&pp->recvbuf) + 4; /* start on the first
2995
                                                          letter */
2996
0
    bool entry_extracted = FALSE;
2997
0
    struct dynbuf out;
2998
0
    curlx_dyn_init(&out, 1000);
2999
3000
    /* Reply format is like
3001
       257<space>[rubbish]"<directory-name>"<space><commentary> and the
3002
       RFC959 says
3003
3004
       The directory name can contain any character; embedded
3005
       double-quotes should be escaped by double-quotes (the
3006
       "quote-doubling" convention).
3007
     */
3008
3009
    /* scan for the first double-quote for non-standard responses */
3010
0
    while(*ptr != '\n' && *ptr != '\0' && *ptr != '"')
3011
0
      ptr++;
3012
3013
0
    if('\"' == *ptr) {
3014
      /* it started good */
3015
0
      for(ptr++; *ptr; ptr++) {
3016
0
        if('\"' == *ptr) {
3017
0
          if('\"' == ptr[1]) {
3018
            /* "quote-doubling" */
3019
0
            result = curlx_dyn_addn(&out, &ptr[1], 1);
3020
0
            ptr++;
3021
0
          }
3022
0
          else {
3023
            /* end of path */
3024
0
            if(curlx_dyn_len(&out))
3025
0
              entry_extracted = TRUE;
3026
0
            break; /* get out of this loop */
3027
0
          }
3028
0
        }
3029
0
        else {
3030
0
          if(ISCNTRL(*ptr)) {
3031
            /* control characters have no business in a path */
3032
0
            curlx_dyn_free(&out);
3033
0
            return CURLE_WEIRD_SERVER_REPLY;
3034
0
          }
3035
0
          result = curlx_dyn_addn(&out, ptr, 1);
3036
0
        }
3037
0
        if(result) {
3038
0
          curlx_dyn_free(&out);
3039
0
          return result;
3040
0
        }
3041
0
      }
3042
0
    }
3043
0
    if(entry_extracted) {
3044
      /* If the path name does not look like an absolute path (i.e.: it
3045
         does not start with a '/'), we probably need some server-dependent
3046
         adjustments. For example, this is the case when connecting to
3047
         an OS400 FTP server: this server supports two name syntaxes,
3048
         the default one being incompatible with standard paths. In
3049
         addition, this server switches automatically to the regular path
3050
         syntax when one is encountered in a command: this results in
3051
         having an entrypath in the wrong syntax when later used in CWD.
3052
         The method used here is to check the server OS: we do it only
3053
         if the path name looks strange to minimize overhead on other
3054
         systems. */
3055
0
      char *dir = curlx_dyn_ptr(&out);
3056
3057
0
      if(!ftpc->server_os && dir[0] != '/') {
3058
0
        result = Curl_pp_sendf(data, &ftpc->pp, "%s", "SYST");
3059
0
        if(result) {
3060
0
          curlx_dyn_free(&out);
3061
0
          return result;
3062
0
        }
3063
0
      }
3064
3065
0
      curlx_free(ftpc->entrypath);
3066
0
      ftpc->entrypath = dir; /* remember this */
3067
0
      infof(data, "Entry path is '%s'", ftpc->entrypath);
3068
      /* also save it where getinfo can access it: */
3069
0
      curlx_free(data->state.most_recent_ftp_entrypath);
3070
0
      data->state.most_recent_ftp_entrypath = curlx_strdup(ftpc->entrypath);
3071
0
      if(!data->state.most_recent_ftp_entrypath)
3072
0
        return CURLE_OUT_OF_MEMORY;
3073
3074
0
      if(!ftpc->server_os && dir[0] != '/') {
3075
0
        ftp_state(data, ftpc, FTP_SYST);
3076
0
        return CURLE_OK;
3077
0
      }
3078
0
    }
3079
0
    else {
3080
      /* could not get the path */
3081
0
      curlx_dyn_free(&out);
3082
0
      infof(data, "Failed to figure out path");
3083
0
    }
3084
0
  }
3085
0
  ftp_state(data, ftpc, FTP_STOP); /* we are done with CONNECT phase! */
3086
0
  CURL_TRC_FTP(data, "[%s] protocol connect phase DONE", FTP_CSTATE(ftpc));
3087
0
  return CURLE_OK;
3088
0
}
3089
3090
static const char * const ftpauth[] = { "SSL", "TLS" };
3091
3092
static CURLcode ftp_wait_resp(struct Curl_easy *data,
3093
                              struct connectdata *conn,
3094
                              struct cf_ftp_ctx *ftpc,
3095
                              int ftpcode)
3096
0
{
3097
0
  CURLcode result = CURLE_OK;
3098
0
  if(ftpcode == 230) {
3099
    /* 230 User logged in - already! Take as 220 if TLS required. */
3100
0
    if(ftpc->use_ssl <= CURLUSESSL_TRY || Curl_conn_is_ssl(conn))
3101
0
      return ftp_state_user_resp(data, ftpc, ftpcode);
3102
0
  }
3103
0
  else if(ftpcode != 220) {
3104
0
    failf(data, "Got a %03d ftp-server response when 220 was expected",
3105
0
          ftpcode);
3106
0
    return CURLE_WEIRD_SERVER_REPLY;
3107
0
  }
3108
3109
0
  if(ftpc->use_ssl && !Curl_conn_is_ssl(conn)) {
3110
    /* We do not have an SSL/TLS control connection yet, but FTPS is
3111
       requested. Try an FTPS connection now */
3112
3113
0
    ftpc->count3 = 0;
3114
0
    switch((long)data->set.ftpsslauth) {
3115
0
    case CURLFTPAUTH_DEFAULT:
3116
0
    case CURLFTPAUTH_SSL:
3117
0
      ftpc->count2 = 1; /* add one to get next */
3118
0
      ftpc->count1 = 0;
3119
0
      break;
3120
0
    case CURLFTPAUTH_TLS:
3121
0
      ftpc->count2 = -1; /* subtract one to get next */
3122
0
      ftpc->count1 = 1;
3123
0
      break;
3124
0
    default:
3125
0
      failf(data, "unsupported parameter to CURLOPT_FTPSSLAUTH: %d",
3126
0
            (int)data->set.ftpsslauth);
3127
0
      return CURLE_UNKNOWN_OPTION; /* we do not know what to do */
3128
0
    }
3129
0
    result = Curl_pp_sendf(data, &ftpc->pp, "AUTH %s", ftpauth[ftpc->count1]);
3130
0
    if(!result)
3131
0
      ftp_state(data, ftpc, FTP_AUTH);
3132
0
  }
3133
0
  else
3134
0
    result = ftp_state_user(data, ftpc, conn);
3135
0
  return result;
3136
0
}
3137
3138
/* an implicit TLS scheme implies TLS on both connections */
3139
static unsigned char ftp_use_ssl(struct connectdata *conn,
3140
                                 struct cf_ftp_ctx *ftpc)
3141
0
{
3142
0
  if(!ftpc->use_ssl && (conn->scheme->flags & PROTOPT_SSL))
3143
0
    return CURLUSESSL_ALL;
3144
0
  return ftpc->use_ssl;
3145
0
}
3146
3147
static CURLcode ftp_pp_statemachine(struct Curl_easy *data,
3148
                                    struct connectdata *conn)
3149
0
{
3150
0
  struct Curl_cfilter *cf = Curl_conn_get_first_cf(conn, &Curl_cft_ftp);
3151
0
  struct cf_ftp_ctx *ftpc = cf ? cf->ctx : NULL;
3152
0
  struct FTP *ftp = Curl_meta_get(data, CURL_META_FTP_EASY);
3153
0
  struct pingpong *pp;
3154
0
  CURLcode result;
3155
0
  int ftpcode;
3156
0
  size_t nread = 0;
3157
3158
0
  if(!ftpc || !ftp)
3159
0
    return CURLE_FAILED_INIT;
3160
0
  pp = &ftpc->pp;
3161
0
  if(pp->sendleft)
3162
0
    return Curl_pp_flushsend(data, pp);
3163
3164
0
  result = ftp_readresp(data, ftpc, pp, &ftpcode, &nread);
3165
0
  if(result || !ftpcode)
3166
0
    return result;
3167
3168
  /* we have now received a full FTP server response */
3169
0
  switch(ftpc->state) {
3170
0
  case FTP_WAIT220:
3171
0
    result = ftp_wait_resp(data, conn, ftpc, ftpcode);
3172
0
    break;
3173
3174
0
  case FTP_AUTH:
3175
    /* we have gotten the response to a previous AUTH command */
3176
3177
0
    if(pp->overflow)
3178
0
      return CURLE_WEIRD_SERVER_REPLY; /* Forbid pipelining in response. */
3179
3180
    /* RFC2228 (page 5) says:
3181
     *
3182
     * If the server is willing to accept the named security mechanism,
3183
     * and does not require any security data, it must respond with
3184
     * reply code 234/334.
3185
     */
3186
3187
0
    if((ftpcode == 234) || (ftpcode == 334)) {
3188
      /* this was BLOCKING, keep it so for now */
3189
0
      if(!Curl_conn_is_ssl(conn)) {
3190
0
        result = Curl_ssl_cf_insert_after(cf, data,
3191
0
          Curl_conn_get_origin(conn),
3192
0
          Curl_conn_get_destination(conn));
3193
0
        if(result) {
3194
          /* we failed and bail out */
3195
0
          return CURLE_USE_SSL_FAILED;
3196
0
        }
3197
0
      }
3198
0
      conn->bits.ftp_use_data_ssl = FALSE; /* clear-text data */
3199
0
      result = ftp_state_user(data, ftpc, conn);
3200
0
    }
3201
0
    else if(ftpc->count3 < 1) {
3202
0
      ftpc->count3++;
3203
0
      ftpc->count1 += ftpc->count2; /* get next attempt */
3204
0
      result = Curl_pp_sendf(data, &ftpc->pp, "AUTH %s",
3205
0
                             ftpauth[ftpc->count1]);
3206
      /* remain in this same state */
3207
0
    }
3208
0
    else {
3209
0
      if(ftpc->use_ssl > CURLUSESSL_TRY)
3210
        /* we failed and CURLUSESSL_CONTROL or CURLUSESSL_ALL is set */
3211
0
        result = CURLE_USE_SSL_FAILED;
3212
0
      else
3213
        /* ignore the failure and continue */
3214
0
        result = ftp_state_user(data, ftpc, conn);
3215
0
    }
3216
0
    break;
3217
3218
0
  case FTP_USER:
3219
0
  case FTP_PASS:
3220
0
    result = ftp_state_user_resp(data, ftpc, ftpcode);
3221
0
    break;
3222
3223
0
  case FTP_ACCT:
3224
0
    result = ftp_state_acct_resp(data, ftpc, ftpcode);
3225
0
    break;
3226
3227
0
  case FTP_PBSZ:
3228
0
    result =
3229
0
      Curl_pp_sendf(data, &ftpc->pp, "PROT %c",
3230
0
                    ftp_use_ssl(conn, ftpc) == CURLUSESSL_CONTROL ? 'C' : 'P');
3231
0
    if(!result)
3232
0
      ftp_state(data, ftpc, FTP_PROT);
3233
0
    break;
3234
3235
0
  case FTP_PROT:
3236
0
    if(ftpcode / 100 == 2)
3237
      /* We have enabled SSL for the data connection! */
3238
0
      conn->bits.ftp_use_data_ssl =
3239
0
        (ftp_use_ssl(conn, ftpc) != CURLUSESSL_CONTROL);
3240
    /* FTP servers typically responds with 500 if they decide to reject
3241
       our 'P' request */
3242
0
    else if(ftp_use_ssl(conn, ftpc) > CURLUSESSL_CONTROL)
3243
      /* we failed and bails out */
3244
0
      return CURLE_USE_SSL_FAILED;
3245
3246
0
    if(data->set.ftp_ccc) {
3247
      /* CCC - Clear Command Channel
3248
       */
3249
0
      result = Curl_pp_sendf(data, &ftpc->pp, "%s", "CCC");
3250
0
      if(!result)
3251
0
        ftp_state(data, ftpc, FTP_CCC);
3252
0
    }
3253
0
    else
3254
0
      result = ftp_state_pwd(data, ftpc);
3255
0
    break;
3256
3257
0
  case FTP_CCC:
3258
0
    if(ftpcode < 500) {
3259
      /* First shut down the SSL layer (note: this call will block) */
3260
      /* This has only been tested on the proftpd server, and the mod_tls
3261
       * code sends a close notify alert without waiting for a close notify
3262
       * alert in response. Thus we wait for a close notify alert from the
3263
       * server, but we do not send one. Let's hope other servers do
3264
       * the same... */
3265
0
      result = Curl_ssl_cfilter_remove(
3266
0
        data, (data->set.ftp_ccc == (uint8_t)CURLFTPSSL_CCC_ACTIVE));
3267
0
      if(result)
3268
0
        failf(data, "Failed to clear the command channel (CCC)");
3269
0
    }
3270
0
    if(!result)
3271
      /* Then continue as normal */
3272
0
      result = ftp_state_pwd(data, ftpc);
3273
0
    break;
3274
3275
0
  case FTP_PWD:
3276
0
    result = ftp_pwd_resp(data, ftpc, ftpcode);
3277
0
    break;
3278
3279
0
  case FTP_SYST:
3280
0
    if(ftpcode == 215) {
3281
0
      const char *ptr = curlx_dyn_ptr(&pp->recvbuf) + 4; /* start on the first
3282
                                                            letter */
3283
0
      const char *start;
3284
0
      char *os;
3285
3286
      /* Reply format is like
3287
         215<space><OS-name><space><commentary>
3288
       */
3289
0
      while(*ptr == ' ')
3290
0
        ptr++;
3291
0
      for(start = ptr; *ptr && *ptr != ' '; ptr++)
3292
0
        ;
3293
0
      os = curlx_memdup0(start, ptr - start);
3294
0
      if(!os)
3295
0
        return CURLE_OUT_OF_MEMORY;
3296
3297
      /* Check for special servers here. */
3298
0
      if(curl_strequal(os, "OS/400")) {
3299
        /* Force OS400 name format 1. */
3300
0
        result = Curl_pp_sendf(data, &ftpc->pp, "%s", "SITE NAMEFMT 1");
3301
0
        if(result) {
3302
0
          curlx_free(os);
3303
0
          return result;
3304
0
        }
3305
        /* remember target server OS */
3306
0
        curlx_free(ftpc->server_os);
3307
0
        ftpc->server_os = os;
3308
0
        ftp_state(data, ftpc, FTP_NAMEFMT);
3309
0
        break;
3310
0
      }
3311
      /* Nothing special for the target server. */
3312
      /* remember target server OS */
3313
0
      curlx_free(ftpc->server_os);
3314
0
      ftpc->server_os = os;
3315
0
    }
3316
0
    else {
3317
      /* Cannot identify server OS. Continue anyway and cross fingers. */
3318
0
    }
3319
3320
0
    ftp_state(data, ftpc, FTP_STOP); /* we are done with CONNECT phase! */
3321
0
    CURL_TRC_FTP(data, "[%s] protocol connect phase DONE", FTP_CSTATE(ftpc));
3322
0
    break;
3323
3324
0
  case FTP_NAMEFMT:
3325
0
    if(ftpcode == 250) {
3326
      /* Name format change successful: reload initial path. */
3327
0
      ftp_state_pwd(data, ftpc);
3328
0
      break;
3329
0
    }
3330
3331
0
    ftp_state(data, ftpc, FTP_STOP); /* we are done with CONNECT phase! */
3332
0
    CURL_TRC_FTP(data, "[%s] protocol connect phase DONE", FTP_CSTATE(ftpc));
3333
0
    break;
3334
3335
0
  case FTP_QUOTE:
3336
0
  case FTP_POSTQUOTE:
3337
0
  case FTP_RETR_PREQUOTE:
3338
0
  case FTP_STOR_PREQUOTE:
3339
0
  case FTP_LIST_PREQUOTE:
3340
0
    if((ftpcode >= 400) && !ftpc->count2) {
3341
      /* failure response code, and not allowed to fail */
3342
0
      failf(data, "QUOT command failed with %03d", ftpcode);
3343
0
      result = CURLE_QUOTE_ERROR;
3344
0
    }
3345
0
    else
3346
0
      result = ftp_state_quote(data, ftpc, ftp, FALSE, ftpc->state);
3347
0
    break;
3348
3349
0
  case FTP_CWD:
3350
0
    if(ftpcode / 100 != 2) {
3351
      /* failure to CWD there */
3352
0
      if(data->set.ftp_create_missing_dirs &&
3353
0
         ftpc->cwdcount && !ftpc->count2) {
3354
        /* try making it */
3355
0
        ftpc->count2++; /* counter to prevent CWD-MKD loops */
3356
3357
        /* count3 is set to allow MKD to fail once per dir. In the case when
3358
           CWD fails and then MKD fails (due to another session raced it to
3359
           create the dir) this then allows for a second try to CWD to it. */
3360
0
        ftpc->count3 = (data->set.ftp_create_missing_dirs == 2) ? 1 : 0;
3361
3362
0
        result = Curl_pp_sendf(data, &ftpc->pp, "MKD %.*s",
3363
0
                               pathlen(ftpc, ftpc->cwdcount - 1),
3364
0
                               pathpiece(ftpc, ftpc->cwdcount - 1));
3365
0
        if(!result)
3366
0
          ftp_state(data, ftpc, FTP_MKD);
3367
0
      }
3368
0
      else {
3369
        /* return failure */
3370
0
        failf(data, "Server denied you to change to the given directory");
3371
0
        ftpc->cwdfail = TRUE; /* do not remember this path as we failed
3372
                                 to enter it */
3373
0
        result = CURLE_REMOTE_ACCESS_DENIED;
3374
0
      }
3375
0
    }
3376
0
    else {
3377
      /* success */
3378
0
      ftpc->count2 = 0;
3379
0
      if(ftpc->cwdcount >= ftpc->dirdepth)
3380
0
        result = ftp_state_mdtm(data, ftpc, ftp);
3381
0
      else {
3382
0
        ftpc->cwdcount++;
3383
        /* send next CWD */
3384
0
        result = Curl_pp_sendf(data, &ftpc->pp, "CWD %.*s",
3385
0
                               pathlen(ftpc, ftpc->cwdcount - 1),
3386
0
                               pathpiece(ftpc, ftpc->cwdcount - 1));
3387
0
      }
3388
0
    }
3389
0
    break;
3390
3391
0
  case FTP_MKD:
3392
0
    if((ftpcode / 100 != 2) && !ftpc->count3--) {
3393
      /* failure to MKD the directory */
3394
0
      failf(data, "Failed to MKD dir: %03d", ftpcode);
3395
0
      result = CURLE_REMOTE_ACCESS_DENIED;
3396
0
    }
3397
0
    else {
3398
0
      ftp_state(data, ftpc, FTP_CWD);
3399
      /* send CWD */
3400
0
      result = Curl_pp_sendf(data, &ftpc->pp, "CWD %.*s",
3401
0
                             pathlen(ftpc, ftpc->cwdcount - 1),
3402
0
                             pathpiece(ftpc, ftpc->cwdcount - 1));
3403
0
    }
3404
0
    break;
3405
3406
0
  case FTP_MDTM:
3407
0
    result = ftp_state_mdtm_resp(data, ftpc, ftp, ftpcode);
3408
0
    break;
3409
3410
0
  case FTP_TYPE:
3411
0
  case FTP_LIST_TYPE:
3412
0
  case FTP_RETR_TYPE:
3413
0
  case FTP_STOR_TYPE:
3414
0
  case FTP_RETR_LIST_TYPE:
3415
0
    result = ftp_state_type_resp(data, ftpc, ftp, ftpcode, ftpc->state);
3416
0
    break;
3417
3418
0
  case FTP_SIZE:
3419
0
  case FTP_RETR_SIZE:
3420
0
  case FTP_STOR_SIZE:
3421
0
    result = ftp_state_size_resp(data, ftpc, ftp, ftpcode, ftpc->state);
3422
0
    break;
3423
3424
0
  case FTP_REST:
3425
0
  case FTP_RETR_REST:
3426
0
    result = ftp_state_rest_resp(data, ftpc, ftp, ftpcode, ftpc->state);
3427
0
    break;
3428
3429
0
  case FTP_PRET:
3430
0
    if(ftpcode != 200) {
3431
      /* there only is this one standard OK return code. */
3432
0
      failf(data, "PRET command not accepted: %03d", ftpcode);
3433
0
      return CURLE_FTP_PRET_FAILED;
3434
0
    }
3435
0
    result = ftp_state_use_pasv(data, ftpc, conn);
3436
0
    break;
3437
3438
0
  case FTP_PASV:
3439
0
    result = ftp_state_pasv_resp(data, ftpc, ftpcode);
3440
0
    break;
3441
3442
0
  case FTP_PORT:
3443
0
    result = ftp_state_port_resp(data, ftpc, ftp, ftpcode);
3444
0
    break;
3445
3446
0
  case FTP_LIST:
3447
0
  case FTP_RETR:
3448
0
    result = ftp_state_get_resp(data, ftpc, ftp, ftpcode, ftpc->state);
3449
0
    break;
3450
3451
0
  case FTP_STOR:
3452
0
    result = ftp_state_stor_resp(data, ftpc, ftpcode);
3453
0
    break;
3454
3455
0
  case FTP_STOP:
3456
0
  default:
3457
    /* internal error */
3458
0
    ftp_state(data, ftpc, FTP_STOP);
3459
0
    break;
3460
0
  }
3461
3462
0
  return result;
3463
0
}
3464
3465
/* called repeatedly until done from multi.c */
3466
static CURLcode ftp_multi_statemach(struct Curl_easy *data,
3467
                                    bool *done)
3468
0
{
3469
0
  struct cf_ftp_ctx *ftpc = ftp_get_cf_ctx(data->conn);
3470
0
  return ftpc ? ftp_statemach(data, ftpc, done) : CURLE_FAILED_INIT;
3471
0
}
3472
3473
/***********************************************************************
3474
 *
3475
 * ftp_sendquote()
3476
 *
3477
 * Where a 'quote' means a list of custom commands to send to the server.
3478
 * The quote list is passed as an argument.
3479
 *
3480
 * BLOCKING
3481
 */
3482
static CURLcode ftp_sendquote(struct Curl_easy *data,
3483
                              struct cf_ftp_ctx *ftpc,
3484
                              struct Curl_frzn_strs *quote)
3485
0
{
3486
0
  struct pingpong *pp = &ftpc->pp;
3487
0
  size_t i;
3488
3489
0
  for(i = 0; i < Curl_frzn_strs_count(quote); ++i) {
3490
0
    const char *cmd = Curl_frzn_strs_get_str(quote, i);
3491
0
    if(cmd) {
3492
0
      size_t nread;
3493
0
      bool acceptfail = FALSE;
3494
0
      CURLcode result;
3495
0
      int ftpcode = 0;
3496
3497
      /* if a command starts with an asterisk, which a legal FTP command never
3498
         can, the command will be allowed to fail without it causing any
3499
         aborts or cancels etc. It will cause libcurl to act as if the command
3500
         is successful, whatever the server responds. */
3501
3502
0
      if(cmd[0] == '*') {
3503
0
        cmd++;
3504
0
        acceptfail = TRUE;
3505
0
      }
3506
3507
0
      result = Curl_pp_sendf(data, &ftpc->pp, "%s", cmd);
3508
0
      if(!result) {
3509
0
        pp->response = *Curl_pgrs_now(data); /* timeout relative now */
3510
0
        result = getftpresponse(data, &nread, &ftpcode);
3511
0
      }
3512
0
      if(result)
3513
0
        return result;
3514
3515
0
      if(!acceptfail && (ftpcode >= 400)) {
3516
0
        failf(data, "QUOT string not accepted: %s", cmd);
3517
0
        return CURLE_QUOTE_ERROR;
3518
0
      }
3519
0
    }
3520
0
  }
3521
3522
0
  return CURLE_OK;
3523
0
}
3524
3525
static CURLcode ftp_done_status(struct Curl_easy *data,
3526
                                struct cf_ftp_ctx *ftpc, CURLcode status,
3527
                                bool premature)
3528
0
{
3529
0
  switch(status) {
3530
0
  case CURLE_BAD_DOWNLOAD_RESUME:
3531
0
  case CURLE_FTP_WEIRD_PASV_REPLY:
3532
0
  case CURLE_FTP_PORT_FAILED:
3533
0
  case CURLE_FTP_ACCEPT_FAILED:
3534
0
  case CURLE_FTP_ACCEPT_TIMEOUT:
3535
0
  case CURLE_FTP_COULDNT_SET_TYPE:
3536
0
  case CURLE_FTP_COULDNT_RETR_FILE:
3537
0
  case CURLE_PARTIAL_FILE:
3538
0
  case CURLE_UPLOAD_FAILED:
3539
0
  case CURLE_REMOTE_ACCESS_DENIED:
3540
0
  case CURLE_FILESIZE_EXCEEDED:
3541
0
  case CURLE_REMOTE_FILE_NOT_FOUND:
3542
0
  case CURLE_WRITE_ERROR:
3543
    /* the connection stays alive fine even though this happened */
3544
0
  case CURLE_OK: /* does not affect the control connection's status */
3545
0
    if(!premature)
3546
0
      break;
3547
3548
    /* until we cope better with prematurely ended requests, let them
3549
     * fallback as if in complete failure */
3550
0
    FALLTHROUGH();
3551
0
  default:       /* by default, an error means the control connection is
3552
                    wedged and should not be used anymore */
3553
0
    ftpc->cwdfail = TRUE; /* set this TRUE to prevent us to remember the
3554
                             current path, as this connection is going */
3555
0
    CURL_TRC_FTP(data, "FTP ended with bad error code");
3556
0
    connclose(data->conn);
3557
0
    return status;      /* use the already set error code */
3558
0
  }
3559
0
  return CURLE_OK;
3560
0
}
3561
3562
static void ftp_done_wildcard(struct Curl_easy *data, struct cf_ftp_ctx *ftpc)
3563
0
{
3564
0
  if(data->state.wildcardmatch) {
3565
0
    if(data->set.chunk_end && ftpc->file) {
3566
0
      struct Curl_mapi_guard guard;
3567
0
      CURL_CBAPI_START(&guard, data, easy_chunk_end);
3568
0
      data->set.chunk_end(data->set.wildcardptr);
3569
0
      CURL_CBAPI_END(&guard);
3570
0
      freedirs(ftpc);
3571
0
    }
3572
0
    ftpc->known_filesize = -1;
3573
0
  }
3574
0
}
3575
3576
static void ftp_done_path(struct Curl_easy *data, struct cf_ftp_ctx *ftpc,
3577
                          CURLcode result)
3578
0
{
3579
0
  struct connectdata *conn = data->conn;
3580
0
  if(result) {
3581
    /* We can limp along anyway (and should try to since we may already be in
3582
     * the error path) */
3583
0
    connclose(conn); /* mark for connection closure */
3584
0
    curlx_safefree(ftpc->prevpath); /* no path remembering */
3585
0
  }
3586
0
  else { /* remember working directory for connection reuse */
3587
0
    const char *rawPath = ftpc->rawpath;
3588
0
    if(rawPath) {
3589
0
      if((data->set.ftp_filemethod == FTPFILE_NOCWD) && (rawPath[0] == '/'))
3590
0
        ; /* full path => no CWDs happened => keep ftpc->prevpath */
3591
0
      else {
3592
0
        size_t pathLen = strlen(ftpc->rawpath);
3593
3594
0
        curlx_free(ftpc->prevpath);
3595
3596
0
        if(!ftpc->cwdfail) {
3597
0
          if(data->set.ftp_filemethod == FTPFILE_NOCWD)
3598
0
            pathLen = 0; /* relative path => working directory is FTP home */
3599
0
          else
3600
            /* file is URL-decoded */
3601
0
            pathLen -= ftpc->file ? strlen(ftpc->file) : 0;
3602
0
          ftpc->prevpath = curlx_memdup0(rawPath, pathLen);
3603
0
        }
3604
0
        else
3605
0
          ftpc->prevpath = NULL; /* no path */
3606
0
      }
3607
0
    }
3608
0
    if(ftpc->prevpath)
3609
0
      infof(data, "Remembering we are in directory \"%s\"", ftpc->prevpath);
3610
0
  }
3611
0
}
3612
3613
static CURLcode ftp_done_secondary_socket(struct Curl_easy *data,
3614
                                          struct cf_ftp_ctx *ftpc,
3615
                                          CURLcode result)
3616
0
{
3617
0
  struct connectdata *conn = data->conn;
3618
0
  if(ftpc->chain_data.cf) {
3619
0
    if(!result && ftpc->dont_check && data->req.maxdownload > 0) {
3620
      /* partial download completed */
3621
0
      result = Curl_pp_sendf(data, &ftpc->pp, "%s", "ABOR");
3622
0
      if(result) {
3623
0
        failf(data, "Failure sending ABOR command: %s",
3624
0
              curl_easy_strerror(result));
3625
0
        connclose(conn); /* connection closure */
3626
0
      }
3627
0
    }
3628
3629
0
    ftp_close_chain_data(data, ftpc);
3630
0
  }
3631
0
  return result;
3632
0
}
3633
3634
static CURLcode ftp_done_control_reply(struct Curl_easy *data,
3635
                                       struct cf_ftp_ctx *ftpc,
3636
                                       struct FTP *ftp, CURLcode result,
3637
                                       bool premature)
3638
0
{
3639
0
  struct connectdata *conn = data->conn;
3640
0
  size_t nread;
3641
0
  int ftpcode;
3642
3643
0
  if(!result && (ftp->transfer == PPTRANSFER_BODY) &&
3644
0
     ftpc->pp.pending_resp && !premature) {
3645
    /*
3646
     * Let's see what the server says about the transfer we performed, but
3647
     * lower the timeout as sometimes this connection has died while the data
3648
     * has been transferred. This happens when doing through NATs etc that
3649
     * abandon old silent connections.
3650
     */
3651
0
    ftpc->pp.response = *Curl_pgrs_now(data); /* timeout relative now */
3652
0
    result = getftpresponse(data, &nread, &ftpcode);
3653
3654
0
    if(!nread && (result == CURLE_OPERATION_TIMEDOUT)) {
3655
0
      failf(data, "control connection looks dead");
3656
0
      connclose(conn); /* close */
3657
0
    }
3658
3659
0
    if(result)
3660
0
      return result;
3661
3662
0
    if(ftpc->dont_check && data->req.maxdownload > 0) {
3663
      /* we have sent ABOR and there is no reliable way to check if it was
3664
       * successful or not; we have to close the connection now */
3665
0
      infof(data, "partial download completed, closing connection");
3666
0
      connclose(conn);
3667
0
      return result;
3668
0
    }
3669
3670
0
    if(!ftpc->dont_check) {
3671
      /* 226 Transfer complete, 250 Requested file action okay, completed. */
3672
0
      switch(ftpcode) {
3673
0
      case 226:
3674
0
      case 250:
3675
0
        break;
3676
0
      case 552:
3677
0
        failf(data, "Exceeded storage allocation");
3678
0
        result = CURLE_REMOTE_DISK_FULL;
3679
0
        break;
3680
0
      default:
3681
0
        failf(data, "server did not report OK, got %d", ftpcode);
3682
0
        result = CURLE_PARTIAL_FILE;
3683
0
        break;
3684
0
      }
3685
0
    }
3686
0
  }
3687
0
  return result;
3688
0
}
3689
3690
static CURLcode ftp_done_check_partial(struct Curl_easy *data,
3691
                                       struct cf_ftp_ctx *ftpc,
3692
                                       struct FTP *ftp, CURLcode result,
3693
                                       bool premature)
3694
0
{
3695
0
  if(result || premature)
3696
    /* the response code from the transfer showed an error already so no
3697
       use checking further */
3698
0
    ;
3699
0
  else if(data->state.upload) {
3700
0
    if((ftp->transfer == PPTRANSFER_BODY) &&
3701
0
       (data->state.infilesize != -1) && /* upload with known size */
3702
0
       ((!data->set.crlf && !data->state.prefer_ascii && /* no conversion */
3703
0
         (data->state.infilesize != data->req.writebytecount)) ||
3704
0
        ((data->set.crlf || data->state.prefer_ascii) && /* maybe CRLF conv */
3705
0
         (data->state.infilesize > data->req.writebytecount))
3706
0
       )) {
3707
0
      failf(data, "Uploaded unaligned file size (%" FMT_OFF_T
3708
0
            " out of %" FMT_OFF_T " bytes)",
3709
0
            data->req.writebytecount, data->state.infilesize);
3710
0
      result = CURLE_PARTIAL_FILE;
3711
0
    }
3712
0
  }
3713
0
  else {
3714
0
    if((data->req.size != -1) &&
3715
0
       (data->req.size != data->req.bytecount) &&
3716
0
       (data->req.maxdownload != data->req.bytecount)) {
3717
0
      failf(data, "Received only partial file: %" FMT_OFF_T " bytes",
3718
0
            data->req.bytecount);
3719
0
      result = CURLE_PARTIAL_FILE;
3720
0
    }
3721
0
    else if(!ftpc->dont_check &&
3722
0
            !data->req.bytecount &&
3723
0
            (data->req.size > 0)) {
3724
0
      failf(data, "No data was received");
3725
0
      result = CURLE_FTP_COULDNT_RETR_FILE;
3726
0
    }
3727
0
  }
3728
0
  return result;
3729
0
}
3730
3731
/***********************************************************************
3732
 *
3733
 * ftp_done()
3734
 *
3735
 * The DONE function. This does what needs to be done after a single DO has
3736
 * performed.
3737
 *
3738
 * Input argument is already checked for validity.
3739
 */
3740
static CURLcode ftp_done(struct Curl_easy *data, CURLcode status,
3741
                         bool premature)
3742
0
{
3743
0
  struct FTP *ftp = Curl_meta_get(data, CURL_META_FTP_EASY);
3744
0
  struct cf_ftp_ctx *ftpc = ftp_get_cf_ctx(data->conn);
3745
0
  CURLcode result;
3746
3747
0
  if(!ftp || !ftpc)
3748
0
    return CURLE_OK;
3749
3750
0
  result = ftp_done_status(data, ftpc, status, premature);
3751
3752
0
  ftp_done_wildcard(data, ftpc);
3753
0
  ftp_done_path(data, ftpc, result);
3754
0
  result = ftp_done_secondary_socket(data, ftpc, result);
3755
0
  result = ftp_done_control_reply(data, ftpc, ftp, result, premature);
3756
0
  result = ftp_done_check_partial(data, ftpc, ftp, result, premature);
3757
3758
  /* clear these for next connection */
3759
0
  ftp->transfer = PPTRANSFER_BODY;
3760
0
  ftpc->dont_check = FALSE;
3761
3762
  /* Send any post-transfer QUOTE strings? */
3763
0
  if(!status && !result && !premature && data->set.a.postquote)
3764
0
    result = ftp_sendquote(data, ftpc, data->set.a.postquote);
3765
0
  CURL_TRC_FTP(data, "[%s] done, result=%d", FTP_CSTATE(ftpc), (int)result);
3766
0
  return result;
3767
0
}
3768
3769
/***********************************************************************
3770
 *
3771
 * ftp_nb_type()
3772
 *
3773
 * Set TYPE. We only deal with ASCII or BINARY so this function
3774
 * sets one of them.
3775
 * If the transfer type is not sent, simulate on OK response in newstate
3776
 */
3777
static CURLcode ftp_nb_type(struct Curl_easy *data,
3778
                            struct cf_ftp_ctx *ftpc,
3779
                            struct FTP *ftp,
3780
                            bool ascii, ftpstate newstate)
3781
0
{
3782
0
  CURLcode result;
3783
0
  char want = (char)(ascii ? 'A' : 'I');
3784
3785
0
  if(ftpc->transfertype == want) {
3786
0
    ftp_state(data, ftpc, newstate);
3787
0
    return ftp_state_type_resp(data, ftpc, ftp, 200, newstate);
3788
0
  }
3789
3790
0
  result = Curl_pp_sendf(data, &ftpc->pp, "TYPE %c", want);
3791
0
  if(!result) {
3792
0
    ftp_state(data, ftpc, newstate);
3793
3794
    /* keep track of our current transfer type */
3795
0
    ftpc->transfertype = want;
3796
0
  }
3797
0
  return result;
3798
0
}
3799
3800
/***********************************************************************
3801
 *
3802
 * ftp_perform()
3803
 *
3804
 * This is the actual DO function for FTP. Get a file/directory according to
3805
 * the options previously setup.
3806
 */
3807
static CURLcode ftp_perform(
3808
  struct Curl_easy *data,
3809
  struct cf_ftp_ctx *ftpc,
3810
  struct FTP *ftp,
3811
  bool *connected,  /* connect status after PASV / PORT */
3812
  bool *dophase_done)
3813
0
{
3814
  /* this is FTP and no proxy */
3815
0
  CURLcode result = CURLE_OK;
3816
3817
0
  CURL_TRC_FTP(data, "[%s] DO phase starts", FTP_CSTATE(ftpc));
3818
3819
0
  if(data->req.no_body) {
3820
    /* requested no body means no transfer... */
3821
0
    ftp->transfer = PPTRANSFER_INFO;
3822
0
  }
3823
3824
0
  *dophase_done = FALSE; /* not done yet */
3825
3826
  /* start the first command in the DO phase */
3827
0
  result = ftp_state_quote(data, ftpc, ftp, TRUE, FTP_QUOTE);
3828
0
  if(result)
3829
0
    return result;
3830
3831
  /* run the state-machine */
3832
0
  result = ftp_statemach(data, ftpc, dophase_done);
3833
3834
0
  *connected = Curl_cfchain_is_connected(&ftpc->chain_data);
3835
3836
0
  if(*connected)
3837
0
    infof(data, "[FTP] [%s] perform, DATA connection established",
3838
0
          FTP_CSTATE(ftpc));
3839
0
  else
3840
0
    CURL_TRC_FTP(data, "[%s] perform, awaiting DATA connect",
3841
0
                 FTP_CSTATE(ftpc));
3842
3843
0
  if(*dophase_done)
3844
0
    CURL_TRC_FTP(data, "[%s] DO phase is complete1", FTP_CSTATE(ftpc));
3845
3846
0
  return result;
3847
0
}
3848
3849
static void wc_data_dtor(void *ptr)
3850
0
{
3851
0
  struct ftp_wc *ftpwc = ptr;
3852
0
  if(ftpwc && ftpwc->parser)
3853
0
    Curl_ftp_parselist_data_free(&ftpwc->parser);
3854
0
  curlx_free(ftpwc);
3855
0
}
3856
3857
static CURLcode init_wc_data(struct Curl_easy *data,
3858
                             struct cf_ftp_ctx *ftpc,
3859
                             struct FTP *ftp)
3860
0
{
3861
0
  char *last_slash;
3862
0
  char *path = ftp->path;
3863
0
  struct WildcardData *wildcard = data->wildcard;
3864
0
  CURLcode result = CURLE_OK;
3865
0
  struct ftp_wc *ftpwc = NULL;
3866
3867
0
  last_slash = strrchr(ftp->path, '/');
3868
0
  if(last_slash) {
3869
0
    last_slash++;
3870
0
    if(last_slash[0] == '\0') {
3871
0
      wildcard->state = CURLWC_CLEAN;
3872
0
      return ftp_parse_url_path(data, ftpc, ftp);
3873
0
    }
3874
0
    wildcard->pattern = curlx_strdup(last_slash);
3875
0
    if(!wildcard->pattern)
3876
0
      return CURLE_OUT_OF_MEMORY;
3877
0
    last_slash[0] = '\0'; /* cut file from path */
3878
0
  }
3879
0
  else { /* there is only 'wildcard pattern' or nothing */
3880
0
    if(path[0]) {
3881
0
      wildcard->pattern = curlx_strdup(path);
3882
0
      if(!wildcard->pattern)
3883
0
        return CURLE_OUT_OF_MEMORY;
3884
0
      path[0] = '\0';
3885
0
    }
3886
0
    else { /* only list */
3887
0
      wildcard->state = CURLWC_CLEAN;
3888
0
      return ftp_parse_url_path(data, ftpc, ftp);
3889
0
    }
3890
0
  }
3891
3892
  /* program continues only if URL is not ending with slash, allocate needed
3893
     resources for wildcard transfer */
3894
3895
  /* allocate ftp protocol specific wildcard data */
3896
0
  ftpwc = curlx_calloc(1, sizeof(struct ftp_wc));
3897
0
  if(!ftpwc) {
3898
0
    result = CURLE_OUT_OF_MEMORY;
3899
0
    goto fail;
3900
0
  }
3901
3902
  /* INITIALIZE parselist structure */
3903
0
  ftpwc->parser = Curl_ftp_parselist_data_alloc();
3904
0
  if(!ftpwc->parser) {
3905
0
    result = CURLE_OUT_OF_MEMORY;
3906
0
    goto fail;
3907
0
  }
3908
3909
0
  wildcard->ftpwc = ftpwc; /* put it to the WildcardData tmp pointer */
3910
0
  wildcard->dtor = wc_data_dtor;
3911
3912
  /* wildcard does not support NOCWD option (assert it?) */
3913
0
  if(data->set.ftp_filemethod == FTPFILE_NOCWD)
3914
0
    data->set.ftp_filemethod = FTPFILE_MULTICWD;
3915
3916
  /* try to parse ftp URL */
3917
0
  result = ftp_parse_url_path(data, ftpc, ftp);
3918
0
  if(result) {
3919
0
    goto fail;
3920
0
  }
3921
3922
0
  wildcard->path = curlx_strdup(ftp->path);
3923
0
  if(!wildcard->path) {
3924
0
    result = CURLE_OUT_OF_MEMORY;
3925
0
    goto fail;
3926
0
  }
3927
3928
0
  infof(data, "Wildcard - Parsing started");
3929
0
  return CURLE_OK;
3930
3931
0
fail:
3932
0
  if(ftpwc) {
3933
0
    Curl_ftp_parselist_data_free(&ftpwc->parser);
3934
0
    curlx_free(ftpwc);
3935
0
  }
3936
0
  curlx_safefree(wildcard->pattern);
3937
0
  wildcard->dtor = ZERO_NULL;
3938
0
  wildcard->ftpwc = NULL;
3939
0
  return result;
3940
0
}
3941
3942
static CURLcode wc_statemach(struct Curl_easy *data,
3943
                             struct cf_ftp_ctx *ftpc,
3944
                             struct FTP *ftp)
3945
0
{
3946
0
  struct WildcardData * const wildcard = data->wildcard;
3947
0
  CURLcode result = CURLE_OK;
3948
3949
0
  for(;;) {
3950
0
    switch(wildcard->state) {
3951
0
    case CURLWC_INIT:
3952
0
      result = init_wc_data(data, ftpc, ftp);
3953
0
      if(wildcard->state == CURLWC_CLEAN)
3954
        /* only listing! */
3955
0
        return result;
3956
0
      wildcard->state = result ? CURLWC_ERROR : CURLWC_MATCHING;
3957
0
      return result;
3958
3959
0
    case CURLWC_MATCHING: {
3960
      /* In this state is LIST response successfully parsed, so lets restore
3961
         previous WRITEFUNCTION callback and WRITEDATA pointer */
3962
0
      struct ftp_wc *ftpwc = wildcard->ftpwc;
3963
0
      wildcard->state = CURLWC_DOWNLOADING;
3964
3965
0
      if(Curl_ftp_parselist_geterror(ftpwc->parser)) {
3966
        /* error found in LIST parsing */
3967
0
        wildcard->state = CURLWC_CLEAN;
3968
0
        continue;
3969
0
      }
3970
0
      if(Curl_llist_count(&wildcard->filelist) == 0) {
3971
        /* no corresponding file */
3972
0
        wildcard->state = CURLWC_CLEAN;
3973
0
        return CURLE_REMOTE_FILE_NOT_FOUND;
3974
0
      }
3975
0
      continue;
3976
0
    }
3977
3978
0
    case CURLWC_DOWNLOADING: {
3979
      /* filelist has at least one file, lets get first one */
3980
0
      struct Curl_llist_node *head = Curl_llist_head(&wildcard->filelist);
3981
0
      struct curl_fileinfo *finfo = Curl_node_elem(head);
3982
0
      char *tmp_path;
3983
0
      char *enc = curl_easy_escape(NULL, finfo->filename, 0);
3984
0
      if(!enc)
3985
0
        return CURLE_OUT_OF_MEMORY;
3986
3987
0
      tmp_path = curl_maprintf("%s%s", wildcard->path, enc);
3988
0
      curl_free(enc);
3989
0
      if(!tmp_path)
3990
0
        return CURLE_OUT_OF_MEMORY;
3991
3992
      /* switch default ftp->path and tmp_path */
3993
0
      curlx_free(ftp->pathalloc);
3994
0
      ftp->pathalloc = ftp->path = tmp_path;
3995
3996
0
      infof(data, "Wildcard - START of \"%s\"", finfo->filename);
3997
0
      if(data->set.chunk_bgn) {
3998
0
        long userresponse;
3999
0
        struct Curl_mapi_guard guard;
4000
0
        CURL_CBAPI_START(&guard, data, easy_chunk_bgn);
4001
0
        userresponse = data->set.chunk_bgn(
4002
0
          finfo, data->set.wildcardptr,
4003
0
          (int)Curl_llist_count(&wildcard->filelist));
4004
0
        CURL_CBAPI_END(&guard);
4005
0
        switch(userresponse) {
4006
0
        case CURL_CHUNK_BGN_FUNC_SKIP:
4007
0
          infof(data, "Wildcard - \"%s\" skipped by user", finfo->filename);
4008
0
          wildcard->state = CURLWC_SKIP;
4009
0
          continue;
4010
0
        case CURL_CHUNK_BGN_FUNC_FAIL:
4011
0
          return CURLE_CHUNK_FAILED;
4012
0
        }
4013
0
      }
4014
4015
0
      if(finfo->filetype != CURLFILETYPE_FILE) {
4016
0
        wildcard->state = CURLWC_SKIP;
4017
0
        continue;
4018
0
      }
4019
4020
0
      if(finfo->flags & CURLFINFOFLAG_KNOWN_SIZE)
4021
0
        ftpc->known_filesize = finfo->size;
4022
4023
0
      result = ftp_parse_url_path(data, ftpc, ftp);
4024
0
      if(result)
4025
0
        return result;
4026
4027
      /* we do not need the Curl_fileinfo of first file anymore */
4028
0
      Curl_node_remove(Curl_llist_head(&wildcard->filelist));
4029
4030
0
      if(Curl_llist_count(&wildcard->filelist) == 0) {
4031
        /* remains only one file to down. */
4032
0
        wildcard->state = CURLWC_CLEAN;
4033
        /* after that will be ftp_do called once again and no transfer
4034
           will be done because of CURLWC_CLEAN state */
4035
0
        return CURLE_OK;
4036
0
      }
4037
0
      return result;
4038
0
    }
4039
4040
0
    case CURLWC_SKIP: {
4041
0
      if(data->set.chunk_end) {
4042
0
        struct Curl_mapi_guard guard;
4043
0
        CURL_CBAPI_START(&guard, data, easy_chunk_end);
4044
0
        data->set.chunk_end(data->set.wildcardptr);
4045
0
        CURL_CBAPI_END(&guard);
4046
0
      }
4047
0
      Curl_node_remove(Curl_llist_head(&wildcard->filelist));
4048
0
      wildcard->state = (Curl_llist_count(&wildcard->filelist) == 0) ?
4049
0
        CURLWC_CLEAN : CURLWC_DOWNLOADING;
4050
0
      continue;
4051
0
    }
4052
4053
0
    case CURLWC_CLEAN: {
4054
0
      struct ftp_wc *ftpwc = wildcard->ftpwc;
4055
0
      result = CURLE_OK;
4056
0
      if(ftpwc)
4057
0
        result = Curl_ftp_parselist_geterror(ftpwc->parser);
4058
4059
0
      wildcard->state = result ? CURLWC_ERROR : CURLWC_DONE;
4060
0
      return result;
4061
0
    }
4062
4063
0
    case CURLWC_DONE:
4064
0
    case CURLWC_ERROR:
4065
0
    case CURLWC_CLEAR:
4066
0
      if(wildcard->dtor) {
4067
0
        wildcard->dtor(wildcard->ftpwc);
4068
0
        wildcard->ftpwc = NULL;
4069
0
      }
4070
0
      return result;
4071
0
    }
4072
0
  }
4073
  /* UNREACHABLE */
4074
0
}
4075
4076
/***********************************************************************
4077
 *
4078
 * ftp_regular_transfer()
4079
 *
4080
 * The input argument is already checked for validity.
4081
 *
4082
 * Performs all commands done before a regular transfer between a local and a
4083
 * remote host.
4084
 *
4085
 */
4086
static CURLcode ftp_regular_transfer(struct Curl_easy *data,
4087
                                     struct cf_ftp_ctx *ftpc,
4088
                                     struct FTP *ftp,
4089
                                     bool *dophase_done)
4090
0
{
4091
0
  CURLcode result = CURLE_OK;
4092
0
  bool connected = FALSE;
4093
0
  data->req.size = -1; /* make sure this is unknown at this point */
4094
4095
0
  Curl_pgrsReset(data);
4096
4097
0
  result = ftp_perform(data, ftpc, ftp,
4098
0
                       &connected, /* have we connected after PASV/PORT */
4099
0
                       dophase_done); /* all commands in the DO-phase done? */
4100
4101
0
  if(!result) {
4102
4103
0
    if(!*dophase_done)
4104
      /* the DO phase has not completed yet */
4105
0
      return CURLE_OK;
4106
4107
0
    result = ftp_dophase_done(data, ftpc, ftp, connected);
4108
0
    if(result)
4109
0
      return result;
4110
0
  }
4111
0
  else
4112
0
    freedirs(ftpc);
4113
4114
0
  return result;
4115
0
}
4116
4117
/***********************************************************************
4118
 *
4119
 * ftp_do()
4120
 *
4121
 * This function is registered as 'curl_do' function. It decodes the path
4122
 * parts etc as a wrapper to the actual DO function (ftp_perform).
4123
 *
4124
 * The input argument is already checked for validity.
4125
 */
4126
static CURLcode ftp_do(struct Curl_easy *data, bool *done)
4127
0
{
4128
0
  CURLcode result = CURLE_OK;
4129
0
  struct cf_ftp_ctx *ftpc = ftp_get_cf_ctx(data->conn);
4130
0
  struct FTP *ftp = Curl_meta_get(data, CURL_META_FTP_EASY);
4131
4132
0
  *done = FALSE; /* default to false */
4133
0
  if(!ftpc || !ftp)
4134
0
    return CURLE_FAILED_INIT;
4135
0
  ftpc->wait_data_conn = FALSE; /* default to no such wait */
4136
4137
0
#ifdef CURL_PREFER_LF_LINEENDS
4138
0
  {
4139
    /* FTP data may need conversion. */
4140
0
    struct Curl_cwriter *ftp_lc_writer;
4141
4142
0
    result = Curl_cwriter_create(&ftp_lc_writer, data, &ftp_cw_lc,
4143
0
                                 CURL_CW_CONTENT_DECODE);
4144
0
    if(result)
4145
0
      return result;
4146
4147
0
    result = Curl_cwriter_add(data, ftp_lc_writer);
4148
0
    if(result) {
4149
0
      Curl_cwriter_free(data, ftp_lc_writer);
4150
0
      return result;
4151
0
    }
4152
0
  }
4153
0
#endif /* CURL_PREFER_LF_LINEENDS */
4154
4155
0
  if(data->state.wildcardmatch) {
4156
0
    result = wc_statemach(data, ftpc, ftp);
4157
0
    if(data->wildcard->state == CURLWC_SKIP ||
4158
0
       data->wildcard->state == CURLWC_DONE) {
4159
      /* do not call ftp_regular_transfer */
4160
0
      return CURLE_OK;
4161
0
    }
4162
0
    if(result) /* error, loop or skipping the file */
4163
0
      return result;
4164
0
  }
4165
0
  else { /* no wildcard FSM needed */
4166
0
    result = ftp_parse_url_path(data, ftpc, ftp);
4167
0
    if(result)
4168
0
      return result;
4169
0
  }
4170
4171
0
  result = ftp_regular_transfer(data, ftpc, ftp, done);
4172
4173
0
  return result;
4174
0
}
4175
4176
/* called from multi.c while DOing */
4177
static CURLcode ftp_doing(struct Curl_easy *data,
4178
                          bool *dophase_done)
4179
0
{
4180
0
  struct cf_ftp_ctx *ftpc = ftp_get_cf_ctx(data->conn);
4181
0
  struct FTP *ftp = Curl_meta_get(data, CURL_META_FTP_EASY);
4182
0
  CURLcode result;
4183
4184
0
  if(!ftpc || !ftp)
4185
0
    return CURLE_FAILED_INIT;
4186
0
  result = ftp_statemach(data, ftpc, dophase_done);
4187
4188
0
  if(result)
4189
0
    CURL_TRC_FTP(data, "[%s] DO phase failed", FTP_CSTATE(ftpc));
4190
0
  else if(*dophase_done) {
4191
0
    result = ftp_dophase_done(data, ftpc, ftp, FALSE /* not connected */);
4192
4193
0
    CURL_TRC_FTP(data, "[%s] DO phase is complete2", FTP_CSTATE(ftpc));
4194
0
  }
4195
0
  return result;
4196
0
}
4197
4198
static void ftp_easy_dtor(const void *key, size_t klen, void *entry)
4199
0
{
4200
0
  struct FTP *ftp = entry;
4201
0
  (void)key;
4202
0
  (void)klen;
4203
0
  curlx_safefree(ftp->pathalloc);
4204
0
  curlx_free(ftp);
4205
0
}
4206
4207
static void type_url_check(struct Curl_easy *data, struct FTP *ftp)
4208
0
{
4209
0
  size_t len = strlen(ftp->path);
4210
  /* FTP URLs support an extension like ";type=<typecode>" that
4211
   * we will try to get now! */
4212
0
  if((len >= 7) && !memcmp(&ftp->path[len - 7], ";type=", 6)) {
4213
0
    char *type = &ftp->path[len - 7];
4214
0
    char command = Curl_raw_toupper(type[6]);
4215
4216
0
    *type = 0; /* cut it off */
4217
4218
0
    switch(command) {
4219
0
    case 'A': /* ASCII mode */
4220
0
      data->state.prefer_ascii = TRUE;
4221
0
      break;
4222
4223
0
    case 'D': /* directory mode */
4224
0
      data->state.list_only = TRUE;
4225
0
      break;
4226
4227
0
    case 'I': /* binary mode */
4228
0
    default:
4229
      /* switch off ASCII */
4230
0
      data->state.prefer_ascii = FALSE;
4231
0
      break;
4232
0
    }
4233
0
  }
4234
0
}
4235
4236
static void cf_ftp_ctx_free(struct cf_ftp_ctx *ctx,
4237
                            struct Curl_easy *data)
4238
0
{
4239
0
  if(ctx) {
4240
0
    Curl_cfchain_cleanup(&ctx->chain_data, data);
4241
0
    freedirs(ctx);
4242
0
    curlx_free(ctx->account);
4243
0
    curlx_free(ctx->alternative_to_user);
4244
0
    curlx_free(ctx->entrypath);
4245
0
    curlx_free(ctx->prevpath);
4246
0
    curlx_free(ctx->server_os);
4247
0
    Curl_pp_disconnect(&ctx->pp);
4248
0
    curlx_free(ctx);
4249
0
  }
4250
0
}
4251
4252
static struct cf_ftp_ctx *cf_ftp_ctx_create(struct Curl_easy *data,
4253
                                            struct connectdata *conn)
4254
0
{
4255
0
  struct cf_ftp_ctx *ftpc = curlx_calloc(1, sizeof(*ftpc));
4256
0
  if(!ftpc)
4257
0
    return NULL;
4258
4259
  /* clone connection related data that is FTP specific */
4260
0
  if(CURL_EASY_STR(data, STRING_FTP_ACCOUNT)) {
4261
0
    ftpc->account = curlx_strdup(CURL_EASY_STR(data, STRING_FTP_ACCOUNT));
4262
0
    if(!ftpc->account) {
4263
0
      cf_ftp_ctx_free(ftpc, data);
4264
0
      return NULL;
4265
0
    }
4266
0
  }
4267
0
  if(CURL_EASY_STR(data, STRING_FTP_ALTERNATIVE_TO_USER)) {
4268
0
    ftpc->alternative_to_user =
4269
0
      curlx_strdup(CURL_EASY_STR(data, STRING_FTP_ALTERNATIVE_TO_USER));
4270
0
    if(!ftpc->alternative_to_user) {
4271
0
      cf_ftp_ctx_free(ftpc, data);
4272
0
      return NULL;
4273
0
    }
4274
0
  }
4275
4276
0
  Curl_cfchain_init(&ftpc->chain_data, conn, FALSE);
4277
0
  ftpc->known_filesize = -1; /* unknown size for now */
4278
0
  ftpc->use_ssl = data->set.use_ssl;
4279
0
  ftpc->ccc = data->set.ftp_ccc;
4280
4281
0
  Curl_pp_init(&ftpc->pp, Curl_pgrs_now(data)); /* once per transfer */
4282
0
  PINGPONG_SETUP(&ftpc->pp, ftp_pp_statemachine, ftp_endofresp);
4283
4284
  /* WE start in the state where we await the 220 response */
4285
0
  ftp_state(data, ftpc, FTP_WAIT220);
4286
4287
0
  return ftpc;
4288
0
}
4289
4290
static void cf_ftp_destroy(struct Curl_cfilter *cf,
4291
                           struct Curl_easy *data)
4292
0
{
4293
0
  CURL_TRC_CF(data, cf, "destroy");
4294
0
  cf_ftp_ctx_free(cf->ctx, data);
4295
0
}
4296
4297
static CURLcode cf_ftp_connect(struct Curl_cfilter *cf,
4298
                               struct Curl_easy *data,
4299
                               bool *done)
4300
0
{
4301
0
  struct cf_ftp_ctx *ctx = cf->ctx;
4302
0
  CURLcode result;
4303
4304
0
  DEBUGASSERT(ctx);
4305
0
  if(cf->connected) {
4306
0
    *done = TRUE;
4307
0
    return CURLE_OK;
4308
0
  }
4309
4310
0
  result = cf->next->cft->do_connect(cf->next, data, done);
4311
0
  if(result || !*done)
4312
0
    return result;
4313
4314
0
  result = ftp_statemach(data, ctx, done);
4315
0
  if(!result && *done) {
4316
0
    CURL_TRC_CF(data, cf, "connected");
4317
0
    cf->connected = TRUE;
4318
0
  }
4319
0
  return result;
4320
0
}
4321
4322
static CURLcode cf_ftp_send(struct Curl_cfilter *cf, struct Curl_easy *data,
4323
                            const uint8_t *buf, size_t blen, bool eos,
4324
                            size_t *pnwritten)
4325
0
{
4326
0
  struct cf_ftp_ctx *ftpc = cf->ctx;
4327
0
  CURLcode result;
4328
4329
0
  if(!cf->connected) {
4330
0
    result = cf->next ?
4331
0
      cf->next->cft->do_send(cf->next, data, buf, blen, eos, pnwritten) :
4332
0
      CURLE_SEND_ERROR;
4333
0
    goto out;
4334
0
  }
4335
4336
0
  if(!ftpc->chain_data.cf) {
4337
0
    result = ftpc->data_shutdown ? CURLE_SEND_ERROR : CURLE_AGAIN;
4338
0
    goto out;
4339
0
  }
4340
4341
0
data_shutdown:
4342
0
  *pnwritten = 0;
4343
0
  if(ftpc->data_shutdown) {
4344
0
    bool done = FALSE;
4345
0
    result = Curl_cshutdn_cfchain_try_once(data, &ftpc->chain_data, &done);
4346
0
    if(!result && !done) {
4347
0
      result = CURLE_AGAIN;
4348
0
      goto out;
4349
0
    }
4350
    /* ignore shutdown errors on send, server will tell us */
4351
0
    Curl_cfchain_reset(&ftpc->chain_data, data);
4352
0
    *pnwritten = blen;
4353
0
    result = CURLE_OK;
4354
0
    goto out;
4355
0
  }
4356
0
  else if(!ftpc->chain_data.cf->connected) {
4357
0
    bool connected;
4358
0
    result = Curl_cfchain_connect(data, &ftpc->chain_data, FALSE, &connected);
4359
0
    if(result)
4360
0
      goto out;
4361
0
    if(!connected) {
4362
0
      result = CURLE_AGAIN;
4363
0
      goto out;
4364
0
    }
4365
0
  }
4366
4367
0
  result = ftpc->chain_data.cf->cft->do_send(
4368
0
    ftpc->chain_data.cf, data, buf, blen, eos, pnwritten);
4369
0
  if(result)
4370
0
    return result;
4371
0
  else if(eos && (*pnwritten == blen)) {
4372
0
    ftpc->data_shutdown = TRUE;
4373
0
    goto data_shutdown;
4374
0
  }
4375
4376
0
out:
4377
0
  CURL_TRC_CF(data, cf, "send(len=%zu, eos=%d) -> %d, %zu",
4378
0
              blen, eos, (int)result, *pnwritten);
4379
0
  return result;
4380
0
}
4381
4382
static CURLcode cf_ftp_recv(struct Curl_cfilter *cf, struct Curl_easy *data,
4383
                            char *buf, size_t blen, size_t *pnread)
4384
0
{
4385
0
  struct cf_ftp_ctx *ftpc = cf->ctx;
4386
0
  CURLcode result;
4387
4388
0
  *pnread = 0;
4389
0
  if(!cf->connected) {
4390
0
    result = cf->next ?
4391
0
             cf->next->cft->do_recv(cf->next, data, buf, blen, pnread) :
4392
0
             CURLE_RECV_ERROR;
4393
0
    goto out;
4394
0
  }
4395
4396
0
  if(!ftpc->chain_data.cf) {
4397
0
    result = ftpc->data_shutdown ? CURLE_RECV_ERROR : CURLE_AGAIN;
4398
0
    goto out;
4399
0
  }
4400
4401
0
data_shutdown:
4402
0
  if(ftpc->data_shutdown) {
4403
0
    bool done = FALSE;
4404
0
    result = Curl_cshutdn_cfchain_try_once(data, &ftpc->chain_data, &done);
4405
0
    if(!result && !done)
4406
0
      result = CURLE_AGAIN;
4407
0
    else {
4408
0
      Curl_cfchain_reset(&ftpc->chain_data, data);
4409
0
    }
4410
0
    goto out;
4411
0
  }
4412
0
  else if(!ftpc->chain_data.cf->connected) {
4413
0
    bool connected;
4414
0
    result = Curl_cfchain_connect(data, &ftpc->chain_data, FALSE, &connected);
4415
0
    if(result)
4416
0
      goto out;
4417
0
    if(!connected) {
4418
0
      result = CURLE_AGAIN;
4419
0
      goto out;
4420
0
    }
4421
0
  }
4422
4423
0
  result = ftpc->chain_data.cf->cft->do_recv(
4424
0
    ftpc->chain_data.cf, data, buf, blen, pnread);
4425
0
  if(!result && !*pnread) {
4426
0
    ftpc->data_shutdown = TRUE;
4427
0
    goto data_shutdown;
4428
0
  }
4429
4430
0
out:
4431
0
  CURL_TRC_CF(data, cf, "recv(len=%zu) -> %d, %zu",
4432
0
              blen, (int)result, *pnread);
4433
0
  return result;
4434
0
}
4435
4436
static CURLcode cf_ftp_shutdown(struct Curl_cfilter *cf,
4437
                                struct Curl_easy *data,
4438
                                bool *done)
4439
0
{
4440
0
  struct cf_ftp_ctx *ftpc = cf->ctx;
4441
0
  CURLcode result;
4442
4443
0
  (void)data;
4444
0
  *done = FALSE;
4445
0
  if(ftpc && ftpc->chain_data.cf)
4446
0
    ftp_close_chain_data(data, ftpc);
4447
0
  if(!cf->connected || !ftpc || data->conn->bits.close || cf->shutdown) {
4448
0
    *done = TRUE;
4449
0
    return CURLE_OK;
4450
0
  }
4451
4452
0
  result = ftp_statemach(data, ftpc, done);
4453
0
  cf->shutdown = (result || *done);
4454
0
  return result;
4455
0
}
4456
4457
static CURLcode cf_ftp_adjust_pollset(struct Curl_cfilter *cf,
4458
                                      struct Curl_easy *data,
4459
                                      struct easy_pollset *ps)
4460
0
{
4461
0
  struct cf_ftp_ctx *ftpc = cf->ctx;
4462
0
  CURLcode result = CURLE_OK;
4463
0
  bool want_recv, want_send;
4464
4465
0
  if(!ftpc)
4466
0
    return CURLE_OK;
4467
4468
0
  if(ftpc->chain_data.cf) {
4469
0
    if(ftpc->chain_data.cf->connected) {
4470
0
      Curl_pollset_check(data, ps, cf->chain->sock, &want_recv, &want_send);
4471
0
      if(ftpc->chain_data.sock != CURL_SOCKET_BAD) {
4472
0
        if(want_send)
4473
0
          result = Curl_pollset_add_out(data, ps, ftpc->chain_data.sock);
4474
0
        if(!result && want_recv)
4475
0
          result = Curl_pollset_add_in(data, ps, ftpc->chain_data.sock);
4476
0
        if(result)
4477
0
          return result;
4478
0
      }
4479
0
    }
4480
0
    result = Curl_cfchain_adjust_pollset(data, &ftpc->chain_data, ps);
4481
0
    if(result)
4482
0
      return result;
4483
0
  }
4484
4485
0
  if(cf->chain->sock == CURL_SOCKET_BAD)
4486
0
    return CURLE_OK;
4487
0
  else if(ftpc->pp.sendleft)
4488
0
    return Curl_pollset_change(data, ps, cf->chain->sock,
4489
0
      CURL_POLL_IN | CURL_POLL_OUT, 0);
4490
0
  else
4491
0
    return Curl_pollset_set_in_only(data, ps, cf->chain->sock);
4492
0
}
4493
4494
static CURLcode cf_ftp_cntrl(struct Curl_cfilter *cf,
4495
                             struct Curl_easy *data,
4496
                             int event, int arg1, void *arg2)
4497
0
{
4498
0
  struct cf_ftp_ctx *ftpc = cf->ctx;
4499
0
  CURLcode result = CURLE_OK;
4500
4501
0
  if(ftpc->chain_data.cf) {
4502
0
    result = Curl_conn_cf_cntrl(
4503
0
      ftpc->chain_data.cf, data, FALSE, event, arg1, arg2);
4504
0
    if(result && (result != CURLE_AGAIN))
4505
0
      goto out;
4506
0
    result = CURLE_OK;
4507
0
  }
4508
0
out:
4509
0
  return result;
4510
0
}
4511
4512
static CURLcode cf_ftp_query(struct Curl_cfilter *cf,
4513
                             struct Curl_easy *data,
4514
                             int query, int *pres1, void *pres2)
4515
0
{
4516
0
  struct cf_ftp_ctx *ftpc = cf->ctx;
4517
4518
0
  if(ftpc->chain_data.cf) {
4519
0
    switch(query) {
4520
0
    case CF_QUERY_NEED_FLUSH:
4521
0
      if(Curl_cfchain_needs_flush(data, &ftpc->chain_data)) {
4522
0
        *pres1 = TRUE;
4523
0
        return CURLE_OK;
4524
0
      }
4525
0
      break;
4526
0
    default:
4527
0
      break;
4528
0
    }
4529
0
  }
4530
4531
0
  return cf->next ?
4532
0
    cf->next->cft->query(cf->next, data, query, pres1, pres2) :
4533
0
    CURLE_UNKNOWN_OPTION;
4534
0
}
4535
4536
static bool cf_ftp_data_pending(struct Curl_cfilter *cf,
4537
                                const struct Curl_easy *data)
4538
0
{
4539
0
  struct cf_ftp_ctx *ftpc = cf->ctx;
4540
4541
0
  if(ftpc->chain_data.cf &&
4542
0
     Curl_cfchain_data_pending(CURL_UNCONST(data), &ftpc->chain_data))
4543
0
    return TRUE;
4544
0
  return cf->next ?
4545
0
    cf->next->cft->has_data_pending(cf->next, data) : FALSE;
4546
0
}
4547
4548
struct Curl_cftype Curl_cft_ftp = {
4549
  "FTP",
4550
  CF_TYPE_SAFE_EOS,
4551
  0,
4552
  cf_ftp_destroy,
4553
  cf_ftp_connect,
4554
  cf_ftp_shutdown,
4555
  cf_ftp_adjust_pollset,
4556
  cf_ftp_data_pending,
4557
  cf_ftp_send,
4558
  cf_ftp_recv,
4559
  cf_ftp_cntrl,
4560
  Curl_cf_def_conn_is_alive,
4561
  Curl_cf_def_conn_keep_alive,
4562
  cf_ftp_query,
4563
};
4564
4565
static struct cf_ftp_ctx *ftp_get_cf_ctx(struct connectdata *conn)
4566
0
{
4567
0
  struct Curl_cfilter *cf = Curl_conn_get_first_cf(conn, &Curl_cft_ftp);
4568
0
  return cf ? cf->ctx : NULL;
4569
0
}
4570
4571
static CURLcode cf_ftp_ctl_send(struct Curl_easy *data, void *io_user_data,
4572
                                char *buf, size_t blen, bool eos,
4573
                                size_t *pnwritten)
4574
0
{
4575
0
  struct Curl_cfilter *cf = io_user_data;
4576
0
  if(cf->next) {
4577
0
    if(!cf->next->connected) {
4578
0
      bool connected;
4579
0
      CURLcode result = Curl_conn_cf_connect(cf->next, data, &connected);
4580
0
      if(result)
4581
0
        return result;
4582
0
      if(!connected)
4583
0
        return CURLE_AGAIN;
4584
0
    }
4585
0
    return cf->next->cft->do_send(cf->next, data,
4586
0
                                  (uint8_t *)buf, blen, eos, pnwritten);
4587
0
  }
4588
0
  *pnwritten = 0;
4589
0
  return CURLE_RECV_ERROR;
4590
0
}
4591
4592
static CURLcode cf_ftp_ctl_recv(struct Curl_easy *data, void *io_user_data,
4593
                                 char *buf, size_t blen,
4594
                                 size_t *pnread)
4595
0
{
4596
0
  struct Curl_cfilter *cf = io_user_data;
4597
0
  if(cf->next) {
4598
0
    if(!cf->next->connected) {
4599
0
      bool connected;
4600
0
      CURLcode result = Curl_conn_cf_connect(cf->next, data, &connected);
4601
0
      if(result)
4602
0
        return result;
4603
0
      if(!connected)
4604
0
        return CURLE_AGAIN;
4605
0
    }
4606
0
    return cf->next->cft->do_recv(cf->next, data, buf, blen, pnread);
4607
0
  }
4608
0
  *pnread = 0;
4609
0
  return CURLE_SEND_ERROR;
4610
0
}
4611
4612
static CURLcode cf_ftp_ctl_poll(struct Curl_easy *data, void *io_user_data,
4613
                                 bool want_send, bool want_recv,
4614
                                 timediff_t timeout_ms)
4615
0
{
4616
0
  struct Curl_cfilter *cf = io_user_data;
4617
0
  if(!cf->next)
4618
0
    return CURLE_FAILED_INIT;
4619
0
  if(cf->next->cft->has_data_pending(cf->next, data))
4620
0
    return CURLE_OK;
4621
0
  else {
4622
0
    curl_socket_t sock = cf->chain->sock;
4623
0
    int rc = Curl_socket_check(want_recv ? sock : CURL_SOCKET_BAD,
4624
0
                               want_send ? sock : CURL_SOCKET_BAD,
4625
0
                               timeout_ms);
4626
0
    if(rc == -1) {
4627
0
      failf(data, "select/poll error");
4628
0
      return want_send ? CURLE_SEND_ERROR : CURLE_RECV_ERROR;
4629
0
    }
4630
0
    return rc ? CURLE_OK : CURLE_AGAIN;
4631
0
  }
4632
0
}
4633
4634
static CURLcode cf_ftp_create(struct Curl_cfilter **pcf,
4635
                              struct Curl_easy *data)
4636
0
{
4637
0
  struct Curl_cfilter *cf = NULL;
4638
0
  struct cf_ftp_ctx *ctx;
4639
0
  CURLcode result;
4640
4641
0
  (void)data;
4642
0
  ctx = cf_ftp_ctx_create(data, data->conn);
4643
0
  if(!ctx) {
4644
0
    result = CURLE_OUT_OF_MEMORY;
4645
0
    goto out;
4646
0
  }
4647
4648
0
  result = Curl_cf_create(&cf, &Curl_cft_ftp, ctx);
4649
0
  if(result)
4650
0
    goto out;
4651
  /* Setup pingpong I/O to go via control filter chain */
4652
0
  Curl_pp_set_io(&ctx->pp, cf_ftp_ctl_send,
4653
0
                 cf_ftp_ctl_recv, cf_ftp_ctl_poll, cf);
4654
0
  ctx = NULL;
4655
4656
0
out:
4657
0
  cf_ftp_ctx_free(ctx, data);
4658
0
  *pcf = result ? NULL : cf;
4659
0
  return result;
4660
0
}
4661
4662
static CURLcode ftp_setup_connection(struct Curl_easy *data,
4663
                                     struct connectdata *conn)
4664
0
{
4665
0
  struct FTP *ftp;
4666
0
  CURLcode result = CURLE_OK;
4667
4668
0
  (void)conn;
4669
0
  ftp = curlx_calloc(1, sizeof(*ftp));
4670
0
  if(!ftp ||
4671
0
     Curl_meta_set(data, CURL_META_FTP_EASY, ftp, ftp_easy_dtor))
4672
0
    return CURLE_OUT_OF_MEMORY;
4673
4674
0
  ftp->path = &data->state.up.path[1]; /* do not include the initial slash */
4675
0
  type_url_check(data, ftp);
4676
4677
  /* get some initial data into the ftp struct */
4678
0
  ftp->transfer = PPTRANSFER_BODY;
4679
0
  ftp->downloadsize = 0;
4680
4681
0
  CURL_TRC_FTP(data, "setup connection -> %d", (int)result);
4682
0
  return result;
4683
0
}
4684
4685
static CURLcode ftp_setup_filters(struct Curl_easy *data,
4686
                                  struct Curl_cfilter *cf_at)
4687
0
{
4688
0
  struct Curl_cfilter *cf;
4689
0
  CURLcode result = CURLE_OK;
4690
4691
0
  if(cf_at->chain->primary) {
4692
0
    result = cf_ftp_create(&cf, data);
4693
0
    if(!result)
4694
0
      Curl_conn_cf_insert_after(cf_at, cf);
4695
0
  }
4696
0
  return result;
4697
0
}
4698
4699
bool Curl_ftp_conn_matches(struct Curl_easy *data,
4700
                           struct connectdata *conn)
4701
0
{
4702
0
  struct Curl_cfilter *cf;
4703
0
  struct cf_ftp_ctx *cftpc;
4704
4705
0
  if(!(data->state.origin->scheme->family & PROTO_FAMILY_FTP))
4706
0
    return FALSE;
4707
4708
0
  cf = Curl_conn_get_first_cf(conn, &Curl_cft_ftp);
4709
0
  if(!cf || !cf->ctx)
4710
0
    return FALSE;
4711
0
  cftpc = cf->ctx;
4712
4713
  /* match ACCOUNT, ALTERNATIVE-TO-USER and CCC options */
4714
0
  if((data->set.ftp_ccc != cftpc->ccc) ||
4715
0
     Curl_timestrcmp(CURL_EASY_STR(data, STRING_FTP_ACCOUNT),
4716
0
                     cftpc->account) ||
4717
0
     Curl_timestrcmp(CURL_EASY_STR(data, STRING_FTP_ALTERNATIVE_TO_USER),
4718
0
                     cftpc->alternative_to_user))
4719
0
    return FALSE;
4720
4721
0
  switch(data->set.use_ssl) {
4722
0
  case CURLUSESSL_TRY:
4723
    /* A transfer that only "tries" SSL, is compatible with a connection
4724
     * of similar or stricter SSL use setting. */
4725
0
    return (cftpc->use_ssl != CURLUSESSL_NONE);
4726
0
  default:
4727
0
    return (data->set.use_ssl == cftpc->use_ssl);
4728
0
  }
4729
0
}
4730
4731
static CURLcode ftp_pollset(struct Curl_easy *data,
4732
                            struct easy_pollset *ps)
4733
0
{
4734
  /* We just add out control connection socket for input to get
4735
   * things started. The filters "adjust_pollset()" callback will
4736
   * then adjust it to current needs.
4737
   *
4738
   * NOTE: we need this kick-staring as our "send index" is SECONDARYSOCKET
4739
   * and that as no valid socket until the DATA connection is established.
4740
   * Without this function, we get errors about that or an empty pollset
4741
   * which does not work at all.
4742
   */
4743
0
  return Curl_pollset_add_in(data, ps, data->conn->chain.sock);
4744
0
}
4745
4746
/*
4747
 * FTP protocol.
4748
 */
4749
const struct Curl_protocol Curl_protocol_ftp = {
4750
  ftp_setup_connection,            /* setup_connection */
4751
  ftp_setup_filters,               /* setup_filters */
4752
  ftp_do,                          /* do_it */
4753
  ftp_done,                        /* done */
4754
  ftp_do_more,                     /* do_more */
4755
  ZERO_NULL,                       /* connect_it */
4756
  ftp_multi_statemach,             /* connecting */
4757
  ftp_doing,                       /* doing */
4758
  ftp_pollset,                     /* proto_pollset */
4759
  ftp_pollset,                     /* doing_pollset */
4760
  ftp_pollset,                     /* domore_pollset */
4761
  ZERO_NULL,                       /* perform_pollset */
4762
  ZERO_NULL,                       /* disconnect */
4763
  ZERO_NULL,                       /* write_resp */
4764
  ZERO_NULL,                       /* write_resp_hd */
4765
  ZERO_NULL,                       /* connection_is_dead */
4766
  ZERO_NULL,                       /* attach connection */
4767
  ZERO_NULL,                       /* follow */
4768
};
4769
4770
#endif /* CURL_DISABLE_FTP */