udp_server.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. // Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <netinet/in.h>
  15. #include <sys/socket.h>
  16. #include <unistd.h> // for some IPC/network system calls
  17. #include <errno.h>
  18. #include <boost/shared_array.hpp>
  19. #include <config.h>
  20. #include <log/dummylog.h>
  21. #include <asio.hpp>
  22. #include <asio/error.hpp>
  23. #include <asiolink/dummy_io_cb.h>
  24. #include <asiolink/udp_endpoint.h>
  25. #include <asiolink/udp_socket.h>
  26. #include "udp_server.h"
  27. #include <dns/opcode.h>
  28. using namespace asio;
  29. using asio::ip::udp;
  30. using isc::log::dlog;
  31. using namespace std;
  32. using namespace isc::dns;
  33. using namespace isc::util;
  34. using namespace isc::asiolink;
  35. namespace isc {
  36. namespace asiodns {
  37. /*
  38. * Some of the member variables here are shared_ptrs and some are
  39. * auto_ptrs. There will be one instance of Data for the lifetime
  40. * of packet. The variables that are state only for a single packet
  41. * use auto_ptr, as it is more lightweight. In the case of shared
  42. * configuration (eg. the callbacks, socket), we use shared_ptrs.
  43. */
  44. struct UDPServer::Data {
  45. /*
  46. * Constructor from parameters passed to UDPServer constructor.
  47. * This instance will not be used to retrieve and answer the actual
  48. * query, it will only hold parameters until we wait for the
  49. * first packet. But we do initialize the socket in here.
  50. */
  51. Data(io_service& io_service, const ip::address& addr, const uint16_t port,
  52. SimpleCallback* checkin, DNSLookup* lookup, DNSAnswer* answer) :
  53. io_(io_service), done_(false),
  54. checkin_callback_(checkin),lookup_callback_(lookup),
  55. answer_callback_(answer)
  56. {
  57. // We must use different instantiations for v4 and v6;
  58. // otherwise ASIO will bind to both
  59. udp proto = addr.is_v4() ? udp::v4() : udp::v6();
  60. socket_.reset(new udp::socket(io_service, proto));
  61. socket_->set_option(socket_base::reuse_address(true));
  62. if (addr.is_v6()) {
  63. socket_->set_option(asio::ip::v6_only(true));
  64. }
  65. socket_->bind(udp::endpoint(addr, port));
  66. }
  67. /*
  68. * Copy constructor. Default one would probably do, but it is unnecessary
  69. * to copy many of the member variables every time we fork to handle
  70. * another packet.
  71. *
  72. * We also allocate data for receiving the packet here.
  73. */
  74. Data(const Data& other) :
  75. io_(other.io_), socket_(other.socket_), done_(false),
  76. checkin_callback_(other.checkin_callback_),
  77. lookup_callback_(other.lookup_callback_),
  78. answer_callback_(other.answer_callback_)
  79. {
  80. // Instantiate the data buffer and endpoint that will
  81. // be used by the asynchronous receive call.
  82. data_.reset(new char[MAX_LENGTH]);
  83. sender_.reset(new udp::endpoint());
  84. }
  85. // The ASIO service object
  86. asio::io_service& io_;
  87. // Class member variables which are dynamic, and changes to which
  88. // need to accessible from both sides of a coroutine fork or from
  89. // outside of the coroutine (i.e., from an asynchronous I/O call),
  90. // should be declared here as pointers and allocated in the
  91. // constructor or in the coroutine. This allows state information
  92. // to persist when an individual copy of the coroutine falls out
  93. // scope while waiting for an event, *so long as* there is another
  94. // object that is referencing the same data. As a side-benefit, using
  95. // pointers also reduces copy overhead for coroutine objects.
  96. //
  97. // Note: Currently these objects are allocated by "new" in the
  98. // constructor, or in the function operator while processing a query.
  99. // Repeated allocations from the heap for every incoming query is
  100. // clearly a performance issue; this must be optimized in the future.
  101. // The plan is to have a structure pre-allocate several "Data"
  102. // objects which can be pulled off a free list and placed on an in-use
  103. // list whenever a query comes in. This will serve the dual purpose
  104. // of improving performance and guaranteeing that state information
  105. // will *not* be destroyed when any one instance of the coroutine
  106. // falls out of scope while waiting for an event.
  107. //
  108. // Socket used to for listen for queries. Created in the
  109. // constructor and stored in a shared_ptr because socket objects
  110. // are not copyable.
  111. boost::shared_ptr<asio::ip::udp::socket> socket_;
  112. // The ASIO-internal endpoint object representing the client
  113. std::auto_ptr<asio::ip::udp::endpoint> sender_;
  114. // \c IOMessage and \c Message objects to be passed to the
  115. // DNS lookup and answer providers
  116. std::auto_ptr<asiolink::IOMessage> io_message_;
  117. // The original query as sent by the client
  118. isc::dns::MessagePtr query_message_;
  119. // The response message we are building
  120. isc::dns::MessagePtr answer_message_;
  121. // The buffer into which the response is written
  122. isc::util::OutputBufferPtr respbuf_;
  123. // The buffer into which the query packet is written
  124. boost::shared_array<char> data_;
  125. // State information that is entirely internal to a given instance
  126. // of the coroutine can be declared here.
  127. size_t bytes_;
  128. bool done_;
  129. // Callback functions provided by the caller
  130. const SimpleCallback* checkin_callback_;
  131. const DNSLookup* lookup_callback_;
  132. const DNSAnswer* answer_callback_;
  133. std::auto_ptr<IOEndpoint> peer_;
  134. std::auto_ptr<IOSocket> iosock_;
  135. };
  136. /// The following functions implement the \c UDPServer class.
  137. ///
  138. /// The constructor. It just creates new internal state object
  139. /// and lets it handle the initialization.
  140. UDPServer::UDPServer(io_service& io_service, const ip::address& addr,
  141. const uint16_t port, SimpleCallback* checkin, DNSLookup* lookup,
  142. DNSAnswer* answer) :
  143. data_(new Data(io_service, addr, port, checkin, lookup, answer))
  144. { }
  145. /// The function operator is implemented with the "stackless coroutine"
  146. /// pattern; see internal/coroutine.h for details.
  147. void
  148. UDPServer::operator()(asio::error_code ec, size_t length) {
  149. /// Because the coroutine reentry block is implemented as
  150. /// a switch statement, inline variable declarations are not
  151. /// permitted. Certain variables used below can be declared here.
  152. CORO_REENTER (this) {
  153. do {
  154. /*
  155. * This is preparation for receiving a packet. We get a new
  156. * state object for the lifetime of the next packet to come.
  157. * It allocates the buffers to receive data into.
  158. */
  159. data_.reset(new Data(*data_));
  160. do {
  161. // Begin an asynchronous receive, then yield.
  162. // When the receive event is posted, the coroutine
  163. // will resume immediately after this point.
  164. CORO_YIELD data_->socket_->async_receive_from(
  165. buffer(data_->data_.get(), MAX_LENGTH), *data_->sender_,
  166. *this);
  167. // Abort on fatal errors
  168. // TODO: add log
  169. if (ec) {
  170. using namespace asio::error;
  171. if (ec.value() != would_block && ec.value() != try_again &&
  172. ec.value() != interrupted) {
  173. return;
  174. }
  175. }
  176. } while (ec || length == 0);
  177. data_->bytes_ = length;
  178. /*
  179. * We fork the coroutine now. One (the child) will keep
  180. * the current state and handle the packet, then die and
  181. * drop ownership of the state. The other (parent) will just
  182. * go into the loop again and replace the current state with
  183. * a new one for a new object.
  184. *
  185. * Actually, both of the coroutines will be a copy of this
  186. * one, but that's just internal implementation detail.
  187. */
  188. CORO_FORK data_->io_.post(UDPServer(*this));
  189. } while (is_parent());
  190. // Create an \c IOMessage object to store the query.
  191. //
  192. // (XXX: It would be good to write a factory function
  193. // that would quickly generate an IOMessage object without
  194. // all these calls to "new".)
  195. data_->peer_.reset(new UDPEndpoint(*data_->sender_));
  196. // The UDP socket class has been extended with asynchronous functions
  197. // and takes as a template parameter a completion callback class. As
  198. // UDPServer does not use these extended functions (only those defined
  199. // in the IOSocket base class) - but needs a UDPSocket to get hold of
  200. // the underlying Boost UDP socket - DummyIOCallback is used. This
  201. // provides the appropriate operator() but is otherwise functionless.
  202. data_->iosock_.reset(
  203. new UDPSocket<DummyIOCallback>(*data_->socket_));
  204. data_->io_message_.reset(new IOMessage(data_->data_.get(),
  205. data_->bytes_, *data_->iosock_, *data_->peer_));
  206. // Perform any necessary operations prior to processing an incoming
  207. // query (e.g., checking for queued configuration messages).
  208. //
  209. // (XXX: it may be a performance issue to check in for every single
  210. // incoming query; we may wish to throttle this in the future.)
  211. if (data_->checkin_callback_ != NULL) {
  212. (*data_->checkin_callback_)(*data_->io_message_);
  213. }
  214. // If we don't have a DNS Lookup provider, there's no point in
  215. // continuing; we exit the coroutine permanently.
  216. if (data_->lookup_callback_ == NULL) {
  217. CORO_YIELD return;
  218. }
  219. // Instantiate objects that will be needed by the
  220. // asynchronous DNS lookup and/or by the send call.
  221. data_->respbuf_.reset(new OutputBuffer(0));
  222. data_->query_message_.reset(new Message(Message::PARSE));
  223. data_->answer_message_.reset(new Message(Message::RENDER));
  224. // Schedule a DNS lookup, and yield. When the lookup is
  225. // finished, the coroutine will resume immediately after
  226. // this point.
  227. CORO_YIELD data_->io_.post(AsyncLookup<UDPServer>(*this));
  228. // The 'done_' flag indicates whether we have an answer
  229. // to send back. If not, exit the coroutine permanently.
  230. if (!data_->done_) {
  231. CORO_YIELD return;
  232. }
  233. // Call the DNS answer provider to render the answer into
  234. // wire format
  235. (*data_->answer_callback_)(*data_->io_message_, data_->query_message_,
  236. data_->answer_message_, data_->respbuf_);
  237. // Begin an asynchronous send, and then yield. When the
  238. // send completes, we will resume immediately after this point
  239. // (though we have nothing further to do, so the coroutine
  240. // will simply exit at that time).
  241. CORO_YIELD data_->socket_->async_send_to(
  242. buffer(data_->respbuf_->getData(), data_->respbuf_->getLength()),
  243. *data_->sender_, *this);
  244. }
  245. }
  246. /// Call the DNS lookup provider. (Expected to be called by the
  247. /// AsyncLookup<UDPServer> handler.)
  248. void
  249. UDPServer::asyncLookup() {
  250. (*data_->lookup_callback_)(*data_->io_message_,
  251. data_->query_message_, data_->answer_message_, data_->respbuf_, this);
  252. }
  253. /// Stop the UDPServer
  254. void
  255. UDPServer::stop() {
  256. /// Using close instead of cancel, because cancel
  257. /// will only cancel the asynchornized event already submitted
  258. /// to io service, the events post to io service after
  259. /// cancel still can be scheduled by io service, if
  260. /// the socket is cloesed, all the asynchronized event
  261. /// for it won't be scheduled by io service not matter it is
  262. /// submit to io serice before or after close call. And we will
  263. //. get bad_descriptor error
  264. data_->socket_->close();
  265. }
  266. /// Post this coroutine on the ASIO service queue so that it will
  267. /// resume processing where it left off. The 'done' parameter indicates
  268. /// whether there is an answer to return to the client.
  269. void
  270. UDPServer::resume(const bool done) {
  271. data_->done_ = done;
  272. data_->io_.post(*this);
  273. }
  274. bool
  275. UDPServer::hasAnswer() {
  276. return (data_->done_);
  277. }
  278. } // namespace asiodns
  279. } // namespace isc