FtpConnection.cc 16 KB

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