FtpNegotiationCommand.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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. BtProgressInfoFileHandle infoFile(new DefaultBtProgressInfoFile(_requestGroup->getDownloadContext(), _requestGroup->getPieceStorage(), e->option));
  319. if(!infoFile->exists() && _requestGroup->downloadFinishedByFileLength()) {
  320. sequence = SEQ_DOWNLOAD_ALREADY_COMPLETED;
  321. poolConnection();
  322. return false;
  323. }
  324. _requestGroup->loadAndOpenFile(infoFile);
  325. prepareForNextAction(this);
  326. disableReadCheckSocket();
  327. }
  328. return false;
  329. }
  330. bool FtpNegotiationCommand::recvSize() {
  331. uint64_t size = 0;
  332. unsigned int status = ftp->receiveSizeResponse(size);
  333. if(status == 0) {
  334. return false;
  335. }
  336. if(status == 213) {
  337. if(size > INT64_MAX) {
  338. throw DlAbortEx
  339. (StringFormat(EX_TOO_LARGE_FILE, Util::uitos(size, true).c_str()).str());
  340. }
  341. if(_requestGroup->getPieceStorage().isNull()) {
  342. sequence = SEQ_FILE_PREPARATION;
  343. return onFileSizeDetermined(size);
  344. } else {
  345. _requestGroup->validateTotalLength(size);
  346. }
  347. } else {
  348. logger->info("CUID#%d - The remote FTP Server doesn't recognize SIZE command. Continue.", cuid);
  349. // Even if one of the other servers waiting in the queue supports SIZE
  350. // command, resuming and segmented downloading are disabled when the first
  351. // contacted FTP server doesn't support it.
  352. if(_requestGroup->getPieceStorage().isNull()) {
  353. if(e->option->getAsBool(PREF_FTP_PASV)) {
  354. sequence = SEQ_SEND_PASV;
  355. } else {
  356. sequence = SEQ_PREPARE_SERVER_SOCKET;
  357. }
  358. return onFileSizeDetermined(0);
  359. }
  360. // TODO Skipping RequestGroup::validateTotalLength(0) here will allow
  361. // wrong file to be downloaded if user-specified URL is wrong.
  362. }
  363. if(e->option->getAsBool(PREF_FTP_PASV)) {
  364. sequence = SEQ_SEND_PASV;
  365. } else {
  366. sequence = SEQ_PREPARE_SERVER_SOCKET;
  367. }
  368. return true;
  369. }
  370. void FtpNegotiationCommand::afterFileAllocation()
  371. {
  372. setReadCheckSocket(socket);
  373. }
  374. bool FtpNegotiationCommand::prepareServerSocket()
  375. {
  376. serverSocket = ftp->createServerSocket();
  377. sequence = SEQ_SEND_PORT;
  378. return true;
  379. }
  380. bool FtpNegotiationCommand::sendPort() {
  381. afterFileAllocation();
  382. if(ftp->sendPort(serverSocket)) {
  383. disableWriteCheckSocket();
  384. sequence = SEQ_RECV_PORT;
  385. } else {
  386. setWriteCheckSocket(socket);
  387. }
  388. return false;
  389. }
  390. bool FtpNegotiationCommand::recvPort() {
  391. unsigned int status = ftp->receiveResponse();
  392. if(status == 0) {
  393. return false;
  394. }
  395. if(status != 200) {
  396. throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
  397. }
  398. sequence = SEQ_SEND_REST;
  399. return true;
  400. }
  401. bool FtpNegotiationCommand::sendPasv() {
  402. afterFileAllocation();
  403. if(ftp->sendPasv()) {
  404. disableWriteCheckSocket();
  405. sequence = SEQ_RECV_PASV;
  406. } else {
  407. setWriteCheckSocket(socket);
  408. }
  409. return false;
  410. }
  411. bool FtpNegotiationCommand::recvPasv() {
  412. std::pair<std::string, uint16_t> dest;
  413. unsigned int status = ftp->receivePasvResponse(dest);
  414. if(status == 0) {
  415. return false;
  416. }
  417. if(status != 227) {
  418. throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
  419. }
  420. // make a data connection to the server.
  421. logger->info(MSG_CONNECTING_TO_SERVER, cuid,
  422. dest.first.c_str(),
  423. dest.second);
  424. dataSocket.reset(new SocketCore());
  425. dataSocket->establishConnection(dest.first, dest.second);
  426. disableReadCheckSocket();
  427. setWriteCheckSocket(dataSocket);
  428. sequence = SEQ_SEND_REST_PASV;
  429. return false;
  430. }
  431. bool FtpNegotiationCommand::sendRestPasv(const SegmentHandle& segment) {
  432. //dataSocket->setBlockingMode();
  433. setReadCheckSocket(socket);
  434. disableWriteCheckSocket();
  435. return sendRest(segment);
  436. }
  437. bool FtpNegotiationCommand::sendRest(const SegmentHandle& segment) {
  438. if(ftp->sendRest(segment)) {
  439. disableWriteCheckSocket();
  440. sequence = SEQ_RECV_REST;
  441. } else {
  442. setWriteCheckSocket(socket);
  443. }
  444. return false;
  445. }
  446. bool FtpNegotiationCommand::recvRest(const SharedHandle<Segment>& segment) {
  447. unsigned int status = ftp->receiveResponse();
  448. if(status == 0) {
  449. return false;
  450. }
  451. // If we recieve negative response and requested file position is not 0,
  452. // then throw exception here.
  453. if(status != 350) {
  454. if(!segment.isNull() && segment->getPositionToWrite() != 0) {
  455. throw DlAbortEx("FTP server doesn't support resuming.");
  456. }
  457. }
  458. sequence = SEQ_SEND_RETR;
  459. return true;
  460. }
  461. bool FtpNegotiationCommand::sendRetr() {
  462. if(ftp->sendRetr()) {
  463. disableWriteCheckSocket();
  464. sequence = SEQ_RECV_RETR;
  465. } else {
  466. setWriteCheckSocket(socket);
  467. }
  468. return false;
  469. }
  470. bool FtpNegotiationCommand::recvRetr() {
  471. unsigned int status = ftp->receiveResponse();
  472. if(status == 0) {
  473. return false;
  474. }
  475. if(status != 150 && status != 125) {
  476. _requestGroup->increaseAndValidateFileNotFoundCount();
  477. throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
  478. }
  479. if(e->option->getAsBool(PREF_FTP_PASV)) {
  480. sequence = SEQ_NEGOTIATION_COMPLETED;
  481. return false;
  482. } else {
  483. disableReadCheckSocket();
  484. setReadCheckSocket(serverSocket);
  485. sequence = SEQ_WAIT_CONNECTION;
  486. return false;
  487. }
  488. }
  489. bool FtpNegotiationCommand::waitConnection()
  490. {
  491. disableReadCheckSocket();
  492. setReadCheckSocket(socket);
  493. dataSocket.reset(serverSocket->acceptConnection());
  494. //dataSocket->setBlockingMode();
  495. sequence = SEQ_NEGOTIATION_COMPLETED;
  496. return false;
  497. }
  498. bool FtpNegotiationCommand::processSequence(const SegmentHandle& segment) {
  499. bool doNextSequence = true;
  500. switch(sequence) {
  501. case SEQ_RECV_GREETING:
  502. return recvGreeting();
  503. case SEQ_SEND_USER:
  504. return sendUser();
  505. case SEQ_RECV_USER:
  506. return recvUser();
  507. case SEQ_SEND_PASS:
  508. return sendPass();
  509. case SEQ_RECV_PASS:
  510. return recvPass();
  511. case SEQ_SEND_TYPE:
  512. return sendType();
  513. case SEQ_RECV_TYPE:
  514. return recvType();
  515. case SEQ_SEND_PWD:
  516. return sendPwd();
  517. case SEQ_RECV_PWD:
  518. return recvPwd();
  519. case SEQ_SEND_CWD:
  520. return sendCwd();
  521. case SEQ_RECV_CWD:
  522. return recvCwd();
  523. case SEQ_SEND_MDTM:
  524. return sendMdtm();
  525. case SEQ_RECV_MDTM:
  526. return recvMdtm();
  527. case SEQ_SEND_SIZE:
  528. return sendSize();
  529. case SEQ_RECV_SIZE:
  530. return recvSize();
  531. case SEQ_PREPARE_SERVER_SOCKET:
  532. return prepareServerSocket();
  533. case SEQ_SEND_PORT:
  534. return sendPort();
  535. case SEQ_RECV_PORT:
  536. return recvPort();
  537. case SEQ_SEND_PASV:
  538. return sendPasv();
  539. case SEQ_RECV_PASV:
  540. return recvPasv();
  541. case SEQ_SEND_REST_PASV:
  542. return sendRestPasv(segment);
  543. case SEQ_SEND_REST:
  544. return sendRest(segment);
  545. case SEQ_RECV_REST:
  546. return recvRest(segment);
  547. case SEQ_SEND_RETR:
  548. return sendRetr();
  549. case SEQ_RECV_RETR:
  550. return recvRetr();
  551. case SEQ_WAIT_CONNECTION:
  552. return waitConnection();
  553. default:
  554. abort();
  555. }
  556. return doNextSequence;
  557. }
  558. void FtpNegotiationCommand::poolConnection() const
  559. {
  560. if(e->option->getAsBool(PREF_FTP_REUSE_CONNECTION)) {
  561. std::map<std::string, std::string> options;
  562. options["baseWorkingDir"] = ftp->getBaseWorkingDir();
  563. e->poolSocket(req, isProxyDefined(), socket, options);
  564. }
  565. }
  566. } // namespace aria2