tcp_server.cc 8.7 KB

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