FtpConnection.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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.begin(), dir.end());
  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 +=
  150. util::percentDecode(req_->getFile().begin(), req_->getFile().end());
  151. request += "\r\n";
  152. A2_LOG_INFO(fmt(MSG_SENDING_REQUEST,
  153. cuid_, request.c_str()));
  154. socketBuffer_.pushStr(request);
  155. }
  156. socketBuffer_.send();
  157. return socketBuffer_.sendBufferIsEmpty();
  158. }
  159. bool FtpConnection::sendSize()
  160. {
  161. if(socketBuffer_.sendBufferIsEmpty()) {
  162. std::string request = "SIZE ";
  163. request +=
  164. util::percentDecode(req_->getFile().begin(), req_->getFile().end());
  165. request += "\r\n";
  166. A2_LOG_INFO(fmt(MSG_SENDING_REQUEST,
  167. cuid_, request.c_str()));
  168. socketBuffer_.pushStr(request);
  169. }
  170. socketBuffer_.send();
  171. return socketBuffer_.sendBufferIsEmpty();
  172. }
  173. bool FtpConnection::sendEpsv()
  174. {
  175. if(socketBuffer_.sendBufferIsEmpty()) {
  176. static const std::string request("EPSV\r\n");
  177. A2_LOG_INFO(fmt(MSG_SENDING_REQUEST,
  178. cuid_, request.c_str()));
  179. socketBuffer_.pushStr(request);
  180. }
  181. socketBuffer_.send();
  182. return socketBuffer_.sendBufferIsEmpty();
  183. }
  184. bool FtpConnection::sendPasv()
  185. {
  186. if(socketBuffer_.sendBufferIsEmpty()) {
  187. static const std::string request("PASV\r\n");
  188. A2_LOG_INFO(fmt(MSG_SENDING_REQUEST,
  189. cuid_, request.c_str()));
  190. socketBuffer_.pushStr(request);
  191. }
  192. socketBuffer_.send();
  193. return socketBuffer_.sendBufferIsEmpty();
  194. }
  195. SharedHandle<SocketCore> FtpConnection::createServerSocket()
  196. {
  197. std::pair<std::string, uint16_t> addrinfo;
  198. socket_->getAddrInfo(addrinfo);
  199. SharedHandle<SocketCore> serverSocket(new SocketCore());
  200. serverSocket->bind(addrinfo.first, 0, AF_UNSPEC);
  201. serverSocket->beginListen();
  202. serverSocket->setNonBlockingMode();
  203. return serverSocket;
  204. }
  205. bool FtpConnection::sendEprt(const SharedHandle<SocketCore>& serverSocket)
  206. {
  207. if(socketBuffer_.sendBufferIsEmpty()) {
  208. sockaddr_union sockaddr;
  209. socklen_t len = sizeof(sockaddr);
  210. serverSocket->getAddrInfo(sockaddr, len);
  211. std::pair<std::string, uint16_t> addrinfo =
  212. util::getNumericNameInfo(&sockaddr.sa, len);
  213. std::string request = "EPRT ";
  214. request += "|";
  215. request += util::itos(sockaddr.storage.ss_family == AF_INET ? 1 : 2);
  216. request += "|";
  217. request += addrinfo.first;
  218. request += "|";
  219. request += util::uitos(addrinfo.second);
  220. request += "|\r\n";
  221. A2_LOG_INFO(fmt(MSG_SENDING_REQUEST, cuid_, request.c_str()));
  222. socketBuffer_.pushStr(request);
  223. }
  224. socketBuffer_.send();
  225. return socketBuffer_.sendBufferIsEmpty();
  226. }
  227. bool FtpConnection::sendPort(const SharedHandle<SocketCore>& serverSocket)
  228. {
  229. if(socketBuffer_.sendBufferIsEmpty()) {
  230. std::pair<std::string, uint16_t> addrinfo;
  231. socket_->getAddrInfo(addrinfo);
  232. unsigned int ipaddr[4];
  233. sscanf(addrinfo.first.c_str(), "%u.%u.%u.%u",
  234. &ipaddr[0], &ipaddr[1], &ipaddr[2], &ipaddr[3]);
  235. serverSocket->getAddrInfo(addrinfo);
  236. std::string request = "PORT ";
  237. request += util::uitos(ipaddr[0]);
  238. request += ",";
  239. request += util::uitos(ipaddr[1]);
  240. request += ",";
  241. request += util::uitos(ipaddr[2]);
  242. request += ",";
  243. request += util::uitos(ipaddr[3]);
  244. request += ",";
  245. request += util::uitos(addrinfo.second/256);
  246. request += ",";
  247. request += util::uitos(addrinfo.second%256);
  248. request += "\r\n";
  249. A2_LOG_INFO(fmt(MSG_SENDING_REQUEST,
  250. cuid_, request.c_str()));
  251. socketBuffer_.pushStr(request);
  252. }
  253. socketBuffer_.send();
  254. return socketBuffer_.sendBufferIsEmpty();
  255. }
  256. bool FtpConnection::sendRest(const SharedHandle<Segment>& segment)
  257. {
  258. if(socketBuffer_.sendBufferIsEmpty()) {
  259. std::string request = "REST ";
  260. if(!segment) {
  261. request += "0";
  262. } else {
  263. request += util::itos(segment->getPositionToWrite());
  264. }
  265. request += "\r\n";
  266. A2_LOG_INFO(fmt(MSG_SENDING_REQUEST,
  267. cuid_, request.c_str()));
  268. socketBuffer_.pushStr(request);
  269. }
  270. socketBuffer_.send();
  271. return socketBuffer_.sendBufferIsEmpty();
  272. }
  273. bool FtpConnection::sendRetr()
  274. {
  275. if(socketBuffer_.sendBufferIsEmpty()) {
  276. std::string request = "RETR ";
  277. request +=
  278. util::percentDecode(req_->getFile().begin(), req_->getFile().end());
  279. request += "\r\n";
  280. A2_LOG_INFO(fmt(MSG_SENDING_REQUEST,
  281. cuid_, request.c_str()));
  282. socketBuffer_.pushStr(request);
  283. }
  284. socketBuffer_.send();
  285. return socketBuffer_.sendBufferIsEmpty();
  286. }
  287. unsigned int FtpConnection::getStatus(const std::string& response) const
  288. {
  289. unsigned int status;
  290. // When the response is not like "%u %*s",
  291. // we return 0.
  292. if(response.find_first_not_of("0123456789") != 3
  293. || !(response.find(" ") == 3 || response.find("-") == 3)) {
  294. return 0;
  295. }
  296. if(sscanf(response.c_str(), "%u %*s", &status) == 1) {
  297. return status;
  298. } else {
  299. return 0;
  300. }
  301. }
  302. // Returns the length of the reponse if the whole response has been received.
  303. // The length includes \r\n.
  304. // If the whole response has not been received, then returns std::string::npos.
  305. std::string::size_type
  306. FtpConnection::findEndOfResponse(unsigned int status,
  307. const std::string& buf) const
  308. {
  309. if(buf.size() <= 4) {
  310. return std::string::npos;
  311. }
  312. // if 4th character of buf is '-', then multi line response is expected.
  313. if(buf.at(3) == '-') {
  314. // multi line response
  315. std::string::size_type p;
  316. std::string endPattern = A2STR::CRLF;
  317. endPattern += util::uitos(status);
  318. endPattern += " ";
  319. p = buf.find(endPattern);
  320. if(p == std::string::npos) {
  321. return std::string::npos;
  322. }
  323. p = buf.find(A2STR::CRLF, p+6);
  324. if(p == std::string::npos) {
  325. return std::string::npos;
  326. } else {
  327. return p+2;
  328. }
  329. } else {
  330. // single line response
  331. std::string::size_type p = buf.find(A2STR::CRLF);
  332. if(p == std::string::npos) {
  333. return std::string::npos;
  334. } else {
  335. return p+2;
  336. }
  337. }
  338. }
  339. bool FtpConnection::bulkReceiveResponse
  340. (std::pair<unsigned int, std::string>& response)
  341. {
  342. char buf[1024];
  343. while(1) {
  344. size_t size = sizeof(buf);
  345. socket_->readData(buf, size);
  346. if(size == 0) {
  347. if(socket_->wantRead() || socket_->wantWrite()) {
  348. break;
  349. } else {
  350. throw DL_RETRY_EX(EX_GOT_EOF);
  351. }
  352. }
  353. if(strbuf_.size()+size > MAX_RECV_BUFFER) {
  354. throw DL_RETRY_EX
  355. (fmt("Max FTP recv buffer reached. length=%lu",
  356. static_cast<unsigned long>(strbuf_.size()+size)));
  357. }
  358. strbuf_.append(&buf[0], &buf[size]);
  359. }
  360. unsigned int status;
  361. if(strbuf_.size() >= 4) {
  362. status = getStatus(strbuf_);
  363. if(status == 0) {
  364. throw DL_ABORT_EX2(EX_INVALID_RESPONSE,
  365. error_code::FTP_PROTOCOL_ERROR);
  366. }
  367. } else {
  368. return false;
  369. }
  370. std::string::size_type length;
  371. if((length = findEndOfResponse(status, strbuf_)) != std::string::npos) {
  372. response.first = status;
  373. response.second = strbuf_.substr(0, length);
  374. A2_LOG_INFO(fmt(MSG_RECEIVE_RESPONSE,
  375. cuid_,
  376. response.second.c_str()));
  377. strbuf_.erase(0, length);
  378. return true;
  379. } else {
  380. // didn't receive response fully.
  381. return false;
  382. }
  383. }
  384. unsigned int FtpConnection::receiveResponse()
  385. {
  386. std::pair<unsigned int, std::string> response;
  387. if(bulkReceiveResponse(response)) {
  388. return response.first;
  389. } else {
  390. return 0;
  391. }
  392. }
  393. #ifdef __MINGW32__
  394. # define LONGLONG_PRINTF "%I64d"
  395. # define ULONGLONG_PRINTF "%I64u"
  396. # define LONGLONG_SCANF "%I64d"
  397. # define ULONGLONG_SCANF "%I64u"
  398. #else
  399. # define LONGLONG_PRINTF "%lld"
  400. # define ULONGLONG_PRINTF "%llu"
  401. # define LONGLONG_SCANF "%Ld"
  402. // Mac OSX uses "%llu" for 64bits integer.
  403. # define ULONGLONG_SCANF "%Lu"
  404. #endif // __MINGW32__
  405. unsigned int FtpConnection::receiveSizeResponse(uint64_t& size)
  406. {
  407. std::pair<unsigned int, std::string> response;
  408. if(bulkReceiveResponse(response)) {
  409. if(response.first == 213) {
  410. std::pair<Scip, Scip> rp;
  411. util::divide(rp, response.second.begin(), response.second.end(), ' ');
  412. size = util::parseULLInt(rp.second.first, rp.second.second);
  413. }
  414. return response.first;
  415. } else {
  416. return 0;
  417. }
  418. }
  419. unsigned int FtpConnection::receiveMdtmResponse(Time& time)
  420. {
  421. // MDTM command, specified in RFC3659.
  422. std::pair<unsigned int, std::string> response;
  423. if(bulkReceiveResponse(response)) {
  424. if(response.first == 213) {
  425. char buf[15]; // YYYYMMDDhhmmss+\0, milli second part is dropped.
  426. sscanf(response.second.c_str(), "%*u %14s", buf);
  427. if(strlen(buf) == 14) {
  428. // We don't use Time::parse(buf,"%Y%m%d%H%M%S") here because Mac OS X
  429. // and included strptime doesn't parse data for this format.
  430. struct tm tm;
  431. memset(&tm, 0, sizeof(tm));
  432. tm.tm_sec = util::parseInt(&buf[12], &buf[14]);
  433. tm.tm_min = util::parseInt(&buf[10], &buf[12]);
  434. tm.tm_hour = util::parseInt(&buf[8], &buf[10]);
  435. tm.tm_mday = util::parseInt(&buf[6], &buf[8]);
  436. tm.tm_mon = util::parseInt(&buf[4], &buf[6])-1;
  437. tm.tm_year = util::parseInt(&buf[0], &buf[4])-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 &&
  465. util::parseUIntNoThrow(portTemp, rd[3].begin(), rd[3].end())) {
  466. if(0 < portTemp && portTemp <= UINT16_MAX) {
  467. port = portTemp;
  468. }
  469. }
  470. }
  471. return response.first;
  472. } else {
  473. return 0;
  474. }
  475. }
  476. unsigned int FtpConnection::receivePasvResponse
  477. (std::pair<std::string, uint16_t>& dest)
  478. {
  479. std::pair<unsigned int, std::string> response;
  480. if(bulkReceiveResponse(response)) {
  481. if(response.first == 227) {
  482. // we assume the format of response is "227 Entering Passive
  483. // Mode (h1,h2,h3,h4,p1,p2)."
  484. unsigned int h1, h2, h3, h4, p1, p2;
  485. std::string::size_type p = response.second.find("(");
  486. if(p >= 4) {
  487. sscanf(response.second.substr(response.second.find("(")).c_str(),
  488. "(%u,%u,%u,%u,%u,%u).",
  489. &h1, &h2, &h3, &h4, &p1, &p2);
  490. // ip address
  491. dest.first = util::uitos(h1);
  492. dest.first += A2STR::DOT_C;
  493. dest.first += util::uitos(h2);
  494. dest.first += A2STR::DOT_C;
  495. dest.first += util::uitos(h3);
  496. dest.first += A2STR::DOT_C;
  497. dest.first += util::uitos(h4);
  498. // port number
  499. dest.second = 256*p1+p2;
  500. } else {
  501. throw DL_RETRY_EX(EX_INVALID_RESPONSE);
  502. }
  503. }
  504. return response.first;
  505. } else {
  506. return 0;
  507. }
  508. }
  509. unsigned int FtpConnection::receivePwdResponse(std::string& pwd)
  510. {
  511. std::pair<unsigned int, std::string> response;
  512. if(bulkReceiveResponse(response)) {
  513. if(response.first == 257) {
  514. std::string::size_type first;
  515. std::string::size_type last;
  516. if((first = response.second.find("\"")) != std::string::npos &&
  517. (last = response.second.find("\"", ++first)) != std::string::npos) {
  518. pwd = response.second.substr(first, last-first);
  519. } else {
  520. throw DL_ABORT_EX2(EX_INVALID_RESPONSE,
  521. error_code::FTP_PROTOCOL_ERROR);
  522. }
  523. }
  524. return response.first;
  525. } else {
  526. return 0;
  527. }
  528. }
  529. void FtpConnection::setBaseWorkingDir(const std::string& baseWorkingDir)
  530. {
  531. baseWorkingDir_ = baseWorkingDir;
  532. }
  533. const std::string& FtpConnection::getUser() const
  534. {
  535. return authConfig_->getUser();
  536. }
  537. } // namespace aria2