DownloadEngine.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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 "Socket.h"
  49. #include "util.h"
  50. #include "a2functional.h"
  51. #include "DlAbortEx.h"
  52. #include "ServerStatMan.h"
  53. #include "CookieStorage.h"
  54. #include "A2STR.h"
  55. #include "AuthConfigFactory.h"
  56. #include "AuthConfig.h"
  57. #include "Request.h"
  58. #include "EventPoll.h"
  59. #include "Command.h"
  60. #include "FileAllocationEntry.h"
  61. #include "CheckIntegrityEntry.h"
  62. #include "BtProgressInfoFile.h"
  63. #include "DownloadContext.h"
  64. #ifdef ENABLE_BITTORRENT
  65. # include "BtRegistry.h"
  66. # include "PeerStorage.h"
  67. # include "PieceStorage.h"
  68. # include "BtAnnounce.h"
  69. # include "BtRuntime.h"
  70. #endif // ENABLE_BITTORRENT
  71. namespace aria2 {
  72. namespace global {
  73. // Global clock, this clock is reseted before executeCommand() call to
  74. // reduce the call gettimeofday() system call.
  75. Timer wallclock;
  76. // 0 ... running
  77. // 1 ... stop signal detected
  78. // 2 ... stop signal processed by DownloadEngine
  79. // 3 ... 2nd stop signal(force shutdown) detected
  80. // 4 ... 2nd stop signal processed by DownloadEngine
  81. volatile sig_atomic_t globalHaltRequested = 0;
  82. } // namespace global
  83. DownloadEngine::DownloadEngine(const SharedHandle<EventPoll>& eventPoll):
  84. eventPoll_(eventPoll),
  85. logger_(LogFactory::getInstance()),
  86. haltRequested_(false),
  87. noWait_(false),
  88. refreshInterval_(DEFAULT_REFRESH_INTERVAL),
  89. cookieStorage_(new CookieStorage()),
  90. #ifdef ENABLE_BITTORRENT
  91. btRegistry_(new BtRegistry()),
  92. #endif // ENABLE_BITTORRENT
  93. dnsCache_(new DNSCache())
  94. {
  95. unsigned char sessionId[20];
  96. util::generateRandomKey(sessionId);
  97. sessionId_ = std::string(&sessionId[0], & sessionId[sizeof(sessionId)]);
  98. }
  99. DownloadEngine::~DownloadEngine() {
  100. cleanQueue();
  101. }
  102. void DownloadEngine::cleanQueue() {
  103. std::for_each(commands_.begin(), commands_.end(), Deleter());
  104. commands_.clear();
  105. }
  106. static void executeCommand(std::deque<Command*>& commands,
  107. Command::STATUS statusFilter)
  108. {
  109. size_t max = commands.size();
  110. for(size_t i = 0; i < max; ++i) {
  111. Command* com = commands.front();
  112. commands.pop_front();
  113. if(com->statusMatch(statusFilter)) {
  114. com->transitStatus();
  115. if(com->execute()) {
  116. delete com;
  117. com = 0;
  118. }
  119. } else {
  120. commands.push_back(com);
  121. }
  122. if(com) {
  123. com->clearIOEvents();
  124. }
  125. }
  126. }
  127. void DownloadEngine::run()
  128. {
  129. Timer cp;
  130. cp.reset(0);
  131. while(!commands_.empty() || !routineCommands_.empty()) {
  132. global::wallclock.reset();
  133. if(cp.differenceInMillis(global::wallclock) >= refreshInterval_) {
  134. refreshInterval_ = DEFAULT_REFRESH_INTERVAL;
  135. cp = global::wallclock;
  136. executeCommand(commands_, Command::STATUS_ALL);
  137. } else {
  138. executeCommand(commands_, Command::STATUS_ACTIVE);
  139. }
  140. executeCommand(routineCommands_, Command::STATUS_ALL);
  141. afterEachIteration();
  142. if(!commands_.empty()) {
  143. waitData();
  144. }
  145. noWait_ = false;
  146. calculateStatistics();
  147. }
  148. onEndOfRun();
  149. }
  150. void DownloadEngine::waitData()
  151. {
  152. struct timeval tv;
  153. if(noWait_) {
  154. tv.tv_sec = tv.tv_usec = 0;
  155. } else {
  156. tv.tv_sec = 1;
  157. tv.tv_usec = 0;
  158. }
  159. eventPoll_->poll(tv);
  160. }
  161. bool DownloadEngine::addSocketForReadCheck(const SocketHandle& socket,
  162. Command* command)
  163. {
  164. return eventPoll_->addEvents(socket->getSockfd(), command,
  165. EventPoll::EVENT_READ);
  166. }
  167. bool DownloadEngine::deleteSocketForReadCheck(const SocketHandle& socket,
  168. Command* command)
  169. {
  170. return eventPoll_->deleteEvents(socket->getSockfd(), command,
  171. EventPoll::EVENT_READ);
  172. }
  173. bool DownloadEngine::addSocketForWriteCheck(const SocketHandle& socket,
  174. Command* command)
  175. {
  176. return eventPoll_->addEvents(socket->getSockfd(), command,
  177. EventPoll::EVENT_WRITE);
  178. }
  179. bool DownloadEngine::deleteSocketForWriteCheck(const SocketHandle& socket,
  180. Command* command)
  181. {
  182. return eventPoll_->deleteEvents(socket->getSockfd(), command,
  183. EventPoll::EVENT_WRITE);
  184. }
  185. void DownloadEngine::calculateStatistics()
  186. {
  187. if(!statCalc_.isNull()) {
  188. statCalc_->calculateStat(this);
  189. }
  190. }
  191. void DownloadEngine::onEndOfRun()
  192. {
  193. requestGroupMan_->updateServerStat();
  194. requestGroupMan_->closeFile();
  195. requestGroupMan_->save();
  196. }
  197. void DownloadEngine::afterEachIteration()
  198. {
  199. requestGroupMan_->calculateStat();
  200. if(global::globalHaltRequested == 1) {
  201. logger_->notice(_("Shutdown sequence commencing..."
  202. " Press Ctrl-C again for emergency shutdown."));
  203. requestHalt();
  204. global::globalHaltRequested = 2;
  205. setNoWait(true);
  206. setRefreshInterval(0);
  207. } else if(global::globalHaltRequested == 3) {
  208. logger_->notice(_("Emergency shutdown sequence commencing..."));
  209. requestForceHalt();
  210. global::globalHaltRequested = 4;
  211. setNoWait(true);
  212. setRefreshInterval(0);
  213. }
  214. }
  215. void DownloadEngine::requestHalt()
  216. {
  217. haltRequested_ = true;
  218. requestGroupMan_->halt();
  219. }
  220. void DownloadEngine::requestForceHalt()
  221. {
  222. haltRequested_ = true;
  223. requestGroupMan_->forceHalt();
  224. }
  225. void DownloadEngine::setStatCalc(const StatCalcHandle& statCalc)
  226. {
  227. statCalc_ = statCalc;
  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& key,
  250. const SocketPoolEntry& entry)
  251. {
  252. logger_->info("Pool socket for %s", key.c_str());
  253. std::multimap<std::string, SocketPoolEntry>::value_type p(key, entry);
  254. socketPool_.insert(p);
  255. if(lastSocketPoolScan_.difference(global::wallclock) >= 60) {
  256. std::multimap<std::string, SocketPoolEntry> newPool;
  257. if(logger_->debug()) {
  258. logger_->debug("Scaning SocketPool and erasing timed out entry.");
  259. }
  260. lastSocketPoolScan_ = global::wallclock;
  261. for(std::multimap<std::string, SocketPoolEntry>::iterator i =
  262. socketPool_.begin(), eoi = socketPool_.end(); i != eoi; ++i) {
  263. if(!(*i).second.isTimeout()) {
  264. newPool.insert(*i);
  265. }
  266. }
  267. if(logger_->debug()) {
  268. logger_->debug
  269. ("%lu entries removed.",
  270. static_cast<unsigned long>(socketPool_.size()-newPool.size()));
  271. }
  272. socketPool_ = newPool;
  273. }
  274. }
  275. static std::string createSockPoolKey
  276. (const std::string& host, uint16_t port,
  277. const std::string& username,
  278. const std::string& proxyhost, uint16_t proxyport)
  279. {
  280. std::string key;
  281. if(!username.empty()) {
  282. key += util::percentEncode(username);
  283. key += '@';
  284. }
  285. key += host;
  286. key += A2STR::COLON_C;
  287. key += util::uitos(port);
  288. if(!proxyhost.empty()) {
  289. key += A2STR::SLASH_C;
  290. key += proxyhost;
  291. key += A2STR::COLON_C;
  292. key += util::uitos(proxyport);
  293. }
  294. return key;
  295. }
  296. void DownloadEngine::poolSocket
  297. (const std::string& ipaddr,
  298. uint16_t port,
  299. const std::string& username,
  300. const std::string& proxyhost,
  301. uint16_t proxyport,
  302. const SharedHandle<SocketCore>& sock,
  303. const std::map<std::string, std::string>& options,
  304. time_t timeout)
  305. {
  306. SocketPoolEntry e(sock, options, timeout);
  307. poolSocket(createSockPoolKey(ipaddr, port, username, proxyhost, proxyport),e);
  308. }
  309. void DownloadEngine::poolSocket
  310. (const std::string& ipaddr,
  311. uint16_t port,
  312. const std::string& proxyhost,
  313. uint16_t proxyport,
  314. const SharedHandle<SocketCore>& sock,
  315. time_t timeout)
  316. {
  317. SocketPoolEntry e(sock, timeout);
  318. poolSocket(createSockPoolKey(ipaddr, port, A2STR::NIL,proxyhost,proxyport),e);
  319. }
  320. void DownloadEngine::poolSocket(const SharedHandle<Request>& request,
  321. const SharedHandle<Request>& proxyRequest,
  322. const SharedHandle<SocketCore>& socket,
  323. time_t timeout)
  324. {
  325. if(proxyRequest.isNull()) {
  326. std::pair<std::string, uint16_t> peerInfo;
  327. socket->getPeerInfo(peerInfo);
  328. poolSocket(peerInfo.first, peerInfo.second,
  329. A2STR::NIL, 0, socket, timeout);
  330. } else {
  331. // If proxy is defined, then pool socket with its hostname.
  332. poolSocket(request->getHost(), request->getPort(),
  333. proxyRequest->getHost(), proxyRequest->getPort(),
  334. socket, timeout);
  335. }
  336. }
  337. void DownloadEngine::poolSocket
  338. (const SharedHandle<Request>& request,
  339. const std::string& username,
  340. const SharedHandle<Request>& proxyRequest,
  341. const SharedHandle<SocketCore>& socket,
  342. const std::map<std::string, std::string>& options,
  343. time_t timeout)
  344. {
  345. if(proxyRequest.isNull()) {
  346. std::pair<std::string, uint16_t> peerInfo;
  347. socket->getPeerInfo(peerInfo);
  348. poolSocket(peerInfo.first, peerInfo.second, username,
  349. A2STR::NIL, 0, socket, options, timeout);
  350. } else {
  351. // If proxy is defined, then pool socket with its hostname.
  352. poolSocket(request->getHost(), request->getPort(), username,
  353. proxyRequest->getHost(), proxyRequest->getPort(),
  354. socket, options, timeout);
  355. }
  356. }
  357. std::multimap<std::string, DownloadEngine::SocketPoolEntry>::iterator
  358. DownloadEngine::findSocketPoolEntry(const std::string& key)
  359. {
  360. std::pair<std::multimap<std::string, SocketPoolEntry>::iterator,
  361. std::multimap<std::string, SocketPoolEntry>::iterator> range =
  362. socketPool_.equal_range(key);
  363. for(std::multimap<std::string, SocketPoolEntry>::iterator i =
  364. range.first, eoi = range.second; i != eoi; ++i) {
  365. const SocketPoolEntry& e = (*i).second;
  366. if(!e.isTimeout()) {
  367. logger_->info("Found socket for %s", key.c_str());
  368. return i;
  369. }
  370. }
  371. return socketPool_.end();
  372. }
  373. SharedHandle<SocketCore>
  374. DownloadEngine::popPooledSocket
  375. (const std::string& ipaddr, uint16_t port,
  376. const std::string& proxyhost, uint16_t proxyport)
  377. {
  378. SharedHandle<SocketCore> s;
  379. std::multimap<std::string, SocketPoolEntry>::iterator i =
  380. findSocketPoolEntry
  381. (createSockPoolKey(ipaddr, port, A2STR::NIL, proxyhost, proxyport));
  382. if(i != socketPool_.end()) {
  383. s = (*i).second.getSocket();
  384. socketPool_.erase(i);
  385. }
  386. return s;
  387. }
  388. SharedHandle<SocketCore>
  389. DownloadEngine::popPooledSocket
  390. (std::map<std::string, std::string>& options,
  391. const std::string& ipaddr, uint16_t port,
  392. const std::string& username,
  393. const std::string& proxyhost, uint16_t proxyport)
  394. {
  395. SharedHandle<SocketCore> s;
  396. std::multimap<std::string, SocketPoolEntry>::iterator i =
  397. findSocketPoolEntry
  398. (createSockPoolKey(ipaddr, port, username, proxyhost, proxyport));
  399. if(i != socketPool_.end()) {
  400. s = (*i).second.getSocket();
  401. options = (*i).second.getOptions();
  402. socketPool_.erase(i);
  403. }
  404. return s;
  405. }
  406. SharedHandle<SocketCore>
  407. DownloadEngine::popPooledSocket
  408. (const std::vector<std::string>& ipaddrs, uint16_t port)
  409. {
  410. SharedHandle<SocketCore> s;
  411. for(std::vector<std::string>::const_iterator i = ipaddrs.begin(),
  412. eoi = ipaddrs.end(); i != eoi; ++i) {
  413. s = popPooledSocket(*i, port, A2STR::NIL, 0);
  414. if(!s.isNull()) {
  415. break;
  416. }
  417. }
  418. return s;
  419. }
  420. SharedHandle<SocketCore>
  421. DownloadEngine::popPooledSocket
  422. (std::map<std::string, std::string>& options,
  423. const std::vector<std::string>& ipaddrs, uint16_t port,
  424. const std::string& username)
  425. {
  426. SharedHandle<SocketCore> s;
  427. for(std::vector<std::string>::const_iterator i = ipaddrs.begin(),
  428. eoi = ipaddrs.end(); i != eoi; ++i) {
  429. s = popPooledSocket(options, *i, port, username, A2STR::NIL, 0);
  430. if(!s.isNull()) {
  431. break;
  432. }
  433. }
  434. return s;
  435. }
  436. DownloadEngine::SocketPoolEntry::SocketPoolEntry
  437. (const SharedHandle<SocketCore>& socket,
  438. const std::map<std::string, std::string>& options,
  439. time_t timeout):
  440. socket_(socket),
  441. options_(options),
  442. timeout_(timeout) {}
  443. DownloadEngine::SocketPoolEntry::SocketPoolEntry
  444. (const SharedHandle<SocketCore>& socket, time_t timeout):
  445. socket_(socket),
  446. timeout_(timeout) {}
  447. DownloadEngine::SocketPoolEntry::~SocketPoolEntry() {}
  448. bool DownloadEngine::SocketPoolEntry::isTimeout() const
  449. {
  450. return registeredTime_.difference(global::wallclock) >= timeout_;
  451. }
  452. cuid_t DownloadEngine::newCUID()
  453. {
  454. return cuidCounter_.newID();
  455. }
  456. const std::string& DownloadEngine::findCachedIPAddress
  457. (const std::string& hostname, uint16_t port) const
  458. {
  459. return dnsCache_->find(hostname, port);
  460. }
  461. void DownloadEngine::cacheIPAddress
  462. (const std::string& hostname, const std::string& ipaddr, uint16_t port)
  463. {
  464. dnsCache_->put(hostname, ipaddr, port);
  465. }
  466. void DownloadEngine::markBadIPAddress
  467. (const std::string& hostname, const std::string& ipaddr, uint16_t port)
  468. {
  469. dnsCache_->markBad(hostname, ipaddr, port);
  470. }
  471. void DownloadEngine::removeCachedIPAddress
  472. (const std::string& hostname, uint16_t port)
  473. {
  474. dnsCache_->remove(hostname, port);
  475. }
  476. void DownloadEngine::setAuthConfigFactory
  477. (const SharedHandle<AuthConfigFactory>& factory)
  478. {
  479. authConfigFactory_ = factory;
  480. }
  481. void DownloadEngine::setRefreshInterval(int64_t interval)
  482. {
  483. refreshInterval_ = interval;
  484. }
  485. } // namespace aria2