tcp_server.cc 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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 <config.h>
  15. #include <netinet/in.h>
  16. #include <sys/socket.h>
  17. #include <unistd.h> // for some IPC/network system calls
  18. #include <errno.h>
  19. #include <boost/shared_array.hpp>
  20. #include <log/dummylog.h>
  21. #include <util/buffer.h>
  22. #include <asio.hpp>
  23. #include <asiolink/dummy_io_cb.h>
  24. #include <asiolink/tcp_endpoint.h>
  25. #include <asiolink/tcp_socket.h>
  26. #include <asiodns/tcp_server.h>
  27. #include <asiodns/logger.h>
  28. using namespace asio;
  29. using asio::ip::udp;
  30. using asio::ip::tcp;
  31. using namespace std;
  32. using namespace isc::dns;
  33. using namespace isc::util;
  34. using namespace isc::asiolink;
  35. namespace isc {
  36. namespace asiodns {
  37. /// The following functions implement the \c TCPServer class.
  38. ///
  39. /// The constructor
  40. TCPServer::TCPServer(io_service& io_service,
  41. const ip::address& addr, const uint16_t port,
  42. const SimpleCallback* checkin,
  43. const DNSLookup* lookup,
  44. const DNSAnswer* answer) :
  45. io_(io_service), done_(false),
  46. checkin_callback_(checkin), lookup_callback_(lookup),
  47. answer_callback_(answer)
  48. {
  49. tcp::endpoint endpoint(addr, port);
  50. acceptor_.reset(new tcp::acceptor(io_service));
  51. acceptor_->open(endpoint.protocol());
  52. // Set v6-only (we use a separate instantiation for v4,
  53. // otherwise asio will bind to both v4 and v6
  54. if (addr.is_v6()) {
  55. acceptor_->set_option(ip::v6_only(true));
  56. }
  57. acceptor_->set_option(tcp::acceptor::reuse_address(true));
  58. acceptor_->bind(endpoint);
  59. acceptor_->listen();
  60. }
  61. TCPServer::TCPServer(io_service& io_service, int fd, int af,
  62. const SimpleCallback* checkin,
  63. const DNSLookup* lookup,
  64. const DNSAnswer* answer) :
  65. io_(io_service), done_(false),
  66. checkin_callback_(checkin), lookup_callback_(lookup),
  67. answer_callback_(answer)
  68. {
  69. if (af != AF_INET && af != AF_INET6) {
  70. isc_throw(InvalidParameter, "Address family must be either AF_INET "
  71. "or AF_INET6, not " << af);
  72. }
  73. LOG_DEBUG(logger, DBGLVL_TRACE_BASIC, ASIODNS_FD_ADD_TCP).arg(fd);
  74. try {
  75. acceptor_.reset(new tcp::acceptor(io_service));
  76. acceptor_->assign(af == AF_INET6 ? tcp::v6() : tcp::v4(), fd);
  77. acceptor_->listen();
  78. } catch (const std::exception& exception) {
  79. // Whatever the thing throws, it is something from ASIO and we convert
  80. // it
  81. isc_throw(IOError, exception.what());
  82. }
  83. }
  84. void
  85. TCPServer::operator()(asio::error_code ec, size_t length) {
  86. /// Because the coroutine reentry block is implemented as
  87. /// a switch statement, inline variable declarations are not
  88. /// permitted. Certain variables used below can be declared here.
  89. boost::array<const_buffer,2> bufs;
  90. OutputBuffer lenbuf(TCP_MESSAGE_LENGTHSIZE);
  91. CORO_REENTER (this) {
  92. do {
  93. /// Create a socket to listen for connections
  94. socket_.reset(new tcp::socket(acceptor_->get_io_service()));
  95. /// Wait for new connections. In the event of non-fatal error,
  96. /// try again
  97. do {
  98. CORO_YIELD acceptor_->async_accept(*socket_, *this);
  99. // Abort on fatal errors
  100. // TODO: Log error?
  101. if (ec) {
  102. using namespace asio::error;
  103. if (ec.value() != would_block && ec.value() != try_again &&
  104. ec.value() != connection_aborted &&
  105. ec.value() != interrupted) {
  106. return;
  107. }
  108. }
  109. } while (ec);
  110. /// Fork the coroutine by creating a copy of this one and
  111. /// scheduling it on the ASIO service queue. The parent
  112. /// will continue listening for DNS connections while the
  113. /// handles the one that has just arrived.
  114. CORO_FORK io_.post(TCPServer(*this));
  115. } while (is_parent());
  116. /// Instantiate the data buffer that will be used by the
  117. /// asynchronous read call.
  118. data_.reset(new char[MAX_LENGTH]);
  119. /// Read the message, in two parts. First, the message length:
  120. CORO_YIELD async_read(*socket_, asio::buffer(data_.get(),
  121. TCP_MESSAGE_LENGTHSIZE), *this);
  122. if (ec) {
  123. socket_->close();
  124. CORO_YIELD return;
  125. }
  126. /// Now read the message itself. (This is done in a different scope
  127. /// to allow inline variable declarations.)
  128. CORO_YIELD {
  129. InputBuffer dnsbuffer(data_.get(), length);
  130. uint16_t msglen = dnsbuffer.readUint16();
  131. async_read(*socket_, asio::buffer(data_.get(), msglen), *this);
  132. }
  133. if (ec) {
  134. socket_->close();
  135. CORO_YIELD return;
  136. }
  137. // Create an \c IOMessage object to store the query.
  138. //
  139. // (XXX: It would be good to write a factory function
  140. // that would quickly generate an IOMessage object without
  141. // all these calls to "new".)
  142. peer_.reset(new TCPEndpoint(socket_->remote_endpoint()));
  143. // The TCP socket class has been extended with asynchronous functions
  144. // and takes as a template parameter a completion callback class. As
  145. // TCPServer does not use these extended functions (only those defined
  146. // in the IOSocket base class) - but needs a TCPSocket to get hold of
  147. // the underlying Boost TCP socket - DummyIOCallback is used. This
  148. // provides the appropriate operator() but is otherwise functionless.
  149. iosock_.reset(new TCPSocket<DummyIOCallback>(*socket_));
  150. io_message_.reset(new IOMessage(data_.get(), length, *iosock_, *peer_));
  151. bytes_ = length;
  152. // Perform any necessary operations prior to processing the incoming
  153. // packet (e.g., checking for queued configuration messages).
  154. //
  155. // (XXX: it may be a performance issue to have this called for
  156. // every single incoming packet; we may wish to throttle it somehow
  157. // in the future.)
  158. if (checkin_callback_ != NULL) {
  159. (*checkin_callback_)(*io_message_);
  160. }
  161. // If we don't have a DNS Lookup provider, there's no point in
  162. // continuing; we exit the coroutine permanently.
  163. if (lookup_callback_ == NULL) {
  164. socket_->close();
  165. CORO_YIELD return;
  166. }
  167. // Reset or instantiate objects that will be needed by the
  168. // DNS lookup and the write call.
  169. respbuf_.reset(new OutputBuffer(0));
  170. query_message_.reset(new Message(Message::PARSE));
  171. answer_message_.reset(new Message(Message::RENDER));
  172. // Schedule a DNS lookup, and yield. When the lookup is
  173. // finished, the coroutine will resume immediately after
  174. // this point.
  175. CORO_YIELD io_.post(AsyncLookup<TCPServer>(*this));
  176. // The 'done_' flag indicates whether we have an answer
  177. // to send back. If not, exit the coroutine permanently.
  178. if (!done_) {
  179. // TODO: should we keep the connection open for a short time
  180. // to see if new requests come in?
  181. socket_->close();
  182. CORO_YIELD return;
  183. }
  184. if (ec) {
  185. CORO_YIELD return;
  186. }
  187. // Call the DNS answer provider to render the answer into
  188. // wire format
  189. (*answer_callback_)(*io_message_, query_message_,
  190. answer_message_, respbuf_);
  191. // Set up the response, beginning with two length bytes.
  192. lenbuf.writeUint16(respbuf_->getLength());
  193. bufs[0] = buffer(lenbuf.getData(), lenbuf.getLength());
  194. bufs[1] = buffer(respbuf_->getData(), respbuf_->getLength());
  195. // Begin an asynchronous send, and then yield. When the
  196. // send completes, we will resume immediately after this point
  197. // (though we have nothing further to do, so the coroutine
  198. // will simply exit at that time).
  199. CORO_YIELD async_write(*socket_, bufs, *this);
  200. // TODO: should we keep the connection open for a short time
  201. // to see if new requests come in?
  202. socket_->close();
  203. }
  204. }
  205. /// Call the DNS lookup provider. (Expected to be called by the
  206. /// AsyncLookup<TCPServer> handler.)
  207. void
  208. TCPServer::asyncLookup() {
  209. (*lookup_callback_)(*io_message_, query_message_,
  210. answer_message_, respbuf_, this);
  211. }
  212. void TCPServer::stop() {
  213. /// we use close instead of cancel, with the same reason
  214. /// with udp server stop, refer to the udp server code
  215. acceptor_->close();
  216. // User may stop the server even when it hasn't started to
  217. // run, in that that socket_ is empty
  218. if (socket_) {
  219. socket_->close();
  220. }
  221. }
  222. /// Post this coroutine on the ASIO service queue so that it will
  223. /// resume processing where it left off. The 'done' parameter indicates
  224. /// whether there is an answer to return to the client.
  225. void
  226. TCPServer::resume(const bool done) {
  227. done_ = done;
  228. io_.post(*this);
  229. }
  230. } // namespace asiodns
  231. } // namespace isc