tcp_server.cc 9.4 KB

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