udp_server.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. SimpleCallback* checkin, DNSLookup* lookup, DNSAnswer* answer) :
  54. io_(io_service), bytes_(0), done_(false),
  55. checkin_callback_(checkin),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, SimpleCallback* checkin,
  69. DNSLookup* lookup, DNSAnswer* answer) :
  70. io_(io_service), bytes_(0), done_(false),
  71. checkin_callback_(checkin),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. checkin_callback_(other.checkin_callback_),
  98. lookup_callback_(other.lookup_callback_),
  99. answer_callback_(other.answer_callback_)
  100. {
  101. // Instantiate the data buffer and endpoint that will
  102. // be used by the asynchronous receive call.
  103. data_.reset(new char[MAX_LENGTH]);
  104. sender_.reset(new udp::endpoint());
  105. }
  106. // The ASIO service object
  107. asio::io_service& io_;
  108. // Class member variables which are dynamic, and changes to which
  109. // need to accessible from both sides of a coroutine fork or from
  110. // outside of the coroutine (i.e., from an asynchronous I/O call),
  111. // should be declared here as pointers and allocated in the
  112. // constructor or in the coroutine. This allows state information
  113. // to persist when an individual copy of the coroutine falls out
  114. // scope while waiting for an event, *so long as* there is another
  115. // object that is referencing the same data. As a side-benefit, using
  116. // pointers also reduces copy overhead for coroutine objects.
  117. //
  118. // Note: Currently these objects are allocated by "new" in the
  119. // constructor, or in the function operator while processing a query.
  120. // Repeated allocations from the heap for every incoming query is
  121. // clearly a performance issue; this must be optimized in the future.
  122. // The plan is to have a structure pre-allocate several "Data"
  123. // objects which can be pulled off a free list and placed on an in-use
  124. // list whenever a query comes in. This will serve the dual purpose
  125. // of improving performance and guaranteeing that state information
  126. // will *not* be destroyed when any one instance of the coroutine
  127. // falls out of scope while waiting for an event.
  128. //
  129. // Socket used to for listen for queries. Created in the
  130. // constructor and stored in a shared_ptr because socket objects
  131. // are not copyable.
  132. boost::shared_ptr<asio::ip::udp::socket> socket_;
  133. // The ASIO-internal endpoint object representing the client
  134. std::auto_ptr<asio::ip::udp::endpoint> sender_;
  135. // \c IOMessage and \c Message objects to be passed to the
  136. // DNS lookup and answer providers
  137. std::auto_ptr<asiolink::IOMessage> io_message_;
  138. // The original query as sent by the client
  139. isc::dns::MessagePtr query_message_;
  140. // The response message we are building
  141. isc::dns::MessagePtr answer_message_;
  142. // The buffer into which the response is written
  143. isc::util::OutputBufferPtr respbuf_;
  144. // The buffer into which the query packet is written
  145. boost::shared_array<char> data_;
  146. // State information that is entirely internal to a given instance
  147. // of the coroutine can be declared here.
  148. size_t bytes_;
  149. bool done_;
  150. // Callback functions provided by the caller
  151. const SimpleCallback* checkin_callback_;
  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. SimpleCallback* checkin, DNSLookup* lookup,
  163. DNSAnswer* answer) :
  164. data_(new Data(io_service, fd, af, checkin, 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 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. // Perform any necessary operations prior to processing an incoming
  233. // query (e.g., checking for queued configuration messages).
  234. //
  235. // (XXX: it may be a performance issue to check in for every single
  236. // incoming query; we may wish to throttle this in the future.)
  237. if (data_->checkin_callback_ != NULL) {
  238. (*data_->checkin_callback_)(*data_->io_message_);
  239. }
  240. // If we don't have a DNS Lookup provider, there's no point in
  241. // continuing; we exit the coroutine permanently.
  242. if (data_->lookup_callback_ == NULL) {
  243. return;
  244. }
  245. // Instantiate objects that will be needed by the
  246. // asynchronous DNS lookup and/or by the send call.
  247. data_->respbuf_.reset(new OutputBuffer(0));
  248. data_->query_message_.reset(new Message(Message::PARSE));
  249. data_->answer_message_.reset(new Message(Message::RENDER));
  250. // Schedule a DNS lookup, and yield. When the lookup is
  251. // finished, the coroutine will resume immediately after
  252. // this point.
  253. CORO_YIELD data_->io_.post(AsyncLookup<UDPServer>(*this));
  254. // The 'done_' flag indicates whether we have an answer
  255. // to send back. If not, exit the coroutine permanently.
  256. if (!data_->done_) {
  257. return;
  258. }
  259. // Call the DNS answer provider to render the answer into
  260. // wire format
  261. (*data_->answer_callback_)(*data_->io_message_, data_->query_message_,
  262. data_->answer_message_, data_->respbuf_);
  263. // Begin an asynchronous send, and then yield. When the
  264. // send completes, we will resume immediately after this point
  265. // (though we have nothing further to do, so the coroutine
  266. // will simply exit at that time, after reporting an error if
  267. // there was one).
  268. CORO_YIELD data_->socket_->async_send_to(
  269. buffer(data_->respbuf_->getData(), data_->respbuf_->getLength()),
  270. *data_->sender_, *this);
  271. if (ec) {
  272. LOG_ERROR(logger, ASIODNS_UDP_ASYNC_SEND_FAIL).
  273. arg(data_->sender_->address().to_string()).
  274. arg(ec.message());
  275. }
  276. }
  277. }
  278. /// Call the DNS lookup provider. (Expected to be called by the
  279. /// AsyncLookup<UDPServer> handler.)
  280. void
  281. UDPServer::asyncLookup() {
  282. (*data_->lookup_callback_)(*data_->io_message_,
  283. data_->query_message_, data_->answer_message_, data_->respbuf_, this);
  284. }
  285. /// Stop the UDPServer
  286. void
  287. UDPServer::stop() {
  288. asio::error_code ec;
  289. /// Using close instead of cancel, because cancel
  290. /// will only cancel the asynchronized event already submitted
  291. /// to io service, the events post to io service after
  292. /// cancel still can be scheduled by io service, if
  293. /// the socket is closed, all the asynchronized event
  294. /// for it won't be scheduled by io service not matter it is
  295. /// submit to io service before or after close call. And we will
  296. // get bad_descriptor error.
  297. data_->socket_->close(ec);
  298. if (ec) {
  299. LOG_ERROR(logger, ASIODNS_UDP_CLOSE_FAIL).arg(ec.message());
  300. }
  301. }
  302. /// Post this coroutine on the ASIO service queue so that it will
  303. /// resume processing where it left off. The 'done' parameter indicates
  304. /// whether there is an answer to return to the client.
  305. void
  306. UDPServer::resume(const bool done) {
  307. data_->done_ = done;
  308. data_->io_.post(*this); // this can throw, but can be considered fatal.
  309. }
  310. } // namespace asiodns
  311. } // namespace isc