EpollEventPoll.cc 14 KB

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