udp_server.cc 14 KB

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