resolver.cpp 7 KB
Newer Older
1
#include <network/dns_handler.hpp>
louiz’'s avatar
louiz’ committed
2
#include <utils/timed_events.hpp>
3
#include <network/resolver.hpp>
louiz’'s avatar
louiz’ committed
4
#include <cstring>
5
#include <arpa/inet.h>
louiz’'s avatar
louiz’ committed
6
#include <netinet/in.h>
louiz’'s avatar
louiz’ committed
7 8 9
#ifdef UDNS_FOUND
# include <udns.h>
#endif
louiz’'s avatar
louiz’ committed
10

louiz’'s avatar
louiz’ committed
11
#include <fstream>
12
#include <cstdlib>
louiz’'s avatar
louiz’ committed
13 14 15
#include <sstream>
#include <chrono>
#include <map>
16 17 18

using namespace std::string_literals;

louiz’'s avatar
louiz’ committed
19
#ifdef UDNS_FOUND
louiz’'s avatar
louiz’ committed
20 21 22 23 24 25 26
static std::map<int, std::string> dns_error_messages {
    {DNS_E_TEMPFAIL, "Timeout while contacting DNS servers"},
    {DNS_E_PROTOCOL, "Misformatted DNS reply"},
    {DNS_E_NXDOMAIN, "Domain name not found"},
    {DNS_E_NOMEM, "Out of memory"},
    {DNS_E_BADQUERY, "Misformatted domain name"}
};
louiz’'s avatar
louiz’ committed
27
#endif
louiz’'s avatar
louiz’ committed
28

29
Resolver::Resolver():
louiz’'s avatar
louiz’ committed
30
#ifdef UDNS_FOUND
31 32 33 34 35 36 37 38 39 40 41 42 43
  resolved4(false),
  resolved6(false),
  resolving(false),
  port{},
#endif
  resolved(false),
  error_msg{}
{
}

void Resolver::resolve(const std::string& hostname, const std::string& port,
                       SuccessCallbackType success_cb, ErrorCallbackType error_cb)
{
louiz’'s avatar
louiz’ committed
44 45
  this->error_cb = std::move(error_cb);
  this->success_cb = std::move(success_cb);
louiz’'s avatar
louiz’ committed
46
#ifdef UDNS_FOUND
47
  this->port = port;
48
#endif
49 50 51 52

  this->start_resolving(hostname, port);
}

louiz’'s avatar
louiz’ committed
53 54
int Resolver::call_getaddrinfo(const char *name, const char* port, int flags)
{
louiz’'s avatar
louiz’ committed
55
  struct addrinfo hints{};
louiz’'s avatar
louiz’ committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
  hints.ai_flags = flags;
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_protocol = 0;

  struct addrinfo* addr_res = nullptr;
  const int res = ::getaddrinfo(name, port,
                                &hints, &addr_res);

  if (res == 0 && addr_res)
    {
      if (!this->addr)
        this->addr.reset(addr_res);
      else
        { // Append this result at the end of the linked list
          struct addrinfo *rp = this->addr.get();
          while (rp->ai_next)
            rp = rp->ai_next;
          rp->ai_next = addr_res;
        }
    }

  return res;
}

#ifdef UDNS_FOUND
void Resolver::start_resolving(const std::string& hostname, const std::string& port)
83 84 85 86 87 88 89
{
  this->resolving = true;
  this->resolved = false;
  this->resolved4 = false;
  this->resolved6 = false;

  this->error_msg.clear();
louiz’'s avatar
louiz’ committed
90
  this->addr.reset(nullptr);
91

louiz’'s avatar
louiz’ committed
92 93 94
  // We first try to use it as an IP address directly. We tell getaddrinfo
  // to NOT use any DNS resolution.
  if (this->call_getaddrinfo(hostname.data(), port.data(), AI_NUMERICHOST) == 0)
95
    {
louiz’'s avatar
louiz’ committed
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
      this->on_resolved();
      return;
    }

  // Then we look into /etc/hosts to translate the given hostname
  const auto hosts = this->look_in_etc_hosts(hostname);
  if (!hosts.empty())
    {
      for (const auto &host: hosts)
        this->call_getaddrinfo(host.data(), port.data(), AI_NUMERICHOST);
      this->on_resolved();
      return;
    }

  // And finally, we try a DNS resolution
  auto hostname6_resolved = [](dns_ctx*, dns_rr_a6* result, void* data)
  {
louiz’'s avatar
louiz’ committed
113
    auto resolver = static_cast<Resolver*>(data);
louiz’'s avatar
louiz’ committed
114
    resolver->on_hostname6_resolved(result);
louiz’'s avatar
louiz’ committed
115
    resolver->after_resolved();
116
    std::free(result);
louiz’'s avatar
louiz’ committed
117 118 119 120
  };

  auto hostname4_resolved = [](dns_ctx*, dns_rr_a4* result, void* data)
  {
louiz’'s avatar
louiz’ committed
121
    auto resolver = static_cast<Resolver*>(data);
louiz’'s avatar
louiz’ committed
122
    resolver->on_hostname4_resolved(result);
louiz’'s avatar
louiz’ committed
123
    resolver->after_resolved();
124
    std::free(result);
louiz’'s avatar
louiz’ committed
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
  };

  DNSHandler::watch();
  auto res = dns_submit_a4(nullptr, hostname.data(), 0, hostname4_resolved, this);
  if (!res)
    this->on_hostname4_resolved(nullptr);
  res = dns_submit_a6(nullptr, hostname.data(), 0, hostname6_resolved, this);
  if (!res)
    this->on_hostname6_resolved(nullptr);

  this->start_timer();
}

void Resolver::start_timer()
{
  const auto timeout = dns_timeouts(nullptr, -1, 0);
  if (timeout < 0)
    return;
  TimedEvent event(std::chrono::steady_clock::now() + std::chrono::seconds(timeout), [this]() { this->start_timer(); }, "DNS");
  TimedEventsManager::instance().add_event(std::move(event));
}

std::vector<std::string> Resolver::look_in_etc_hosts(const std::string &hostname)
{
  std::ifstream hosts("/etc/hosts");
  std::string line;

  std::vector<std::string> results;
  while (std::getline(hosts, line))
154
    {
louiz’'s avatar
louiz’ committed
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
      if (line.empty())
        continue;

      std::string ip;
      std::istringstream line_stream(line);
      line_stream >> ip;
      if (ip.empty() || ip[0] == '#')
        continue;

      std::string host;
      while (line_stream >> host && !host.empty() && host[0] != '#')
        {
          if (hostname == host)
            {
              results.push_back(ip);
              break;
            }
        }
    }
  return results;
175 176
}

louiz’'s avatar
louiz’ committed
177
void Resolver::on_hostname4_resolved(dns_rr_a4 *result)
178 179
{
  this->resolved4 = true;
louiz’'s avatar
louiz’ committed
180 181 182 183 184 185 186 187 188 189 190 191 192

  const auto status = dns_status(nullptr);

  if (status >= 0 && result)
    {
      char buf[INET6_ADDRSTRLEN];

      for (auto i = 0; i < result->dnsa4_nrr; ++i)
        {
          inet_ntop(AF_INET, &result->dnsa4_addr[i], buf, sizeof(buf));
          this->call_getaddrinfo(buf, this->port.data(), AI_NUMERICHOST);
        }
    }
193
  else
louiz’'s avatar
louiz’ committed
194 195 196 197 198
    {
      const auto error = dns_error_messages.find(status);
      if (error != end(dns_error_messages))
        this->error_msg = error->second;
    }
199 200
}

louiz’'s avatar
louiz’ committed
201
void Resolver::on_hostname6_resolved(dns_rr_a6 *result)
202 203
{
  this->resolved6 = true;
louiz’'s avatar
louiz’ committed
204 205

  const auto status = dns_status(nullptr);
206

louiz’'s avatar
louiz’ committed
207 208
  if (status >= 0 && result)
    {
louiz’'s avatar
louiz’ committed
209
      char buf[INET6_ADDRSTRLEN];
louiz’'s avatar
louiz’ committed
210 211 212 213 214 215
      for (auto i = 0; i < result->dnsa6_nrr; ++i)
        {
          inet_ntop(AF_INET6, &result->dnsa6_addr[i], buf, sizeof(buf));
          this->call_getaddrinfo(buf, this->port.data(), AI_NUMERICHOST);
        }
    }
216 217 218 219 220 221
  else
    {
      const auto error = dns_error_messages.find(status);
      if (error != end(dns_error_messages))
        this->error_msg = error->second;
    }
louiz’'s avatar
louiz’ committed
222 223 224 225 226 227
}

void Resolver::after_resolved()
{
  if (dns_active(nullptr) == 0)
    DNSHandler::unwatch();
louiz’'s avatar
louiz’ committed
228 229

  if (this->resolved6 && this->resolved4)
230 231 232 233 234 235 236
    this->on_resolved();
}

void Resolver::on_resolved()
{
  this->resolved = true;
  this->resolving = false;
louiz’'s avatar
louiz’ committed
237
  if (!this->addr)
238 239 240 241 242 243 244 245 246 247 248
    {
      if (this->error_cb)
        this->error_cb(this->error_msg.data());
    }
  else
    {
      if (this->success_cb)
        this->success_cb(this->addr.get());
    }
}

louiz’'s avatar
louiz’ committed
249
#else  // ifdef UDNS_FOUND
250 251 252 253 254 255

void Resolver::start_resolving(const std::string& hostname, const std::string& port)
{
  // If the resolution fails, the addr will be unset
  this->addr.reset(nullptr);

louiz’'s avatar
louiz’ committed
256
  const auto res = this->call_getaddrinfo(hostname.data(), port.data(), 0);
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271

  this->resolved = true;

  if (res != 0)
    {
      this->error_msg = gai_strerror(res);
      if (this->error_cb)
        this->error_cb(this->error_msg.data());
    }
  else
    {
      if (this->success_cb)
        this->success_cb(this->addr.get());
    }
}
louiz’'s avatar
louiz’ committed
272
#endif  // ifdef UDNS_FOUND
273 274 275 276 277 278 279 280 281 282 283 284 285 286

std::string addr_to_string(const struct addrinfo* rp)
{
  char buf[INET6_ADDRSTRLEN];
  if (rp->ai_family == AF_INET)
    return ::inet_ntop(rp->ai_family,
                       &reinterpret_cast<sockaddr_in*>(rp->ai_addr)->sin_addr,
                       buf, sizeof(buf));
  else if (rp->ai_family == AF_INET6)
    return ::inet_ntop(rp->ai_family,
                       &reinterpret_cast<sockaddr_in6*>(rp->ai_addr)->sin6_addr,
                       buf, sizeof(buf));
  return {};
}