FtpConnection.cc 16 KB

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