BIND 10 trac495, updated. cb13c22e8b2464d903d2254dec4d46c1103cf5ea [trac495] remove now unused if gcc -Wno-unused
BIND 10 source code commits
bind10-changes at lists.isc.org
Wed Mar 2 13:51:04 UTC 2011
The branch, trac495 has been updated
via cb13c22e8b2464d903d2254dec4d46c1103cf5ea (commit)
via 68c33a7725a2e41dab53b4d74e2aedec79090380 (commit)
via 860be372d776c05c9535790257812dbde1b9f74f (commit)
via b73ea473019bceeab7aab78ddc5d1c4a7710a8bd (commit)
via cac094e7e14a483bbf84394adf55a86d70097188 (commit)
from 38f2d6e49c7f693c55e5d27b3b247a167895826c (commit)
Those revisions listed above that are new to this repository have
not appeared on any other notification email; so we list those
revisions in full, below.
- Log -----------------------------------------------------------------
commit cb13c22e8b2464d903d2254dec4d46c1103cf5ea
Author: Jelte Jansen <jelte at isc.org>
Date: Wed Mar 2 14:50:13 2011 +0100
[trac495] remove now unused if gcc -Wno-unused
previous commit changed the methods that had unused parameters (rather than disabling the check in multiple places)
commit 68c33a7725a2e41dab53b4d74e2aedec79090380
Author: Jelte Jansen <jelte at isc.org>
Date: Wed Mar 2 14:48:39 2011 +0100
[trac495] more recursive_query to lib/resolve
commit 860be372d776c05c9535790257812dbde1b9f74f
Author: Jelte Jansen <jelte at isc.org>
Date: Wed Mar 2 11:38:21 2011 +0100
[trac495] update some tests
commit b73ea473019bceeab7aab78ddc5d1c4a7710a8bd
Author: Jelte Jansen <jelte at isc.org>
Date: Wed Mar 2 11:06:52 2011 +0100
[trac495] added makeSERVFAIL for errors, improved timeout handling
almost good now, it should not crash anymore, however it can happen that a runningquery runs a bit longer than necessary
commit cac094e7e14a483bbf84394adf55a86d70097188
Author: Jelte Jansen <jelte at isc.org>
Date: Tue Mar 1 17:50:39 2011 +0100
[trac495] added NSAS::cancel(callback), and tweaked the timeout code
It still fails if lookup timeout is smaller than client timeout though
-----------------------------------------------------------------------
Summary of changes:
ext/asio/asio/detail/epoll_reactor.hpp | 2 +-
src/bin/resolver/Makefile.am | 1 +
src/bin/resolver/resolver.cc | 2 +
src/bin/resolver/tests/Makefile.am | 1 +
src/lib/Makefile.am | 2 +-
src/lib/asiolink/Makefile.am | 7 --
src/lib/asiolink/asiolink.h | 1 -
src/lib/asiolink/tcp_socket.h | 8 +-
src/lib/asiolink/tests/Makefile.am | 3 -
src/lib/nsas/nameserver_address_store.cc | 13 +++
src/lib/nsas/nameserver_address_store.h | 7 ++
src/lib/nsas/zone_entry.cc | 13 +++
src/lib/nsas/zone_entry.h | 9 ++
src/lib/resolve/Makefile.am | 1 +
src/lib/{asiolink => resolve}/recursive_query.cc | 88 ++++++++++++++++----
src/lib/{asiolink => resolve}/recursive_query.h | 0
src/lib/resolve/tests/Makefile.am | 6 ++
.../tests/recursive_query_unittest.cc | 21 ++---
18 files changed, 141 insertions(+), 44 deletions(-)
rename src/lib/{asiolink => resolve}/recursive_query.cc (90%)
rename src/lib/{asiolink => resolve}/recursive_query.h (100%)
rename src/lib/{asiolink => resolve}/tests/recursive_query_unittest.cc (98%)
-----------------------------------------------------------------------
diff --git a/ext/asio/asio/detail/epoll_reactor.hpp b/ext/asio/asio/detail/epoll_reactor.hpp
index 6367398..0a1eac0 100644
--- a/ext/asio/asio/detail/epoll_reactor.hpp
+++ b/ext/asio/asio/detail/epoll_reactor.hpp
@@ -207,7 +207,7 @@ public:
// Cancel all operations associated with the given descriptor. The
// handlers associated with the descriptor will be invoked with the
// operation_aborted error.
- void cancel_ops(socket_type descriptor, per_descriptor_data& descriptor_data)
+ void cancel_ops(socket_type, per_descriptor_data& descriptor_data)
{
mutex::scoped_lock descriptor_lock(descriptor_data->mutex_);
diff --git a/src/bin/resolver/Makefile.am b/src/bin/resolver/Makefile.am
index 608e1a9..62155eb 100644
--- a/src/bin/resolver/Makefile.am
+++ b/src/bin/resolver/Makefile.am
@@ -50,6 +50,7 @@ b10_resolver_LDADD += $(top_builddir)/src/lib/xfr/libxfr.la
b10_resolver_LDADD += $(top_builddir)/src/lib/log/liblog.la
b10_resolver_LDADD += $(top_builddir)/src/lib/cache/libcache.la
b10_resolver_LDADD += $(top_builddir)/src/lib/nsas/libnsas.la
+b10_resolver_LDADD += $(top_builddir)/src/lib/resolve/libresolve.la
b10_resolver_LDADD += $(top_builddir)/src/bin/auth/change_user.o
b10_resolver_LDFLAGS = -pthread
diff --git a/src/bin/resolver/resolver.cc b/src/bin/resolver/resolver.cc
index 8f24441..af93515 100644
--- a/src/bin/resolver/resolver.cc
+++ b/src/bin/resolver/resolver.cc
@@ -40,6 +40,8 @@
#include <dns/message.h>
#include <dns/messagerenderer.h>
+#include <resolve/recursive_query.h>
+
#include <log/dummylog.h>
#include <resolver/resolver.h>
diff --git a/src/bin/resolver/tests/Makefile.am b/src/bin/resolver/tests/Makefile.am
index 3dc6b3b..1b0184c 100644
--- a/src/bin/resolver/tests/Makefile.am
+++ b/src/bin/resolver/tests/Makefile.am
@@ -39,6 +39,7 @@ run_unittests_LDADD += $(top_builddir)/src/lib/xfr/libxfr.la
run_unittests_LDADD += $(top_builddir)/src/lib/log/liblog.la
run_unittests_LDADD += $(top_builddir)/src/lib/cache/libcache.la
run_unittests_LDADD += $(top_builddir)/src/lib/nsas/libnsas.la
+run_unittests_LDADD += $(top_builddir)/src/lib/resolve/libresolve.la
# Note the ordering matters: -Wno-... must follow -Wextra (defined in
# B10_CXXFLAGS
diff --git a/src/lib/Makefile.am b/src/lib/Makefile.am
index d5486a0..5f9c4a0 100644
--- a/src/lib/Makefile.am
+++ b/src/lib/Makefile.am
@@ -1,2 +1,2 @@
SUBDIRS = exceptions dns cc config datasrc python xfr bench log \
- resolve nsas cache asiolink testutils
+ asiolink nsas cache resolve testutils
diff --git a/src/lib/asiolink/Makefile.am b/src/lib/asiolink/Makefile.am
index b3968f0..005cf96 100644
--- a/src/lib/asiolink/Makefile.am
+++ b/src/lib/asiolink/Makefile.am
@@ -27,7 +27,6 @@ libasiolink_la_SOURCES += io_fetch.h io_fetch.cc
libasiolink_la_SOURCES += io_message.h
libasiolink_la_SOURCES += io_service.h io_service.cc
libasiolink_la_SOURCES += io_socket.h io_socket.cc
-libasiolink_la_SOURCES += recursive_query.h recursive_query.cc
libasiolink_la_SOURCES += simple_callback.h
libasiolink_la_SOURCES += tcp_endpoint.h
libasiolink_la_SOURCES += tcp_server.h tcp_server.cc
@@ -38,15 +37,9 @@ libasiolink_la_SOURCES += udp_socket.h
# Note: the ordering matters: -Wno-... must follow -Wextra (defined in
# B10_CXXFLAGS)
libasiolink_la_CXXFLAGS = $(AM_CXXFLAGS)
-if USE_GXX
-libasiolink_la_CXXFLAGS += -Wno-unused-parameter
-endif
if USE_CLANGPP
# Same for clang++, but we need to turn off -Werror completely.
libasiolink_la_CXXFLAGS += -Wno-error
endif
libasiolink_la_CPPFLAGS = $(AM_CPPFLAGS)
libasiolink_la_LIBADD = $(top_builddir)/src/lib/log/liblog.la
-libasiolink_la_LIBADD += $(top_builddir)/src/lib/resolve/libresolve.la
-libasiolink_la_LIBADD += $(top_builddir)/src/lib/cache/libcache.la
-libasiolink_la_LIBADD += $(top_builddir)/src/lib/nsas/libnsas.la
diff --git a/src/lib/asiolink/asiolink.h b/src/lib/asiolink/asiolink.h
index 03951ae..c0b36ce 100644
--- a/src/lib/asiolink/asiolink.h
+++ b/src/lib/asiolink/asiolink.h
@@ -25,7 +25,6 @@
#include <asiolink/dns_lookup.h>
#include <asiolink/dns_answer.h>
#include <asiolink/simple_callback.h>
-#include <asiolink/recursive_query.h>
#include <asiolink/interval_timer.h>
#include <asiolink/io_address.h>
diff --git a/src/lib/asiolink/recursive_query.cc b/src/lib/asiolink/recursive_query.cc
deleted file mode 100644
index 267fcb6..0000000
--- a/src/lib/asiolink/recursive_query.cc
+++ /dev/null
@@ -1,628 +0,0 @@
-// Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <netinet/in.h>
-#include <stdlib.h>
-#include <sys/socket.h>
-#include <unistd.h> // for some IPC/network system calls
-
-#include <boost/lexical_cast.hpp>
-#include <boost/bind.hpp>
-
-#include <config.h>
-
-#include <log/dummylog.h>
-
-#include <dns/question.h>
-#include <dns/message.h>
-#include <dns/opcode.h>
-
-#include <resolve/resolve.h>
-#include <cache/resolver_cache.h>
-#include <nsas/address_request_callback.h>
-#include <nsas/nameserver_address.h>
-
-#include <asio.hpp>
-#include <asiolink/dns_service.h>
-#include <asiolink/io_fetch.h>
-#include <asiolink/io_service.h>
-#include <asiolink/recursive_query.h>
-
-using isc::log::dlog;
-using namespace isc::dns;
-
-namespace asiolink {
-
-typedef std::vector<std::pair<std::string, uint16_t> > AddressVector;
-
-// Here we do not use the typedef above, as the SunStudio compiler
-// mishandles this in its name mangling, and wouldn't compile.
-// We can probably use a typedef, but need to move it to a central
-// location and use it consistently.
-RecursiveQuery::RecursiveQuery(DNSService& dns_service,
- isc::nsas::NameserverAddressStore& nsas,
- isc::cache::ResolverCache& cache,
- const std::vector<std::pair<std::string, uint16_t> >& upstream,
- const std::vector<std::pair<std::string, uint16_t> >& upstream_root,
- int query_timeout, int client_timeout, int lookup_timeout,
- unsigned retries) :
- dns_service_(dns_service),
- nsas_(nsas), cache_(cache),
- upstream_(new AddressVector(upstream)),
- upstream_root_(new AddressVector(upstream_root)),
- query_timeout_(query_timeout), client_timeout_(client_timeout),
- lookup_timeout_(lookup_timeout), retries_(retries)
-{
-}
-
-namespace {
-
-typedef std::pair<std::string, uint16_t> addr_t;
-
-/*
- * This is a query in progress. When a new query is made, this one holds
- * the context information about it, like how many times we are allowed
- * to retry on failure, what to do when we succeed, etc.
- *
- * Used by RecursiveQuery::sendQuery.
- */
-class RunningQuery : public IOFetch::Callback {
-
-class ResolverNSASCallback : public isc::nsas::AddressRequestCallback {
-public:
- ResolverNSASCallback(RunningQuery* rq) : rq_(rq) {}
-
- void success(const isc::nsas::NameserverAddress& address) {
- dlog("Found a nameserver, sending query to " + address.getAddress().toText());
- rq_->sendTo(address);
- }
-
- void unreachable() {
- dlog("Nameservers unreachable");
- // Drop query or send servfail?
- rq_->stop(false);
- }
-
-private:
- RunningQuery* rq_;
-};
-
-
-private:
- // The io service to handle async calls
- IOService& io_;
-
- // Info for (re)sending the query (the question and destination)
- Question question_;
-
- // This is where we build and store our final answer
- MessagePtr answer_message_;
-
- // currently we use upstream as the current list of NS records
- // we should differentiate between forwarding and resolving
- boost::shared_ptr<AddressVector> upstream_;
-
- // Buffer to store the result.
- OutputBufferPtr buffer_;
-
- // Server to notify when we succeed or fail
- //shared_ptr<DNSServer> server_;
- isc::resolve::ResolverInterface::CallbackPtr resolvercallback_;
-
- // To prevent both unreasonably long cname chains and cname loops,
- // we simply keep a counter of the number of CNAMEs we have
- // followed so far (and error if it exceeds RESOLVER_MAX_CNAME_CHAIN
- // from lib/resolve/response_classifier.h)
- unsigned cname_count_;
-
- /*
- * TODO Do something more clever with timeouts. In the long term, some
- * computation of average RTT, increase with each retry, etc.
- */
- // Timeout information
- int query_timeout_;
- unsigned retries_;
-
- // normal query state
-
- // Update the question that will be sent to the server
- void setQuestion(const Question& new_question) {
- question_ = new_question;
- }
-
- // TODO: replace by our wrapper
- asio::deadline_timer client_timer;
- asio::deadline_timer lookup_timer;
-
- size_t queries_out_;
-
- // If we timed out ourselves (lookup timeout), stop issuing queries
- bool done_;
-
- // If we have a client timeout, we send back an answer, but don't
- // stop. We use this variable to make sure we don't send another
- // answer if we do find one later (or if we have a lookup_timeout)
- bool answer_sent_;
-
- // Reference to our NSAS
- isc::nsas::NameserverAddressStore& nsas_;
-
- // Reference to our cache
- isc::cache::ResolverCache& cache_;
-
- // the 'current' nameserver we have a query out to
- std::string cur_zone_;
- boost::shared_ptr<ResolverNSASCallback> nsas_callback_;
- isc::nsas::NameserverAddress current_ns_address;
- struct timeval current_ns_qsent_time;
-
- // perform a single lookup; first we check the cache to see
- // if we have a response for our query stored already. if
- // so, call handlerecursiveresponse(), if not, we call send()
- void doLookup() {
- dlog("doLookup: try cache");
- Message cached_message(Message::RENDER);
- isc::resolve::initResponseMessage(question_, cached_message);
- if (cache_.lookup(question_.getName(), question_.getType(),
- question_.getClass(), cached_message)) {
- dlog("Message found in cache, returning that");
- if (handleRecursiveAnswer(cached_message)) {
- stop(true);
- }
- } else {
- cur_zone_ = ".";
- send();
- }
-
- }
-
- void sendTo(const isc::nsas::NameserverAddress& address) {
- // We need to keep track of the Address, so that we can update
- // the RTT
- current_ns_address = address;
- gettimeofday(¤t_ns_qsent_time, NULL);
- ++queries_out_;
- IOFetch query(IPPROTO_UDP, io_, question_,
- current_ns_address.getAddress(),
- 53, buffer_, this,
- query_timeout_);
- io_.get_io_service().post(query);
- }
-
- void send() {
- // If are in forwarder mode, send it to a random
- // forwarder. If not, ask the NSAS for an address
- const int uc = upstream_->size();
- if (uc > 0) {
- int serverIndex = rand() % uc;
- dlog("Sending upstream query (" + question_.toText() +
- ") to " + upstream_->at(serverIndex).first);
- ++queries_out_;
- IOFetch query(IPPROTO_UDP, io_, question_,
- upstream_->at(serverIndex).first,
- upstream_->at(serverIndex).second, buffer_, this,
- query_timeout_);
- io_.get_io_service().post(query);
- } else {
- // Ask the NSAS for an address for the current zone,
- // the callback will call the actual sendTo()
- dlog("Look up nameserver for " + cur_zone_ + " in NSAS");
- nsas_.lookup(cur_zone_, question_.getClass(), nsas_callback_);
- }
- }
-
- // This function is called by operator() if there is an actual
- // answer from a server and we are in recursive mode
- // depending on the contents, we go on recursing or return
- //
- // Note that the footprint may change as this function may
- // need to append data to the answer we are building later.
- //
- // returns true if we are done (either we have an answer or an
- // error message)
- // returns false if we are not done
- bool handleRecursiveAnswer(const Message& incoming) {
- dlog("Handle response");
- // In case we get a CNAME, we store the target
- // here (classify() will set it when it walks through
- // the cname chain to verify it).
- Name cname_target(question_.getName());
-
- isc::resolve::ResponseClassifier::Category category =
- isc::resolve::ResponseClassifier::classify(
- question_, incoming, cname_target, cname_count_, true);
-
- bool found_ns_address = false;
-
- // If the packet is OK, store it in the cache
- //if (!isc::resolve::ResponseClassifier::error(category)) {
- // cache_.update(incoming);
- //}
-
- switch (category) {
- case isc::resolve::ResponseClassifier::ANSWER:
- case isc::resolve::ResponseClassifier::ANSWERCNAME:
- // Done. copy and return.
- dlog("Response is an answer");
- cache_.update(incoming);
- isc::resolve::copyResponseMessage(incoming, answer_message_);
- return true;
- break;
- case isc::resolve::ResponseClassifier::CNAME:
- dlog("Response is CNAME!");
- cache_.update(incoming);
- // (unfinished) CNAME. We set our question_ to the CNAME
- // target, then start over at the beginning (for now, that
- // is, we reset our 'current servers' to the root servers).
- if (cname_count_ >= RESOLVER_MAX_CNAME_CHAIN) {
- // just give up
- dlog("CNAME chain too long");
- isc::resolve::makeErrorMessage(answer_message_,
- Rcode::SERVFAIL());
- return true;
- }
-
- answer_message_->appendSection(Message::SECTION_ANSWER,
- incoming);
-
- question_ = Question(cname_target, question_.getClass(),
- question_.getType());
-
- dlog("Following CNAME chain to " + question_.toText());
- doLookup();
- return false;
- break;
- case isc::resolve::ResponseClassifier::NXDOMAIN:
- case isc::resolve::ResponseClassifier::NXRRSET:
- dlog("Response is NXDOMAIN or NXRRSET");
- // NXDOMAIN, just copy and return.
- // no negcache yet
- //cache_.update(incoming);
- dlog(incoming.toText());
- isc::resolve::copyResponseMessage(incoming, answer_message_);
- return true;
- break;
- case isc::resolve::ResponseClassifier::REFERRAL:
- dlog("Response is referral");
- cache_.update(incoming);
- // Referral. For now we just take the first glue address
- // we find and continue with that
-
- // auth section should have at least one RRset
- // and one of them should be an NS (otherwise
- // classifier should have error'd)
- // TODO: should we check if it really is subzone?
- for (RRsetIterator rrsi = incoming.beginSection(Message::SECTION_AUTHORITY);
- rrsi != incoming.endSection(Message::SECTION_AUTHORITY) && !found_ns_address;
- ++rrsi) {
- ConstRRsetPtr rrs = *rrsi;
- if (rrs->getType() == RRType::NS()) {
- cur_zone_ = rrs->getName().toText();
- dlog("Referred to zone " + cur_zone_);
- found_ns_address = true;
- break;
- }
- }
-
- if (found_ns_address) {
- // next resolver round
- // we do NOT use doLookup() here, but send() (i.e. we
- // skip the cache), since if we had the final answer
- // instead of a delegation cached, we would have been
- // there by now.
- send();
- return false;
- } else {
- dlog("No NS RRset in referral?");
- // TODO this will result in answering with the delegation. oh well
- isc::resolve::copyResponseMessage(incoming, answer_message_);
- return true;
- }
- break;
- case isc::resolve::ResponseClassifier::EMPTY:
- case isc::resolve::ResponseClassifier::EXTRADATA:
- case isc::resolve::ResponseClassifier::INVNAMCLASS:
- case isc::resolve::ResponseClassifier::INVTYPE:
- case isc::resolve::ResponseClassifier::MISMATQUEST:
- case isc::resolve::ResponseClassifier::MULTICLASS:
- case isc::resolve::ResponseClassifier::NOTONEQUEST:
- case isc::resolve::ResponseClassifier::NOTRESPONSE:
- case isc::resolve::ResponseClassifier::NOTSINGLE:
- case isc::resolve::ResponseClassifier::OPCODE:
- case isc::resolve::ResponseClassifier::RCODE:
- case isc::resolve::ResponseClassifier::TRUNCATED:
- dlog("Error in response, returning SERVFAIL");
- // Should we try a different server rather than SERVFAIL?
- isc::resolve::makeErrorMessage(answer_message_,
- Rcode::SERVFAIL());
- return true;
- break;
- }
- // should not be reached. assert here?
- dlog("[FATAL] unreachable code");
- return true;
- }
-
-public:
- RunningQuery(IOService& io,
- const Question& question,
- MessagePtr answer_message,
- boost::shared_ptr<AddressVector> upstream,
- OutputBufferPtr buffer,
- isc::resolve::ResolverInterface::CallbackPtr cb,
- int query_timeout, int client_timeout, int lookup_timeout,
- unsigned retries,
- isc::nsas::NameserverAddressStore& nsas,
- isc::cache::ResolverCache& cache) :
- io_(io),
- question_(question),
- answer_message_(answer_message),
- upstream_(upstream),
- buffer_(buffer),
- resolvercallback_(cb),
- cname_count_(0),
- query_timeout_(query_timeout),
- retries_(retries),
- client_timer(io.get_io_service()),
- lookup_timer(io.get_io_service()),
- queries_out_(0),
- done_(false),
- answer_sent_(false),
- nsas_(nsas),
- cache_(cache),
- nsas_callback_(boost::shared_ptr<ResolverNSASCallback>(
- new ResolverNSASCallback(this)))
- {
- // Setup the timer to stop trying (lookup_timeout)
- if (lookup_timeout >= 0) {
- lookup_timer.expires_from_now(
- boost::posix_time::milliseconds(lookup_timeout));
- lookup_timer.async_wait(boost::bind(&RunningQuery::stop, this, false));
- }
-
- // Setup the timer to send an answer (client_timeout)
- if (client_timeout >= 0) {
- client_timer.expires_from_now(
- boost::posix_time::milliseconds(client_timeout));
- client_timer.async_wait(boost::bind(&RunningQuery::clientTimeout, this));
- }
-
- doLookup();
- }
-
- virtual void clientTimeout() {
- // Return a SERVFAIL, but do not stop until
- // we have an answer or timeout ourselves
- isc::resolve::makeErrorMessage(answer_message_,
- Rcode::SERVFAIL());
- if (!answer_sent_) {
- answer_sent_ = true;
- resolvercallback_->success(answer_message_);
- }
- }
-
- virtual void stop(bool resume) {
- // if we cancel our timers, we will still get an event for
- // that, so we cannot delete ourselves just yet (those events
- // would be bound to a deleted object)
- // cancel them one by one, both cancels should get us back
- // here again.
- // same goes if we have an outstanding query (can't delete
- // until that one comes back to us)
- done_ = true;
- if (resume && !answer_sent_) {
- answer_sent_ = true;
-
- // There are two types of messages we could store in the
- // cache;
- // 1. answers to our fetches from authoritative servers,
- // exactly as we receive them, and
- // 2. answers to queries we received from clients, which
- // have received additional processing (following CNAME
- // chains, for instance)
- //
- // Doing only the first would mean we would have to re-do
- // processing when we get data from our cache, and doing
- // only the second would miss out on the side-effect of
- // having nameserver data in our cache.
- //
- // So right now we do both. Since the cache (currently)
- // stores Messages on their question section only, this
- // does mean that we overwrite the messages we stored in
- // the previous iteration if we are following a delegation.
- cache_.update(*answer_message_);
-
- resolvercallback_->success(answer_message_);
- } else {
- resolvercallback_->failure();
- }
- if (lookup_timer.cancel() != 0) {
- return;
- }
- if (client_timer.cancel() != 0) {
- return;
- }
- if (queries_out_ > 0) {
- return;
- }
- dlog("Recursive query stopped, deleting");
- delete this;
- }
-
- // This function is used as callback from DNSQuery.
- virtual void operator()(IOFetch::Result result) {
- // XXX is this the place for TCP retry?
- --queries_out_;
-
- if (!done_ && result != IOFetch::TIME_OUT) {
- // we got an answer
-
- // Update the NSAS with the time it took
- struct timeval cur_time;
- gettimeofday(&cur_time, NULL);
- uint32_t rtt;
- if (cur_time.tv_sec >= current_ns_qsent_time.tv_sec &&
- cur_time.tv_usec > current_ns_qsent_time.tv_usec) {
- rtt = 1000 * (cur_time.tv_sec - current_ns_qsent_time.tv_sec);
- rtt += (cur_time.tv_usec - current_ns_qsent_time.tv_usec) / 1000;
- } else {
- rtt = 1;
- }
-
- dlog("RTT: " + boost::lexical_cast<std::string>(rtt));
- current_ns_address.updateRTT(rtt);
-
- Message incoming(Message::PARSE);
- InputBuffer ibuf(buffer_->getData(), buffer_->getLength());
- incoming.fromWire(ibuf);
-
- buffer_->clear();
- if (recursive_mode() &&
- incoming.getRcode() == Rcode::NOERROR()) {
- done_ = handleRecursiveAnswer(incoming);
- } else {
- isc::resolve::copyResponseMessage(incoming, answer_message_);
- done_ = true;
- }
-
- if (done_) {
- stop(true);
- }
- } else if (!done_ && retries_--) {
- // We timed out, but we have some retries, so send again
- dlog("Timeout for " + question_.toText() + " to " + current_ns_address.getAddress().toText() + ", resending query");
- if (recursive_mode()) {
- current_ns_address.updateRTT(isc::nsas::AddressEntry::UNREACHABLE);
- }
- send();
- } else {
- // out of retries, give up for now
- dlog("Timeout for " + question_.toText() + " to " + current_ns_address.getAddress().toText() + ", giving up");
- if (recursive_mode()) {
- current_ns_address.updateRTT(isc::nsas::AddressEntry::UNREACHABLE);
- }
- stop(false);
- }
- }
-
- // Returns true if we are in 'recursive' mode
- // Returns false if we are in 'forwarding' mode
- // (i.e. if we have anything in upstream_)
- bool recursive_mode() const {
- return upstream_->empty();
- }
-};
-
-}
-
-void
-RecursiveQuery::resolve(const QuestionPtr& question,
- const isc::resolve::ResolverInterface::CallbackPtr callback)
-{
- IOService& io = dns_service_.getIOService();
-
- MessagePtr answer_message(new Message(Message::RENDER));
- isc::resolve::initResponseMessage(*question, *answer_message);
-
- OutputBufferPtr buffer(new OutputBuffer(0));
-
- dlog("Asked to resolve: " + question->toText());
-
- dlog("Try out cache first (direct call to resolve)");
- // First try to see if we have something cached in the messagecache
- if (cache_.lookup(question->getName(), question->getType(),
- question->getClass(), *answer_message) &&
- answer_message->getRRCount(Message::SECTION_ANSWER) > 0) {
- dlog("Message found in cache, returning that");
- // TODO: err, should cache set rcode as well?
- answer_message->setRcode(Rcode::NOERROR());
- callback->success(answer_message);
- } else {
- // Perhaps we only have the one RRset?
- // TODO: can we do this? should we check for specific types only?
- RRsetPtr cached_rrset = cache_.lookup(question->getName(),
- question->getType(),
- question->getClass());
- if (cached_rrset) {
- dlog("Found single RRset in cache");
- answer_message->addRRset(Message::SECTION_ANSWER,
- cached_rrset);
- answer_message->setRcode(Rcode::NOERROR());
- callback->success(answer_message);
- } else {
- dlog("Message not found in cache, starting recursive query");
- // It will delete itself when it is done
- new RunningQuery(io, *question, answer_message, upstream_,
- buffer, callback, query_timeout_,
- client_timeout_, lookup_timeout_, retries_,
- nsas_, cache_);
- }
- }
-}
-
-void
-RecursiveQuery::resolve(const Question& question,
- MessagePtr answer_message,
- OutputBufferPtr buffer,
- DNSServer* server)
-{
- // XXX: eventually we will need to be able to determine whether
- // the message should be sent via TCP or UDP, or sent initially via
- // UDP and then fall back to TCP on failure, but for the moment
- // we're only going to handle UDP.
- IOService& io = dns_service_.getIOService();
-
- isc::resolve::ResolverInterface::CallbackPtr crs(
- new isc::resolve::ResolverCallbackServer(server));
-
- // TODO: general 'prepareinitialanswer'
- answer_message->setOpcode(isc::dns::Opcode::QUERY());
- answer_message->addQuestion(question);
-
- dlog("Asked to resolve: " + question.toText());
-
- // First try to see if we have something cached in the messagecache
- dlog("Try out cache first (started by incoming event)");
- if (cache_.lookup(question.getName(), question.getType(),
- question.getClass(), *answer_message) &&
- answer_message->getRRCount(Message::SECTION_ANSWER) > 0) {
- dlog("Message found in cache, returning that");
- // TODO: err, should cache set rcode as well?
- answer_message->setRcode(Rcode::NOERROR());
- crs->success(answer_message);
- } else {
- // Perhaps we only have the one RRset?
- // TODO: can we do this? should we check for specific types only?
- RRsetPtr cached_rrset = cache_.lookup(question.getName(),
- question.getType(),
- question.getClass());
- if (cached_rrset) {
- dlog("Found single RRset in cache");
- answer_message->addRRset(Message::SECTION_ANSWER,
- cached_rrset);
- answer_message->setRcode(Rcode::NOERROR());
- crs->success(answer_message);
- } else {
- dlog("Message not found in cache, starting recursive query");
- // It will delete itself when it is done
- new RunningQuery(io, question, answer_message, upstream_,
- buffer, crs, query_timeout_, client_timeout_,
- lookup_timeout_, retries_, nsas_, cache_);
- }
- }
-}
-
-
-
-} // namespace asiolink
diff --git a/src/lib/asiolink/recursive_query.h b/src/lib/asiolink/recursive_query.h
deleted file mode 100644
index 7beae05..0000000
--- a/src/lib/asiolink/recursive_query.h
+++ /dev/null
@@ -1,119 +0,0 @@
-// Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#ifndef __ASIOLINK_RECURSIVE_QUERY_H
-#define __ASIOLINK_RECURSIVE_QUERY_H 1
-
-#include <asiolink/dns_service.h>
-#include <asiolink/dns_server.h>
-#include <dns/buffer.h>
-#include <nsas/nameserver_address_store.h>
-#include <cache/resolver_cache.h>
-
-namespace asiolink {
-/// \brief The \c RecursiveQuery class provides a layer of abstraction around
-/// the ASIO code that carries out an upstream query.
-///
-/// This design is very preliminary; currently it is only capable of
-/// handling simple forward requests to a single resolver.
-class RecursiveQuery {
- ///
- /// \name Constructors
- ///
- //@{
-public:
- /// \brief Constructor
- ///
- /// This is currently the only way to construct \c RecursiveQuery
- /// object. If the addresses of the forward nameservers is specified,
- /// and every upstream query will be sent to one random address, and
- /// the result sent back directly. If not, it will do full resolving.
- ///
- /// \param dns_service The DNS Service to perform the recursive
- /// query on.
- /// \param upstream Addresses and ports of the upstream servers
- /// to forward queries to.
- /// \param upstream_root Addresses and ports of the root servers
- /// to use when resolving.
- /// \param query_timeout Timeout value for queries we sent, in ms
- /// \param client_timeout Timeout value for when we send back an
- /// error, in ms
- /// \param lookup_timeout Timeout value for when we give up, in ms
- /// \param retries how many times we try again (0 means just send and
- /// and return if it returs).
- RecursiveQuery(DNSService& dns_service,
- isc::nsas::NameserverAddressStore& nsas,
- isc::cache::ResolverCache& cache,
- const std::vector<std::pair<std::string, uint16_t> >&
- upstream,
- const std::vector<std::pair<std::string, uint16_t> >&
- upstream_root,
- int query_timeout = 2000,
- int client_timeout = 4000,
- int lookup_timeout = 30000,
- unsigned retries = 3);
- //@}
-
- /// \brief Initiate resolving
- ///
- /// When sendQuery() is called, a (set of) message(s) is sent
- /// asynchronously. If upstream servers are set, one is chosen
- /// and the response (if any) from that server will be returned.
- ///
- /// If not upstream is set, a root server is chosen from the
- /// root_servers, and the RunningQuery shall do a full resolve
- /// (i.e. if the answer is a delegation, it will be followed, etc.)
- /// until there is an answer or an error.
- ///
- /// When there is a response or an error and we give up, the given
- /// CallbackPtr object shall be called (with either success() or
- /// failure(). See ResolverInterface::Callback for more information.
- ///
- /// \param question The question being answered <qname/qclass/qtype>
- /// \param callback Callback object. See
- /// \c ResolverInterface::Callback for more information
- void resolve(const isc::dns::QuestionPtr& question,
- const isc::resolve::ResolverInterface::CallbackPtr callback);
-
-
- /// \brief Initiates resolving for the given question.
- ///
- /// This actually calls the previous sendQuery() with a default
- /// callback object, which calls resume() on the given DNSServer
- /// object.
- ///
- /// \param question The question being answered <qname/qclass/qtype>
- /// \param answer_message An output Message into which the final response will be copied
- /// \param buffer An output buffer into which the intermediate responses will be copied
- /// \param server A pointer to the \c DNSServer object handling the client
- void resolve(const isc::dns::Question& question,
- isc::dns::MessagePtr answer_message,
- isc::dns::OutputBufferPtr buffer,
- DNSServer* server);
-private:
- DNSService& dns_service_;
- isc::nsas::NameserverAddressStore& nsas_;
- isc::cache::ResolverCache& cache_;
- boost::shared_ptr<std::vector<std::pair<std::string, uint16_t> > >
- upstream_;
- boost::shared_ptr<std::vector<std::pair<std::string, uint16_t> > >
- upstream_root_;
- int query_timeout_;
- int client_timeout_;
- int lookup_timeout_;
- unsigned retries_;
-};
-
-} // namespace asiolink
-#endif // __ASIOLINK_RECURSIVE_QUERY_H
diff --git a/src/lib/asiolink/tcp_socket.h b/src/lib/asiolink/tcp_socket.h
index 5a85aaa..4f5a81e 100644
--- a/src/lib/asiolink/tcp_socket.h
+++ b/src/lib/asiolink/tcp_socket.h
@@ -200,8 +200,8 @@ TCPSocket<C>::open(const IOEndpoint* endpoint, C&) {
// an exception if this is the case.
template <typename C> void
-TCPSocket<C>::asyncSend(const void* data, size_t length,
- const IOEndpoint* endpoint, C& callback)
+TCPSocket<C>::asyncSend(const void*, size_t,
+ const IOEndpoint* endpoint, C&)
{
if (isopen_) {
@@ -232,8 +232,8 @@ TCPSocket<C>::asyncSend(const void* data, size_t length,
// the need for the socket to be open.
template <typename C> void
-TCPSocket<C>::asyncReceive(void* data, size_t length, size_t,
- IOEndpoint* endpoint, C& callback)
+TCPSocket<C>::asyncReceive(void*, size_t, size_t,
+ IOEndpoint* endpoint, C&)
{
if (isopen_) {
diff --git a/src/lib/asiolink/tests/Makefile.am b/src/lib/asiolink/tests/Makefile.am
index b4f0a87..fa8af4f 100644
--- a/src/lib/asiolink/tests/Makefile.am
+++ b/src/lib/asiolink/tests/Makefile.am
@@ -24,7 +24,6 @@ run_unittests_SOURCES += io_fetch_unittest.cc
run_unittests_SOURCES += io_socket_unittest.cc
run_unittests_SOURCES += io_service_unittest.cc
run_unittests_SOURCES += interval_timer_unittest.cc
-run_unittests_SOURCES += recursive_query_unittest.cc
run_unittests_SOURCES += udp_endpoint_unittest.cc
run_unittests_SOURCES += udp_socket_unittest.cc
@@ -36,8 +35,6 @@ run_unittests_LDADD += $(top_builddir)/src/lib/dns/libdns++.la
run_unittests_LDADD += $(top_builddir)/src/lib/exceptions/libexceptions.la
run_unittests_LDADD += $(top_builddir)/src/lib/asiolink/libasiolink.la
run_unittests_LDADD += $(top_builddir)/src/lib/log/liblog.la
-run_unittests_LDADD += $(top_builddir)/src/lib/cache/libcache.la
-run_unittests_LDADD += $(top_builddir)/src/lib/nsas/libnsas.la
run_unittests_LDFLAGS = $(AM_LDFLAGS) $(GTEST_LDFLAGS)
diff --git a/src/lib/asiolink/tests/recursive_query_unittest.cc b/src/lib/asiolink/tests/recursive_query_unittest.cc
deleted file mode 100644
index b8cab8d..0000000
--- a/src/lib/asiolink/tests/recursive_query_unittest.cc
+++ /dev/null
@@ -1,815 +0,0 @@
-// Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <config.h>
-
-#include <sys/socket.h>
-#include <sys/time.h>
-
-#include <string.h>
-
-#include <boost/lexical_cast.hpp>
-#include <boost/bind.hpp>
-#include <boost/date_time/posix_time/posix_time_types.hpp>
-
-#include <gtest/gtest.h>
-
-#include <exceptions/exceptions.h>
-
-#include <dns/tests/unittest_util.h>
-#include <dns/rcode.h>
-
-#include <dns/buffer.h>
-#include <dns/message.h>
-
-#include <nsas/nameserver_address_store.h>
-#include <cache/resolver_cache.h>
-
-// IMPORTANT: We shouldn't directly use ASIO definitions in this test.
-// In particular, we must not include asio.hpp in this file.
-// The asiolink module is primarily intended to be a wrapper that hide the
-// details of the underlying implementations. We need to test the wrapper
-// level behaviors. In addition, some compilers reject to compile this file
-// if we include asio.hpp unless we specify a special compiler option.
-// If we need to test something at the level of underlying ASIO and need
-// their definition, that test should go to asiolink/internal/tests.
-#include <asiolink/recursive_query.h>
-#include <asiolink/io_socket.h>
-#include <asiolink/io_service.h>
-#include <asiolink/io_message.h>
-#include <asiolink/io_error.h>
-#include <asiolink/dns_lookup.h>
-#include <asiolink/simple_callback.h>
-
-using isc::UnitTestUtil;
-using namespace std;
-using namespace asiolink;
-using namespace isc::dns;
-
-namespace {
-const char* const TEST_SERVER_PORT = "53535";
-const char* const TEST_CLIENT_PORT = "53536";
-const char* const TEST_IPV6_ADDR = "::1";
-const char* const TEST_IPV4_ADDR = "127.0.0.1";
-// This data is intended to be valid as a DNS/TCP-like message: the first
-// two octets encode the length of the rest of the data. This is crucial
-// for the tests below.
-const uint8_t test_data[] = {0, 4, 1, 2, 3, 4};
-
-// This function returns an addrinfo structure for use by tests, using
-// different addresses and ports depending on whether we're testing
-// IPv4 or v6, TCP or UDP, and client or server operation.
-struct addrinfo*
-resolveAddress(const int family, const int protocol, const bool client) {
- const char* const addr = (family == AF_INET6) ?
- TEST_IPV6_ADDR : TEST_IPV4_ADDR;
- const char* const port = client ? TEST_CLIENT_PORT : TEST_SERVER_PORT;
-
- struct addrinfo hints;
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = family;
- hints.ai_socktype = (protocol == IPPROTO_UDP) ? SOCK_DGRAM : SOCK_STREAM;
- hints.ai_protocol = protocol;
- hints.ai_flags = AI_NUMERICSERV;
-
- struct addrinfo* res;
- const int error = getaddrinfo(addr, port, &hints, &res);
- if (error != 0) {
- isc_throw(IOError, "getaddrinfo failed: " << gai_strerror(error));
- }
-
- return (res);
-}
-
-// This fixture is a framework for various types of network operations
-// using the ASIO interfaces. Each test case creates an IOService object,
-// opens a local "client" socket for testing, sends data via the local socket
-// to the service that would run in the IOService object.
-// A mock callback function (an ASIOCallBack object) is registered with the
-// IOService object, so the test code should be able to examine the data
-// received on the server side. It then checks the received data matches
-// expected parameters.
-// If initialization parameters of the IOService should be modified, the test
-// case can do it using the setDNSService() method.
-// Note: the set of tests in RecursiveQueryTest use actual network services and may
-// involve undesirable side effects such as blocking.
-class RecursiveQueryTest : public ::testing::Test {
-protected:
- RecursiveQueryTest();
- ~RecursiveQueryTest() {
- if (res_ != NULL) {
- freeaddrinfo(res_);
- }
- if (sock_ != -1) {
- close(sock_);
- }
- delete dns_service_;
- delete callback_;
- delete io_service_;
- }
-
- // Send a test UDP packet to a mock server
- void sendUDP(const int family) {
- res_ = resolveAddress(family, IPPROTO_UDP, false);
-
- sock_ = socket(res_->ai_family, res_->ai_socktype, res_->ai_protocol);
- if (sock_ < 0) {
- isc_throw(IOError, "failed to open test socket");
- }
- const int cc = sendto(sock_, test_data, sizeof(test_data), 0,
- res_->ai_addr, res_->ai_addrlen);
- if (cc != sizeof(test_data)) {
- isc_throw(IOError, "unexpected sendto result: " << cc);
- }
- io_service_->run();
- }
-
- // Send a test TCP packet to a mock server
- void sendTCP(const int family) {
- res_ = resolveAddress(family, IPPROTO_TCP, false);
-
- sock_ = socket(res_->ai_family, res_->ai_socktype, res_->ai_protocol);
- if (sock_ < 0) {
- isc_throw(IOError, "failed to open test socket");
- }
- if (connect(sock_, res_->ai_addr, res_->ai_addrlen) < 0) {
- isc_throw(IOError, "failed to connect to the test server");
- }
- const int cc = send(sock_, test_data, sizeof(test_data), 0);
- if (cc != sizeof(test_data)) {
- isc_throw(IOError, "unexpected send result: " << cc);
- }
- io_service_->run();
- }
-
- // Receive a UDP packet from a mock server; used for testing
- // recursive lookup. The caller must place a RecursiveQuery
- // on the IO Service queue before running this routine.
- void recvUDP(const int family, void* buffer, size_t& size) {
- res_ = resolveAddress(family, IPPROTO_UDP, true);
-
- sock_ = socket(res_->ai_family, res_->ai_socktype, res_->ai_protocol);
- if (sock_ < 0) {
- isc_throw(IOError, "failed to open test socket");
- }
-
- if (bind(sock_, res_->ai_addr, res_->ai_addrlen) < 0) {
- isc_throw(IOError, "bind failed: " << strerror(errno));
- }
-
- // The IO service queue should have a RecursiveQuery object scheduled
- // to run at this point. This call will cause it to begin an
- // async send, then return.
- io_service_->run_one();
-
- // ... and this one will block until the send has completed
- io_service_->run_one();
-
- // Now we attempt to recv() whatever was sent.
- // XXX: there's no guarantee the receiving socket can immediately get
- // the packet. Normally we can perform blocking recv to wait for it,
- // but in theory it's even possible that the packet is lost.
- // In order to prevent the test from hanging in such a worst case
- // we add an ad hoc timeout.
- const struct timeval timeo = { 10, 0 };
- int recv_options = 0;
- if (setsockopt(sock_, SOL_SOCKET, SO_RCVTIMEO, &timeo,
- sizeof(timeo))) {
- if (errno == ENOPROTOOPT) {
- // Workaround for Solaris: it doesn't accept SO_RCVTIMEO
- // with the error of ENOPROTOOPT. Since this is a workaround
- // for rare error cases anyway, we simply switch to the
- // "don't wait" mode. If we still find an error in recv()
- // can happen often we'll consider a more complete solution.
- recv_options = MSG_DONTWAIT;
- } else {
- isc_throw(IOError, "set RCVTIMEO failed: " << strerror(errno));
- }
- }
- const int ret = recv(sock_, buffer, size, recv_options);
- if (ret < 0) {
- isc_throw(IOError, "recvfrom failed: " << strerror(errno));
- }
-
- // Pass the message size back via the size parameter
- size = ret;
- }
-
-
- // Set up an IO Service queue using the specified address
- void setDNSService(const char& address) {
- delete dns_service_;
- dns_service_ = NULL;
- delete io_service_;
- io_service_ = new IOService();
- callback_ = new ASIOCallBack(this);
- dns_service_ = new DNSService(*io_service_, *TEST_SERVER_PORT, address, callback_, NULL, NULL);
- }
-
- // Set up an IO Service queue using the "any" address, on IPv4 if
- // 'use_ipv4' is true and on IPv6 if 'use_ipv6' is true.
- void setDNSService(const bool use_ipv4, const bool use_ipv6) {
- delete dns_service_;
- dns_service_ = NULL;
- delete io_service_;
- io_service_ = new IOService();
- callback_ = new ASIOCallBack(this);
- dns_service_ = new DNSService(*io_service_, *TEST_SERVER_PORT, use_ipv4, use_ipv6, callback_,
- NULL, NULL);
- }
-
- // Set up empty DNS Service
- // Set up an IO Service queue without any addresses
- void setDNSService() {
- delete dns_service_;
- dns_service_ = NULL;
- delete io_service_;
- io_service_ = new IOService();
- callback_ = new ASIOCallBack(this);
- dns_service_ = new DNSService(*io_service_, callback_, NULL, NULL);
- }
-
- // Run a simple server test, on either IPv4 or IPv6, and over either
- // UDP or TCP. Calls the sendUDP() or sendTCP() methods, which will
- // start the IO Service queue. The UDPServer or TCPServer that was
- // created by setIOService() will receive the test packet and issue a
- // callback, which enables us to check that the data it received
- // matches what we sent.
- void doTest(const int family, const int protocol) {
- if (protocol == IPPROTO_UDP) {
- sendUDP(family);
- } else {
- sendTCP(family);
- }
-
- // There doesn't seem to be an effective test for the validity of
- // 'native'.
- // One thing we are sure is it must be different from our local socket.
- EXPECT_NE(sock_, callback_native_);
- EXPECT_EQ(protocol, callback_protocol_);
- EXPECT_EQ(family == AF_INET6 ? TEST_IPV6_ADDR : TEST_IPV4_ADDR,
- callback_address_);
-
- const uint8_t* expected_data =
- protocol == IPPROTO_UDP ? test_data : test_data + 2;
- const size_t expected_datasize =
- protocol == IPPROTO_UDP ? sizeof(test_data) :
- sizeof(test_data) - 2;
- EXPECT_PRED_FORMAT4(UnitTestUtil::matchWireData, &callback_data_[0],
- callback_data_.size(),
- expected_data, expected_datasize);
- }
-
-protected:
- // This is a nonfunctional mockup of a DNSServer object. Its purpose
- // is to resume after a recursive query or other asynchronous call
- // has completed.
- class MockServer : public DNSServer {
- public:
- explicit MockServer(IOService& io_service,
- SimpleCallback* checkin = NULL,
- DNSLookup* lookup = NULL,
- DNSAnswer* answer = NULL) :
- io_(io_service),
- message_(new Message(Message::PARSE)),
- answer_message_(new Message(Message::RENDER)),
- respbuf_(new OutputBuffer(0)),
- checkin_(checkin), lookup_(lookup), answer_(answer)
- {}
-
- void operator()(asio::error_code ec = asio::error_code(),
- size_t length = 0)
- {}
-
- void resume(const bool) {
- // should never be called in our tests
- }
-
- DNSServer* clone() {
- MockServer* s = new MockServer(*this);
- return (s);
- }
-
- inline void asyncLookup() {
- if (lookup_) {
- (*lookup_)(*io_message_, message_, answer_message_,
- respbuf_, this);
- }
- }
-
- protected:
- IOService& io_;
- bool done_;
-
- private:
- // Currently unused; these will be used for testing
- // asynchronous lookup calls via the asyncLookup() method
- boost::shared_ptr<asiolink::IOMessage> io_message_;
- isc::dns::MessagePtr message_;
- isc::dns::MessagePtr answer_message_;
- isc::dns::OutputBufferPtr respbuf_;
-
- // Callback functions provided by the caller
- const SimpleCallback* checkin_;
- const DNSLookup* lookup_;
- const DNSAnswer* answer_;
- };
-
- // This version of mock server just stops the io_service when it is resumed
- class MockServerStop : public MockServer {
- public:
- explicit MockServerStop(IOService& io_service, bool* done) :
- MockServer(io_service),
- done_(done)
- {}
-
- void resume(const bool done) {
- *done_ = done;
- io_.stop();
- }
-
- DNSServer* clone() {
- return (new MockServerStop(*this));
- }
- private:
- bool* done_;
- };
-
- class MockResolver : public isc::resolve::ResolverInterface {
- void resolve(const QuestionPtr& question,
- const ResolverInterface::CallbackPtr& callback) {
- }
- };
-
- // This version of mock server just stops the io_service when it is resumed
- // the second time. (Used in the clientTimeout test, where resume
- // is called initially with the error answer, and later when the
- // lookup times out, it is called without an answer to send back)
- class MockServerStop2 : public MockServer {
- public:
- explicit MockServerStop2(IOService& io_service,
- bool* done1, bool* done2) :
- MockServer(io_service),
- done1_(done1),
- done2_(done2),
- stopped_once_(false)
- {}
-
- void resume(const bool done) {
- if (stopped_once_) {
- *done2_ = done;
- io_.stop();
- } else {
- *done1_ = done;
- stopped_once_ = true;
- }
- }
-
- DNSServer* clone() {
- return (new MockServerStop2(*this));
- }
- private:
- bool* done1_;
- bool* done2_;
- bool stopped_once_;
- };
-
-private:
- class ASIOCallBack : public SimpleCallback {
- public:
- ASIOCallBack(RecursiveQueryTest* test_obj) : test_obj_(test_obj) {}
- void operator()(const IOMessage& io_message) const {
- test_obj_->callBack(io_message);
- }
- private:
- RecursiveQueryTest* test_obj_;
- };
- void callBack(const IOMessage& io_message) {
- callback_protocol_ = io_message.getSocket().getProtocol();
- callback_native_ = io_message.getSocket().getNative();
- callback_address_ =
- io_message.getRemoteEndpoint().getAddress().toText();
- callback_data_.assign(
- static_cast<const uint8_t*>(io_message.getData()),
- static_cast<const uint8_t*>(io_message.getData()) +
- io_message.getDataSize());
- io_service_->stop();
- }
-protected:
- // We use a pointer for io_service_, because for some tests we
- // need to recreate a new one within one onstance of this class
- IOService* io_service_;
- DNSService* dns_service_;
- isc::nsas::NameserverAddressStore* nsas_;
- isc::cache::ResolverCache cache_;
- ASIOCallBack* callback_;
- int callback_protocol_;
- int callback_native_;
- string callback_address_;
- vector<uint8_t> callback_data_;
- int sock_;
- struct addrinfo* res_;
-};
-
-RecursiveQueryTest::RecursiveQueryTest() :
- dns_service_(NULL), callback_(NULL), sock_(-1), res_(NULL)
-{
- io_service_ = new IOService();
- setDNSService(true, true);
- boost::shared_ptr<MockResolver>mock_resolver(new MockResolver());
- nsas_ = new isc::nsas::NameserverAddressStore(mock_resolver);
-}
-
-TEST_F(RecursiveQueryTest, v6UDPSend) {
- doTest(AF_INET6, IPPROTO_UDP);
-}
-
-TEST_F(RecursiveQueryTest, v6TCPSend) {
- doTest(AF_INET6, IPPROTO_TCP);
-}
-
-TEST_F(RecursiveQueryTest, v4UDPSend) {
- doTest(AF_INET, IPPROTO_UDP);
-}
-
-TEST_F(RecursiveQueryTest, v4TCPSend) {
- doTest(AF_INET, IPPROTO_TCP);
-}
-
-TEST_F(RecursiveQueryTest, v6UDPSendSpecific) {
- // Explicitly set a specific address to be bound to the socket.
- // The subsequent test does not directly ensures the underlying socket
- // is bound to the expected address, but the success of the tests should
- // reasonably suggest it works as intended.
- // Specifying an address also implicitly means the service runs in a
- // single address-family mode. In tests using TCP we can confirm that
- // by trying to make a connection and seeing a failure. In UDP, it'd be
- // more complicated because we need to use a connected socket and catch
- // an error on a subsequent read operation. We could do it, but for
- // simplicity we only tests the easier cases for now.
-
- setDNSService(*TEST_IPV6_ADDR);
- doTest(AF_INET6, IPPROTO_UDP);
-}
-
-TEST_F(RecursiveQueryTest, v6TCPSendSpecific) {
- setDNSService(*TEST_IPV6_ADDR);
- doTest(AF_INET6, IPPROTO_TCP);
-
- EXPECT_THROW(sendTCP(AF_INET), IOError);
-}
-
-TEST_F(RecursiveQueryTest, v4UDPSendSpecific) {
- setDNSService(*TEST_IPV4_ADDR);
- doTest(AF_INET, IPPROTO_UDP);
-}
-
-TEST_F(RecursiveQueryTest, v4TCPSendSpecific) {
- setDNSService(*TEST_IPV4_ADDR);
- doTest(AF_INET, IPPROTO_TCP);
-
- EXPECT_THROW(sendTCP(AF_INET6), IOError);
-}
-
-TEST_F(RecursiveQueryTest, v6AddServer) {
- setDNSService();
- dns_service_->addServer(*TEST_SERVER_PORT, TEST_IPV6_ADDR);
- doTest(AF_INET6, IPPROTO_TCP);
-
- EXPECT_THROW(sendTCP(AF_INET), IOError);
-}
-
-TEST_F(RecursiveQueryTest, v4AddServer) {
- setDNSService();
- dns_service_->addServer(*TEST_SERVER_PORT, TEST_IPV4_ADDR);
- doTest(AF_INET, IPPROTO_TCP);
-
- EXPECT_THROW(sendTCP(AF_INET6), IOError);
-}
-
-TEST_F(RecursiveQueryTest, clearServers) {
- setDNSService();
- dns_service_->clearServers();
-
- EXPECT_THROW(sendTCP(AF_INET), IOError);
- EXPECT_THROW(sendTCP(AF_INET6), IOError);
-}
-
-TEST_F(RecursiveQueryTest, v6TCPOnly) {
- // Open only IPv6 TCP socket. A subsequent attempt of establishing an
- // IPv4/TCP connection should fail. See above for why we only test this
- // for TCP.
- setDNSService(false, true);
- EXPECT_THROW(sendTCP(AF_INET), IOError);
-}
-
-TEST_F(RecursiveQueryTest, v4TCPOnly) {
- setDNSService(true, false);
- EXPECT_THROW(sendTCP(AF_INET6), IOError);
-}
-
-vector<pair<string, uint16_t> >
-singleAddress(const string &address, uint16_t port) {
- vector<pair<string, uint16_t> > result;
- result.push_back(pair<string, uint16_t>(address, port));
- return (result);
-}
-
-TEST_F(RecursiveQueryTest, recursiveSetupV4) {
- setDNSService(true, false);
- uint16_t port = boost::lexical_cast<uint16_t>(TEST_CLIENT_PORT);
- EXPECT_NO_THROW(RecursiveQuery(*dns_service_,
- *nsas_, cache_,
- singleAddress(TEST_IPV4_ADDR, port),
- singleAddress(TEST_IPV4_ADDR, port)));
-}
-
-TEST_F(RecursiveQueryTest, recursiveSetupV6) {
- setDNSService(false, true);
- uint16_t port = boost::lexical_cast<uint16_t>(TEST_CLIENT_PORT);
- EXPECT_NO_THROW(RecursiveQuery(*dns_service_,
- *nsas_, cache_,
- singleAddress(TEST_IPV6_ADDR, port),
- singleAddress(TEST_IPV6_ADDR,port)));
-}
-
-// XXX:
-// This is very inadequate unit testing. It should be generalized into
-// a routine that can do this with variable address family, address, and
-// port, and with the various callbacks defined in such a way as to ensure
-// full code coverage including error cases.
-TEST_F(RecursiveQueryTest, forwarderSend) {
- setDNSService(true, false);
-
- // Note: We use the test prot plus one to ensure we aren't binding
- // to the same port as the actual server
- uint16_t port = boost::lexical_cast<uint16_t>(TEST_CLIENT_PORT);
-
- MockServer server(*io_service_);
- RecursiveQuery rq(*dns_service_,
- *nsas_, cache_,
- singleAddress(TEST_IPV4_ADDR, port),
- singleAddress(TEST_IPV4_ADDR, port));
-
- Question q(Name("example.com"), RRClass::IN(), RRType::TXT());
- OutputBufferPtr buffer(new OutputBuffer(0));
- MessagePtr answer(new Message(Message::RENDER));
- rq.resolve(q, answer, buffer, &server);
-
- char data[4096];
- size_t size = sizeof(data);
- ASSERT_NO_THROW(recvUDP(AF_INET, data, size));
-
- Message m(Message::PARSE);
- InputBuffer ibuf(data, size);
-
- // Make sure we can parse the message that was sent
- EXPECT_NO_THROW(m.parseHeader(ibuf));
- EXPECT_NO_THROW(m.fromWire(ibuf));
-
- // Check that the question sent matches the one we wanted
- QuestionPtr q2 = *m.beginQuestion();
- EXPECT_EQ(q.getName(), q2->getName());
- EXPECT_EQ(q.getType(), q2->getType());
- EXPECT_EQ(q.getClass(), q2->getClass());
-}
-
-int
-createTestSocket()
-{
- struct addrinfo* res_ = resolveAddress(AF_INET, IPPROTO_UDP, true);
- int sock_ = socket(res_->ai_family, res_->ai_socktype, res_->ai_protocol);
- if (sock_ < 0) {
- isc_throw(IOError, "failed to open test socket");
- }
- if (bind(sock_, res_->ai_addr, res_->ai_addrlen) < 0) {
- isc_throw(IOError, "failed to bind test socket");
- }
- return sock_;
-}
-
-int
-setSocketTimeout(int sock_, size_t tv_sec, size_t tv_usec) {
- const struct timeval timeo = { tv_sec, tv_usec };
- int recv_options = 0;
- if (setsockopt(sock_, SOL_SOCKET, SO_RCVTIMEO, &timeo, sizeof(timeo))) {
- if (errno == ENOPROTOOPT) { // see RecursiveQueryTest::recvUDP()
- recv_options = MSG_DONTWAIT;
- } else {
- isc_throw(IOError, "set RCVTIMEO failed: " << strerror(errno));
- }
- }
- return recv_options;
-}
-
-// try to read from the socket max time
-// *num is incremented for every succesfull read
-// returns true if it can read max times, false otherwise
-bool tryRead(int sock_, int recv_options, size_t max, int* num) {
- size_t i = 0;
- do {
- char inbuff[512];
- if (recv(sock_, inbuff, sizeof(inbuff), recv_options) < 0) {
- return false;
- } else {
- ++i;
- ++*num;
- }
- } while (i < max);
- return true;
-}
-
-
-// Test it tries the correct amount of times before giving up
-TEST_F(RecursiveQueryTest, forwardQueryTimeout) {
- // Prepare the service (we do not use the common setup, we do not answer
- setDNSService();
-
- // Prepare the socket
- sock_ = createTestSocket();
-
- // Prepare the server
- bool done(true);
- MockServerStop server(*io_service_, &done);
-
- // Do the answer
- const uint16_t port = boost::lexical_cast<uint16_t>(TEST_CLIENT_PORT);
- RecursiveQuery query(*dns_service_,
- *nsas_, cache_,
- singleAddress(TEST_IPV4_ADDR, port),
- singleAddress(TEST_IPV4_ADDR, port),
- 10, 4000, 3000, 2);
- Question question(Name("example.net"), RRClass::IN(), RRType::A());
- OutputBufferPtr buffer(new OutputBuffer(0));
- MessagePtr answer(new Message(Message::RENDER));
- query.resolve(question, answer, buffer, &server);
-
- // Run the test
- io_service_->run();
-
- // Read up to 3 packets. Use some ad hoc timeout to prevent an infinite
- // block (see also recvUDP()).
- int recv_options = setSocketTimeout(sock_, 10, 0);
- int num = 0;
- bool read_success = tryRead(sock_, recv_options, 3, &num);
-
- // The query should fail
- EXPECT_FALSE(done);
- EXPECT_EQ(3, num);
- EXPECT_TRUE(read_success);
-}
-
-// If we set client timeout to lower than querytimeout, we should
-// get a failure answer, but still see retries
-// (no actual answer is given here yet)
-TEST_F(RecursiveQueryTest, forwardClientTimeout) {
- // Prepare the service (we do not use the common setup, we do not answer
- setDNSService();
-
- sock_ = createTestSocket();
-
- // Prepare the server
- bool done1(true);
- bool done2(true);
- MockServerStop2 server(*io_service_, &done1, &done2);
-
- MessagePtr answer(new Message(Message::RENDER));
-
- // Do the answer
- const uint16_t port = boost::lexical_cast<uint16_t>(TEST_CLIENT_PORT);
- // Set it up to retry twice before client timeout fires
- // Since the lookup timer has not fired, it should retry
- // four times
- RecursiveQuery query(*dns_service_,
- *nsas_, cache_,
- singleAddress(TEST_IPV4_ADDR, port),
- singleAddress(TEST_IPV4_ADDR, port),
- 200, 480, 4000, 4);
- Question question(Name("example.net"), RRClass::IN(), RRType::A());
- OutputBufferPtr buffer(new OutputBuffer(0));
- query.resolve(question, answer, buffer, &server);
-
- // Run the test
- io_service_->run();
-
- // we know it'll fail, so make it a shorter timeout
- int recv_options = setSocketTimeout(sock_, 1, 0);
-
- // Try to read 5 times
- int num = 0;
- bool read_success = tryRead(sock_, recv_options, 5, &num);
-
- // The query should fail, but we should have kept on trying
- EXPECT_TRUE(done1);
- EXPECT_FALSE(done2);
- EXPECT_EQ(5, num);
- EXPECT_TRUE(read_success);
-}
-
-// If we set lookup timeout to lower than querytimeout*retries, we should
-// fail before the full amount of retries
-TEST_F(RecursiveQueryTest, forwardLookupTimeout) {
- // Prepare the service (we do not use the common setup, we do not answer
- setDNSService();
-
- // Prepare the socket
- sock_ = createTestSocket();
-
- // Prepare the server
- bool done(true);
- MockServerStop server(*io_service_, &done);
-
- MessagePtr answer(new Message(Message::RENDER));
-
- // Do the answer
- const uint16_t port = boost::lexical_cast<uint16_t>(TEST_CLIENT_PORT);
- // Set up the test so that it will retry 5 times, but the lookup
- // timeout will fire after only 3 normal timeouts
- RecursiveQuery query(*dns_service_,
- *nsas_, cache_,
- singleAddress(TEST_IPV4_ADDR, port),
- singleAddress(TEST_IPV4_ADDR, port),
- 200, 4000, 480, 5);
- Question question(Name("example.net"), RRClass::IN(), RRType::A());
- OutputBufferPtr buffer(new OutputBuffer(0));
- query.resolve(question, answer, buffer, &server);
-
- // Run the test
- io_service_->run();
-
- int recv_options = setSocketTimeout(sock_, 1, 0);
-
- // Try to read 5 times, should stop after 3 reads
- int num = 0;
- bool read_success = tryRead(sock_, recv_options, 5, &num);
-
- // The query should fail
- EXPECT_FALSE(done);
- EXPECT_EQ(3, num);
- EXPECT_FALSE(read_success);
-}
-
-// as mentioned above, we need a more better framework for this,
-// in addition to that, this sends out queries into the world
-// (which we should catch somehow and fake replies for)
-// for the skeleton code, it shouldn't be too much of a problem
-// Ok so even we don't all have access to the DNS world right now,
-// so disabling these tests too.
-TEST_F(RecursiveQueryTest, DISABLED_recursiveSendOk) {
- setDNSService(true, false);
- bool done;
-
- MockServerStop server(*io_service_, &done);
- vector<pair<string, uint16_t> > empty_vector;
- RecursiveQuery rq(*dns_service_, *nsas_, cache_, empty_vector,
- empty_vector, 10000, 0);
-
- Question q(Name("www.isc.org"), RRClass::IN(), RRType::A());
- OutputBufferPtr buffer(new OutputBuffer(0));
- MessagePtr answer(new Message(Message::RENDER));
- rq.resolve(q, answer, buffer, &server);
- io_service_->run();
-
- // Check that the answer we got matches the one we wanted
- EXPECT_EQ(Rcode::NOERROR(), answer->getRcode());
- ASSERT_EQ(1, answer->getRRCount(Message::SECTION_ANSWER));
- RRsetPtr a = *answer->beginSection(Message::SECTION_ANSWER);
- EXPECT_EQ(q.getName(), a->getName());
- EXPECT_EQ(q.getType(), a->getType());
- EXPECT_EQ(q.getClass(), a->getClass());
- EXPECT_EQ(1, a->getRdataCount());
-}
-
-// see comments at previous test
-TEST_F(RecursiveQueryTest, DISABLED_recursiveSendNXDOMAIN) {
- setDNSService(true, false);
- bool done;
-
- MockServerStop server(*io_service_, &done);
- vector<pair<string, uint16_t> > empty_vector;
- RecursiveQuery rq(*dns_service_, *nsas_, cache_, empty_vector,
- empty_vector, 10000, 0);
-
- Question q(Name("wwwdoesnotexist.isc.org"), RRClass::IN(), RRType::A());
- OutputBufferPtr buffer(new OutputBuffer(0));
- MessagePtr answer(new Message(Message::RENDER));
- rq.resolve(q, answer, buffer, &server);
- io_service_->run();
-
- // Check that the answer we got matches the one we wanted
- EXPECT_EQ(Rcode::NXDOMAIN(), answer->getRcode());
- EXPECT_EQ(0, answer->getRRCount(Message::SECTION_ANSWER));
-}
-
-}
diff --git a/src/lib/nsas/nameserver_address_store.cc b/src/lib/nsas/nameserver_address_store.cc
index 7bb0eee..6e5ca27 100644
--- a/src/lib/nsas/nameserver_address_store.cc
+++ b/src/lib/nsas/nameserver_address_store.cc
@@ -93,5 +93,18 @@ NameserverAddressStore::lookup(const string& zone, const RRClass& class_code,
zone_obj.second->addCallback(callback, family);
}
+void
+NameserverAddressStore::cancel(const string& zone,
+ const RRClass& class_code,
+ boost::shared_ptr<AddressRequestCallback> callback,
+ AddressFamily family)
+{
+ boost::shared_ptr<ZoneEntry> entry(zone_hash_->get(HashKey(zone,
+ class_code)));
+ if (entry) {
+ entry->removeCallback(callback, family);
+ }
+}
+
} // namespace nsas
} // namespace isc
diff --git a/src/lib/nsas/nameserver_address_store.h b/src/lib/nsas/nameserver_address_store.h
index f183871..717ebf4 100644
--- a/src/lib/nsas/nameserver_address_store.h
+++ b/src/lib/nsas/nameserver_address_store.h
@@ -87,6 +87,13 @@ public:
boost::shared_ptr<AddressRequestCallback> callback, AddressFamily
family = ANY_OK);
+ /// \brief cancel the given lookup action
+ ///
+ /// \param callback Callback object that would be called
+ void cancel(const std::string& zone, const dns::RRClass& class_code,
+ boost::shared_ptr<AddressRequestCallback> callback,
+ AddressFamily family = ANY_OK);
+
/// \brief Protected Members
///
/// These members should be private. However, with so few public methods
diff --git a/src/lib/nsas/zone_entry.cc b/src/lib/nsas/zone_entry.cc
index 77f3dad..6e1d8b0 100644
--- a/src/lib/nsas/zone_entry.cc
+++ b/src/lib/nsas/zone_entry.cc
@@ -261,6 +261,19 @@ ZoneEntry::addCallback(CallbackPtr callback, AddressFamily family) {
}
}
+void
+ZoneEntry::removeCallback(CallbackPtr callback, AddressFamily family) {
+ Lock lock(mutex_);
+ std::vector<boost::shared_ptr<AddressRequestCallback> >::iterator i =
+ callbacks_[family].begin();
+ for (; i != callbacks_[family].end(); ++i) {
+ if (*i == callback) {
+ callbacks_[family].erase(i);
+ return;
+ }
+ }
+}
+
namespace {
// This just moves items from one container to another
diff --git a/src/lib/nsas/zone_entry.h b/src/lib/nsas/zone_entry.h
index 28a42ea..3a361fe 100644
--- a/src/lib/nsas/zone_entry.h
+++ b/src/lib/nsas/zone_entry.h
@@ -101,6 +101,15 @@ public:
void addCallback(boost::shared_ptr<AddressRequestCallback>
callback, AddressFamily family);
+ /**
+ * \short Remove a callback from the list
+ *
+ * \param callback The callback itself.
+ * \param family Which address family is acceptable as an answer?
+ */
+ void removeCallback(boost::shared_ptr<AddressRequestCallback>
+ callback, AddressFamily family);
+
/// \short Protected members, so they can be accessed by tests.
//@{
protected:
diff --git a/src/lib/resolve/Makefile.am b/src/lib/resolve/Makefile.am
index c9f1326..c6f65a4 100644
--- a/src/lib/resolve/Makefile.am
+++ b/src/lib/resolve/Makefile.am
@@ -14,5 +14,6 @@ libresolve_la_SOURCES = resolve.h resolve.cc
libresolve_la_SOURCES += resolver_interface.h
libresolve_la_SOURCES += resolver_callback.h resolver_callback.cc
libresolve_la_SOURCES += response_classifier.cc response_classifier.h
+libresolve_la_SOURCES += recursive_query.cc recursive_query.h
libresolve_la_LIBADD = $(top_builddir)/src/lib/dns/libdns++.la
libresolve_la_LIBADD += $(top_builddir)/src/lib/exceptions/libexceptions.la
diff --git a/src/lib/resolve/recursive_query.cc b/src/lib/resolve/recursive_query.cc
new file mode 100644
index 0000000..bf3ef6b
--- /dev/null
+++ b/src/lib/resolve/recursive_query.cc
@@ -0,0 +1,684 @@
+// Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
+//
+// Permission to use, copy, modify, and/or distribute this software for any
+// purpose with or without fee is hereby granted, provided that the above
+// copyright notice and this permission notice appear in all copies.
+//
+// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
+// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+// AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
+// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
+// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+// PERFORMANCE OF THIS SOFTWARE.
+
+#include <netinet/in.h>
+#include <stdlib.h>
+#include <sys/socket.h>
+#include <unistd.h> // for some IPC/network system calls
+
+#include <boost/lexical_cast.hpp>
+#include <boost/bind.hpp>
+
+#include <config.h>
+
+#include <log/dummylog.h>
+
+#include <dns/question.h>
+#include <dns/message.h>
+#include <dns/opcode.h>
+
+#include <resolve/resolve.h>
+#include <cache/resolver_cache.h>
+#include <nsas/address_request_callback.h>
+#include <nsas/nameserver_address.h>
+
+#include <asio.hpp>
+#include <asiolink/dns_service.h>
+#include <asiolink/io_fetch.h>
+#include <asiolink/io_service.h>
+#include <resolve/recursive_query.h>
+
+using isc::log::dlog;
+using namespace isc::dns;
+
+namespace asiolink {
+
+typedef std::vector<std::pair<std::string, uint16_t> > AddressVector;
+
+// Here we do not use the typedef above, as the SunStudio compiler
+// mishandles this in its name mangling, and wouldn't compile.
+// We can probably use a typedef, but need to move it to a central
+// location and use it consistently.
+RecursiveQuery::RecursiveQuery(DNSService& dns_service,
+ isc::nsas::NameserverAddressStore& nsas,
+ isc::cache::ResolverCache& cache,
+ const std::vector<std::pair<std::string, uint16_t> >& upstream,
+ const std::vector<std::pair<std::string, uint16_t> >& upstream_root,
+ int query_timeout, int client_timeout, int lookup_timeout,
+ unsigned retries) :
+ dns_service_(dns_service),
+ nsas_(nsas), cache_(cache),
+ upstream_(new AddressVector(upstream)),
+ upstream_root_(new AddressVector(upstream_root)),
+ query_timeout_(query_timeout), client_timeout_(client_timeout),
+ lookup_timeout_(lookup_timeout), retries_(retries)
+{
+}
+
+namespace {
+
+typedef std::pair<std::string, uint16_t> addr_t;
+
+/*
+ * This is a query in progress. When a new query is made, this one holds
+ * the context information about it, like how many times we are allowed
+ * to retry on failure, what to do when we succeed, etc.
+ *
+ * Used by RecursiveQuery::sendQuery.
+ */
+class RunningQuery : public IOFetch::Callback {
+
+class ResolverNSASCallback : public isc::nsas::AddressRequestCallback {
+public:
+ ResolverNSASCallback(RunningQuery* rq) : rq_(rq) {}
+
+ void success(const isc::nsas::NameserverAddress& address) {
+ dlog("Found a nameserver, sending query to " + address.getAddress().toText());
+ rq_->nsasCallbackCalled();
+ rq_->sendTo(address);
+ }
+
+ void unreachable() {
+ dlog("Nameservers unreachable");
+ // Drop query or send servfail?
+ rq_->nsasCallbackCalled();
+ rq_->makeSERVFAIL();
+ rq_->stop(false);
+ }
+
+private:
+ RunningQuery* rq_;
+};
+
+
+private:
+ // The io service to handle async calls
+ IOService& io_;
+
+ // Info for (re)sending the query (the question and destination)
+ Question question_;
+
+ // This is where we build and store our final answer
+ MessagePtr answer_message_;
+
+ // currently we use upstream as the current list of NS records
+ // we should differentiate between forwarding and resolving
+ boost::shared_ptr<AddressVector> upstream_;
+
+ // Buffer to store the result.
+ OutputBufferPtr buffer_;
+
+ // Server to notify when we succeed or fail
+ //shared_ptr<DNSServer> server_;
+ isc::resolve::ResolverInterface::CallbackPtr resolvercallback_;
+
+ // To prevent both unreasonably long cname chains and cname loops,
+ // we simply keep a counter of the number of CNAMEs we have
+ // followed so far (and error if it exceeds RESOLVER_MAX_CNAME_CHAIN
+ // from lib/resolve/response_classifier.h)
+ unsigned cname_count_;
+
+ /*
+ * TODO Do something more clever with timeouts. In the long term, some
+ * computation of average RTT, increase with each retry, etc.
+ */
+ // Timeout information
+ int query_timeout_;
+ unsigned retries_;
+
+ // normal query state
+
+ // Update the question that will be sent to the server
+ void setQuestion(const Question& new_question) {
+ question_ = new_question;
+ }
+
+ // TODO: replace by our wrapper
+ asio::deadline_timer client_timer;
+ bool client_timer_canceled_;
+ asio::deadline_timer lookup_timer;
+
+ size_t queries_out_;
+
+ // If we timed out ourselves (lookup timeout), stop issuing queries
+ bool done_;
+
+ // If we have a client timeout, we send back an answer, but don't
+ // stop. We use this variable to make sure we don't send another
+ // answer if we do find one later (or if we have a lookup_timeout)
+ bool answer_sent_;
+
+ // Reference to our NSAS
+ isc::nsas::NameserverAddressStore& nsas_;
+
+ // Reference to our cache
+ isc::cache::ResolverCache& cache_;
+
+ // the 'current' nameserver we have a query out to
+ std::string cur_zone_;
+ boost::shared_ptr<ResolverNSASCallback> nsas_callback_;
+ // this is set to true if we have asked the nsas to give us
+ // an address and we are waiting for it to call us back
+ bool nsas_callback_out_;
+ isc::nsas::NameserverAddress current_ns_address;
+ struct timeval current_ns_qsent_time;
+
+ // perform a single lookup; first we check the cache to see
+ // if we have a response for our query stored already. if
+ // so, call handlerecursiveresponse(), if not, we call send()
+ void doLookup() {
+ dlog("doLookup: try cache");
+ Message cached_message(Message::RENDER);
+ isc::resolve::initResponseMessage(question_, cached_message);
+ if (cache_.lookup(question_.getName(), question_.getType(),
+ question_.getClass(), cached_message)) {
+ dlog("Message found in cache, returning that");
+ if (handleRecursiveAnswer(cached_message)) {
+ stop(true);
+ }
+ } else {
+ cur_zone_ = ".";
+ send();
+ }
+
+ }
+
+ void sendTo(const isc::nsas::NameserverAddress& address) {
+ // We need to keep track of the Address, so that we can update
+ // the RTT
+ current_ns_address = address;
+ gettimeofday(¤t_ns_qsent_time, NULL);
+ ++queries_out_;
+ IOFetch query(IPPROTO_UDP, io_, question_,
+ current_ns_address.getAddress(),
+ 53, buffer_, this,
+ query_timeout_);
+ io_.get_io_service().post(query);
+ }
+
+ void send() {
+ // If are in forwarder mode, send it to a random
+ // forwarder. If not, ask the NSAS for an address
+ const int uc = upstream_->size();
+ if (uc > 0) {
+ int serverIndex = rand() % uc;
+ dlog("Sending upstream query (" + question_.toText() +
+ ") to " + upstream_->at(serverIndex).first);
+ ++queries_out_;
+ IOFetch query(IPPROTO_UDP, io_, question_,
+ upstream_->at(serverIndex).first,
+ upstream_->at(serverIndex).second, buffer_, this,
+ query_timeout_);
+ io_.get_io_service().post(query);
+ } else {
+ // Ask the NSAS for an address for the current zone,
+ // the callback will call the actual sendTo()
+ dlog("Look up nameserver for " + cur_zone_ + " in NSAS");
+ // Can we have multiple calls to nsas_out? Let's assume not
+ // for now
+ std::cout << "[XX] NSASLOOKUP " << this << " for " << cur_zone_ << std::endl;
+ assert(!nsas_callback_out_);
+ nsas_callback_out_ = true;
+ nsas_.lookup(cur_zone_, question_.getClass(), nsas_callback_);
+ }
+ }
+
+ void nsasCallbackCalled() {
+ std::cout << "[XX] NSASLOOKUP DONE " << this << " for " << cur_zone_ << std::endl;
+ nsas_callback_out_ = false;
+ }
+
+ // This function is called by operator() if there is an actual
+ // answer from a server and we are in recursive mode
+ // depending on the contents, we go on recursing or return
+ //
+ // Note that the footprint may change as this function may
+ // need to append data to the answer we are building later.
+ //
+ // returns true if we are done (either we have an answer or an
+ // error message)
+ // returns false if we are not done
+ bool handleRecursiveAnswer(const Message& incoming) {
+ dlog("Handle response");
+ // In case we get a CNAME, we store the target
+ // here (classify() will set it when it walks through
+ // the cname chain to verify it).
+ Name cname_target(question_.getName());
+
+ isc::resolve::ResponseClassifier::Category category =
+ isc::resolve::ResponseClassifier::classify(
+ question_, incoming, cname_target, cname_count_, true);
+
+ bool found_ns_address = false;
+
+ // If the packet is OK, store it in the cache
+ //if (!isc::resolve::ResponseClassifier::error(category)) {
+ // cache_.update(incoming);
+ //}
+
+ switch (category) {
+ case isc::resolve::ResponseClassifier::ANSWER:
+ case isc::resolve::ResponseClassifier::ANSWERCNAME:
+ // Done. copy and return.
+ dlog("Response is an answer");
+ cache_.update(incoming);
+ isc::resolve::copyResponseMessage(incoming, answer_message_);
+ return true;
+ break;
+ case isc::resolve::ResponseClassifier::CNAME:
+ dlog("Response is CNAME!");
+ cache_.update(incoming);
+ // (unfinished) CNAME. We set our question_ to the CNAME
+ // target, then start over at the beginning (for now, that
+ // is, we reset our 'current servers' to the root servers).
+ if (cname_count_ >= RESOLVER_MAX_CNAME_CHAIN) {
+ // just give up
+ dlog("CNAME chain too long");
+ makeSERVFAIL();
+ return true;
+ }
+
+ answer_message_->appendSection(Message::SECTION_ANSWER,
+ incoming);
+
+ question_ = Question(cname_target, question_.getClass(),
+ question_.getType());
+
+ dlog("Following CNAME chain to " + question_.toText());
+ doLookup();
+ return false;
+ break;
+ case isc::resolve::ResponseClassifier::NXDOMAIN:
+ case isc::resolve::ResponseClassifier::NXRRSET:
+ dlog("Response is NXDOMAIN or NXRRSET");
+ // NXDOMAIN, just copy and return.
+ // no negcache yet
+ //cache_.update(incoming);
+ dlog(incoming.toText());
+ isc::resolve::copyResponseMessage(incoming, answer_message_);
+ return true;
+ break;
+ case isc::resolve::ResponseClassifier::REFERRAL:
+ dlog("Response is referral");
+ cache_.update(incoming);
+ // Referral. For now we just take the first glue address
+ // we find and continue with that
+
+ // auth section should have at least one RRset
+ // and one of them should be an NS (otherwise
+ // classifier should have error'd)
+ // TODO: should we check if it really is subzone?
+ for (RRsetIterator rrsi = incoming.beginSection(Message::SECTION_AUTHORITY);
+ rrsi != incoming.endSection(Message::SECTION_AUTHORITY) && !found_ns_address;
+ ++rrsi) {
+ ConstRRsetPtr rrs = *rrsi;
+ if (rrs->getType() == RRType::NS()) {
+ cur_zone_ = rrs->getName().toText();
+ dlog("Referred to zone " + cur_zone_);
+ found_ns_address = true;
+ break;
+ }
+ }
+
+ if (found_ns_address) {
+ // next resolver round
+ // we do NOT use doLookup() here, but send() (i.e. we
+ // skip the cache), since if we had the final answer
+ // instead of a delegation cached, we would have been
+ // there by now.
+ send();
+ return false;
+ } else {
+ dlog("No NS RRset in referral?");
+ // TODO this will result in answering with the delegation. oh well
+ isc::resolve::copyResponseMessage(incoming, answer_message_);
+ return true;
+ }
+ break;
+ case isc::resolve::ResponseClassifier::EMPTY:
+ case isc::resolve::ResponseClassifier::EXTRADATA:
+ case isc::resolve::ResponseClassifier::INVNAMCLASS:
+ case isc::resolve::ResponseClassifier::INVTYPE:
+ case isc::resolve::ResponseClassifier::MISMATQUEST:
+ case isc::resolve::ResponseClassifier::MULTICLASS:
+ case isc::resolve::ResponseClassifier::NOTONEQUEST:
+ case isc::resolve::ResponseClassifier::NOTRESPONSE:
+ case isc::resolve::ResponseClassifier::NOTSINGLE:
+ case isc::resolve::ResponseClassifier::OPCODE:
+ case isc::resolve::ResponseClassifier::RCODE:
+ case isc::resolve::ResponseClassifier::TRUNCATED:
+ dlog("Error in response, returning SERVFAIL");
+ // Should we try a different server rather than SERVFAIL?
+ makeSERVFAIL();
+ return true;
+ break;
+ }
+ // should not be reached. assert here?
+ // (since we do not have a default in the switch above,
+ // the compiler should have errored on any missing case
+ // statements
+ assert(false);
+ return true;
+ }
+
+public:
+ RunningQuery(IOService& io,
+ const Question& question,
+ MessagePtr answer_message,
+ boost::shared_ptr<AddressVector> upstream,
+ OutputBufferPtr buffer,
+ isc::resolve::ResolverInterface::CallbackPtr cb,
+ int query_timeout, int client_timeout, int lookup_timeout,
+ unsigned retries,
+ isc::nsas::NameserverAddressStore& nsas,
+ isc::cache::ResolverCache& cache) :
+ io_(io),
+ question_(question),
+ answer_message_(answer_message),
+ upstream_(upstream),
+ buffer_(buffer),
+ resolvercallback_(cb),
+ cname_count_(0),
+ query_timeout_(query_timeout),
+ retries_(retries),
+ client_timer(io.get_io_service()),
+ client_timer_canceled_(false),
+ lookup_timer(io.get_io_service()),
+ queries_out_(0),
+ done_(false),
+ answer_sent_(false),
+ nsas_(nsas),
+ cache_(cache),
+ nsas_callback_(boost::shared_ptr<ResolverNSASCallback>(
+ new ResolverNSASCallback(this))),
+ nsas_callback_out_(false)
+ {
+ // Setup the timer to stop trying (lookup_timeout)
+ if (lookup_timeout >= 0) {
+ lookup_timer.expires_from_now(
+ boost::posix_time::milliseconds(lookup_timeout));
+ lookup_timer.async_wait(boost::bind(&RunningQuery::stop, this, false));
+ }
+
+ // Setup the timer to send an answer (client_timeout)
+ if (client_timeout >= 0) {
+ client_timer.expires_from_now(
+ boost::posix_time::milliseconds(client_timeout));
+ client_timer.async_wait(boost::bind(&RunningQuery::clientTimeout, this));
+ }
+
+ doLookup();
+ }
+
+ virtual void clientTimeout() {
+ dlog("[XX] client timer fired");
+ // Return a SERVFAIL, but do not stop until
+ // we have an answer or timeout ourselves
+ if (!answer_sent_) {
+ dlog("[XX] answer not sent yet");
+ answer_sent_ = true;
+ makeSERVFAIL();
+ resolvercallback_->success(answer_message_);
+ }
+ // if we got here because we canceled it in stop(), we
+ // need to go back to stop()
+ if (client_timer_canceled_) {
+ dlog("[XX] fired due to cancellation");
+ stop(false);
+ }
+ }
+
+ virtual void stop(bool resume) {
+ dlog("[XX] stop() called");
+ // if we cancel our timers, we will still get an event for
+ // that, so we cannot delete ourselves just yet (those events
+ // would be bound to a deleted object)
+ // cancel them one by one, both cancels should get us back
+ // here again.
+ // same goes if we have an outstanding query (can't delete
+ // until that one comes back to us)
+ done_ = true;
+ dlog("[XX] stop() called1");
+ if (!answer_sent_) {
+ dlog("[XX] no answer sent yet");
+ answer_sent_ = true;
+
+ // There are two types of messages we could store in the
+ // cache;
+ // 1. answers to our fetches from authoritative servers,
+ // exactly as we receive them, and
+ // 2. answers to queries we received from clients, which
+ // have received additional processing (following CNAME
+ // chains, for instance)
+ //
+ // Doing only the first would mean we would have to re-do
+ // processing when we get data from our cache, and doing
+ // only the second would miss out on the side-effect of
+ // having nameserver data in our cache.
+ //
+ // So right now we do both. Since the cache (currently)
+ // stores Messages on their question section only, this
+ // does mean that we overwrite the messages we stored in
+ // the previous iteration if we are following a delegation.
+ if (resume) {
+ cache_.update(*answer_message_);
+
+ resolvercallback_->success(answer_message_);
+ } else {
+ resolvercallback_->failure();
+ }
+ return;
+ }
+ dlog("[XX] stop() called2");
+ if (lookup_timer.cancel() != 0) {
+ dlog("[XX] lookup timer canceled");
+ return;
+ }
+ dlog("[XX] stop() called3");
+ if (client_timer.cancel() != 0) {
+ dlog("[XX] client timer canceled");
+ client_timer_canceled_ = true;
+ return;
+ } else {
+ dlog("[XX] no client timer anymore");
+ }
+ dlog("[XX] continuing");
+ if (queries_out_ > 0) {
+ dlog("[XX] still one or more queries out");
+ return;
+ }
+ dlog("[XX] stop() called4");
+ if (nsas_callback_out_) {
+ nsas_.cancel(cur_zone_, question_.getClass(), nsas_callback_);
+ nsas_callback_out_ = false;
+ }
+ dlog("Recursive query stopped, deleting");
+ delete this;
+ }
+
+ // This function is used as callback from DNSQuery.
+ virtual void operator()(IOFetch::Result result) {
+ // XXX is this the place for TCP retry?
+ --queries_out_;
+
+ if (!done_ && result != IOFetch::TIME_OUT) {
+ // we got an answer
+
+ // Update the NSAS with the time it took
+ struct timeval cur_time;
+ gettimeofday(&cur_time, NULL);
+ uint32_t rtt;
+ if (cur_time.tv_sec >= current_ns_qsent_time.tv_sec &&
+ cur_time.tv_usec > current_ns_qsent_time.tv_usec) {
+ rtt = 1000 * (cur_time.tv_sec - current_ns_qsent_time.tv_sec);
+ rtt += (cur_time.tv_usec - current_ns_qsent_time.tv_usec) / 1000;
+ } else {
+ rtt = 1;
+ }
+
+ dlog("RTT: " + boost::lexical_cast<std::string>(rtt));
+ current_ns_address.updateRTT(rtt);
+
+ Message incoming(Message::PARSE);
+ InputBuffer ibuf(buffer_->getData(), buffer_->getLength());
+ incoming.fromWire(ibuf);
+
+ buffer_->clear();
+ if (recursive_mode() &&
+ incoming.getRcode() == Rcode::NOERROR()) {
+ done_ = handleRecursiveAnswer(incoming);
+ } else {
+ isc::resolve::copyResponseMessage(incoming, answer_message_);
+ done_ = true;
+ }
+
+ if (done_) {
+ stop(true);
+ }
+ } else if (!done_ && retries_--) {
+ // We timed out, but we have some retries, so send again
+ dlog("Timeout for " + question_.toText() + " to " + current_ns_address.getAddress().toText() + ", resending query");
+ if (recursive_mode()) {
+ current_ns_address.updateRTT(isc::nsas::AddressEntry::UNREACHABLE);
+ }
+ send();
+ } else {
+ // out of retries, give up for now
+ dlog("Timeout for " + question_.toText() + " to " + current_ns_address.getAddress().toText() + ", giving up");
+ if (recursive_mode()) {
+ current_ns_address.updateRTT(isc::nsas::AddressEntry::UNREACHABLE);
+ }
+ if (!answer_sent_) {
+ makeSERVFAIL();
+ }
+ stop(!answer_sent_);
+ }
+ }
+
+ // Clear the answer parts of answer_message, and set the rcode
+ // to servfail
+ void makeSERVFAIL() {
+ isc::resolve::makeErrorMessage(answer_message_, Rcode::SERVFAIL());
+ }
+
+ // Returns true if we are in 'recursive' mode
+ // Returns false if we are in 'forwarding' mode
+ // (i.e. if we have anything in upstream_)
+ bool recursive_mode() const {
+ return upstream_->empty();
+ }
+};
+
+}
+
+void
+RecursiveQuery::resolve(const QuestionPtr& question,
+ const isc::resolve::ResolverInterface::CallbackPtr callback)
+{
+ IOService& io = dns_service_.getIOService();
+
+ MessagePtr answer_message(new Message(Message::RENDER));
+ isc::resolve::initResponseMessage(*question, *answer_message);
+
+ OutputBufferPtr buffer(new OutputBuffer(0));
+
+ dlog("Asked to resolve: " + question->toText());
+
+ dlog("Try out cache first (direct call to resolve)");
+ // First try to see if we have something cached in the messagecache
+ if (cache_.lookup(question->getName(), question->getType(),
+ question->getClass(), *answer_message) &&
+ answer_message->getRRCount(Message::SECTION_ANSWER) > 0) {
+ dlog("Message found in cache, returning that");
+ // TODO: err, should cache set rcode as well?
+ answer_message->setRcode(Rcode::NOERROR());
+ callback->success(answer_message);
+ } else {
+ // Perhaps we only have the one RRset?
+ // TODO: can we do this? should we check for specific types only?
+ RRsetPtr cached_rrset = cache_.lookup(question->getName(),
+ question->getType(),
+ question->getClass());
+ if (cached_rrset) {
+ dlog("Found single RRset in cache");
+ answer_message->addRRset(Message::SECTION_ANSWER,
+ cached_rrset);
+ answer_message->setRcode(Rcode::NOERROR());
+ callback->success(answer_message);
+ } else {
+ dlog("Message not found in cache, starting recursive query");
+ // It will delete itself when it is done
+ new RunningQuery(io, *question, answer_message, upstream_,
+ buffer, callback, query_timeout_,
+ client_timeout_, lookup_timeout_, retries_,
+ nsas_, cache_);
+ }
+ }
+}
+
+void
+RecursiveQuery::resolve(const Question& question,
+ MessagePtr answer_message,
+ OutputBufferPtr buffer,
+ DNSServer* server)
+{
+ // XXX: eventually we will need to be able to determine whether
+ // the message should be sent via TCP or UDP, or sent initially via
+ // UDP and then fall back to TCP on failure, but for the moment
+ // we're only going to handle UDP.
+ IOService& io = dns_service_.getIOService();
+
+ isc::resolve::ResolverInterface::CallbackPtr crs(
+ new isc::resolve::ResolverCallbackServer(server));
+
+ // TODO: general 'prepareinitialanswer'
+ answer_message->setOpcode(isc::dns::Opcode::QUERY());
+ answer_message->addQuestion(question);
+
+ dlog("Asked to resolve: " + question.toText());
+
+ // First try to see if we have something cached in the messagecache
+ dlog("Try out cache first (started by incoming event)");
+ if (cache_.lookup(question.getName(), question.getType(),
+ question.getClass(), *answer_message) &&
+ answer_message->getRRCount(Message::SECTION_ANSWER) > 0) {
+ dlog("Message found in cache, returning that");
+ // TODO: err, should cache set rcode as well?
+ answer_message->setRcode(Rcode::NOERROR());
+ crs->success(answer_message);
+ } else {
+ // Perhaps we only have the one RRset?
+ // TODO: can we do this? should we check for specific types only?
+ RRsetPtr cached_rrset = cache_.lookup(question.getName(),
+ question.getType(),
+ question.getClass());
+ if (cached_rrset) {
+ dlog("Found single RRset in cache");
+ answer_message->addRRset(Message::SECTION_ANSWER,
+ cached_rrset);
+ answer_message->setRcode(Rcode::NOERROR());
+ crs->success(answer_message);
+ } else {
+ dlog("Message not found in cache, starting recursive query");
+ // It will delete itself when it is done
+ new RunningQuery(io, question, answer_message, upstream_,
+ buffer, crs, query_timeout_, client_timeout_,
+ lookup_timeout_, retries_, nsas_, cache_);
+ }
+ }
+}
+
+
+
+} // namespace asiolink
diff --git a/src/lib/resolve/recursive_query.h b/src/lib/resolve/recursive_query.h
new file mode 100644
index 0000000..7beae05
--- /dev/null
+++ b/src/lib/resolve/recursive_query.h
@@ -0,0 +1,119 @@
+// Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
+//
+// Permission to use, copy, modify, and/or distribute this software for any
+// purpose with or without fee is hereby granted, provided that the above
+// copyright notice and this permission notice appear in all copies.
+//
+// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
+// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+// AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
+// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
+// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+// PERFORMANCE OF THIS SOFTWARE.
+
+#ifndef __ASIOLINK_RECURSIVE_QUERY_H
+#define __ASIOLINK_RECURSIVE_QUERY_H 1
+
+#include <asiolink/dns_service.h>
+#include <asiolink/dns_server.h>
+#include <dns/buffer.h>
+#include <nsas/nameserver_address_store.h>
+#include <cache/resolver_cache.h>
+
+namespace asiolink {
+/// \brief The \c RecursiveQuery class provides a layer of abstraction around
+/// the ASIO code that carries out an upstream query.
+///
+/// This design is very preliminary; currently it is only capable of
+/// handling simple forward requests to a single resolver.
+class RecursiveQuery {
+ ///
+ /// \name Constructors
+ ///
+ //@{
+public:
+ /// \brief Constructor
+ ///
+ /// This is currently the only way to construct \c RecursiveQuery
+ /// object. If the addresses of the forward nameservers is specified,
+ /// and every upstream query will be sent to one random address, and
+ /// the result sent back directly. If not, it will do full resolving.
+ ///
+ /// \param dns_service The DNS Service to perform the recursive
+ /// query on.
+ /// \param upstream Addresses and ports of the upstream servers
+ /// to forward queries to.
+ /// \param upstream_root Addresses and ports of the root servers
+ /// to use when resolving.
+ /// \param query_timeout Timeout value for queries we sent, in ms
+ /// \param client_timeout Timeout value for when we send back an
+ /// error, in ms
+ /// \param lookup_timeout Timeout value for when we give up, in ms
+ /// \param retries how many times we try again (0 means just send and
+ /// and return if it returs).
+ RecursiveQuery(DNSService& dns_service,
+ isc::nsas::NameserverAddressStore& nsas,
+ isc::cache::ResolverCache& cache,
+ const std::vector<std::pair<std::string, uint16_t> >&
+ upstream,
+ const std::vector<std::pair<std::string, uint16_t> >&
+ upstream_root,
+ int query_timeout = 2000,
+ int client_timeout = 4000,
+ int lookup_timeout = 30000,
+ unsigned retries = 3);
+ //@}
+
+ /// \brief Initiate resolving
+ ///
+ /// When sendQuery() is called, a (set of) message(s) is sent
+ /// asynchronously. If upstream servers are set, one is chosen
+ /// and the response (if any) from that server will be returned.
+ ///
+ /// If not upstream is set, a root server is chosen from the
+ /// root_servers, and the RunningQuery shall do a full resolve
+ /// (i.e. if the answer is a delegation, it will be followed, etc.)
+ /// until there is an answer or an error.
+ ///
+ /// When there is a response or an error and we give up, the given
+ /// CallbackPtr object shall be called (with either success() or
+ /// failure(). See ResolverInterface::Callback for more information.
+ ///
+ /// \param question The question being answered <qname/qclass/qtype>
+ /// \param callback Callback object. See
+ /// \c ResolverInterface::Callback for more information
+ void resolve(const isc::dns::QuestionPtr& question,
+ const isc::resolve::ResolverInterface::CallbackPtr callback);
+
+
+ /// \brief Initiates resolving for the given question.
+ ///
+ /// This actually calls the previous sendQuery() with a default
+ /// callback object, which calls resume() on the given DNSServer
+ /// object.
+ ///
+ /// \param question The question being answered <qname/qclass/qtype>
+ /// \param answer_message An output Message into which the final response will be copied
+ /// \param buffer An output buffer into which the intermediate responses will be copied
+ /// \param server A pointer to the \c DNSServer object handling the client
+ void resolve(const isc::dns::Question& question,
+ isc::dns::MessagePtr answer_message,
+ isc::dns::OutputBufferPtr buffer,
+ DNSServer* server);
+private:
+ DNSService& dns_service_;
+ isc::nsas::NameserverAddressStore& nsas_;
+ isc::cache::ResolverCache& cache_;
+ boost::shared_ptr<std::vector<std::pair<std::string, uint16_t> > >
+ upstream_;
+ boost::shared_ptr<std::vector<std::pair<std::string, uint16_t> > >
+ upstream_root_;
+ int query_timeout_;
+ int client_timeout_;
+ int lookup_timeout_;
+ unsigned retries_;
+};
+
+} // namespace asiolink
+#endif // __ASIOLINK_RECURSIVE_QUERY_H
diff --git a/src/lib/resolve/tests/Makefile.am b/src/lib/resolve/tests/Makefile.am
index e669384..249b17c 100644
--- a/src/lib/resolve/tests/Makefile.am
+++ b/src/lib/resolve/tests/Makefile.am
@@ -14,12 +14,18 @@ TESTS += run_unittests
run_unittests_CPPFLAGS = $(AM_CPPFLAGS) $(GTEST_INCLUDES)
run_unittests_LDFLAGS = $(AM_LDFLAGS) $(GTEST_LDFLAGS)
run_unittests_SOURCES = run_unittests.cc
+run_unittests_SOURCES += $(top_srcdir)/src/lib/dns/tests/unittest_util.h
+run_unittests_SOURCES += $(top_srcdir)/src/lib/dns/tests/unittest_util.cc
run_unittests_SOURCES += resolve_unittest.cc
run_unittests_SOURCES += resolver_callback_unittest.cc
run_unittests_SOURCES += response_classifier_unittest.cc
+run_unittests_SOURCES += recursive_query_unittest.cc
run_unittests_LDADD = $(GTEST_LDADD)
run_unittests_LDADD += $(top_builddir)/src/lib/exceptions/libexceptions.la
+run_unittests_LDADD += $(top_builddir)/src/lib/nsas/libnsas.la
+run_unittests_LDADD += $(top_builddir)/src/lib/cache/libcache.la
+run_unittests_LDADD += $(top_builddir)/src/lib/asiolink/libasiolink.la
run_unittests_LDADD += $(top_builddir)/src/lib/resolve/libresolve.la
run_unittests_LDADD += $(top_builddir)/src/lib/dns/libdns++.la
diff --git a/src/lib/resolve/tests/recursive_query_unittest.cc b/src/lib/resolve/tests/recursive_query_unittest.cc
new file mode 100644
index 0000000..4d9ee30
--- /dev/null
+++ b/src/lib/resolve/tests/recursive_query_unittest.cc
@@ -0,0 +1,814 @@
+// Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
+//
+// Permission to use, copy, modify, and/or distribute this software for any
+// purpose with or without fee is hereby granted, provided that the above
+// copyright notice and this permission notice appear in all copies.
+//
+// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
+// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+// AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
+// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
+// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+// PERFORMANCE OF THIS SOFTWARE.
+
+#include <config.h>
+
+#include <sys/socket.h>
+#include <sys/time.h>
+
+#include <string.h>
+
+#include <boost/lexical_cast.hpp>
+#include <boost/bind.hpp>
+#include <boost/date_time/posix_time/posix_time_types.hpp>
+
+#include <gtest/gtest.h>
+
+#include <exceptions/exceptions.h>
+
+#include <dns/tests/unittest_util.h>
+#include <dns/rcode.h>
+
+#include <dns/buffer.h>
+#include <dns/message.h>
+
+#include <nsas/nameserver_address_store.h>
+#include <cache/resolver_cache.h>
+
+// IMPORTANT: We shouldn't directly use ASIO definitions in this test.
+// In particular, we must not include asio.hpp in this file.
+// The asiolink module is primarily intended to be a wrapper that hide the
+// details of the underlying implementations. We need to test the wrapper
+// level behaviors. In addition, some compilers reject to compile this file
+// if we include asio.hpp unless we specify a special compiler option.
+// If we need to test something at the level of underlying ASIO and need
+// their definition, that test should go to asiolink/internal/tests.
+#include <resolve/recursive_query.h>
+#include <asiolink/io_socket.h>
+#include <asiolink/io_service.h>
+#include <asiolink/io_message.h>
+#include <asiolink/io_error.h>
+#include <asiolink/dns_lookup.h>
+#include <asiolink/simple_callback.h>
+
+using isc::UnitTestUtil;
+using namespace std;
+using namespace asiolink;
+using namespace isc::dns;
+
+namespace {
+const char* const TEST_SERVER_PORT = "53535";
+const char* const TEST_CLIENT_PORT = "53536";
+const char* const TEST_IPV6_ADDR = "::1";
+const char* const TEST_IPV4_ADDR = "127.0.0.1";
+// This data is intended to be valid as a DNS/TCP-like message: the first
+// two octets encode the length of the rest of the data. This is crucial
+// for the tests below.
+const uint8_t test_data[] = {0, 4, 1, 2, 3, 4};
+
+// This function returns an addrinfo structure for use by tests, using
+// different addresses and ports depending on whether we're testing
+// IPv4 or v6, TCP or UDP, and client or server operation.
+struct addrinfo*
+resolveAddress(const int family, const int protocol, const bool client) {
+ const char* const addr = (family == AF_INET6) ?
+ TEST_IPV6_ADDR : TEST_IPV4_ADDR;
+ const char* const port = client ? TEST_CLIENT_PORT : TEST_SERVER_PORT;
+
+ struct addrinfo hints;
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = family;
+ hints.ai_socktype = (protocol == IPPROTO_UDP) ? SOCK_DGRAM : SOCK_STREAM;
+ hints.ai_protocol = protocol;
+ hints.ai_flags = AI_NUMERICSERV;
+
+ struct addrinfo* res;
+ const int error = getaddrinfo(addr, port, &hints, &res);
+ if (error != 0) {
+ isc_throw(IOError, "getaddrinfo failed: " << gai_strerror(error));
+ }
+
+ return (res);
+}
+
+// This fixture is a framework for various types of network operations
+// using the ASIO interfaces. Each test case creates an IOService object,
+// opens a local "client" socket for testing, sends data via the local socket
+// to the service that would run in the IOService object.
+// A mock callback function (an ASIOCallBack object) is registered with the
+// IOService object, so the test code should be able to examine the data
+// received on the server side. It then checks the received data matches
+// expected parameters.
+// If initialization parameters of the IOService should be modified, the test
+// case can do it using the setDNSService() method.
+// Note: the set of tests in RecursiveQueryTest use actual network services and may
+// involve undesirable side effects such as blocking.
+class RecursiveQueryTest : public ::testing::Test {
+protected:
+ RecursiveQueryTest();
+ ~RecursiveQueryTest() {
+ if (res_ != NULL) {
+ freeaddrinfo(res_);
+ }
+ if (sock_ != -1) {
+ close(sock_);
+ }
+ delete dns_service_;
+ delete callback_;
+ delete io_service_;
+ }
+
+ // Send a test UDP packet to a mock server
+ void sendUDP(const int family) {
+ res_ = resolveAddress(family, IPPROTO_UDP, false);
+
+ sock_ = socket(res_->ai_family, res_->ai_socktype, res_->ai_protocol);
+ if (sock_ < 0) {
+ isc_throw(IOError, "failed to open test socket");
+ }
+ const int cc = sendto(sock_, test_data, sizeof(test_data), 0,
+ res_->ai_addr, res_->ai_addrlen);
+ if (cc != sizeof(test_data)) {
+ isc_throw(IOError, "unexpected sendto result: " << cc);
+ }
+ io_service_->run();
+ }
+
+ // Send a test TCP packet to a mock server
+ void sendTCP(const int family) {
+ res_ = resolveAddress(family, IPPROTO_TCP, false);
+
+ sock_ = socket(res_->ai_family, res_->ai_socktype, res_->ai_protocol);
+ if (sock_ < 0) {
+ isc_throw(IOError, "failed to open test socket");
+ }
+ if (connect(sock_, res_->ai_addr, res_->ai_addrlen) < 0) {
+ isc_throw(IOError, "failed to connect to the test server");
+ }
+ const int cc = send(sock_, test_data, sizeof(test_data), 0);
+ if (cc != sizeof(test_data)) {
+ isc_throw(IOError, "unexpected send result: " << cc);
+ }
+ io_service_->run();
+ }
+
+ // Receive a UDP packet from a mock server; used for testing
+ // recursive lookup. The caller must place a RecursiveQuery
+ // on the IO Service queue before running this routine.
+ void recvUDP(const int family, void* buffer, size_t& size) {
+ res_ = resolveAddress(family, IPPROTO_UDP, true);
+
+ sock_ = socket(res_->ai_family, res_->ai_socktype, res_->ai_protocol);
+ if (sock_ < 0) {
+ isc_throw(IOError, "failed to open test socket");
+ }
+
+ if (bind(sock_, res_->ai_addr, res_->ai_addrlen) < 0) {
+ isc_throw(IOError, "bind failed: " << strerror(errno));
+ }
+
+ // The IO service queue should have a RecursiveQuery object scheduled
+ // to run at this point. This call will cause it to begin an
+ // async send, then return.
+ io_service_->run_one();
+
+ // ... and this one will block until the send has completed
+ io_service_->run_one();
+
+ // Now we attempt to recv() whatever was sent.
+ // XXX: there's no guarantee the receiving socket can immediately get
+ // the packet. Normally we can perform blocking recv to wait for it,
+ // but in theory it's even possible that the packet is lost.
+ // In order to prevent the test from hanging in such a worst case
+ // we add an ad hoc timeout.
+ const struct timeval timeo = { 10, 0 };
+ int recv_options = 0;
+ if (setsockopt(sock_, SOL_SOCKET, SO_RCVTIMEO, &timeo,
+ sizeof(timeo))) {
+ if (errno == ENOPROTOOPT) {
+ // Workaround for Solaris: it doesn't accept SO_RCVTIMEO
+ // with the error of ENOPROTOOPT. Since this is a workaround
+ // for rare error cases anyway, we simply switch to the
+ // "don't wait" mode. If we still find an error in recv()
+ // can happen often we'll consider a more complete solution.
+ recv_options = MSG_DONTWAIT;
+ } else {
+ isc_throw(IOError, "set RCVTIMEO failed: " << strerror(errno));
+ }
+ }
+ const int ret = recv(sock_, buffer, size, recv_options);
+ if (ret < 0) {
+ isc_throw(IOError, "recvfrom failed: " << strerror(errno));
+ }
+
+ // Pass the message size back via the size parameter
+ size = ret;
+ }
+
+
+ // Set up an IO Service queue using the specified address
+ void setDNSService(const char& address) {
+ delete dns_service_;
+ dns_service_ = NULL;
+ delete io_service_;
+ io_service_ = new IOService();
+ callback_ = new ASIOCallBack(this);
+ dns_service_ = new DNSService(*io_service_, *TEST_SERVER_PORT, address, callback_, NULL, NULL);
+ }
+
+ // Set up an IO Service queue using the "any" address, on IPv4 if
+ // 'use_ipv4' is true and on IPv6 if 'use_ipv6' is true.
+ void setDNSService(const bool use_ipv4, const bool use_ipv6) {
+ delete dns_service_;
+ dns_service_ = NULL;
+ delete io_service_;
+ io_service_ = new IOService();
+ callback_ = new ASIOCallBack(this);
+ dns_service_ = new DNSService(*io_service_, *TEST_SERVER_PORT, use_ipv4, use_ipv6, callback_,
+ NULL, NULL);
+ }
+
+ // Set up empty DNS Service
+ // Set up an IO Service queue without any addresses
+ void setDNSService() {
+ delete dns_service_;
+ dns_service_ = NULL;
+ delete io_service_;
+ io_service_ = new IOService();
+ callback_ = new ASIOCallBack(this);
+ dns_service_ = new DNSService(*io_service_, callback_, NULL, NULL);
+ }
+
+ // Run a simple server test, on either IPv4 or IPv6, and over either
+ // UDP or TCP. Calls the sendUDP() or sendTCP() methods, which will
+ // start the IO Service queue. The UDPServer or TCPServer that was
+ // created by setIOService() will receive the test packet and issue a
+ // callback, which enables us to check that the data it received
+ // matches what we sent.
+ void doTest(const int family, const int protocol) {
+ if (protocol == IPPROTO_UDP) {
+ sendUDP(family);
+ } else {
+ sendTCP(family);
+ }
+
+ // There doesn't seem to be an effective test for the validity of
+ // 'native'.
+ // One thing we are sure is it must be different from our local socket.
+ EXPECT_NE(sock_, callback_native_);
+ EXPECT_EQ(protocol, callback_protocol_);
+ EXPECT_EQ(family == AF_INET6 ? TEST_IPV6_ADDR : TEST_IPV4_ADDR,
+ callback_address_);
+
+ const uint8_t* expected_data =
+ protocol == IPPROTO_UDP ? test_data : test_data + 2;
+ const size_t expected_datasize =
+ protocol == IPPROTO_UDP ? sizeof(test_data) :
+ sizeof(test_data) - 2;
+ EXPECT_PRED_FORMAT4(UnitTestUtil::matchWireData, &callback_data_[0],
+ callback_data_.size(),
+ expected_data, expected_datasize);
+ }
+
+protected:
+ // This is a nonfunctional mockup of a DNSServer object. Its purpose
+ // is to resume after a recursive query or other asynchronous call
+ // has completed.
+ class MockServer : public DNSServer {
+ public:
+ explicit MockServer(IOService& io_service,
+ SimpleCallback* checkin = NULL,
+ DNSLookup* lookup = NULL,
+ DNSAnswer* answer = NULL) :
+ io_(io_service),
+ message_(new Message(Message::PARSE)),
+ answer_message_(new Message(Message::RENDER)),
+ respbuf_(new OutputBuffer(0)),
+ checkin_(checkin), lookup_(lookup), answer_(answer)
+ {}
+
+ void operator()(asio::error_code ec = asio::error_code(),
+ size_t length = 0)
+ {}
+
+ void resume(const bool) {
+ // should never be called in our tests
+ }
+
+ DNSServer* clone() {
+ MockServer* s = new MockServer(*this);
+ return (s);
+ }
+
+ inline void asyncLookup() {
+ if (lookup_) {
+ (*lookup_)(*io_message_, message_, answer_message_,
+ respbuf_, this);
+ }
+ }
+
+ protected:
+ IOService& io_;
+ bool done_;
+
+ private:
+ // Currently unused; these will be used for testing
+ // asynchronous lookup calls via the asyncLookup() method
+ boost::shared_ptr<asiolink::IOMessage> io_message_;
+ isc::dns::MessagePtr message_;
+ isc::dns::MessagePtr answer_message_;
+ isc::dns::OutputBufferPtr respbuf_;
+
+ // Callback functions provided by the caller
+ const SimpleCallback* checkin_;
+ const DNSLookup* lookup_;
+ const DNSAnswer* answer_;
+ };
+
+ // This version of mock server just stops the io_service when it is resumed
+ class MockServerStop : public MockServer {
+ public:
+ explicit MockServerStop(IOService& io_service, bool* done) :
+ MockServer(io_service),
+ done_(done)
+ {}
+
+ void resume(const bool done) {
+ std::cout << "[XX] RESUME!" << std::endl;
+ *done_ = done;
+ io_.stop();
+ }
+
+ DNSServer* clone() {
+ return (new MockServerStop(*this));
+ }
+ private:
+ bool* done_;
+ };
+
+ class MockResolver : public isc::resolve::ResolverInterface {
+ void resolve(const QuestionPtr& question,
+ const ResolverInterface::CallbackPtr& callback) {
+ }
+ };
+
+ // This version of mock server just stops the io_service when it is resumed
+ // the second time. (Used in the clientTimeout test, where resume
+ // is called initially with the error answer, and later when the
+ // lookup times out, it is called without an answer to send back)
+ class MockServerStop2 : public MockServer {
+ public:
+ explicit MockServerStop2(IOService& io_service,
+ bool* done1, bool* done2) :
+ MockServer(io_service),
+ done1_(done1),
+ done2_(done2),
+ stopped_once_(false)
+ {}
+
+ void resume(const bool done) {
+ if (stopped_once_) {
+ *done2_ = done;
+ io_.stop();
+ } else {
+ *done1_ = done;
+ stopped_once_ = true;
+ }
+ }
+
+ DNSServer* clone() {
+ return (new MockServerStop2(*this));
+ }
+ private:
+ bool* done1_;
+ bool* done2_;
+ bool stopped_once_;
+ };
+
+private:
+ class ASIOCallBack : public SimpleCallback {
+ public:
+ ASIOCallBack(RecursiveQueryTest* test_obj) : test_obj_(test_obj) {}
+ void operator()(const IOMessage& io_message) const {
+ test_obj_->callBack(io_message);
+ }
+ private:
+ RecursiveQueryTest* test_obj_;
+ };
+ void callBack(const IOMessage& io_message) {
+ callback_protocol_ = io_message.getSocket().getProtocol();
+ callback_native_ = io_message.getSocket().getNative();
+ callback_address_ =
+ io_message.getRemoteEndpoint().getAddress().toText();
+ callback_data_.assign(
+ static_cast<const uint8_t*>(io_message.getData()),
+ static_cast<const uint8_t*>(io_message.getData()) +
+ io_message.getDataSize());
+ io_service_->stop();
+ }
+protected:
+ // We use a pointer for io_service_, because for some tests we
+ // need to recreate a new one within one onstance of this class
+ IOService* io_service_;
+ DNSService* dns_service_;
+ isc::nsas::NameserverAddressStore* nsas_;
+ isc::cache::ResolverCache cache_;
+ ASIOCallBack* callback_;
+ int callback_protocol_;
+ int callback_native_;
+ string callback_address_;
+ vector<uint8_t> callback_data_;
+ int sock_;
+ struct addrinfo* res_;
+};
+
+RecursiveQueryTest::RecursiveQueryTest() :
+ dns_service_(NULL), callback_(NULL), sock_(-1), res_(NULL)
+{
+ io_service_ = new IOService();
+ setDNSService(true, true);
+ boost::shared_ptr<MockResolver>mock_resolver(new MockResolver());
+ nsas_ = new isc::nsas::NameserverAddressStore(mock_resolver);
+}
+
+TEST_F(RecursiveQueryTest, v6UDPSend) {
+ doTest(AF_INET6, IPPROTO_UDP);
+}
+
+TEST_F(RecursiveQueryTest, v6TCPSend) {
+ doTest(AF_INET6, IPPROTO_TCP);
+}
+
+TEST_F(RecursiveQueryTest, v4UDPSend) {
+ doTest(AF_INET, IPPROTO_UDP);
+}
+
+TEST_F(RecursiveQueryTest, v4TCPSend) {
+ doTest(AF_INET, IPPROTO_TCP);
+}
+
+TEST_F(RecursiveQueryTest, v6UDPSendSpecific) {
+ // Explicitly set a specific address to be bound to the socket.
+ // The subsequent test does not directly ensures the underlying socket
+ // is bound to the expected address, but the success of the tests should
+ // reasonably suggest it works as intended.
+ // Specifying an address also implicitly means the service runs in a
+ // single address-family mode. In tests using TCP we can confirm that
+ // by trying to make a connection and seeing a failure. In UDP, it'd be
+ // more complicated because we need to use a connected socket and catch
+ // an error on a subsequent read operation. We could do it, but for
+ // simplicity we only tests the easier cases for now.
+
+ setDNSService(*TEST_IPV6_ADDR);
+ doTest(AF_INET6, IPPROTO_UDP);
+}
+
+TEST_F(RecursiveQueryTest, v6TCPSendSpecific) {
+ setDNSService(*TEST_IPV6_ADDR);
+ doTest(AF_INET6, IPPROTO_TCP);
+
+ EXPECT_THROW(sendTCP(AF_INET), IOError);
+}
+
+TEST_F(RecursiveQueryTest, v4UDPSendSpecific) {
+ setDNSService(*TEST_IPV4_ADDR);
+ doTest(AF_INET, IPPROTO_UDP);
+}
+
+TEST_F(RecursiveQueryTest, v4TCPSendSpecific) {
+ setDNSService(*TEST_IPV4_ADDR);
+ doTest(AF_INET, IPPROTO_TCP);
+
+ EXPECT_THROW(sendTCP(AF_INET6), IOError);
+}
+
+TEST_F(RecursiveQueryTest, v6AddServer) {
+ setDNSService();
+ dns_service_->addServer(*TEST_SERVER_PORT, TEST_IPV6_ADDR);
+ doTest(AF_INET6, IPPROTO_TCP);
+
+ EXPECT_THROW(sendTCP(AF_INET), IOError);
+}
+
+TEST_F(RecursiveQueryTest, v4AddServer) {
+ setDNSService();
+ dns_service_->addServer(*TEST_SERVER_PORT, TEST_IPV4_ADDR);
+ doTest(AF_INET, IPPROTO_TCP);
+
+ EXPECT_THROW(sendTCP(AF_INET6), IOError);
+}
+
+TEST_F(RecursiveQueryTest, clearServers) {
+ setDNSService();
+ dns_service_->clearServers();
+
+ EXPECT_THROW(sendTCP(AF_INET), IOError);
+ EXPECT_THROW(sendTCP(AF_INET6), IOError);
+}
+
+TEST_F(RecursiveQueryTest, v6TCPOnly) {
+ // Open only IPv6 TCP socket. A subsequent attempt of establishing an
+ // IPv4/TCP connection should fail. See above for why we only test this
+ // for TCP.
+ setDNSService(false, true);
+ EXPECT_THROW(sendTCP(AF_INET), IOError);
+}
+
+TEST_F(RecursiveQueryTest, v4TCPOnly) {
+ setDNSService(true, false);
+ EXPECT_THROW(sendTCP(AF_INET6), IOError);
+}
+
+vector<pair<string, uint16_t> >
+singleAddress(const string &address, uint16_t port) {
+ vector<pair<string, uint16_t> > result;
+ result.push_back(pair<string, uint16_t>(address, port));
+ return (result);
+}
+
+TEST_F(RecursiveQueryTest, recursiveSetupV4) {
+ setDNSService(true, false);
+ uint16_t port = boost::lexical_cast<uint16_t>(TEST_CLIENT_PORT);
+ EXPECT_NO_THROW(RecursiveQuery(*dns_service_,
+ *nsas_, cache_,
+ singleAddress(TEST_IPV4_ADDR, port),
+ singleAddress(TEST_IPV4_ADDR, port)));
+}
+
+TEST_F(RecursiveQueryTest, recursiveSetupV6) {
+ setDNSService(false, true);
+ uint16_t port = boost::lexical_cast<uint16_t>(TEST_CLIENT_PORT);
+ EXPECT_NO_THROW(RecursiveQuery(*dns_service_,
+ *nsas_, cache_,
+ singleAddress(TEST_IPV6_ADDR, port),
+ singleAddress(TEST_IPV6_ADDR,port)));
+}
+
+// XXX:
+// This is very inadequate unit testing. It should be generalized into
+// a routine that can do this with variable address family, address, and
+// port, and with the various callbacks defined in such a way as to ensure
+// full code coverage including error cases.
+TEST_F(RecursiveQueryTest, forwarderSend) {
+ setDNSService(true, false);
+
+ // Note: We use the test prot plus one to ensure we aren't binding
+ // to the same port as the actual server
+ uint16_t port = boost::lexical_cast<uint16_t>(TEST_CLIENT_PORT);
+
+ MockServer server(*io_service_);
+ RecursiveQuery rq(*dns_service_,
+ *nsas_, cache_,
+ singleAddress(TEST_IPV4_ADDR, port),
+ singleAddress(TEST_IPV4_ADDR, port));
+
+ Question q(Name("example.com"), RRClass::IN(), RRType::TXT());
+ OutputBufferPtr buffer(new OutputBuffer(0));
+ MessagePtr answer(new Message(Message::RENDER));
+ rq.resolve(q, answer, buffer, &server);
+
+ char data[4096];
+ size_t size = sizeof(data);
+ ASSERT_NO_THROW(recvUDP(AF_INET, data, size));
+
+ Message m(Message::PARSE);
+ InputBuffer ibuf(data, size);
+
+ // Make sure we can parse the message that was sent
+ EXPECT_NO_THROW(m.parseHeader(ibuf));
+ EXPECT_NO_THROW(m.fromWire(ibuf));
+
+ // Check that the question sent matches the one we wanted
+ QuestionPtr q2 = *m.beginQuestion();
+ EXPECT_EQ(q.getName(), q2->getName());
+ EXPECT_EQ(q.getType(), q2->getType());
+ EXPECT_EQ(q.getClass(), q2->getClass());
+}
+
+int
+createTestSocket()
+{
+ struct addrinfo* res_ = resolveAddress(AF_INET, IPPROTO_UDP, true);
+ int sock_ = socket(res_->ai_family, res_->ai_socktype, res_->ai_protocol);
+ if (sock_ < 0) {
+ isc_throw(IOError, "failed to open test socket");
+ }
+ if (bind(sock_, res_->ai_addr, res_->ai_addrlen) < 0) {
+ isc_throw(IOError, "failed to bind test socket");
+ }
+ return sock_;
+}
+
+int
+setSocketTimeout(int sock_, size_t tv_sec, size_t tv_usec) {
+ const struct timeval timeo = { tv_sec, tv_usec };
+ int recv_options = 0;
+ if (setsockopt(sock_, SOL_SOCKET, SO_RCVTIMEO, &timeo, sizeof(timeo))) {
+ if (errno == ENOPROTOOPT) { // see RecursiveQueryTest::recvUDP()
+ recv_options = MSG_DONTWAIT;
+ } else {
+ isc_throw(IOError, "set RCVTIMEO failed: " << strerror(errno));
+ }
+ }
+ return recv_options;
+}
+
+// try to read from the socket max time
+// *num is incremented for every succesfull read
+// returns true if it can read max times, false otherwise
+bool tryRead(int sock_, int recv_options, size_t max, int* num) {
+ size_t i = 0;
+ do {
+ char inbuff[512];
+ if (recv(sock_, inbuff, sizeof(inbuff), recv_options) < 0) {
+ return false;
+ } else {
+ ++i;
+ ++*num;
+ }
+ } while (i < max);
+ return true;
+}
+
+
+// Test it tries the correct amount of times before giving up
+TEST_F(RecursiveQueryTest, forwardQueryTimeout) {
+ // Prepare the service (we do not use the common setup, we do not answer
+ setDNSService();
+
+ // Prepare the socket
+ sock_ = createTestSocket();
+
+ // Prepare the server
+ bool done(true);
+ MockServerStop server(*io_service_, &done);
+
+ // Do the answer
+ const uint16_t port = boost::lexical_cast<uint16_t>(TEST_CLIENT_PORT);
+ RecursiveQuery query(*dns_service_,
+ *nsas_, cache_,
+ singleAddress(TEST_IPV4_ADDR, port),
+ singleAddress(TEST_IPV4_ADDR, port),
+ 10, 4000, 3000, 2);
+ Question question(Name("example.net"), RRClass::IN(), RRType::A());
+ OutputBufferPtr buffer(new OutputBuffer(0));
+ MessagePtr answer(new Message(Message::RENDER));
+ query.resolve(question, answer, buffer, &server);
+
+ // Run the test
+ io_service_->run();
+
+ // Read up to 3 packets. Use some ad hoc timeout to prevent an infinite
+ // block (see also recvUDP()).
+ int recv_options = setSocketTimeout(sock_, 10, 0);
+ int num = 0;
+ bool read_success = tryRead(sock_, recv_options, 3, &num);
+
+ // The query should 'succeed' with an error response
+ EXPECT_TRUE(done);
+ EXPECT_EQ(3, num);
+ EXPECT_TRUE(read_success);
+}
+
+// If we set client timeout to lower than querytimeout, we should
+// get a failure answer, but still see retries
+// (no actual answer is given here yet)
+TEST_F(RecursiveQueryTest, forwardClientTimeout) {
+ // Prepare the service (we do not use the common setup, we do not answer
+ setDNSService();
+
+ sock_ = createTestSocket();
+
+ // Prepare the server
+ bool done1(true);
+ MockServerStop server(*io_service_, &done1);
+
+ MessagePtr answer(new Message(Message::RENDER));
+
+ // Do the answer
+ const uint16_t port = boost::lexical_cast<uint16_t>(TEST_CLIENT_PORT);
+ // Set it up to retry twice before client timeout fires
+ // Since the lookup timer has not fired, it should retry
+ // four times
+ RecursiveQuery query(*dns_service_,
+ *nsas_, cache_,
+ singleAddress(TEST_IPV4_ADDR, port),
+ singleAddress(TEST_IPV4_ADDR, port),
+ 200, 480, 4000, 4);
+ Question question(Name("example.net"), RRClass::IN(), RRType::A());
+ OutputBufferPtr buffer(new OutputBuffer(0));
+ query.resolve(question, answer, buffer, &server);
+
+ // Run the test
+ io_service_->run();
+
+ // we know it'll fail, so make it a shorter timeout
+ int recv_options = setSocketTimeout(sock_, 1, 0);
+
+ // Try to read 4 times
+ int num = 0;
+ bool read_success = tryRead(sock_, recv_options, 4, &num);
+
+ // The query should fail
+ EXPECT_TRUE(done1);
+ EXPECT_EQ(3, num);
+ EXPECT_FALSE(read_success);
+}
+
+// If we set lookup timeout to lower than querytimeout*retries, we should
+// fail before the full amount of retries
+TEST_F(RecursiveQueryTest, forwardLookupTimeout) {
+ // Prepare the service (we do not use the common setup, we do not answer
+ setDNSService();
+
+ // Prepare the socket
+ sock_ = createTestSocket();
+
+ // Prepare the server
+ bool done(true);
+ MockServerStop server(*io_service_, &done);
+
+ MessagePtr answer(new Message(Message::RENDER));
+
+ // Do the answer
+ const uint16_t port = boost::lexical_cast<uint16_t>(TEST_CLIENT_PORT);
+ // Set up the test so that it will retry 5 times, but the lookup
+ // timeout will fire after only 3 normal timeouts
+ RecursiveQuery query(*dns_service_,
+ *nsas_, cache_,
+ singleAddress(TEST_IPV4_ADDR, port),
+ singleAddress(TEST_IPV4_ADDR, port),
+ 200, 4000, 480, 5);
+ Question question(Name("example.net"), RRClass::IN(), RRType::A());
+ OutputBufferPtr buffer(new OutputBuffer(0));
+ query.resolve(question, answer, buffer, &server);
+
+ // Run the test
+ io_service_->run();
+
+ int recv_options = setSocketTimeout(sock_, 1, 0);
+
+ // Try to read 5 times, should stop after 3 reads
+ int num = 0;
+ bool read_success = tryRead(sock_, recv_options, 5, &num);
+
+ // The query should fail
+ EXPECT_FALSE(done);
+ EXPECT_EQ(3, num);
+ EXPECT_FALSE(read_success);
+}
+
+// as mentioned above, we need a more better framework for this,
+// in addition to that, this sends out queries into the world
+// (which we should catch somehow and fake replies for)
+// for the skeleton code, it shouldn't be too much of a problem
+// Ok so even we don't all have access to the DNS world right now,
+// so disabling these tests too.
+TEST_F(RecursiveQueryTest, DISABLED_recursiveSendOk) {
+ setDNSService(true, false);
+ bool done;
+
+ MockServerStop server(*io_service_, &done);
+ vector<pair<string, uint16_t> > empty_vector;
+ RecursiveQuery rq(*dns_service_, *nsas_, cache_, empty_vector,
+ empty_vector, 10000, 0);
+
+ Question q(Name("www.isc.org"), RRClass::IN(), RRType::A());
+ OutputBufferPtr buffer(new OutputBuffer(0));
+ MessagePtr answer(new Message(Message::RENDER));
+ rq.resolve(q, answer, buffer, &server);
+ io_service_->run();
+
+ // Check that the answer we got matches the one we wanted
+ EXPECT_EQ(Rcode::NOERROR(), answer->getRcode());
+ ASSERT_EQ(1, answer->getRRCount(Message::SECTION_ANSWER));
+ RRsetPtr a = *answer->beginSection(Message::SECTION_ANSWER);
+ EXPECT_EQ(q.getName(), a->getName());
+ EXPECT_EQ(q.getType(), a->getType());
+ EXPECT_EQ(q.getClass(), a->getClass());
+ EXPECT_EQ(1, a->getRdataCount());
+}
+
+// see comments at previous test
+TEST_F(RecursiveQueryTest, DISABLED_recursiveSendNXDOMAIN) {
+ setDNSService(true, false);
+ bool done;
+
+ MockServerStop server(*io_service_, &done);
+ vector<pair<string, uint16_t> > empty_vector;
+ RecursiveQuery rq(*dns_service_, *nsas_, cache_, empty_vector,
+ empty_vector, 10000, 0);
+
+ Question q(Name("wwwdoesnotexist.isc.org"), RRClass::IN(), RRType::A());
+ OutputBufferPtr buffer(new OutputBuffer(0));
+ MessagePtr answer(new Message(Message::RENDER));
+ rq.resolve(q, answer, buffer, &server);
+ io_service_->run();
+
+ // Check that the answer we got matches the one we wanted
+ EXPECT_EQ(Rcode::NXDOMAIN(), answer->getRcode());
+ EXPECT_EQ(0, answer->getRRCount(Message::SECTION_ANSWER));
+}
+
+}
More information about the bind10-changes
mailing list