FtpNegotiationCommand.cc 26 KB

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