FtpNegotiationCommand.cc 27 KB

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