DownloadEngine.cc 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  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. #ifdef ENABLE_ASYNC_DNS
  42. #include "AsyncNameResolver.h"
  43. #endif // ENABLE_ASYNC_DNS
  44. #include "StatCalc.h"
  45. #include "RequestGroup.h"
  46. #include "RequestGroupMan.h"
  47. #include "FileAllocationMan.h"
  48. #include "CheckIntegrityMan.h"
  49. #include "DownloadResult.h"
  50. #include "StatCalc.h"
  51. #include "LogFactory.h"
  52. #include "Logger.h"
  53. #include "TimeA2.h"
  54. #include "a2time.h"
  55. #include "Socket.h"
  56. #include "Util.h"
  57. #include "a2functional.h"
  58. #include "DlAbortEx.h"
  59. #include "ServerStatMan.h"
  60. #include "CookieStorage.h"
  61. #include "A2STR.h"
  62. #include "DNSCache.h"
  63. #include "AuthConfigFactory.h"
  64. #include "AuthConfig.h"
  65. #include "Request.h"
  66. #include "BtRegistry.h"
  67. #include "BtContext.h"
  68. #include "PeerStorage.h"
  69. #include "PieceStorage.h"
  70. #include "BtAnnounce.h"
  71. #include "BtRuntime.h"
  72. #include "BtProgressInfoFile.h"
  73. namespace aria2 {
  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. CommandEvent::CommandEvent(Command* command, int events):
  81. _command(command), _events(events) {}
  82. bool CommandEvent::operator==(const CommandEvent& commandEvent) const
  83. {
  84. return _command == commandEvent._command;
  85. }
  86. int CommandEvent::getEvents() const
  87. {
  88. return _events;
  89. }
  90. void CommandEvent::addEvents(int events)
  91. {
  92. _events |= events;
  93. }
  94. void CommandEvent::removeEvents(int events)
  95. {
  96. _events &= (~events);
  97. }
  98. bool CommandEvent::eventsEmpty() const
  99. {
  100. return _events == 0;
  101. }
  102. void CommandEvent::processEvents(int events)
  103. {
  104. if((_events&events) ||
  105. ((SocketEntry::EVENT_ERROR|SocketEntry::EVENT_HUP)&events)) {
  106. _command->setStatusActive();
  107. }
  108. if(SocketEntry::EVENT_READ&events) {
  109. _command->readEventReceived();
  110. }
  111. if(SocketEntry::EVENT_WRITE&events) {
  112. _command->writeEventReceived();
  113. }
  114. if(SocketEntry::EVENT_ERROR&events) {
  115. _command->errorEventReceived();
  116. }
  117. if(SocketEntry::EVENT_HUP&events) {
  118. _command->hupEventReceived();
  119. }
  120. }
  121. #if defined HAVE_EPOLL && defined ENABLE_ASYNC_DNS
  122. ADNSEvent::ADNSEvent(const SharedHandle<AsyncNameResolver>& resolver,
  123. Command* command,
  124. sock_t socket, int events):
  125. _resolver(resolver), _command(command), _socket(socket), _events(events) {}
  126. bool ADNSEvent::operator==(const ADNSEvent& event) const
  127. {
  128. return _resolver == event._resolver;
  129. }
  130. int ADNSEvent::getEvents() const
  131. {
  132. return _events;
  133. }
  134. void ADNSEvent::processEvents(int events)
  135. {
  136. ares_socket_t readfd;
  137. ares_socket_t writefd;
  138. if(events&(SocketEntry::EVENT_READ|SocketEntry::EVENT_ERROR|SocketEntry::EVENT_HUP)) {
  139. readfd = _socket;
  140. } else {
  141. readfd = ARES_SOCKET_BAD;
  142. }
  143. if(events&(SocketEntry::EVENT_WRITE|SocketEntry::EVENT_ERROR|SocketEntry::EVENT_HUP)) {
  144. writefd = _socket;
  145. } else {
  146. writefd = ARES_SOCKET_BAD;
  147. }
  148. _resolver->process(readfd, writefd);
  149. _command->setStatusActive();
  150. }
  151. #endif // HAVE_EPOLL && ENABLE_ASYNC_DNS
  152. SocketEntry::SocketEntry(sock_t socket):_socket(socket)
  153. {
  154. #ifdef HAVE_EPOLL
  155. memset(&_epEvent, 0, sizeof(struct epoll_event));
  156. #endif // HAVE_EPOLL
  157. }
  158. bool SocketEntry::operator==(const SocketEntry& entry) const
  159. {
  160. return _socket == entry._socket;
  161. }
  162. bool SocketEntry::operator<(const SocketEntry& entry) const
  163. {
  164. return _socket < entry._socket;
  165. }
  166. void SocketEntry::addCommandEvent(Command* command, int events)
  167. {
  168. CommandEvent cev(command, events);
  169. std::deque<CommandEvent>::iterator i = std::find(_commandEvents.begin(),
  170. _commandEvents.end(),
  171. cev);
  172. if(i == _commandEvents.end()) {
  173. _commandEvents.push_back(cev);
  174. } else {
  175. (*i).addEvents(events);
  176. }
  177. }
  178. void SocketEntry::removeCommandEvent(Command* command, int events)
  179. {
  180. CommandEvent cev(command, events);
  181. std::deque<CommandEvent>::iterator i = std::find(_commandEvents.begin(),
  182. _commandEvents.end(),
  183. cev);
  184. if(i == _commandEvents.end()) {
  185. // not found
  186. } else {
  187. (*i).removeEvents(events);
  188. if((*i).eventsEmpty()) {
  189. _commandEvents.erase(i);
  190. }
  191. }
  192. }
  193. #if defined HAVE_EPOLL && defined ENABLE_ASYNC_DNS
  194. void SocketEntry::addADNSEvent(const SharedHandle<AsyncNameResolver>& resolver,
  195. Command* command, int events)
  196. {
  197. ADNSEvent aev(resolver, command, _socket, events);
  198. std::deque<ADNSEvent>::iterator i = std::find(_adnsEvents.begin(),
  199. _adnsEvents.end(),
  200. aev);
  201. if(i == _adnsEvents.end()) {
  202. _adnsEvents.push_back(aev);
  203. }
  204. }
  205. void SocketEntry::removeADNSEvent(const SharedHandle<AsyncNameResolver>& resolver,
  206. Command* command)
  207. {
  208. ADNSEvent aev(resolver, command, _socket, 0);
  209. std::deque<ADNSEvent>::iterator i = std::find(_adnsEvents.begin(),
  210. _adnsEvents.end(),
  211. aev);
  212. if(i == _adnsEvents.end()) {
  213. // not found
  214. } else {
  215. _adnsEvents.erase(i);
  216. }
  217. }
  218. #endif // HAVE_EPOLL && ENABLE_ASYNC_DNS
  219. void SocketEntry::processEvents(int events)
  220. {
  221. std::for_each(_commandEvents.begin(), _commandEvents.end(),
  222. std::bind2nd(std::mem_fun_ref(&CommandEvent::processEvents),
  223. events));
  224. #if defined HAVE_EPOLL && defined ENABLE_ASYNC_DNS
  225. std::for_each(_adnsEvents.begin(), _adnsEvents.end(),
  226. std::bind2nd(std::mem_fun_ref(&ADNSEvent::processEvents),
  227. events));
  228. #endif // HAVE_EPOLL && ENABLE_ASYNC_DNS
  229. }
  230. sock_t SocketEntry::getSocket() const
  231. {
  232. return _socket;
  233. }
  234. bool SocketEntry::eventEmpty() const
  235. {
  236. #if defined HAVE_EPOLL && defined ENABLE_ASYNC_DNS
  237. return _commandEvents.empty() && _adnsEvents.empty();
  238. #else // !(HAVE_EPOLL && ENABLE_ASYNC_DNS)
  239. return _commandEvents.empty();
  240. #endif // !(HAVE_EPOLL && ENABLE_ASYNC_DNS)
  241. }
  242. class AccEvent {
  243. public:
  244. int operator()(int events, const CommandEvent& commandEvent) const
  245. {
  246. return events|commandEvent.getEvents();
  247. }
  248. #if defined HAVE_EPOLL && defined ENABLE_ASYNC_DNS
  249. int operator()(int events, const ADNSEvent& adnsEvent) const
  250. {
  251. return events|adnsEvent.getEvents();
  252. }
  253. #endif // HAVE_EPOLL && ENABLE_ASYNC_DNS
  254. };
  255. #ifdef HAVE_EPOLL
  256. struct epoll_event& SocketEntry::getEpEvent()
  257. {
  258. _epEvent.data.ptr = this;
  259. #ifdef ENABLE_ASYNC_DNS
  260. _epEvent.events =
  261. std::accumulate(_adnsEvents.begin(),
  262. _adnsEvents.end(),
  263. std::accumulate(_commandEvents.begin(),
  264. _commandEvents.end(), 0, AccEvent()),
  265. AccEvent());
  266. #else // !ENABLE_ASYNC_DNS
  267. _epEvent.events =
  268. std::accumulate(_commandEvents.begin(), _commandEvents.end(), 0, AccEvent());
  269. #endif // !ENABLE_ASYNC_DNS
  270. return _epEvent;
  271. }
  272. #else // !HAVE_EPOLL
  273. int SocketEntry::getEvents()
  274. {
  275. return
  276. std::accumulate(_commandEvents.begin(), _commandEvents.end(), 0, AccEvent());
  277. }
  278. #endif // !HAVE_EPOLL
  279. #ifdef ENABLE_ASYNC_DNS
  280. AsyncNameResolverEntry::AsyncNameResolverEntry
  281. (const SharedHandle<AsyncNameResolver>& nameResolver, Command* command):
  282. _nameResolver(nameResolver), _command(command)
  283. #ifdef HAVE_EPOLL
  284. , _socketsSize(0)
  285. #endif // HAVE_EPOLL
  286. {}
  287. bool AsyncNameResolverEntry::operator==(const AsyncNameResolverEntry& entry)
  288. {
  289. return _nameResolver == entry._nameResolver &&
  290. _command == entry._command;
  291. }
  292. #ifdef HAVE_EPOLL
  293. void AsyncNameResolverEntry::addSocketEvents(DownloadEngine* e)
  294. {
  295. _socketsSize = 0;
  296. int mask = _nameResolver->getsock(_sockets);
  297. if(mask == 0) {
  298. return;
  299. }
  300. size_t i;
  301. for(i = 0; i < ARES_GETSOCK_MAXNUM; ++i) {
  302. //epoll_event_t* epEventPtr = &_epEvents[_socketsSize];
  303. int events = 0;
  304. if(ARES_GETSOCK_READABLE(mask, i)) {
  305. events |= EPOLLIN;
  306. }
  307. if(ARES_GETSOCK_WRITABLE(mask, i)) {
  308. events |= EPOLLOUT;
  309. }
  310. if(events == 0) {
  311. // assume no further sockets are returned.
  312. break;
  313. }
  314. e->addSocketEvents(_sockets[i], _command, events, _nameResolver);
  315. }
  316. _socketsSize = i;
  317. }
  318. void AsyncNameResolverEntry::removeSocketEvents(DownloadEngine* e)
  319. {
  320. for(size_t i = 0; i < _socketsSize; ++i) {
  321. e->deleteSocketEvents(_sockets[i], _command, 0, _nameResolver);
  322. }
  323. }
  324. #else // !HAVE_EPOLL
  325. int AsyncNameResolverEntry::getFds(fd_set* rfdsPtr, fd_set* wfdsPtr)
  326. {
  327. return _nameResolver->getFds(rfdsPtr, wfdsPtr);
  328. }
  329. void AsyncNameResolverEntry::process(fd_set* rfdsPtr, fd_set* wfdsPtr)
  330. {
  331. _nameResolver->process(rfdsPtr, wfdsPtr);
  332. switch(_nameResolver->getStatus()) {
  333. case AsyncNameResolver::STATUS_SUCCESS:
  334. case AsyncNameResolver::STATUS_ERROR:
  335. _command->setStatusActive();
  336. break;
  337. default:
  338. break;
  339. }
  340. }
  341. #endif // !HAVE_EPOLL
  342. #endif // ENABLE_ASYNC_DNS
  343. DownloadEngine::DownloadEngine():logger(LogFactory::getInstance()),
  344. _haltRequested(false),
  345. _noWait(false),
  346. _refreshInterval(DEFAULT_REFRESH_INTERVAL),
  347. _cookieStorage(new CookieStorage()),
  348. _btRegistry(new BtRegistry()),
  349. _dnsCache(new SimpleDNSCache())
  350. {
  351. #ifdef HAVE_EPOLL
  352. _epfd = epoll_create(EPOLL_EVENTS_MAX);
  353. _epEvents = new struct epoll_event[EPOLL_EVENTS_MAX];
  354. #else // !HAVE_EPOLL
  355. updateFdSet();
  356. #endif // !HAVE_EPOLL
  357. }
  358. DownloadEngine::~DownloadEngine() {
  359. cleanQueue();
  360. #ifdef HAVE_EPOLL
  361. if(_epfd != -1) {
  362. int r;
  363. while((r = close(_epfd)) == -1 && errno == EINTR);
  364. if(r == -1) {
  365. logger->error("Error occurred while closing epoll file descriptor %d: %s",
  366. _epfd, strerror(errno));
  367. }
  368. }
  369. delete [] _epEvents;
  370. #endif // HAVE_EPOLL
  371. }
  372. void DownloadEngine::cleanQueue() {
  373. std::for_each(commands.begin(), commands.end(), Deleter());
  374. commands.clear();
  375. }
  376. static void executeCommand(std::deque<Command*>& commands,
  377. Command::STATUS statusFilter)
  378. {
  379. size_t max = commands.size();
  380. for(size_t i = 0; i < max; i++) {
  381. Command* com = commands.front();
  382. commands.pop_front();
  383. if(com->statusMatch(statusFilter)) {
  384. com->transitStatus();
  385. if(com->execute()) {
  386. delete com;
  387. com = 0;
  388. }
  389. } else {
  390. commands.push_back(com);
  391. }
  392. if(com) {
  393. com->clearIOEvents();
  394. }
  395. }
  396. }
  397. void DownloadEngine::run() {
  398. #ifdef HAVE_EPOLL
  399. if(_epfd == -1) {
  400. throw DlAbortEx("epoll_init() failed.");
  401. }
  402. #endif // HAVE_EPOLL
  403. Time cp;
  404. cp.setTimeInSec(0);
  405. while(!commands.empty() || !_routineCommands.empty()) {
  406. if(cp.elapsed(_refreshInterval)) {
  407. _refreshInterval = DEFAULT_REFRESH_INTERVAL;
  408. cp.reset();
  409. executeCommand(commands, Command::STATUS_ALL);
  410. } else {
  411. executeCommand(commands, Command::STATUS_ACTIVE);
  412. }
  413. executeCommand(_routineCommands, Command::STATUS_ALL);
  414. afterEachIteration();
  415. if(!commands.empty()) {
  416. waitData();
  417. }
  418. _noWait = false;
  419. calculateStatistics();
  420. }
  421. onEndOfRun();
  422. }
  423. void DownloadEngine::shortSleep() const {
  424. struct timeval tv;
  425. tv.tv_sec = 0;
  426. tv.tv_usec = 1000;
  427. fd_set rfds;
  428. FD_ZERO(&rfds);
  429. select(0, &rfds, NULL, NULL, &tv);
  430. }
  431. void DownloadEngine::waitData()
  432. {
  433. #ifdef HAVE_EPOLL
  434. // timeout is millisec
  435. int timeout = _noWait ? 0 : 1000;
  436. int res;
  437. while((res = epoll_wait(_epfd, _epEvents, EPOLL_EVENTS_MAX, timeout)) == -1 &&
  438. errno == EINTR);
  439. if(res > 0) {
  440. for(int i = 0; i < res; ++i) {
  441. SocketEntry* p = (SocketEntry*)_epEvents[i].data.ptr;
  442. p->processEvents(_epEvents[i].events);
  443. }
  444. }
  445. // TODO timeout of name resolver is determined in Command(AbstractCommand,
  446. // DHTEntryPoint...Command)
  447. #else // !HAVE_EPOLL
  448. fd_set rfds;
  449. fd_set wfds;
  450. struct timeval tv;
  451. memcpy(&rfds, &rfdset, sizeof(fd_set));
  452. memcpy(&wfds, &wfdset, sizeof(fd_set));
  453. #ifdef ENABLE_ASYNC_DNS
  454. for(std::deque<SharedHandle<AsyncNameResolverEntry> >::iterator itr =
  455. nameResolverEntries.begin(); itr != nameResolverEntries.end(); ++itr) {
  456. SharedHandle<AsyncNameResolverEntry>& entry = *itr;
  457. int fd = entry->getFds(&rfds, &wfds);
  458. // TODO force error if fd == 0
  459. if(fdmax < fd) {
  460. fdmax = fd;
  461. }
  462. }
  463. #endif // ENABLE_ASYNC_DNS
  464. tv.tv_sec = _noWait ? 0 : 1;
  465. tv.tv_usec = 0;
  466. int retval = select(fdmax+1, &rfds, &wfds, NULL, &tv);
  467. if(retval > 0) {
  468. for(std::deque<SharedHandle<SocketEntry> >::iterator i =
  469. socketEntries.begin(); i != socketEntries.end(); ++i) {
  470. int events = 0;
  471. if(FD_ISSET((*i)->getSocket(), &rfds)) {
  472. events |= SocketEntry::EVENT_READ;
  473. }
  474. if(FD_ISSET((*i)->getSocket(), &wfds)) {
  475. events |= SocketEntry::EVENT_WRITE;
  476. }
  477. (*i)->processEvents(events);
  478. }
  479. }
  480. #ifdef ENABLE_ASYNC_DNS
  481. for(std::deque<SharedHandle<AsyncNameResolverEntry> >::iterator i =
  482. nameResolverEntries.begin(); i != nameResolverEntries.end(); ++i) {
  483. (*i)->process(&rfds, &wfds);
  484. }
  485. #endif // ENABLE_ASYNC_DNS
  486. #endif // !HAVE_EPOLL
  487. }
  488. #ifndef HAVE_EPOLL
  489. void DownloadEngine::updateFdSet() {
  490. fdmax = 0;
  491. FD_ZERO(&rfdset);
  492. FD_ZERO(&wfdset);
  493. for(std::deque<SharedHandle<SocketEntry> >::iterator i =
  494. socketEntries.begin(); i != socketEntries.end(); ++i) {
  495. sock_t fd = (*i)->getSocket();
  496. int events = (*i)->getEvents();
  497. if(events&SocketEntry::EVENT_READ) {
  498. FD_SET(fd, &rfdset);
  499. }
  500. if(events&SocketEntry::EVENT_WRITE) {
  501. FD_SET(fd, &wfdset);
  502. }
  503. if(fdmax < fd) {
  504. fdmax = fd;
  505. }
  506. }
  507. }
  508. #endif // !HAVE_EPOLL
  509. bool DownloadEngine::addSocketEvents(sock_t socket, Command* command, int events
  510. #if defined HAVE_EPOLL && defined ENABLE_ASYNC_DNS
  511. ,const SharedHandle<AsyncNameResolver>& rs
  512. #endif // HAVE_EPOLL && ENABLE_ASYNC_DNS
  513. )
  514. {
  515. SharedHandle<SocketEntry> socketEntry(new SocketEntry(socket));
  516. std::deque<SharedHandle<SocketEntry> >::iterator i =
  517. std::lower_bound(socketEntries.begin(), socketEntries.end(), socketEntry);
  518. int r = 0;
  519. if(i != socketEntries.end() && (*i) == socketEntry) {
  520. #ifdef HAVE_EPOLL
  521. #ifdef ENABLE_ASYNC_DNS
  522. if(rs.isNull()) {
  523. (*i)->addCommandEvent(command, events);
  524. } else {
  525. (*i)->addADNSEvent(rs, command, events);
  526. }
  527. #else // !ENABLE_ASYNC_DNS
  528. (*i)->addCommandEvent(command, events);
  529. #endif // !ENABLE_ASYNC_DNS
  530. r = epoll_ctl(_epfd, EPOLL_CTL_MOD, (*i)->getSocket(), &(*i)->getEpEvent());
  531. if(r == -1) {
  532. // try EPOLL_CTL_ADD: There is a chance that previously socket X is
  533. // added to epoll, but it is closed and is not yet removed from
  534. // SocketEntries. In this case, EPOLL_CTL_MOD is failed with ENOENT.
  535. r = epoll_ctl(_epfd, EPOLL_CTL_ADD, (*i)->getSocket(), &(*i)->getEpEvent());
  536. }
  537. #else // !HAVE_EPOLL
  538. (*i)->addCommandEvent(command, events);
  539. #endif // !HAVE_EPOLL
  540. } else {
  541. socketEntries.insert(i, socketEntry);
  542. #ifdef HAVE_EPOLL
  543. #ifdef ENABLE_ASYNC_DNS
  544. if(rs.isNull()) {
  545. socketEntry->addCommandEvent(command, events);
  546. } else {
  547. socketEntry->addADNSEvent(rs, command, events);
  548. }
  549. #else // !ENABLE_ASYNC_DNS
  550. socketEntry->addCommandEvent(command, events);
  551. #endif // !ENABLE_ASYNC_DNS
  552. r = epoll_ctl(_epfd, EPOLL_CTL_ADD, socketEntry->getSocket(), &socketEntry->getEpEvent());
  553. #else // !HAVE_EPOLL
  554. socketEntry->addCommandEvent(command, events);
  555. #endif // !HAVE_EPOLL
  556. }
  557. #ifndef HAVE_EPOLL
  558. updateFdSet();
  559. #endif // !HAVE_EPOLL
  560. if(r == -1) {
  561. logger->debug("Failed to add socket event %d:%s", socket, strerror(errno));
  562. return false;
  563. } else {
  564. return true;
  565. }
  566. }
  567. bool DownloadEngine::deleteSocketEvents(sock_t socket, Command* command, int events
  568. #if defined HAVE_EPOLL && defined ENABLE_ASYNC_DNS
  569. ,const SharedHandle<AsyncNameResolver>& rs
  570. #endif // HAVE_EPOLL && ENABLE_ASYNC_DNS
  571. )
  572. {
  573. SharedHandle<SocketEntry> socketEntry(new SocketEntry(socket));
  574. std::deque<SharedHandle<SocketEntry> >::iterator i =
  575. std::lower_bound(socketEntries.begin(), socketEntries.end(), socketEntry);
  576. if(i != socketEntries.end() && (*i) == socketEntry) {
  577. #ifdef HAVE_EPOLL
  578. #ifdef ENABLE_ASYNC_DNS
  579. if(rs.isNull()) {
  580. (*i)->removeCommandEvent(command, events);
  581. } else {
  582. (*i)->removeADNSEvent(rs, command);
  583. }
  584. #else // !ENABLE_ASYNC_DNS
  585. (*i)->removeCommandEvent(command, events);
  586. #endif // !ENABLE_ASYNC_DNS
  587. #else // !HAVE_EPOLL
  588. (*i)->removeCommandEvent(command, events);
  589. #endif // !HAVE_EPOLL
  590. int r = 0;
  591. if((*i)->eventEmpty()) {
  592. #ifdef HAVE_EPOLL
  593. r = epoll_ctl(_epfd, EPOLL_CTL_DEL, (*i)->getSocket(), 0);
  594. #endif // HAVE_EPOLL
  595. socketEntries.erase(i);
  596. } else {
  597. #ifdef HAVE_EPOLL
  598. // If socket is closed, then it seems it is automatically removed from
  599. // epoll, so following EPOLL_CTL_MOD may fail.
  600. r = epoll_ctl(_epfd, EPOLL_CTL_MOD, (*i)->getSocket(), &(*i)->getEpEvent());
  601. if(r == -1) {
  602. logger->debug("Failed to delete socket event, but may be ignored:%s", strerror(errno));
  603. }
  604. #endif // HAVE_EPOLL
  605. }
  606. #ifndef HAVE_EPOLL
  607. updateFdSet();
  608. #endif // !HAVE_EPOLL
  609. if(r == -1) {
  610. logger->debug("Failed to delete socket event:%s", strerror(errno));
  611. return false;
  612. } else {
  613. return true;
  614. }
  615. } else {
  616. logger->debug("Socket %d is not found in SocketEntries.", socket);
  617. return false;
  618. }
  619. }
  620. bool DownloadEngine::addSocketForReadCheck(const SocketHandle& socket,
  621. Command* command)
  622. {
  623. return addSocketEvents(socket->getSockfd(), command, SocketEntry::EVENT_READ);
  624. }
  625. bool DownloadEngine::deleteSocketForReadCheck(const SocketHandle& socket,
  626. Command* command)
  627. {
  628. return deleteSocketEvents(socket->getSockfd(), command, SocketEntry::EVENT_READ);
  629. }
  630. bool DownloadEngine::addSocketForWriteCheck(const SocketHandle& socket,
  631. Command* command)
  632. {
  633. return addSocketEvents(socket->getSockfd(), command, SocketEntry::EVENT_WRITE);
  634. }
  635. bool DownloadEngine::deleteSocketForWriteCheck(const SocketHandle& socket,
  636. Command* command)
  637. {
  638. return deleteSocketEvents(socket->getSockfd(), command, SocketEntry::EVENT_WRITE);
  639. }
  640. void DownloadEngine::calculateStatistics()
  641. {
  642. if(!_statCalc.isNull()) {
  643. _statCalc->calculateStat(_requestGroupMan, _fileAllocationMan, _checkIntegrityMan);
  644. }
  645. }
  646. void DownloadEngine::onEndOfRun()
  647. {
  648. _requestGroupMan->updateServerStat();
  649. _requestGroupMan->closeFile();
  650. _requestGroupMan->save();
  651. }
  652. void DownloadEngine::afterEachIteration()
  653. {
  654. if(globalHaltRequested == 1) {
  655. logger->notice(_("Shutdown sequence commencing... Press Ctrl-C again for emergency shutdown."));
  656. requestHalt();
  657. globalHaltRequested = 2;
  658. setNoWait(true);
  659. setRefreshInterval(0);
  660. } else if(globalHaltRequested == 3) {
  661. logger->notice(_("Emergency shutdown sequence commencing..."));
  662. _requestGroupMan->forceHalt();
  663. globalHaltRequested = 4;
  664. setNoWait(true);
  665. setRefreshInterval(0);
  666. }
  667. }
  668. void DownloadEngine::requestHalt()
  669. {
  670. _haltRequested = true;
  671. _requestGroupMan->halt();
  672. }
  673. void DownloadEngine::fillCommand()
  674. {
  675. std::deque<Command*> commands;
  676. _requestGroupMan->getInitialCommands(commands, this);
  677. addCommand(commands);
  678. }
  679. void DownloadEngine::setStatCalc(const StatCalcHandle& statCalc)
  680. {
  681. _statCalc = statCalc;
  682. }
  683. void DownloadEngine::addCommand(const Commands& commands)
  684. {
  685. this->commands.insert(this->commands.end(), commands.begin(), commands.end());
  686. }
  687. #ifdef ENABLE_ASYNC_DNS
  688. bool DownloadEngine::addNameResolverCheck
  689. (const SharedHandle<AsyncNameResolver>& resolver, Command* command)
  690. {
  691. SharedHandle<AsyncNameResolverEntry> entry
  692. (new AsyncNameResolverEntry(resolver, command));
  693. std::deque<SharedHandle<AsyncNameResolverEntry> >::iterator itr =
  694. std::find(nameResolverEntries.begin(), nameResolverEntries.end(), entry);
  695. if(itr == nameResolverEntries.end()) {
  696. nameResolverEntries.push_back(entry);
  697. #ifdef HAVE_EPOLL
  698. entry->addSocketEvents(this);
  699. #endif // HAVE_EPOLL
  700. return true;
  701. } else {
  702. return false;
  703. }
  704. }
  705. bool DownloadEngine::deleteNameResolverCheck
  706. (const SharedHandle<AsyncNameResolver>& resolver, Command* command)
  707. {
  708. SharedHandle<AsyncNameResolverEntry> entry
  709. (new AsyncNameResolverEntry(resolver, command));
  710. std::deque<SharedHandle<AsyncNameResolverEntry> >::iterator itr =
  711. std::find(nameResolverEntries.begin(), nameResolverEntries.end(), entry);
  712. if(itr == nameResolverEntries.end()) {
  713. return false;
  714. } else {
  715. #ifdef HAVE_EPOLL
  716. (*itr)->removeSocketEvents(this);
  717. #endif // HAVE_EPOLL
  718. nameResolverEntries.erase(itr);
  719. return true;
  720. }
  721. }
  722. #endif // ENABLE_ASYNC_DNS
  723. void DownloadEngine::setNoWait(bool b)
  724. {
  725. _noWait = b;
  726. }
  727. void DownloadEngine::addRoutineCommand(Command* command)
  728. {
  729. _routineCommands.push_back(command);
  730. }
  731. SharedHandle<CookieStorage> DownloadEngine::getCookieStorage() const
  732. {
  733. return _cookieStorage;
  734. }
  735. void DownloadEngine::poolSocket(const std::string& ipaddr,
  736. uint16_t port,
  737. const SocketPoolEntry& entry)
  738. {
  739. std::string addr = ipaddr+":"+Util::uitos(port);
  740. logger->info("Pool socket for %s", addr.c_str());
  741. std::multimap<std::string, SocketPoolEntry>::value_type p(addr, entry);
  742. _socketPool.insert(p);
  743. if(_lastSocketPoolScan.elapsed(60)) {
  744. std::multimap<std::string, SocketPoolEntry> newPool;
  745. logger->debug("Scaning SocketPool and erasing timed out entry.");
  746. _lastSocketPoolScan.reset();
  747. for(std::multimap<std::string, SocketPoolEntry>::iterator i =
  748. _socketPool.begin(); i != _socketPool.end(); ++i) {
  749. if(!(*i).second.isTimeout()) {
  750. newPool.insert(*i);
  751. }
  752. }
  753. logger->debug
  754. ("%lu entries removed.",
  755. static_cast<unsigned long>(_socketPool.size()-newPool.size()));
  756. _socketPool = newPool;
  757. }
  758. }
  759. void DownloadEngine::poolSocket
  760. (const std::string& ipaddr,
  761. uint16_t port,
  762. const SharedHandle<SocketCore>& sock,
  763. const std::map<std::string, std::string>& options,
  764. time_t timeout)
  765. {
  766. SocketPoolEntry e(sock, options, timeout);
  767. poolSocket(ipaddr, port, e);
  768. }
  769. void DownloadEngine::poolSocket
  770. (const std::string& ipaddr,
  771. uint16_t port,
  772. const SharedHandle<SocketCore>& sock,
  773. time_t timeout)
  774. {
  775. SocketPoolEntry e(sock, std::map<std::string, std::string>(), timeout);
  776. poolSocket(ipaddr, port, e);
  777. }
  778. void DownloadEngine::poolSocket(const SharedHandle<Request>& request,
  779. bool proxyDefined,
  780. const SharedHandle<SocketCore>& socket,
  781. time_t timeout)
  782. {
  783. if(proxyDefined) {
  784. // If proxy is defined, then pool socket with its hostname.
  785. poolSocket(request->getHost(), request->getPort(), socket);
  786. } else {
  787. std::pair<std::string, uint16_t> peerInfo;
  788. socket->getPeerInfo(peerInfo);
  789. poolSocket(peerInfo.first, peerInfo.second, socket);
  790. }
  791. }
  792. void DownloadEngine::poolSocket
  793. (const SharedHandle<Request>& request,
  794. bool proxyDefined,
  795. const SharedHandle<SocketCore>& socket,
  796. const std::map<std::string, std::string>& options,
  797. time_t timeout)
  798. {
  799. if(proxyDefined) {
  800. // If proxy is defined, then pool socket with its hostname.
  801. poolSocket(request->getHost(), request->getPort(), socket, options);
  802. } else {
  803. std::pair<std::string, uint16_t> peerInfo;
  804. socket->getPeerInfo(peerInfo);
  805. poolSocket(peerInfo.first, peerInfo.second, socket, options);
  806. }
  807. }
  808. std::multimap<std::string, DownloadEngine::SocketPoolEntry>::iterator
  809. DownloadEngine::findSocketPoolEntry(const std::string& ipaddr, uint16_t port)
  810. {
  811. std::string addr = ipaddr+":"+Util::uitos(port);
  812. std::pair<std::multimap<std::string, SocketPoolEntry>::iterator,
  813. std::multimap<std::string, SocketPoolEntry>::iterator> range =
  814. _socketPool.equal_range(addr);
  815. for(std::multimap<std::string, SocketPoolEntry>::iterator i = range.first;
  816. i != range.second; ++i) {
  817. const SocketPoolEntry& e = (*i).second;
  818. if(!e.isTimeout()) {
  819. logger->info("Found socket for %s", addr.c_str());
  820. return i;
  821. }
  822. }
  823. return _socketPool.end();
  824. }
  825. SharedHandle<SocketCore>
  826. DownloadEngine::popPooledSocket(const std::string& ipaddr, uint16_t port)
  827. {
  828. SharedHandle<SocketCore> s;
  829. std::multimap<std::string, SocketPoolEntry>::iterator i =
  830. findSocketPoolEntry(ipaddr, port);
  831. if(i != _socketPool.end()) {
  832. s = (*i).second.getSocket();
  833. _socketPool.erase(i);
  834. }
  835. return s;
  836. }
  837. SharedHandle<SocketCore>
  838. DownloadEngine::popPooledSocket(std::map<std::string, std::string>& options,
  839. const std::string& ipaddr, uint16_t port)
  840. {
  841. SharedHandle<SocketCore> s;
  842. std::multimap<std::string, SocketPoolEntry>::iterator i =
  843. findSocketPoolEntry(ipaddr, port);
  844. if(i != _socketPool.end()) {
  845. s = (*i).second.getSocket();
  846. options = (*i).second.getOptions();
  847. _socketPool.erase(i);
  848. }
  849. return s;
  850. }
  851. SharedHandle<SocketCore>
  852. DownloadEngine::popPooledSocket
  853. (const std::deque<std::string>& ipaddrs, uint16_t port)
  854. {
  855. SharedHandle<SocketCore> s;
  856. for(std::deque<std::string>::const_iterator i = ipaddrs.begin();
  857. i != ipaddrs.end(); ++i) {
  858. s = popPooledSocket(*i, port);
  859. if(!s.isNull()) {
  860. break;
  861. }
  862. }
  863. return s;
  864. }
  865. SharedHandle<SocketCore>
  866. DownloadEngine::popPooledSocket
  867. (std::map<std::string, std::string>& options,
  868. const std::deque<std::string>& ipaddrs, uint16_t port)
  869. {
  870. SharedHandle<SocketCore> s;
  871. for(std::deque<std::string>::const_iterator i = ipaddrs.begin();
  872. i != ipaddrs.end(); ++i) {
  873. s = popPooledSocket(options, *i, port);
  874. if(!s.isNull()) {
  875. break;
  876. }
  877. }
  878. return s;
  879. }
  880. SharedHandle<BtRegistry> DownloadEngine::getBtRegistry() const
  881. {
  882. return _btRegistry;
  883. }
  884. DownloadEngine::SocketPoolEntry::SocketPoolEntry
  885. (const SharedHandle<SocketCore>& socket,
  886. const std::map<std::string, std::string>& options,
  887. time_t timeout):
  888. _socket(socket),
  889. _options(options),
  890. _timeout(timeout) {}
  891. DownloadEngine::SocketPoolEntry::~SocketPoolEntry() {}
  892. bool DownloadEngine::SocketPoolEntry::isTimeout() const
  893. {
  894. return _registeredTime.elapsed(_timeout);
  895. }
  896. SharedHandle<SocketCore> DownloadEngine::SocketPoolEntry::getSocket() const
  897. {
  898. return _socket;
  899. }
  900. const std::map<std::string, std::string>&
  901. DownloadEngine::SocketPoolEntry::getOptions() const
  902. {
  903. return _options;
  904. }
  905. CUID DownloadEngine::newCUID()
  906. {
  907. return _cuidCounter.newID();
  908. }
  909. const std::string& DownloadEngine::findCachedIPAddress
  910. (const std::string& hostname) const
  911. {
  912. return _dnsCache->find(hostname);
  913. }
  914. void DownloadEngine::cacheIPAddress
  915. (const std::string& hostname, const std::string& ipaddr)
  916. {
  917. _dnsCache->put(hostname, ipaddr);
  918. }
  919. void DownloadEngine::setAuthConfigFactory
  920. (const SharedHandle<AuthConfigFactory>& factory)
  921. {
  922. _authConfigFactory = factory;
  923. }
  924. SharedHandle<AuthConfigFactory> DownloadEngine::getAuthConfigFactory() const
  925. {
  926. return _authConfigFactory;
  927. }
  928. void DownloadEngine::setRefreshInterval(time_t interval)
  929. {
  930. _refreshInterval = interval;
  931. }
  932. } // namespace aria2