FtpNegotiationCommand.cc 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  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#%lld - 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#%lld - 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(off_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
  472. (fmt(EX_TOO_LARGE_FILE, static_cast<long long int>(size)),
  473. error_code::FTP_PROTOCOL_ERROR);
  474. }
  475. if(!getPieceStorage()) {
  476. sequence_ = SEQ_FILE_PREPARATION;
  477. return onFileSizeDetermined(size);
  478. } else {
  479. getRequestGroup()->validateTotalLength(getFileEntry()->getLength(), size);
  480. }
  481. } else {
  482. A2_LOG_INFO(fmt("CUID#%lld - The remote FTP Server doesn't recognize SIZE"
  483. " command. Continue.", getCuid()));
  484. // Even if one of the other servers waiting in the queue supports SIZE
  485. // command, resuming and segmented downloading are disabled when the first
  486. // contacted FTP server doesn't support it.
  487. if(!getPieceStorage()) {
  488. getDownloadContext()->markTotalLengthIsUnknown();
  489. return onFileSizeDetermined(0);
  490. }
  491. // TODO Skipping RequestGroup::validateTotalLength(0) here will allow
  492. // wrong file to be downloaded if user-specified URL is wrong.
  493. }
  494. if(getOption()->getAsBool(PREF_FTP_PASV)) {
  495. sequence_ = SEQ_PREPARE_PASV;
  496. } else {
  497. sequence_ = SEQ_PREPARE_PORT;
  498. }
  499. return true;
  500. }
  501. void FtpNegotiationCommand::afterFileAllocation()
  502. {
  503. setReadCheckSocket(getSocket());
  504. }
  505. bool FtpNegotiationCommand::preparePort() {
  506. afterFileAllocation();
  507. if(getSocket()->getAddressFamily() == AF_INET6) {
  508. sequence_ = SEQ_PREPARE_SERVER_SOCKET_EPRT;
  509. } else {
  510. sequence_ = SEQ_PREPARE_SERVER_SOCKET;
  511. }
  512. return true;
  513. }
  514. bool FtpNegotiationCommand::prepareServerSocketEprt() {
  515. serverSocket_ = ftp_->createServerSocket();
  516. sequence_ = SEQ_SEND_EPRT;
  517. return true;
  518. }
  519. bool FtpNegotiationCommand::prepareServerSocket()
  520. {
  521. serverSocket_ = ftp_->createServerSocket();
  522. sequence_ = SEQ_SEND_PORT;
  523. return true;
  524. }
  525. bool FtpNegotiationCommand::sendEprt() {
  526. if(ftp_->sendEprt(serverSocket_)) {
  527. disableWriteCheckSocket();
  528. sequence_ = SEQ_RECV_EPRT;
  529. } else {
  530. setWriteCheckSocket(getSocket());
  531. }
  532. return false;
  533. }
  534. bool FtpNegotiationCommand::recvEprt() {
  535. int status = ftp_->receiveResponse();
  536. if(status == 0) {
  537. return false;
  538. }
  539. if(status == 200) {
  540. sequence_ = SEQ_SEND_REST;
  541. } else {
  542. sequence_ = SEQ_PREPARE_SERVER_SOCKET;
  543. }
  544. return true;
  545. }
  546. bool FtpNegotiationCommand::sendPort() {
  547. if(ftp_->sendPort(serverSocket_)) {
  548. disableWriteCheckSocket();
  549. sequence_ = SEQ_RECV_PORT;
  550. } else {
  551. setWriteCheckSocket(getSocket());
  552. }
  553. return false;
  554. }
  555. bool FtpNegotiationCommand::recvPort() {
  556. int status = ftp_->receiveResponse();
  557. if(status == 0) {
  558. return false;
  559. }
  560. if(status != 200) {
  561. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
  562. error_code::FTP_PROTOCOL_ERROR);
  563. }
  564. sequence_ = SEQ_SEND_REST;
  565. return true;
  566. }
  567. bool FtpNegotiationCommand::preparePasv() {
  568. afterFileAllocation();
  569. if(getSocket()->getAddressFamily() == AF_INET6) {
  570. sequence_ = SEQ_SEND_EPSV;
  571. } else {
  572. sequence_ = SEQ_SEND_PASV;
  573. }
  574. return true;
  575. }
  576. bool FtpNegotiationCommand::sendEpsv() {
  577. if(ftp_->sendEpsv()) {
  578. disableWriteCheckSocket();
  579. sequence_ = SEQ_RECV_EPSV;
  580. } else {
  581. setWriteCheckSocket(getSocket());
  582. }
  583. return true;
  584. }
  585. bool FtpNegotiationCommand::recvEpsv() {
  586. uint16_t port;
  587. int status = ftp_->receiveEpsvResponse(port);
  588. if(status == 0) {
  589. return false;
  590. }
  591. if(status == 229) {
  592. pasvPort_ = port;
  593. return preparePasvConnect();
  594. } else {
  595. sequence_ = SEQ_SEND_PASV;
  596. return true;
  597. }
  598. }
  599. bool FtpNegotiationCommand::sendPasv() {
  600. if(ftp_->sendPasv()) {
  601. disableWriteCheckSocket();
  602. sequence_ = SEQ_RECV_PASV;
  603. } else {
  604. setWriteCheckSocket(getSocket());
  605. }
  606. return false;
  607. }
  608. bool FtpNegotiationCommand::recvPasv() {
  609. std::pair<std::string, uint16_t> dest;
  610. int status = ftp_->receivePasvResponse(dest);
  611. if(status == 0) {
  612. return false;
  613. }
  614. if(status != 227) {
  615. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
  616. error_code::FTP_PROTOCOL_ERROR);
  617. }
  618. pasvPort_ = dest.second;;
  619. return preparePasvConnect();
  620. }
  621. bool FtpNegotiationCommand::preparePasvConnect() {
  622. if(isProxyDefined()) {
  623. sequence_ = SEQ_RESOLVE_PROXY;
  624. return true;
  625. } else {
  626. std::pair<std::string, uint16_t> dataAddr;
  627. getSocket()->getPeerInfo(dataAddr);
  628. // make a data connection to the server.
  629. A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER,
  630. getCuid(),
  631. dataAddr.first.c_str(),
  632. pasvPort_));
  633. dataSocket_.reset(new SocketCore());
  634. dataSocket_->establishConnection(dataAddr.first, pasvPort_);
  635. disableReadCheckSocket();
  636. setWriteCheckSocket(dataSocket_);
  637. sequence_ = SEQ_SEND_REST_PASV;
  638. return false;
  639. }
  640. }
  641. bool FtpNegotiationCommand::resolveProxy()
  642. {
  643. SharedHandle<Request> proxyReq = createProxyRequest();
  644. std::vector<std::string> addrs;
  645. proxyAddr_ = resolveHostname
  646. (addrs, proxyReq->getHost(), proxyReq->getPort());
  647. if(proxyAddr_.empty()) {
  648. return false;
  649. }
  650. A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER,
  651. getCuid(),
  652. proxyAddr_.c_str(), proxyReq->getPort()));
  653. dataSocket_.reset(new SocketCore());
  654. dataSocket_->establishConnection(proxyAddr_, proxyReq->getPort());
  655. disableReadCheckSocket();
  656. setWriteCheckSocket(dataSocket_);
  657. SharedHandle<SocketRecvBuffer> socketRecvBuffer
  658. (new SocketRecvBuffer(dataSocket_));
  659. http_.reset(new HttpConnection(getCuid(), dataSocket_, socketRecvBuffer));
  660. sequence_ = SEQ_SEND_TUNNEL_REQUEST;
  661. return false;
  662. }
  663. bool FtpNegotiationCommand::sendTunnelRequest()
  664. {
  665. if(http_->sendBufferIsEmpty()) {
  666. if(dataSocket_->isReadable(0)) {
  667. std::string error = getSocket()->getSocketError();
  668. if(!error.empty()) {
  669. SharedHandle<Request> proxyReq = createProxyRequest();
  670. getDownloadEngine()->markBadIPAddress(proxyReq->getHost(),
  671. proxyAddr_,proxyReq->getPort());
  672. std::string nextProxyAddr = getDownloadEngine()->findCachedIPAddress
  673. (proxyReq->getHost(), proxyReq->getPort());
  674. if(nextProxyAddr.empty()) {
  675. getDownloadEngine()->removeCachedIPAddress(proxyReq->getHost(),
  676. proxyReq->getPort());
  677. throw DL_RETRY_EX
  678. (fmt(MSG_ESTABLISHING_CONNECTION_FAILED,
  679. error.c_str()));
  680. } else {
  681. A2_LOG_INFO(fmt(MSG_CONNECT_FAILED_AND_RETRY,
  682. getCuid(),
  683. proxyAddr_.c_str(), proxyReq->getPort()));
  684. proxyAddr_ = nextProxyAddr;
  685. A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER,
  686. getCuid(),
  687. proxyAddr_.c_str(), proxyReq->getPort()));
  688. dataSocket_->establishConnection(proxyAddr_, proxyReq->getPort());
  689. return false;
  690. }
  691. }
  692. }
  693. SharedHandle<HttpRequest> httpRequest(new HttpRequest());
  694. httpRequest->setUserAgent(getOption()->get(PREF_USER_AGENT));
  695. SharedHandle<Request> req(new Request());
  696. // Construct fake URI in order to use HttpRequest
  697. std::pair<std::string, uint16_t> dataAddr;
  698. uri::UriStruct us;
  699. us.protocol = "ftp";
  700. us.host = getRequest()->getHost();
  701. us.port = pasvPort_;
  702. us.ipv6LiteralAddress = getRequest()->isIPv6LiteralAddress();
  703. if(!req->setUri(uri::construct(us))) {
  704. throw DL_RETRY_EX("Something wrong with FTP URI");
  705. }
  706. httpRequest->setRequest(req);
  707. httpRequest->setProxyRequest(createProxyRequest());
  708. http_->sendProxyRequest(httpRequest);
  709. } else {
  710. http_->sendPendingData();
  711. }
  712. if(http_->sendBufferIsEmpty()) {
  713. disableWriteCheckSocket();
  714. setReadCheckSocket(dataSocket_);
  715. sequence_ = SEQ_RECV_TUNNEL_RESPONSE;
  716. return false;
  717. } else {
  718. setWriteCheckSocket(dataSocket_);
  719. return false;
  720. }
  721. }
  722. bool FtpNegotiationCommand::recvTunnelResponse()
  723. {
  724. SharedHandle<HttpResponse> httpResponse = http_->receiveResponse();
  725. if(!httpResponse) {
  726. return false;
  727. }
  728. if(httpResponse->getStatusCode() != 200) {
  729. throw DL_RETRY_EX(EX_PROXY_CONNECTION_FAILED);
  730. }
  731. sequence_ = SEQ_SEND_REST_PASV;
  732. return true;
  733. }
  734. bool FtpNegotiationCommand::sendRestPasv(const SharedHandle<Segment>& segment) {
  735. //dataSocket_->setBlockingMode();
  736. // Check connection is made properly
  737. if(dataSocket_->isReadable(0)) {
  738. std::string error = dataSocket_->getSocketError();
  739. throw DL_ABORT_EX2
  740. (fmt(MSG_ESTABLISHING_CONNECTION_FAILED, error.c_str()),
  741. error_code::FTP_PROTOCOL_ERROR);
  742. }
  743. setReadCheckSocket(getSocket());
  744. disableWriteCheckSocket();
  745. return sendRest(segment);
  746. }
  747. bool FtpNegotiationCommand::sendRest(const SharedHandle<Segment>& segment) {
  748. if(ftp_->sendRest(segment)) {
  749. disableWriteCheckSocket();
  750. sequence_ = SEQ_RECV_REST;
  751. } else {
  752. setWriteCheckSocket(getSocket());
  753. }
  754. return false;
  755. }
  756. bool FtpNegotiationCommand::recvRest(const SharedHandle<Segment>& segment) {
  757. int status = ftp_->receiveResponse();
  758. if(status == 0) {
  759. return false;
  760. }
  761. // If we recieve negative response and requested file position is not 0,
  762. // then throw exception here.
  763. if(status != 350) {
  764. if(segment && segment->getPositionToWrite() != 0) {
  765. throw DL_ABORT_EX2("FTP server doesn't support resuming.",
  766. error_code::CANNOT_RESUME);
  767. }
  768. }
  769. sequence_ = SEQ_SEND_RETR;
  770. return true;
  771. }
  772. bool FtpNegotiationCommand::sendRetr() {
  773. if(ftp_->sendRetr()) {
  774. disableWriteCheckSocket();
  775. sequence_ = SEQ_RECV_RETR;
  776. } else {
  777. setWriteCheckSocket(getSocket());
  778. }
  779. return false;
  780. }
  781. bool FtpNegotiationCommand::recvRetr() {
  782. int status = ftp_->receiveResponse();
  783. if(status == 0) {
  784. return false;
  785. }
  786. if(status != 150 && status != 125) {
  787. getRequestGroup()->increaseAndValidateFileNotFoundCount();
  788. if (status == 550)
  789. throw DL_ABORT_EX2(MSG_RESOURCE_NOT_FOUND,
  790. error_code::RESOURCE_NOT_FOUND);
  791. else
  792. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
  793. error_code::FTP_PROTOCOL_ERROR);
  794. }
  795. if(getOption()->getAsBool(PREF_FTP_PASV)) {
  796. sequence_ = SEQ_NEGOTIATION_COMPLETED;
  797. return false;
  798. } else {
  799. disableReadCheckSocket();
  800. setReadCheckSocket(serverSocket_);
  801. sequence_ = SEQ_WAIT_CONNECTION;
  802. return false;
  803. }
  804. }
  805. bool FtpNegotiationCommand::waitConnection()
  806. {
  807. disableReadCheckSocket();
  808. setReadCheckSocket(getSocket());
  809. dataSocket_.reset(serverSocket_->acceptConnection());
  810. dataSocket_->setNonBlockingMode();
  811. sequence_ = SEQ_NEGOTIATION_COMPLETED;
  812. return false;
  813. }
  814. bool FtpNegotiationCommand::processSequence
  815. (const SharedHandle<Segment>& segment) {
  816. bool doNextSequence = true;
  817. switch(sequence_) {
  818. case SEQ_RECV_GREETING:
  819. return recvGreeting();
  820. case SEQ_SEND_USER:
  821. return sendUser();
  822. case SEQ_RECV_USER:
  823. return recvUser();
  824. case SEQ_SEND_PASS:
  825. return sendPass();
  826. case SEQ_RECV_PASS:
  827. return recvPass();
  828. case SEQ_SEND_TYPE:
  829. return sendType();
  830. case SEQ_RECV_TYPE:
  831. return recvType();
  832. case SEQ_SEND_PWD:
  833. return sendPwd();
  834. case SEQ_RECV_PWD:
  835. return recvPwd();
  836. case SEQ_SEND_CWD_PREP:
  837. return sendCwdPrep();
  838. case SEQ_SEND_CWD:
  839. return sendCwd();
  840. case SEQ_RECV_CWD:
  841. return recvCwd();
  842. case SEQ_SEND_MDTM:
  843. return sendMdtm();
  844. case SEQ_RECV_MDTM:
  845. return recvMdtm();
  846. case SEQ_SEND_SIZE:
  847. return sendSize();
  848. case SEQ_RECV_SIZE:
  849. return recvSize();
  850. case SEQ_PREPARE_PORT:
  851. return preparePort();
  852. case SEQ_PREPARE_SERVER_SOCKET_EPRT:
  853. return prepareServerSocketEprt();
  854. case SEQ_SEND_EPRT:
  855. return sendEprt();
  856. case SEQ_RECV_EPRT:
  857. return recvEprt();
  858. case SEQ_PREPARE_SERVER_SOCKET:
  859. return prepareServerSocket();
  860. case SEQ_SEND_PORT:
  861. return sendPort();
  862. case SEQ_RECV_PORT:
  863. return recvPort();
  864. case SEQ_PREPARE_PASV:
  865. return preparePasv();
  866. case SEQ_SEND_EPSV:
  867. return sendEpsv();
  868. case SEQ_RECV_EPSV:
  869. return recvEpsv();
  870. case SEQ_SEND_PASV:
  871. return sendPasv();
  872. case SEQ_RECV_PASV:
  873. return recvPasv();
  874. case SEQ_RESOLVE_PROXY:
  875. return resolveProxy();
  876. case SEQ_SEND_TUNNEL_REQUEST:
  877. return sendTunnelRequest();
  878. case SEQ_RECV_TUNNEL_RESPONSE:
  879. return recvTunnelResponse();
  880. case SEQ_SEND_REST_PASV:
  881. return sendRestPasv(segment);
  882. case SEQ_SEND_REST:
  883. return sendRest(segment);
  884. case SEQ_RECV_REST:
  885. return recvRest(segment);
  886. case SEQ_SEND_RETR:
  887. return sendRetr();
  888. case SEQ_RECV_RETR:
  889. return recvRetr();
  890. case SEQ_WAIT_CONNECTION:
  891. return waitConnection();
  892. default:
  893. abort();
  894. }
  895. return doNextSequence;
  896. }
  897. void FtpNegotiationCommand::poolConnection() const
  898. {
  899. if(getOption()->getAsBool(PREF_FTP_REUSE_CONNECTION)) {
  900. std::map<std::string, std::string> options;
  901. options["baseWorkingDir"] = ftp_->getBaseWorkingDir();
  902. getDownloadEngine()->poolSocket(getRequest(), ftp_->getUser(),
  903. createProxyRequest(), getSocket(), options);
  904. }
  905. }
  906. void FtpNegotiationCommand::onDryRunFileFound()
  907. {
  908. getPieceStorage()->markAllPiecesDone();
  909. getDownloadContext()->setChecksumVerified(true);
  910. poolConnection();
  911. sequence_ = SEQ_HEAD_OK;
  912. }
  913. } // namespace aria2