LibuvEventPoll.cc 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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> static void close_callback(uv_handle_t* handle)
  57. {
  58. delete reinterpret_cast<T*>(handle);
  59. }
  60. #if !defined(UV_VERSION_MINOR) || \
  61. (UV_VERSION_MAJOR == 0 && UV_VERSION_MINOR <= 10)
  62. static void timer_callback(uv_timer_t* handle, int status)
  63. {
  64. uv_stop(handle->loop);
  65. }
  66. static void timer_callback(uv_timer_t* handle) { timer_callback(handle, 0); }
  67. #else // !defined(UV_VERSION_MINOR) || (UV_VERSION_MAJOR == 0 &&
  68. // UV_VERSION_MINOR <= 10)
  69. static void timer_callback(uv_timer_t* handle) { uv_stop(handle->loop); }
  70. #endif // !defined(UV_VERSION_MINOR) || UV_VERSION_MINOR <= 10
  71. }
  72. namespace aria2 {
  73. LibuvEventPoll::KSocketEntry::KSocketEntry(sock_t s)
  74. : SocketEntry<KCommandEvent, KADNSEvent>(s)
  75. {
  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 =
  86. std::accumulate(adnsEvents_.begin(), adnsEvents_.end(),
  87. std::accumulate(commandEvents_.begin(),
  88. commandEvents_.end(), 0, 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() { loop_ = uv_loop_new(); }
  97. LibuvEventPoll::~LibuvEventPoll()
  98. {
  99. for (auto& p : polls_) {
  100. p.second->close();
  101. }
  102. // Actually kill the polls, and timers, if any.
  103. uv_run(loop_, (uv_run_mode)(UV_RUN_ONCE | UV_RUN_NOWAIT));
  104. if (loop_) {
  105. uv_loop_delete(loop_);
  106. loop_ = nullptr;
  107. }
  108. // Need this to free only after the loop is gone.
  109. polls_.clear();
  110. }
  111. void LibuvEventPoll::poll(const struct timeval& tv)
  112. {
  113. const int timeout = tv.tv_sec * 1000 + tv.tv_usec / 1000;
  114. // timeout == 0 will tick once
  115. if (timeout >= 0) {
  116. auto timer = new uv_timer_t;
  117. uv_timer_init(loop_, timer);
  118. uv_timer_start(timer, timer_callback, timeout, timeout);
  119. uv_run(loop_, UV_RUN_DEFAULT);
  120. // Remove timer again.
  121. uv_timer_stop(timer);
  122. uv_close((uv_handle_t*)timer, close_callback<uv_timer_t>);
  123. }
  124. else {
  125. while (uv_run(loop_, (uv_run_mode)(UV_RUN_ONCE | UV_RUN_NOWAIT)) > 0) {
  126. }
  127. }
  128. #ifdef ENABLE_ASYNC_DNS
  129. // It turns out that we have to call ares_process_fd before ares's
  130. // own timeout and ares may create new sockets or closes socket in
  131. // their API. So we call ares_process_fd for all ares_channel and
  132. // re-register their sockets.
  133. for (auto& r : nameResolverEntries_) {
  134. auto& ent = r.second;
  135. ent.processTimeout();
  136. ent.removeSocketEvents(this);
  137. ent.addSocketEvents(this);
  138. }
  139. #endif // ENABLE_ASYNC_DNS
  140. // TODO timeout of name resolver is determined in Command(AbstractCommand,
  141. // DHTEntryPoint...Command)
  142. }
  143. int LibuvEventPoll::translateEvents(EventPoll::EventType events)
  144. {
  145. int newEvents = 0;
  146. if (EventPoll::EVENT_READ & events) {
  147. newEvents |= IEV_READ;
  148. }
  149. if (EventPoll::EVENT_WRITE & events) {
  150. newEvents |= IEV_WRITE;
  151. }
  152. if (EventPoll::EVENT_ERROR & events) {
  153. newEvents |= IEV_ERROR;
  154. }
  155. if (EventPoll::EVENT_HUP & events) {
  156. newEvents |= IEV_HUP;
  157. }
  158. return newEvents;
  159. }
  160. void LibuvEventPoll::pollCallback(KPoll* poll, int status, int events)
  161. {
  162. #if HAVE_UV_LAST_ERROR
  163. if (status == -1) {
  164. uv_err_t err = uv_last_error(loop_);
  165. switch (err.code) {
  166. #else
  167. if (status < 0) {
  168. switch (status) {
  169. #endif
  170. case UV_EAGAIN:
  171. case UV_EINTR:
  172. return;
  173. case UV_EOF:
  174. case UV_ECONNABORTED:
  175. case UV_ECONNREFUSED:
  176. case UV_ECONNRESET:
  177. case UV_ENOTCONN:
  178. case UV_EPIPE:
  179. case UV_ESHUTDOWN:
  180. events = IEV_HUP;
  181. poll->processEvents(events);
  182. poll->stop();
  183. uv_stop(loop_);
  184. return;
  185. default:
  186. events = IEV_ERROR;
  187. poll->processEvents(events);
  188. poll->stop();
  189. uv_stop(loop_);
  190. return;
  191. }
  192. }
  193. // Got something
  194. poll->processEvents(events);
  195. uv_stop(loop_);
  196. }
  197. bool LibuvEventPoll::addEvents(sock_t socket,
  198. const LibuvEventPoll::KEvent& event)
  199. {
  200. auto i = socketEntries_.lower_bound(socket);
  201. if (i != socketEntries_.end() && i->first == socket) {
  202. auto& socketEntry = i->second;
  203. event.addSelf(&socketEntry);
  204. auto poll = polls_.find(socket);
  205. if (poll == polls_.end()) {
  206. throw std::logic_error("Invalid socket");
  207. }
  208. poll->second->start();
  209. return true;
  210. }
  211. i = socketEntries_.insert(i, std::make_pair(socket, KSocketEntry(socket)));
  212. auto& socketEntry = i->second;
  213. event.addSelf(&socketEntry);
  214. auto poll = new KPoll(this, &socketEntry, socket);
  215. polls_[socket] = poll;
  216. poll->start();
  217. return true;
  218. }
  219. bool LibuvEventPoll::addEvents(sock_t socket, Command* command,
  220. EventPoll::EventType events)
  221. {
  222. int pollEvents = translateEvents(events);
  223. return addEvents(socket, KCommandEvent(command, pollEvents));
  224. }
  225. #ifdef ENABLE_ASYNC_DNS
  226. bool LibuvEventPoll::addEvents(sock_t socket, Command* command, int events,
  227. const std::shared_ptr<AsyncNameResolver>& rs)
  228. {
  229. return addEvents(socket, KADNSEvent(rs, command, socket, events));
  230. }
  231. #endif // ENABLE_ASYNC_DNS
  232. bool LibuvEventPoll::deleteEvents(sock_t socket,
  233. const LibuvEventPoll::KEvent& event)
  234. {
  235. auto i = socketEntries_.find(socket);
  236. if (i == socketEntries_.end()) {
  237. A2_LOG_DEBUG(fmt("Socket %d is not found in SocketEntries.", socket));
  238. return false;
  239. }
  240. auto& socketEntry = (*i).second;
  241. event.removeSelf(&socketEntry);
  242. auto poll = polls_.find(socket);
  243. if (poll == polls_.end()) {
  244. return false;
  245. }
  246. if (socketEntry.eventEmpty()) {
  247. poll->second->close();
  248. polls_.erase(poll);
  249. socketEntries_.erase(i);
  250. return true;
  251. }
  252. poll->second->start();
  253. return true;
  254. }
  255. #ifdef ENABLE_ASYNC_DNS
  256. bool LibuvEventPoll::deleteEvents(sock_t socket, Command* command,
  257. const std::shared_ptr<AsyncNameResolver>& rs)
  258. {
  259. return deleteEvents(socket, KADNSEvent(rs, command, socket, 0));
  260. }
  261. #endif // ENABLE_ASYNC_DNS
  262. bool LibuvEventPoll::deleteEvents(sock_t socket, Command* command,
  263. EventPoll::EventType events)
  264. {
  265. int pollEvents = translateEvents(events);
  266. return deleteEvents(socket, KCommandEvent(command, pollEvents));
  267. }
  268. #ifdef ENABLE_ASYNC_DNS
  269. bool LibuvEventPoll::addNameResolver(
  270. const std::shared_ptr<AsyncNameResolver>& resolver, Command* command)
  271. {
  272. auto key = std::make_pair(resolver.get(), command);
  273. auto itr = nameResolverEntries_.lower_bound(key);
  274. if (itr != std::end(nameResolverEntries_) && (*itr).first == key) {
  275. return false;
  276. }
  277. itr = nameResolverEntries_.insert(
  278. itr, std::make_pair(key, KAsyncNameResolverEntry(resolver, command)));
  279. (*itr).second.addSocketEvents(this);
  280. return true;
  281. }
  282. bool LibuvEventPoll::deleteNameResolver(
  283. const std::shared_ptr<AsyncNameResolver>& resolver, Command* command)
  284. {
  285. auto key = std::make_pair(resolver.get(), command);
  286. auto itr = nameResolverEntries_.find(key);
  287. if (itr == std::end(nameResolverEntries_)) {
  288. return false;
  289. }
  290. (*itr).second.removeSocketEvents(this);
  291. nameResolverEntries_.erase(itr);
  292. return true;
  293. }
  294. #endif // ENABLE_ASYNC_DNS
  295. } // namespace aria2