DownloadEngine.cc 25 KB

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