FtpConnection.cc 16 KB

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