summaryrefslogtreecommitdiff
path: root/src/FtpNegotiationCommand.cc
blob: af0f80e110b696bf67c318cc93d0fb671d553e36 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
/* <!-- copyright */
/*
 * aria2 - The high speed download utility
 *
 * Copyright (C) 2006 Tatsuhiro Tsujikawa
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations
 * including the two.
 * You must obey the GNU General Public License in all respects
 * for all of the code used other than OpenSSL.  If you modify
 * file(s) with this exception, you may extend this exception to your
 * version of the file(s), but you are not obligated to do so.  If you
 * do not wish to do so, delete this exception statement from your
 * version.  If you delete this exception statement from all source
 * files in the program, then also delete it here.
 */
/* copyright --> */
#include "FtpNegotiationCommand.h"

#include <stdint.h>
#include <cassert>
#include <utility>
#include <map>

#include "Request.h"
#include "DownloadEngine.h"
#include "FtpConnection.h"
#include "RequestGroup.h"
#include "PieceStorage.h"
#include "FtpDownloadCommand.h"
#include "FileEntry.h"
#include "DlAbortEx.h"
#include "message.h"
#include "prefs.h"
#include "util.h"
#include "Option.h"
#include "Logger.h"
#include "LogFactory.h"
#include "Segment.h"
#include "DownloadContext.h"
#include "DefaultBtProgressInfoFile.h"
#include "RequestGroupMan.h"
#include "DownloadFailureException.h"
#include "SocketCore.h"
#include "fmt.h"
#include "DiskAdaptor.h"
#include "SegmentMan.h"
#include "AuthConfigFactory.h"
#include "AuthConfig.h"
#include "a2functional.h"
#include "URISelector.h"
#include "HttpConnection.h"
#include "HttpHeader.h"
#include "HttpRequest.h"
#include "HttpResponse.h"
#include "DlRetryEx.h"
#include "CheckIntegrityEntry.h"
#include "error_code.h"
#include "SocketRecvBuffer.h"
#ifdef ENABLE_MESSAGE_DIGEST
# include "ChecksumCheckIntegrityEntry.h"
#endif // ENABLE_MESSAGE_DIGEST

namespace aria2 {

FtpNegotiationCommand::FtpNegotiationCommand
(cuid_t cuid,
 const std::shared_ptr<Request>& req,
 const std::shared_ptr<FileEntry>& fileEntry,
 RequestGroup* requestGroup,
 DownloadEngine* e,
 const std::shared_ptr<SocketCore>& socket,
 Seq seq,
 const std::string& baseWorkingDir):
  AbstractCommand(cuid, req, fileEntry, requestGroup, e, socket),
  sequence_(seq),
  ftp_(new FtpConnection(cuid, socket, req,
                        e->getAuthConfigFactory()->createAuthConfig
                        (req, requestGroup->getOption().get()),
                         getOption().get())),
  pasvPort_(0)
{
  ftp_->setBaseWorkingDir(baseWorkingDir);
  if(seq == SEQ_RECV_GREETING) {
    setTimeout(getOption()->getAsInt(PREF_CONNECT_TIMEOUT));
  }
}

FtpNegotiationCommand::~FtpNegotiationCommand() {}

bool FtpNegotiationCommand::executeInternal() {
  while(processSequence(getSegments().front()));
  if(sequence_ == SEQ_RETRY) {
    return prepareForRetry(0);
  } else if(sequence_ == SEQ_NEGOTIATION_COMPLETED) {
    auto command = make_unique<FtpDownloadCommand>
      (getCuid(), getRequest(), getFileEntry(), getRequestGroup(), ftp_,
       getDownloadEngine(), dataSocket_, getSocket());
    command->setStartupIdleTime(getOption()->getAsInt(PREF_STARTUP_IDLE_TIME));
    command->setLowestDownloadSpeedLimit
      (getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT));
    if(getFileEntry()->isUniqueProtocol()) {
      getFileEntry()->removeURIWhoseHostnameIs(getRequest()->getHost());
    }
    getRequestGroup()->getURISelector()->tuneDownloadCommand
      (getFileEntry()->getRemainingUris(), command.get());
    getDownloadEngine()->addCommand(std::move(command));
    return true;
  } else if(sequence_ == SEQ_HEAD_OK ||
            sequence_ == SEQ_DOWNLOAD_ALREADY_COMPLETED) {
    return true;
  } else if(sequence_ == SEQ_FILE_PREPARATION) {
    if(getOption()->getAsBool(PREF_FTP_PASV)) {
      sequence_ = SEQ_PREPARE_PASV;
    } else {
      sequence_ = SEQ_PREPARE_PORT;
    }
    return false;
  } else if(sequence_ == SEQ_EXIT) {
    return true;
  } else {
    addCommandSelf();
    return false;
  }
}

bool FtpNegotiationCommand::recvGreeting() {
  setTimeout(getRequestGroup()->getTimeout());
  //socket->setBlockingMode();
  disableWriteCheckSocket();
  setReadCheckSocket(getSocket());

  int status = ftp_->receiveResponse();
  if(status == 0) {
    return false;
  }
  if(status != 220) {
    throw DL_ABORT_EX2(EX_CONNECTION_FAILED, error_code::FTP_PROTOCOL_ERROR);
  }
  sequence_ = SEQ_SEND_USER;

  return true;
}

bool FtpNegotiationCommand::sendUser() {
  if(ftp_->sendUser()) {
    disableWriteCheckSocket();
    sequence_ = SEQ_RECV_USER;
  } else {
    setWriteCheckSocket(getSocket());
  }
  return false;
}

bool FtpNegotiationCommand::recvUser() {
  int status = ftp_->receiveResponse();
  switch(status) {
  case 0:
    return false;
  case 230:
    sequence_ = SEQ_SEND_TYPE;
    break;
  case 331:
    sequence_ = SEQ_SEND_PASS;
    break;
  default:
    throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
                       error_code::FTP_PROTOCOL_ERROR);
  }
  return true;
}

bool FtpNegotiationCommand::sendPass() {
  if(ftp_->sendPass()) {
    disableWriteCheckSocket();
    sequence_ = SEQ_RECV_PASS;
  } else {
    setWriteCheckSocket(getSocket());
  }
  return false;
}

bool FtpNegotiationCommand::recvPass() {
  int status = ftp_->receiveResponse();
  if(status == 0) {
    return false;
  }
  if(status != 230) {
    throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
                       error_code::FTP_PROTOCOL_ERROR);
  }
  sequence_ = SEQ_SEND_TYPE;
  return true;
}

bool FtpNegotiationCommand::sendType() {
  if(ftp_->sendType()) {
    disableWriteCheckSocket();
    sequence_ = SEQ_RECV_TYPE;
  } else {
    setWriteCheckSocket(getSocket());
  }
  return false;
}

bool FtpNegotiationCommand::recvType() {
  int status = ftp_->receiveResponse();
  if(status == 0) {
    return false;
  }
  if(status != 200) {
    throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
                       error_code::FTP_PROTOCOL_ERROR);
  }
  sequence_ = SEQ_SEND_PWD;
  return true;
}

bool FtpNegotiationCommand::sendPwd()
{
  if(ftp_->sendPwd()) {
    disableWriteCheckSocket();
    sequence_ = SEQ_RECV_PWD;
  } else {
    setWriteCheckSocket(getSocket());
  }
  return false;
}

bool FtpNegotiationCommand::recvPwd()
{
  std::string pwd;
  int status = ftp_->receivePwdResponse(pwd);
  if(status == 0) {
    return false;
  }
  if(status != 257) {
    throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
                       error_code::FTP_PROTOCOL_ERROR);
  }
  ftp_->setBaseWorkingDir(pwd);
  A2_LOG_INFO(fmt("CUID#%" PRId64 " - base working directory is '%s'",
                  getCuid(), pwd.c_str()));
  sequence_ = SEQ_SEND_CWD_PREP;
  return true;
}

bool FtpNegotiationCommand::sendCwdPrep()
{
  // Calling setReadCheckSocket() is needed when the socket is reused,
  setReadCheckSocket(getSocket());
  cwdDirs_.push_front(ftp_->getBaseWorkingDir());
  util::split(getRequest()->getDir().begin(), getRequest()->getDir().end(),
              std::back_inserter(cwdDirs_), '/');
  sequence_ = SEQ_SEND_CWD;
  return true;
}

bool FtpNegotiationCommand::sendCwd()
{
  if(ftp_->sendCwd(cwdDirs_.front())) {
    disableWriteCheckSocket();
    sequence_ = SEQ_RECV_CWD;
  } else {
    setWriteCheckSocket(getSocket());
  }
  return false;
}

bool FtpNegotiationCommand::recvCwd()
{
  int status = ftp_->receiveResponse();
  if(status == 0) {
    return false;
  }
  if(status != 250) {
    poolConnection();
    getRequestGroup()->increaseAndValidateFileNotFoundCount();
    if (status == 550)
      throw DL_ABORT_EX2(MSG_RESOURCE_NOT_FOUND,
                         error_code::RESOURCE_NOT_FOUND);
    else
      throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
                         error_code::FTP_PROTOCOL_ERROR);
  }
  cwdDirs_.pop_front();
  if(cwdDirs_.empty()) {
    if(getOption()->getAsBool(PREF_REMOTE_TIME)) {
      sequence_ = SEQ_SEND_MDTM;
    } else {
      sequence_ = SEQ_SEND_SIZE;
    }
  } else {
    sequence_ = SEQ_SEND_CWD;
  }
  return true;
}

bool FtpNegotiationCommand::sendMdtm()
{
  if(ftp_->sendMdtm()) {
    disableWriteCheckSocket();
    sequence_ = SEQ_RECV_MDTM;
  } else {
    setWriteCheckSocket(getSocket());
  }
  return false;
}

bool FtpNegotiationCommand::recvMdtm()
{
  Time lastModifiedTime = Time::null();
  int status = ftp_->receiveMdtmResponse(lastModifiedTime);
  if(status == 0) {
    return false;
  }
  if(status == 213) {
    if(lastModifiedTime.good()) {
      getRequestGroup()->updateLastModifiedTime(lastModifiedTime);
      A2_LOG_DEBUG(fmt("MDTM result was parsed as: %s",
                       lastModifiedTime.toHTTPDate().c_str()));
    } else {
      A2_LOG_DEBUG("MDTM response was returned, but it seems not to be"
                   " a time value as in specified in RFC3659.");
    }
  } else {
    A2_LOG_INFO(fmt("CUID#%" PRId64 " - MDTM command failed.",
                    getCuid()));
  }
  sequence_ = SEQ_SEND_SIZE;
  return true;
}

bool FtpNegotiationCommand::sendSize() {
  if(ftp_->sendSize()) {
    disableWriteCheckSocket();
    sequence_ = SEQ_RECV_SIZE;
  } else {
    setWriteCheckSocket(getSocket());
  }
  return false;
}

bool FtpNegotiationCommand::onFileSizeDetermined(int64_t totalLength)
{
  getFileEntry()->setLength(totalLength);
  if(getFileEntry()->getPath().empty()) {
    getFileEntry()->setPath
      (util::createSafePath
       (getOption()->get(PREF_DIR),
        util::percentDecode(getRequest()->getFile().begin(),
                            getRequest()->getFile().end())));
  }
  getRequestGroup()->preDownloadProcessing();
  if(getDownloadEngine()->getRequestGroupMan()->
     isSameFileBeingDownloaded(getRequestGroup())) {
    throw DOWNLOAD_FAILURE_EXCEPTION2
      (fmt(EX_DUPLICATE_FILE_DOWNLOAD,
           getRequestGroup()->getFirstFilePath().c_str()),
       error_code::DUPLICATE_DOWNLOAD);
  }
  if(totalLength == 0) {

    if(getOption()->getAsBool(PREF_FTP_PASV)) {
      sequence_ = SEQ_PREPARE_PASV;
    } else {
      sequence_ = SEQ_PREPARE_PORT;
    }

    if(getOption()->getAsBool(PREF_DRY_RUN)) {
      getRequestGroup()->initPieceStorage();
      onDryRunFileFound();
      return false;
    }

    if(getDownloadContext()->knowsTotalLength() &&
       getRequestGroup()->downloadFinishedByFileLength()) {
#ifdef ENABLE_MESSAGE_DIGEST
      // TODO Known issue: if .aria2 file exists, it will not be
      // deleted on successful verification, because .aria2 file is
      // not loaded.  See also
      // HttpResponseCommand::handleOtherEncoding()
      getRequestGroup()->initPieceStorage();
      if(getDownloadContext()->isChecksumVerificationNeeded()) {
        A2_LOG_DEBUG("Zero length file exists. Verify checksum.");
        std::shared_ptr<ChecksumCheckIntegrityEntry> entry
          (new ChecksumCheckIntegrityEntry(getRequestGroup()));
        entry->initValidator();
        getPieceStorage()->getDiskAdaptor()->openExistingFile();
        getDownloadEngine()->getCheckIntegrityMan()->pushEntry(entry);
        sequence_ = SEQ_EXIT;
      } else
#endif // ENABLE_MESSAGE_DIGEST
        {
          getPieceStorage()->markAllPiecesDone();
          getDownloadContext()->setChecksumVerified(true);
          sequence_ = SEQ_DOWNLOAD_ALREADY_COMPLETED;
          A2_LOG_NOTICE
            (fmt(MSG_DOWNLOAD_ALREADY_COMPLETED,
                 GroupId::toHex(getRequestGroup()->getGID()).c_str(),
                 getRequestGroup()->getFirstFilePath().c_str()));
        }
      poolConnection();
      return false;
    }

    getRequestGroup()->shouldCancelDownloadForSafety();
    getRequestGroup()->initPieceStorage();
    getPieceStorage()->getDiskAdaptor()->initAndOpenFile();

    if(getDownloadContext()->knowsTotalLength()) {
      A2_LOG_DEBUG("File length becomes zero and it means download completed.");
#ifdef ENABLE_MESSAGE_DIGEST
      // TODO Known issue: if .aria2 file exists, it will not be
      // deleted on successful verification, because .aria2 file is
      // not loaded.  See also
      // HttpResponseCommand::handleOtherEncoding()
      if(getDownloadContext()->isChecksumVerificationNeeded()) {
        A2_LOG_DEBUG("Verify checksum for zero-length file");
        std::shared_ptr<ChecksumCheckIntegrityEntry> entry
          (new ChecksumCheckIntegrityEntry(getRequestGroup()));
        entry->initValidator();
        getDownloadEngine()->getCheckIntegrityMan()->pushEntry(entry);
        sequence_ = SEQ_EXIT;
      } else
#endif // ENABLE_MESSAGE_DIGEST
        {
          sequence_ = SEQ_DOWNLOAD_ALREADY_COMPLETED;
          getPieceStorage()->markAllPiecesDone();
        }
      poolConnection();
      return false;
    }
    // We have to make sure that command that has Request object must
    // have segment after PieceStorage is initialized. See
    // AbstractCommand::execute()
    getSegmentMan()->getSegmentWithIndex(getCuid(), 0);
    return true;
  } else {
    std::shared_ptr<BtProgressInfoFile> progressInfoFile
      (new DefaultBtProgressInfoFile
       (getDownloadContext(), std::shared_ptr<PieceStorage>(), getOption().get()));
    getRequestGroup()->adjustFilename(progressInfoFile);
    getRequestGroup()->initPieceStorage();

    if(getOption()->getAsBool(PREF_DRY_RUN)) {
      onDryRunFileFound();
      return false;
    }

    std::shared_ptr<CheckIntegrityEntry> checkIntegrityEntry =
      getRequestGroup()->createCheckIntegrityEntry();
    if(!checkIntegrityEntry) {
      sequence_ = SEQ_DOWNLOAD_ALREADY_COMPLETED;
      poolConnection();
      return false;
    }
    checkIntegrityEntry->pushNextCommand(std::unique_ptr<Command>(this));
    // We have to make sure that command that has Request object must
    // have segment after PieceStorage is initialized. See
    // AbstractCommand::execute()
    getSegmentMan()->getSegmentWithIndex(getCuid(), 0);

    prepareForNextAction(checkIntegrityEntry);

    disableReadCheckSocket();
  }
  return false;
}

bool FtpNegotiationCommand::recvSize() {
  int64_t size = 0;
  int status = ftp_->receiveSizeResponse(size);
  if(status == 0) {
    return false;
  }
  if(status == 213) {
    if(size > std::numeric_limits<a2_off_t>::max()) {
      throw DL_ABORT_EX2(fmt(EX_TOO_LARGE_FILE, size),
                         error_code::FTP_PROTOCOL_ERROR);
    }
    if(!getPieceStorage()) {

      sequence_ = SEQ_FILE_PREPARATION;
      return onFileSizeDetermined(size);

    } else {
      getRequestGroup()->validateTotalLength(getFileEntry()->getLength(), size);
    }

  } else {
    A2_LOG_INFO(fmt("CUID#%" PRId64 " - The remote FTP Server doesn't recognize SIZE"
                    " command. Continue.", getCuid()));
    // Even if one of the other servers waiting in the queue supports SIZE
    // command, resuming and segmented downloading are disabled when the first
    // contacted FTP server doesn't support it.
    if(!getPieceStorage()) {
      getDownloadContext()->markTotalLengthIsUnknown();
      return onFileSizeDetermined(0);

    }
    // TODO Skipping RequestGroup::validateTotalLength(0) here will allow
    // wrong file to be downloaded if user-specified URL is wrong.
  }
  if(getOption()->getAsBool(PREF_FTP_PASV)) {
    sequence_ = SEQ_PREPARE_PASV;
  } else {
    sequence_ = SEQ_PREPARE_PORT;
  }
  return true;
}

void FtpNegotiationCommand::afterFileAllocation()
{
  setReadCheckSocket(getSocket());
}

bool FtpNegotiationCommand::preparePort() {
  afterFileAllocation();
  if(getSocket()->getAddressFamily() == AF_INET6) {
    sequence_ = SEQ_PREPARE_SERVER_SOCKET_EPRT;
  } else {
    sequence_ = SEQ_PREPARE_SERVER_SOCKET;
  }
  return true;
}

bool FtpNegotiationCommand::prepareServerSocketEprt() {
  serverSocket_ = ftp_->createServerSocket();
  sequence_ = SEQ_SEND_EPRT;
  return true;
}

bool FtpNegotiationCommand::prepareServerSocket()
{
  serverSocket_ = ftp_->createServerSocket();
  sequence_ = SEQ_SEND_PORT;
  return true;
}

bool FtpNegotiationCommand::sendEprt() {
  if(ftp_->sendEprt(serverSocket_)) {
    disableWriteCheckSocket();
    sequence_ = SEQ_RECV_EPRT;
  } else {
    setWriteCheckSocket(getSocket());
  }
  return false;
}

bool FtpNegotiationCommand::recvEprt() {
  int status = ftp_->receiveResponse();
  if(status == 0) {
    return false;
  }
  if(status == 200) {
    sequence_ = SEQ_SEND_REST;
  } else {
    sequence_ = SEQ_PREPARE_SERVER_SOCKET;
  }
  return true;
}

bool FtpNegotiationCommand::sendPort() {
  if(ftp_->sendPort(serverSocket_)) {
    disableWriteCheckSocket();
    sequence_ = SEQ_RECV_PORT;
  } else {
    setWriteCheckSocket(getSocket());
  }
  return false;
}

bool FtpNegotiationCommand::recvPort() {
  int status = ftp_->receiveResponse();
  if(status == 0) {
    return false;
  }
  if(status != 200) {
    throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
                       error_code::FTP_PROTOCOL_ERROR);
  }
  sequence_ = SEQ_SEND_REST;
  return true;
}

bool FtpNegotiationCommand::preparePasv() {
  afterFileAllocation();
  if(getSocket()->getAddressFamily() == AF_INET6) {
    sequence_ = SEQ_SEND_EPSV;
  } else {
    sequence_ = SEQ_SEND_PASV;
  }
  return true;
}

bool FtpNegotiationCommand::sendEpsv() {
  if(ftp_->sendEpsv()) {
    disableWriteCheckSocket();
    sequence_ = SEQ_RECV_EPSV;
  } else {
    setWriteCheckSocket(getSocket());
  }
  return true;
}

bool FtpNegotiationCommand::recvEpsv() {
  uint16_t port;
  int status = ftp_->receiveEpsvResponse(port);
  if(status == 0) {
    return false;
  }
  if(status == 229) {
    pasvPort_ = port;
    return preparePasvConnect();
  } else {
    sequence_ = SEQ_SEND_PASV;
    return true;
  }
}

bool FtpNegotiationCommand::sendPasv() {
  if(ftp_->sendPasv()) {
    disableWriteCheckSocket();
    sequence_ = SEQ_RECV_PASV;
  } else {
    setWriteCheckSocket(getSocket());
  }
  return false;
}

bool FtpNegotiationCommand::recvPasv() {
  std::pair<std::string, uint16_t> dest;
  int status = ftp_->receivePasvResponse(dest);
  if(status == 0) {
    return false;
  }
  if(status != 227) {
    throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
                       error_code::FTP_PROTOCOL_ERROR);
  }
  pasvPort_ = dest.second;;
  return preparePasvConnect();
}

bool FtpNegotiationCommand::preparePasvConnect() {
  if(isProxyDefined()) {
    sequence_ = SEQ_RESOLVE_PROXY;
    return true;
  } else {
    std::pair<std::string, uint16_t> dataAddr;
    getSocket()->getPeerInfo(dataAddr);
    // make a data connection to the server.
    A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER,
                    getCuid(),
                    dataAddr.first.c_str(),
                    pasvPort_));
    dataSocket_.reset(new SocketCore());
    dataSocket_->establishConnection(dataAddr.first, pasvPort_, false);
    disableReadCheckSocket();
    setWriteCheckSocket(dataSocket_);
    sequence_ = SEQ_SEND_REST_PASV;
    return false;
  }
}

bool FtpNegotiationCommand::resolveProxy()
{
  std::shared_ptr<Request> proxyReq = createProxyRequest();
  std::vector<std::string> addrs;
  proxyAddr_ = resolveHostname
    (addrs, proxyReq->getHost(), proxyReq->getPort());
  if(proxyAddr_.empty()) {
    return false;
  }
  A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER,
                  getCuid(),
                  proxyAddr_.c_str(), proxyReq->getPort()));
  dataSocket_.reset(new SocketCore());
  dataSocket_->establishConnection(proxyAddr_, proxyReq->getPort());
  disableReadCheckSocket();
  setWriteCheckSocket(dataSocket_);
  std::shared_ptr<SocketRecvBuffer> socketRecvBuffer
    (new SocketRecvBuffer(dataSocket_));
  http_.reset(new HttpConnection(getCuid(), dataSocket_, socketRecvBuffer));
  sequence_ = SEQ_SEND_TUNNEL_REQUEST;
  return false;
}

bool FtpNegotiationCommand::sendTunnelRequest()
{
  if(http_->sendBufferIsEmpty()) {
    if(dataSocket_->isReadable(0)) {
      std::string error = getSocket()->getSocketError();
      if(!error.empty()) {
        std::shared_ptr<Request> proxyReq = createProxyRequest();
        getDownloadEngine()->markBadIPAddress(proxyReq->getHost(),
                                              proxyAddr_,proxyReq->getPort());
        std::string nextProxyAddr = getDownloadEngine()->findCachedIPAddress
          (proxyReq->getHost(), proxyReq->getPort());
        if(nextProxyAddr.empty()) {
          getDownloadEngine()->removeCachedIPAddress(proxyReq->getHost(),
                                                     proxyReq->getPort());
          throw DL_RETRY_EX
            (fmt(MSG_ESTABLISHING_CONNECTION_FAILED,
                 error.c_str()));
        } else {
          A2_LOG_INFO(fmt(MSG_CONNECT_FAILED_AND_RETRY,
                          getCuid(),
                          proxyAddr_.c_str(), proxyReq->getPort()));
          proxyAddr_ = nextProxyAddr;
          A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER,
                          getCuid(),
                          proxyAddr_.c_str(), proxyReq->getPort()));
          dataSocket_->establishConnection(proxyAddr_, proxyReq->getPort());
          return false;
        }
      }
    }
    std::shared_ptr<HttpRequest> httpRequest(new HttpRequest());
    httpRequest->setUserAgent(getOption()->get(PREF_USER_AGENT));
    std::shared_ptr<Request> req(new Request());
    // Construct fake URI in order to use HttpRequest
    std::pair<std::string, uint16_t> dataAddr;
    uri::UriStruct us;
    us.protocol = "ftp";
    us.host = getRequest()->getHost();
    us.port = pasvPort_;
    us.ipv6LiteralAddress = getRequest()->isIPv6LiteralAddress();
    if(!req->setUri(uri::construct(us))) {
      throw DL_RETRY_EX("Something wrong with FTP URI");
    }
    httpRequest->setRequest(req);
    httpRequest->setProxyRequest(createProxyRequest());
    http_->sendProxyRequest(httpRequest);
  } else {
    http_->sendPendingData();
  }
  if(http_->sendBufferIsEmpty()) {
    disableWriteCheckSocket();
    setReadCheckSocket(dataSocket_);
    sequence_ = SEQ_RECV_TUNNEL_RESPONSE;
    return false;
  } else {
    setWriteCheckSocket(dataSocket_);
    return false;
  }
}

bool FtpNegotiationCommand::recvTunnelResponse()
{
  std::shared_ptr<HttpResponse> httpResponse = http_->receiveResponse();
  if(!httpResponse) {
    return false;
  }
  if(httpResponse->getStatusCode() != 200) {
    throw DL_RETRY_EX(EX_PROXY_CONNECTION_FAILED);
  }
  sequence_ = SEQ_SEND_REST_PASV;
  return true;
}

bool FtpNegotiationCommand::sendRestPasv(const std::shared_ptr<Segment>& segment) {
  //dataSocket_->setBlockingMode();
  // Check connection is made properly
  if(dataSocket_->isReadable(0)) {
    std::string error = dataSocket_->getSocketError();
    throw DL_ABORT_EX2
      (fmt(MSG_ESTABLISHING_CONNECTION_FAILED, error.c_str()),
       error_code::FTP_PROTOCOL_ERROR);
  }
  setReadCheckSocket(getSocket());
  disableWriteCheckSocket();
  return sendRest(segment);
}

bool FtpNegotiationCommand::sendRest(const std::shared_ptr<Segment>& segment) {
  if(ftp_->sendRest(segment)) {
    disableWriteCheckSocket();
    sequence_ = SEQ_RECV_REST;
  } else {
    setWriteCheckSocket(getSocket());
  }
  return false;
}

bool FtpNegotiationCommand::recvRest(const std::shared_ptr<Segment>& segment) {
  int status = ftp_->receiveResponse();
  if(status == 0) {
    return false;
  }
  // If we recieve negative response and requested file position is not 0,
  // then throw exception here.
  if(status != 350) {
    if(segment && segment->getPositionToWrite() != 0) {
      throw DL_ABORT_EX2("FTP server doesn't support resuming.",
                         error_code::CANNOT_RESUME);
    }
  }
  sequence_ = SEQ_SEND_RETR;
  return true;
}

bool FtpNegotiationCommand::sendRetr() {
  if(ftp_->sendRetr()) {
    disableWriteCheckSocket();
    sequence_ = SEQ_RECV_RETR;
  } else {
    setWriteCheckSocket(getSocket());
  }
  return false;
}

bool FtpNegotiationCommand::recvRetr() {
  int status = ftp_->receiveResponse();
  if(status == 0) {
    return false;
  }
  if(status != 150 && status != 125) {
    getRequestGroup()->increaseAndValidateFileNotFoundCount();
    if (status == 550)
      throw DL_ABORT_EX2(MSG_RESOURCE_NOT_FOUND,
                         error_code::RESOURCE_NOT_FOUND);
    else
      throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
                         error_code::FTP_PROTOCOL_ERROR);
  }
  if(getOption()->getAsBool(PREF_FTP_PASV)) {
    sequence_ = SEQ_NEGOTIATION_COMPLETED;
    return false;
  } else {
    disableReadCheckSocket();
    setReadCheckSocket(serverSocket_);
    sequence_ = SEQ_WAIT_CONNECTION;
    return false;
  }
}

bool FtpNegotiationCommand::waitConnection()
{
  disableReadCheckSocket();
  setReadCheckSocket(getSocket());
  dataSocket_ = serverSocket_->acceptConnection();
  sequence_ = SEQ_NEGOTIATION_COMPLETED;
  return false;
}

bool FtpNegotiationCommand::processSequence
(const std::shared_ptr<Segment>& segment) {
  bool doNextSequence = true;
  switch(sequence_) {
  case SEQ_RECV_GREETING:
    return recvGreeting();
  case SEQ_SEND_USER:
    return sendUser();
  case SEQ_RECV_USER:
    return recvUser();
  case SEQ_SEND_PASS:
    return sendPass();
  case SEQ_RECV_PASS:
    return recvPass();
  case SEQ_SEND_TYPE:
    return sendType();
  case SEQ_RECV_TYPE:
    return recvType();
  case SEQ_SEND_PWD:
    return sendPwd();
  case SEQ_RECV_PWD:
    return recvPwd();
  case SEQ_SEND_CWD_PREP:
    return sendCwdPrep();
  case SEQ_SEND_CWD:
    return sendCwd();
  case SEQ_RECV_CWD:
    return recvCwd();
  case SEQ_SEND_MDTM:
    return sendMdtm();
  case SEQ_RECV_MDTM:
    return recvMdtm();
  case SEQ_SEND_SIZE:
    return sendSize();
  case SEQ_RECV_SIZE:
    return recvSize();
  case SEQ_PREPARE_PORT:
    return preparePort();
  case SEQ_PREPARE_SERVER_SOCKET_EPRT:
    return prepareServerSocketEprt();
  case SEQ_SEND_EPRT:
    return sendEprt();
  case SEQ_RECV_EPRT:
    return recvEprt();
  case SEQ_PREPARE_SERVER_SOCKET:
    return prepareServerSocket();
  case SEQ_SEND_PORT:
    return sendPort();
  case SEQ_RECV_PORT:
    return recvPort();
  case SEQ_PREPARE_PASV:
    return preparePasv();
  case SEQ_SEND_EPSV:
    return sendEpsv();
  case SEQ_RECV_EPSV:
    return recvEpsv();
  case SEQ_SEND_PASV:
    return sendPasv();
  case SEQ_RECV_PASV:
    return recvPasv();
  case SEQ_RESOLVE_PROXY:
    return resolveProxy();
  case SEQ_SEND_TUNNEL_REQUEST:
    return sendTunnelRequest();
  case SEQ_RECV_TUNNEL_RESPONSE:
    return recvTunnelResponse();
  case SEQ_SEND_REST_PASV:
    return sendRestPasv(segment);
  case SEQ_SEND_REST:
    return sendRest(segment);
  case SEQ_RECV_REST:
    return recvRest(segment);
  case SEQ_SEND_RETR:
    return sendRetr();
  case SEQ_RECV_RETR:
    return recvRetr();
  case SEQ_WAIT_CONNECTION:
    return waitConnection();
  default:
    abort();
  }
  return doNextSequence;
}

void FtpNegotiationCommand::poolConnection() const
{
  if(getOption()->getAsBool(PREF_FTP_REUSE_CONNECTION)) {
    // Store ftp_->getBaseWorkingDir() as options
    getDownloadEngine()->poolSocket(getRequest(), ftp_->getUser(),
                                    createProxyRequest(), getSocket(),
                                    ftp_->getBaseWorkingDir());
  }
}

void FtpNegotiationCommand::onDryRunFileFound()
{
  getPieceStorage()->markAllPiecesDone();
  getDownloadContext()->setChecksumVerified(true);
  poolConnection();
  sequence_ = SEQ_HEAD_OK;
}

} // namespace aria2