tcp_server.cc 7.5 KB

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