resolver.cpp 6.88 KB
Newer Older
1
#include <network/dns_handler.hpp>
louiz’'s avatar
louiz’ committed
2
#include <utils/timed_events.hpp>
3 4 5
#include <network/resolver.hpp>
#include <string.h>
#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 44 45
  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)
{
  this->error_cb = error_cb;
  this->success_cb = 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 55 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 83
int Resolver::call_getaddrinfo(const char *name, const char* port, int flags)
{
  struct addrinfo hints;
  memset(&hints, 0, sizeof(struct addrinfo));
  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)
84 85 86 87 88 89 90
{
  this->resolving = true;
  this->resolved = false;
  this->resolved4 = false;
  this->resolved6 = false;

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

louiz’'s avatar
louiz’ committed
93 94 95
  // 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)
96
    {
louiz’'s avatar
louiz’ committed
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
      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)
  {
    Resolver* resolver = static_cast<Resolver*>(data);
    resolver->on_hostname6_resolved(result);
louiz’'s avatar
louiz’ committed
116
    resolver->after_resolved();
117
    std::free(result);
louiz’'s avatar
louiz’ committed
118 119 120 121 122 123
  };

  auto hostname4_resolved = [](dns_ctx*, dns_rr_a4* result, void* data)
  {
    Resolver* resolver = static_cast<Resolver*>(data);
    resolver->on_hostname4_resolved(result);
louiz’'s avatar
louiz’ committed
124
    resolver->after_resolved();
125
    std::free(result);
louiz’'s avatar
louiz’ committed
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 154
  };

  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))
155
    {
louiz’'s avatar
louiz’ committed
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
      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;
176 177
}

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

  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);
        }
    }
194
  else
louiz’'s avatar
louiz’ committed
195 196 197 198 199
    {
      const auto error = dns_error_messages.find(status);
      if (error != end(dns_error_messages))
        this->error_msg = error->second;
    }
200 201
}

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

  const auto status = dns_status(nullptr);
207

louiz’'s avatar
louiz’ committed
208 209
  if (status >= 0 && result)
    {
louiz’'s avatar
louiz’ committed
210
      char buf[INET6_ADDRSTRLEN];
louiz’'s avatar
louiz’ committed
211 212 213 214 215 216
      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);
        }
    }
louiz’'s avatar
louiz’ committed
217 218 219 220 221 222
}

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

  if (this->resolved6 && this->resolved4)
225 226 227 228 229 230 231
    this->on_resolved();
}

void Resolver::on_resolved()
{
  this->resolved = true;
  this->resolving = false;
louiz’'s avatar
louiz’ committed
232
  if (!this->addr)
233 234 235 236 237 238 239 240 241 242 243
    {
      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
244
#else  // ifdef UDNS_FOUND
245 246 247 248 249 250

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
251
  const auto res = this->call_getaddrinfo(hostname.data(), port.data(), 0);
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266

  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
267
#endif  // ifdef UDNS_FOUND
268 269 270 271 272 273 274 275 276 277 278 279 280 281

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 {};
}