DownloadEngine.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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 "DownloadEngine.h"
  36. #include <signal.h>
  37. #include <cstring>
  38. #include <cerrno>
  39. #include <algorithm>
  40. #include <numeric>
  41. #include "StatCalc.h"
  42. #include "RequestGroup.h"
  43. #include "RequestGroupMan.h"
  44. #include "DownloadResult.h"
  45. #include "StatCalc.h"
  46. #include "LogFactory.h"
  47. #include "Logger.h"
  48. #include "TimeA2.h"
  49. #include "a2time.h"
  50. #include "Socket.h"
  51. #include "util.h"
  52. #include "a2functional.h"
  53. #include "DlAbortEx.h"
  54. #include "ServerStatMan.h"
  55. #include "CookieStorage.h"
  56. #include "A2STR.h"
  57. #include "AuthConfigFactory.h"
  58. #include "AuthConfig.h"
  59. #include "Request.h"
  60. #include "EventPoll.h"
  61. #include "Command.h"
  62. #include "FileAllocationEntry.h"
  63. #include "CheckIntegrityEntry.h"
  64. #include "BtProgressInfoFile.h"
  65. #include "DownloadContext.h"
  66. #ifdef ENABLE_BITTORRENT
  67. # include "BtRegistry.h"
  68. # include "PeerStorage.h"
  69. # include "PieceStorage.h"
  70. # include "BtAnnounce.h"
  71. # include "BtRuntime.h"
  72. #endif // ENABLE_BITTORRENT
  73. namespace aria2 {
  74. // 0 ... running
  75. // 1 ... stop signal detected
  76. // 2 ... stop signal processed by DownloadEngine
  77. // 3 ... 2nd stop signal(force shutdown) detected
  78. // 4 ... 2nd stop signal processed by DownloadEngine
  79. volatile sig_atomic_t globalHaltRequested = 0;
  80. DownloadEngine::DownloadEngine(const SharedHandle<EventPoll>& eventPoll):
  81. _eventPoll(eventPoll),
  82. logger(LogFactory::getInstance()),
  83. _haltRequested(false),
  84. _noWait(false),
  85. _refreshInterval(DEFAULT_REFRESH_INTERVAL),
  86. _cookieStorage(new CookieStorage()),
  87. #ifdef ENABLE_BITTORRENT
  88. _btRegistry(new BtRegistry()),
  89. #endif // ENABLE_BITTORRENT
  90. _dnsCache(new DNSCache())
  91. {
  92. unsigned char sessionId[20];
  93. util::generateRandomKey(sessionId);
  94. _sessionId = std::string(&sessionId[0], & sessionId[sizeof(sessionId)]);
  95. }
  96. DownloadEngine::~DownloadEngine() {
  97. cleanQueue();
  98. }
  99. void DownloadEngine::cleanQueue() {
  100. std::for_each(commands.begin(), commands.end(), Deleter());
  101. commands.clear();
  102. }
  103. static void executeCommand(std::deque<Command*>& commands,
  104. Command::STATUS statusFilter)
  105. {
  106. size_t max = commands.size();
  107. for(size_t i = 0; i < max; ++i) {
  108. Command* com = commands.front();
  109. commands.pop_front();
  110. if(com->statusMatch(statusFilter)) {
  111. com->transitStatus();
  112. if(com->execute()) {
  113. delete com;
  114. com = 0;
  115. }
  116. } else {
  117. commands.push_back(com);
  118. }
  119. if(com) {
  120. com->clearIOEvents();
  121. }
  122. }
  123. }
  124. void DownloadEngine::run()
  125. {
  126. Time cp;
  127. cp.setTimeInSec(0);
  128. while(!commands.empty() || !_routineCommands.empty()) {
  129. if(cp.elapsed(_refreshInterval)) {
  130. _refreshInterval = DEFAULT_REFRESH_INTERVAL;
  131. cp.reset();
  132. executeCommand(commands, Command::STATUS_ALL);
  133. } else {
  134. executeCommand(commands, Command::STATUS_ACTIVE);
  135. }
  136. executeCommand(_routineCommands, Command::STATUS_ALL);
  137. afterEachIteration();
  138. if(!commands.empty()) {
  139. waitData();
  140. }
  141. _noWait = false;
  142. calculateStatistics();
  143. }
  144. onEndOfRun();
  145. }
  146. void DownloadEngine::waitData()
  147. {
  148. struct timeval tv;
  149. if(_noWait) {
  150. tv.tv_sec = tv.tv_usec = 0;
  151. } else {
  152. tv.tv_sec = 1;
  153. tv.tv_usec = 0;
  154. }
  155. _eventPoll->poll(tv);
  156. }
  157. bool DownloadEngine::addSocketForReadCheck(const SocketHandle& socket,
  158. Command* command)
  159. {
  160. return _eventPoll->addEvents(socket->getSockfd(), command,
  161. EventPoll::EVENT_READ);
  162. }
  163. bool DownloadEngine::deleteSocketForReadCheck(const SocketHandle& socket,
  164. Command* command)
  165. {
  166. return _eventPoll->deleteEvents(socket->getSockfd(), command,
  167. EventPoll::EVENT_READ);
  168. }
  169. bool DownloadEngine::addSocketForWriteCheck(const SocketHandle& socket,
  170. Command* command)
  171. {
  172. return _eventPoll->addEvents(socket->getSockfd(), command,
  173. EventPoll::EVENT_WRITE);
  174. }
  175. bool DownloadEngine::deleteSocketForWriteCheck(const SocketHandle& socket,
  176. Command* command)
  177. {
  178. return _eventPoll->deleteEvents(socket->getSockfd(), command,
  179. EventPoll::EVENT_WRITE);
  180. }
  181. void DownloadEngine::calculateStatistics()
  182. {
  183. if(!_statCalc.isNull()) {
  184. _statCalc->calculateStat(this);
  185. }
  186. }
  187. void DownloadEngine::onEndOfRun()
  188. {
  189. _requestGroupMan->updateServerStat();
  190. _requestGroupMan->closeFile();
  191. _requestGroupMan->save();
  192. }
  193. void DownloadEngine::afterEachIteration()
  194. {
  195. _requestGroupMan->calculateStat();
  196. if(globalHaltRequested == 1) {
  197. logger->notice(_("Shutdown sequence commencing... Press Ctrl-C again for emergency shutdown."));
  198. requestHalt();
  199. globalHaltRequested = 2;
  200. setNoWait(true);
  201. setRefreshInterval(0);
  202. } else if(globalHaltRequested == 3) {
  203. logger->notice(_("Emergency shutdown sequence commencing..."));
  204. _requestGroupMan->forceHalt();
  205. globalHaltRequested = 4;
  206. setNoWait(true);
  207. setRefreshInterval(0);
  208. }
  209. }
  210. void DownloadEngine::requestHalt()
  211. {
  212. _haltRequested = true;
  213. _requestGroupMan->halt();
  214. }
  215. void DownloadEngine::setStatCalc(const StatCalcHandle& statCalc)
  216. {
  217. _statCalc = statCalc;
  218. }
  219. void DownloadEngine::addCommand(const std::vector<Command*>& commands)
  220. {
  221. this->commands.insert(this->commands.end(), commands.begin(), commands.end());
  222. }
  223. #ifdef ENABLE_ASYNC_DNS
  224. bool DownloadEngine::addNameResolverCheck
  225. (const SharedHandle<AsyncNameResolver>& resolver, Command* command)
  226. {
  227. return _eventPoll->addNameResolver(resolver, command);
  228. }
  229. bool DownloadEngine::deleteNameResolverCheck
  230. (const SharedHandle<AsyncNameResolver>& resolver, Command* command)
  231. {
  232. return _eventPoll->deleteNameResolver(resolver, command);
  233. }
  234. #endif // ENABLE_ASYNC_DNS
  235. void DownloadEngine::setNoWait(bool b)
  236. {
  237. _noWait = b;
  238. }
  239. void DownloadEngine::addRoutineCommand(Command* command)
  240. {
  241. _routineCommands.push_back(command);
  242. }
  243. void DownloadEngine::poolSocket(const std::string& ipaddr,
  244. uint16_t port,
  245. const SocketPoolEntry& entry)
  246. {
  247. std::string addr = strconcat(ipaddr, ":", util::uitos(port));
  248. logger->info("Pool socket for %s", addr.c_str());
  249. std::multimap<std::string, SocketPoolEntry>::value_type p(addr, entry);
  250. _socketPool.insert(p);
  251. if(_lastSocketPoolScan.elapsed(60)) {
  252. std::multimap<std::string, SocketPoolEntry> newPool;
  253. if(logger->debug()) {
  254. logger->debug("Scaning SocketPool and erasing timed out entry.");
  255. }
  256. _lastSocketPoolScan.reset();
  257. for(std::multimap<std::string, SocketPoolEntry>::iterator i =
  258. _socketPool.begin(), eoi = _socketPool.end(); i != eoi; ++i) {
  259. if(!(*i).second.isTimeout()) {
  260. newPool.insert(*i);
  261. }
  262. }
  263. if(logger->debug()) {
  264. logger->debug
  265. ("%lu entries removed.",
  266. static_cast<unsigned long>(_socketPool.size()-newPool.size()));
  267. }
  268. _socketPool = newPool;
  269. }
  270. }
  271. void DownloadEngine::poolSocket
  272. (const std::string& ipaddr,
  273. uint16_t port,
  274. const SharedHandle<SocketCore>& sock,
  275. const std::map<std::string, std::string>& options,
  276. time_t timeout)
  277. {
  278. SocketPoolEntry e(sock, options, timeout);
  279. poolSocket(ipaddr, port, e);
  280. }
  281. void DownloadEngine::poolSocket
  282. (const std::string& ipaddr,
  283. uint16_t port,
  284. const SharedHandle<SocketCore>& sock,
  285. time_t timeout)
  286. {
  287. SocketPoolEntry e(sock, std::map<std::string, std::string>(), timeout);
  288. poolSocket(ipaddr, port, e);
  289. }
  290. void DownloadEngine::poolSocket(const SharedHandle<Request>& request,
  291. bool proxyDefined,
  292. const SharedHandle<SocketCore>& socket,
  293. time_t timeout)
  294. {
  295. if(proxyDefined) {
  296. // If proxy is defined, then pool socket with its hostname.
  297. poolSocket(request->getHost(), request->getPort(), socket);
  298. } else {
  299. std::pair<std::string, uint16_t> peerInfo;
  300. socket->getPeerInfo(peerInfo);
  301. poolSocket(peerInfo.first, peerInfo.second, socket);
  302. }
  303. }
  304. void DownloadEngine::poolSocket
  305. (const SharedHandle<Request>& request,
  306. bool proxyDefined,
  307. const SharedHandle<SocketCore>& socket,
  308. const std::map<std::string, std::string>& options,
  309. time_t timeout)
  310. {
  311. if(proxyDefined) {
  312. // If proxy is defined, then pool socket with its hostname.
  313. poolSocket(request->getHost(), request->getPort(), socket, options);
  314. } else {
  315. std::pair<std::string, uint16_t> peerInfo;
  316. socket->getPeerInfo(peerInfo);
  317. poolSocket(peerInfo.first, peerInfo.second, socket, options);
  318. }
  319. }
  320. std::multimap<std::string, DownloadEngine::SocketPoolEntry>::iterator
  321. DownloadEngine::findSocketPoolEntry(const std::string& ipaddr, uint16_t port)
  322. {
  323. std::string addr = ipaddr;
  324. strappend(addr, ":", util::uitos(port));
  325. std::pair<std::multimap<std::string, SocketPoolEntry>::iterator,
  326. std::multimap<std::string, SocketPoolEntry>::iterator> range =
  327. _socketPool.equal_range(addr);
  328. for(std::multimap<std::string, SocketPoolEntry>::iterator i =
  329. range.first, eoi = range.second; i != eoi; ++i) {
  330. const SocketPoolEntry& e = (*i).second;
  331. if(!e.isTimeout()) {
  332. logger->info("Found socket for %s", addr.c_str());
  333. return i;
  334. }
  335. }
  336. return _socketPool.end();
  337. }
  338. SharedHandle<SocketCore>
  339. DownloadEngine::popPooledSocket(const std::string& ipaddr, uint16_t port)
  340. {
  341. SharedHandle<SocketCore> s;
  342. std::multimap<std::string, SocketPoolEntry>::iterator i =
  343. findSocketPoolEntry(ipaddr, port);
  344. if(i != _socketPool.end()) {
  345. s = (*i).second.getSocket();
  346. _socketPool.erase(i);
  347. }
  348. return s;
  349. }
  350. SharedHandle<SocketCore>
  351. DownloadEngine::popPooledSocket(std::map<std::string, std::string>& options,
  352. const std::string& ipaddr, uint16_t port)
  353. {
  354. SharedHandle<SocketCore> s;
  355. std::multimap<std::string, SocketPoolEntry>::iterator i =
  356. findSocketPoolEntry(ipaddr, port);
  357. if(i != _socketPool.end()) {
  358. s = (*i).second.getSocket();
  359. options = (*i).second.getOptions();
  360. _socketPool.erase(i);
  361. }
  362. return s;
  363. }
  364. SharedHandle<SocketCore>
  365. DownloadEngine::popPooledSocket
  366. (const std::vector<std::string>& ipaddrs, uint16_t port)
  367. {
  368. SharedHandle<SocketCore> s;
  369. for(std::vector<std::string>::const_iterator i = ipaddrs.begin(),
  370. eoi = ipaddrs.end(); i != eoi; ++i) {
  371. s = popPooledSocket(*i, port);
  372. if(!s.isNull()) {
  373. break;
  374. }
  375. }
  376. return s;
  377. }
  378. SharedHandle<SocketCore>
  379. DownloadEngine::popPooledSocket
  380. (std::map<std::string, std::string>& options,
  381. const std::vector<std::string>& ipaddrs, uint16_t port)
  382. {
  383. SharedHandle<SocketCore> s;
  384. for(std::vector<std::string>::const_iterator i = ipaddrs.begin(),
  385. eoi = ipaddrs.end(); i != eoi; ++i) {
  386. s = popPooledSocket(options, *i, port);
  387. if(!s.isNull()) {
  388. break;
  389. }
  390. }
  391. return s;
  392. }
  393. DownloadEngine::SocketPoolEntry::SocketPoolEntry
  394. (const SharedHandle<SocketCore>& socket,
  395. const std::map<std::string, std::string>& options,
  396. time_t timeout):
  397. _socket(socket),
  398. _options(options),
  399. _timeout(timeout) {}
  400. DownloadEngine::SocketPoolEntry::~SocketPoolEntry() {}
  401. bool DownloadEngine::SocketPoolEntry::isTimeout() const
  402. {
  403. return _registeredTime.elapsed(_timeout);
  404. }
  405. cuid_t DownloadEngine::newCUID()
  406. {
  407. return _cuidCounter.newID();
  408. }
  409. const std::string& DownloadEngine::findCachedIPAddress
  410. (const std::string& hostname, uint16_t port) const
  411. {
  412. return _dnsCache->find(hostname, port);
  413. }
  414. void DownloadEngine::cacheIPAddress
  415. (const std::string& hostname, const std::string& ipaddr, uint16_t port)
  416. {
  417. _dnsCache->put(hostname, ipaddr, port);
  418. }
  419. void DownloadEngine::markBadIPAddress
  420. (const std::string& hostname, const std::string& ipaddr, uint16_t port)
  421. {
  422. _dnsCache->markBad(hostname, ipaddr, port);
  423. }
  424. void DownloadEngine::removeCachedIPAddress
  425. (const std::string& hostname, uint16_t port)
  426. {
  427. _dnsCache->remove(hostname, port);
  428. }
  429. void DownloadEngine::setAuthConfigFactory
  430. (const SharedHandle<AuthConfigFactory>& factory)
  431. {
  432. _authConfigFactory = factory;
  433. }
  434. void DownloadEngine::setRefreshInterval(time_t interval)
  435. {
  436. _refreshInterval = interval;
  437. }
  438. } // namespace aria2