EpollEventPoll.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2009 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 "EpollEventPoll.h"
  36. #include <cstring>
  37. #include <algorithm>
  38. #include <numeric>
  39. #include "Command.h"
  40. #include "LogFactory.h"
  41. #include "Logger.h"
  42. namespace aria2 {
  43. EpollEventPoll::CommandEvent::CommandEvent(Command* command, int events):
  44. _command(command), _events(events) {}
  45. bool EpollEventPoll::CommandEvent::operator==
  46. (const CommandEvent& commandEvent) const
  47. {
  48. return _command == commandEvent._command;
  49. }
  50. Command* EpollEventPoll::CommandEvent::getCommand() const
  51. {
  52. return _command;
  53. }
  54. int EpollEventPoll::CommandEvent::getEvents() const
  55. {
  56. return _events;
  57. }
  58. void EpollEventPoll::CommandEvent::addEvents(int events)
  59. {
  60. _events |= events;
  61. }
  62. void EpollEventPoll::CommandEvent::removeEvents(int events)
  63. {
  64. _events &= (~events);
  65. }
  66. bool EpollEventPoll::CommandEvent::eventsEmpty() const
  67. {
  68. return _events == 0;
  69. }
  70. void EpollEventPoll::CommandEvent::processEvents(int events)
  71. {
  72. if((_events&events) ||
  73. ((EpollEventPoll::EVENT_ERROR|EpollEventPoll::EVENT_HUP)&events)) {
  74. _command->setStatusActive();
  75. }
  76. if(EpollEventPoll::EVENT_READ&events) {
  77. _command->readEventReceived();
  78. }
  79. if(EpollEventPoll::EVENT_WRITE&events) {
  80. _command->writeEventReceived();
  81. }
  82. if(EpollEventPoll::EVENT_ERROR&events) {
  83. _command->errorEventReceived();
  84. }
  85. if(EpollEventPoll::EVENT_HUP&events) {
  86. _command->hupEventReceived();
  87. }
  88. }
  89. void EpollEventPoll::CommandEvent::addSelf
  90. (const SharedHandle<SocketEntry>& socketEntry) const
  91. {
  92. socketEntry->addCommandEvent(*this);
  93. }
  94. void EpollEventPoll::CommandEvent::removeSelf
  95. (const SharedHandle<SocketEntry>& socketEntry) const
  96. {
  97. socketEntry->removeCommandEvent(*this);
  98. }
  99. #ifdef ENABLE_ASYNC_DNS
  100. EpollEventPoll::ADNSEvent::ADNSEvent
  101. (const SharedHandle<AsyncNameResolver>& resolver,
  102. Command* command,
  103. sock_t socket, int events):
  104. _resolver(resolver), _command(command), _socket(socket), _events(events) {}
  105. bool EpollEventPoll::ADNSEvent::operator==(const ADNSEvent& event) const
  106. {
  107. return _resolver == event._resolver;
  108. }
  109. int EpollEventPoll::ADNSEvent::getEvents() const
  110. {
  111. return _events;
  112. }
  113. void EpollEventPoll::ADNSEvent::processEvents(int events)
  114. {
  115. ares_socket_t readfd;
  116. ares_socket_t writefd;
  117. if(events&(EpollEventPoll::EVENT_READ|EpollEventPoll::EVENT_ERROR|
  118. EpollEventPoll::EVENT_HUP)) {
  119. readfd = _socket;
  120. } else {
  121. readfd = ARES_SOCKET_BAD;
  122. }
  123. if(events&(EpollEventPoll::EVENT_WRITE|EpollEventPoll::EVENT_ERROR|
  124. EpollEventPoll::EVENT_HUP)) {
  125. writefd = _socket;
  126. } else {
  127. writefd = ARES_SOCKET_BAD;
  128. }
  129. _resolver->process(readfd, writefd);
  130. _command->setStatusActive();
  131. }
  132. void EpollEventPoll::ADNSEvent::addSelf
  133. (const SharedHandle<SocketEntry>& socketEntry) const
  134. {
  135. socketEntry->addADNSEvent(*this);
  136. }
  137. void EpollEventPoll::ADNSEvent::removeSelf
  138. (const SharedHandle<SocketEntry>& socketEntry) const
  139. {
  140. socketEntry->removeADNSEvent(*this);
  141. }
  142. #endif // ENABLE_ASYNC_DNS
  143. EpollEventPoll::SocketEntry::SocketEntry(sock_t socket):_socket(socket)
  144. {
  145. memset(&_epEvent, 0, sizeof(struct epoll_event));
  146. }
  147. bool EpollEventPoll::SocketEntry::operator==(const SocketEntry& entry) const
  148. {
  149. return _socket == entry._socket;
  150. }
  151. bool EpollEventPoll::SocketEntry::operator<(const SocketEntry& entry) const
  152. {
  153. return _socket < entry._socket;
  154. }
  155. void EpollEventPoll::SocketEntry::addCommandEvent(const CommandEvent& cev)
  156. {
  157. std::deque<CommandEvent>::iterator i = std::find(_commandEvents.begin(),
  158. _commandEvents.end(),
  159. cev);
  160. if(i == _commandEvents.end()) {
  161. _commandEvents.push_back(cev);
  162. } else {
  163. (*i).addEvents(cev.getEvents());
  164. }
  165. }
  166. void EpollEventPoll::SocketEntry::removeCommandEvent(const CommandEvent& cev)
  167. {
  168. std::deque<CommandEvent>::iterator i = std::find(_commandEvents.begin(),
  169. _commandEvents.end(),
  170. cev);
  171. if(i == _commandEvents.end()) {
  172. // not found
  173. } else {
  174. (*i).removeEvents(cev.getEvents());
  175. if((*i).eventsEmpty()) {
  176. _commandEvents.erase(i);
  177. }
  178. }
  179. }
  180. #ifdef ENABLE_ASYNC_DNS
  181. void EpollEventPoll::SocketEntry::addADNSEvent(const ADNSEvent& aev)
  182. {
  183. std::deque<ADNSEvent>::iterator i = std::find(_adnsEvents.begin(),
  184. _adnsEvents.end(),
  185. aev);
  186. if(i == _adnsEvents.end()) {
  187. _adnsEvents.push_back(aev);
  188. }
  189. }
  190. void EpollEventPoll::SocketEntry::removeADNSEvent(const ADNSEvent& aev)
  191. {
  192. std::deque<ADNSEvent>::iterator i = std::find(_adnsEvents.begin(),
  193. _adnsEvents.end(),
  194. aev);
  195. if(i == _adnsEvents.end()) {
  196. // not found
  197. } else {
  198. _adnsEvents.erase(i);
  199. }
  200. }
  201. #endif // ENABLE_ASYNC_DNS
  202. void EpollEventPoll::SocketEntry::processEvents(int events)
  203. {
  204. std::for_each(_commandEvents.begin(), _commandEvents.end(),
  205. std::bind2nd(std::mem_fun_ref
  206. (&EpollEventPoll::CommandEvent::processEvents),
  207. events));
  208. #ifdef ENABLE_ASYNC_DNS
  209. std::for_each(_adnsEvents.begin(), _adnsEvents.end(),
  210. std::bind2nd(std::mem_fun_ref
  211. (&EpollEventPoll::ADNSEvent::processEvents),
  212. events));
  213. #endif // ENABLE_ASYNC_DNS
  214. }
  215. sock_t EpollEventPoll::SocketEntry::getSocket() const
  216. {
  217. return _socket;
  218. }
  219. bool EpollEventPoll::SocketEntry::eventEmpty() const
  220. {
  221. #ifdef ENABLE_ASYNC_DNS
  222. return _commandEvents.empty() && _adnsEvents.empty();
  223. #else // !ENABLE_ASYNC_DNS
  224. return _commandEvents.empty();
  225. #endif // !ENABLE_ASYNC_DNS)
  226. }
  227. int accumulateEvent(int events, const EpollEventPoll::Event& event)
  228. {
  229. return events|event.getEvents();
  230. }
  231. struct epoll_event& EpollEventPoll::SocketEntry::getEpEvent()
  232. {
  233. _epEvent.data.ptr = this;
  234. #ifdef ENABLE_ASYNC_DNS
  235. _epEvent.events =
  236. std::accumulate(_adnsEvents.begin(),
  237. _adnsEvents.end(),
  238. std::accumulate(_commandEvents.begin(),
  239. _commandEvents.end(), 0, accumulateEvent),
  240. accumulateEvent);
  241. #else // !ENABLE_ASYNC_DNS
  242. _epEvent.events =
  243. std::accumulate(_commandEvents.begin(), _commandEvents.end(), 0,
  244. accumulateEvent);
  245. #endif // !ENABLE_ASYNC_DNS
  246. return _epEvent;
  247. }
  248. #ifdef ENABLE_ASYNC_DNS
  249. EpollEventPoll::AsyncNameResolverEntry::AsyncNameResolverEntry
  250. (const SharedHandle<AsyncNameResolver>& nameResolver, Command* command):
  251. _nameResolver(nameResolver), _command(command), _socketsSize(0)
  252. {}
  253. bool EpollEventPoll::AsyncNameResolverEntry::operator==
  254. (const AsyncNameResolverEntry& entry)
  255. {
  256. return _nameResolver == entry._nameResolver &&
  257. _command == entry._command;
  258. }
  259. void EpollEventPoll::AsyncNameResolverEntry::addSocketEvents
  260. (EpollEventPoll* e)
  261. {
  262. _socketsSize = 0;
  263. int mask = _nameResolver->getsock(_sockets);
  264. if(mask == 0) {
  265. return;
  266. }
  267. size_t i;
  268. for(i = 0; i < ARES_GETSOCK_MAXNUM; ++i) {
  269. //epoll_event_t* epEventPtr = &_epEvents[_socketsSize];
  270. int events = 0;
  271. if(ARES_GETSOCK_READABLE(mask, i)) {
  272. events |= EPOLLIN;
  273. }
  274. if(ARES_GETSOCK_WRITABLE(mask, i)) {
  275. events |= EPOLLOUT;
  276. }
  277. if(events == 0) {
  278. // assume no further sockets are returned.
  279. break;
  280. }
  281. e->addEvents(_sockets[i], _command, events, _nameResolver);
  282. }
  283. _socketsSize = i;
  284. }
  285. void EpollEventPoll::AsyncNameResolverEntry::removeSocketEvents
  286. (EpollEventPoll* e)
  287. {
  288. for(size_t i = 0; i < _socketsSize; ++i) {
  289. e->deleteEvents(_sockets[i], _command, _nameResolver);
  290. }
  291. }
  292. #endif // ENABLE_ASYNC_DNS
  293. EpollEventPoll::EpollEventPoll():_logger(LogFactory::getInstance())
  294. {
  295. _epfd = epoll_create(EPOLL_EVENTS_MAX);
  296. _epEvents = new struct epoll_event[EPOLL_EVENTS_MAX];
  297. }
  298. EpollEventPoll::~EpollEventPoll()
  299. {
  300. if(_epfd != -1) {
  301. int r;
  302. while((r = close(_epfd)) == -1 && errno == EINTR);
  303. if(r == -1) {
  304. _logger->error("Error occurred while closing epoll file descriptor"
  305. " %d: %s",
  306. _epfd, strerror(errno));
  307. }
  308. }
  309. delete [] _epEvents;
  310. }
  311. bool EpollEventPoll::good() const
  312. {
  313. return _epfd != -1;
  314. }
  315. void EpollEventPoll::poll(const struct timeval& tv)
  316. {
  317. // timeout is millisec
  318. int timeout = tv.tv_sec*1000+tv.tv_usec/1000;
  319. int res;
  320. while((res = epoll_wait(_epfd, _epEvents, EPOLL_EVENTS_MAX, timeout)) == -1 &&
  321. errno == EINTR);
  322. if(res > 0) {
  323. for(int i = 0; i < res; ++i) {
  324. SocketEntry* p = (SocketEntry*)_epEvents[i].data.ptr;
  325. p->processEvents(_epEvents[i].events);
  326. }
  327. }
  328. // TODO timeout of name resolver is determined in Command(AbstractCommand,
  329. // DHTEntryPoint...Command)
  330. }
  331. static int translateEvents(EventPoll::EventType events)
  332. {
  333. int newEvents = 0;
  334. if(EventPoll::EVENT_READ&events) {
  335. newEvents |= EPOLLIN;
  336. }
  337. if(EventPoll::EVENT_WRITE&events) {
  338. newEvents |= EPOLLOUT;
  339. }
  340. if(EventPoll::EVENT_ERROR&events) {
  341. newEvents |= EPOLLERR;
  342. }
  343. if(EventPoll::EVENT_HUP&events) {
  344. newEvents |= EPOLLHUP;
  345. }
  346. return newEvents;
  347. }
  348. bool EpollEventPoll::addEvents(sock_t socket,
  349. const EpollEventPoll::Event& event)
  350. {
  351. SharedHandle<SocketEntry> socketEntry(new SocketEntry(socket));
  352. std::deque<SharedHandle<SocketEntry> >::iterator i =
  353. std::lower_bound(_socketEntries.begin(), _socketEntries.end(), socketEntry);
  354. int r = 0;
  355. if(i != _socketEntries.end() && (*i) == socketEntry) {
  356. event.addSelf(*i);
  357. r = epoll_ctl(_epfd, EPOLL_CTL_MOD, (*i)->getSocket(), &(*i)->getEpEvent());
  358. if(r == -1) {
  359. // try EPOLL_CTL_ADD: There is a chance that previously socket X is
  360. // added to epoll, but it is closed and is not yet removed from
  361. // SocketEntries. In this case, EPOLL_CTL_MOD is failed with ENOENT.
  362. r = epoll_ctl(_epfd, EPOLL_CTL_ADD, (*i)->getSocket(),
  363. &(*i)->getEpEvent());
  364. }
  365. } else {
  366. _socketEntries.insert(i, socketEntry);
  367. event.addSelf(socketEntry);
  368. r = epoll_ctl(_epfd, EPOLL_CTL_ADD, socketEntry->getSocket(),
  369. &socketEntry->getEpEvent());
  370. }
  371. if(r == -1) {
  372. _logger->debug("Failed to add socket event %d:%s", socket, strerror(errno));
  373. return false;
  374. } else {
  375. return true;
  376. }
  377. }
  378. bool EpollEventPoll::addEvents(sock_t socket, Command* command,
  379. EventPoll::EventType events)
  380. {
  381. int epEvents = translateEvents(events);
  382. return addEvents(socket, CommandEvent(command, epEvents));
  383. }
  384. #ifdef ENABLE_ASYNC_DNS
  385. bool EpollEventPoll::addEvents(sock_t socket, Command* command, int events,
  386. const SharedHandle<AsyncNameResolver>& rs)
  387. {
  388. return addEvents(socket, ADNSEvent(rs, command, socket, events));
  389. }
  390. #endif // ENABLE_ASYNC_DNS
  391. bool EpollEventPoll::deleteEvents(sock_t socket,
  392. const EpollEventPoll::Event& event)
  393. {
  394. SharedHandle<SocketEntry> socketEntry(new SocketEntry(socket));
  395. std::deque<SharedHandle<SocketEntry> >::iterator i =
  396. std::lower_bound(_socketEntries.begin(), _socketEntries.end(), socketEntry);
  397. if(i != _socketEntries.end() && (*i) == socketEntry) {
  398. event.removeSelf(*i);
  399. int r = 0;
  400. if((*i)->eventEmpty()) {
  401. // In kernel before 2.6.9, epoll_ctl with EPOLL_CTL_DEL requires non-null
  402. // pointer of epoll_event.
  403. struct epoll_event ev = {0,{0}};
  404. r = epoll_ctl(_epfd, EPOLL_CTL_DEL, (*i)->getSocket(), &ev);
  405. _socketEntries.erase(i);
  406. } else {
  407. // If socket is closed, then it seems it is automatically removed from
  408. // epoll, so following EPOLL_CTL_MOD may fail.
  409. r = epoll_ctl(_epfd, EPOLL_CTL_MOD, (*i)->getSocket(),
  410. &(*i)->getEpEvent());
  411. if(r == -1) {
  412. _logger->debug("Failed to delete socket event, but may be ignored:%s",
  413. strerror(errno));
  414. }
  415. }
  416. if(r == -1) {
  417. _logger->debug("Failed to delete socket event:%s", strerror(errno));
  418. return false;
  419. } else {
  420. return true;
  421. }
  422. } else {
  423. _logger->debug("Socket %d is not found in SocketEntries.", socket);
  424. return false;
  425. }
  426. }
  427. #ifdef ENABLE_ASYNC_DNS
  428. bool EpollEventPoll::deleteEvents(sock_t socket, Command* command,
  429. const SharedHandle<AsyncNameResolver>& rs)
  430. {
  431. return deleteEvents(socket, ADNSEvent(rs, command, socket, 0));
  432. }
  433. #endif // ENABLE_ASYNC_DNS
  434. bool EpollEventPoll::deleteEvents(sock_t socket, Command* command,
  435. EventPoll::EventType events)
  436. {
  437. int epEvents = translateEvents(events);
  438. return deleteEvents(socket, CommandEvent(command, epEvents));
  439. }
  440. #ifdef ENABLE_ASYNC_DNS
  441. bool EpollEventPoll::addNameResolver
  442. (const SharedHandle<AsyncNameResolver>& resolver, Command* command)
  443. {
  444. SharedHandle<AsyncNameResolverEntry> entry
  445. (new AsyncNameResolverEntry(resolver, command));
  446. std::deque<SharedHandle<AsyncNameResolverEntry> >::iterator itr =
  447. std::find(_nameResolverEntries.begin(), _nameResolverEntries.end(), entry);
  448. if(itr == _nameResolverEntries.end()) {
  449. _nameResolverEntries.push_back(entry);
  450. entry->addSocketEvents(this);
  451. return true;
  452. } else {
  453. return false;
  454. }
  455. }
  456. bool EpollEventPoll::deleteNameResolver
  457. (const SharedHandle<AsyncNameResolver>& resolver, Command* command)
  458. {
  459. SharedHandle<AsyncNameResolverEntry> entry
  460. (new AsyncNameResolverEntry(resolver, command));
  461. std::deque<SharedHandle<AsyncNameResolverEntry> >::iterator itr =
  462. std::find(_nameResolverEntries.begin(), _nameResolverEntries.end(), entry);
  463. if(itr == _nameResolverEntries.end()) {
  464. return false;
  465. } else {
  466. (*itr)->removeSocketEvents(this);
  467. _nameResolverEntries.erase(itr);
  468. return true;
  469. }
  470. }
  471. #endif // ENABLE_ASYNC_DNS
  472. } // namespace aria2