util: Add DNS resolver utility class

refs: #1918

Change-Id: Ia393498febfb8e3a7473d5390ba6a378be71f412
diff --git a/src/util/dns.cpp b/src/util/dns.cpp
new file mode 100644
index 0000000..8df097f
--- /dev/null
+++ b/src/util/dns.cpp
@@ -0,0 +1,167 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2014 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#include "dns.hpp"
+
+#include "scheduler.hpp"
+
+namespace ndn {
+namespace dns {
+
+typedef boost::asio::ip::udp::endpoint EndPoint;
+typedef boost::asio::ip::basic_resolver<boost::asio::ip::udp> BoostResolver;
+
+class Resolver : noncopyable
+{
+public:
+  Resolver(const SuccessCallback& onSuccess,
+           const ErrorCallback& onError,
+           const ndn::dns::AddressSelector& addressSelector,
+           boost::asio::io_service& ioService)
+    : m_resolver(ioService)
+    , m_addressSelector(addressSelector)
+    , m_onSuccess(onSuccess)
+    , m_onError(onError)
+    , m_scheduler(ioService)
+  {
+  }
+
+  void
+  asyncResolve(const std::string& host,
+               const time::nanoseconds& timeout,
+               const shared_ptr<Resolver>& self)
+  {
+    BoostResolver::query query(host, NULL_PORT
+
+#if not defined(__FreeBSD__)
+                               , BoostResolver::query::all_matching
+#endif
+                               );
+
+    m_resolver.async_resolve(query, bind(&Resolver::onResolveSuccess, this, _1, _2, self));
+
+    m_resolveTimeout = m_scheduler.scheduleEvent(timeout,
+                                                 bind(&Resolver::onResolveError, this,
+                                                 "Timeout", self));
+  }
+
+  BoostResolver::iterator
+  syncResolve(BoostResolver::query query)
+  {
+    return m_resolver.resolve(query);
+  }
+
+  void
+  onResolveSuccess(const boost::system::error_code& error,
+                   BoostResolver::iterator remoteEndpoint,
+                   const shared_ptr<Resolver>& self)
+  {
+    m_scheduler.cancelEvent(m_resolveTimeout);
+
+    if (error)
+      {
+        if (error == boost::system::errc::operation_canceled)
+          {
+            return;
+          }
+
+        return m_onError("Remote endpoint hostname or port cannot be resolved: " +
+                         error.category().message(error.value()));
+      }
+
+    BoostResolver::iterator end;
+    for (; remoteEndpoint != end; ++remoteEndpoint)
+      {
+        IpAddress address(EndPoint(*remoteEndpoint).address());
+
+        if (m_addressSelector(address))
+          {
+            return m_onSuccess(address);
+          }
+      }
+
+    m_onError("No endpoint matching the specified address selector found");
+  }
+
+  void
+  onResolveError(const std::string& errorInfo, const shared_ptr<Resolver>& self)
+  {
+    m_resolver.cancel();
+    m_onError(errorInfo);
+  }
+
+public:
+  static const std::string NULL_PORT;
+
+private:
+  BoostResolver m_resolver;
+  EventId m_resolveTimeout;
+
+  ndn::dns::AddressSelector m_addressSelector;
+  SuccessCallback m_onSuccess;
+  ErrorCallback m_onError;
+
+  Scheduler m_scheduler;
+};
+
+const std::string Resolver::NULL_PORT = "";
+
+void
+asyncResolve(const std::string& host,
+             const SuccessCallback& onSuccess,
+             const ErrorCallback& onError,
+             boost::asio::io_service& ioService,
+             const ndn::dns::AddressSelector& addressSelector,
+             const time::nanoseconds& timeout)
+{
+  shared_ptr<Resolver> resolver = make_shared<Resolver>(onSuccess, onError,
+                                                        addressSelector, ndn::ref(ioService));
+  resolver->asyncResolve(host, timeout, resolver);
+  // resolver will be destroyed when async operation finishes or global IO service stops
+}
+
+IpAddress
+syncResolve(const std::string& host, boost::asio::io_service& ioService,
+            const ndn::dns::AddressSelector& addressSelector)
+{
+  Resolver resolver(SuccessCallback(), ErrorCallback(), addressSelector, ioService);
+
+  BoostResolver::query query(host, Resolver::NULL_PORT
+#if not defined(__FreeBSD__)
+                                 , BoostResolver::query::all_matching
+#endif
+                                 );
+
+  BoostResolver::iterator remoteEndpoint = resolver.syncResolve(query);
+
+  BoostResolver::iterator end;
+  for (; remoteEndpoint != end; ++remoteEndpoint)
+    {
+      if (addressSelector(EndPoint(*remoteEndpoint).address()))
+        {
+          return EndPoint(*remoteEndpoint).address();
+        }
+    }
+  throw Error("No endpoint matching the specified address selector found");
+}
+
+} // namespace dns
+} // namespace ndn
diff --git a/src/util/dns.hpp b/src/util/dns.hpp
new file mode 100644
index 0000000..ed15dd3
--- /dev/null
+++ b/src/util/dns.hpp
@@ -0,0 +1,112 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2014 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#ifndef NDN_UTIL_DNS_H
+#define NDN_UTIL_DNS_H
+
+#include "../util/time.hpp"
+#include <boost/asio/ip/address.hpp>
+#include <boost/asio/io_service.hpp>
+
+namespace ndn {
+namespace dns {
+
+typedef function<bool (const boost::asio::ip::address& address)> AddressSelector;
+
+struct AnyAddress
+{
+  bool
+  operator()(const boost::asio::ip::address& address)
+  {
+    return true;
+  }
+};
+
+struct Ipv4Only
+{
+  bool
+  operator()(const boost::asio::ip::address& address)
+  {
+    return address.is_v4();
+  }
+};
+
+struct Ipv6Only
+{
+  bool
+  operator()(const boost::asio::ip::address& address)
+  {
+    return address.is_v6();
+  }
+};
+
+struct Error : public std::runtime_error
+{
+  Error(const std::string& what)
+    : std::runtime_error(what)
+  {
+  }
+};
+
+typedef boost::asio::ip::address IpAddress;
+
+typedef function<void (const IpAddress& address)> SuccessCallback;
+typedef function<void (const std::string& reason)> ErrorCallback;
+
+/** \brief Asynchronously resolve host
+ *
+ * If an address selector predicate is specified, then each resolved IP address
+ * is checked against the predicate.
+ *
+ * Available address selector predicates:
+ *
+ * - resolver::AnyAddress()
+ * - resolver::Ipv4Address()
+ * - resolver::Ipv6Address()
+ */
+void
+asyncResolve(const std::string& host,
+             const SuccessCallback& onSuccess,
+             const ErrorCallback& onError,
+             boost::asio::io_service& ioService,
+             const ndn::dns::AddressSelector& addressSelector = ndn::dns::AnyAddress(),
+             const time::nanoseconds& timeout = time::seconds(4));
+
+/** \brief Synchronously resolve host
+ *
+ * If an address selector predicate is specified, then each resolved IP address
+ * is checked against the predicate.
+ *
+ * Available address selector predicates:
+ *
+ * - resolver::AnyAddress()
+ * - resolver::Ipv4Address()
+ * - resolver::Ipv6Address()
+ */
+IpAddress
+syncResolve(const std::string& host,
+            boost::asio::io_service& ioService,
+            const ndn::dns::AddressSelector& addressSelector = ndn::dns::AnyAddress());
+
+} // namespace dns
+} // namespace ndn
+
+#endif // NDN_UTIL_DNS_H
diff --git a/tests/unit-tests/util/test-dns.cpp b/tests/unit-tests/util/test-dns.cpp
new file mode 100644
index 0000000..94cf027
--- /dev/null
+++ b/tests/unit-tests/util/test-dns.cpp
@@ -0,0 +1,169 @@
+/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
+/**
+ * Copyright (c) 2013-2014 Regents of the University of California.
+ *
+ * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
+ *
+ * ndn-cxx library is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free Software
+ * Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
+ *
+ * You should have received copies of the GNU General Public License and GNU Lesser
+ * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
+ * <http://www.gnu.org/licenses/>.
+ *
+ * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
+ */
+
+#include "util/dns.hpp"
+
+#include "boost-test.hpp"
+#include <boost/lexical_cast.hpp>
+
+namespace ndn {
+
+using boost::asio::ip::address_v4;
+using boost::asio::ip::address_v6;
+
+class DnsFixture
+{
+public:
+  DnsFixture()
+    : m_nFailures(0)
+    , m_nSuccesses(0)
+  {
+  }
+
+  void
+  onSuccess(const dns::IpAddress& resolvedAddress,
+            const dns::IpAddress& expectedAddress,
+            bool isValid,
+            bool shouldCheckAddress = false)
+  {
+    std::cout << "Resolved to: " << resolvedAddress << std::endl;
+
+    ++m_nSuccesses;
+
+    if (!isValid)
+      {
+        BOOST_FAIL("Resolved to " + boost::lexical_cast<std::string>(resolvedAddress)
+                   + ", but should have failed");
+      }
+
+    BOOST_CHECK_EQUAL(resolvedAddress.is_v4(), expectedAddress.is_v4());
+
+    // checking address is not deterministic and should be enabled only
+    // if only one IP address will be returned by resolution
+    if (shouldCheckAddress)
+      {
+        BOOST_CHECK_EQUAL(resolvedAddress, expectedAddress);
+      }
+  }
+
+  void
+  onFailure(bool isValid)
+  {
+    ++m_nFailures;
+
+    if (!isValid)
+      {
+        BOOST_FAIL("Resolution should not have failed");
+      }
+
+    BOOST_CHECK_MESSAGE(true, "Resolution failed as expected");
+  }
+
+public:
+  uint32_t m_nFailures;
+  uint32_t m_nSuccesses;
+
+  boost::asio::io_service m_ioService;
+};
+
+BOOST_FIXTURE_TEST_SUITE(UtilDns, DnsFixture)
+
+BOOST_AUTO_TEST_CASE(Asynchronous)
+{
+  dns::asyncResolve("www.named-data.net",
+                    bind(&DnsFixture::onSuccess, this, _1,
+                         dns::IpAddress(address_v4()), true, false),
+                    bind(&DnsFixture::onFailure, this, false),
+                    m_ioService,
+                    dns::Ipv4Only());
+
+  dns::asyncResolve("nothost.nothost.nothost.arpa",
+                    bind(&DnsFixture::onSuccess, this, _1,
+                         dns::IpAddress(address_v4()), false, false),
+                    bind(&DnsFixture::onFailure, this, true),
+                    m_ioService); // should fail
+
+  dns::asyncResolve("www.google.com",
+                    bind(&DnsFixture::onSuccess, this, _1,
+                         dns::IpAddress(address_v4()), true, false),
+                    bind(&DnsFixture::onFailure, this, false),
+                    m_ioService,
+                    dns::Ipv4Only()); // request IPv4 address
+
+  dns::asyncResolve("www.google.com",
+                    bind(&DnsFixture::onSuccess, this, _1,
+                         dns::IpAddress(address_v6()), true, false),
+                    bind(&DnsFixture::onFailure, this, false),
+                    m_ioService,
+                    dns::Ipv6Only()); // request IPv6 address
+
+  dns::asyncResolve("ipv6.google.com", // only IPv6 address should be available
+                    bind(&DnsFixture::onSuccess, this, _1,
+                         dns::IpAddress(address_v6()), true, false),
+                    bind(&DnsFixture::onFailure, this, false),
+                    m_ioService);
+
+  dns::asyncResolve("ipv6.google.com", // only IPv6 address should be available
+                    bind(&DnsFixture::onSuccess, this, _1,
+                         dns::IpAddress(address_v6()), true, false),
+                    bind(&DnsFixture::onFailure, this, false),
+                    m_ioService,
+                    dns::Ipv6Only());
+
+  dns::asyncResolve("ipv6.google.com", // only IPv6 address should be available
+                    bind(&DnsFixture::onSuccess, this, _1,
+                         dns::IpAddress(address_v6()), false, false),
+                    bind(&DnsFixture::onFailure, this, true), // should fail
+                    m_ioService,
+                    dns::Ipv4Only());
+
+  dns::asyncResolve("192.0.2.1",
+                    bind(&DnsFixture::onSuccess, this, _1,
+                         dns::IpAddress(address_v4::from_string("192.0.2.1")),
+                         true, true),
+                    bind(&DnsFixture::onFailure, this, false),
+                    m_ioService);
+
+  dns::asyncResolve("2001:db8:3f9:0:3025:ccc5:eeeb:86d3",
+                    bind(&DnsFixture::onSuccess, this, _1,
+                         dns::IpAddress(address_v6::
+                                      from_string("2001:db8:3f9:0:3025:ccc5:eeeb:86d3")),
+                         true, true),
+                    bind(&DnsFixture::onFailure, this, false),
+                    m_ioService);
+
+  m_ioService.run();
+
+  BOOST_CHECK_EQUAL(m_nFailures, 2);
+  BOOST_CHECK_EQUAL(m_nSuccesses, 7);
+}
+
+BOOST_AUTO_TEST_CASE(Synchronous)
+{
+  dns::IpAddress address;
+  BOOST_CHECK_NO_THROW(address = dns::syncResolve("www.named-data.net", m_ioService));
+
+  BOOST_CHECK(address.is_v4() || address.is_v6());
+}
+
+BOOST_AUTO_TEST_SUITE_END()
+
+} // namespace ndn