tcp_server.cc 10 KB

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