FtpNegotiationCommand.cc 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  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. 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. poolConnection();
  394. return false;
  395. }
  396. // We have to make sure that command that has Request object must
  397. // have segment after PieceStorage is initialized. See
  398. // AbstractCommand::execute()
  399. getSegmentMan()->getSegmentWithIndex(getCuid(), 0);
  400. return true;
  401. } else {
  402. getRequestGroup()->adjustFilename
  403. (SharedHandle<BtProgressInfoFile>
  404. (new DefaultBtProgressInfoFile
  405. (getDownloadContext(),
  406. SharedHandle<PieceStorage>(),
  407. getOption().get())));
  408. getRequestGroup()->initPieceStorage();
  409. if(getOption()->getAsBool(PREF_DRY_RUN)) {
  410. onDryRunFileFound();
  411. return false;
  412. }
  413. BtProgressInfoFileHandle infoFile
  414. (new DefaultBtProgressInfoFile(getDownloadContext(),
  415. getPieceStorage(),
  416. getOption().get()));
  417. if(!infoFile->exists() &&
  418. getRequestGroup()->downloadFinishedByFileLength()) {
  419. getPieceStorage()->markAllPiecesDone();
  420. sequence_ = SEQ_DOWNLOAD_ALREADY_COMPLETED;
  421. getLogger()->notice(MSG_DOWNLOAD_ALREADY_COMPLETED,
  422. util::itos(getRequestGroup()->getGID()).c_str(),
  423. getRequestGroup()->getFirstFilePath().c_str());
  424. poolConnection();
  425. return false;
  426. }
  427. getRequestGroup()->loadAndOpenFile(infoFile);
  428. // We have to make sure that command that has Request object must
  429. // have segment after PieceStorage is initialized. See
  430. // AbstractCommand::execute()
  431. getSegmentMan()->getSegmentWithIndex(getCuid(), 0);
  432. prepareForNextAction(this);
  433. disableReadCheckSocket();
  434. }
  435. return false;
  436. }
  437. bool FtpNegotiationCommand::recvSize() {
  438. uint64_t size = 0;
  439. unsigned int status = ftp_->receiveSizeResponse(size);
  440. if(status == 0) {
  441. return false;
  442. }
  443. if(status == 213) {
  444. if(size > INT64_MAX) {
  445. throw DL_ABORT_EX
  446. (StringFormat(EX_TOO_LARGE_FILE,
  447. util::uitos(size, true).c_str()).str());
  448. }
  449. if(getPieceStorage().isNull()) {
  450. sequence_ = SEQ_FILE_PREPARATION;
  451. return onFileSizeDetermined(size);
  452. } else {
  453. getRequestGroup()->validateTotalLength(getFileEntry()->getLength(), size);
  454. }
  455. } else {
  456. if(getLogger()->info()) {
  457. getLogger()->info("CUID#%s - The remote FTP Server doesn't recognize SIZE"
  458. " command. Continue.", util::itos(getCuid()).c_str());
  459. }
  460. // Even if one of the other servers waiting in the queue supports SIZE
  461. // command, resuming and segmented downloading are disabled when the first
  462. // contacted FTP server doesn't support it.
  463. if(getPieceStorage().isNull()) {
  464. getDownloadContext()->markTotalLengthIsUnknown();
  465. return onFileSizeDetermined(0);
  466. }
  467. // TODO Skipping RequestGroup::validateTotalLength(0) here will allow
  468. // wrong file to be downloaded if user-specified URL is wrong.
  469. }
  470. if(getOption()->getAsBool(PREF_FTP_PASV)) {
  471. sequence_ = SEQ_PREPARE_PASV;
  472. } else {
  473. sequence_ = SEQ_PREPARE_PORT;
  474. }
  475. return true;
  476. }
  477. void FtpNegotiationCommand::afterFileAllocation()
  478. {
  479. setReadCheckSocket(getSocket());
  480. }
  481. bool FtpNegotiationCommand::preparePort() {
  482. afterFileAllocation();
  483. if(getSocket()->getAddressFamily() == AF_INET6) {
  484. sequence_ = SEQ_PREPARE_SERVER_SOCKET_EPRT;
  485. } else {
  486. sequence_ = SEQ_PREPARE_SERVER_SOCKET;
  487. }
  488. return true;
  489. }
  490. bool FtpNegotiationCommand::prepareServerSocketEprt() {
  491. serverSocket_ = ftp_->createServerSocket();
  492. sequence_ = SEQ_SEND_EPRT;
  493. return true;
  494. }
  495. bool FtpNegotiationCommand::prepareServerSocket()
  496. {
  497. serverSocket_ = ftp_->createServerSocket();
  498. sequence_ = SEQ_SEND_PORT;
  499. return true;
  500. }
  501. bool FtpNegotiationCommand::sendEprt() {
  502. if(ftp_->sendEprt(serverSocket_)) {
  503. disableWriteCheckSocket();
  504. sequence_ = SEQ_RECV_EPRT;
  505. } else {
  506. setWriteCheckSocket(getSocket());
  507. }
  508. return false;
  509. }
  510. bool FtpNegotiationCommand::recvEprt() {
  511. unsigned int status = ftp_->receiveResponse();
  512. if(status == 0) {
  513. return false;
  514. }
  515. if(status == 200) {
  516. sequence_ = SEQ_SEND_REST;
  517. } else {
  518. sequence_ = SEQ_PREPARE_SERVER_SOCKET;
  519. }
  520. return true;
  521. }
  522. bool FtpNegotiationCommand::sendPort() {
  523. if(ftp_->sendPort(serverSocket_)) {
  524. disableWriteCheckSocket();
  525. sequence_ = SEQ_RECV_PORT;
  526. } else {
  527. setWriteCheckSocket(getSocket());
  528. }
  529. return false;
  530. }
  531. bool FtpNegotiationCommand::recvPort() {
  532. unsigned int status = ftp_->receiveResponse();
  533. if(status == 0) {
  534. return false;
  535. }
  536. if(status != 200) {
  537. throw DL_ABORT_EX(StringFormat(EX_BAD_STATUS, status).str());
  538. }
  539. sequence_ = SEQ_SEND_REST;
  540. return true;
  541. }
  542. bool FtpNegotiationCommand::preparePasv() {
  543. afterFileAllocation();
  544. if(getSocket()->getAddressFamily() == AF_INET6) {
  545. sequence_ = SEQ_SEND_EPSV;
  546. } else {
  547. sequence_ = SEQ_SEND_PASV;
  548. }
  549. return true;
  550. }
  551. bool FtpNegotiationCommand::sendEpsv() {
  552. if(ftp_->sendEpsv()) {
  553. disableWriteCheckSocket();
  554. sequence_ = SEQ_RECV_EPSV;
  555. } else {
  556. setWriteCheckSocket(getSocket());
  557. }
  558. return true;
  559. }
  560. bool FtpNegotiationCommand::recvEpsv() {
  561. uint16_t port;
  562. unsigned int status = ftp_->receiveEpsvResponse(port);
  563. if(status == 0) {
  564. return false;
  565. }
  566. if(status == 229) {
  567. std::pair<std::string, uint16_t> peerInfo;
  568. getSocket()->getPeerInfo(peerInfo);
  569. peerInfo.second = port;
  570. dataConnAddr_ = peerInfo;
  571. return preparePasvConnect();
  572. } else {
  573. sequence_ = SEQ_SEND_PASV;
  574. return true;
  575. }
  576. }
  577. bool FtpNegotiationCommand::sendPasv() {
  578. if(ftp_->sendPasv()) {
  579. disableWriteCheckSocket();
  580. sequence_ = SEQ_RECV_PASV;
  581. } else {
  582. setWriteCheckSocket(getSocket());
  583. }
  584. return false;
  585. }
  586. bool FtpNegotiationCommand::recvPasv() {
  587. std::pair<std::string, uint16_t> dest;
  588. unsigned int status = ftp_->receivePasvResponse(dest);
  589. if(status == 0) {
  590. return false;
  591. }
  592. if(status != 227) {
  593. throw DL_ABORT_EX(StringFormat(EX_BAD_STATUS, status).str());
  594. }
  595. dataConnAddr_ = dest;
  596. return preparePasvConnect();
  597. }
  598. bool FtpNegotiationCommand::preparePasvConnect() {
  599. // TODO Should we check to see that dataConnAddr_.first is not in
  600. // noProxy list?
  601. if(isProxyDefined()) {
  602. sequence_ = SEQ_RESOLVE_PROXY;
  603. return true;
  604. } else {
  605. // make a data connection to the server.
  606. if(getLogger()->info()) {
  607. getLogger()->info(MSG_CONNECTING_TO_SERVER, util::itos(getCuid()).c_str(),
  608. dataConnAddr_.first.c_str(),
  609. dataConnAddr_.second);
  610. }
  611. dataSocket_.reset(new SocketCore());
  612. dataSocket_->establishConnection(dataConnAddr_.first, dataConnAddr_.second);
  613. disableReadCheckSocket();
  614. setWriteCheckSocket(dataSocket_);
  615. sequence_ = SEQ_SEND_REST_PASV;
  616. return false;
  617. }
  618. }
  619. bool FtpNegotiationCommand::resolveProxy()
  620. {
  621. SharedHandle<Request> proxyReq = createProxyRequest();
  622. std::vector<std::string> addrs;
  623. proxyAddr_ = resolveHostname
  624. (addrs, proxyReq->getHost(), proxyReq->getPort());
  625. if(proxyAddr_.empty()) {
  626. return false;
  627. }
  628. if(getLogger()->info()) {
  629. getLogger()->info(MSG_CONNECTING_TO_SERVER, util::itos(getCuid()).c_str(),
  630. proxyAddr_.c_str(), proxyReq->getPort());
  631. }
  632. dataSocket_.reset(new SocketCore());
  633. dataSocket_->establishConnection(proxyAddr_, proxyReq->getPort());
  634. disableReadCheckSocket();
  635. setWriteCheckSocket(dataSocket_);
  636. http_.reset(new HttpConnection(getCuid(), dataSocket_));
  637. sequence_ = SEQ_SEND_TUNNEL_REQUEST;
  638. return false;
  639. }
  640. bool FtpNegotiationCommand::sendTunnelRequest()
  641. {
  642. if(http_->sendBufferIsEmpty()) {
  643. if(dataSocket_->isReadable(0)) {
  644. std::string error = getSocket()->getSocketError();
  645. if(!error.empty()) {
  646. SharedHandle<Request> proxyReq = createProxyRequest();
  647. getDownloadEngine()->markBadIPAddress(proxyReq->getHost(),
  648. proxyAddr_,proxyReq->getPort());
  649. std::string nextProxyAddr = getDownloadEngine()->findCachedIPAddress
  650. (proxyReq->getHost(), proxyReq->getPort());
  651. if(nextProxyAddr.empty()) {
  652. getDownloadEngine()->removeCachedIPAddress(proxyReq->getHost(),
  653. proxyReq->getPort());
  654. throw DL_RETRY_EX
  655. (StringFormat(MSG_ESTABLISHING_CONNECTION_FAILED,
  656. error.c_str()).str());
  657. } else {
  658. if(getLogger()->info()) {
  659. getLogger()->info(MSG_CONNECT_FAILED_AND_RETRY,
  660. util::itos(getCuid()).c_str(),
  661. proxyAddr_.c_str(), proxyReq->getPort());
  662. }
  663. proxyAddr_ = nextProxyAddr;
  664. if(getLogger()->info()) {
  665. getLogger()->info(MSG_CONNECTING_TO_SERVER,
  666. util::itos(getCuid()).c_str(),
  667. proxyAddr_.c_str(), proxyReq->getPort());
  668. }
  669. dataSocket_->establishConnection(proxyAddr_, proxyReq->getPort());
  670. return false;
  671. }
  672. }
  673. }
  674. SharedHandle<HttpRequest> httpRequest(new HttpRequest());
  675. httpRequest->setUserAgent(getOption()->get(PREF_USER_AGENT));
  676. SharedHandle<Request> req(new Request());
  677. // Construct fake URI in order to use HttpRequest
  678. req->setUri(strconcat("ftp://", dataConnAddr_.first,
  679. A2STR::COLON_C, util::uitos(dataConnAddr_.second)));
  680. httpRequest->setRequest(req);
  681. httpRequest->setProxyRequest(createProxyRequest());
  682. http_->sendProxyRequest(httpRequest);
  683. } else {
  684. http_->sendPendingData();
  685. }
  686. if(http_->sendBufferIsEmpty()) {
  687. disableWriteCheckSocket();
  688. setReadCheckSocket(dataSocket_);
  689. sequence_ = SEQ_RECV_TUNNEL_RESPONSE;
  690. return false;
  691. } else {
  692. setWriteCheckSocket(dataSocket_);
  693. return false;
  694. }
  695. }
  696. bool FtpNegotiationCommand::recvTunnelResponse()
  697. {
  698. SharedHandle<HttpResponse> httpResponse = http_->receiveResponse();
  699. if(httpResponse.isNull()) {
  700. return false;
  701. }
  702. if(httpResponse->getResponseStatus() != HttpHeader::S200) {
  703. throw DL_RETRY_EX(EX_PROXY_CONNECTION_FAILED);
  704. }
  705. sequence_ = SEQ_SEND_REST_PASV;
  706. return true;
  707. }
  708. bool FtpNegotiationCommand::sendRestPasv(const SharedHandle<Segment>& segment) {
  709. //dataSocket_->setBlockingMode();
  710. // Check connection is made properly
  711. if(dataSocket_->isReadable(0)) {
  712. std::string error = dataSocket_->getSocketError();
  713. throw DL_ABORT_EX
  714. (StringFormat(MSG_ESTABLISHING_CONNECTION_FAILED, error.c_str()).str());
  715. }
  716. setReadCheckSocket(getSocket());
  717. disableWriteCheckSocket();
  718. return sendRest(segment);
  719. }
  720. bool FtpNegotiationCommand::sendRest(const SharedHandle<Segment>& segment) {
  721. if(ftp_->sendRest(segment)) {
  722. disableWriteCheckSocket();
  723. sequence_ = SEQ_RECV_REST;
  724. } else {
  725. setWriteCheckSocket(getSocket());
  726. }
  727. return false;
  728. }
  729. bool FtpNegotiationCommand::recvRest(const SharedHandle<Segment>& segment) {
  730. unsigned int status = ftp_->receiveResponse();
  731. if(status == 0) {
  732. return false;
  733. }
  734. // If we recieve negative response and requested file position is not 0,
  735. // then throw exception here.
  736. if(status != 350) {
  737. if(!segment.isNull() && segment->getPositionToWrite() != 0) {
  738. throw DL_ABORT_EX2("FTP server doesn't support resuming.",
  739. downloadresultcode::CANNOT_RESUME);
  740. }
  741. }
  742. sequence_ = SEQ_SEND_RETR;
  743. return true;
  744. }
  745. bool FtpNegotiationCommand::sendRetr() {
  746. if(ftp_->sendRetr()) {
  747. disableWriteCheckSocket();
  748. sequence_ = SEQ_RECV_RETR;
  749. } else {
  750. setWriteCheckSocket(getSocket());
  751. }
  752. return false;
  753. }
  754. bool FtpNegotiationCommand::recvRetr() {
  755. unsigned int status = ftp_->receiveResponse();
  756. if(status == 0) {
  757. return false;
  758. }
  759. if(status != 150 && status != 125) {
  760. getRequestGroup()->increaseAndValidateFileNotFoundCount();
  761. if (status == 550)
  762. throw DL_ABORT_EX2(MSG_RESOURCE_NOT_FOUND,
  763. downloadresultcode::RESOURCE_NOT_FOUND);
  764. else
  765. throw DL_ABORT_EX(StringFormat(EX_BAD_STATUS, status).str());
  766. }
  767. if(getOption()->getAsBool(PREF_FTP_PASV)) {
  768. sequence_ = SEQ_NEGOTIATION_COMPLETED;
  769. return false;
  770. } else {
  771. disableReadCheckSocket();
  772. setReadCheckSocket(serverSocket_);
  773. sequence_ = SEQ_WAIT_CONNECTION;
  774. return false;
  775. }
  776. }
  777. bool FtpNegotiationCommand::waitConnection()
  778. {
  779. disableReadCheckSocket();
  780. setReadCheckSocket(getSocket());
  781. dataSocket_.reset(serverSocket_->acceptConnection());
  782. dataSocket_->setNonBlockingMode();
  783. sequence_ = SEQ_NEGOTIATION_COMPLETED;
  784. return false;
  785. }
  786. bool FtpNegotiationCommand::processSequence
  787. (const SharedHandle<Segment>& segment) {
  788. bool doNextSequence = true;
  789. switch(sequence_) {
  790. case SEQ_RECV_GREETING:
  791. return recvGreeting();
  792. case SEQ_SEND_USER:
  793. return sendUser();
  794. case SEQ_RECV_USER:
  795. return recvUser();
  796. case SEQ_SEND_PASS:
  797. return sendPass();
  798. case SEQ_RECV_PASS:
  799. return recvPass();
  800. case SEQ_SEND_TYPE:
  801. return sendType();
  802. case SEQ_RECV_TYPE:
  803. return recvType();
  804. case SEQ_SEND_PWD:
  805. return sendPwd();
  806. case SEQ_RECV_PWD:
  807. return recvPwd();
  808. case SEQ_SEND_CWD_PREP:
  809. return sendCwdPrep();
  810. case SEQ_SEND_CWD:
  811. return sendCwd();
  812. case SEQ_RECV_CWD:
  813. return recvCwd();
  814. case SEQ_SEND_MDTM:
  815. return sendMdtm();
  816. case SEQ_RECV_MDTM:
  817. return recvMdtm();
  818. case SEQ_SEND_SIZE:
  819. return sendSize();
  820. case SEQ_RECV_SIZE:
  821. return recvSize();
  822. case SEQ_PREPARE_PORT:
  823. return preparePort();
  824. case SEQ_PREPARE_SERVER_SOCKET_EPRT:
  825. return prepareServerSocketEprt();
  826. case SEQ_SEND_EPRT:
  827. return sendEprt();
  828. case SEQ_RECV_EPRT:
  829. return recvEprt();
  830. case SEQ_PREPARE_SERVER_SOCKET:
  831. return prepareServerSocket();
  832. case SEQ_SEND_PORT:
  833. return sendPort();
  834. case SEQ_RECV_PORT:
  835. return recvPort();
  836. case SEQ_PREPARE_PASV:
  837. return preparePasv();
  838. case SEQ_SEND_EPSV:
  839. return sendEpsv();
  840. case SEQ_RECV_EPSV:
  841. return recvEpsv();
  842. case SEQ_SEND_PASV:
  843. return sendPasv();
  844. case SEQ_RECV_PASV:
  845. return recvPasv();
  846. case SEQ_RESOLVE_PROXY:
  847. return resolveProxy();
  848. case SEQ_SEND_TUNNEL_REQUEST:
  849. return sendTunnelRequest();
  850. case SEQ_RECV_TUNNEL_RESPONSE:
  851. return recvTunnelResponse();
  852. case SEQ_SEND_REST_PASV:
  853. return sendRestPasv(segment);
  854. case SEQ_SEND_REST:
  855. return sendRest(segment);
  856. case SEQ_RECV_REST:
  857. return recvRest(segment);
  858. case SEQ_SEND_RETR:
  859. return sendRetr();
  860. case SEQ_RECV_RETR:
  861. return recvRetr();
  862. case SEQ_WAIT_CONNECTION:
  863. return waitConnection();
  864. default:
  865. abort();
  866. }
  867. return doNextSequence;
  868. }
  869. void FtpNegotiationCommand::poolConnection() const
  870. {
  871. if(getOption()->getAsBool(PREF_FTP_REUSE_CONNECTION)) {
  872. std::map<std::string, std::string> options;
  873. options["baseWorkingDir"] = ftp_->getBaseWorkingDir();
  874. getDownloadEngine()->poolSocket(getRequest(), ftp_->getUser(),
  875. createProxyRequest(), getSocket(), options);
  876. }
  877. }
  878. void FtpNegotiationCommand::onDryRunFileFound()
  879. {
  880. getPieceStorage()->markAllPiecesDone();
  881. poolConnection();
  882. sequence_ = SEQ_HEAD_OK;
  883. }
  884. } // namespace aria2