tcp_server.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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 <util/buffer.h>
  16. #include <asio.hpp>
  17. #include <asiolink/dummy_io_cb.h>
  18. #include <asiolink/tcp_endpoint.h>
  19. #include <asiolink/tcp_socket.h>
  20. #include <asiodns/tcp_server.h>
  21. #include <asiodns/logger.h>
  22. #include <boost/shared_array.hpp>
  23. #include <cassert>
  24. #include <unistd.h> // for some IPC/network system calls
  25. #include <netinet/in.h>
  26. #include <sys/socket.h>
  27. #include <errno.h>
  28. // Note: we intentionally avoid 'using namespace asio' to avoid conflicts with
  29. // std:: definitions in C++11.
  30. using asio::io_service;
  31. using asio::buffer;
  32. using asio::const_buffer;
  33. using asio::ip::tcp;
  34. using namespace std;
  35. using namespace isc::dns;
  36. using namespace isc::util;
  37. using namespace isc::asiolink;
  38. namespace isc {
  39. namespace asiodns {
  40. /// The following functions implement the \c TCPServer class.
  41. ///
  42. /// The constructor
  43. TCPServer::TCPServer(io_service& io_service, int fd, int af,
  44. const DNSLookup* lookup,
  45. const DNSAnswer* answer) :
  46. io_(io_service), done_(false),
  47. lookup_callback_(lookup),
  48. answer_callback_(answer)
  49. {
  50. if (af != AF_INET && af != AF_INET6) {
  51. isc_throw(InvalidParameter, "Address family must be either AF_INET "
  52. "or AF_INET6, not " << af);
  53. }
  54. LOG_DEBUG(logger, DBGLVL_TRACE_BASIC, ASIODNS_FD_ADD_TCP).arg(fd);
  55. try {
  56. acceptor_.reset(new tcp::acceptor(io_service));
  57. acceptor_->assign(af == AF_INET6 ? tcp::v6() : tcp::v4(), fd);
  58. acceptor_->listen();
  59. } catch (const std::exception& exception) {
  60. // Whatever the thing throws, it is something from ASIO and we convert
  61. // it
  62. isc_throw(IOError, exception.what());
  63. }
  64. // Set it to some value. It should be set to the right one
  65. // immediately, but set it to something non-zero just in case.
  66. tcp_recv_timeout_.reset(new size_t(5000));
  67. }
  68. namespace {
  69. // Called by the timeout_ deadline timer if the client takes too long.
  70. // If not aborted, cancels the given socket
  71. // (in which case TCPServer::operator() will be called to continue,
  72. // with an 'aborted' error code.)
  73. void doTimeOut(boost::shared_ptr<asio::ip::tcp::socket> socket,
  74. const asio::error_code& error)
  75. {
  76. if (error != asio::error::operation_aborted) {
  77. socket->cancel();
  78. }
  79. }
  80. }
  81. void
  82. TCPServer::operator()(asio::error_code ec, size_t length) {
  83. /// Because the coroutine reentry block is implemented as
  84. /// a switch statement, inline variable declarations are not
  85. /// permitted. Certain variables used below can be declared here.
  86. boost::array<const_buffer,2> bufs;
  87. OutputBuffer lenbuf(TCP_MESSAGE_LENGTHSIZE);
  88. CORO_REENTER (this) {
  89. do {
  90. /// Create a socket to listen for connections (no-throw operation)
  91. socket_.reset(new tcp::socket(acceptor_->get_io_service()));
  92. /// Wait for new connections. In the event of non-fatal error,
  93. /// try again
  94. do {
  95. CORO_YIELD acceptor_->async_accept(*socket_, *this);
  96. if (ec) {
  97. using namespace asio::error;
  98. const asio::error_code::value_type err_val = ec.value();
  99. // The following two cases can happen when this server is
  100. // stopped: operation_aborted in case it's stopped after
  101. // starting accept(). bad_descriptor in case it's stopped
  102. // even before starting. In these cases we should simply
  103. // stop handling events.
  104. if (err_val == operation_aborted ||
  105. err_val == bad_descriptor) {
  106. return;
  107. }
  108. // Other errors should generally be temporary and we should
  109. // keep waiting for new connections. We log errors that
  110. // should really be rare and would only be caused by an
  111. // internal erroneous condition (not an odd remote
  112. // behavior).
  113. if (err_val != would_block && err_val != try_again &&
  114. err_val != connection_aborted &&
  115. err_val != interrupted) {
  116. LOG_ERROR(logger, ASIODNS_TCP_ACCEPT_FAIL).
  117. arg(ec.message());
  118. }
  119. }
  120. } while (ec);
  121. /// Fork the coroutine by creating a copy of this one and
  122. /// scheduling it on the ASIO service queue. The parent
  123. /// will continue listening for DNS connections while the child
  124. /// handles the one that has just arrived.
  125. CORO_FORK io_.post(TCPServer(*this));
  126. } while (is_parent());
  127. // From this point, we'll simply return on error, which will
  128. // immediately trigger destroying this object, cleaning up all
  129. // resources including any open sockets.
  130. /// Instantiate the data buffer that will be used by the
  131. /// asynchronous read call.
  132. data_.reset(new char[MAX_LENGTH]);
  133. /// Start a timer to drop the connection if it is idle. note that
  134. // we pass a shared_ptr of the socket object so that it won't be
  135. // destroyed at least until the timeout callback (including abort)
  136. // is called.
  137. if (*tcp_recv_timeout_ > 0) {
  138. timeout_.reset(new asio::deadline_timer(io_)); // shouldn't throw
  139. timeout_->expires_from_now( // consider any exception fatal.
  140. boost::posix_time::milliseconds(*tcp_recv_timeout_));
  141. timeout_->async_wait(boost::bind(&doTimeOut, socket_,
  142. asio::placeholders::error));
  143. }
  144. /// Read the message, in two parts. First, the message length:
  145. CORO_YIELD async_read(*socket_, asio::buffer(data_.get(),
  146. TCP_MESSAGE_LENGTHSIZE), *this);
  147. if (ec) {
  148. LOG_DEBUG(logger, DBGLVL_TRACE_BASIC, ASIODNS_TCP_READLEN_FAIL).
  149. arg(ec.message());
  150. return;
  151. }
  152. /// Now read the message itself. (This is done in a different scope
  153. /// to allow inline variable declarations.)
  154. CORO_YIELD {
  155. InputBuffer dnsbuffer(data_.get(), length);
  156. const uint16_t msglen = dnsbuffer.readUint16();
  157. async_read(*socket_, asio::buffer(data_.get(), msglen), *this);
  158. }
  159. if (ec) {
  160. LOG_DEBUG(logger, DBGLVL_TRACE_BASIC, ASIODNS_TCP_READDATA_FAIL).
  161. arg(ec.message());
  162. return;
  163. }
  164. // Create an \c IOMessage object to store the query.
  165. //
  166. // (XXX: It would be good to write a factory function
  167. // that would quickly generate an IOMessage object without
  168. // all these calls to "new".)
  169. peer_.reset(new TCPEndpoint(socket_->remote_endpoint(ec)));
  170. if (ec) {
  171. LOG_DEBUG(logger, DBGLVL_TRACE_BASIC, ASIODNS_TCP_GETREMOTE_FAIL).
  172. arg(ec.message());
  173. return;
  174. }
  175. // The TCP socket class has been extended with asynchronous functions
  176. // and takes as a template parameter a completion callback class. As
  177. // TCPServer does not use these extended functions (only those defined
  178. // in the IOSocket base class) - but needs a TCPSocket to get hold of
  179. // the underlying Boost TCP socket - DummyIOCallback is used. This
  180. // provides the appropriate operator() but is otherwise functionless.
  181. iosock_.reset(new TCPSocket<DummyIOCallback>(*socket_));
  182. io_message_.reset(new IOMessage(data_.get(), length, *iosock_,
  183. *peer_));
  184. // If we don't have a DNS Lookup provider, there's no point in
  185. // continuing; we exit the coroutine permanently.
  186. if (lookup_callback_ == NULL) {
  187. return;
  188. }
  189. // Reset or instantiate objects that will be needed by the
  190. // DNS lookup and the write call.
  191. respbuf_.reset(new OutputBuffer(0));
  192. query_message_.reset(new Message(Message::PARSE));
  193. answer_message_.reset(new Message(Message::RENDER));
  194. // Schedule a DNS lookup, and yield. When the lookup is
  195. // finished, the coroutine will resume immediately after
  196. // this point. On resume, this method should be called with its
  197. // default parameter values (because of the signature of post()'s
  198. // handler), so ec shouldn't indicate any error.
  199. CORO_YIELD io_.post(AsyncLookup<TCPServer>(*this));
  200. assert(!ec);
  201. // The 'done_' flag indicates whether we have an answer
  202. // to send back. If not, exit the coroutine permanently.
  203. if (!done_) {
  204. // Explicitly close() isn't necessary for most cases. But for the
  205. // very connection, socket_ is shared with the original owner of
  206. // the server object and would stay open.
  207. // TODO: should we keep the connection open for a short time
  208. // to see if new requests come in?
  209. socket_->close(ec);
  210. if (ec) {
  211. LOG_DEBUG(logger, 0, ASIODNS_TCP_CLOSE_FAIL).arg(ec.message());
  212. }
  213. return;
  214. }
  215. // Call the DNS answer provider to render the answer into
  216. // wire format
  217. (*answer_callback_)(*io_message_, query_message_, answer_message_,
  218. respbuf_);
  219. // Set up the response, beginning with two length bytes.
  220. lenbuf.writeUint16(respbuf_->getLength());
  221. bufs[0] = buffer(lenbuf.getData(), lenbuf.getLength());
  222. bufs[1] = buffer(respbuf_->getData(), respbuf_->getLength());
  223. // Begin an asynchronous send, and then yield. When the
  224. // send completes, we will resume immediately after this point
  225. // (though we have nothing further to do, so the coroutine
  226. // will simply exit at that time).
  227. CORO_YIELD async_write(*socket_, bufs, *this);
  228. if (ec) {
  229. LOG_DEBUG(logger, DBGLVL_TRACE_BASIC, ASIODNS_TCP_WRITE_FAIL).
  230. arg(ec.message());
  231. }
  232. // All done, cancel the timeout timer. if it throws, consider it fatal.
  233. timeout_->cancel();
  234. // TODO: should we keep the connection open for a short time
  235. // to see if new requests come in?
  236. socket_->close(ec);
  237. if (ec) {
  238. // close() should be unlikely to fail, but we've seen it fail once,
  239. // so we log the event (at the lowest level of debug).
  240. LOG_DEBUG(logger, 0, ASIODNS_TCP_CLOSE_FAIL).arg(ec.message());
  241. }
  242. }
  243. }
  244. /// Call the DNS lookup provider. (Expected to be called by the
  245. /// AsyncLookup<TCPServer> handler.)
  246. void
  247. TCPServer::asyncLookup() {
  248. (*lookup_callback_)(*io_message_, query_message_,
  249. answer_message_, respbuf_, this);
  250. }
  251. void TCPServer::stop() {
  252. asio::error_code ec;
  253. /// we use close instead of cancel, with the same reason
  254. /// with udp server stop, refer to the udp server code
  255. acceptor_->close(ec);
  256. if (ec) {
  257. LOG_ERROR(logger, ASIODNS_TCP_CLOSE_ACCEPTOR_FAIL).arg(ec.message());
  258. }
  259. // User may stop the server even when it hasn't started to
  260. // run, in that case socket_ is empty
  261. if (socket_) {
  262. socket_->close(ec);
  263. if (ec) {
  264. LOG_ERROR(logger, ASIODNS_TCP_CLEANUP_CLOSE_FAIL).arg(ec.message());
  265. }
  266. }
  267. }
  268. /// Post this coroutine on the ASIO service queue so that it will
  269. /// resume processing where it left off. The 'done' parameter indicates
  270. /// whether there is an answer to return to the client.
  271. void
  272. TCPServer::resume(const bool done) {
  273. done_ = done;
  274. // post() can throw due to memory allocation failure, but as like other
  275. // cases of the entire BIND 10 implementation, we consider it fatal and
  276. // let the exception be propagated.
  277. io_.post(*this);
  278. }
  279. } // namespace asiodns
  280. } // namespace isc