udpdns.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. #include <config.h>
  15. #include <unistd.h> // for some IPC/network system calls
  16. #include <sys/socket.h>
  17. #include <netinet/in.h>
  18. #include <boost/bind.hpp>
  19. #include <asio.hpp>
  20. #include <asio/deadline_timer.hpp>
  21. #include <memory>
  22. #include <boost/shared_ptr.hpp>
  23. #include <boost/date_time/posix_time/posix_time_types.hpp>
  24. #include <dns/buffer.h>
  25. #include <dns/message.h>
  26. #include <dns/messagerenderer.h>
  27. #include <log/dummylog.h>
  28. #include <dns/opcode.h>
  29. #include <dns/rcode.h>
  30. #include <asiolink.h>
  31. #include <internal/coroutine.h>
  32. #include <internal/udpdns.h>
  33. using namespace asio;
  34. using asio::ip::udp;
  35. using asio::ip::tcp;
  36. using isc::log::dlog;
  37. using namespace std;
  38. using namespace isc::dns;
  39. namespace asiolink {
  40. struct UDPServer::Data {
  41. Data(io_service& io_service, const ip::address& addr, const uint16_t port,
  42. SimpleCallback* checkin, DNSLookup* lookup, DNSAnswer* answer) :
  43. io_(io_service), done_(false), checkin_callback_(checkin),
  44. lookup_callback_(lookup), answer_callback_(answer)
  45. {
  46. // We must use different instantiations for v4 and v6;
  47. // otherwise ASIO will bind to both
  48. udp proto = addr.is_v4() ? udp::v4() : udp::v6();
  49. socket_.reset(new udp::socket(io_service, proto));
  50. socket_->set_option(socket_base::reuse_address(true));
  51. if (addr.is_v6()) {
  52. socket_->set_option(asio::ip::v6_only(true));
  53. }
  54. socket_->bind(udp::endpoint(addr, port));
  55. }
  56. Data(const Data& other) :
  57. io_(other.io_), socket_(other.socket_), done_(false),
  58. checkin_callback_(other.checkin_callback_),
  59. lookup_callback_(other.lookup_callback_),
  60. answer_callback_(other.answer_callback_)
  61. {
  62. // Instantiate the data buffer and endpoint that will
  63. // be used by the asynchronous receive call.
  64. data_.reset(new char[MAX_LENGTH]);
  65. sender_.reset(new udp::endpoint());
  66. }
  67. // The ASIO service object
  68. asio::io_service& io_;
  69. // Class member variables which are dynamic, and changes to which
  70. // need to accessible from both sides of a coroutine fork or from
  71. // outside of the coroutine (i.e., from an asynchronous I/O call),
  72. // should be declared here as pointers and allocated in the
  73. // constructor or in the coroutine. This allows state information
  74. // to persist when an individual copy of the coroutine falls out
  75. // scope while waiting for an event, *so long as* there is another
  76. // object that is referencing the same data. As a side-benefit, using
  77. // pointers also reduces copy overhead for coroutine objects.
  78. //
  79. // Note: Currently these objects are allocated by "new" in the
  80. // constructor, or in the function operator while processing a query.
  81. // Repeated allocations from the heap for every incoming query is
  82. // clearly a performance issue; this must be optimized in the future.
  83. // The plan is to have a structure pre-allocate several "server state"
  84. // objects which can be pulled off a free list and placed on an in-use
  85. // list whenever a query comes in. This will serve the dual purpose
  86. // of improving performance and guaranteeing that state information
  87. // will *not* be destroyed when any one instance of the coroutine
  88. // falls out of scope while waiting for an event.
  89. //
  90. // Socket used to for listen for queries. Created in the
  91. // constructor and stored in a shared_ptr because socket objects
  92. // are not copyable.
  93. boost::shared_ptr<asio::ip::udp::socket> socket_;
  94. // The ASIO-enternal endpoint object representing the client
  95. std::auto_ptr<asio::ip::udp::endpoint> sender_;
  96. // \c IOMessage and \c Message objects to be passed to the
  97. // DNS lookup and answer providers
  98. std::auto_ptr<asiolink::IOMessage> io_message_;
  99. // The original query as sent by the client
  100. isc::dns::MessagePtr query_message_;
  101. // The response message we are building
  102. isc::dns::MessagePtr answer_message_;
  103. // The buffer into which the response is written
  104. isc::dns::OutputBufferPtr respbuf_;
  105. // The buffer into which the query packet is written
  106. boost::shared_array<char> data_;
  107. // State information that is entirely internal to a given instance
  108. // of the coroutine can be declared here.
  109. size_t bytes_;
  110. bool done_;
  111. // Callback functions provided by the caller
  112. const SimpleCallback* checkin_callback_;
  113. const DNSLookup* lookup_callback_;
  114. const DNSAnswer* answer_callback_;
  115. std::auto_ptr<IOEndpoint> peer_;
  116. std::auto_ptr<IOSocket> iosock_;
  117. };
  118. /// The following functions implement the \c UDPServer class.
  119. ///
  120. /// The constructor
  121. UDPServer::UDPServer(io_service& io_service, const ip::address& addr,
  122. const uint16_t port, SimpleCallback* checkin, DNSLookup* lookup,
  123. DNSAnswer* answer) :
  124. data_(new Data(io_service, addr, port, checkin, lookup, answer))
  125. { }
  126. /// The function operator is implemented with the "stackless coroutine"
  127. /// pattern; see internal/coroutine.h for details.
  128. void
  129. UDPServer::operator()(error_code ec, size_t length) {
  130. /// Because the coroutine reeentry block is implemented as
  131. /// a switch statement, inline variable declarations are not
  132. /// permitted. Certain variables used below can be declared here.
  133. CORO_REENTER (this) {
  134. do {
  135. data_.reset(new Data(*data_));
  136. do {
  137. // Begin an asynchronous receive, then yield.
  138. // When the receive event is posted, the coroutine
  139. // will resume immediately after this point.
  140. CORO_YIELD data_->socket_->async_receive_from(
  141. buffer(data_->data_.get(), MAX_LENGTH), *data_->sender_,
  142. *this);
  143. } while (ec || length == 0);
  144. data_->bytes_ = length;
  145. /// Fork the coroutine by creating a copy of this one and
  146. /// scheduling it on the ASIO service queue. The parent
  147. /// will continue listening for DNS packets while the child
  148. /// processes the one that has just arrived.
  149. CORO_FORK data_->io_.post(UDPServer(*this));
  150. } while (is_parent());
  151. // Create an \c IOMessage object to store the query.
  152. //
  153. // (XXX: It would be good to write a factory function
  154. // that would quickly generate an IOMessage object without
  155. // all these calls to "new".)
  156. data_->peer_.reset(new UDPEndpoint(*data_->sender_));
  157. data_->iosock_.reset(new UDPSocket(*data_->socket_));
  158. data_->io_message_.reset(new IOMessage(data_->data_.get(),
  159. data_->bytes_, *data_->iosock_, *data_->peer_));
  160. // Perform any necessary operations prior to processing an incoming
  161. // query (e.g., checking for queued configuration messages).
  162. //
  163. // (XXX: it may be a performance issue to check in for every single
  164. // incoming query; we may wish to throttle this in the future.)
  165. if (data_->checkin_callback_ != NULL) {
  166. (*data_->checkin_callback_)(*data_->io_message_);
  167. }
  168. // If we don't have a DNS Lookup provider, there's no point in
  169. // continuing; we exit the coroutine permanently.
  170. if (data_->lookup_callback_ == NULL) {
  171. CORO_YIELD return;
  172. }
  173. // Instantiate objects that will be needed by the
  174. // asynchronous DNS lookup and/or by the send call.
  175. data_->respbuf_.reset(new OutputBuffer(0));
  176. data_->query_message_.reset(new Message(Message::PARSE));
  177. data_->answer_message_.reset(new Message(Message::RENDER));
  178. // Schedule a DNS lookup, and yield. When the lookup is
  179. // finished, the coroutine will resume immediately after
  180. // this point.
  181. CORO_YIELD data_->io_.post(AsyncLookup<UDPServer>(*this));
  182. dlog("[XX] got an answer");
  183. // The 'done_' flag indicates whether we have an answer
  184. // to send back. If not, exit the coroutine permanently.
  185. if (!data_->done_) {
  186. CORO_YIELD return;
  187. }
  188. // Call the DNS answer provider to render the answer into
  189. // wire format
  190. (*data_->answer_callback_)(*data_->io_message_, data_->query_message_,
  191. data_->answer_message_, data_->respbuf_);
  192. // Begin an asynchronous send, and then yield. When the
  193. // send completes, we will resume immediately after this point
  194. // (though we have nothing further to do, so the coroutine
  195. // will simply exit at that time).
  196. CORO_YIELD data_->socket_->async_send_to(
  197. buffer(data_->respbuf_->getData(), data_->respbuf_->getLength()),
  198. *data_->sender_, *this);
  199. }
  200. }
  201. /// Call the DNS lookup provider. (Expected to be called by the
  202. /// AsyncLookup<UDPServer> handler.)
  203. void
  204. UDPServer::asyncLookup() {
  205. (*data_->lookup_callback_)(*data_->io_message_,
  206. data_->query_message_, data_->answer_message_, data_->respbuf_, this);
  207. }
  208. /// Post this coroutine on the ASIO service queue so that it will
  209. /// resume processing where it left off. The 'done' parameter indicates
  210. /// whether there is an answer to return to the client.
  211. void
  212. UDPServer::resume(const bool done) {
  213. data_->done_ = done;
  214. data_->io_.post(*this);
  215. }
  216. bool
  217. UDPServer::hasAnswer() {
  218. return (data_->done_);
  219. }
  220. // Private UDPQuery data (see internal/udpdns.h for reasons)
  221. struct UDPQuery::PrivateData {
  222. // Socket we send query to and expect reply from there
  223. udp::socket socket;
  224. // Where was the query sent
  225. udp::endpoint remote;
  226. // What we ask the server
  227. Question question;
  228. // We will store the answer here
  229. OutputBufferPtr buffer;
  230. OutputBufferPtr msgbuf;
  231. // Temporary buffer for answer
  232. boost::shared_array<char> data;
  233. // This will be called when the data arrive or timeouts
  234. Callback* callback;
  235. // Did we already stop operating (data arrived, we timed out, someone
  236. // called stop). This can be so when we are cleaning up/there are
  237. // still pointers to us.
  238. bool stopped;
  239. // Timer to measure timeouts.
  240. deadline_timer timer;
  241. // How many milliseconds are we willing to wait for answer?
  242. int timeout;
  243. PrivateData(io_service& service,
  244. const udp::socket::protocol_type& protocol, const Question &q,
  245. OutputBufferPtr b, Callback *c) :
  246. socket(service, protocol),
  247. question(q),
  248. buffer(b),
  249. msgbuf(new OutputBuffer(512)),
  250. callback(c),
  251. stopped(false),
  252. timer(service)
  253. { }
  254. };
  255. /// The following functions implement the \c UDPQuery class.
  256. ///
  257. /// The constructor
  258. UDPQuery::UDPQuery(io_service& io_service,
  259. const Question& q, const IOAddress& addr, uint16_t port,
  260. OutputBufferPtr buffer, Callback *callback, int timeout) :
  261. data_(new PrivateData(io_service,
  262. addr.getFamily() == AF_INET ? udp::v4() : udp::v6(), q, buffer,
  263. callback))
  264. {
  265. data_->remote = UDPEndpoint(addr, port).getASIOEndpoint();
  266. data_->timeout = timeout;
  267. }
  268. /// The function operator is implemented with the "stackless coroutine"
  269. /// pattern; see internal/coroutine.h for details.
  270. void
  271. UDPQuery::operator()(error_code ec, size_t length) {
  272. if (ec || data_->stopped) {
  273. return;
  274. }
  275. CORO_REENTER (this) {
  276. /// Generate the upstream query and render it to wire format
  277. /// This is done in a different scope to allow inline variable
  278. /// declarations.
  279. {
  280. Message msg(Message::RENDER);
  281. // XXX: replace with boost::random or some other suitable PRNG
  282. msg.setQid(0);
  283. msg.setOpcode(Opcode::QUERY());
  284. msg.setRcode(Rcode::NOERROR());
  285. msg.setHeaderFlag(Message::HEADERFLAG_RD);
  286. msg.addQuestion(data_->question);
  287. MessageRenderer renderer(*data_->msgbuf);
  288. msg.toWire(renderer);
  289. dlog("Sending " + msg.toText() + " to " +
  290. data_->remote.address().to_string());
  291. }
  292. // If we timeout, we stop, which will shutdown everything and
  293. // cancel all other attempts to run inside the coroutine
  294. if (data_->timeout != -1) {
  295. data_->timer.expires_from_now(boost::posix_time::milliseconds(
  296. data_->timeout));
  297. data_->timer.async_wait(boost::bind(&UDPQuery::stop, *this,
  298. TIME_OUT));
  299. }
  300. // Begin an asynchronous send, and then yield. When the
  301. // send completes, we will resume immediately after this point.
  302. CORO_YIELD data_->socket.async_send_to(buffer(data_->msgbuf->getData(),
  303. data_->msgbuf->getLength()), data_->remote, *this);
  304. /// Allocate space for the response. (XXX: This should be
  305. /// optimized by maintaining a free list of pre-allocated blocks)
  306. data_->data.reset(new char[MAX_LENGTH]);
  307. /// Begin an asynchronous receive, and yield. When the receive
  308. /// completes, we will resume immediately after this point.
  309. CORO_YIELD data_->socket.async_receive_from(buffer(data_->data.get(),
  310. MAX_LENGTH), data_->remote, *this);
  311. // The message is not rendered yet, so we can't print it easilly
  312. dlog("Received response from " + data_->remote.address().to_string());
  313. /// Copy the answer into the response buffer. (XXX: If the
  314. /// OutputBuffer object were made to meet the requirements of
  315. /// a MutableBufferSequence, then it could be written to directly
  316. /// by async_recieve_from() and this additional copy step would
  317. /// be unnecessary.)
  318. data_->buffer->writeData(data_->data.get(), length);
  319. /// We are done
  320. stop(SUCCESS);
  321. }
  322. }
  323. void
  324. UDPQuery::stop(Result result) {
  325. if (!data_->stopped) {
  326. switch (result) {
  327. case TIME_OUT:
  328. dlog("Query timed out");
  329. break;
  330. case STOPPED:
  331. dlog("Query stopped");
  332. break;
  333. default:;
  334. }
  335. data_->stopped = true;
  336. data_->socket.cancel();
  337. data_->socket.close();
  338. data_->timer.cancel();
  339. if (data_->callback) {
  340. (*data_->callback)(result);
  341. }
  342. }
  343. }
  344. }