Coverage Report

Created: 2026-10-31 06:46

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