FtpNegotiationCommand.cc 27 KB

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