DownloadEngine.cc 17 KB

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