LibuvEventPoll.cc 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2010 Tatsuhiro Tsujikawa
  6. * Copyright (C) 2013 Tatsuhiro Tsujikawa, Nils Maier
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. *
  22. * In addition, as a special exception, the copyright holders give
  23. * permission to link the code of portions of this program with the
  24. * OpenSSL library under certain conditions as described in each
  25. * individual source file, and distribute linked combinations
  26. * including the two.
  27. * You must obey the GNU General Public License in all respects
  28. * for all of the code used other than OpenSSL. If you modify
  29. * file(s) with this exception, you may extend this exception to your
  30. * version of the file(s), but you are not obligated to do so. If you
  31. * do not wish to do so, delete this exception statement from your
  32. * version. If you delete this exception statement from all source
  33. * files in the program, then also delete it here.
  34. */
  35. /* copyright --> */
  36. #ifdef __MINGW32__
  37. #ifdef _WIN32_WINNT
  38. #undef _WIN32_WINNT
  39. #endif // _WIN32_WINNT
  40. #define _WIN32_WINNT 0x0600
  41. #endif // __MINGW32__
  42. #include "LibuvEventPoll.h"
  43. #include <algorithm>
  44. #include <cstring>
  45. #include <numeric>
  46. #include <stdexcept>
  47. #include <uv.h>
  48. #include "Command.h"
  49. #include "LogFactory.h"
  50. #include "Logger.h"
  51. #include "a2functional.h"
  52. #include "fmt.h"
  53. #include "util.h"
  54. namespace {
  55. using namespace aria2;
  56. template<typename T>
  57. static void close_callback(uv_handle_t* handle)
  58. {
  59. delete reinterpret_cast<T*>(handle);
  60. }
  61. #if !defined(UV_VERSION_MINOR) || UV_VERSION_MINOR <= 10
  62. static void timer_callback(uv_timer_t* handle, int status)
  63. {
  64. uv_stop(handle->loop);
  65. }
  66. #else // !defined(UV_VERSION_MINOR) || UV_VERSION_MINOR <= 10
  67. static void timer_callback(uv_timer_t* handle)
  68. {
  69. uv_stop(handle->loop);
  70. }
  71. #endif // !defined(UV_VERSION_MINOR) || UV_VERSION_MINOR <= 10
  72. }
  73. namespace aria2 {
  74. LibuvEventPoll::KSocketEntry::KSocketEntry(sock_t s)
  75. : SocketEntry<KCommandEvent, KADNSEvent>(s)
  76. {}
  77. inline int accumulateEvent(int events, const LibuvEventPoll::KEvent& event)
  78. {
  79. return events | event.getEvents();
  80. }
  81. int LibuvEventPoll::KSocketEntry::getEvents() const
  82. {
  83. int events = 0;
  84. #ifdef ENABLE_ASYNC_DNS
  85. events = std::accumulate(adnsEvents_.begin(), adnsEvents_.end(),
  86. std::accumulate(commandEvents_.begin(),
  87. commandEvents_.end(), 0,
  88. accumulateEvent),
  89. accumulateEvent);
  90. #else // !ENABLE_ASYNC_DNS
  91. events = std::accumulate(commandEvents_.begin(), commandEvents_.end(), 0,
  92. accumulateEvent);
  93. #endif // !ENABLE_ASYNC_DNS
  94. return events;
  95. }
  96. LibuvEventPoll::LibuvEventPoll()
  97. {
  98. loop_ = uv_loop_new();
  99. }
  100. LibuvEventPoll::~LibuvEventPoll()
  101. {
  102. for (auto& p: polls_) {
  103. p.second->close();
  104. }
  105. // Actually kill the polls, and timers, if any.
  106. uv_run(loop_, (uv_run_mode)(UV_RUN_ONCE | UV_RUN_NOWAIT));
  107. if (loop_) {
  108. uv_loop_delete(loop_);
  109. loop_ = nullptr;
  110. }
  111. // Need this to free only after the loop is gone.
  112. polls_.clear();
  113. }
  114. void LibuvEventPoll::poll(const struct timeval& tv)
  115. {
  116. const int timeout = tv.tv_sec * 1000 + tv.tv_usec / 1000;
  117. // timeout == 0 will tick once
  118. if (timeout >= 0) {
  119. auto timer = new uv_timer_t;
  120. uv_timer_init(loop_, timer);
  121. uv_timer_start(timer, timer_callback, timeout, timeout);
  122. uv_run(loop_, UV_RUN_DEFAULT);
  123. // Remove timer again.
  124. uv_timer_stop(timer);
  125. uv_close((uv_handle_t*)timer, close_callback<uv_timer_t>);
  126. }
  127. else {
  128. while (uv_run(loop_, (uv_run_mode)(UV_RUN_ONCE | UV_RUN_NOWAIT)) > 0) {}
  129. }
  130. #ifdef ENABLE_ASYNC_DNS
  131. // It turns out that we have to call ares_process_fd before ares's
  132. // own timeout and ares may create new sockets or closes socket in
  133. // their API. So we call ares_process_fd for all ares_channel and
  134. // re-register their sockets.
  135. for (auto& r: nameResolverEntries_) {
  136. r->processTimeout();
  137. r->removeSocketEvents(this);
  138. r->addSocketEvents(this);
  139. }
  140. #endif // ENABLE_ASYNC_DNS
  141. // TODO timeout of name resolver is determined in Command(AbstractCommand,
  142. // DHTEntryPoint...Command)
  143. }
  144. int LibuvEventPoll::translateEvents(EventPoll::EventType events)
  145. {
  146. int newEvents = 0;
  147. if (EventPoll::EVENT_READ & events) {
  148. newEvents |= IEV_READ;
  149. }
  150. if (EventPoll::EVENT_WRITE & events) {
  151. newEvents |= IEV_WRITE;
  152. }
  153. if (EventPoll::EVENT_ERROR & events) {
  154. newEvents |= IEV_ERROR;
  155. }
  156. if (EventPoll::EVENT_HUP & events) {
  157. newEvents |= IEV_HUP;
  158. }
  159. return newEvents;
  160. }
  161. void LibuvEventPoll::pollCallback(KPoll* poll, int status, int events)
  162. {
  163. #if HAVE_UV_LAST_ERROR
  164. if (status == -1) {
  165. uv_err_t err = uv_last_error(loop_);
  166. switch (err.code) {
  167. #else
  168. if (status < 0) {
  169. switch (status) {
  170. #endif
  171. case UV_EAGAIN:
  172. case UV_EINTR:
  173. return;
  174. case UV_EOF:
  175. case UV_ECONNABORTED:
  176. case UV_ECONNREFUSED:
  177. case UV_ECONNRESET:
  178. case UV_ENOTCONN:
  179. case UV_EPIPE:
  180. case UV_ESHUTDOWN:
  181. events = IEV_HUP;
  182. poll->processEvents(events);
  183. poll->stop();
  184. uv_stop(loop_);
  185. return;
  186. default:
  187. events = IEV_ERROR;
  188. poll->processEvents(events);
  189. poll->stop();
  190. uv_stop(loop_);
  191. return;
  192. }
  193. }
  194. // Got something
  195. poll->processEvents(events);
  196. uv_stop(loop_);
  197. }
  198. bool LibuvEventPoll::addEvents(sock_t socket,
  199. const LibuvEventPoll::KEvent& event)
  200. {
  201. auto socketEntry = std::make_shared<KSocketEntry>(socket);
  202. auto i = socketEntries_.lower_bound(socketEntry);
  203. if (i != socketEntries_.end() && **i == *socketEntry) {
  204. event.addSelf((*i).get());
  205. auto poll = polls_.find(socket);
  206. if (poll == polls_.end()) {
  207. throw std::logic_error("Invalid socket");
  208. }
  209. poll->second->start();
  210. return true;
  211. }
  212. socketEntries_.insert(i, socketEntry);
  213. event.addSelf(socketEntry.get());
  214. auto poll = new KPoll(this, socketEntry.get(), socket);
  215. polls_[socket] = poll;
  216. poll->start();
  217. return true;
  218. }
  219. bool LibuvEventPoll::addEvents(sock_t socket, Command* command, EventPoll::EventType events)
  220. {
  221. int pollEvents = translateEvents(events);
  222. return addEvents(socket, KCommandEvent(command, pollEvents));
  223. }
  224. #ifdef ENABLE_ASYNC_DNS
  225. bool LibuvEventPoll::addEvents(sock_t socket, Command* command, int events,
  226. const std::shared_ptr<AsyncNameResolver>& rs)
  227. {
  228. return addEvents(socket, KADNSEvent(rs, command, socket, events));
  229. }
  230. #endif // ENABLE_ASYNC_DNS
  231. bool LibuvEventPoll::deleteEvents(sock_t socket,
  232. const LibuvEventPoll::KEvent& event)
  233. {
  234. auto socketEntry = std::make_shared<KSocketEntry>(socket);
  235. auto i = socketEntries_.find(socketEntry);
  236. if (i == socketEntries_.end()) {
  237. A2_LOG_DEBUG(fmt("Socket %d is not found in SocketEntries.", socket));
  238. return false;
  239. }
  240. event.removeSelf((*i).get());
  241. auto poll = polls_.find(socket);
  242. if (poll == polls_.end()) {
  243. return false;
  244. }
  245. if ((*i)->eventEmpty()) {
  246. poll->second->close();
  247. polls_.erase(poll);
  248. socketEntries_.erase(i);
  249. return true;
  250. }
  251. poll->second->start();
  252. return true;
  253. }
  254. #ifdef ENABLE_ASYNC_DNS
  255. bool LibuvEventPoll::deleteEvents(sock_t socket, Command* command,
  256. const std::shared_ptr<AsyncNameResolver>& rs)
  257. {
  258. return deleteEvents(socket, KADNSEvent(rs, command, socket, 0));
  259. }
  260. #endif // ENABLE_ASYNC_DNS
  261. bool LibuvEventPoll::deleteEvents(sock_t socket, Command* command,
  262. EventPoll::EventType events)
  263. {
  264. int pollEvents = translateEvents(events);
  265. return deleteEvents(socket, KCommandEvent(command, pollEvents));
  266. }
  267. #ifdef ENABLE_ASYNC_DNS
  268. bool LibuvEventPoll::addNameResolver(const std::shared_ptr<AsyncNameResolver>& resolver,
  269. Command* command)
  270. {
  271. auto entry = std::make_shared<KAsyncNameResolverEntry>(resolver, command);
  272. auto itr = nameResolverEntries_.lower_bound(entry);
  273. if (itr != nameResolverEntries_.end() && *(*itr) == *entry) {
  274. return false;
  275. }
  276. nameResolverEntries_.insert(itr, entry);
  277. entry->addSocketEvents(this);
  278. return true;
  279. }
  280. bool LibuvEventPoll::deleteNameResolver(const std::shared_ptr<AsyncNameResolver>& resolver,
  281. Command* command)
  282. {
  283. auto entry = std::make_shared<KAsyncNameResolverEntry>(resolver, command);
  284. auto itr = nameResolverEntries_.find(entry);
  285. if (itr == nameResolverEntries_.end()) {
  286. return false;
  287. }
  288. (*itr)->removeSocketEvents(this);
  289. nameResolverEntries_.erase(itr);
  290. return true;
  291. }
  292. #endif // ENABLE_ASYNC_DNS
  293. } // namespace aria2