FtpNegotiationCommand.cc 27 KB

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