EpollEventPoll.cc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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 <cerrno>
  37. #include <cstring>
  38. #include <algorithm>
  39. #include <numeric>
  40. #include "Command.h"
  41. #include "LogFactory.h"
  42. #include "Logger.h"
  43. #include "util.h"
  44. #include "a2functional.h"
  45. #include "fmt.h"
  46. namespace aria2 {
  47. EpollEventPoll::KSocketEntry::KSocketEntry(sock_t s):
  48. SocketEntry<KCommandEvent, KADNSEvent>(s) {}
  49. int accumulateEvent(int events, const EpollEventPoll::KEvent& event)
  50. {
  51. return events|event.getEvents();
  52. }
  53. struct epoll_event EpollEventPoll::KSocketEntry::getEvents()
  54. {
  55. struct epoll_event epEvent;
  56. memset(&epEvent, 0, sizeof(struct epoll_event));
  57. epEvent.data.ptr = this;
  58. #ifdef ENABLE_ASYNC_DNS
  59. epEvent.events =
  60. std::accumulate(adnsEvents_.begin(),
  61. adnsEvents_.end(),
  62. std::accumulate(commandEvents_.begin(),
  63. commandEvents_.end(), 0, accumulateEvent),
  64. accumulateEvent);
  65. #else // !ENABLE_ASYNC_DNS
  66. epEvent.events =
  67. std::accumulate(commandEvents_.begin(), commandEvents_.end(), 0,
  68. accumulateEvent);
  69. #endif // !ENABLE_ASYNC_DNS
  70. return epEvent;
  71. }
  72. EpollEventPoll::EpollEventPoll()
  73. : epEventsSize_(EPOLL_EVENTS_MAX),
  74. epEvents_(new struct epoll_event[epEventsSize_])
  75. {
  76. epfd_ = epoll_create(EPOLL_EVENTS_MAX);
  77. }
  78. EpollEventPoll::~EpollEventPoll()
  79. {
  80. if(epfd_ != -1) {
  81. int r;
  82. while((r = close(epfd_)) == -1 && errno == EINTR);
  83. int errNum = errno;
  84. if(r == -1) {
  85. A2_LOG_ERROR(fmt("Error occurred while closing epoll file descriptor"
  86. " %d: %s",
  87. epfd_,
  88. util::safeStrerror(errNum).c_str()));
  89. }
  90. }
  91. delete [] epEvents_;
  92. }
  93. bool EpollEventPoll::good() const
  94. {
  95. return epfd_ != -1;
  96. }
  97. void EpollEventPoll::poll(const struct timeval& tv)
  98. {
  99. // timeout is millisec
  100. int timeout = tv.tv_sec*1000+tv.tv_usec/1000;
  101. int res;
  102. while((res = epoll_wait(epfd_, epEvents_, EPOLL_EVENTS_MAX, timeout)) == -1 &&
  103. errno == EINTR);
  104. if(res > 0) {
  105. for(int i = 0; i < res; ++i) {
  106. KSocketEntry* p = reinterpret_cast<KSocketEntry*>(epEvents_[i].data.ptr);
  107. p->processEvents(epEvents_[i].events);
  108. }
  109. }
  110. #ifdef ENABLE_ASYNC_DNS
  111. // It turns out that we have to call ares_process_fd before ares's
  112. // own timeout and ares may create new sockets or closes socket in
  113. // their API. So we call ares_process_fd for all ares_channel and
  114. // re-register their sockets.
  115. for(std::deque<SharedHandle<KAsyncNameResolverEntry> >::iterator i =
  116. nameResolverEntries_.begin(), eoi = nameResolverEntries_.end();
  117. i != eoi; ++i) {
  118. (*i)->processTimeout();
  119. (*i)->removeSocketEvents(this);
  120. (*i)->addSocketEvents(this);
  121. }
  122. #endif // ENABLE_ASYNC_DNS
  123. // TODO timeout of name resolver is determined in Command(AbstractCommand,
  124. // DHTEntryPoint...Command)
  125. }
  126. namespace {
  127. int translateEvents(EventPoll::EventType events)
  128. {
  129. int newEvents = 0;
  130. if(EventPoll::EVENT_READ&events) {
  131. newEvents |= EPOLLIN;
  132. }
  133. if(EventPoll::EVENT_WRITE&events) {
  134. newEvents |= EPOLLOUT;
  135. }
  136. if(EventPoll::EVENT_ERROR&events) {
  137. newEvents |= EPOLLERR;
  138. }
  139. if(EventPoll::EVENT_HUP&events) {
  140. newEvents |= EPOLLHUP;
  141. }
  142. return newEvents;
  143. }
  144. } // namespace
  145. bool EpollEventPoll::addEvents(sock_t socket,
  146. const EpollEventPoll::KEvent& event)
  147. {
  148. SharedHandle<KSocketEntry> socketEntry(new KSocketEntry(socket));
  149. std::deque<SharedHandle<KSocketEntry> >::iterator i =
  150. std::lower_bound(socketEntries_.begin(), socketEntries_.end(), socketEntry,
  151. DerefLess<SharedHandle<KSocketEntry> >());
  152. int r = 0;
  153. int errNum = 0;
  154. if(i != socketEntries_.end() && *(*i) == *socketEntry) {
  155. event.addSelf(*i);
  156. struct epoll_event epEvent = (*i)->getEvents();
  157. r = epoll_ctl(epfd_, EPOLL_CTL_MOD, (*i)->getSocket(), &epEvent);
  158. if(r == -1) {
  159. // try EPOLL_CTL_ADD: There is a chance that previously socket X is
  160. // added to epoll, but it is closed and is not yet removed from
  161. // SocketEntries. In this case, EPOLL_CTL_MOD is failed with ENOENT.
  162. r = epoll_ctl(epfd_, EPOLL_CTL_ADD, (*i)->getSocket(),
  163. &epEvent);
  164. errNum = errno;
  165. }
  166. } else {
  167. socketEntries_.insert(i, socketEntry);
  168. if(socketEntries_.size() > epEventsSize_) {
  169. epEventsSize_ *= 2;
  170. delete [] epEvents_;
  171. epEvents_ = new struct epoll_event[epEventsSize_];
  172. }
  173. event.addSelf(socketEntry);
  174. struct epoll_event epEvent = socketEntry->getEvents();
  175. r = epoll_ctl(epfd_, EPOLL_CTL_ADD, socketEntry->getSocket(), &epEvent);
  176. errNum = errno;
  177. }
  178. if(r == -1) {
  179. A2_LOG_DEBUG(fmt("Failed to add socket event %d:%s",
  180. socket,
  181. util::safeStrerror(errNum).c_str()));
  182. return false;
  183. } else {
  184. return true;
  185. }
  186. }
  187. bool EpollEventPoll::addEvents(sock_t socket, Command* command,
  188. EventPoll::EventType events)
  189. {
  190. int epEvents = translateEvents(events);
  191. return addEvents(socket, KCommandEvent(command, epEvents));
  192. }
  193. #ifdef ENABLE_ASYNC_DNS
  194. bool EpollEventPoll::addEvents(sock_t socket, Command* command, int events,
  195. const SharedHandle<AsyncNameResolver>& rs)
  196. {
  197. return addEvents(socket, KADNSEvent(rs, command, socket, events));
  198. }
  199. #endif // ENABLE_ASYNC_DNS
  200. bool EpollEventPoll::deleteEvents(sock_t socket,
  201. const EpollEventPoll::KEvent& event)
  202. {
  203. SharedHandle<KSocketEntry> socketEntry(new KSocketEntry(socket));
  204. std::deque<SharedHandle<KSocketEntry> >::iterator i =
  205. std::lower_bound(socketEntries_.begin(), socketEntries_.end(), socketEntry,
  206. DerefLess<SharedHandle<KSocketEntry> >());
  207. if(i != socketEntries_.end() && *(*i) == *socketEntry) {
  208. event.removeSelf(*i);
  209. int r = 0;
  210. int errNum = 0;
  211. if((*i)->eventEmpty()) {
  212. // In kernel before 2.6.9, epoll_ctl with EPOLL_CTL_DEL requires non-null
  213. // pointer of epoll_event.
  214. struct epoll_event ev = {0,{0}};
  215. r = epoll_ctl(epfd_, EPOLL_CTL_DEL, (*i)->getSocket(), &ev);
  216. errNum = r;
  217. socketEntries_.erase(i);
  218. } else {
  219. // If socket is closed, then it seems it is automatically removed from
  220. // epoll, so following EPOLL_CTL_MOD may fail.
  221. struct epoll_event epEvent = (*i)->getEvents();
  222. r = epoll_ctl(epfd_, EPOLL_CTL_MOD, (*i)->getSocket(), &epEvent);
  223. errNum = r;
  224. if(r == -1) {
  225. A2_LOG_DEBUG(fmt("Failed to delete socket event, but may be ignored:%s",
  226. util::safeStrerror(errNum).c_str()));
  227. }
  228. }
  229. if(r == -1) {
  230. A2_LOG_DEBUG(fmt("Failed to delete socket event:%s",
  231. util::safeStrerror(errNum).c_str()));
  232. return false;
  233. } else {
  234. return true;
  235. }
  236. } else {
  237. A2_LOG_DEBUG(fmt("Socket %d is not found in SocketEntries.", socket));
  238. return false;
  239. }
  240. }
  241. #ifdef ENABLE_ASYNC_DNS
  242. bool EpollEventPoll::deleteEvents(sock_t socket, Command* command,
  243. const SharedHandle<AsyncNameResolver>& rs)
  244. {
  245. return deleteEvents(socket, KADNSEvent(rs, command, socket, 0));
  246. }
  247. #endif // ENABLE_ASYNC_DNS
  248. bool EpollEventPoll::deleteEvents(sock_t socket, Command* command,
  249. EventPoll::EventType events)
  250. {
  251. int epEvents = translateEvents(events);
  252. return deleteEvents(socket, KCommandEvent(command, epEvents));
  253. }
  254. #ifdef ENABLE_ASYNC_DNS
  255. bool EpollEventPoll::addNameResolver
  256. (const SharedHandle<AsyncNameResolver>& resolver, Command* command)
  257. {
  258. SharedHandle<KAsyncNameResolverEntry> entry
  259. (new KAsyncNameResolverEntry(resolver, command));
  260. std::deque<SharedHandle<KAsyncNameResolverEntry> >::iterator itr =
  261. std::find_if(nameResolverEntries_.begin(), nameResolverEntries_.end(),
  262. derefEqual(entry));
  263. if(itr == nameResolverEntries_.end()) {
  264. nameResolverEntries_.push_back(entry);
  265. entry->addSocketEvents(this);
  266. return true;
  267. } else {
  268. return false;
  269. }
  270. }
  271. bool EpollEventPoll::deleteNameResolver
  272. (const SharedHandle<AsyncNameResolver>& resolver, Command* command)
  273. {
  274. SharedHandle<KAsyncNameResolverEntry> entry
  275. (new KAsyncNameResolverEntry(resolver, command));
  276. std::deque<SharedHandle<KAsyncNameResolverEntry> >::iterator itr =
  277. std::find_if(nameResolverEntries_.begin(), nameResolverEntries_.end(),
  278. derefEqual(entry));
  279. if(itr == nameResolverEntries_.end()) {
  280. return false;
  281. } else {
  282. (*itr)->removeSocketEvents(this);
  283. nameResolverEntries_.erase(itr);
  284. return true;
  285. }
  286. }
  287. #endif // ENABLE_ASYNC_DNS
  288. } // namespace aria2