udp_server.cc 12 KB

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