Coverage Report

Created: 2025-11-09 06:51

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