FtpConnection.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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 "StringFormat.h"
  54. #include "AuthConfig.h"
  55. namespace aria2 {
  56. const std::string FtpConnection::A("A");
  57. const std::string FtpConnection::I("I");
  58. FtpConnection::FtpConnection(int32_t cuid, const SocketHandle& socket,
  59. const RequestHandle& req,
  60. const SharedHandle<AuthConfig>& authConfig,
  61. const Option* op):
  62. cuid(cuid), socket(socket), req(req),
  63. _authConfig(authConfig), option(op),
  64. logger(LogFactory::getInstance()),
  65. _socketBuffer(socket),
  66. _baseWorkingDir("/") {}
  67. FtpConnection::~FtpConnection() {}
  68. bool FtpConnection::sendUser()
  69. {
  70. if(_socketBuffer.sendBufferIsEmpty()) {
  71. std::string request = "USER "+_authConfig->getUser()+"\r\n";
  72. logger->info(MSG_SENDING_REQUEST, cuid, "USER ********");
  73. _socketBuffer.feedSendBuffer(request);
  74. }
  75. _socketBuffer.send();
  76. return _socketBuffer.sendBufferIsEmpty();
  77. }
  78. bool FtpConnection::sendPass()
  79. {
  80. if(_socketBuffer.sendBufferIsEmpty()) {
  81. std::string request = "PASS "+_authConfig->getPassword()+"\r\n";
  82. logger->info(MSG_SENDING_REQUEST, cuid, "PASS ********");
  83. _socketBuffer.feedSendBuffer(request);
  84. }
  85. _socketBuffer.send();
  86. return _socketBuffer.sendBufferIsEmpty();
  87. }
  88. bool FtpConnection::sendType()
  89. {
  90. if(_socketBuffer.sendBufferIsEmpty()) {
  91. std::string type;
  92. if(option->get(PREF_FTP_TYPE) == V_ASCII) {
  93. type = FtpConnection::A;
  94. } else {
  95. type = FtpConnection::I;
  96. }
  97. std::string request = "TYPE "+type+"\r\n";
  98. logger->info(MSG_SENDING_REQUEST, cuid, request.c_str());
  99. _socketBuffer.feedSendBuffer(request);
  100. }
  101. _socketBuffer.send();
  102. return _socketBuffer.sendBufferIsEmpty();
  103. }
  104. bool FtpConnection::sendPwd()
  105. {
  106. if(_socketBuffer.sendBufferIsEmpty()) {
  107. std::string request = "PWD\r\n";
  108. logger->info(MSG_SENDING_REQUEST, cuid, request.c_str());
  109. _socketBuffer.feedSendBuffer(request);
  110. }
  111. _socketBuffer.send();
  112. return _socketBuffer.sendBufferIsEmpty();
  113. }
  114. bool FtpConnection::sendCwd()
  115. {
  116. if(_socketBuffer.sendBufferIsEmpty()) {
  117. logger->info("CUID#%d - Using base working directory '%s'",
  118. cuid, _baseWorkingDir.c_str());
  119. std::string request = "CWD "+
  120. (_baseWorkingDir == "/" ? "" : _baseWorkingDir)+
  121. Util::urldecode(req->getDir())+"\r\n";
  122. logger->info(MSG_SENDING_REQUEST, cuid, request.c_str());
  123. _socketBuffer.feedSendBuffer(request);
  124. }
  125. _socketBuffer.send();
  126. return _socketBuffer.sendBufferIsEmpty();
  127. }
  128. bool FtpConnection::sendMdtm()
  129. {
  130. if(_socketBuffer.sendBufferIsEmpty()) {
  131. std::string request = "MDTM "+Util::urlencode(req->getFile())+"\r\n";
  132. logger->info(MSG_SENDING_REQUEST, cuid, request.c_str());
  133. _socketBuffer.feedSendBuffer(request);
  134. }
  135. _socketBuffer.send();
  136. return _socketBuffer.sendBufferIsEmpty();
  137. }
  138. bool FtpConnection::sendSize()
  139. {
  140. if(_socketBuffer.sendBufferIsEmpty()) {
  141. std::string request = "SIZE "+Util::urldecode(req->getFile())+"\r\n";
  142. logger->info(MSG_SENDING_REQUEST, cuid, request.c_str());
  143. _socketBuffer.feedSendBuffer(request);
  144. }
  145. _socketBuffer.send();
  146. return _socketBuffer.sendBufferIsEmpty();
  147. }
  148. bool FtpConnection::sendPasv()
  149. {
  150. if(_socketBuffer.sendBufferIsEmpty()) {
  151. static const std::string request("PASV\r\n");
  152. logger->info(MSG_SENDING_REQUEST, cuid, request.c_str());
  153. _socketBuffer.feedSendBuffer(request);
  154. }
  155. _socketBuffer.send();
  156. return _socketBuffer.sendBufferIsEmpty();
  157. }
  158. SharedHandle<SocketCore> FtpConnection::createServerSocket()
  159. {
  160. SharedHandle<SocketCore> serverSocket(new SocketCore());
  161. serverSocket->bind(0);
  162. serverSocket->beginListen();
  163. serverSocket->setNonBlockingMode();
  164. return serverSocket;
  165. }
  166. bool FtpConnection::sendPort(const SharedHandle<SocketCore>& serverSocket)
  167. {
  168. if(_socketBuffer.sendBufferIsEmpty()) {
  169. std::pair<std::string, uint16_t> addrinfo;
  170. socket->getAddrInfo(addrinfo);
  171. unsigned int ipaddr[4];
  172. sscanf(addrinfo.first.c_str(), "%u.%u.%u.%u",
  173. &ipaddr[0], &ipaddr[1], &ipaddr[2], &ipaddr[3]);
  174. serverSocket->getAddrInfo(addrinfo);
  175. std::string request = "PORT "+
  176. Util::uitos(ipaddr[0])+","+Util::uitos(ipaddr[1])+","+
  177. Util::uitos(ipaddr[2])+","+Util::uitos(ipaddr[3])+","+
  178. Util::uitos(addrinfo.second/256)+","+
  179. Util::uitos(addrinfo.second%256)+"\r\n";
  180. logger->info(MSG_SENDING_REQUEST, cuid, request.c_str());
  181. _socketBuffer.feedSendBuffer(request);
  182. }
  183. _socketBuffer.send();
  184. return _socketBuffer.sendBufferIsEmpty();
  185. }
  186. bool FtpConnection::sendRest(const SegmentHandle& segment)
  187. {
  188. if(_socketBuffer.sendBufferIsEmpty()) {
  189. std::string request = "REST ";
  190. if(segment.isNull()) {
  191. request += "0";
  192. } else {
  193. request += Util::itos(segment->getPositionToWrite());
  194. }
  195. request += "\r\n";
  196. logger->info(MSG_SENDING_REQUEST, cuid, request.c_str());
  197. _socketBuffer.feedSendBuffer(request);
  198. }
  199. _socketBuffer.send();
  200. return _socketBuffer.sendBufferIsEmpty();
  201. }
  202. bool FtpConnection::sendRetr()
  203. {
  204. if(_socketBuffer.sendBufferIsEmpty()) {
  205. std::string request = "RETR "+Util::urldecode(req->getFile())+"\r\n";
  206. logger->info(MSG_SENDING_REQUEST, cuid, request.c_str());
  207. _socketBuffer.feedSendBuffer(request);
  208. }
  209. _socketBuffer.send();
  210. return _socketBuffer.sendBufferIsEmpty();
  211. }
  212. unsigned int FtpConnection::getStatus(const std::string& response) const
  213. {
  214. unsigned int status;
  215. // When the response is not like "%u %*s",
  216. // we return 0.
  217. if(response.find_first_not_of("0123456789") != 3
  218. || !(response.find(" ") == 3 || response.find("-") == 3)) {
  219. return 0;
  220. }
  221. if(sscanf(response.c_str(), "%u %*s", &status) == 1) {
  222. return status;
  223. } else {
  224. return 0;
  225. }
  226. }
  227. // Returns the length of the reponse if the whole response has been received.
  228. // The length includes \r\n.
  229. // If the whole response has not been recieved, then returns std::string::npos.
  230. std::string::size_type
  231. FtpConnection::findEndOfResponse(unsigned int status,
  232. const std::string& buf) const
  233. {
  234. if(buf.size() <= 4) {
  235. return std::string::npos;
  236. }
  237. // if 4th character of buf is '-', then multi line response is expected.
  238. if(buf.at(3) == '-') {
  239. // multi line response
  240. std::string::size_type p;
  241. p = buf.find(A2STR::CRLF+Util::uitos(status)+" ");
  242. if(p == std::string::npos) {
  243. return std::string::npos;
  244. }
  245. p = buf.find(A2STR::CRLF, p+6);
  246. if(p == std::string::npos) {
  247. return std::string::npos;
  248. } else {
  249. return p+2;
  250. }
  251. } else {
  252. // single line response
  253. std::string::size_type p = buf.find(A2STR::CRLF);
  254. if(p == std::string::npos) {
  255. return std::string::npos;
  256. } else {
  257. return p+2;
  258. }
  259. }
  260. }
  261. bool FtpConnection::bulkReceiveResponse(std::pair<unsigned int, std::string>& response)
  262. {
  263. char buf[1024];
  264. while(socket->isReadable(0)) {
  265. size_t size = sizeof(buf);
  266. socket->readData(buf, size);
  267. if(size == 0) {
  268. if(socket->wantRead() || socket->wantWrite()) {
  269. return false;
  270. }
  271. throw DL_RETRY_EX(EX_GOT_EOF);
  272. }
  273. if(strbuf.size()+size > MAX_RECV_BUFFER) {
  274. throw DL_RETRY_EX
  275. (StringFormat("Max FTP recv buffer reached. length=%lu",
  276. static_cast<unsigned long>(strbuf.size()+size)).str());
  277. }
  278. strbuf.append(&buf[0], &buf[size]);
  279. }
  280. unsigned int status;
  281. if(strbuf.size() >= 4) {
  282. status = getStatus(strbuf);
  283. if(status == 0) {
  284. throw DL_ABORT_EX(EX_INVALID_RESPONSE);
  285. }
  286. } else {
  287. return false;
  288. }
  289. std::string::size_type length;
  290. if((length = findEndOfResponse(status, strbuf)) != std::string::npos) {
  291. response.first = status;
  292. response.second = strbuf.substr(0, length);
  293. logger->info(MSG_RECEIVE_RESPONSE, cuid, response.second.c_str());
  294. strbuf.erase(0, length);
  295. return true;
  296. } else {
  297. // didn't receive response fully.
  298. return false;
  299. }
  300. }
  301. unsigned int FtpConnection::receiveResponse()
  302. {
  303. std::pair<unsigned int, std::string> response;
  304. if(bulkReceiveResponse(response)) {
  305. return response.first;
  306. } else {
  307. return 0;
  308. }
  309. }
  310. #ifdef __MINGW32__
  311. # define LONGLONG_PRINTF "%I64d"
  312. # define ULONGLONG_PRINTF "%I64u"
  313. # define LONGLONG_SCANF "%I64d"
  314. # define ULONGLONG_SCANF "%I64u"
  315. #else
  316. # define LONGLONG_PRINTF "%lld"
  317. # define ULONGLONG_PRINTF "%llu"
  318. # define LONGLONG_SCANF "%Ld"
  319. // Mac OSX uses "%llu" for 64bits integer.
  320. # define ULONGLONG_SCANF "%Lu"
  321. #endif // __MINGW32__
  322. unsigned int FtpConnection::receiveSizeResponse(uint64_t& size)
  323. {
  324. std::pair<unsigned int, std::string> response;
  325. if(bulkReceiveResponse(response)) {
  326. if(response.first == 213) {
  327. std::pair<std::string, std::string> rp = Util::split(response.second," ");
  328. size = Util::parseULLInt(rp.second);
  329. }
  330. return response.first;
  331. } else {
  332. return 0;
  333. }
  334. }
  335. unsigned int FtpConnection::receiveMdtmResponse(Time& time)
  336. {
  337. // MDTM command, specified in RFC3659.
  338. std::pair<unsigned int, std::string> response;
  339. if(bulkReceiveResponse(response)) {
  340. if(response.first == 213) {
  341. char buf[15]; // YYYYMMDDhhmmss+\0, milli second part is dropped.
  342. sscanf(response.second.c_str(), "%*u %14s", buf);
  343. if(strlen(buf) == 14) {
  344. // We don't use Time::parse(buf,"%Y%m%d%H%M%S") here because Mac OS X
  345. // and included strptime doesn't parse data for this format.
  346. struct tm tm;
  347. memset(&tm, 0, sizeof(tm));
  348. tm.tm_sec = Util::parseInt(&buf[12]);
  349. buf[12] = '\0';
  350. tm.tm_min = Util::parseInt(&buf[10]);
  351. buf[10] = '\0';
  352. tm.tm_hour = Util::parseInt(&buf[8]);
  353. buf[8] = '\0';
  354. tm.tm_mday = Util::parseInt(&buf[6]);
  355. buf[6] = '\0';
  356. tm.tm_mon = Util::parseInt(&buf[4])-1;
  357. buf[4] = '\0';
  358. tm.tm_year = Util::parseInt(&buf[0])-1900;
  359. time = Time(timegm(&tm));
  360. } else {
  361. time = Time::null();
  362. }
  363. }
  364. return response.first;
  365. } else {
  366. return 0;
  367. }
  368. }
  369. unsigned int FtpConnection::receivePasvResponse(std::pair<std::string, uint16_t>& dest)
  370. {
  371. std::pair<unsigned int, std::string> response;
  372. if(bulkReceiveResponse(response)) {
  373. if(response.first == 227) {
  374. // we assume the format of response is "227 Entering Passive Mode (h1,h2,h3,h4,p1,p2)."
  375. unsigned int h1, h2, h3, h4, p1, p2;
  376. std::string::size_type p = response.second.find("(");
  377. if(p >= 4) {
  378. sscanf(response.second.substr(response.second.find("(")).c_str(),
  379. "(%u,%u,%u,%u,%u,%u).",
  380. &h1, &h2, &h3, &h4, &p1, &p2);
  381. // ip address
  382. dest.first = Util::uitos(h1)+"."+Util::uitos(h2)+"."+Util::uitos(h3)+"."+Util::uitos(h4);
  383. // port number
  384. dest.second = 256*p1+p2;
  385. } else {
  386. throw DL_RETRY_EX(EX_INVALID_RESPONSE);
  387. }
  388. }
  389. return response.first;
  390. } else {
  391. return 0;
  392. }
  393. }
  394. unsigned int FtpConnection::receivePwdResponse(std::string& pwd)
  395. {
  396. std::pair<unsigned int, std::string> response;
  397. if(bulkReceiveResponse(response)) {
  398. if(response.first == 257) {
  399. std::string::size_type first;
  400. std::string::size_type last;
  401. if((first = response.second.find("\"")) != std::string::npos &&
  402. (last = response.second.find("\"", ++first)) != std::string::npos) {
  403. pwd = response.second.substr(first, last-first);
  404. } else {
  405. throw DL_ABORT_EX(EX_INVALID_RESPONSE);
  406. }
  407. }
  408. return response.first;
  409. } else {
  410. return 0;
  411. }
  412. }
  413. void FtpConnection::setBaseWorkingDir(const std::string& baseWorkingDir)
  414. {
  415. _baseWorkingDir = baseWorkingDir;
  416. }
  417. } // namespace aria2