DownloadEngine.cc 16 KB

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