FtpConnection.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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. sockaddr_union sockaddr;
  207. socklen_t len = sizeof(sockaddr);
  208. serverSocket->getAddrInfo(sockaddr, len);
  209. std::pair<std::string, uint16_t> addrinfo =
  210. util::getNumericNameInfo(&sockaddr.sa, len);
  211. std::string request = "EPRT ";
  212. request += "|";
  213. request += util::itos(sockaddr.storage.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, 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(1) {
  341. size_t size = sizeof(buf);
  342. socket_->readData(buf, size);
  343. if(size == 0) {
  344. if(socket_->wantRead() || socket_->wantWrite()) {
  345. break;
  346. } else {
  347. throw DL_RETRY_EX(EX_GOT_EOF);
  348. }
  349. }
  350. if(strbuf_.size()+size > MAX_RECV_BUFFER) {
  351. throw DL_RETRY_EX
  352. (fmt("Max FTP recv buffer reached. length=%lu",
  353. static_cast<unsigned long>(strbuf_.size()+size)));
  354. }
  355. strbuf_.append(&buf[0], &buf[size]);
  356. }
  357. unsigned int status;
  358. if(strbuf_.size() >= 4) {
  359. status = getStatus(strbuf_);
  360. if(status == 0) {
  361. throw DL_ABORT_EX2(EX_INVALID_RESPONSE,
  362. error_code::FTP_PROTOCOL_ERROR);
  363. }
  364. } else {
  365. return false;
  366. }
  367. std::string::size_type length;
  368. if((length = findEndOfResponse(status, strbuf_)) != std::string::npos) {
  369. response.first = status;
  370. response.second = strbuf_.substr(0, length);
  371. A2_LOG_INFO(fmt(MSG_RECEIVE_RESPONSE,
  372. cuid_,
  373. response.second.c_str()));
  374. strbuf_.erase(0, length);
  375. return true;
  376. } else {
  377. // didn't receive response fully.
  378. return false;
  379. }
  380. }
  381. unsigned int FtpConnection::receiveResponse()
  382. {
  383. std::pair<unsigned int, std::string> response;
  384. if(bulkReceiveResponse(response)) {
  385. return response.first;
  386. } else {
  387. return 0;
  388. }
  389. }
  390. #ifdef __MINGW32__
  391. # define LONGLONG_PRINTF "%I64d"
  392. # define ULONGLONG_PRINTF "%I64u"
  393. # define LONGLONG_SCANF "%I64d"
  394. # define ULONGLONG_SCANF "%I64u"
  395. #else
  396. # define LONGLONG_PRINTF "%lld"
  397. # define ULONGLONG_PRINTF "%llu"
  398. # define LONGLONG_SCANF "%Ld"
  399. // Mac OSX uses "%llu" for 64bits integer.
  400. # define ULONGLONG_SCANF "%Lu"
  401. #endif // __MINGW32__
  402. unsigned int FtpConnection::receiveSizeResponse(uint64_t& size)
  403. {
  404. std::pair<unsigned int, std::string> response;
  405. if(bulkReceiveResponse(response)) {
  406. if(response.first == 213) {
  407. std::pair<std::string, std::string> rp;
  408. util::divide(rp, response.second, ' ');
  409. size = util::parseULLInt(rp.second);
  410. }
  411. return response.first;
  412. } else {
  413. return 0;
  414. }
  415. }
  416. unsigned int FtpConnection::receiveMdtmResponse(Time& time)
  417. {
  418. // MDTM command, specified in RFC3659.
  419. std::pair<unsigned int, std::string> response;
  420. if(bulkReceiveResponse(response)) {
  421. if(response.first == 213) {
  422. char buf[15]; // YYYYMMDDhhmmss+\0, milli second part is dropped.
  423. sscanf(response.second.c_str(), "%*u %14s", buf);
  424. if(strlen(buf) == 14) {
  425. // We don't use Time::parse(buf,"%Y%m%d%H%M%S") here because Mac OS X
  426. // and included strptime doesn't parse data for this format.
  427. struct tm tm;
  428. memset(&tm, 0, sizeof(tm));
  429. tm.tm_sec = util::parseInt(&buf[12]);
  430. buf[12] = '\0';
  431. tm.tm_min = util::parseInt(&buf[10]);
  432. buf[10] = '\0';
  433. tm.tm_hour = util::parseInt(&buf[8]);
  434. buf[8] = '\0';
  435. tm.tm_mday = util::parseInt(&buf[6]);
  436. buf[6] = '\0';
  437. tm.tm_mon = util::parseInt(&buf[4])-1;
  438. buf[4] = '\0';
  439. tm.tm_year = util::parseInt(&buf[0])-1900;
  440. time = Time(timegm(&tm));
  441. } else {
  442. time = Time::null();
  443. }
  444. }
  445. return response.first;
  446. } else {
  447. return 0;
  448. }
  449. }
  450. unsigned int FtpConnection::receiveEpsvResponse(uint16_t& port)
  451. {
  452. std::pair<unsigned int, std::string> response;
  453. if(bulkReceiveResponse(response)) {
  454. if(response.first == 229) {
  455. port = 0;
  456. std::string::size_type leftParen = response.second.find("(");
  457. std::string::size_type rightParen = response.second.find(")");
  458. if(leftParen == std::string::npos || rightParen == std::string::npos ||
  459. leftParen > rightParen) {
  460. return response.first;
  461. }
  462. std::vector<std::string> rd;
  463. util::split(response.second.substr(leftParen+1, rightParen-(leftParen+1)),
  464. std::back_inserter(rd), "|", true, true);
  465. uint32_t portTemp = 0;
  466. if(rd.size() == 5 && util::parseUIntNoThrow(portTemp, rd[3])) {
  467. if(0 < portTemp && portTemp <= UINT16_MAX) {
  468. port = portTemp;
  469. }
  470. }
  471. }
  472. return response.first;
  473. } else {
  474. return 0;
  475. }
  476. }
  477. unsigned int FtpConnection::receivePasvResponse
  478. (std::pair<std::string, uint16_t>& dest)
  479. {
  480. std::pair<unsigned int, std::string> response;
  481. if(bulkReceiveResponse(response)) {
  482. if(response.first == 227) {
  483. // we assume the format of response is "227 Entering Passive
  484. // Mode (h1,h2,h3,h4,p1,p2)."
  485. unsigned int h1, h2, h3, h4, p1, p2;
  486. std::string::size_type p = response.second.find("(");
  487. if(p >= 4) {
  488. sscanf(response.second.substr(response.second.find("(")).c_str(),
  489. "(%u,%u,%u,%u,%u,%u).",
  490. &h1, &h2, &h3, &h4, &p1, &p2);
  491. // ip address
  492. dest.first = util::uitos(h1);
  493. dest.first += A2STR::DOT_C;
  494. dest.first += util::uitos(h2);
  495. dest.first += A2STR::DOT_C;
  496. dest.first += util::uitos(h3);
  497. dest.first += A2STR::DOT_C;
  498. dest.first += util::uitos(h4);
  499. // port number
  500. dest.second = 256*p1+p2;
  501. } else {
  502. throw DL_RETRY_EX(EX_INVALID_RESPONSE);
  503. }
  504. }
  505. return response.first;
  506. } else {
  507. return 0;
  508. }
  509. }
  510. unsigned int FtpConnection::receivePwdResponse(std::string& pwd)
  511. {
  512. std::pair<unsigned int, std::string> response;
  513. if(bulkReceiveResponse(response)) {
  514. if(response.first == 257) {
  515. std::string::size_type first;
  516. std::string::size_type last;
  517. if((first = response.second.find("\"")) != std::string::npos &&
  518. (last = response.second.find("\"", ++first)) != std::string::npos) {
  519. pwd = response.second.substr(first, last-first);
  520. } else {
  521. throw DL_ABORT_EX2(EX_INVALID_RESPONSE,
  522. error_code::FTP_PROTOCOL_ERROR);
  523. }
  524. }
  525. return response.first;
  526. } else {
  527. return 0;
  528. }
  529. }
  530. void FtpConnection::setBaseWorkingDir(const std::string& baseWorkingDir)
  531. {
  532. baseWorkingDir_ = baseWorkingDir;
  533. }
  534. const std::string& FtpConnection::getUser() const
  535. {
  536. return authConfig_->getUser();
  537. }
  538. } // namespace aria2