DownloadEngine.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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. #endif // ENABLE_BITTORRENT
  67. namespace aria2 {
  68. namespace global {
  69. // Global clock, this clock is reseted before executeCommand() call to
  70. // reduce the call gettimeofday() system call.
  71. Timer wallclock;
  72. // 0 ... running
  73. // 1 ... stop signal detected
  74. // 2 ... stop signal processed by DownloadEngine
  75. // 3 ... 2nd stop signal(force shutdown) detected
  76. // 4 ... 2nd stop signal processed by DownloadEngine
  77. volatile sig_atomic_t globalHaltRequested = 0;
  78. } // namespace global
  79. DownloadEngine::DownloadEngine(const SharedHandle<EventPoll>& eventPoll):
  80. eventPoll_(eventPoll),
  81. logger_(LogFactory::getInstance()),
  82. haltRequested_(false),
  83. noWait_(false),
  84. refreshInterval_(DEFAULT_REFRESH_INTERVAL),
  85. cookieStorage_(new CookieStorage()),
  86. #ifdef ENABLE_BITTORRENT
  87. btRegistry_(new BtRegistry()),
  88. #endif // ENABLE_BITTORRENT
  89. dnsCache_(new DNSCache())
  90. {
  91. unsigned char sessionId[20];
  92. util::generateRandomKey(sessionId);
  93. sessionId_ = std::string(&sessionId[0], & sessionId[sizeof(sessionId)]);
  94. }
  95. DownloadEngine::~DownloadEngine() {
  96. cleanQueue();
  97. }
  98. void DownloadEngine::cleanQueue() {
  99. std::for_each(commands_.begin(), commands_.end(), Deleter());
  100. commands_.clear();
  101. }
  102. namespace {
  103. 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. } // namespace
  125. void DownloadEngine::run()
  126. {
  127. Timer cp;
  128. cp.reset(0);
  129. while(!commands_.empty() || !routineCommands_.empty()) {
  130. global::wallclock.reset();
  131. if(cp.differenceInMillis(global::wallclock) >= refreshInterval_) {
  132. refreshInterval_ = DEFAULT_REFRESH_INTERVAL;
  133. cp = global::wallclock;
  134. executeCommand(commands_, Command::STATUS_ALL);
  135. } else {
  136. executeCommand(commands_, Command::STATUS_ACTIVE);
  137. }
  138. executeCommand(routineCommands_, Command::STATUS_ALL);
  139. afterEachIteration();
  140. if(!commands_.empty()) {
  141. waitData();
  142. }
  143. noWait_ = false;
  144. calculateStatistics();
  145. }
  146. onEndOfRun();
  147. }
  148. void DownloadEngine::waitData()
  149. {
  150. struct timeval tv;
  151. if(noWait_) {
  152. tv.tv_sec = tv.tv_usec = 0;
  153. } else {
  154. tv.tv_sec = 1;
  155. tv.tv_usec = 0;
  156. }
  157. eventPoll_->poll(tv);
  158. }
  159. bool DownloadEngine::addSocketForReadCheck(const SocketHandle& socket,
  160. Command* command)
  161. {
  162. return eventPoll_->addEvents(socket->getSockfd(), command,
  163. EventPoll::EVENT_READ);
  164. }
  165. bool DownloadEngine::deleteSocketForReadCheck(const SocketHandle& socket,
  166. Command* command)
  167. {
  168. return eventPoll_->deleteEvents(socket->getSockfd(), command,
  169. EventPoll::EVENT_READ);
  170. }
  171. bool DownloadEngine::addSocketForWriteCheck(const SocketHandle& socket,
  172. Command* command)
  173. {
  174. return eventPoll_->addEvents(socket->getSockfd(), command,
  175. EventPoll::EVENT_WRITE);
  176. }
  177. bool DownloadEngine::deleteSocketForWriteCheck(const SocketHandle& socket,
  178. Command* command)
  179. {
  180. return eventPoll_->deleteEvents(socket->getSockfd(), command,
  181. EventPoll::EVENT_WRITE);
  182. }
  183. void DownloadEngine::calculateStatistics()
  184. {
  185. if(statCalc_) {
  186. statCalc_->calculateStat(this);
  187. }
  188. }
  189. void DownloadEngine::onEndOfRun()
  190. {
  191. requestGroupMan_->updateServerStat();
  192. requestGroupMan_->closeFile();
  193. requestGroupMan_->save();
  194. }
  195. void DownloadEngine::afterEachIteration()
  196. {
  197. requestGroupMan_->calculateStat();
  198. if(global::globalHaltRequested == 1) {
  199. logger_->notice(_("Shutdown sequence commencing..."
  200. " Press Ctrl-C again for emergency shutdown."));
  201. requestHalt();
  202. global::globalHaltRequested = 2;
  203. setNoWait(true);
  204. setRefreshInterval(0);
  205. } else if(global::globalHaltRequested == 3) {
  206. logger_->notice(_("Emergency shutdown sequence commencing..."));
  207. requestForceHalt();
  208. global::globalHaltRequested = 4;
  209. setNoWait(true);
  210. setRefreshInterval(0);
  211. }
  212. }
  213. void DownloadEngine::requestHalt()
  214. {
  215. haltRequested_ = true;
  216. requestGroupMan_->halt();
  217. }
  218. void DownloadEngine::requestForceHalt()
  219. {
  220. haltRequested_ = true;
  221. requestGroupMan_->forceHalt();
  222. }
  223. void DownloadEngine::setStatCalc(const StatCalcHandle& statCalc)
  224. {
  225. statCalc_ = statCalc;
  226. }
  227. #ifdef ENABLE_ASYNC_DNS
  228. bool DownloadEngine::addNameResolverCheck
  229. (const SharedHandle<AsyncNameResolver>& resolver, Command* command)
  230. {
  231. return eventPoll_->addNameResolver(resolver, command);
  232. }
  233. bool DownloadEngine::deleteNameResolverCheck
  234. (const SharedHandle<AsyncNameResolver>& resolver, Command* command)
  235. {
  236. return eventPoll_->deleteNameResolver(resolver, command);
  237. }
  238. #endif // ENABLE_ASYNC_DNS
  239. void DownloadEngine::setNoWait(bool b)
  240. {
  241. noWait_ = b;
  242. }
  243. void DownloadEngine::addRoutineCommand(Command* command)
  244. {
  245. routineCommands_.push_back(command);
  246. }
  247. void DownloadEngine::poolSocket(const std::string& key,
  248. const SocketPoolEntry& entry)
  249. {
  250. logger_->info("Pool socket for %s", key.c_str());
  251. std::multimap<std::string, SocketPoolEntry>::value_type p(key, entry);
  252. socketPool_.insert(p);
  253. if(lastSocketPoolScan_.difference(global::wallclock) >= 60) {
  254. std::multimap<std::string, SocketPoolEntry> newPool;
  255. if(logger_->debug()) {
  256. logger_->debug("Scaning SocketPool and erasing timed out entry.");
  257. }
  258. lastSocketPoolScan_ = global::wallclock;
  259. for(std::multimap<std::string, SocketPoolEntry>::iterator i =
  260. socketPool_.begin(), eoi = socketPool_.end(); i != eoi; ++i) {
  261. if(!(*i).second.isTimeout()) {
  262. newPool.insert(*i);
  263. }
  264. }
  265. if(logger_->debug()) {
  266. logger_->debug
  267. ("%lu entries removed.",
  268. static_cast<unsigned long>(socketPool_.size()-newPool.size()));
  269. }
  270. socketPool_ = newPool;
  271. }
  272. }
  273. namespace {
  274. std::string createSockPoolKey
  275. (const std::string& host, uint16_t port,
  276. const std::string& username,
  277. const std::string& proxyhost, uint16_t proxyport)
  278. {
  279. std::string key;
  280. if(!username.empty()) {
  281. key += util::percentEncode(username);
  282. key += '@';
  283. }
  284. key += host;
  285. key += A2STR::COLON_C;
  286. key += util::uitos(port);
  287. if(!proxyhost.empty()) {
  288. key += A2STR::SLASH_C;
  289. key += proxyhost;
  290. key += A2STR::COLON_C;
  291. key += util::uitos(proxyport);
  292. }
  293. return key;
  294. }
  295. } // namespace
  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) {
  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) {
  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. // We assume that if socket is readable it means peer shutdowns
  367. // connection and the socket will receive EOF. So skip it.
  368. if(!e.isTimeout() && !e.getSocket()->isReadable(0)) {
  369. logger_->info("Found socket for %s", key.c_str());
  370. return i;
  371. }
  372. }
  373. return socketPool_.end();
  374. }
  375. SharedHandle<SocketCore>
  376. DownloadEngine::popPooledSocket
  377. (const std::string& ipaddr, uint16_t port,
  378. const std::string& proxyhost, uint16_t proxyport)
  379. {
  380. SharedHandle<SocketCore> s;
  381. std::multimap<std::string, SocketPoolEntry>::iterator i =
  382. findSocketPoolEntry
  383. (createSockPoolKey(ipaddr, port, A2STR::NIL, proxyhost, proxyport));
  384. if(i != socketPool_.end()) {
  385. s = (*i).second.getSocket();
  386. socketPool_.erase(i);
  387. }
  388. return s;
  389. }
  390. SharedHandle<SocketCore>
  391. DownloadEngine::popPooledSocket
  392. (std::map<std::string, std::string>& options,
  393. const std::string& ipaddr, uint16_t port,
  394. const std::string& username,
  395. const std::string& proxyhost, uint16_t proxyport)
  396. {
  397. SharedHandle<SocketCore> s;
  398. std::multimap<std::string, SocketPoolEntry>::iterator i =
  399. findSocketPoolEntry
  400. (createSockPoolKey(ipaddr, port, username, proxyhost, proxyport));
  401. if(i != socketPool_.end()) {
  402. s = (*i).second.getSocket();
  403. options = (*i).second.getOptions();
  404. socketPool_.erase(i);
  405. }
  406. return s;
  407. }
  408. SharedHandle<SocketCore>
  409. DownloadEngine::popPooledSocket
  410. (const std::vector<std::string>& ipaddrs, uint16_t port)
  411. {
  412. SharedHandle<SocketCore> s;
  413. for(std::vector<std::string>::const_iterator i = ipaddrs.begin(),
  414. eoi = ipaddrs.end(); i != eoi; ++i) {
  415. s = popPooledSocket(*i, port, A2STR::NIL, 0);
  416. if(s) {
  417. break;
  418. }
  419. }
  420. return s;
  421. }
  422. SharedHandle<SocketCore>
  423. DownloadEngine::popPooledSocket
  424. (std::map<std::string, std::string>& options,
  425. const std::vector<std::string>& ipaddrs, uint16_t port,
  426. const std::string& username)
  427. {
  428. SharedHandle<SocketCore> s;
  429. for(std::vector<std::string>::const_iterator i = ipaddrs.begin(),
  430. eoi = ipaddrs.end(); i != eoi; ++i) {
  431. s = popPooledSocket(options, *i, port, username, A2STR::NIL, 0);
  432. if(s) {
  433. break;
  434. }
  435. }
  436. return s;
  437. }
  438. DownloadEngine::SocketPoolEntry::SocketPoolEntry
  439. (const SharedHandle<SocketCore>& socket,
  440. const std::map<std::string, std::string>& options,
  441. time_t timeout):
  442. socket_(socket),
  443. options_(options),
  444. timeout_(timeout) {}
  445. DownloadEngine::SocketPoolEntry::SocketPoolEntry
  446. (const SharedHandle<SocketCore>& socket, time_t timeout):
  447. socket_(socket),
  448. timeout_(timeout) {}
  449. DownloadEngine::SocketPoolEntry::~SocketPoolEntry() {}
  450. bool DownloadEngine::SocketPoolEntry::isTimeout() const
  451. {
  452. return registeredTime_.difference(global::wallclock) >= timeout_;
  453. }
  454. cuid_t DownloadEngine::newCUID()
  455. {
  456. return cuidCounter_.newID();
  457. }
  458. const std::string& DownloadEngine::findCachedIPAddress
  459. (const std::string& hostname, uint16_t port) const
  460. {
  461. return dnsCache_->find(hostname, port);
  462. }
  463. void DownloadEngine::cacheIPAddress
  464. (const std::string& hostname, const std::string& ipaddr, uint16_t port)
  465. {
  466. dnsCache_->put(hostname, ipaddr, port);
  467. }
  468. void DownloadEngine::markBadIPAddress
  469. (const std::string& hostname, const std::string& ipaddr, uint16_t port)
  470. {
  471. dnsCache_->markBad(hostname, ipaddr, port);
  472. }
  473. void DownloadEngine::removeCachedIPAddress
  474. (const std::string& hostname, uint16_t port)
  475. {
  476. dnsCache_->remove(hostname, port);
  477. }
  478. void DownloadEngine::setAuthConfigFactory
  479. (const SharedHandle<AuthConfigFactory>& factory)
  480. {
  481. authConfigFactory_ = factory;
  482. }
  483. void DownloadEngine::setRefreshInterval(int64_t interval)
  484. {
  485. refreshInterval_ = interval;
  486. }
  487. void DownloadEngine::addCommand(const std::vector<Command*>& commands)
  488. {
  489. commands_.insert(commands_.end(), commands.begin(), commands.end());
  490. }
  491. void DownloadEngine::addCommand(Command* command)
  492. {
  493. commands_.push_back(command);
  494. }
  495. void DownloadEngine::setRequestGroupMan
  496. (const SharedHandle<RequestGroupMan>& rgman)
  497. {
  498. requestGroupMan_ = rgman;
  499. }
  500. void DownloadEngine::setFileAllocationMan
  501. (const SharedHandle<FileAllocationMan>& faman)
  502. {
  503. fileAllocationMan_ = faman;
  504. }
  505. void DownloadEngine::setCheckIntegrityMan
  506. (const SharedHandle<CheckIntegrityMan>& ciman)
  507. {
  508. checkIntegrityMan_ = ciman;
  509. }
  510. } // namespace aria2