FtpNegotiationCommand.cc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  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. namespace aria2 {
  76. FtpNegotiationCommand::FtpNegotiationCommand
  77. (cuid_t cuid,
  78. const SharedHandle<Request>& req,
  79. const SharedHandle<FileEntry>& fileEntry,
  80. RequestGroup* requestGroup,
  81. DownloadEngine* e,
  82. const SocketHandle& socket,
  83. Seq seq,
  84. const std::string& baseWorkingDir):
  85. AbstractCommand(cuid, req, fileEntry, requestGroup, e, socket), sequence_(seq),
  86. ftp_(new FtpConnection(cuid, socket, req,
  87. e->getAuthConfigFactory()->createAuthConfig
  88. (req, requestGroup->getOption().get()),
  89. getOption().get()))
  90. {
  91. ftp_->setBaseWorkingDir(baseWorkingDir);
  92. if(seq == SEQ_RECV_GREETING) {
  93. setTimeout(getOption()->getAsInt(PREF_CONNECT_TIMEOUT));
  94. }
  95. disableReadCheckSocket();
  96. setWriteCheckSocket(getSocket());
  97. }
  98. FtpNegotiationCommand::~FtpNegotiationCommand() {}
  99. bool FtpNegotiationCommand::executeInternal() {
  100. while(processSequence(getSegments().front()));
  101. if(sequence_ == SEQ_RETRY) {
  102. return prepareForRetry(0);
  103. } else if(sequence_ == SEQ_NEGOTIATION_COMPLETED) {
  104. FtpDownloadCommand* command =
  105. new FtpDownloadCommand
  106. (getCuid(), getRequest(), getFileEntry(), getRequestGroup(), ftp_,
  107. getDownloadEngine(), dataSocket_, getSocket());
  108. command->setStartupIdleTime(getOption()->getAsInt(PREF_STARTUP_IDLE_TIME));
  109. command->setLowestDownloadSpeedLimit
  110. (getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT));
  111. if(getFileEntry()->isUniqueProtocol()) {
  112. getFileEntry()->removeURIWhoseHostnameIs(getRequest()->getHost());
  113. }
  114. getRequestGroup()->getURISelector()->tuneDownloadCommand
  115. (getFileEntry()->getRemainingUris(), command);
  116. getDownloadEngine()->addCommand(command);
  117. return true;
  118. } else if(sequence_ == SEQ_HEAD_OK ||
  119. sequence_ == SEQ_DOWNLOAD_ALREADY_COMPLETED) {
  120. return true;
  121. } else if(sequence_ == SEQ_FILE_PREPARATION) {
  122. if(getOption()->getAsBool(PREF_FTP_PASV)) {
  123. sequence_ = SEQ_PREPARE_PASV;
  124. } else {
  125. sequence_ = SEQ_PREPARE_PORT;
  126. }
  127. return false;
  128. } else if(sequence_ == SEQ_EXIT) {
  129. return true;
  130. } else {
  131. getDownloadEngine()->addCommand(this);
  132. return false;
  133. }
  134. }
  135. bool FtpNegotiationCommand::recvGreeting() {
  136. if(!checkIfConnectionEstablished
  137. (getSocket(), getRequest()->getConnectedHostname(),
  138. getRequest()->getConnectedAddr(), getRequest()->getConnectedPort())) {
  139. sequence_ = SEQ_EXIT;
  140. return false;
  141. }
  142. setTimeout(getRequestGroup()->getTimeout());
  143. //socket->setBlockingMode();
  144. disableWriteCheckSocket();
  145. setReadCheckSocket(getSocket());
  146. unsigned int status = ftp_->receiveResponse();
  147. if(status == 0) {
  148. return false;
  149. }
  150. if(status != 220) {
  151. throw DL_ABORT_EX2(EX_CONNECTION_FAILED, error_code::FTP_PROTOCOL_ERROR);
  152. }
  153. sequence_ = SEQ_SEND_USER;
  154. return true;
  155. }
  156. bool FtpNegotiationCommand::sendUser() {
  157. if(ftp_->sendUser()) {
  158. disableWriteCheckSocket();
  159. sequence_ = SEQ_RECV_USER;
  160. } else {
  161. setWriteCheckSocket(getSocket());
  162. }
  163. return false;
  164. }
  165. bool FtpNegotiationCommand::recvUser() {
  166. unsigned int status = ftp_->receiveResponse();
  167. switch(status) {
  168. case 0:
  169. return false;
  170. case 230:
  171. sequence_ = SEQ_SEND_TYPE;
  172. break;
  173. case 331:
  174. sequence_ = SEQ_SEND_PASS;
  175. break;
  176. default:
  177. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
  178. error_code::FTP_PROTOCOL_ERROR);
  179. }
  180. return true;
  181. }
  182. bool FtpNegotiationCommand::sendPass() {
  183. if(ftp_->sendPass()) {
  184. disableWriteCheckSocket();
  185. sequence_ = SEQ_RECV_PASS;
  186. } else {
  187. setWriteCheckSocket(getSocket());
  188. }
  189. return false;
  190. }
  191. bool FtpNegotiationCommand::recvPass() {
  192. unsigned int status = ftp_->receiveResponse();
  193. if(status == 0) {
  194. return false;
  195. }
  196. if(status != 230) {
  197. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
  198. error_code::FTP_PROTOCOL_ERROR);
  199. }
  200. sequence_ = SEQ_SEND_TYPE;
  201. return true;
  202. }
  203. bool FtpNegotiationCommand::sendType() {
  204. if(ftp_->sendType()) {
  205. disableWriteCheckSocket();
  206. sequence_ = SEQ_RECV_TYPE;
  207. } else {
  208. setWriteCheckSocket(getSocket());
  209. }
  210. return false;
  211. }
  212. bool FtpNegotiationCommand::recvType() {
  213. unsigned int status = ftp_->receiveResponse();
  214. if(status == 0) {
  215. return false;
  216. }
  217. if(status != 200) {
  218. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
  219. error_code::FTP_PROTOCOL_ERROR);
  220. }
  221. sequence_ = SEQ_SEND_PWD;
  222. return true;
  223. }
  224. bool FtpNegotiationCommand::sendPwd()
  225. {
  226. if(ftp_->sendPwd()) {
  227. disableWriteCheckSocket();
  228. sequence_ = SEQ_RECV_PWD;
  229. } else {
  230. setWriteCheckSocket(getSocket());
  231. }
  232. return false;
  233. }
  234. bool FtpNegotiationCommand::recvPwd()
  235. {
  236. std::string pwd;
  237. unsigned int status = ftp_->receivePwdResponse(pwd);
  238. if(status == 0) {
  239. return false;
  240. }
  241. if(status != 257) {
  242. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
  243. error_code::FTP_PROTOCOL_ERROR);
  244. }
  245. ftp_->setBaseWorkingDir(pwd);
  246. A2_LOG_INFO(fmt("CUID#%lld - base working directory is '%s'",
  247. getCuid(), pwd.c_str()));
  248. sequence_ = SEQ_SEND_CWD_PREP;
  249. return true;
  250. }
  251. bool FtpNegotiationCommand::sendCwdPrep()
  252. {
  253. // Calling setReadCheckSocket() is needed when the socket is reused,
  254. setReadCheckSocket(getSocket());
  255. util::split(getRequest()->getDir(), std::back_inserter(cwdDirs_),
  256. A2STR::SLASH_C);
  257. cwdDirs_.push_front(ftp_->getBaseWorkingDir());
  258. sequence_ = SEQ_SEND_CWD;
  259. return true;
  260. }
  261. bool FtpNegotiationCommand::sendCwd()
  262. {
  263. if(ftp_->sendCwd(cwdDirs_.front())) {
  264. disableWriteCheckSocket();
  265. sequence_ = SEQ_RECV_CWD;
  266. } else {
  267. setWriteCheckSocket(getSocket());
  268. }
  269. return false;
  270. }
  271. bool FtpNegotiationCommand::recvCwd()
  272. {
  273. unsigned int status = ftp_->receiveResponse();
  274. if(status == 0) {
  275. return false;
  276. }
  277. if(status != 250) {
  278. poolConnection();
  279. getRequestGroup()->increaseAndValidateFileNotFoundCount();
  280. if (status == 550)
  281. throw DL_ABORT_EX2(MSG_RESOURCE_NOT_FOUND,
  282. error_code::RESOURCE_NOT_FOUND);
  283. else
  284. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
  285. error_code::FTP_PROTOCOL_ERROR);
  286. }
  287. cwdDirs_.pop_front();
  288. if(cwdDirs_.empty()) {
  289. if(getOption()->getAsBool(PREF_REMOTE_TIME)) {
  290. sequence_ = SEQ_SEND_MDTM;
  291. } else {
  292. sequence_ = SEQ_SEND_SIZE;
  293. }
  294. } else {
  295. sequence_ = SEQ_SEND_CWD;
  296. }
  297. return true;
  298. }
  299. bool FtpNegotiationCommand::sendMdtm()
  300. {
  301. if(ftp_->sendMdtm()) {
  302. disableWriteCheckSocket();
  303. sequence_ = SEQ_RECV_MDTM;
  304. } else {
  305. setWriteCheckSocket(getSocket());
  306. }
  307. return false;
  308. }
  309. bool FtpNegotiationCommand::recvMdtm()
  310. {
  311. Time lastModifiedTime = Time::null();
  312. unsigned int status = ftp_->receiveMdtmResponse(lastModifiedTime);
  313. if(status == 0) {
  314. return false;
  315. }
  316. if(status == 213) {
  317. if(lastModifiedTime.good()) {
  318. getRequestGroup()->updateLastModifiedTime(lastModifiedTime);
  319. A2_LOG_DEBUG(fmt("MDTM result was parsed as: %s",
  320. lastModifiedTime.toHTTPDate().c_str()));
  321. } else {
  322. A2_LOG_DEBUG("MDTM response was returned, but it seems not to be"
  323. " a time value as in specified in RFC3659.");
  324. }
  325. } else {
  326. A2_LOG_INFO(fmt("CUID#%lld - MDTM command failed.",
  327. getCuid()));
  328. }
  329. sequence_ = SEQ_SEND_SIZE;
  330. return true;
  331. }
  332. bool FtpNegotiationCommand::sendSize() {
  333. if(ftp_->sendSize()) {
  334. disableWriteCheckSocket();
  335. sequence_ = SEQ_RECV_SIZE;
  336. } else {
  337. setWriteCheckSocket(getSocket());
  338. }
  339. return false;
  340. }
  341. bool FtpNegotiationCommand::onFileSizeDetermined(uint64_t totalLength)
  342. {
  343. getFileEntry()->setLength(totalLength);
  344. if(getFileEntry()->getPath().empty()) {
  345. getFileEntry()->setPath
  346. (util::createSafePath
  347. (getOption()->get(PREF_DIR),
  348. util::percentDecode(getRequest()->getFile())));
  349. }
  350. getRequestGroup()->preDownloadProcessing();
  351. if(getDownloadEngine()->getRequestGroupMan()->
  352. isSameFileBeingDownloaded(getRequestGroup())) {
  353. throw DOWNLOAD_FAILURE_EXCEPTION2
  354. (fmt(EX_DUPLICATE_FILE_DOWNLOAD,
  355. getRequestGroup()->getFirstFilePath().c_str()),
  356. error_code::DUPLICATE_DOWNLOAD);
  357. }
  358. if(totalLength == 0) {
  359. if(getOption()->getAsBool(PREF_FTP_PASV)) {
  360. sequence_ = SEQ_PREPARE_PASV;
  361. } else {
  362. sequence_ = SEQ_PREPARE_PORT;
  363. }
  364. if(getOption()->getAsBool(PREF_DRY_RUN)) {
  365. getRequestGroup()->initPieceStorage();
  366. onDryRunFileFound();
  367. return false;
  368. }
  369. if(getDownloadContext()->knowsTotalLength() &&
  370. getRequestGroup()->downloadFinishedByFileLength()) {
  371. // TODO If metalink file does not contain size and it contains
  372. // hash and file is not zero length, but remote server says the
  373. // file size is 0, no hash check is performed in the current
  374. // implementation. See also
  375. // HttpResponseCommand::handleOtherEncoding()
  376. getRequestGroup()->initPieceStorage();
  377. getPieceStorage()->markAllPiecesDone();
  378. getDownloadContext()->setChecksumVerified(true);
  379. sequence_ = SEQ_DOWNLOAD_ALREADY_COMPLETED;
  380. A2_LOG_NOTICE(fmt(MSG_DOWNLOAD_ALREADY_COMPLETED,
  381. util::itos(getRequestGroup()->getGID()).c_str(),
  382. getRequestGroup()->getFirstFilePath().c_str()));
  383. poolConnection();
  384. return false;
  385. }
  386. getRequestGroup()->shouldCancelDownloadForSafety();
  387. getRequestGroup()->initPieceStorage();
  388. getPieceStorage()->getDiskAdaptor()->initAndOpenFile();
  389. if(getDownloadContext()->knowsTotalLength()) {
  390. sequence_ = SEQ_DOWNLOAD_ALREADY_COMPLETED;
  391. getPieceStorage()->markAllPiecesDone();
  392. poolConnection();
  393. return false;
  394. }
  395. // We have to make sure that command that has Request object must
  396. // have segment after PieceStorage is initialized. See
  397. // AbstractCommand::execute()
  398. getSegmentMan()->getSegmentWithIndex(getCuid(), 0);
  399. return true;
  400. } else {
  401. SharedHandle<BtProgressInfoFile> progressInfoFile
  402. (new DefaultBtProgressInfoFile
  403. (getDownloadContext(), SharedHandle<PieceStorage>(), getOption().get()));
  404. getRequestGroup()->adjustFilename(progressInfoFile);
  405. getRequestGroup()->initPieceStorage();
  406. if(getOption()->getAsBool(PREF_DRY_RUN)) {
  407. onDryRunFileFound();
  408. return false;
  409. }
  410. SharedHandle<CheckIntegrityEntry> checkIntegrityEntry =
  411. getRequestGroup()->createCheckIntegrityEntry();
  412. if(!checkIntegrityEntry) {
  413. sequence_ = SEQ_DOWNLOAD_ALREADY_COMPLETED;
  414. poolConnection();
  415. return false;
  416. }
  417. checkIntegrityEntry->pushNextCommand(this);
  418. // We have to make sure that command that has Request object must
  419. // have segment after PieceStorage is initialized. See
  420. // AbstractCommand::execute()
  421. getSegmentMan()->getSegmentWithIndex(getCuid(), 0);
  422. prepareForNextAction(checkIntegrityEntry);
  423. disableReadCheckSocket();
  424. }
  425. return false;
  426. }
  427. bool FtpNegotiationCommand::recvSize() {
  428. uint64_t size = 0;
  429. unsigned int status = ftp_->receiveSizeResponse(size);
  430. if(status == 0) {
  431. return false;
  432. }
  433. if(status == 213) {
  434. if(size > INT64_MAX) {
  435. throw DL_ABORT_EX2
  436. (fmt(EX_TOO_LARGE_FILE,
  437. util::uitos(size, true).c_str()),
  438. error_code::FTP_PROTOCOL_ERROR);
  439. }
  440. if(!getPieceStorage()) {
  441. sequence_ = SEQ_FILE_PREPARATION;
  442. return onFileSizeDetermined(size);
  443. } else {
  444. getRequestGroup()->validateTotalLength(getFileEntry()->getLength(), size);
  445. }
  446. } else {
  447. A2_LOG_INFO(fmt("CUID#%lld - The remote FTP Server doesn't recognize SIZE"
  448. " command. Continue.", getCuid()));
  449. // Even if one of the other servers waiting in the queue supports SIZE
  450. // command, resuming and segmented downloading are disabled when the first
  451. // contacted FTP server doesn't support it.
  452. if(!getPieceStorage()) {
  453. getDownloadContext()->markTotalLengthIsUnknown();
  454. return onFileSizeDetermined(0);
  455. }
  456. // TODO Skipping RequestGroup::validateTotalLength(0) here will allow
  457. // wrong file to be downloaded if user-specified URL is wrong.
  458. }
  459. if(getOption()->getAsBool(PREF_FTP_PASV)) {
  460. sequence_ = SEQ_PREPARE_PASV;
  461. } else {
  462. sequence_ = SEQ_PREPARE_PORT;
  463. }
  464. return true;
  465. }
  466. void FtpNegotiationCommand::afterFileAllocation()
  467. {
  468. setReadCheckSocket(getSocket());
  469. }
  470. bool FtpNegotiationCommand::preparePort() {
  471. afterFileAllocation();
  472. if(getSocket()->getAddressFamily() == AF_INET6) {
  473. sequence_ = SEQ_PREPARE_SERVER_SOCKET_EPRT;
  474. } else {
  475. sequence_ = SEQ_PREPARE_SERVER_SOCKET;
  476. }
  477. return true;
  478. }
  479. bool FtpNegotiationCommand::prepareServerSocketEprt() {
  480. serverSocket_ = ftp_->createServerSocket();
  481. sequence_ = SEQ_SEND_EPRT;
  482. return true;
  483. }
  484. bool FtpNegotiationCommand::prepareServerSocket()
  485. {
  486. serverSocket_ = ftp_->createServerSocket();
  487. sequence_ = SEQ_SEND_PORT;
  488. return true;
  489. }
  490. bool FtpNegotiationCommand::sendEprt() {
  491. if(ftp_->sendEprt(serverSocket_)) {
  492. disableWriteCheckSocket();
  493. sequence_ = SEQ_RECV_EPRT;
  494. } else {
  495. setWriteCheckSocket(getSocket());
  496. }
  497. return false;
  498. }
  499. bool FtpNegotiationCommand::recvEprt() {
  500. unsigned int status = ftp_->receiveResponse();
  501. if(status == 0) {
  502. return false;
  503. }
  504. if(status == 200) {
  505. sequence_ = SEQ_SEND_REST;
  506. } else {
  507. sequence_ = SEQ_PREPARE_SERVER_SOCKET;
  508. }
  509. return true;
  510. }
  511. bool FtpNegotiationCommand::sendPort() {
  512. if(ftp_->sendPort(serverSocket_)) {
  513. disableWriteCheckSocket();
  514. sequence_ = SEQ_RECV_PORT;
  515. } else {
  516. setWriteCheckSocket(getSocket());
  517. }
  518. return false;
  519. }
  520. bool FtpNegotiationCommand::recvPort() {
  521. unsigned int status = ftp_->receiveResponse();
  522. if(status == 0) {
  523. return false;
  524. }
  525. if(status != 200) {
  526. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
  527. error_code::FTP_PROTOCOL_ERROR);
  528. }
  529. sequence_ = SEQ_SEND_REST;
  530. return true;
  531. }
  532. bool FtpNegotiationCommand::preparePasv() {
  533. afterFileAllocation();
  534. if(getSocket()->getAddressFamily() == AF_INET6) {
  535. sequence_ = SEQ_SEND_EPSV;
  536. } else {
  537. sequence_ = SEQ_SEND_PASV;
  538. }
  539. return true;
  540. }
  541. bool FtpNegotiationCommand::sendEpsv() {
  542. if(ftp_->sendEpsv()) {
  543. disableWriteCheckSocket();
  544. sequence_ = SEQ_RECV_EPSV;
  545. } else {
  546. setWriteCheckSocket(getSocket());
  547. }
  548. return true;
  549. }
  550. bool FtpNegotiationCommand::recvEpsv() {
  551. uint16_t port;
  552. unsigned int status = ftp_->receiveEpsvResponse(port);
  553. if(status == 0) {
  554. return false;
  555. }
  556. if(status == 229) {
  557. std::pair<std::string, uint16_t> peerInfo;
  558. getSocket()->getPeerInfo(peerInfo);
  559. peerInfo.second = port;
  560. dataConnAddr_ = peerInfo;
  561. return preparePasvConnect();
  562. } else {
  563. sequence_ = SEQ_SEND_PASV;
  564. return true;
  565. }
  566. }
  567. bool FtpNegotiationCommand::sendPasv() {
  568. if(ftp_->sendPasv()) {
  569. disableWriteCheckSocket();
  570. sequence_ = SEQ_RECV_PASV;
  571. } else {
  572. setWriteCheckSocket(getSocket());
  573. }
  574. return false;
  575. }
  576. bool FtpNegotiationCommand::recvPasv() {
  577. std::pair<std::string, uint16_t> dest;
  578. unsigned int status = ftp_->receivePasvResponse(dest);
  579. if(status == 0) {
  580. return false;
  581. }
  582. if(status != 227) {
  583. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
  584. error_code::FTP_PROTOCOL_ERROR);
  585. }
  586. dataConnAddr_ = dest;
  587. return preparePasvConnect();
  588. }
  589. bool FtpNegotiationCommand::preparePasvConnect() {
  590. // TODO Should we check to see that dataConnAddr_.first is not in
  591. // noProxy list?
  592. if(isProxyDefined()) {
  593. sequence_ = SEQ_RESOLVE_PROXY;
  594. return true;
  595. } else {
  596. // make a data connection to the server.
  597. A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER,
  598. getCuid(),
  599. dataConnAddr_.first.c_str(),
  600. dataConnAddr_.second));
  601. dataSocket_.reset(new SocketCore());
  602. dataSocket_->establishConnection(dataConnAddr_.first, dataConnAddr_.second);
  603. disableReadCheckSocket();
  604. setWriteCheckSocket(dataSocket_);
  605. sequence_ = SEQ_SEND_REST_PASV;
  606. return false;
  607. }
  608. }
  609. bool FtpNegotiationCommand::resolveProxy()
  610. {
  611. SharedHandle<Request> proxyReq = createProxyRequest();
  612. std::vector<std::string> addrs;
  613. proxyAddr_ = resolveHostname
  614. (addrs, proxyReq->getHost(), proxyReq->getPort());
  615. if(proxyAddr_.empty()) {
  616. return false;
  617. }
  618. A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER,
  619. getCuid(),
  620. proxyAddr_.c_str(), proxyReq->getPort()));
  621. dataSocket_.reset(new SocketCore());
  622. dataSocket_->establishConnection(proxyAddr_, proxyReq->getPort());
  623. disableReadCheckSocket();
  624. setWriteCheckSocket(dataSocket_);
  625. SharedHandle<SocketRecvBuffer> socketRecvBuffer
  626. (new SocketRecvBuffer(dataSocket_));
  627. http_.reset(new HttpConnection(getCuid(), dataSocket_, socketRecvBuffer));
  628. sequence_ = SEQ_SEND_TUNNEL_REQUEST;
  629. return false;
  630. }
  631. bool FtpNegotiationCommand::sendTunnelRequest()
  632. {
  633. if(http_->sendBufferIsEmpty()) {
  634. if(dataSocket_->isReadable(0)) {
  635. std::string error = getSocket()->getSocketError();
  636. if(!error.empty()) {
  637. SharedHandle<Request> proxyReq = createProxyRequest();
  638. getDownloadEngine()->markBadIPAddress(proxyReq->getHost(),
  639. proxyAddr_,proxyReq->getPort());
  640. std::string nextProxyAddr = getDownloadEngine()->findCachedIPAddress
  641. (proxyReq->getHost(), proxyReq->getPort());
  642. if(nextProxyAddr.empty()) {
  643. getDownloadEngine()->removeCachedIPAddress(proxyReq->getHost(),
  644. proxyReq->getPort());
  645. throw DL_RETRY_EX
  646. (fmt(MSG_ESTABLISHING_CONNECTION_FAILED,
  647. error.c_str()));
  648. } else {
  649. A2_LOG_INFO(fmt(MSG_CONNECT_FAILED_AND_RETRY,
  650. getCuid(),
  651. proxyAddr_.c_str(), proxyReq->getPort()));
  652. proxyAddr_ = nextProxyAddr;
  653. A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER,
  654. getCuid(),
  655. proxyAddr_.c_str(), proxyReq->getPort()));
  656. dataSocket_->establishConnection(proxyAddr_, proxyReq->getPort());
  657. return false;
  658. }
  659. }
  660. }
  661. SharedHandle<HttpRequest> httpRequest(new HttpRequest());
  662. httpRequest->setUserAgent(getOption()->get(PREF_USER_AGENT));
  663. SharedHandle<Request> req(new Request());
  664. // Construct fake URI in order to use HttpRequest
  665. req->setUri(strconcat("ftp://", dataConnAddr_.first,
  666. A2STR::COLON_C, util::uitos(dataConnAddr_.second)));
  667. httpRequest->setRequest(req);
  668. httpRequest->setProxyRequest(createProxyRequest());
  669. http_->sendProxyRequest(httpRequest);
  670. } else {
  671. http_->sendPendingData();
  672. }
  673. if(http_->sendBufferIsEmpty()) {
  674. disableWriteCheckSocket();
  675. setReadCheckSocket(dataSocket_);
  676. sequence_ = SEQ_RECV_TUNNEL_RESPONSE;
  677. return false;
  678. } else {
  679. setWriteCheckSocket(dataSocket_);
  680. return false;
  681. }
  682. }
  683. bool FtpNegotiationCommand::recvTunnelResponse()
  684. {
  685. SharedHandle<HttpResponse> httpResponse = http_->receiveResponse();
  686. if(!httpResponse) {
  687. return false;
  688. }
  689. if(httpResponse->getStatusCode() != 200) {
  690. throw DL_RETRY_EX(EX_PROXY_CONNECTION_FAILED);
  691. }
  692. sequence_ = SEQ_SEND_REST_PASV;
  693. return true;
  694. }
  695. bool FtpNegotiationCommand::sendRestPasv(const SharedHandle<Segment>& segment) {
  696. //dataSocket_->setBlockingMode();
  697. // Check connection is made properly
  698. if(dataSocket_->isReadable(0)) {
  699. std::string error = dataSocket_->getSocketError();
  700. throw DL_ABORT_EX2
  701. (fmt(MSG_ESTABLISHING_CONNECTION_FAILED, error.c_str()),
  702. error_code::FTP_PROTOCOL_ERROR);
  703. }
  704. setReadCheckSocket(getSocket());
  705. disableWriteCheckSocket();
  706. return sendRest(segment);
  707. }
  708. bool FtpNegotiationCommand::sendRest(const SharedHandle<Segment>& segment) {
  709. if(ftp_->sendRest(segment)) {
  710. disableWriteCheckSocket();
  711. sequence_ = SEQ_RECV_REST;
  712. } else {
  713. setWriteCheckSocket(getSocket());
  714. }
  715. return false;
  716. }
  717. bool FtpNegotiationCommand::recvRest(const SharedHandle<Segment>& segment) {
  718. unsigned int status = ftp_->receiveResponse();
  719. if(status == 0) {
  720. return false;
  721. }
  722. // If we recieve negative response and requested file position is not 0,
  723. // then throw exception here.
  724. if(status != 350) {
  725. if(segment && segment->getPositionToWrite() != 0) {
  726. throw DL_ABORT_EX2("FTP server doesn't support resuming.",
  727. error_code::CANNOT_RESUME);
  728. }
  729. }
  730. sequence_ = SEQ_SEND_RETR;
  731. return true;
  732. }
  733. bool FtpNegotiationCommand::sendRetr() {
  734. if(ftp_->sendRetr()) {
  735. disableWriteCheckSocket();
  736. sequence_ = SEQ_RECV_RETR;
  737. } else {
  738. setWriteCheckSocket(getSocket());
  739. }
  740. return false;
  741. }
  742. bool FtpNegotiationCommand::recvRetr() {
  743. unsigned int status = ftp_->receiveResponse();
  744. if(status == 0) {
  745. return false;
  746. }
  747. if(status != 150 && status != 125) {
  748. getRequestGroup()->increaseAndValidateFileNotFoundCount();
  749. if (status == 550)
  750. throw DL_ABORT_EX2(MSG_RESOURCE_NOT_FOUND,
  751. error_code::RESOURCE_NOT_FOUND);
  752. else
  753. throw DL_ABORT_EX2(fmt(EX_BAD_STATUS, status),
  754. error_code::FTP_PROTOCOL_ERROR);
  755. }
  756. if(getOption()->getAsBool(PREF_FTP_PASV)) {
  757. sequence_ = SEQ_NEGOTIATION_COMPLETED;
  758. return false;
  759. } else {
  760. disableReadCheckSocket();
  761. setReadCheckSocket(serverSocket_);
  762. sequence_ = SEQ_WAIT_CONNECTION;
  763. return false;
  764. }
  765. }
  766. bool FtpNegotiationCommand::waitConnection()
  767. {
  768. disableReadCheckSocket();
  769. setReadCheckSocket(getSocket());
  770. dataSocket_.reset(serverSocket_->acceptConnection());
  771. dataSocket_->setNonBlockingMode();
  772. sequence_ = SEQ_NEGOTIATION_COMPLETED;
  773. return false;
  774. }
  775. bool FtpNegotiationCommand::processSequence
  776. (const SharedHandle<Segment>& segment) {
  777. bool doNextSequence = true;
  778. switch(sequence_) {
  779. case SEQ_RECV_GREETING:
  780. return recvGreeting();
  781. case SEQ_SEND_USER:
  782. return sendUser();
  783. case SEQ_RECV_USER:
  784. return recvUser();
  785. case SEQ_SEND_PASS:
  786. return sendPass();
  787. case SEQ_RECV_PASS:
  788. return recvPass();
  789. case SEQ_SEND_TYPE:
  790. return sendType();
  791. case SEQ_RECV_TYPE:
  792. return recvType();
  793. case SEQ_SEND_PWD:
  794. return sendPwd();
  795. case SEQ_RECV_PWD:
  796. return recvPwd();
  797. case SEQ_SEND_CWD_PREP:
  798. return sendCwdPrep();
  799. case SEQ_SEND_CWD:
  800. return sendCwd();
  801. case SEQ_RECV_CWD:
  802. return recvCwd();
  803. case SEQ_SEND_MDTM:
  804. return sendMdtm();
  805. case SEQ_RECV_MDTM:
  806. return recvMdtm();
  807. case SEQ_SEND_SIZE:
  808. return sendSize();
  809. case SEQ_RECV_SIZE:
  810. return recvSize();
  811. case SEQ_PREPARE_PORT:
  812. return preparePort();
  813. case SEQ_PREPARE_SERVER_SOCKET_EPRT:
  814. return prepareServerSocketEprt();
  815. case SEQ_SEND_EPRT:
  816. return sendEprt();
  817. case SEQ_RECV_EPRT:
  818. return recvEprt();
  819. case SEQ_PREPARE_SERVER_SOCKET:
  820. return prepareServerSocket();
  821. case SEQ_SEND_PORT:
  822. return sendPort();
  823. case SEQ_RECV_PORT:
  824. return recvPort();
  825. case SEQ_PREPARE_PASV:
  826. return preparePasv();
  827. case SEQ_SEND_EPSV:
  828. return sendEpsv();
  829. case SEQ_RECV_EPSV:
  830. return recvEpsv();
  831. case SEQ_SEND_PASV:
  832. return sendPasv();
  833. case SEQ_RECV_PASV:
  834. return recvPasv();
  835. case SEQ_RESOLVE_PROXY:
  836. return resolveProxy();
  837. case SEQ_SEND_TUNNEL_REQUEST:
  838. return sendTunnelRequest();
  839. case SEQ_RECV_TUNNEL_RESPONSE:
  840. return recvTunnelResponse();
  841. case SEQ_SEND_REST_PASV:
  842. return sendRestPasv(segment);
  843. case SEQ_SEND_REST:
  844. return sendRest(segment);
  845. case SEQ_RECV_REST:
  846. return recvRest(segment);
  847. case SEQ_SEND_RETR:
  848. return sendRetr();
  849. case SEQ_RECV_RETR:
  850. return recvRetr();
  851. case SEQ_WAIT_CONNECTION:
  852. return waitConnection();
  853. default:
  854. abort();
  855. }
  856. return doNextSequence;
  857. }
  858. void FtpNegotiationCommand::poolConnection() const
  859. {
  860. if(getOption()->getAsBool(PREF_FTP_REUSE_CONNECTION)) {
  861. std::map<std::string, std::string> options;
  862. options["baseWorkingDir"] = ftp_->getBaseWorkingDir();
  863. getDownloadEngine()->poolSocket(getRequest(), ftp_->getUser(),
  864. createProxyRequest(), getSocket(), options);
  865. }
  866. }
  867. void FtpNegotiationCommand::onDryRunFileFound()
  868. {
  869. getPieceStorage()->markAllPiecesDone();
  870. getDownloadContext()->setChecksumVerified(true);
  871. poolConnection();
  872. sequence_ = SEQ_HEAD_OK;
  873. }
  874. } // namespace aria2