FtpNegotiationCommand.cc 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "FtpNegotiationCommand.h"
  36. #include <stdint.h>
  37. #include <cassert>
  38. #include <utility>
  39. #include <map>
  40. #include "Request.h"
  41. #include "DownloadEngine.h"
  42. #include "FtpConnection.h"
  43. #include "RequestGroup.h"
  44. #include "PieceStorage.h"
  45. #include "FtpDownloadCommand.h"
  46. #include "FileEntry.h"
  47. #include "DlAbortEx.h"
  48. #include "message.h"
  49. #include "prefs.h"
  50. #include "util.h"
  51. #include "Option.h"
  52. #include "Logger.h"
  53. #include "LogFactory.h"
  54. #include "Segment.h"
  55. #include "DownloadContext.h"
  56. #include "DefaultBtProgressInfoFile.h"
  57. #include "RequestGroupMan.h"
  58. #include "DownloadFailureException.h"
  59. #include "Socket.h"
  60. #include "fmt.h"
  61. #include "DiskAdaptor.h"
  62. #include "SegmentMan.h"
  63. #include "AuthConfigFactory.h"
  64. #include "AuthConfig.h"
  65. #include "a2functional.h"
  66. #include "URISelector.h"
  67. #include "HttpConnection.h"
  68. #include "HttpHeader.h"
  69. #include "HttpRequest.h"
  70. #include "HttpResponse.h"
  71. #include "DlRetryEx.h"
  72. #include "CheckIntegrityEntry.h"
  73. #include "error_code.h"
  74. #include "SocketRecvBuffer.h"
  75. #ifdef ENABLE_MESSAGE_DIGEST
  76. # include "ChecksumCheckIntegrityEntry.h"
  77. #endif // ENABLE_MESSAGE_DIGEST
  78. namespace aria2 {
  79. FtpNegotiationCommand::FtpNegotiationCommand
  80. (cuid_t cuid,
  81. const SharedHandle<Request>& req,
  82. const SharedHandle<FileEntry>& fileEntry,
  83. RequestGroup* requestGroup,
  84. DownloadEngine* e,
  85. const SocketHandle& socket,
  86. Seq seq,
  87. const std::string& baseWorkingDir):
  88. AbstractCommand(cuid, req, fileEntry, requestGroup, e, socket),
  89. sequence_(seq),
  90. ftp_(new FtpConnection(cuid, socket, req,
  91. e->getAuthConfigFactory()->createAuthConfig
  92. (req, requestGroup->getOption().get()),
  93. getOption().get())),
  94. pasvPort_(0)
  95. {
  96. ftp_->setBaseWorkingDir(baseWorkingDir);
  97. if(seq == SEQ_RECV_GREETING) {
  98. setTimeout(getOption()->getAsInt(PREF_CONNECT_TIMEOUT));
  99. }
  100. disableReadCheckSocket();
  101. setWriteCheckSocket(getSocket());
  102. }
  103. FtpNegotiationCommand::~FtpNegotiationCommand() {}
  104. bool FtpNegotiationCommand::executeInternal() {
  105. while(processSequence(getSegments().front()));
  106. if(sequence_ == SEQ_RETRY) {
  107. return prepareForRetry(0);
  108. } else if(sequence_ == SEQ_NEGOTIATION_COMPLETED) {
  109. FtpDownloadCommand* command =
  110. new FtpDownloadCommand
  111. (getCuid(), getRequest(), getFileEntry(), getRequestGroup(), ftp_,
  112. getDownloadEngine(), dataSocket_, getSocket());
  113. command->setStartupIdleTime(getOption()->getAsInt(PREF_STARTUP_IDLE_TIME));
  114. command->setLowestDownloadSpeedLimit
  115. (getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT));
  116. if(getFileEntry()->isUniqueProtocol()) {
  117. getFileEntry()->removeURIWhoseHostnameIs(getRequest()->getHost());
  118. }
  119. getRequestGroup()->getURISelector()->tuneDownloadCommand
  120. (getFileEntry()->getRemainingUris(), command);
  121. getDownloadEngine()->addCommand(command);
  122. return true;
  123. } else if(sequence_ == SEQ_HEAD_OK ||
  124. sequence_ == SEQ_DOWNLOAD_ALREADY_COMPLETED) {
  125. return true;
  126. } else if(sequence_ == SEQ_FILE_PREPARATION) {
  127. if(getOption()->getAsBool(PREF_FTP_PASV)) {
  128. sequence_ = SEQ_PREPARE_PASV;
  129. } else {
  130. sequence_ = SEQ_PREPARE_PORT;
  131. }
  132. return false;
  133. } else if(sequence_ == SEQ_EXIT) {
  134. return true;
  135. } else {
  136. getDownloadEngine()->addCommand(this);
  137. return false;
  138. }
  139. }
  140. bool FtpNegotiationCommand::recvGreeting() {
  141. if(!checkIfConnectionEstablished
  142. (getSocket(), getRequest()->getConnectedHostname(),
  143. getRequest()->getConnectedAddr(), getRequest()->getConnectedPort())) {
  144. sequence_ = SEQ_EXIT;
  145. return false;
  146. }
  147. setTimeout(getRequestGroup()->getTimeout());
  148. //socket->setBlockingMode();
  149. disableWriteCheckSocket();
  150. setReadCheckSocket(getSocket());
  151. int status = ftp_->receiveResponse();
  152. if(status == 0) {
  153. return false;
  154. }
  155. if(status != 220) {
  156. throw DL_ABORT_EX2(EX_CONNECTION_FAILED, error_code::FTP_PROTOCOL_ERROR);
  157. }
  158. sequence_ = SEQ_SEND_USER;
  159. return true;
  160. }
  161. bool FtpNegotiationCommand::sendUser() {
  162. if(ftp_->sendUser()) {
  163. disableWriteCheckSocket();
  164. sequence_ = SEQ_RECV_USER;
  165. } else {
  166. setWriteCheckSocket(getSocket());
  167. }
  168. return false;
  169. }
  170. bool FtpNegotiationCommand::recvUser() {
  171. int status = ftp_->receiveResponse();
  172. switch(status) {
  173. case 0:
  174. return false;
  175. case 230:
  176. sequence_ = SEQ_SEND_TYPE;
  177. break;
  178. case 331:
  179. sequence_ = SEQ_SEND_PASS;
  180. break;
  181. default:
  182. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
  183. error_code::FTP_PROTOCOL_ERROR);
  184. }
  185. return true;
  186. }
  187. bool FtpNegotiationCommand::sendPass() {
  188. if(ftp_->sendPass()) {
  189. disableWriteCheckSocket();
  190. sequence_ = SEQ_RECV_PASS;
  191. } else {
  192. setWriteCheckSocket(getSocket());
  193. }
  194. return false;
  195. }
  196. bool FtpNegotiationCommand::recvPass() {
  197. int status = ftp_->receiveResponse();
  198. if(status == 0) {
  199. return false;
  200. }
  201. if(status != 230) {
  202. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
  203. error_code::FTP_PROTOCOL_ERROR);
  204. }
  205. sequence_ = SEQ_SEND_TYPE;
  206. return true;
  207. }
  208. bool FtpNegotiationCommand::sendType() {
  209. if(ftp_->sendType()) {
  210. disableWriteCheckSocket();
  211. sequence_ = SEQ_RECV_TYPE;
  212. } else {
  213. setWriteCheckSocket(getSocket());
  214. }
  215. return false;
  216. }
  217. bool FtpNegotiationCommand::recvType() {
  218. int status = ftp_->receiveResponse();
  219. if(status == 0) {
  220. return false;
  221. }
  222. if(status != 200) {
  223. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
  224. error_code::FTP_PROTOCOL_ERROR);
  225. }
  226. sequence_ = SEQ_SEND_PWD;
  227. return true;
  228. }
  229. bool FtpNegotiationCommand::sendPwd()
  230. {
  231. if(ftp_->sendPwd()) {
  232. disableWriteCheckSocket();
  233. sequence_ = SEQ_RECV_PWD;
  234. } else {
  235. setWriteCheckSocket(getSocket());
  236. }
  237. return false;
  238. }
  239. bool FtpNegotiationCommand::recvPwd()
  240. {
  241. std::string pwd;
  242. int status = ftp_->receivePwdResponse(pwd);
  243. if(status == 0) {
  244. return false;
  245. }
  246. if(status != 257) {
  247. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
  248. error_code::FTP_PROTOCOL_ERROR);
  249. }
  250. ftp_->setBaseWorkingDir(pwd);
  251. A2_LOG_INFO(fmt("CUID#%" PRId64 " - base working directory is '%s'",
  252. getCuid(), pwd.c_str()));
  253. sequence_ = SEQ_SEND_CWD_PREP;
  254. return true;
  255. }
  256. bool FtpNegotiationCommand::sendCwdPrep()
  257. {
  258. // Calling setReadCheckSocket() is needed when the socket is reused,
  259. setReadCheckSocket(getSocket());
  260. cwdDirs_.push_front(ftp_->getBaseWorkingDir());
  261. util::split(getRequest()->getDir().begin(), getRequest()->getDir().end(),
  262. std::back_inserter(cwdDirs_), '/');
  263. sequence_ = SEQ_SEND_CWD;
  264. return true;
  265. }
  266. bool FtpNegotiationCommand::sendCwd()
  267. {
  268. if(ftp_->sendCwd(cwdDirs_.front())) {
  269. disableWriteCheckSocket();
  270. sequence_ = SEQ_RECV_CWD;
  271. } else {
  272. setWriteCheckSocket(getSocket());
  273. }
  274. return false;
  275. }
  276. bool FtpNegotiationCommand::recvCwd()
  277. {
  278. int status = ftp_->receiveResponse();
  279. if(status == 0) {
  280. return false;
  281. }
  282. if(status != 250) {
  283. poolConnection();
  284. getRequestGroup()->increaseAndValidateFileNotFoundCount();
  285. if (status == 550)
  286. throw DL_ABORT_EX2(MSG_RESOURCE_NOT_FOUND,
  287. error_code::RESOURCE_NOT_FOUND);
  288. else
  289. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
  290. error_code::FTP_PROTOCOL_ERROR);
  291. }
  292. cwdDirs_.pop_front();
  293. if(cwdDirs_.empty()) {
  294. if(getOption()->getAsBool(PREF_REMOTE_TIME)) {
  295. sequence_ = SEQ_SEND_MDTM;
  296. } else {
  297. sequence_ = SEQ_SEND_SIZE;
  298. }
  299. } else {
  300. sequence_ = SEQ_SEND_CWD;
  301. }
  302. return true;
  303. }
  304. bool FtpNegotiationCommand::sendMdtm()
  305. {
  306. if(ftp_->sendMdtm()) {
  307. disableWriteCheckSocket();
  308. sequence_ = SEQ_RECV_MDTM;
  309. } else {
  310. setWriteCheckSocket(getSocket());
  311. }
  312. return false;
  313. }
  314. bool FtpNegotiationCommand::recvMdtm()
  315. {
  316. Time lastModifiedTime = Time::null();
  317. int status = ftp_->receiveMdtmResponse(lastModifiedTime);
  318. if(status == 0) {
  319. return false;
  320. }
  321. if(status == 213) {
  322. if(lastModifiedTime.good()) {
  323. getRequestGroup()->updateLastModifiedTime(lastModifiedTime);
  324. A2_LOG_DEBUG(fmt("MDTM result was parsed as: %s",
  325. lastModifiedTime.toHTTPDate().c_str()));
  326. } else {
  327. A2_LOG_DEBUG("MDTM response was returned, but it seems not to be"
  328. " a time value as in specified in RFC3659.");
  329. }
  330. } else {
  331. A2_LOG_INFO(fmt("CUID#%" PRId64 " - MDTM command failed.",
  332. getCuid()));
  333. }
  334. sequence_ = SEQ_SEND_SIZE;
  335. return true;
  336. }
  337. bool FtpNegotiationCommand::sendSize() {
  338. if(ftp_->sendSize()) {
  339. disableWriteCheckSocket();
  340. sequence_ = SEQ_RECV_SIZE;
  341. } else {
  342. setWriteCheckSocket(getSocket());
  343. }
  344. return false;
  345. }
  346. bool FtpNegotiationCommand::onFileSizeDetermined(int64_t totalLength)
  347. {
  348. getFileEntry()->setLength(totalLength);
  349. if(getFileEntry()->getPath().empty()) {
  350. getFileEntry()->setPath
  351. (util::createSafePath
  352. (getOption()->get(PREF_DIR),
  353. util::percentDecode(getRequest()->getFile().begin(),
  354. getRequest()->getFile().end())));
  355. }
  356. getRequestGroup()->preDownloadProcessing();
  357. if(getDownloadEngine()->getRequestGroupMan()->
  358. isSameFileBeingDownloaded(getRequestGroup())) {
  359. throw DOWNLOAD_FAILURE_EXCEPTION2
  360. (fmt(EX_DUPLICATE_FILE_DOWNLOAD,
  361. getRequestGroup()->getFirstFilePath().c_str()),
  362. error_code::DUPLICATE_DOWNLOAD);
  363. }
  364. if(totalLength == 0) {
  365. if(getOption()->getAsBool(PREF_FTP_PASV)) {
  366. sequence_ = SEQ_PREPARE_PASV;
  367. } else {
  368. sequence_ = SEQ_PREPARE_PORT;
  369. }
  370. if(getOption()->getAsBool(PREF_DRY_RUN)) {
  371. getRequestGroup()->initPieceStorage();
  372. onDryRunFileFound();
  373. return false;
  374. }
  375. if(getDownloadContext()->knowsTotalLength() &&
  376. getRequestGroup()->downloadFinishedByFileLength()) {
  377. #ifdef ENABLE_MESSAGE_DIGEST
  378. // TODO Known issue: if .aria2 file exists, it will not be
  379. // deleted on successful verification, because .aria2 file is
  380. // not loaded. See also
  381. // HttpResponseCommand::handleOtherEncoding()
  382. getRequestGroup()->initPieceStorage();
  383. if(getDownloadContext()->isChecksumVerificationNeeded()) {
  384. A2_LOG_DEBUG("Zero length file exists. Verify checksum.");
  385. SharedHandle<ChecksumCheckIntegrityEntry> entry
  386. (new ChecksumCheckIntegrityEntry(getRequestGroup()));
  387. entry->initValidator();
  388. getPieceStorage()->getDiskAdaptor()->openExistingFile();
  389. getDownloadEngine()->getCheckIntegrityMan()->pushEntry(entry);
  390. sequence_ = SEQ_EXIT;
  391. } else
  392. #endif // ENABLE_MESSAGE_DIGEST
  393. {
  394. getPieceStorage()->markAllPiecesDone();
  395. getDownloadContext()->setChecksumVerified(true);
  396. sequence_ = SEQ_DOWNLOAD_ALREADY_COMPLETED;
  397. A2_LOG_NOTICE
  398. (fmt(MSG_DOWNLOAD_ALREADY_COMPLETED,
  399. getRequestGroup()->getGID(),
  400. getRequestGroup()->getFirstFilePath().c_str()));
  401. }
  402. poolConnection();
  403. return false;
  404. }
  405. getRequestGroup()->shouldCancelDownloadForSafety();
  406. getRequestGroup()->initPieceStorage();
  407. getPieceStorage()->getDiskAdaptor()->initAndOpenFile();
  408. if(getDownloadContext()->knowsTotalLength()) {
  409. A2_LOG_DEBUG("File length becomes zero and it means download completed.");
  410. #ifdef ENABLE_MESSAGE_DIGEST
  411. // TODO Known issue: if .aria2 file exists, it will not be
  412. // deleted on successful verification, because .aria2 file is
  413. // not loaded. See also
  414. // HttpResponseCommand::handleOtherEncoding()
  415. if(getDownloadContext()->isChecksumVerificationNeeded()) {
  416. A2_LOG_DEBUG("Verify checksum for zero-length file");
  417. SharedHandle<ChecksumCheckIntegrityEntry> entry
  418. (new ChecksumCheckIntegrityEntry(getRequestGroup()));
  419. entry->initValidator();
  420. getDownloadEngine()->getCheckIntegrityMan()->pushEntry(entry);
  421. sequence_ = SEQ_EXIT;
  422. } else
  423. #endif // ENABLE_MESSAGE_DIGEST
  424. {
  425. sequence_ = SEQ_DOWNLOAD_ALREADY_COMPLETED;
  426. getPieceStorage()->markAllPiecesDone();
  427. }
  428. poolConnection();
  429. return false;
  430. }
  431. // We have to make sure that command that has Request object must
  432. // have segment after PieceStorage is initialized. See
  433. // AbstractCommand::execute()
  434. getSegmentMan()->getSegmentWithIndex(getCuid(), 0);
  435. return true;
  436. } else {
  437. SharedHandle<BtProgressInfoFile> progressInfoFile
  438. (new DefaultBtProgressInfoFile
  439. (getDownloadContext(), SharedHandle<PieceStorage>(), getOption().get()));
  440. getRequestGroup()->adjustFilename(progressInfoFile);
  441. getRequestGroup()->initPieceStorage();
  442. if(getOption()->getAsBool(PREF_DRY_RUN)) {
  443. onDryRunFileFound();
  444. return false;
  445. }
  446. SharedHandle<CheckIntegrityEntry> checkIntegrityEntry =
  447. getRequestGroup()->createCheckIntegrityEntry();
  448. if(!checkIntegrityEntry) {
  449. sequence_ = SEQ_DOWNLOAD_ALREADY_COMPLETED;
  450. poolConnection();
  451. return false;
  452. }
  453. checkIntegrityEntry->pushNextCommand(this);
  454. // We have to make sure that command that has Request object must
  455. // have segment after PieceStorage is initialized. See
  456. // AbstractCommand::execute()
  457. getSegmentMan()->getSegmentWithIndex(getCuid(), 0);
  458. prepareForNextAction(checkIntegrityEntry);
  459. disableReadCheckSocket();
  460. }
  461. return false;
  462. }
  463. bool FtpNegotiationCommand::recvSize() {
  464. int64_t size = 0;
  465. int status = ftp_->receiveSizeResponse(size);
  466. if(status == 0) {
  467. return false;
  468. }
  469. if(status == 213) {
  470. if(size > std::numeric_limits<off_t>::max()) {
  471. throw DL_ABORT_EX2(fmt(EX_TOO_LARGE_FILE, size),
  472. error_code::FTP_PROTOCOL_ERROR);
  473. }
  474. if(!getPieceStorage()) {
  475. sequence_ = SEQ_FILE_PREPARATION;
  476. return onFileSizeDetermined(size);
  477. } else {
  478. getRequestGroup()->validateTotalLength(getFileEntry()->getLength(), size);
  479. }
  480. } else {
  481. A2_LOG_INFO(fmt("CUID#%" PRId64 " - The remote FTP Server doesn't recognize SIZE"
  482. " command. Continue.", getCuid()));
  483. // Even if one of the other servers waiting in the queue supports SIZE
  484. // command, resuming and segmented downloading are disabled when the first
  485. // contacted FTP server doesn't support it.
  486. if(!getPieceStorage()) {
  487. getDownloadContext()->markTotalLengthIsUnknown();
  488. return onFileSizeDetermined(0);
  489. }
  490. // TODO Skipping RequestGroup::validateTotalLength(0) here will allow
  491. // wrong file to be downloaded if user-specified URL is wrong.
  492. }
  493. if(getOption()->getAsBool(PREF_FTP_PASV)) {
  494. sequence_ = SEQ_PREPARE_PASV;
  495. } else {
  496. sequence_ = SEQ_PREPARE_PORT;
  497. }
  498. return true;
  499. }
  500. void FtpNegotiationCommand::afterFileAllocation()
  501. {
  502. setReadCheckSocket(getSocket());
  503. }
  504. bool FtpNegotiationCommand::preparePort() {
  505. afterFileAllocation();
  506. if(getSocket()->getAddressFamily() == AF_INET6) {
  507. sequence_ = SEQ_PREPARE_SERVER_SOCKET_EPRT;
  508. } else {
  509. sequence_ = SEQ_PREPARE_SERVER_SOCKET;
  510. }
  511. return true;
  512. }
  513. bool FtpNegotiationCommand::prepareServerSocketEprt() {
  514. serverSocket_ = ftp_->createServerSocket();
  515. sequence_ = SEQ_SEND_EPRT;
  516. return true;
  517. }
  518. bool FtpNegotiationCommand::prepareServerSocket()
  519. {
  520. serverSocket_ = ftp_->createServerSocket();
  521. sequence_ = SEQ_SEND_PORT;
  522. return true;
  523. }
  524. bool FtpNegotiationCommand::sendEprt() {
  525. if(ftp_->sendEprt(serverSocket_)) {
  526. disableWriteCheckSocket();
  527. sequence_ = SEQ_RECV_EPRT;
  528. } else {
  529. setWriteCheckSocket(getSocket());
  530. }
  531. return false;
  532. }
  533. bool FtpNegotiationCommand::recvEprt() {
  534. int status = ftp_->receiveResponse();
  535. if(status == 0) {
  536. return false;
  537. }
  538. if(status == 200) {
  539. sequence_ = SEQ_SEND_REST;
  540. } else {
  541. sequence_ = SEQ_PREPARE_SERVER_SOCKET;
  542. }
  543. return true;
  544. }
  545. bool FtpNegotiationCommand::sendPort() {
  546. if(ftp_->sendPort(serverSocket_)) {
  547. disableWriteCheckSocket();
  548. sequence_ = SEQ_RECV_PORT;
  549. } else {
  550. setWriteCheckSocket(getSocket());
  551. }
  552. return false;
  553. }
  554. bool FtpNegotiationCommand::recvPort() {
  555. int status = ftp_->receiveResponse();
  556. if(status == 0) {
  557. return false;
  558. }
  559. if(status != 200) {
  560. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
  561. error_code::FTP_PROTOCOL_ERROR);
  562. }
  563. sequence_ = SEQ_SEND_REST;
  564. return true;
  565. }
  566. bool FtpNegotiationCommand::preparePasv() {
  567. afterFileAllocation();
  568. if(getSocket()->getAddressFamily() == AF_INET6) {
  569. sequence_ = SEQ_SEND_EPSV;
  570. } else {
  571. sequence_ = SEQ_SEND_PASV;
  572. }
  573. return true;
  574. }
  575. bool FtpNegotiationCommand::sendEpsv() {
  576. if(ftp_->sendEpsv()) {
  577. disableWriteCheckSocket();
  578. sequence_ = SEQ_RECV_EPSV;
  579. } else {
  580. setWriteCheckSocket(getSocket());
  581. }
  582. return true;
  583. }
  584. bool FtpNegotiationCommand::recvEpsv() {
  585. uint16_t port;
  586. int status = ftp_->receiveEpsvResponse(port);
  587. if(status == 0) {
  588. return false;
  589. }
  590. if(status == 229) {
  591. pasvPort_ = port;
  592. return preparePasvConnect();
  593. } else {
  594. sequence_ = SEQ_SEND_PASV;
  595. return true;
  596. }
  597. }
  598. bool FtpNegotiationCommand::sendPasv() {
  599. if(ftp_->sendPasv()) {
  600. disableWriteCheckSocket();
  601. sequence_ = SEQ_RECV_PASV;
  602. } else {
  603. setWriteCheckSocket(getSocket());
  604. }
  605. return false;
  606. }
  607. bool FtpNegotiationCommand::recvPasv() {
  608. std::pair<std::string, uint16_t> dest;
  609. int status = ftp_->receivePasvResponse(dest);
  610. if(status == 0) {
  611. return false;
  612. }
  613. if(status != 227) {
  614. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
  615. error_code::FTP_PROTOCOL_ERROR);
  616. }
  617. pasvPort_ = dest.second;;
  618. return preparePasvConnect();
  619. }
  620. bool FtpNegotiationCommand::preparePasvConnect() {
  621. if(isProxyDefined()) {
  622. sequence_ = SEQ_RESOLVE_PROXY;
  623. return true;
  624. } else {
  625. std::pair<std::string, uint16_t> dataAddr;
  626. getSocket()->getPeerInfo(dataAddr);
  627. // make a data connection to the server.
  628. A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER,
  629. getCuid(),
  630. dataAddr.first.c_str(),
  631. pasvPort_));
  632. dataSocket_.reset(new SocketCore());
  633. dataSocket_->establishConnection(dataAddr.first, pasvPort_);
  634. disableReadCheckSocket();
  635. setWriteCheckSocket(dataSocket_);
  636. sequence_ = SEQ_SEND_REST_PASV;
  637. return false;
  638. }
  639. }
  640. bool FtpNegotiationCommand::resolveProxy()
  641. {
  642. SharedHandle<Request> proxyReq = createProxyRequest();
  643. std::vector<std::string> addrs;
  644. proxyAddr_ = resolveHostname
  645. (addrs, proxyReq->getHost(), proxyReq->getPort());
  646. if(proxyAddr_.empty()) {
  647. return false;
  648. }
  649. A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER,
  650. getCuid(),
  651. proxyAddr_.c_str(), proxyReq->getPort()));
  652. dataSocket_.reset(new SocketCore());
  653. dataSocket_->establishConnection(proxyAddr_, proxyReq->getPort());
  654. disableReadCheckSocket();
  655. setWriteCheckSocket(dataSocket_);
  656. SharedHandle<SocketRecvBuffer> socketRecvBuffer
  657. (new SocketRecvBuffer(dataSocket_));
  658. http_.reset(new HttpConnection(getCuid(), dataSocket_, socketRecvBuffer));
  659. sequence_ = SEQ_SEND_TUNNEL_REQUEST;
  660. return false;
  661. }
  662. bool FtpNegotiationCommand::sendTunnelRequest()
  663. {
  664. if(http_->sendBufferIsEmpty()) {
  665. if(dataSocket_->isReadable(0)) {
  666. std::string error = getSocket()->getSocketError();
  667. if(!error.empty()) {
  668. SharedHandle<Request> proxyReq = createProxyRequest();
  669. getDownloadEngine()->markBadIPAddress(proxyReq->getHost(),
  670. proxyAddr_,proxyReq->getPort());
  671. std::string nextProxyAddr = getDownloadEngine()->findCachedIPAddress
  672. (proxyReq->getHost(), proxyReq->getPort());
  673. if(nextProxyAddr.empty()) {
  674. getDownloadEngine()->removeCachedIPAddress(proxyReq->getHost(),
  675. proxyReq->getPort());
  676. throw DL_RETRY_EX
  677. (fmt(MSG_ESTABLISHING_CONNECTION_FAILED,
  678. error.c_str()));
  679. } else {
  680. A2_LOG_INFO(fmt(MSG_CONNECT_FAILED_AND_RETRY,
  681. getCuid(),
  682. proxyAddr_.c_str(), proxyReq->getPort()));
  683. proxyAddr_ = nextProxyAddr;
  684. A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER,
  685. getCuid(),
  686. proxyAddr_.c_str(), proxyReq->getPort()));
  687. dataSocket_->establishConnection(proxyAddr_, proxyReq->getPort());
  688. return false;
  689. }
  690. }
  691. }
  692. SharedHandle<HttpRequest> httpRequest(new HttpRequest());
  693. httpRequest->setUserAgent(getOption()->get(PREF_USER_AGENT));
  694. SharedHandle<Request> req(new Request());
  695. // Construct fake URI in order to use HttpRequest
  696. std::pair<std::string, uint16_t> dataAddr;
  697. uri::UriStruct us;
  698. us.protocol = "ftp";
  699. us.host = getRequest()->getHost();
  700. us.port = pasvPort_;
  701. us.ipv6LiteralAddress = getRequest()->isIPv6LiteralAddress();
  702. if(!req->setUri(uri::construct(us))) {
  703. throw DL_RETRY_EX("Something wrong with FTP URI");
  704. }
  705. httpRequest->setRequest(req);
  706. httpRequest->setProxyRequest(createProxyRequest());
  707. http_->sendProxyRequest(httpRequest);
  708. } else {
  709. http_->sendPendingData();
  710. }
  711. if(http_->sendBufferIsEmpty()) {
  712. disableWriteCheckSocket();
  713. setReadCheckSocket(dataSocket_);
  714. sequence_ = SEQ_RECV_TUNNEL_RESPONSE;
  715. return false;
  716. } else {
  717. setWriteCheckSocket(dataSocket_);
  718. return false;
  719. }
  720. }
  721. bool FtpNegotiationCommand::recvTunnelResponse()
  722. {
  723. SharedHandle<HttpResponse> httpResponse = http_->receiveResponse();
  724. if(!httpResponse) {
  725. return false;
  726. }
  727. if(httpResponse->getStatusCode() != 200) {
  728. throw DL_RETRY_EX(EX_PROXY_CONNECTION_FAILED);
  729. }
  730. sequence_ = SEQ_SEND_REST_PASV;
  731. return true;
  732. }
  733. bool FtpNegotiationCommand::sendRestPasv(const SharedHandle<Segment>& segment) {
  734. //dataSocket_->setBlockingMode();
  735. // Check connection is made properly
  736. if(dataSocket_->isReadable(0)) {
  737. std::string error = dataSocket_->getSocketError();
  738. throw DL_ABORT_EX2
  739. (fmt(MSG_ESTABLISHING_CONNECTION_FAILED, error.c_str()),
  740. error_code::FTP_PROTOCOL_ERROR);
  741. }
  742. setReadCheckSocket(getSocket());
  743. disableWriteCheckSocket();
  744. return sendRest(segment);
  745. }
  746. bool FtpNegotiationCommand::sendRest(const SharedHandle<Segment>& segment) {
  747. if(ftp_->sendRest(segment)) {
  748. disableWriteCheckSocket();
  749. sequence_ = SEQ_RECV_REST;
  750. } else {
  751. setWriteCheckSocket(getSocket());
  752. }
  753. return false;
  754. }
  755. bool FtpNegotiationCommand::recvRest(const SharedHandle<Segment>& segment) {
  756. int status = ftp_->receiveResponse();
  757. if(status == 0) {
  758. return false;
  759. }
  760. // If we recieve negative response and requested file position is not 0,
  761. // then throw exception here.
  762. if(status != 350) {
  763. if(segment && segment->getPositionToWrite() != 0) {
  764. throw DL_ABORT_EX2("FTP server doesn't support resuming.",
  765. error_code::CANNOT_RESUME);
  766. }
  767. }
  768. sequence_ = SEQ_SEND_RETR;
  769. return true;
  770. }
  771. bool FtpNegotiationCommand::sendRetr() {
  772. if(ftp_->sendRetr()) {
  773. disableWriteCheckSocket();
  774. sequence_ = SEQ_RECV_RETR;
  775. } else {
  776. setWriteCheckSocket(getSocket());
  777. }
  778. return false;
  779. }
  780. bool FtpNegotiationCommand::recvRetr() {
  781. int status = ftp_->receiveResponse();
  782. if(status == 0) {
  783. return false;
  784. }
  785. if(status != 150 && status != 125) {
  786. getRequestGroup()->increaseAndValidateFileNotFoundCount();
  787. if (status == 550)
  788. throw DL_ABORT_EX2(MSG_RESOURCE_NOT_FOUND,
  789. error_code::RESOURCE_NOT_FOUND);
  790. else
  791. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
  792. error_code::FTP_PROTOCOL_ERROR);
  793. }
  794. if(getOption()->getAsBool(PREF_FTP_PASV)) {
  795. sequence_ = SEQ_NEGOTIATION_COMPLETED;
  796. return false;
  797. } else {
  798. disableReadCheckSocket();
  799. setReadCheckSocket(serverSocket_);
  800. sequence_ = SEQ_WAIT_CONNECTION;
  801. return false;
  802. }
  803. }
  804. bool FtpNegotiationCommand::waitConnection()
  805. {
  806. disableReadCheckSocket();
  807. setReadCheckSocket(getSocket());
  808. dataSocket_.reset(serverSocket_->acceptConnection());
  809. dataSocket_->setNonBlockingMode();
  810. sequence_ = SEQ_NEGOTIATION_COMPLETED;
  811. return false;
  812. }
  813. bool FtpNegotiationCommand::processSequence
  814. (const SharedHandle<Segment>& segment) {
  815. bool doNextSequence = true;
  816. switch(sequence_) {
  817. case SEQ_RECV_GREETING:
  818. return recvGreeting();
  819. case SEQ_SEND_USER:
  820. return sendUser();
  821. case SEQ_RECV_USER:
  822. return recvUser();
  823. case SEQ_SEND_PASS:
  824. return sendPass();
  825. case SEQ_RECV_PASS:
  826. return recvPass();
  827. case SEQ_SEND_TYPE:
  828. return sendType();
  829. case SEQ_RECV_TYPE:
  830. return recvType();
  831. case SEQ_SEND_PWD:
  832. return sendPwd();
  833. case SEQ_RECV_PWD:
  834. return recvPwd();
  835. case SEQ_SEND_CWD_PREP:
  836. return sendCwdPrep();
  837. case SEQ_SEND_CWD:
  838. return sendCwd();
  839. case SEQ_RECV_CWD:
  840. return recvCwd();
  841. case SEQ_SEND_MDTM:
  842. return sendMdtm();
  843. case SEQ_RECV_MDTM:
  844. return recvMdtm();
  845. case SEQ_SEND_SIZE:
  846. return sendSize();
  847. case SEQ_RECV_SIZE:
  848. return recvSize();
  849. case SEQ_PREPARE_PORT:
  850. return preparePort();
  851. case SEQ_PREPARE_SERVER_SOCKET_EPRT:
  852. return prepareServerSocketEprt();
  853. case SEQ_SEND_EPRT:
  854. return sendEprt();
  855. case SEQ_RECV_EPRT:
  856. return recvEprt();
  857. case SEQ_PREPARE_SERVER_SOCKET:
  858. return prepareServerSocket();
  859. case SEQ_SEND_PORT:
  860. return sendPort();
  861. case SEQ_RECV_PORT:
  862. return recvPort();
  863. case SEQ_PREPARE_PASV:
  864. return preparePasv();
  865. case SEQ_SEND_EPSV:
  866. return sendEpsv();
  867. case SEQ_RECV_EPSV:
  868. return recvEpsv();
  869. case SEQ_SEND_PASV:
  870. return sendPasv();
  871. case SEQ_RECV_PASV:
  872. return recvPasv();
  873. case SEQ_RESOLVE_PROXY:
  874. return resolveProxy();
  875. case SEQ_SEND_TUNNEL_REQUEST:
  876. return sendTunnelRequest();
  877. case SEQ_RECV_TUNNEL_RESPONSE:
  878. return recvTunnelResponse();
  879. case SEQ_SEND_REST_PASV:
  880. return sendRestPasv(segment);
  881. case SEQ_SEND_REST:
  882. return sendRest(segment);
  883. case SEQ_RECV_REST:
  884. return recvRest(segment);
  885. case SEQ_SEND_RETR:
  886. return sendRetr();
  887. case SEQ_RECV_RETR:
  888. return recvRetr();
  889. case SEQ_WAIT_CONNECTION:
  890. return waitConnection();
  891. default:
  892. abort();
  893. }
  894. return doNextSequence;
  895. }
  896. void FtpNegotiationCommand::poolConnection() const
  897. {
  898. if(getOption()->getAsBool(PREF_FTP_REUSE_CONNECTION)) {
  899. std::map<std::string, std::string> options;
  900. options["baseWorkingDir"] = ftp_->getBaseWorkingDir();
  901. getDownloadEngine()->poolSocket(getRequest(), ftp_->getUser(),
  902. createProxyRequest(), getSocket(), options);
  903. }
  904. }
  905. void FtpNegotiationCommand::onDryRunFileFound()
  906. {
  907. getPieceStorage()->markAllPiecesDone();
  908. getDownloadContext()->setChecksumVerified(true);
  909. poolConnection();
  910. sequence_ = SEQ_HEAD_OK;
  911. }
  912. } // namespace aria2