FtpConnection.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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 "FtpConnection.h"
  36. #include <array>
  37. #include <cstring>
  38. #include <cstdio>
  39. #include <cassert>
  40. #include "Request.h"
  41. #include "Segment.h"
  42. #include "Option.h"
  43. #include "util.h"
  44. #include "message.h"
  45. #include "prefs.h"
  46. #include "LogFactory.h"
  47. #include "Logger.h"
  48. #include "AuthConfigFactory.h"
  49. #include "AuthConfig.h"
  50. #include "DlRetryEx.h"
  51. #include "DlAbortEx.h"
  52. #include "SocketCore.h"
  53. #include "A2STR.h"
  54. #include "fmt.h"
  55. #include "AuthConfig.h"
  56. #include "a2functional.h"
  57. #include "util.h"
  58. #include "error_code.h"
  59. namespace aria2 {
  60. FtpConnection::FtpConnection(cuid_t cuid,
  61. const std::shared_ptr<SocketCore>& socket,
  62. const std::shared_ptr<Request>& req,
  63. const std::shared_ptr<AuthConfig>& authConfig,
  64. const Option* op)
  65. : cuid_(cuid),
  66. socket_(socket),
  67. req_(req),
  68. authConfig_(authConfig),
  69. option_(op),
  70. socketBuffer_(socket),
  71. baseWorkingDir_("/")
  72. {
  73. }
  74. FtpConnection::~FtpConnection() = default;
  75. bool FtpConnection::sendUser()
  76. {
  77. if (socketBuffer_.sendBufferIsEmpty()) {
  78. std::string request = "USER ";
  79. request += authConfig_->getUser();
  80. request += "\r\n";
  81. A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, cuid_, "USER ********"));
  82. socketBuffer_.pushStr(std::move(request));
  83. }
  84. socketBuffer_.send();
  85. return socketBuffer_.sendBufferIsEmpty();
  86. }
  87. bool FtpConnection::sendPass()
  88. {
  89. if (socketBuffer_.sendBufferIsEmpty()) {
  90. std::string request = "PASS ";
  91. request += authConfig_->getPassword();
  92. request += "\r\n";
  93. A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, cuid_, "PASS ********"));
  94. socketBuffer_.pushStr(std::move(request));
  95. }
  96. socketBuffer_.send();
  97. return socketBuffer_.sendBufferIsEmpty();
  98. }
  99. bool FtpConnection::sendType()
  100. {
  101. if (socketBuffer_.sendBufferIsEmpty()) {
  102. std::string request = "TYPE ";
  103. request += (option_->get(PREF_FTP_TYPE) == V_ASCII ? 'A' : 'I');
  104. request += "\r\n";
  105. A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, cuid_, request.c_str()));
  106. socketBuffer_.pushStr(std::move(request));
  107. }
  108. socketBuffer_.send();
  109. return socketBuffer_.sendBufferIsEmpty();
  110. }
  111. bool FtpConnection::sendPwd()
  112. {
  113. if (socketBuffer_.sendBufferIsEmpty()) {
  114. std::string request = "PWD\r\n";
  115. A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, cuid_, request.c_str()));
  116. socketBuffer_.pushStr(std::move(request));
  117. }
  118. socketBuffer_.send();
  119. return socketBuffer_.sendBufferIsEmpty();
  120. }
  121. bool FtpConnection::sendCwd(const std::string& dir)
  122. {
  123. if (socketBuffer_.sendBufferIsEmpty()) {
  124. std::string request = "CWD ";
  125. request += util::percentDecode(dir.begin(), dir.end());
  126. request += "\r\n";
  127. A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, cuid_, request.c_str()));
  128. socketBuffer_.pushStr(std::move(request));
  129. }
  130. socketBuffer_.send();
  131. return socketBuffer_.sendBufferIsEmpty();
  132. }
  133. bool FtpConnection::sendMdtm()
  134. {
  135. if (socketBuffer_.sendBufferIsEmpty()) {
  136. std::string request = "MDTM ";
  137. request +=
  138. util::percentDecode(req_->getFile().begin(), req_->getFile().end());
  139. request += "\r\n";
  140. A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, cuid_, request.c_str()));
  141. socketBuffer_.pushStr(std::move(request));
  142. }
  143. socketBuffer_.send();
  144. return socketBuffer_.sendBufferIsEmpty();
  145. }
  146. bool FtpConnection::sendSize()
  147. {
  148. if (socketBuffer_.sendBufferIsEmpty()) {
  149. std::string request = "SIZE ";
  150. request +=
  151. util::percentDecode(req_->getFile().begin(), req_->getFile().end());
  152. request += "\r\n";
  153. A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, cuid_, request.c_str()));
  154. socketBuffer_.pushStr(std::move(request));
  155. }
  156. socketBuffer_.send();
  157. return socketBuffer_.sendBufferIsEmpty();
  158. }
  159. bool FtpConnection::sendEpsv()
  160. {
  161. if (socketBuffer_.sendBufferIsEmpty()) {
  162. std::string request("EPSV\r\n");
  163. A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, cuid_, request.c_str()));
  164. socketBuffer_.pushStr(std::move(request));
  165. }
  166. socketBuffer_.send();
  167. return socketBuffer_.sendBufferIsEmpty();
  168. }
  169. bool FtpConnection::sendPasv()
  170. {
  171. if (socketBuffer_.sendBufferIsEmpty()) {
  172. std::string request("PASV\r\n");
  173. A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, cuid_, request.c_str()));
  174. socketBuffer_.pushStr(std::move(request));
  175. }
  176. socketBuffer_.send();
  177. return socketBuffer_.sendBufferIsEmpty();
  178. }
  179. std::shared_ptr<SocketCore> FtpConnection::createServerSocket()
  180. {
  181. auto endpoint = socket_->getAddrInfo();
  182. auto serverSocket = std::make_shared<SocketCore>();
  183. serverSocket->bind(endpoint.addr.c_str(), 0, AF_UNSPEC);
  184. serverSocket->beginListen();
  185. return serverSocket;
  186. }
  187. bool FtpConnection::sendEprt(const std::shared_ptr<SocketCore>& serverSocket)
  188. {
  189. if (socketBuffer_.sendBufferIsEmpty()) {
  190. auto endpoint = serverSocket->getAddrInfo();
  191. auto request =
  192. fmt("EPRT |%d|%s|%u|\r\n", endpoint.family == AF_INET ? 1 : 2,
  193. endpoint.addr.c_str(), endpoint.port);
  194. A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, cuid_, request.c_str()));
  195. socketBuffer_.pushStr(std::move(request));
  196. }
  197. socketBuffer_.send();
  198. return socketBuffer_.sendBufferIsEmpty();
  199. }
  200. bool FtpConnection::sendPort(const std::shared_ptr<SocketCore>& serverSocket)
  201. {
  202. if (socketBuffer_.sendBufferIsEmpty()) {
  203. auto endpoint = socket_->getAddrInfo();
  204. int ipaddr[4];
  205. sscanf(endpoint.addr.c_str(), "%d.%d.%d.%d", &ipaddr[0], &ipaddr[1],
  206. &ipaddr[2], &ipaddr[3]);
  207. auto svEndpoint = serverSocket->getAddrInfo();
  208. auto request =
  209. fmt("PORT %d,%d,%d,%d,%d,%d\r\n", ipaddr[0], ipaddr[1], ipaddr[2],
  210. ipaddr[3], svEndpoint.port / 256, svEndpoint.port % 256);
  211. A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, cuid_, request.c_str()));
  212. socketBuffer_.pushStr(std::move(request));
  213. }
  214. socketBuffer_.send();
  215. return socketBuffer_.sendBufferIsEmpty();
  216. }
  217. bool FtpConnection::sendRest(const std::shared_ptr<Segment>& segment)
  218. {
  219. if (socketBuffer_.sendBufferIsEmpty()) {
  220. std::string request =
  221. fmt("REST %" PRId64 "\r\n", segment ? segment->getPositionToWrite()
  222. : static_cast<int64_t>(0LL));
  223. A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, cuid_, request.c_str()));
  224. socketBuffer_.pushStr(std::move(request));
  225. }
  226. socketBuffer_.send();
  227. return socketBuffer_.sendBufferIsEmpty();
  228. }
  229. bool FtpConnection::sendRetr()
  230. {
  231. if (socketBuffer_.sendBufferIsEmpty()) {
  232. std::string request = "RETR ";
  233. request +=
  234. util::percentDecode(req_->getFile().begin(), req_->getFile().end());
  235. request += "\r\n";
  236. A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, cuid_, request.c_str()));
  237. socketBuffer_.pushStr(std::move(request));
  238. }
  239. socketBuffer_.send();
  240. return socketBuffer_.sendBufferIsEmpty();
  241. }
  242. int FtpConnection::getStatus(const std::string& response) const
  243. {
  244. int status;
  245. // When the response is not like "%d %*s",
  246. // we return 0.
  247. if (response.find_first_not_of("0123456789") != 3 ||
  248. !(response.find(" ") == 3 || response.find("-") == 3)) {
  249. return 0;
  250. }
  251. if (sscanf(response.c_str(), "%d %*s", &status) == 1) {
  252. return status;
  253. }
  254. else {
  255. return 0;
  256. }
  257. }
  258. // Returns the length of the response if the whole response has been received.
  259. // The length includes \r\n.
  260. // If the whole response has not been received, then returns std::string::npos.
  261. std::string::size_type
  262. FtpConnection::findEndOfResponse(int status, const std::string& buf) const
  263. {
  264. if (buf.size() <= 4) {
  265. return std::string::npos;
  266. }
  267. // if 4th character of buf is '-', then multi line response is expected.
  268. if (buf.at(3) == '-') {
  269. // multi line response
  270. std::string::size_type p;
  271. p = buf.find(fmt("\r\n%d ", status));
  272. if (p == std::string::npos) {
  273. return std::string::npos;
  274. }
  275. p = buf.find("\r\n", p + 6);
  276. if (p == std::string::npos) {
  277. return std::string::npos;
  278. }
  279. else {
  280. return p + 2;
  281. }
  282. }
  283. else {
  284. // single line response
  285. std::string::size_type p = buf.find("\r\n");
  286. if (p == std::string::npos) {
  287. return std::string::npos;
  288. }
  289. else {
  290. return p + 2;
  291. }
  292. }
  293. }
  294. bool FtpConnection::bulkReceiveResponse(std::pair<int, std::string>& response)
  295. {
  296. std::array<char, 1_k> buf;
  297. while (1) {
  298. size_t size = buf.size();
  299. socket_->readData(buf.data(), size);
  300. if (size == 0) {
  301. if (socket_->wantRead() || socket_->wantWrite()) {
  302. break;
  303. }
  304. else {
  305. throw DL_RETRY_EX(EX_GOT_EOF);
  306. }
  307. }
  308. if (strbuf_.size() + size > MAX_RECV_BUFFER) {
  309. throw DL_RETRY_EX(fmt("Max FTP recv buffer reached. length=%lu",
  310. static_cast<unsigned long>(strbuf_.size() + size)));
  311. }
  312. strbuf_.append(std::begin(buf), std::begin(buf) + size);
  313. }
  314. int status;
  315. if (strbuf_.size() >= 4) {
  316. status = getStatus(strbuf_);
  317. if (status == 0) {
  318. throw DL_ABORT_EX2(EX_INVALID_RESPONSE, error_code::FTP_PROTOCOL_ERROR);
  319. }
  320. }
  321. else {
  322. return false;
  323. }
  324. std::string::size_type length;
  325. if ((length = findEndOfResponse(status, strbuf_)) != std::string::npos) {
  326. response.first = status;
  327. response.second.assign(strbuf_.begin(), strbuf_.begin() + length);
  328. A2_LOG_INFO(fmt(MSG_RECEIVE_RESPONSE, cuid_, response.second.c_str()));
  329. strbuf_.erase(0, length);
  330. return true;
  331. }
  332. else {
  333. // didn't receive response fully.
  334. return false;
  335. }
  336. }
  337. int FtpConnection::receiveResponse()
  338. {
  339. std::pair<int, std::string> response;
  340. if (bulkReceiveResponse(response)) {
  341. return response.first;
  342. }
  343. else {
  344. return 0;
  345. }
  346. }
  347. #ifdef __MINGW32__
  348. #define LONGLONG_PRINTF "%I64d"
  349. #define ULONGLONG_PRINTF "%I64u"
  350. #define LONGLONG_SCANF "%I64d"
  351. #define ULONGLONG_SCANF "%I64u"
  352. #else
  353. #define LONGLONG_PRINTF "%" PRId64 ""
  354. #define ULONGLONG_PRINTF "%llu"
  355. #define LONGLONG_SCANF "%Ld"
  356. // Mac OSX uses "%llu" for 64bits integer.
  357. #define ULONGLONG_SCANF "%Lu"
  358. #endif // __MINGW32__
  359. int FtpConnection::receiveSizeResponse(int64_t& size)
  360. {
  361. std::pair<int, std::string> response;
  362. if (bulkReceiveResponse(response)) {
  363. if (response.first == 213) {
  364. auto rp = util::divide(std::begin(response.second),
  365. std::end(response.second), ' ');
  366. if (!util::parseLLIntNoThrow(
  367. size, std::string(rp.second.first, rp.second.second)) ||
  368. size < 0) {
  369. throw DL_ABORT_EX("Size must be positive integer");
  370. }
  371. }
  372. return response.first;
  373. }
  374. else {
  375. return 0;
  376. }
  377. }
  378. namespace {
  379. template <typename T>
  380. bool getInteger(T* dest, const char* first, const char* last)
  381. {
  382. int res = 0;
  383. // We assume *dest won't overflow.
  384. for (; first != last; ++first) {
  385. if (util::isDigit(*first)) {
  386. res *= 10;
  387. res += (*first) - '0';
  388. }
  389. else {
  390. return false;
  391. }
  392. }
  393. *dest = res;
  394. return true;
  395. }
  396. } // namespace
  397. int FtpConnection::receiveMdtmResponse(Time& time)
  398. {
  399. // MDTM command, specified in RFC3659.
  400. std::pair<int, std::string> response;
  401. if (bulkReceiveResponse(response)) {
  402. if (response.first == 213) {
  403. char buf[15]; // YYYYMMDDhhmmss+\0, milli second part is dropped.
  404. sscanf(response.second.c_str(), "%*u %14s", buf);
  405. if (strlen(buf) == 14) {
  406. // We don't use Time::parse(buf,"%Y%m%d%H%M%S") here because Mac OS X
  407. // and included strptime doesn't parse data for this format.
  408. struct tm tm;
  409. memset(&tm, 0, sizeof(tm));
  410. if (getInteger(&tm.tm_sec, &buf[12], &buf[14]) &&
  411. getInteger(&tm.tm_min, &buf[10], &buf[12]) &&
  412. getInteger(&tm.tm_hour, &buf[8], &buf[10]) &&
  413. getInteger(&tm.tm_mday, &buf[6], &buf[8]) &&
  414. getInteger(&tm.tm_mon, &buf[4], &buf[6]) &&
  415. getInteger(&tm.tm_year, &buf[0], &buf[4])) {
  416. tm.tm_mon -= 1;
  417. tm.tm_year -= 1900;
  418. time = Time(timegm(&tm));
  419. }
  420. else {
  421. time = Time::null();
  422. }
  423. }
  424. else {
  425. time = Time::null();
  426. }
  427. }
  428. return response.first;
  429. }
  430. else {
  431. return 0;
  432. }
  433. }
  434. int FtpConnection::receiveEpsvResponse(uint16_t& port)
  435. {
  436. std::pair<int, std::string> response;
  437. if (bulkReceiveResponse(response)) {
  438. if (response.first == 229) {
  439. port = 0;
  440. std::string::size_type leftParen = response.second.find("(");
  441. std::string::size_type rightParen = response.second.find(")");
  442. if (leftParen == std::string::npos || rightParen == std::string::npos ||
  443. leftParen > rightParen) {
  444. return response.first;
  445. }
  446. std::vector<Scip> rd;
  447. util::splitIter(response.second.begin() + leftParen + 1,
  448. response.second.begin() + rightParen,
  449. std::back_inserter(rd), '|', true, true);
  450. uint32_t portTemp = 0;
  451. if (rd.size() == 5 &&
  452. util::parseUIntNoThrow(portTemp,
  453. std::string(rd[3].first, rd[3].second))) {
  454. if (0 < portTemp && portTemp <= UINT16_MAX) {
  455. port = portTemp;
  456. }
  457. }
  458. }
  459. return response.first;
  460. }
  461. else {
  462. return 0;
  463. }
  464. }
  465. int FtpConnection::receivePasvResponse(std::pair<std::string, uint16_t>& dest)
  466. {
  467. std::pair<int, std::string> response;
  468. if (bulkReceiveResponse(response)) {
  469. if (response.first == 227) {
  470. // we assume the format of response is "227 Entering Passive
  471. // Mode (h1,h2,h3,h4,p1,p2)."
  472. int h1, h2, h3, h4, p1, p2;
  473. std::string::size_type p = response.second.find("(");
  474. if (p >= 4) {
  475. sscanf(response.second.c_str() + p, "(%d,%d,%d,%d,%d,%d).", &h1, &h2,
  476. &h3, &h4, &p1, &p2);
  477. // ip address
  478. dest.first = fmt("%d.%d.%d.%d", h1, h2, h3, h4);
  479. // port number
  480. dest.second = 256 * p1 + p2;
  481. }
  482. else {
  483. throw DL_RETRY_EX(EX_INVALID_RESPONSE);
  484. }
  485. }
  486. return response.first;
  487. }
  488. else {
  489. return 0;
  490. }
  491. }
  492. int FtpConnection::receivePwdResponse(std::string& pwd)
  493. {
  494. std::pair<int, std::string> response;
  495. if (bulkReceiveResponse(response)) {
  496. if (response.first == 257) {
  497. std::string::size_type first;
  498. std::string::size_type last;
  499. if ((first = response.second.find("\"")) != std::string::npos &&
  500. (last = response.second.find("\"", ++first)) != std::string::npos) {
  501. pwd.assign(response.second.begin() + first,
  502. response.second.begin() + last);
  503. }
  504. else {
  505. throw DL_ABORT_EX2(EX_INVALID_RESPONSE, error_code::FTP_PROTOCOL_ERROR);
  506. }
  507. }
  508. return response.first;
  509. }
  510. else {
  511. return 0;
  512. }
  513. }
  514. void FtpConnection::setBaseWorkingDir(const std::string& baseWorkingDir)
  515. {
  516. baseWorkingDir_ = baseWorkingDir;
  517. }
  518. const std::string& FtpConnection::getUser() const
  519. {
  520. return authConfig_->getUser();
  521. }
  522. } // namespace aria2