udp_server.cc 13 KB

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