dns_client.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. // Copyright (C) 2013 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 <d2/dns_client.h>
  15. #include <d2/d2_log.h>
  16. #include <dns/messagerenderer.h>
  17. #include <limits>
  18. namespace isc {
  19. namespace d2 {
  20. namespace {
  21. // OutputBuffer objects are pre-allocated before data is written to them.
  22. // This is a default number of bytes for the buffers we create within
  23. // DNSClient class.
  24. const size_t DEFAULT_BUFFER_SIZE = 128;
  25. }
  26. using namespace isc::util;
  27. using namespace isc::asiolink;
  28. using namespace isc::asiodns;
  29. using namespace isc::dns;
  30. // This class provides the implementation for the DNSClient. This allows for
  31. // the separation of the DNSClient interface from the implementation details.
  32. // Currently, implementation uses IOFetch object to handle asynchronous
  33. // communication with the DNS. This design may be revisited in the future. If
  34. // implementation is changed, the DNSClient API will remain unchanged thanks
  35. // to this separation.
  36. class DNSClientImpl : public asiodns::IOFetch::Callback {
  37. public:
  38. // A buffer holding response from a DNS.
  39. util::OutputBufferPtr in_buf_;
  40. // A caller-supplied object which will hold the parsed response from DNS.
  41. // The response object is (or descends from) isc::dns::Message and is
  42. // populated using Message::fromWire(). This method may only be called
  43. // once in the lifetime of a Message instance. Therefore, response_ is a
  44. // pointer reference thus allowing this class to replace the object
  45. // pointed to with a new Message instance each time a message is
  46. // received. This allows a single DNSClientImpl instance to be used for
  47. // multiple, sequential IOFetch calls. (@todo Trac# 3286 has been opened
  48. // against dns::Message::fromWire. Should the behavior of fromWire change
  49. // the behavior here with could be rexamined).
  50. D2UpdateMessagePtr& response_;
  51. // A caller-supplied external callback which is invoked when DNS message
  52. // exchange is complete or interrupted.
  53. DNSClient::Callback* callback_;
  54. // A Transport Layer protocol used to communicate with a DNS.
  55. DNSClient::Protocol proto_;
  56. // TSIG context used to sign outbound and verify inbound messages.
  57. dns::TSIGContextPtr tsig_context_;
  58. // Constructor and Destructor
  59. DNSClientImpl(D2UpdateMessagePtr& response_placeholder,
  60. DNSClient::Callback* callback,
  61. const DNSClient::Protocol proto);
  62. virtual ~DNSClientImpl();
  63. // This internal callback is called when the DNS update message exchange is
  64. // complete. It further invokes the external callback provided by a caller.
  65. // Before external callback is invoked, an object of the D2UpdateMessage
  66. // type, representing a response from the server is set.
  67. virtual void operator()(asiodns::IOFetch::Result result);
  68. // Starts asynchronous DNS Update using TSIG.
  69. void doUpdate(asiolink::IOService& io_service,
  70. const asiolink::IOAddress& ns_addr,
  71. const uint16_t ns_port,
  72. D2UpdateMessage& update,
  73. const unsigned int wait,
  74. const dns::TSIGKey& tsig_key);
  75. // Starts asynchronous DNS Update.
  76. void doUpdate(asiolink::IOService& io_service,
  77. const asiolink::IOAddress& ns_addr,
  78. const uint16_t ns_port,
  79. D2UpdateMessage& update,
  80. const unsigned int wait);
  81. // This function maps the IO error to the DNSClient error.
  82. DNSClient::Status getStatus(const asiodns::IOFetch::Result);
  83. };
  84. DNSClientImpl::DNSClientImpl(D2UpdateMessagePtr& response_placeholder,
  85. DNSClient::Callback* callback,
  86. const DNSClient::Protocol proto)
  87. : in_buf_(new OutputBuffer(DEFAULT_BUFFER_SIZE)),
  88. response_(response_placeholder), callback_(callback), proto_(proto) {
  89. // Response should be an empty pointer. It gets populated by the
  90. // operator() method.
  91. if (response_) {
  92. isc_throw(isc::BadValue, "Response buffer pointer should be null");
  93. }
  94. // @todo Currently we only support UDP. The support for TCP is planned for
  95. // the future release.
  96. if (proto_ == DNSClient::TCP) {
  97. isc_throw(isc::NotImplemented, "TCP is currently not supported as a"
  98. << " Transport protocol for DNS Updates; please use UDP");
  99. }
  100. // Given that we already eliminated the possibility that TCP is used, it
  101. // would be sufficient to check that (proto != DNSClient::UDP). But, once
  102. // support TCP is added the check above will disappear and the extra check
  103. // will be needed here anyway.
  104. // Note that cascaded check is used here instead of:
  105. // if (proto_ != DNSClient::TCP && proto_ != DNSClient::UDP)..
  106. // because some versions of GCC compiler complain that check above would
  107. // be always 'false' due to limited range of enumeration. In fact, it is
  108. // possible to pass out of range integral value through enum and it should
  109. // be caught here.
  110. if (proto_ != DNSClient::TCP) {
  111. if (proto_ != DNSClient::UDP) {
  112. isc_throw(isc::NotImplemented, "invalid transport protocol type '"
  113. << proto_ << "' specified for DNS Updates");
  114. }
  115. }
  116. }
  117. DNSClientImpl::~DNSClientImpl() {
  118. }
  119. void
  120. DNSClientImpl::operator()(asiodns::IOFetch::Result result) {
  121. // Get the status from IO. If no success, we just call user's callback
  122. // and pass the status code.
  123. DNSClient::Status status = getStatus(result);
  124. if (status == DNSClient::SUCCESS) {
  125. // Allocate a new response message. (Note that Message::fromWire
  126. // may only be run once per message, so we need to start fresh
  127. // each time.)
  128. response_.reset(new D2UpdateMessage(D2UpdateMessage::INBOUND));
  129. // Server's response may be corrupted. In such case, fromWire will
  130. // throw an exception. We want to catch this exception to return
  131. // appropriate status code to the caller and log this event.
  132. try {
  133. response_->fromWire(in_buf_->getData(), in_buf_->getLength(),
  134. tsig_context_.get());
  135. } catch (const isc::Exception& ex) {
  136. status = DNSClient::INVALID_RESPONSE;
  137. LOG_DEBUG(dctl_logger, DBGLVL_TRACE_DETAIL,
  138. DHCP_DDNS_INVALID_RESPONSE).arg(ex.what());
  139. }
  140. if (tsig_context_) {
  141. // Context is a one-shot deal, get rid of it.
  142. tsig_context_.reset();
  143. }
  144. }
  145. // Once we are done with internal business, let's call a callback supplied
  146. // by a caller.
  147. if (callback_ != NULL) {
  148. (*callback_)(status);
  149. }
  150. }
  151. DNSClient::Status
  152. DNSClientImpl::getStatus(const asiodns::IOFetch::Result result) {
  153. switch (result) {
  154. case IOFetch::SUCCESS:
  155. return (DNSClient::SUCCESS);
  156. case IOFetch::TIME_OUT:
  157. return (DNSClient::TIMEOUT);
  158. case IOFetch::STOPPED:
  159. return (DNSClient::IO_STOPPED);
  160. default:
  161. ;
  162. }
  163. return (DNSClient::OTHER);
  164. }
  165. void
  166. DNSClientImpl::doUpdate(asiolink::IOService& io_service,
  167. const IOAddress& ns_addr,
  168. const uint16_t ns_port,
  169. D2UpdateMessage& update,
  170. const unsigned int wait,
  171. const dns::TSIGKey& tsig_key) {
  172. tsig_context_.reset(new TSIGContext(tsig_key));
  173. doUpdate(io_service, ns_addr, ns_port, update, wait);
  174. }
  175. void
  176. DNSClientImpl::doUpdate(asiolink::IOService& io_service,
  177. const IOAddress& ns_addr,
  178. const uint16_t ns_port,
  179. D2UpdateMessage& update,
  180. const unsigned int wait) {
  181. // The underlying implementation which we use to send DNS Updates uses
  182. // signed integers for timeout. If we want to avoid overflows we need to
  183. // respect this limitation here.
  184. if (wait > DNSClient::getMaxTimeout()) {
  185. isc_throw(isc::BadValue, "A timeout value for DNS Update request must"
  186. " not exceed " << DNSClient::getMaxTimeout()
  187. << ". Provided timeout value is '" << wait << "'");
  188. }
  189. // A renderer is used by the toWire function which creates the on-wire data
  190. // from the DNS Update message. A renderer has its internal buffer where it
  191. // renders data by default. However, this buffer can't be directly accessed.
  192. // Fortunately, the renderer's API accepts user-supplied buffers. So, let's
  193. // create our own buffer and pass it to the renderer so as the message is
  194. // rendered to this buffer. Finally, we pass this buffer to IOFetch.
  195. dns::MessageRenderer renderer;
  196. OutputBufferPtr msg_buf(new OutputBuffer(DEFAULT_BUFFER_SIZE));
  197. renderer.setBuffer(msg_buf.get());
  198. // Render DNS Update message. This may throw a bunch of exceptions if
  199. // invalid message object is given.
  200. update.toWire(renderer, tsig_context_.get());
  201. // IOFetch has all the mechanisms that we need to perform asynchronous
  202. // communication with the DNS server. The last but one argument points to
  203. // this object as a completion callback for the message exchange. As a
  204. // result operator()(Status) will be called.
  205. // Timeout value is explicitly cast to the int type to avoid warnings about
  206. // overflows when doing implicit cast. It should have been checked by the
  207. // caller that the unsigned timeout value will fit into int.
  208. IOFetch io_fetch(IOFetch::UDP, io_service, msg_buf, ns_addr, ns_port,
  209. in_buf_, this, static_cast<int>(wait));
  210. // Post the task to the task queue in the IO service. Caller will actually
  211. // run these tasks by executing IOService::run.
  212. io_service.post(io_fetch);
  213. }
  214. DNSClient::DNSClient(D2UpdateMessagePtr& response_placeholder,
  215. Callback* callback, const DNSClient::Protocol proto)
  216. : impl_(new DNSClientImpl(response_placeholder, callback, proto)) {
  217. }
  218. DNSClient::~DNSClient() {
  219. delete (impl_);
  220. }
  221. unsigned int
  222. DNSClient::getMaxTimeout() {
  223. static const unsigned int max_timeout = std::numeric_limits<int>::max();
  224. return (max_timeout);
  225. }
  226. void
  227. DNSClient::doUpdate(asiolink::IOService& io_service,
  228. const IOAddress& ns_addr,
  229. const uint16_t ns_port,
  230. D2UpdateMessage& update,
  231. const unsigned int wait,
  232. const dns::TSIGKey& tsig_key) {
  233. impl_->doUpdate(io_service, ns_addr, ns_port, update, wait, tsig_key);
  234. }
  235. void
  236. DNSClient::doUpdate(asiolink::IOService& io_service,
  237. const IOAddress& ns_addr,
  238. const uint16_t ns_port,
  239. D2UpdateMessage& update,
  240. const unsigned int wait) {
  241. impl_->doUpdate(io_service, ns_addr, ns_port, update, wait);
  242. }
  243. } // namespace d2
  244. } // namespace isc