FtpNegotiationCommand.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  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 "Request.h"
  37. #include "DownloadEngine.h"
  38. #include "FtpConnection.h"
  39. #include "RequestGroup.h"
  40. #include "PieceStorage.h"
  41. #include "FtpDownloadCommand.h"
  42. #include "FileEntry.h"
  43. #include "DlAbortEx.h"
  44. #include "message.h"
  45. #include "prefs.h"
  46. #include "Util.h"
  47. #include "Option.h"
  48. #include "Logger.h"
  49. #include "Segment.h"
  50. #include "SingleFileDownloadContext.h"
  51. #include "DefaultBtProgressInfoFile.h"
  52. #include "RequestGroupMan.h"
  53. #include "DownloadFailureException.h"
  54. #include "ServerHost.h"
  55. #include "Socket.h"
  56. #include "StringFormat.h"
  57. #include "DiskAdaptor.h"
  58. #include "SegmentMan.h"
  59. #include <stdint.h>
  60. #include <cassert>
  61. #include <utility>
  62. #include <map>
  63. namespace aria2 {
  64. FtpNegotiationCommand::FtpNegotiationCommand(int32_t cuid,
  65. const RequestHandle& req,
  66. RequestGroup* requestGroup,
  67. DownloadEngine* e,
  68. const SocketHandle& s,
  69. Seq seq,
  70. const std::string& baseWorkingDir):
  71. AbstractCommand(cuid, req, requestGroup, e, s), sequence(seq),
  72. ftp(new FtpConnection(cuid, socket, req, e->option))
  73. {
  74. ftp->setBaseWorkingDir(baseWorkingDir);
  75. if(seq == SEQ_RECV_GREETING) {
  76. setTimeout(e->option->getAsInt(PREF_CONNECT_TIMEOUT));
  77. }
  78. disableReadCheckSocket();
  79. setWriteCheckSocket(socket);
  80. }
  81. FtpNegotiationCommand::~FtpNegotiationCommand() {}
  82. bool FtpNegotiationCommand::executeInternal() {
  83. while(processSequence(_segments.front()));
  84. if(sequence == SEQ_RETRY) {
  85. return prepareForRetry(0);
  86. } else if(sequence == SEQ_NEGOTIATION_COMPLETED) {
  87. FtpDownloadCommand* command =
  88. new FtpDownloadCommand(cuid, req, _requestGroup, ftp, e, dataSocket, socket);
  89. command->setMaxDownloadSpeedLimit(e->option->getAsInt(PREF_MAX_DOWNLOAD_LIMIT));
  90. command->setStartupIdleTime(e->option->getAsInt(PREF_STARTUP_IDLE_TIME));
  91. command->setLowestDownloadSpeedLimit(e->option->getAsInt(PREF_LOWEST_SPEED_LIMIT));
  92. if(!_requestGroup->isSingleHostMultiConnectionEnabled()) {
  93. SharedHandle<ServerHost> sv =
  94. _requestGroup->searchServerHost(req->getHost());
  95. if(!sv.isNull()) {
  96. _requestGroup->removeURIWhoseHostnameIs(sv->getHostname());
  97. }
  98. }
  99. e->commands.push_back(command);
  100. return true;
  101. } else if(sequence == SEQ_HEAD_OK || sequence == SEQ_DOWNLOAD_ALREADY_COMPLETED) {
  102. return true;
  103. } else if(sequence == SEQ_FILE_PREPARATION) {
  104. if(e->option->getAsBool(PREF_FTP_PASV)) {
  105. sequence = SEQ_SEND_PASV;
  106. } else {
  107. sequence = SEQ_PREPARE_SERVER_SOCKET;
  108. }
  109. return false;
  110. } else {
  111. e->commands.push_back(this);
  112. return false;
  113. }
  114. }
  115. bool FtpNegotiationCommand::recvGreeting() {
  116. checkIfConnectionEstablished(socket);
  117. setTimeout(e->option->getAsInt(PREF_TIMEOUT));
  118. //socket->setBlockingMode();
  119. disableWriteCheckSocket();
  120. setReadCheckSocket(socket);
  121. unsigned int status = ftp->receiveResponse();
  122. if(status == 0) {
  123. return false;
  124. }
  125. if(status != 220) {
  126. throw DlAbortEx(EX_CONNECTION_FAILED);
  127. }
  128. sequence = SEQ_SEND_USER;
  129. return true;
  130. }
  131. bool FtpNegotiationCommand::sendUser() {
  132. if(ftp->sendUser()) {
  133. disableWriteCheckSocket();
  134. sequence = SEQ_RECV_USER;
  135. } else {
  136. setWriteCheckSocket(socket);
  137. }
  138. return false;
  139. }
  140. bool FtpNegotiationCommand::recvUser() {
  141. unsigned int status = ftp->receiveResponse();
  142. switch(status) {
  143. case 0:
  144. return false;
  145. case 230:
  146. sequence = SEQ_SEND_TYPE;
  147. break;
  148. case 331:
  149. sequence = SEQ_SEND_PASS;
  150. break;
  151. default:
  152. throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
  153. }
  154. return true;
  155. }
  156. bool FtpNegotiationCommand::sendPass() {
  157. if(ftp->sendPass()) {
  158. disableWriteCheckSocket();
  159. sequence = SEQ_RECV_PASS;
  160. } else {
  161. setWriteCheckSocket(socket);
  162. }
  163. return false;
  164. }
  165. bool FtpNegotiationCommand::recvPass() {
  166. unsigned int status = ftp->receiveResponse();
  167. if(status == 0) {
  168. return false;
  169. }
  170. if(status != 230) {
  171. throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
  172. }
  173. sequence = SEQ_SEND_TYPE;
  174. return true;
  175. }
  176. bool FtpNegotiationCommand::sendType() {
  177. if(ftp->sendType()) {
  178. disableWriteCheckSocket();
  179. sequence = SEQ_RECV_TYPE;
  180. } else {
  181. setWriteCheckSocket(socket);
  182. }
  183. return false;
  184. }
  185. bool FtpNegotiationCommand::recvType() {
  186. unsigned int status = ftp->receiveResponse();
  187. if(status == 0) {
  188. return false;
  189. }
  190. if(status != 200) {
  191. throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
  192. }
  193. sequence = SEQ_SEND_PWD;
  194. return true;
  195. }
  196. bool FtpNegotiationCommand::sendPwd()
  197. {
  198. if(ftp->sendPwd()) {
  199. disableWriteCheckSocket();
  200. sequence = SEQ_RECV_PWD;
  201. } else {
  202. setWriteCheckSocket(socket);
  203. }
  204. return false;
  205. }
  206. bool FtpNegotiationCommand::recvPwd()
  207. {
  208. std::string pwd;
  209. unsigned int status = ftp->receivePwdResponse(pwd);
  210. if(status == 0) {
  211. return false;
  212. }
  213. if(status != 257) {
  214. throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
  215. }
  216. ftp->setBaseWorkingDir(pwd);
  217. logger->info("CUID#%d - base working directory is '%s'", cuid, pwd.c_str());
  218. sequence = SEQ_SEND_CWD;
  219. return true;
  220. }
  221. bool FtpNegotiationCommand::sendCwd() {
  222. // Calling setReadCheckSocket() is needed when the socket is reused,
  223. setReadCheckSocket(socket);
  224. if(ftp->sendCwd()) {
  225. disableWriteCheckSocket();
  226. sequence = SEQ_RECV_CWD;
  227. } else {
  228. setWriteCheckSocket(socket);
  229. }
  230. return false;
  231. }
  232. bool FtpNegotiationCommand::recvCwd() {
  233. unsigned int status = ftp->receiveResponse();
  234. if(status == 0) {
  235. return false;
  236. }
  237. if(status != 250) {
  238. poolConnection();
  239. _requestGroup->increaseAndValidateFileNotFoundCount();
  240. throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
  241. }
  242. if(e->option->getAsBool(PREF_REMOTE_TIME)) {
  243. sequence = SEQ_SEND_MDTM;
  244. } else {
  245. sequence = SEQ_SEND_SIZE;
  246. }
  247. return true;
  248. }
  249. bool FtpNegotiationCommand::sendMdtm()
  250. {
  251. if(ftp->sendMdtm()) {
  252. disableWriteCheckSocket();
  253. sequence = SEQ_RECV_MDTM;
  254. } else {
  255. setWriteCheckSocket(socket);
  256. }
  257. return false;
  258. }
  259. bool FtpNegotiationCommand::recvMdtm()
  260. {
  261. Time lastModifiedTime(-1);
  262. unsigned int status = ftp->receiveMdtmResponse(lastModifiedTime);
  263. if(status == 0) {
  264. return false;
  265. }
  266. if(status == 213) {
  267. if(lastModifiedTime.good()) {
  268. _requestGroup->updateLastModifiedTime(lastModifiedTime);
  269. time_t t = lastModifiedTime.getTime();
  270. struct tm* tms = gmtime(&t); // returned struct is statically allocated.
  271. if(tms) {
  272. logger->debug("MDTM result was parsed as: %s GMT", asctime(tms));
  273. } else {
  274. logger->debug("gmtime() failed for MDTM result.");
  275. }
  276. } else {
  277. logger->debug("MDTM response was returned, but it seems not to be a time"
  278. " value as in specified in RFC3659.");
  279. }
  280. } else {
  281. logger->info("CUID#%d - MDTM command failed.", cuid);
  282. }
  283. sequence = SEQ_SEND_SIZE;
  284. return true;
  285. }
  286. bool FtpNegotiationCommand::sendSize() {
  287. if(ftp->sendSize()) {
  288. disableWriteCheckSocket();
  289. sequence = SEQ_RECV_SIZE;
  290. } else {
  291. setWriteCheckSocket(socket);
  292. }
  293. return false;
  294. }
  295. bool FtpNegotiationCommand::onFileSizeDetermined(uint64_t totalLength)
  296. {
  297. SingleFileDownloadContextHandle dctx =
  298. dynamic_pointer_cast<SingleFileDownloadContext>(_requestGroup->getDownloadContext());
  299. dctx->setTotalLength(totalLength);
  300. dctx->setFilename(Util::urldecode(req->getFile()));
  301. _requestGroup->preDownloadProcessing();
  302. if(e->_requestGroupMan->isSameFileBeingDownloaded(_requestGroup)) {
  303. throw DownloadFailureException
  304. (StringFormat(EX_DUPLICATE_FILE_DOWNLOAD,
  305. _requestGroup->getFilePath().c_str()).str());
  306. }
  307. if(totalLength == 0) {
  308. _requestGroup->initPieceStorage();
  309. _requestGroup->shouldCancelDownloadForSafety();
  310. _requestGroup->getPieceStorage()->getDiskAdaptor()->initAndOpenFile();
  311. return true;
  312. } else {
  313. _requestGroup->initPieceStorage();
  314. // TODO Is this really necessary?
  315. if(req->getMethod() == Request::METHOD_HEAD) {
  316. sequence = SEQ_HEAD_OK;
  317. return false;
  318. }
  319. BtProgressInfoFileHandle infoFile(new DefaultBtProgressInfoFile(_requestGroup->getDownloadContext(), _requestGroup->getPieceStorage(), e->option));
  320. if(!infoFile->exists() && _requestGroup->downloadFinishedByFileLength()) {
  321. sequence = SEQ_DOWNLOAD_ALREADY_COMPLETED;
  322. poolConnection();
  323. return false;
  324. }
  325. _requestGroup->loadAndOpenFile(infoFile);
  326. prepareForNextAction(this);
  327. disableReadCheckSocket();
  328. }
  329. return false;
  330. }
  331. bool FtpNegotiationCommand::recvSize() {
  332. uint64_t size = 0;
  333. unsigned int status = ftp->receiveSizeResponse(size);
  334. if(status == 0) {
  335. return false;
  336. }
  337. if(status == 213) {
  338. if(size > INT64_MAX) {
  339. throw DlAbortEx
  340. (StringFormat(EX_TOO_LARGE_FILE, Util::uitos(size, true).c_str()).str());
  341. }
  342. if(_requestGroup->getPieceStorage().isNull()) {
  343. sequence = SEQ_FILE_PREPARATION;
  344. return onFileSizeDetermined(size);
  345. } else {
  346. _requestGroup->validateTotalLength(size);
  347. }
  348. } else {
  349. logger->info("CUID#%d - The remote FTP Server doesn't recognize SIZE command. Continue.", cuid);
  350. // Even if one of the other servers waiting in the queue supports SIZE
  351. // command, resuming and segmented downloading are disabled when the first
  352. // contacted FTP server doesn't support it.
  353. if(_requestGroup->getPieceStorage().isNull()) {
  354. if(e->option->getAsBool(PREF_FTP_PASV)) {
  355. sequence = SEQ_SEND_PASV;
  356. } else {
  357. sequence = SEQ_PREPARE_SERVER_SOCKET;
  358. }
  359. return onFileSizeDetermined(0);
  360. }
  361. // TODO Skipping RequestGroup::validateTotalLength(0) here will allow
  362. // wrong file to be downloaded if user-specified URL is wrong.
  363. }
  364. if(e->option->getAsBool(PREF_FTP_PASV)) {
  365. sequence = SEQ_SEND_PASV;
  366. } else {
  367. sequence = SEQ_PREPARE_SERVER_SOCKET;
  368. }
  369. return true;
  370. }
  371. void FtpNegotiationCommand::afterFileAllocation()
  372. {
  373. setReadCheckSocket(socket);
  374. }
  375. bool FtpNegotiationCommand::prepareServerSocket()
  376. {
  377. serverSocket = ftp->createServerSocket();
  378. sequence = SEQ_SEND_PORT;
  379. return true;
  380. }
  381. bool FtpNegotiationCommand::sendPort() {
  382. afterFileAllocation();
  383. if(ftp->sendPort(serverSocket)) {
  384. disableWriteCheckSocket();
  385. sequence = SEQ_RECV_PORT;
  386. } else {
  387. setWriteCheckSocket(socket);
  388. }
  389. return false;
  390. }
  391. bool FtpNegotiationCommand::recvPort() {
  392. unsigned int status = ftp->receiveResponse();
  393. if(status == 0) {
  394. return false;
  395. }
  396. if(status != 200) {
  397. throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
  398. }
  399. sequence = SEQ_SEND_REST;
  400. return true;
  401. }
  402. bool FtpNegotiationCommand::sendPasv() {
  403. afterFileAllocation();
  404. if(ftp->sendPasv()) {
  405. disableWriteCheckSocket();
  406. sequence = SEQ_RECV_PASV;
  407. } else {
  408. setWriteCheckSocket(socket);
  409. }
  410. return false;
  411. }
  412. bool FtpNegotiationCommand::recvPasv() {
  413. std::pair<std::string, uint16_t> dest;
  414. unsigned int status = ftp->receivePasvResponse(dest);
  415. if(status == 0) {
  416. return false;
  417. }
  418. if(status != 227) {
  419. throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
  420. }
  421. // make a data connection to the server.
  422. logger->info(MSG_CONNECTING_TO_SERVER, cuid,
  423. dest.first.c_str(),
  424. dest.second);
  425. dataSocket.reset(new SocketCore());
  426. dataSocket->establishConnection(dest.first, dest.second);
  427. disableReadCheckSocket();
  428. setWriteCheckSocket(dataSocket);
  429. sequence = SEQ_SEND_REST_PASV;
  430. return false;
  431. }
  432. bool FtpNegotiationCommand::sendRestPasv(const SegmentHandle& segment) {
  433. //dataSocket->setBlockingMode();
  434. setReadCheckSocket(socket);
  435. disableWriteCheckSocket();
  436. return sendRest(segment);
  437. }
  438. bool FtpNegotiationCommand::sendRest(const SegmentHandle& segment) {
  439. if(ftp->sendRest(segment)) {
  440. disableWriteCheckSocket();
  441. sequence = SEQ_RECV_REST;
  442. } else {
  443. setWriteCheckSocket(socket);
  444. }
  445. return false;
  446. }
  447. bool FtpNegotiationCommand::recvRest(const SharedHandle<Segment>& segment) {
  448. unsigned int status = ftp->receiveResponse();
  449. if(status == 0) {
  450. return false;
  451. }
  452. // If we recieve negative response and requested file position is not 0,
  453. // then throw exception here.
  454. if(status != 350) {
  455. if(!segment.isNull() && segment->getPositionToWrite() != 0) {
  456. throw DlAbortEx("FTP server doesn't support resuming.");
  457. }
  458. }
  459. sequence = SEQ_SEND_RETR;
  460. return true;
  461. }
  462. bool FtpNegotiationCommand::sendRetr() {
  463. if(ftp->sendRetr()) {
  464. disableWriteCheckSocket();
  465. sequence = SEQ_RECV_RETR;
  466. } else {
  467. setWriteCheckSocket(socket);
  468. }
  469. return false;
  470. }
  471. bool FtpNegotiationCommand::recvRetr() {
  472. unsigned int status = ftp->receiveResponse();
  473. if(status == 0) {
  474. return false;
  475. }
  476. if(status != 150 && status != 125) {
  477. _requestGroup->increaseAndValidateFileNotFoundCount();
  478. throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
  479. }
  480. if(e->option->getAsBool(PREF_FTP_PASV)) {
  481. sequence = SEQ_NEGOTIATION_COMPLETED;
  482. return false;
  483. } else {
  484. disableReadCheckSocket();
  485. setReadCheckSocket(serverSocket);
  486. sequence = SEQ_WAIT_CONNECTION;
  487. return false;
  488. }
  489. }
  490. bool FtpNegotiationCommand::waitConnection()
  491. {
  492. disableReadCheckSocket();
  493. setReadCheckSocket(socket);
  494. dataSocket.reset(serverSocket->acceptConnection());
  495. //dataSocket->setBlockingMode();
  496. sequence = SEQ_NEGOTIATION_COMPLETED;
  497. return false;
  498. }
  499. bool FtpNegotiationCommand::processSequence(const SegmentHandle& segment) {
  500. bool doNextSequence = true;
  501. switch(sequence) {
  502. case SEQ_RECV_GREETING:
  503. return recvGreeting();
  504. case SEQ_SEND_USER:
  505. return sendUser();
  506. case SEQ_RECV_USER:
  507. return recvUser();
  508. case SEQ_SEND_PASS:
  509. return sendPass();
  510. case SEQ_RECV_PASS:
  511. return recvPass();
  512. case SEQ_SEND_TYPE:
  513. return sendType();
  514. case SEQ_RECV_TYPE:
  515. return recvType();
  516. case SEQ_SEND_PWD:
  517. return sendPwd();
  518. case SEQ_RECV_PWD:
  519. return recvPwd();
  520. case SEQ_SEND_CWD:
  521. return sendCwd();
  522. case SEQ_RECV_CWD:
  523. return recvCwd();
  524. case SEQ_SEND_MDTM:
  525. return sendMdtm();
  526. case SEQ_RECV_MDTM:
  527. return recvMdtm();
  528. case SEQ_SEND_SIZE:
  529. return sendSize();
  530. case SEQ_RECV_SIZE:
  531. return recvSize();
  532. case SEQ_PREPARE_SERVER_SOCKET:
  533. return prepareServerSocket();
  534. case SEQ_SEND_PORT:
  535. return sendPort();
  536. case SEQ_RECV_PORT:
  537. return recvPort();
  538. case SEQ_SEND_PASV:
  539. return sendPasv();
  540. case SEQ_RECV_PASV:
  541. return recvPasv();
  542. case SEQ_SEND_REST_PASV:
  543. return sendRestPasv(segment);
  544. case SEQ_SEND_REST:
  545. return sendRest(segment);
  546. case SEQ_RECV_REST:
  547. return recvRest(segment);
  548. case SEQ_SEND_RETR:
  549. return sendRetr();
  550. case SEQ_RECV_RETR:
  551. return recvRetr();
  552. case SEQ_WAIT_CONNECTION:
  553. return waitConnection();
  554. default:
  555. abort();
  556. }
  557. return doNextSequence;
  558. }
  559. void FtpNegotiationCommand::poolConnection() const
  560. {
  561. if(!e->option->getAsBool(PREF_HTTP_PROXY_ENABLED) &&
  562. e->option->getAsBool(PREF_FTP_REUSE_CONNECTION)) {
  563. std::pair<std::string, uint16_t> peerInfo;
  564. socket->getPeerInfo(peerInfo);
  565. std::map<std::string, std::string> options;
  566. options["baseWorkingDir"] = ftp->getBaseWorkingDir();
  567. e->poolSocket(peerInfo.first, peerInfo.second, socket, options);
  568. }
  569. }
  570. } // namespace aria2