udpdns.cc 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. // Copyright (C) 2010 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. // $Id$
  15. #include <config.h>
  16. #include <unistd.h> // for some IPC/network system calls
  17. #include <sys/socket.h>
  18. #include <netinet/in.h>
  19. #include <boost/bind.hpp>
  20. #include <asio.hpp>
  21. #include <boost/shared_ptr.hpp>
  22. #include <dns/buffer.h>
  23. #include <dns/message.h>
  24. #include <dns/messagerenderer.h>
  25. #include <log/dummylog.h>
  26. #include <asiolink.h>
  27. #include <internal/coroutine.h>
  28. #include <internal/udpdns.h>
  29. using namespace asio;
  30. using asio::ip::udp;
  31. using asio::ip::tcp;
  32. using isc::log::dlog;
  33. using namespace std;
  34. using namespace isc::dns;
  35. namespace asiolink {
  36. /// The following functions implement the \c UDPServer class.
  37. ///
  38. /// The constructor
  39. UDPServer::UDPServer(io_service& io_service,
  40. const ip::address& addr, const uint16_t port,
  41. SimpleCallback* checkin,
  42. DNSLookup* lookup,
  43. DNSAnswer* answer) :
  44. io_(io_service), done_(false),
  45. checkin_callback_(checkin),
  46. lookup_callback_(lookup),
  47. answer_callback_(answer)
  48. {
  49. // We must use different instantiations for v4 and v6;
  50. // otherwise ASIO will bind to both
  51. udp proto = addr.is_v4() ? udp::v4() : udp::v6();
  52. socket_.reset(new udp::socket(io_service, proto));
  53. socket_->set_option(socket_base::reuse_address(true));
  54. if (addr.is_v6()) {
  55. socket_->set_option(asio::ip::v6_only(true));
  56. }
  57. socket_->bind(udp::endpoint(proto, port));
  58. }
  59. /// The function operator is implemented with the "stackless coroutine"
  60. /// pattern; see internal/coroutine.h for details.
  61. void
  62. UDPServer::operator()(error_code ec, size_t length) {
  63. /// Because the coroutine reeentry block is implemented as
  64. /// a switch statement, inline variable declarations are not
  65. /// permitted. Certain variables used below can be declared here.
  66. IOEndpoint* peer;
  67. IOSocket* iosock;
  68. CORO_REENTER (this) {
  69. do {
  70. // Instantiate the data buffer and endpoint that will
  71. // be used by the asynchronous receive call.
  72. data_.reset(new char[MAX_LENGTH]);
  73. sender_.reset(new udp::endpoint());
  74. do {
  75. // Begin an asynchronous receive, then yield.
  76. // When the receive event is posted, the coroutine
  77. // will resume immediately after this point.
  78. CORO_YIELD socket_->async_receive_from(buffer(data_.get(),
  79. MAX_LENGTH),
  80. *sender_, *this);
  81. } while (ec || length == 0);
  82. bytes_ = length;
  83. /// Fork the coroutine by creating a copy of this one and
  84. /// scheduling it on the ASIO service queue. The parent
  85. /// will continue listening for DNS packets while the child
  86. /// processes the one that has just arrived.
  87. CORO_FORK io_.post(UDPServer(*this));
  88. } while (is_parent());
  89. // Create an \c IOMessage object to store the query.
  90. //
  91. // (XXX: It would be good to write a factory function
  92. // that would quickly generate an IOMessage object without
  93. // all these calls to "new".)
  94. peer = new UDPEndpoint(*sender_);
  95. iosock = new UDPSocket(*socket_);
  96. io_message_.reset(new IOMessage(data_.get(), bytes_, *iosock, *peer));
  97. // Perform any necessary operations prior to processing an incoming
  98. // query (e.g., checking for queued configuration messages).
  99. //
  100. // (XXX: it may be a performance issue to check in for every single
  101. // incoming query; we may wish to throttle this in the future.)
  102. if (checkin_callback_ != NULL) {
  103. (*checkin_callback_)(*io_message_);
  104. }
  105. // If we don't have a DNS Lookup provider, there's no point in
  106. // continuing; we exit the coroutine permanently.
  107. if (lookup_callback_ == NULL) {
  108. CORO_YIELD return;
  109. }
  110. // Instantiate objects that will be needed by the
  111. // asynchronous DNS lookup and/or by the send call.
  112. respbuf_.reset(new OutputBuffer(0));
  113. message_.reset(new Message(Message::PARSE));
  114. // Schedule a DNS lookup, and yield. When the lookup is
  115. // finished, the coroutine will resume immediately after
  116. // this point.
  117. CORO_YIELD io_.post(AsyncLookup<UDPServer>(*this));
  118. // The 'done_' flag indicates whether we have an answer
  119. // to send back. If not, exit the coroutine permanently.
  120. if (!done_) {
  121. CORO_YIELD return;
  122. }
  123. // Call the DNS answer provider to render the answer into
  124. // wire format
  125. (*answer_callback_)(*io_message_, message_, respbuf_);
  126. // Begin an asynchronous send, and then yield. When the
  127. // send completes, we will resume immediately after this point
  128. // (though we have nothing further to do, so the coroutine
  129. // will simply exit at that time).
  130. CORO_YIELD socket_->async_send_to(buffer(respbuf_->getData(),
  131. respbuf_->getLength()),
  132. *sender_, *this);
  133. }
  134. }
  135. /// Call the DNS lookup provider. (Expected to be called by the
  136. /// AsyncLookup<UDPServer> handler.)
  137. void
  138. UDPServer::asyncLookup() {
  139. (*lookup_callback_)(*io_message_, message_, respbuf_, this);
  140. }
  141. /// Post this coroutine on the ASIO service queue so that it will
  142. /// resume processing where it left off. The 'done' parameter indicates
  143. /// whether there is an answer to return to the client.
  144. void
  145. UDPServer::resume(const bool done) {
  146. done_ = done;
  147. io_.post(*this);
  148. }
  149. /// The following functions implement the \c UDPQuery class.
  150. ///
  151. /// The constructor
  152. UDPQuery::UDPQuery(io_service& io_service,
  153. const Question& q, const IOAddress& addr, uint16_t port,
  154. OutputBufferPtr buffer, DNSServer* server) :
  155. question_(q), buffer_(buffer), server_(server->clone())
  156. {
  157. udp proto = (addr.getFamily() == AF_INET) ? udp::v4() : udp::v6();
  158. socket_.reset(new udp::socket(io_service, proto));
  159. msgbuf_.reset(new OutputBuffer(512));
  160. remote_ = UDPEndpoint(addr, port).getASIOEndpoint();
  161. }
  162. /// The function operator is implemented with the "stackless coroutine"
  163. /// pattern; see internal/coroutine.h for details.
  164. void
  165. UDPQuery::operator()(error_code ec, size_t length) {
  166. if (ec) {
  167. return;
  168. }
  169. CORO_REENTER (this) {
  170. /// Generate the upstream query and render it to wire format
  171. /// This is done in a different scope to allow inline variable
  172. /// declarations.
  173. {
  174. Message msg(Message::RENDER);
  175. // XXX: replace with boost::random or some other suitable PRNG
  176. msg.setQid(0);
  177. msg.setOpcode(Opcode::QUERY());
  178. msg.setRcode(Rcode::NOERROR());
  179. msg.setHeaderFlag(MessageFlag::RD());
  180. msg.addQuestion(question_);
  181. MessageRenderer renderer(*msgbuf_);
  182. msg.toWire(renderer);
  183. dlog("Sending " + msg.toText() + " to " +
  184. remote_.address().to_string());
  185. }
  186. // Begin an asynchronous send, and then yield. When the
  187. // send completes, we will resume immediately after this point.
  188. CORO_YIELD socket_->async_send_to(buffer(msgbuf_->getData(),
  189. msgbuf_->getLength()),
  190. remote_, *this);
  191. /// Allocate space for the response. (XXX: This should be
  192. /// optimized by maintaining a free list of pre-allocated blocks)
  193. data_.reset(new char[MAX_LENGTH]);
  194. /// Begin an asynchronous receive, and yield. When the receive
  195. /// completes, we will resume immediately after this point.
  196. CORO_YIELD socket_->async_receive_from(buffer(data_.get(), MAX_LENGTH),
  197. remote_, *this);
  198. // The message is not rendered yet, so we can't print it easilly
  199. dlog("Received response from " + remote_.address().to_string());
  200. /// Copy the answer into the response buffer. (XXX: If the
  201. /// OutputBuffer object were made to meet the requirements of
  202. /// a MutableBufferSequence, then it could be written to directly
  203. /// by async_recieve_from() and this additional copy step would
  204. /// be unnecessary.)
  205. buffer_->writeData(data_.get(), length);
  206. /// Signal the DNSServer object to resume processing.
  207. server_->resume(true);
  208. }
  209. }
  210. }