DownloadEngine.cc 14 KB

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