FtpNegotiationCommand.cc 26 KB

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