FtpConnection.cc 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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 "Request.h"
  37. #include "Segment.h"
  38. #include "Option.h"
  39. #include "Util.h"
  40. #include "message.h"
  41. #include "prefs.h"
  42. #include "LogFactory.h"
  43. #include "Logger.h"
  44. #include "AuthConfigFactory.h"
  45. #include "AuthConfig.h"
  46. #include "DlRetryEx.h"
  47. #include "DlAbortEx.h"
  48. #include "Socket.h"
  49. #include "A2STR.h"
  50. namespace aria2 {
  51. const std::string FtpConnection::A("A");
  52. const std::string FtpConnection::I("I");
  53. FtpConnection::FtpConnection(int32_t cuid, const SocketHandle& socket,
  54. const RequestHandle& req, const Option* op):
  55. cuid(cuid), socket(socket), req(req), option(op),
  56. logger(LogFactory::getInstance()) {}
  57. FtpConnection::~FtpConnection() {}
  58. void FtpConnection::sendUser() const
  59. {
  60. std::string request = "USER "+AuthConfigFactorySingleton::instance()->createAuthConfig(req)->getUser()+"\r\n";
  61. logger->info(MSG_SENDING_REQUEST, cuid, "USER ********");
  62. socket->writeData(request);
  63. }
  64. void FtpConnection::sendPass() const
  65. {
  66. std::string request = "PASS "+AuthConfigFactorySingleton::instance()->createAuthConfig(req)->getPassword()+"\r\n";
  67. logger->info(MSG_SENDING_REQUEST, cuid, "PASS ********");
  68. socket->writeData(request);
  69. }
  70. void FtpConnection::sendType() const
  71. {
  72. std::string type;
  73. if(option->get(PREF_FTP_TYPE) == V_ASCII) {
  74. type = FtpConnection::A;
  75. } else {
  76. type = FtpConnection::I;
  77. }
  78. std::string request = "TYPE "+type+"\r\n";
  79. logger->info(MSG_SENDING_REQUEST, cuid, request.c_str());
  80. socket->writeData(request);
  81. }
  82. void FtpConnection::sendCwd() const
  83. {
  84. std::string request = "CWD "+Util::urldecode(req->getDir())+"\r\n";
  85. logger->info(MSG_SENDING_REQUEST, cuid, request.c_str());
  86. socket->writeData(request);
  87. }
  88. void FtpConnection::sendSize() const
  89. {
  90. std::string request = "SIZE "+Util::urldecode(req->getFile())+"\r\n";
  91. logger->info(MSG_SENDING_REQUEST, cuid, request.c_str());
  92. socket->writeData(request);
  93. }
  94. void FtpConnection::sendPasv() const
  95. {
  96. static const std::string request("PASV\r\n");
  97. logger->info(MSG_SENDING_REQUEST, cuid, request.c_str());
  98. socket->writeData(request);
  99. }
  100. SocketHandle FtpConnection::sendPort() const
  101. {
  102. SocketHandle serverSocket(new SocketCore());
  103. serverSocket->bind(0);
  104. serverSocket->beginListen();
  105. serverSocket->setNonBlockingMode();
  106. std::pair<std::string, uint16_t> addrinfo;
  107. socket->getAddrInfo(addrinfo);
  108. unsigned int ipaddr[4];
  109. sscanf(addrinfo.first.c_str(), "%u.%u.%u.%u",
  110. &ipaddr[0], &ipaddr[1], &ipaddr[2], &ipaddr[3]);
  111. serverSocket->getAddrInfo(addrinfo);
  112. std::string request = "PORT "+
  113. Util::uitos(ipaddr[0])+","+Util::uitos(ipaddr[1])+","+
  114. Util::uitos(ipaddr[2])+","+Util::uitos(ipaddr[3])+","+
  115. Util::uitos(addrinfo.second/256)+","+Util::uitos(addrinfo.second%256)+"\r\n";
  116. logger->info(MSG_SENDING_REQUEST, cuid, request.c_str());
  117. socket->writeData(request);
  118. return serverSocket;
  119. }
  120. void FtpConnection::sendRest(const SegmentHandle& segment) const
  121. {
  122. std::string request = "REST ";
  123. if(segment.isNull()) {
  124. request += "0";
  125. } else {
  126. request += Util::itos(segment->getPositionToWrite());
  127. }
  128. request += "\r\n";
  129. logger->info(MSG_SENDING_REQUEST, cuid, request.c_str());
  130. socket->writeData(request);
  131. }
  132. void FtpConnection::sendRetr() const
  133. {
  134. std::string request = "RETR "+Util::urldecode(req->getFile())+"\r\n";
  135. logger->info(MSG_SENDING_REQUEST, cuid, request.c_str());
  136. socket->writeData(request);
  137. }
  138. unsigned int FtpConnection::getStatus(const std::string& response) const
  139. {
  140. unsigned int status;
  141. // When the response is not like "%u %*s",
  142. // we return 0.
  143. if(response.find_first_not_of("0123456789") != 3
  144. || !(response.find(" ") == 3 || response.find("-") == 3)) {
  145. return 0;
  146. }
  147. if(sscanf(response.c_str(), "%u %*s", &status) == 1) {
  148. return status;
  149. } else {
  150. return 0;
  151. }
  152. }
  153. bool FtpConnection::isEndOfResponse(unsigned int status, const std::string& response) const
  154. {
  155. if(response.size() <= 4) {
  156. return false;
  157. }
  158. // if 4th character of buf is '-', then multi line response is expected.
  159. if(response.at(3) == '-') {
  160. // multi line response
  161. std::string::size_type p;
  162. p = response.find("\r\n"+Util::uitos(status)+" ");
  163. if(p == std::string::npos) {
  164. return false;
  165. }
  166. }
  167. if(Util::endsWith(response, A2STR::CRLF)) {
  168. return true;
  169. } else {
  170. return false;
  171. }
  172. }
  173. bool FtpConnection::bulkReceiveResponse(std::pair<unsigned int, std::string>& response)
  174. {
  175. char buf[1024];
  176. while(socket->isReadable(0)) {
  177. size_t size = sizeof(buf)-1;
  178. socket->readData(buf, size);
  179. if(size == 0) {
  180. throw DlRetryEx(EX_GOT_EOF);
  181. }
  182. buf[size] = '\0';
  183. strbuf += buf;
  184. }
  185. unsigned int status;
  186. if(strbuf.size() >= 4) {
  187. status = getStatus(strbuf);
  188. if(status == 0) {
  189. throw DlAbortEx(EX_INVALID_RESPONSE);
  190. }
  191. } else {
  192. return false;
  193. }
  194. if(isEndOfResponse(status, strbuf)) {
  195. logger->info(MSG_RECEIVE_RESPONSE, cuid, strbuf.c_str());
  196. response.first = status;
  197. response.second = strbuf;
  198. strbuf.erase();
  199. return true;
  200. } else {
  201. // didn't receive response fully.
  202. return false;
  203. }
  204. }
  205. unsigned int FtpConnection::receiveResponse()
  206. {
  207. std::pair<unsigned int, std::string> response;
  208. if(bulkReceiveResponse(response)) {
  209. return response.first;
  210. } else {
  211. return 0;
  212. }
  213. }
  214. #ifdef __MINGW32__
  215. # define LONGLONG_PRINTF "%I64d"
  216. # define ULONGLONG_PRINTF "%I64u"
  217. # define LONGLONG_SCANF "%I64d"
  218. # define ULONGLONG_SCANF "%I64u"
  219. #else
  220. # define LONGLONG_PRINTF "%lld"
  221. # define ULONGLONG_PRINTF "%llu"
  222. # define LONGLONG_SCANF "%Ld"
  223. # define ULONGLONG_SCANF "%Lu"
  224. #endif // __MINGW32__
  225. unsigned int FtpConnection::receiveSizeResponse(uint64_t& size)
  226. {
  227. std::pair<unsigned int, std::string> response;
  228. if(bulkReceiveResponse(response)) {
  229. if(response.first == 213) {
  230. sscanf(response.second.c_str(), "%*u " LONGLONG_SCANF, &size);
  231. }
  232. return response.first;
  233. } else {
  234. return 0;
  235. }
  236. }
  237. unsigned int FtpConnection::receivePasvResponse(std::pair<std::string, uint16_t>& dest)
  238. {
  239. std::pair<unsigned int, std::string> response;
  240. if(bulkReceiveResponse(response)) {
  241. if(response.first == 227) {
  242. // we assume the format of response is "227 Entering Passive Mode (h1,h2,h3,h4,p1,p2)."
  243. unsigned int h1, h2, h3, h4, p1, p2;
  244. std::string::size_type p = response.second.find("(");
  245. if(p >= 4) {
  246. sscanf(response.second.substr(response.second.find("(")).c_str(),
  247. "(%u,%u,%u,%u,%u,%u).",
  248. &h1, &h2, &h3, &h4, &p1, &p2);
  249. // ip address
  250. dest.first = Util::uitos(h1)+"."+Util::uitos(h2)+"."+Util::uitos(h3)+"."+Util::uitos(h4);
  251. // port number
  252. dest.second = 256*p1+p2;
  253. } else {
  254. throw DlRetryEx(EX_INVALID_RESPONSE);
  255. }
  256. }
  257. return response.first;
  258. } else {
  259. return 0;
  260. }
  261. }
  262. unsigned int FtpConnection::receiveRetrResponse(uint64_t& size)
  263. {
  264. static const char* DIGITS = "0123456789";
  265. std::pair<unsigned int, std::string> response;
  266. if(bulkReceiveResponse(response)) {
  267. if(response.first == 150 || response.first == 125) {
  268. // Attempting to get file size from the response.
  269. // We assume the response is like:
  270. // 150 Opening BINARY mode data connection for aria2.tar.bz2 (12345 bytes)
  271. // If the attempt is failed, size is unchanged.
  272. std::string& res = response.second;
  273. std::string::size_type start;
  274. if((start = res.find_first_of("(")) != std::string::npos &&
  275. (start = res.find_first_of(DIGITS, start)) != std::string::npos) {
  276. // now start points to the first digit of the size string.
  277. std::string::size_type end =
  278. res.find_first_not_of(DIGITS, start);
  279. if(end != std::string::npos) {
  280. size = Util::parseULLInt(res.substr(start, end-start));
  281. }
  282. }
  283. }
  284. return response.first;
  285. } else {
  286. return 0;
  287. }
  288. }
  289. } // namespace aria2