FtpNegotiationCommand.cc 16 KB

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