sync_udp_server.cc 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. // Copyright (C) 2012 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 <asio.hpp>
  16. #include <asio/error.hpp>
  17. #include "sync_udp_server.h"
  18. #include "logger.h"
  19. #include <asiolink/dummy_io_cb.h>
  20. #include <asiolink/udp_endpoint.h>
  21. #include <asiolink/udp_socket.h>
  22. #include <boost/bind.hpp>
  23. #include <netinet/in.h>
  24. #include <sys/socket.h>
  25. #include <unistd.h> // for some IPC/network system calls
  26. #include <errno.h>
  27. using namespace std;
  28. using namespace isc::asiolink;
  29. namespace isc {
  30. namespace asiodns {
  31. SyncUDPServer::SyncUDPServer(asio::io_service& io_service,
  32. const asio::ip::address& addr,
  33. const uint16_t port,
  34. asiolink::SimpleCallback* checkin,
  35. DNSLookup* lookup, DNSAnswer* answer) :
  36. output_buffer_(new isc::util::OutputBuffer(0)),
  37. query_(new isc::dns::Message(isc::dns::Message::PARSE)),
  38. answer_(new isc::dns::Message(isc::dns::Message::RENDER)),
  39. io_(io_service), checkin_callback_(checkin), lookup_callback_(lookup),
  40. answer_callback_(answer), stopped_(false)
  41. {
  42. // We must use different instantiations for v4 and v6;
  43. // otherwise ASIO will bind to both
  44. asio::ip::udp proto = addr.is_v4() ? asio::ip::udp::v4() :
  45. asio::ip::udp::v6();
  46. socket_.reset(new asio::ip::udp::socket(io_service, proto));
  47. socket_->set_option(asio::socket_base::reuse_address(true));
  48. if (addr.is_v6()) {
  49. socket_->set_option(asio::ip::v6_only(true));
  50. }
  51. socket_->bind(asio::ip::udp::endpoint(addr, port));
  52. }
  53. SyncUDPServer::SyncUDPServer(asio::io_service& io_service, const int fd,
  54. const int af, asiolink::SimpleCallback* checkin,
  55. DNSLookup* lookup, DNSAnswer* answer) :
  56. output_buffer_(new isc::util::OutputBuffer(0)),
  57. query_(new isc::dns::Message(isc::dns::Message::PARSE)),
  58. answer_(new isc::dns::Message(isc::dns::Message::RENDER)),
  59. io_(io_service), checkin_callback_(checkin), lookup_callback_(lookup),
  60. answer_callback_(answer), stopped_(false)
  61. {
  62. if (af != AF_INET && af != AF_INET6) {
  63. isc_throw(InvalidParameter, "Address family must be either AF_INET "
  64. "or AF_INET6, not " << af);
  65. }
  66. LOG_DEBUG(logger, DBGLVL_TRACE_BASIC, ASIODNS_FD_ADD_UDP).arg(fd);
  67. try {
  68. socket_.reset(new asio::ip::udp::socket(io_service));
  69. socket_->assign(af == AF_INET6 ? asio::ip::udp::v6() :
  70. asio::ip::udp::v4(), fd);
  71. } catch (const std::exception& exception) {
  72. // Whatever the thing throws, it is something from ASIO and we
  73. // convert it
  74. isc_throw(IOError, exception.what());
  75. }
  76. }
  77. void
  78. SyncUDPServer::scheduleRead() {
  79. socket_->async_receive_from(asio::buffer(data_, MAX_LENGTH), sender_,
  80. boost::bind(&SyncUDPServer::handleRead, this,
  81. _1, _2));
  82. }
  83. void
  84. SyncUDPServer::handleRead(const asio::error_code& ec, const size_t length) {
  85. // Abort on fatal errors
  86. if (ec) {
  87. using namespace asio::error;
  88. if (ec.value() != would_block && ec.value() != try_again &&
  89. ec.value() != interrupted) {
  90. return;
  91. }
  92. }
  93. // Some kind of interrupt, spurious wakeup, or like that. Just try reading
  94. // again.
  95. if (ec || length == 0) {
  96. scheduleRead();
  97. return;
  98. }
  99. // OK, we have a real packet of data. Let's dig into it!
  100. // XXX: This is taken (and ported) from UDPSocket class. What the hell does
  101. // it really mean?
  102. // The UDP socket class has been extended with asynchronous functions
  103. // and takes as a template parameter a completion callback class. As
  104. // UDPServer does not use these extended functions (only those defined
  105. // in the IOSocket base class) - but needs a UDPSocket to get hold of
  106. // the underlying Boost UDP socket - DummyIOCallback is used. This
  107. // provides the appropriate operator() but is otherwise functionless.
  108. UDPSocket<DummyIOCallback> socket(*socket_);
  109. UDPEndpoint endpoint(sender_);
  110. IOMessage message(data_, length, socket, endpoint);
  111. if (checkin_callback_ != NULL) {
  112. (*checkin_callback_)(message);
  113. if (stopped_) {
  114. return;
  115. }
  116. }
  117. // If we don't have a DNS Lookup provider, there's no point in
  118. // continuing; we exit the coroutine permanently.
  119. if (lookup_callback_ == NULL) {
  120. scheduleRead();
  121. return;
  122. }
  123. // Make sure the buffers are fresh
  124. output_buffer_->clear();
  125. query_->clear(isc::dns::Message::PARSE);
  126. answer_->clear(isc::dns::Message::RENDER);
  127. // Mark that we don't have an answer yet.
  128. done_ = false;
  129. resume_called_ = false;
  130. // Call the actual lookup
  131. (*lookup_callback_)(message, query_, answer_, output_buffer_, this);
  132. if (!resume_called_) {
  133. isc_throw(isc::Unexpected,
  134. "No resume called from the lookup callback");
  135. }
  136. if (stopped_) {
  137. return;
  138. }
  139. if (done_) {
  140. // Good, there's an answer.
  141. // Call the answer callback to render it.
  142. (*answer_callback_)(message, query_, answer_, output_buffer_);
  143. if (stopped_) {
  144. return;
  145. }
  146. socket_->send_to(asio::buffer(output_buffer_->getData(),
  147. output_buffer_->getLength()),
  148. sender_);
  149. }
  150. // And schedule handling another socket.
  151. scheduleRead();
  152. }
  153. void
  154. SyncUDPServer::operator()(asio::error_code, size_t) {
  155. // To start the server, we just schedule reading of data when they
  156. // arrive.
  157. scheduleRead();
  158. }
  159. /// Stop the UDPServer
  160. void
  161. SyncUDPServer::stop() {
  162. /// Using close instead of cancel, because cancel
  163. /// will only cancel the asynchornized event already submitted
  164. /// to io service, the events post to io service after
  165. /// cancel still can be scheduled by io service, if
  166. /// the socket is cloesed, all the asynchronized event
  167. /// for it won't be scheduled by io service not matter it is
  168. /// submit to io serice before or after close call. And we will
  169. //. get bad_descriptor error
  170. socket_->close();
  171. stopped_ = true;
  172. }
  173. /// Post this coroutine on the ASIO service queue so that it will
  174. /// resume processing where it left off. The 'done' parameter indicates
  175. /// whether there is an answer to return to the client.
  176. void
  177. SyncUDPServer::resume(const bool done) {
  178. resume_called_ = true;
  179. done_ = done;
  180. }
  181. bool
  182. SyncUDPServer::hasAnswer() {
  183. return (done_);
  184. }
  185. } // namespace asiodns
  186. } // namespace isc