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