FtpNegotiationCommand.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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. namespace aria2 {
  63. FtpNegotiationCommand::FtpNegotiationCommand(int32_t cuid,
  64. const RequestHandle& req,
  65. RequestGroup* requestGroup,
  66. DownloadEngine* e,
  67. const SocketHandle& s,
  68. Seq seq):
  69. AbstractCommand(cuid, req, requestGroup, e, s), sequence(seq),
  70. ftp(new FtpConnection(cuid, socket, req, e->option))
  71. {
  72. disableReadCheckSocket();
  73. setWriteCheckSocket(socket);
  74. }
  75. FtpNegotiationCommand::~FtpNegotiationCommand() {}
  76. bool FtpNegotiationCommand::executeInternal() {
  77. while(processSequence(_segments.front()));
  78. if(sequence == SEQ_RETRY) {
  79. return prepareForRetry(0);
  80. } else if(sequence == SEQ_EXIT) {
  81. return true;
  82. } else if(sequence == SEQ_NEGOTIATION_COMPLETED) {
  83. afterFileAllocation();
  84. FtpDownloadCommand* command =
  85. new FtpDownloadCommand(cuid, req, _requestGroup, ftp, e, dataSocket, socket);
  86. command->setMaxDownloadSpeedLimit(e->option->getAsInt(PREF_MAX_DOWNLOAD_LIMIT));
  87. command->setStartupIdleTime(e->option->getAsInt(PREF_STARTUP_IDLE_TIME));
  88. command->setLowestDownloadSpeedLimit(e->option->getAsInt(PREF_LOWEST_SPEED_LIMIT));
  89. if(!_requestGroup->isSingleHostMultiConnectionEnabled()) {
  90. _requestGroup->removeURIWhoseHostnameIs(_requestGroup->searchServerHost(cuid)->getHostname());
  91. }
  92. e->commands.push_back(command);
  93. return true;
  94. } else if(sequence == SEQ_HEAD_OK || sequence == SEQ_DOWNLOAD_ALREADY_COMPLETED) {
  95. return true;
  96. } else if(sequence == SEQ_FILE_PREPARATION) {
  97. if(e->option->getAsBool(PREF_FTP_PASV)) {
  98. sequence = SEQ_SEND_PASV;
  99. } else {
  100. sequence = SEQ_SEND_PORT;
  101. }
  102. return false;
  103. } else if(sequence == SEQ_FILE_PREPARATION_ON_RETR) {
  104. if(e->option->getAsBool(PREF_FTP_PASV)) {
  105. sequence = SEQ_NEGOTIATION_COMPLETED;
  106. } else {
  107. sequence = SEQ_WAIT_CONNECTION;
  108. }
  109. return false;
  110. } else {
  111. e->commands.push_back(this);
  112. return false;
  113. }
  114. }
  115. bool FtpNegotiationCommand::recvGreeting() {
  116. socket->setBlockingMode();
  117. disableWriteCheckSocket();
  118. setReadCheckSocket(socket);
  119. unsigned int status = ftp->receiveResponse();
  120. if(status == 0) {
  121. return false;
  122. }
  123. if(status != 220) {
  124. throw DlAbortEx(EX_CONNECTION_FAILED);
  125. }
  126. sequence = SEQ_SEND_USER;
  127. return true;
  128. }
  129. bool FtpNegotiationCommand::sendUser() {
  130. ftp->sendUser();
  131. sequence = SEQ_RECV_USER;
  132. return false;
  133. }
  134. bool FtpNegotiationCommand::recvUser() {
  135. unsigned int status = ftp->receiveResponse();
  136. switch(status) {
  137. case 0:
  138. return false;
  139. case 230:
  140. sequence = SEQ_SEND_TYPE;
  141. break;
  142. case 331:
  143. sequence = SEQ_SEND_PASS;
  144. break;
  145. default:
  146. throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
  147. }
  148. return true;
  149. }
  150. bool FtpNegotiationCommand::sendPass() {
  151. ftp->sendPass();
  152. sequence = SEQ_RECV_PASS;
  153. return false;
  154. }
  155. bool FtpNegotiationCommand::recvPass() {
  156. unsigned int status = ftp->receiveResponse();
  157. if(status == 0) {
  158. return false;
  159. }
  160. if(status != 230) {
  161. throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
  162. }
  163. sequence = SEQ_SEND_TYPE;
  164. return true;
  165. }
  166. bool FtpNegotiationCommand::sendType() {
  167. ftp->sendType();
  168. sequence = SEQ_RECV_TYPE;
  169. return false;
  170. }
  171. bool FtpNegotiationCommand::recvType() {
  172. unsigned int status = ftp->receiveResponse();
  173. if(status == 0) {
  174. return false;
  175. }
  176. if(status != 200) {
  177. throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
  178. }
  179. sequence = SEQ_SEND_CWD;
  180. return true;
  181. }
  182. bool FtpNegotiationCommand::sendCwd() {
  183. ftp->sendCwd();
  184. sequence = SEQ_RECV_CWD;
  185. return false;
  186. }
  187. bool FtpNegotiationCommand::recvCwd() {
  188. unsigned int status = ftp->receiveResponse();
  189. if(status == 0) {
  190. return false;
  191. }
  192. if(status != 250) {
  193. poolConnection();
  194. throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
  195. }
  196. sequence = SEQ_SEND_SIZE;
  197. return true;
  198. }
  199. bool FtpNegotiationCommand::sendSize() {
  200. ftp->sendSize();
  201. sequence = SEQ_RECV_SIZE;
  202. return false;
  203. }
  204. bool FtpNegotiationCommand::onFileSizeDetermined(uint64_t totalLength)
  205. {
  206. SingleFileDownloadContextHandle dctx =
  207. dynamic_pointer_cast<SingleFileDownloadContext>(_requestGroup->getDownloadContext());
  208. dctx->setTotalLength(totalLength);
  209. dctx->setFilename(Util::urldecode(req->getFile()));
  210. _requestGroup->preDownloadProcessing();
  211. if(e->_requestGroupMan->isSameFileBeingDownloaded(_requestGroup)) {
  212. throw DownloadFailureException
  213. (StringFormat(EX_DUPLICATE_FILE_DOWNLOAD,
  214. _requestGroup->getFilePath().c_str()).str());
  215. }
  216. if(totalLength == 0) {
  217. _requestGroup->initPieceStorage();
  218. _requestGroup->shouldCancelDownloadForSafety();
  219. _requestGroup->getPieceStorage()->getDiskAdaptor()->initAndOpenFile();
  220. } else {
  221. _requestGroup->initPieceStorage();
  222. // TODO Is this really necessary?
  223. if(req->getMethod() == Request::METHOD_HEAD) {
  224. sequence = SEQ_HEAD_OK;
  225. return false;
  226. }
  227. BtProgressInfoFileHandle infoFile(new DefaultBtProgressInfoFile(_requestGroup->getDownloadContext(), _requestGroup->getPieceStorage(), e->option));
  228. if(!infoFile->exists() && _requestGroup->downloadFinishedByFileLength()) {
  229. sequence = SEQ_DOWNLOAD_ALREADY_COMPLETED;
  230. poolConnection();
  231. return false;
  232. }
  233. _requestGroup->loadAndOpenFile(infoFile);
  234. if(sequence == SEQ_FILE_PREPARATION_ON_RETR) {
  235. // See the transfer is starting from 0 byte.
  236. SharedHandle<Segment> segment =
  237. _requestGroup->getSegmentMan()->getSegment(cuid, 0);
  238. if(!segment.isNull() && segment->getPositionToWrite() == 0) {
  239. prepareForNextAction(this);
  240. } else {
  241. // If not, drop connection and connect the server and send REST
  242. // with appropriate starting position.
  243. logger->debug("Request range is not valid. Re-sending RETR is necessary.");
  244. sequence = SEQ_EXIT;
  245. prepareForNextAction(0);
  246. }
  247. } else {
  248. // At the time of this writing, when this clause is executed,
  249. // sequence should be SEQ_FILE_PREPARATION.
  250. // At this point, REST is not sent yet, so checking the starting byte
  251. // is not necessary.
  252. prepareForNextAction(this);
  253. }
  254. disableReadCheckSocket();
  255. }
  256. return false;
  257. }
  258. bool FtpNegotiationCommand::recvSize() {
  259. uint64_t size = 0;
  260. unsigned int status = ftp->receiveSizeResponse(size);
  261. if(status == 0) {
  262. return false;
  263. }
  264. if(status == 213) {
  265. if(size > INT64_MAX) {
  266. throw DlAbortEx
  267. (StringFormat(EX_TOO_LARGE_FILE, Util::uitos(size, true).c_str()).str());
  268. }
  269. if(_requestGroup->getPieceStorage().isNull()) {
  270. sequence = SEQ_FILE_PREPARATION;
  271. return onFileSizeDetermined(size);
  272. } else {
  273. _requestGroup->validateTotalLength(size);
  274. }
  275. } else {
  276. logger->info("CUID#%d - The remote FTP Server doesn't recognize SIZE command. Continue.", cuid);
  277. }
  278. if(e->option->getAsBool(PREF_FTP_PASV)) {
  279. sequence = SEQ_SEND_PASV;
  280. } else {
  281. sequence = SEQ_SEND_PORT;
  282. }
  283. return true;
  284. }
  285. void FtpNegotiationCommand::afterFileAllocation()
  286. {
  287. setReadCheckSocket(socket);
  288. }
  289. bool FtpNegotiationCommand::sendPort() {
  290. afterFileAllocation();
  291. serverSocket = ftp->sendPort();
  292. sequence = SEQ_RECV_PORT;
  293. return false;
  294. }
  295. bool FtpNegotiationCommand::recvPort() {
  296. unsigned int status = ftp->receiveResponse();
  297. if(status == 0) {
  298. return false;
  299. }
  300. if(status != 200) {
  301. throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
  302. }
  303. sequence = SEQ_SEND_REST;
  304. return true;
  305. }
  306. bool FtpNegotiationCommand::sendPasv() {
  307. afterFileAllocation();
  308. ftp->sendPasv();
  309. sequence = SEQ_RECV_PASV;
  310. return false;
  311. }
  312. bool FtpNegotiationCommand::recvPasv() {
  313. std::pair<std::string, uint16_t> dest;
  314. unsigned int status = ftp->receivePasvResponse(dest);
  315. if(status == 0) {
  316. return false;
  317. }
  318. if(status != 227) {
  319. throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
  320. }
  321. // make a data connection to the server.
  322. logger->info(MSG_CONNECTING_TO_SERVER, cuid,
  323. dest.first.c_str(),
  324. dest.second);
  325. dataSocket.reset(new SocketCore());
  326. dataSocket->establishConnection(dest.first, dest.second);
  327. disableReadCheckSocket();
  328. setWriteCheckSocket(dataSocket);
  329. sequence = SEQ_SEND_REST_PASV;
  330. return false;
  331. }
  332. bool FtpNegotiationCommand::sendRestPasv(const SegmentHandle& segment) {
  333. dataSocket->setBlockingMode();
  334. setReadCheckSocket(socket);
  335. disableWriteCheckSocket();
  336. return sendRest(segment);
  337. }
  338. bool FtpNegotiationCommand::sendRest(const SegmentHandle& segment) {
  339. ftp->sendRest(segment);
  340. sequence = SEQ_RECV_REST;
  341. return false;
  342. }
  343. bool FtpNegotiationCommand::recvRest() {
  344. unsigned int status = ftp->receiveResponse();
  345. if(status == 0) {
  346. return false;
  347. }
  348. // TODO if we recieve negative response, then we set _requestGroup->getSegmentMan()->splittable = false, and continue.
  349. if(status != 350) {
  350. throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
  351. }
  352. sequence = SEQ_SEND_RETR;
  353. return true;
  354. }
  355. bool FtpNegotiationCommand::sendRetr() {
  356. ftp->sendRetr();
  357. sequence = SEQ_RECV_RETR;
  358. return false;
  359. }
  360. bool FtpNegotiationCommand::recvRetr() {
  361. uint64_t size = 0;
  362. unsigned int status = ftp->receiveRetrResponse(size);
  363. if(status == 0) {
  364. return false;
  365. }
  366. if(status != 150 && status != 125) {
  367. throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str());
  368. }
  369. if(_requestGroup->getPieceStorage().isNull()) {
  370. sequence = SEQ_FILE_PREPARATION_ON_RETR;
  371. return onFileSizeDetermined(size);
  372. } else {
  373. _requestGroup->validateTotalLength(size);
  374. }
  375. if(e->option->getAsBool(PREF_FTP_PASV)) {
  376. sequence = SEQ_NEGOTIATION_COMPLETED;
  377. return false;
  378. } else {
  379. disableReadCheckSocket();
  380. setReadCheckSocket(serverSocket);
  381. sequence = SEQ_WAIT_CONNECTION;
  382. return false;
  383. }
  384. }
  385. bool FtpNegotiationCommand::waitConnection()
  386. {
  387. disableReadCheckSocket();
  388. setReadCheckSocket(socket);
  389. dataSocket.reset(serverSocket->acceptConnection());
  390. dataSocket->setBlockingMode();
  391. sequence = SEQ_NEGOTIATION_COMPLETED;
  392. return false;
  393. }
  394. bool FtpNegotiationCommand::processSequence(const SegmentHandle& segment) {
  395. bool doNextSequence = true;
  396. switch(sequence) {
  397. case SEQ_RECV_GREETING:
  398. return recvGreeting();
  399. case SEQ_SEND_USER:
  400. return sendUser();
  401. case SEQ_RECV_USER:
  402. return recvUser();
  403. case SEQ_SEND_PASS:
  404. return sendPass();
  405. case SEQ_RECV_PASS:
  406. return recvPass();
  407. case SEQ_SEND_TYPE:
  408. return sendType();
  409. case SEQ_RECV_TYPE:
  410. return recvType();
  411. case SEQ_SEND_CWD:
  412. return sendCwd();
  413. case SEQ_RECV_CWD:
  414. return recvCwd();
  415. case SEQ_SEND_SIZE:
  416. return sendSize();
  417. case SEQ_RECV_SIZE:
  418. return recvSize();
  419. case SEQ_SEND_PORT:
  420. return sendPort();
  421. case SEQ_RECV_PORT:
  422. return recvPort();
  423. case SEQ_SEND_PASV:
  424. return sendPasv();
  425. case SEQ_RECV_PASV:
  426. return recvPasv();
  427. case SEQ_SEND_REST_PASV:
  428. return sendRestPasv(segment);
  429. case SEQ_SEND_REST:
  430. return sendRest(segment);
  431. case SEQ_RECV_REST:
  432. return recvRest();
  433. case SEQ_SEND_RETR:
  434. return sendRetr();
  435. case SEQ_RECV_RETR:
  436. return recvRetr();
  437. case SEQ_WAIT_CONNECTION:
  438. return waitConnection();
  439. case SEQ_NEGOTIATION_COMPLETED:
  440. return false;
  441. default:
  442. abort();
  443. }
  444. return doNextSequence;
  445. }
  446. void FtpNegotiationCommand::poolConnection() const
  447. {
  448. if(!e->option->getAsBool(PREF_HTTP_PROXY_ENABLED) &&
  449. e->option->getAsBool(PREF_FTP_REUSE_CONNECTION)) {
  450. std::pair<std::string, uint16_t> peerInfo;
  451. socket->getPeerInfo(peerInfo);
  452. e->poolSocket(peerInfo.first, peerInfo.second, socket);
  453. }
  454. }
  455. } // namespace aria2