DownloadEngine.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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 "SocketCore.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. #include "fmt.h"
  65. #include "wallclock.h"
  66. #ifdef ENABLE_BITTORRENT
  67. # include "BtRegistry.h"
  68. #endif // ENABLE_BITTORRENT
  69. namespace aria2 {
  70. namespace global {
  71. // 0 ... running
  72. // 1 ... stop signal detected
  73. // 2 ... stop signal processed by DownloadEngine
  74. // 3 ... 2nd stop signal(force shutdown) detected
  75. // 4 ... 2nd stop signal processed by DownloadEngine
  76. volatile sig_atomic_t globalHaltRequested = 0;
  77. } // namespace global
  78. DownloadEngine::DownloadEngine(const SharedHandle<EventPoll>& eventPoll)
  79. : eventPoll_(eventPoll),
  80. haltRequested_(false),
  81. noWait_(false),
  82. refreshInterval_(DEFAULT_REFRESH_INTERVAL),
  83. cookieStorage_(new CookieStorage()),
  84. #ifdef ENABLE_BITTORRENT
  85. btRegistry_(new BtRegistry()),
  86. #endif // ENABLE_BITTORRENT
  87. #ifdef HAVE_ARES_ADDR_NODE
  88. asyncDNSServers_(0),
  89. #endif // HAVE_ARES_ADDR_NODE
  90. dnsCache_(new DNSCache()),
  91. option_(0)
  92. {
  93. unsigned char sessionId[20];
  94. util::generateRandomKey(sessionId);
  95. sessionId_.assign(&sessionId[0], & sessionId[sizeof(sessionId)]);
  96. }
  97. DownloadEngine::~DownloadEngine() {
  98. cleanQueue();
  99. #ifdef HAVE_ARES_ADDR_NODE
  100. setAsyncDNSServers(0);
  101. #endif // HAVE_ARES_ADDR_NODE
  102. }
  103. void DownloadEngine::cleanQueue() {
  104. std::for_each(commands_.begin(), commands_.end(), Deleter());
  105. commands_.clear();
  106. }
  107. namespace {
  108. 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. } // namespace
  130. void DownloadEngine::run()
  131. {
  132. Timer cp;
  133. cp.reset(0);
  134. while(!commands_.empty() || !routineCommands_.empty()) {
  135. global::wallclock().reset();
  136. calculateStatistics();
  137. if(cp.differenceInMillis(global::wallclock())+A2_DELTA_MILLIS >=
  138. refreshInterval_) {
  139. refreshInterval_ = DEFAULT_REFRESH_INTERVAL;
  140. cp = global::wallclock();
  141. executeCommand(commands_, Command::STATUS_ALL);
  142. } else {
  143. executeCommand(commands_, Command::STATUS_ACTIVE);
  144. }
  145. executeCommand(routineCommands_, Command::STATUS_ALL);
  146. afterEachIteration();
  147. if(!commands_.empty()) {
  148. waitData();
  149. }
  150. noWait_ = false;
  151. }
  152. onEndOfRun();
  153. }
  154. void DownloadEngine::waitData()
  155. {
  156. struct timeval tv;
  157. if(noWait_) {
  158. tv.tv_sec = tv.tv_usec = 0;
  159. } else {
  160. lldiv_t qr = lldiv(refreshInterval_*1000, 1000000);
  161. tv.tv_sec = qr.quot;
  162. tv.tv_usec = qr.rem;
  163. }
  164. eventPoll_->poll(tv);
  165. }
  166. bool DownloadEngine::addSocketForReadCheck(const SharedHandle<SocketCore>& socket,
  167. Command* command)
  168. {
  169. return eventPoll_->addEvents(socket->getSockfd(), command,
  170. EventPoll::EVENT_READ);
  171. }
  172. bool DownloadEngine::deleteSocketForReadCheck(const SharedHandle<SocketCore>& socket,
  173. Command* command)
  174. {
  175. return eventPoll_->deleteEvents(socket->getSockfd(), command,
  176. EventPoll::EVENT_READ);
  177. }
  178. bool DownloadEngine::addSocketForWriteCheck(const SharedHandle<SocketCore>& socket,
  179. Command* command)
  180. {
  181. return eventPoll_->addEvents(socket->getSockfd(), command,
  182. EventPoll::EVENT_WRITE);
  183. }
  184. bool DownloadEngine::deleteSocketForWriteCheck(const SharedHandle<SocketCore>& socket,
  185. Command* command)
  186. {
  187. return eventPoll_->deleteEvents(socket->getSockfd(), command,
  188. EventPoll::EVENT_WRITE);
  189. }
  190. void DownloadEngine::calculateStatistics()
  191. {
  192. if(statCalc_) {
  193. statCalc_->calculateStat(this);
  194. }
  195. }
  196. void DownloadEngine::onEndOfRun()
  197. {
  198. requestGroupMan_->removeStoppedGroup(this);
  199. requestGroupMan_->closeFile();
  200. requestGroupMan_->save();
  201. }
  202. void DownloadEngine::afterEachIteration()
  203. {
  204. if(global::globalHaltRequested == 1) {
  205. A2_LOG_NOTICE(_("Shutdown sequence commencing..."
  206. " Press Ctrl-C again for emergency shutdown."));
  207. requestHalt();
  208. global::globalHaltRequested = 2;
  209. setNoWait(true);
  210. setRefreshInterval(0);
  211. } else if(global::globalHaltRequested == 3) {
  212. A2_LOG_NOTICE(_("Emergency shutdown sequence commencing..."));
  213. requestForceHalt();
  214. global::globalHaltRequested = 4;
  215. setNoWait(true);
  216. setRefreshInterval(0);
  217. }
  218. }
  219. void DownloadEngine::requestHalt()
  220. {
  221. haltRequested_ = true;
  222. requestGroupMan_->halt();
  223. }
  224. void DownloadEngine::requestForceHalt()
  225. {
  226. haltRequested_ = true;
  227. requestGroupMan_->forceHalt();
  228. }
  229. void DownloadEngine::setStatCalc(const SharedHandle<StatCalc>& statCalc)
  230. {
  231. statCalc_ = statCalc;
  232. }
  233. #ifdef ENABLE_ASYNC_DNS
  234. bool DownloadEngine::addNameResolverCheck
  235. (const SharedHandle<AsyncNameResolver>& resolver, Command* command)
  236. {
  237. return eventPoll_->addNameResolver(resolver, command);
  238. }
  239. bool DownloadEngine::deleteNameResolverCheck
  240. (const SharedHandle<AsyncNameResolver>& resolver, Command* command)
  241. {
  242. return eventPoll_->deleteNameResolver(resolver, command);
  243. }
  244. #endif // ENABLE_ASYNC_DNS
  245. void DownloadEngine::setNoWait(bool b)
  246. {
  247. noWait_ = b;
  248. }
  249. void DownloadEngine::addRoutineCommand(Command* command)
  250. {
  251. routineCommands_.push_back(command);
  252. }
  253. void DownloadEngine::poolSocket(const std::string& key,
  254. const SocketPoolEntry& entry)
  255. {
  256. A2_LOG_INFO(fmt("Pool socket for %s", key.c_str()));
  257. std::multimap<std::string, SocketPoolEntry>::value_type p(key, entry);
  258. socketPool_.insert(p);
  259. if(lastSocketPoolScan_.difference(global::wallclock()) >= 60) {
  260. std::multimap<std::string, SocketPoolEntry> newPool;
  261. A2_LOG_DEBUG("Scaning SocketPool and erasing timed out entry.");
  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. A2_LOG_DEBUG(fmt("%lu entries removed.",
  270. static_cast<unsigned long>
  271. (socketPool_.size()-newPool.size())));
  272. socketPool_ = newPool;
  273. }
  274. }
  275. namespace {
  276. std::string createSockPoolKey
  277. (const std::string& host, uint16_t port,
  278. const std::string& username,
  279. const std::string& proxyhost, uint16_t proxyport)
  280. {
  281. std::string key;
  282. if(!username.empty()) {
  283. key += util::percentEncode(username);
  284. key += "@";
  285. }
  286. key += fmt("%s(%u)", host.c_str(), port);
  287. if(!proxyhost.empty()) {
  288. key += fmt("/%s(%u)", proxyhost.c_str(), proxyport);
  289. }
  290. return key;
  291. }
  292. } // namespace
  293. void DownloadEngine::poolSocket
  294. (const std::string& ipaddr,
  295. uint16_t port,
  296. const std::string& username,
  297. const std::string& proxyhost,
  298. uint16_t proxyport,
  299. const SharedHandle<SocketCore>& sock,
  300. const std::string& options,
  301. time_t timeout)
  302. {
  303. SocketPoolEntry e(sock, options, timeout);
  304. poolSocket(createSockPoolKey(ipaddr, port, username, proxyhost, proxyport),e);
  305. }
  306. void DownloadEngine::poolSocket
  307. (const std::string& ipaddr,
  308. uint16_t port,
  309. const std::string& proxyhost,
  310. uint16_t proxyport,
  311. const SharedHandle<SocketCore>& sock,
  312. time_t timeout)
  313. {
  314. SocketPoolEntry e(sock, timeout);
  315. poolSocket(createSockPoolKey(ipaddr, port, A2STR::NIL,proxyhost,proxyport),e);
  316. }
  317. namespace {
  318. bool getPeerInfo(std::pair<std::string, uint16_t>& res,
  319. const SharedHandle<SocketCore>& socket)
  320. {
  321. try {
  322. socket->getPeerInfo(res);
  323. return true;
  324. } catch(RecoverableException& e) {
  325. // socket->getPeerInfo() can fail if the socket has been
  326. // disconnected.
  327. A2_LOG_INFO_EX("Getting peer info failed. Pooling socket canceled.", e);
  328. return false;
  329. }
  330. }
  331. } // namespace
  332. void DownloadEngine::poolSocket(const SharedHandle<Request>& request,
  333. const SharedHandle<Request>& proxyRequest,
  334. const SharedHandle<SocketCore>& socket,
  335. time_t timeout)
  336. {
  337. if(!proxyRequest) {
  338. std::pair<std::string, uint16_t> peerInfo;
  339. if(getPeerInfo(peerInfo, socket)) {
  340. poolSocket(peerInfo.first, peerInfo.second,
  341. A2STR::NIL, 0, socket, timeout);
  342. }
  343. } else {
  344. // If proxy is defined, then pool socket with its hostname.
  345. poolSocket(request->getHost(), request->getPort(),
  346. proxyRequest->getHost(), proxyRequest->getPort(),
  347. socket, timeout);
  348. }
  349. }
  350. void DownloadEngine::poolSocket
  351. (const SharedHandle<Request>& request,
  352. const std::string& username,
  353. const SharedHandle<Request>& proxyRequest,
  354. const SharedHandle<SocketCore>& socket,
  355. const std::string& options,
  356. time_t timeout)
  357. {
  358. if(!proxyRequest) {
  359. std::pair<std::string, uint16_t> peerInfo;
  360. if(getPeerInfo(peerInfo, socket)) {
  361. poolSocket(peerInfo.first, peerInfo.second, username,
  362. A2STR::NIL, 0, socket, options, timeout);
  363. }
  364. } else {
  365. // If proxy is defined, then pool socket with its hostname.
  366. poolSocket(request->getHost(), request->getPort(), username,
  367. proxyRequest->getHost(), proxyRequest->getPort(),
  368. socket, options, timeout);
  369. }
  370. }
  371. std::multimap<std::string, DownloadEngine::SocketPoolEntry>::iterator
  372. DownloadEngine::findSocketPoolEntry(const std::string& key)
  373. {
  374. std::pair<std::multimap<std::string, SocketPoolEntry>::iterator,
  375. std::multimap<std::string, SocketPoolEntry>::iterator> range =
  376. socketPool_.equal_range(key);
  377. for(std::multimap<std::string, SocketPoolEntry>::iterator i =
  378. range.first, eoi = range.second; i != eoi; ++i) {
  379. const SocketPoolEntry& e = (*i).second;
  380. // We assume that if socket is readable it means peer shutdowns
  381. // connection and the socket will receive EOF. So skip it.
  382. if(!e.isTimeout() && !e.getSocket()->isReadable(0)) {
  383. A2_LOG_INFO(fmt("Found socket for %s", key.c_str()));
  384. return i;
  385. }
  386. }
  387. return socketPool_.end();
  388. }
  389. SharedHandle<SocketCore>
  390. DownloadEngine::popPooledSocket
  391. (const std::string& ipaddr, uint16_t port,
  392. const std::string& proxyhost, uint16_t proxyport)
  393. {
  394. SharedHandle<SocketCore> s;
  395. std::multimap<std::string, SocketPoolEntry>::iterator i =
  396. findSocketPoolEntry
  397. (createSockPoolKey(ipaddr, port, A2STR::NIL, proxyhost, proxyport));
  398. if(i != socketPool_.end()) {
  399. s = (*i).second.getSocket();
  400. socketPool_.erase(i);
  401. }
  402. return s;
  403. }
  404. SharedHandle<SocketCore>
  405. DownloadEngine::popPooledSocket
  406. (std::string& options,
  407. const std::string& ipaddr, uint16_t port,
  408. const std::string& username,
  409. const std::string& proxyhost, uint16_t proxyport)
  410. {
  411. SharedHandle<SocketCore> s;
  412. std::multimap<std::string, SocketPoolEntry>::iterator i =
  413. findSocketPoolEntry
  414. (createSockPoolKey(ipaddr, port, username, proxyhost, proxyport));
  415. if(i != socketPool_.end()) {
  416. s = (*i).second.getSocket();
  417. options = (*i).second.getOptions();
  418. socketPool_.erase(i);
  419. }
  420. return s;
  421. }
  422. SharedHandle<SocketCore>
  423. DownloadEngine::popPooledSocket
  424. (const std::vector<std::string>& ipaddrs, uint16_t port)
  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(*i, port, A2STR::NIL, 0);
  430. if(s) {
  431. break;
  432. }
  433. }
  434. return s;
  435. }
  436. SharedHandle<SocketCore>
  437. DownloadEngine::popPooledSocket
  438. (std::string& options,
  439. const std::vector<std::string>& ipaddrs, uint16_t port,
  440. const std::string& username)
  441. {
  442. SharedHandle<SocketCore> s;
  443. for(std::vector<std::string>::const_iterator i = ipaddrs.begin(),
  444. eoi = ipaddrs.end(); i != eoi; ++i) {
  445. s = popPooledSocket(options, *i, port, username, A2STR::NIL, 0);
  446. if(s) {
  447. break;
  448. }
  449. }
  450. return s;
  451. }
  452. DownloadEngine::SocketPoolEntry::SocketPoolEntry
  453. (const SharedHandle<SocketCore>& socket,
  454. const std::string& options,
  455. time_t timeout)
  456. : socket_(socket),
  457. options_(options),
  458. timeout_(timeout)
  459. {}
  460. DownloadEngine::SocketPoolEntry::SocketPoolEntry
  461. (const SharedHandle<SocketCore>& socket, time_t timeout)
  462. : socket_(socket),
  463. timeout_(timeout)
  464. {}
  465. DownloadEngine::SocketPoolEntry::~SocketPoolEntry() {}
  466. bool DownloadEngine::SocketPoolEntry::isTimeout() const
  467. {
  468. return registeredTime_.difference(global::wallclock()) >= timeout_;
  469. }
  470. cuid_t DownloadEngine::newCUID()
  471. {
  472. return cuidCounter_.newID();
  473. }
  474. const std::string& DownloadEngine::findCachedIPAddress
  475. (const std::string& hostname, uint16_t port) const
  476. {
  477. return dnsCache_->find(hostname, port);
  478. }
  479. void DownloadEngine::cacheIPAddress
  480. (const std::string& hostname, const std::string& ipaddr, uint16_t port)
  481. {
  482. dnsCache_->put(hostname, ipaddr, port);
  483. }
  484. void DownloadEngine::markBadIPAddress
  485. (const std::string& hostname, const std::string& ipaddr, uint16_t port)
  486. {
  487. dnsCache_->markBad(hostname, ipaddr, port);
  488. }
  489. void DownloadEngine::removeCachedIPAddress
  490. (const std::string& hostname, uint16_t port)
  491. {
  492. dnsCache_->remove(hostname, port);
  493. }
  494. void DownloadEngine::setAuthConfigFactory
  495. (const SharedHandle<AuthConfigFactory>& factory)
  496. {
  497. authConfigFactory_ = factory;
  498. }
  499. void DownloadEngine::setRefreshInterval(int64_t interval)
  500. {
  501. refreshInterval_ = std::min(static_cast<int64_t>(999), interval);
  502. }
  503. void DownloadEngine::addCommand(const std::vector<Command*>& commands)
  504. {
  505. commands_.insert(commands_.end(), commands.begin(), commands.end());
  506. }
  507. void DownloadEngine::addCommand(Command* command)
  508. {
  509. commands_.push_back(command);
  510. }
  511. void DownloadEngine::setRequestGroupMan
  512. (const SharedHandle<RequestGroupMan>& rgman)
  513. {
  514. requestGroupMan_ = rgman;
  515. }
  516. void DownloadEngine::setFileAllocationMan
  517. (const SharedHandle<FileAllocationMan>& faman)
  518. {
  519. fileAllocationMan_ = faman;
  520. }
  521. void DownloadEngine::setCheckIntegrityMan
  522. (const SharedHandle<CheckIntegrityMan>& ciman)
  523. {
  524. checkIntegrityMan_ = ciman;
  525. }
  526. #ifdef HAVE_ARES_ADDR_NODE
  527. void DownloadEngine::setAsyncDNSServers(ares_addr_node* asyncDNSServers)
  528. {
  529. ares_addr_node* node = asyncDNSServers_;
  530. while(node) {
  531. ares_addr_node* next = node->next;
  532. delete node;
  533. node = next;
  534. }
  535. asyncDNSServers_ = asyncDNSServers;
  536. }
  537. #endif // HAVE_ARES_ADDR_NODE
  538. } // namespace aria2