-
Notifications
You must be signed in to change notification settings - Fork 8.2k
Expand file tree
/
Copy pathDNSResolver.cpp
More file actions
584 lines (487 loc) · 17.9 KB
/
DNSResolver.cpp
File metadata and controls
584 lines (487 loc) · 17.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
#include <Common/DNSResolver.h>
#include <Common/CacheBase.h>
#include <Common/Exception.h>
#include <Common/NetException.h>
#include <Common/ProfileEvents.h>
#include <Common/CurrentMetrics.h>
#include <Common/thread_local_rng.h>
#include <Common/logger_useful.h>
#include <Poco/Net/IPAddress.h>
#include <Poco/Net/DNS.h>
#include <Poco/Net/NetException.h>
#include <Poco/NumberParser.h>
#include <base/sort.h>
#include <atomic>
#include <optional>
#include <string_view>
#include <Common/MultiVersion.h>
#include <unordered_set>
#include <Common/DNSPTRResolverProvider.h>
namespace ProfileEvents
{
extern const Event DNSError;
}
namespace CurrentMetrics
{
extern const Metric DNSHostsCacheBytes;
extern const Metric DNSHostsCacheSize;
extern const Metric DNSAddressesCacheBytes;
extern const Metric DNSAddressesCacheSize;
}
namespace std
{
template<> struct hash<Poco::Net::IPAddress>
{
size_t operator()(const Poco::Net::IPAddress & address) const noexcept
{
std::string_view addr(static_cast<const char *>(address.addr()), address.length());
std::hash<std::string_view> hash_impl;
return hash_impl(addr);
}
};
}
namespace DB
{
namespace ErrorCodes
{
extern const int BAD_ARGUMENTS;
extern const int DNS_ERROR;
}
namespace
{
/// Slightly altered implementation from https://github.com/pocoproject/poco/blob/poco-1.6.1/Net/src/SocketAddress.cpp#L86
void splitHostAndPort(const std::string & host_and_port, std::string & out_host, UInt16 & out_port)
{
String port_str;
out_host.clear();
auto it = host_and_port.begin();
auto end = host_and_port.end();
if (*it == '[') /// Try parse case '[<IPv6 or something else>]:<port>'
{
++it;
while (it != end && *it != ']')
out_host += *it++;
if (it == end)
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Malformed IPv6 address");
++it;
}
else /// Case '<IPv4 or domain name or something else>:<port>'
{
while (it != end && *it != ':')
out_host += *it++;
}
if (it != end && *it == ':')
{
++it;
while (it != end)
port_str += *it++;
}
else
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Missing port number");
unsigned port;
if (Poco::NumberParser::tryParseUnsigned(port_str, port) && port <= 0xFFFF)
{
out_port = static_cast<UInt16>(port);
}
else
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Port must be numeric");
}
DNSResolver::IPAddresses hostByName(const std::string & host)
{
/// Do not resolve IPv6 (or IPv4) if no local IPv6 (or IPv4) addresses are configured.
/// It should not affect client address checking, since client cannot connect from IPv6 address
/// if server has no IPv6 addresses.
auto flags = Poco::Net::DNS::DNS_HINT_AI_ADDRCONFIG;
DNSResolver::IPAddresses addresses;
try
{
addresses = Poco::Net::DNS::hostByName(host, flags).addresses();
}
catch (const Poco::Net::DNSException & e)
{
LOG_WARNING(getLogger("DNSResolver"), "Cannot resolve host ({}), error {}: {}.", host, e.code(), e.name());
addresses.clear();
}
if (addresses.empty())
{
ProfileEvents::increment(ProfileEvents::DNSError);
throw DB::NetException(ErrorCodes::DNS_ERROR, "Not found address of host: {}", host);
}
/// `getaddrinfo` returns duplicate addresses with different socket types, but useless for `Poco::Net::IPAddress`
addresses.erase(std::unique(addresses.begin(), addresses.end()), addresses.end());
return addresses;
}
DNSResolver::IPAddresses resolveIPAddressImpl(const std::string & host)
{
Poco::Net::IPAddress ip;
/// NOTE:
/// - Poco::Net::DNS::resolveOne(host) doesn't work for IP addresses like 127.0.0.2
/// - Poco::Net::IPAddress::tryParse() expect hex string for IPv6 (without brackets)
if (host.starts_with('['))
{
assert(host.ends_with(']'));
if (Poco::Net::IPAddress::tryParse(host.substr(1, host.size() - 2), ip))
return DNSResolver::IPAddresses(1, ip);
}
else
{
if (Poco::Net::IPAddress::tryParse(host, ip))
return DNSResolver::IPAddresses(1, ip);
}
DNSResolver::IPAddresses addresses = hostByName(host);
return addresses;
}
std::unordered_set<String> reverseResolveImpl(const Poco::Net::IPAddress & address)
{
auto ptr_resolver = DB::DNSPTRResolverProvider::get();
if (address.family() == Poco::Net::IPAddress::Family::IPv4)
{
return ptr_resolver->resolve(address.toString());
}
return ptr_resolver->resolve_v6(address.toString());
}
Poco::Net::IPAddress pickAddress(const DNSResolver::IPAddresses & addresses)
{
return addresses.front();
}
}
struct DNSResolver::Impl
{
using HostWithConsecutiveFailures = std::unordered_map<String, UInt32>;
using AddressWithConsecutiveFailures = std::unordered_map<Poco::Net::IPAddress, UInt32>;
CacheBase<std::string, DNSResolver::CacheEntry> cache_host{CurrentMetrics::DNSHostsCacheBytes, CurrentMetrics::DNSHostsCacheSize, 1024};
CacheBase<Poco::Net::IPAddress, std::unordered_set<std::string>> cache_address{CurrentMetrics::DNSAddressesCacheBytes, CurrentMetrics::DNSAddressesCacheSize, 1024};
std::mutex drop_mutex;
std::mutex update_mutex;
/// Cached server host name and its IPs
std::optional<String> host_name;
std::optional<DNSResolver::IPAddresses> host_addresses;
/// Store hosts, which was asked to resolve from last update of DNS cache.
HostWithConsecutiveFailures new_hosts;
AddressWithConsecutiveFailures new_addresses;
/// Store all hosts, which was whenever asked to resolve
HostWithConsecutiveFailures known_hosts;
AddressWithConsecutiveFailures known_addresses;
/// If disabled, will not make cache lookups, will resolve addresses manually on each call
std::atomic<bool> disable_cache{false};
Impl()
{
try
{
host_name.emplace(Poco::Net::DNS::hostName());
auto addresses = hostByName(*host_name);
::sort(addresses.begin(), addresses.end());
host_addresses.emplace(std::move(addresses));
}
catch (...)
{
tryLogCurrentException("DNSResolver", __PRETTY_FUNCTION__);
}
}
};
struct DNSResolver::AddressFilter
{
struct DNSFilterSettings
{
bool dns_allow_resolve_names_to_ipv4{true};
bool dns_allow_resolve_names_to_ipv6{true};
};
AddressFilter() : settings(std::make_unique<DNSFilterSettings>()) {}
void performAddressFiltering(DNSResolver::IPAddresses & addresses) const
{
const auto current_settings = settings.get();
bool dns_resolve_ipv4 = current_settings->dns_allow_resolve_names_to_ipv4;
bool dns_resolve_ipv6 = current_settings->dns_allow_resolve_names_to_ipv6;
if (dns_resolve_ipv4 && dns_resolve_ipv6)
{
return;
}
if (!dns_resolve_ipv4 && !dns_resolve_ipv6)
{
throw Exception(ErrorCodes::BAD_ARGUMENTS, "DNS can't resolve any address, because dns_allow_resolve_names_to_ipv6 and dns_allow_resolve_names_to_ipv4 both are disabled");
}
std::erase_if(addresses, [dns_resolve_ipv6, dns_resolve_ipv4](const Poco::Net::IPAddress& address)
{
return (address.family() == Poco::Net::IPAddress::IPv6 && !dns_resolve_ipv6)
|| (address.family() == Poco::Net::IPAddress::IPv4 && !dns_resolve_ipv4);
});
}
void setSettings(bool dns_allow_resolve_names_to_ipv4, bool dns_allow_resolve_names_to_ipv6)
{
settings.set(std::make_unique<DNSFilterSettings>(dns_allow_resolve_names_to_ipv4, dns_allow_resolve_names_to_ipv6));
}
MultiVersion<DNSFilterSettings> settings;
};
DNSResolver::DNSResolver()
: impl(std::make_unique<DNSResolver::Impl>())
, addressFilter(std::make_unique<DNSResolver::AddressFilter>())
, log(getLogger("DNSResolver")) {}
DNSResolver::IPAddresses DNSResolver::getResolvedIPAddressesWithFiltering(const std::string & host)
{
auto addresses = resolveIPAddressImpl(host);
addressFilter->performAddressFiltering(addresses);
if (addresses.empty())
{
ProfileEvents::increment(ProfileEvents::DNSError);
throw DB::NetException(ErrorCodes::DNS_ERROR, "After filtering there are no resolved address for host({}).", host);
}
return addresses;
}
DNSResolver::IPAddresses DNSResolver::resolveIPAddressWithCache(const std::string & host)
{
auto [result, _ ] = impl->cache_host.getOrSet(host, [&host, this]() {return std::make_shared<DNSResolver::CacheEntry>(getResolvedIPAddressesWithFiltering(host), std::chrono::system_clock::now());});
return result->addresses;
}
std::unordered_set<String> DNSResolver::reverseResolveWithCache(const Poco::Net::IPAddress & address)
{
auto [result, _ ] = impl->cache_address.getOrSet(address, [&address]() { return std::make_shared<std::unordered_set<String>>(reverseResolveImpl(address)); });
return *result;
}
Poco::Net::IPAddress DNSResolver::resolveHost(const std::string & host)
{
return pickAddress(resolveHostAll(host)); // random order -> random pick
}
void DNSResolver::setFilterSettings(bool dns_allow_resolve_names_to_ipv4, bool dns_allow_resolve_names_to_ipv6)
{
addressFilter->setSettings(dns_allow_resolve_names_to_ipv4, dns_allow_resolve_names_to_ipv6);
}
bool DNSResolver::getFilterIPv4() const
{
return addressFilter->settings.get()->dns_allow_resolve_names_to_ipv4;
}
bool DNSResolver::getFilterIPv6() const
{
return addressFilter->settings.get()->dns_allow_resolve_names_to_ipv6;
}
DNSResolver::IPAddresses DNSResolver::resolveHostAllInOriginOrder(const std::string & host)
{
if (impl->disable_cache)
return getResolvedIPAddressesWithFiltering(host);
addToNewHosts(host);
return resolveIPAddressWithCache(host);
}
DNSResolver::IPAddresses DNSResolver::resolveHostAll(const std::string & host)
{
auto addresses = resolveHostAllInOriginOrder(host);
std::shuffle(addresses.begin(), addresses.end(), thread_local_rng);
return addresses;
}
Poco::Net::SocketAddress DNSResolver::resolveAddress(const std::string & host_and_port)
{
String host;
UInt16 port;
splitHostAndPort(host_and_port, host, port);
if (impl->disable_cache)
return Poco::Net::SocketAddress(pickAddress(getResolvedIPAddressesWithFiltering(host)), port);
addToNewHosts(host);
return Poco::Net::SocketAddress(pickAddress(resolveIPAddressWithCache(host)), port);
}
Poco::Net::SocketAddress DNSResolver::resolveAddress(const std::string & host, UInt16 port)
{
if (impl->disable_cache)
return Poco::Net::SocketAddress(pickAddress(getResolvedIPAddressesWithFiltering(host)), port);
addToNewHosts(host);
return Poco::Net::SocketAddress(pickAddress(resolveIPAddressWithCache(host)), port);
}
std::vector<Poco::Net::SocketAddress> DNSResolver::resolveAddressList(const std::string & host, UInt16 port)
{
auto ip_addresses = resolveHostAllInOriginOrder(host);
std::vector<Poco::Net::SocketAddress> socket_addresses;
socket_addresses.reserve(ip_addresses.size());
for (auto & ip_addresse : ip_addresses)
socket_addresses.emplace_back(ip_addresse, port);
return socket_addresses;
}
std::unordered_set<String> DNSResolver::reverseResolve(const Poco::Net::IPAddress & address)
{
if (impl->disable_cache)
return reverseResolveImpl(address);
addToNewAddresses(address);
return reverseResolveWithCache(address);
}
void DNSResolver::dropCache()
{
impl->cache_host.clear();
impl->cache_address.clear();
std::scoped_lock lock(impl->update_mutex, impl->drop_mutex);
impl->known_hosts.clear();
impl->known_addresses.clear();
impl->new_hosts.clear();
impl->new_addresses.clear();
impl->host_name.reset();
impl->host_addresses.reset();
}
void DNSResolver::removeHostFromCache(const std::string & host)
{
impl->cache_host.remove(host);
}
void DNSResolver::setDisableCacheFlag(bool is_disabled)
{
impl->disable_cache = is_disabled;
}
void DNSResolver::setCacheMaxEntries(UInt64 cache_max_entries)
{
impl->cache_address.setMaxSizeInBytes(cache_max_entries);
impl->cache_host.setMaxSizeInBytes(cache_max_entries);
}
String DNSResolver::getHostName()
{
if (impl->disable_cache)
return Poco::Net::DNS::hostName();
std::lock_guard lock(impl->drop_mutex);
if (!impl->host_name.has_value())
impl->host_name.emplace(Poco::Net::DNS::hostName());
return *impl->host_name;
}
bool DNSResolver::updateHostNameAndAddresses()
{
bool updated = false;
try
{
String updated_host_name = Poco::Net::DNS::hostName();
DNSResolver::IPAddresses updated_host_addresses = hostByName(updated_host_name);
::sort(updated_host_addresses.begin(), updated_host_addresses.end());
std::lock_guard lock(impl->drop_mutex);
if (!impl->host_name.has_value() || updated_host_name != *impl->host_name)
{
impl->host_name.emplace(updated_host_name);
}
if (!impl->host_addresses.has_value() || updated_host_addresses != *impl->host_addresses)
{
impl->host_addresses.emplace(updated_host_addresses);
updated = true;
}
}
catch (...)
{
tryLogCurrentException(log, __PRETTY_FUNCTION__);
}
return updated;
}
static String cacheElemToString(String str) { return str; }
static String cacheElemToString(const Poco::Net::IPAddress & addr) { return addr.toString(); }
template <typename UpdateF, typename ElemsT>
void DNSResolver::updateCacheImpl(
UpdateF && update_func, // NOLINT(cppcoreguidelines-missing-std-forward)
ElemsT && elems, // NOLINT(cppcoreguidelines-missing-std-forward)
UInt32 max_consecutive_failures,
FormatStringHelper<String> notfound_log_msg,
FormatStringHelper<String> dropped_log_msg)
{
String lost_elems;
using iterators = typename std::remove_reference_t<decltype(elems)>::iterator;
std::vector<iterators> elements_to_drop;
for (auto it = elems.begin(); it != elems.end(); it++)
{
try
{
(this->*update_func)(it->first);
it->second = 0;
}
catch (const DB::Exception & e)
{
if (e.code() != ErrorCodes::DNS_ERROR)
{
tryLogCurrentException(log, __PRETTY_FUNCTION__);
continue;
}
if (!lost_elems.empty())
lost_elems += ", ";
lost_elems += cacheElemToString(it->first);
if (max_consecutive_failures)
{
it->second++;
if (it->second >= max_consecutive_failures)
elements_to_drop.emplace_back(it);
}
}
catch (...)
{
tryLogCurrentException(log, __PRETTY_FUNCTION__);
}
}
if (!lost_elems.empty())
LOG_INFO(log, notfound_log_msg.format(std::move(lost_elems)));
if (elements_to_drop.size())
{
String deleted_elements;
for (auto it : elements_to_drop)
{
if (!deleted_elements.empty())
deleted_elements += ", ";
deleted_elements += cacheElemToString(it->first);
elems.erase(it);
}
LOG_INFO(log, dropped_log_msg.format(std::move(deleted_elements)));
}
}
void DNSResolver::updateCache(UInt32 max_consecutive_failures)
{
LOG_DEBUG(log, "Updating DNS cache");
{
std::lock_guard lock(impl->drop_mutex);
for (const auto & host : impl->new_hosts)
impl->known_hosts.insert(host);
impl->new_hosts.clear();
for (const auto & address : impl->new_addresses)
impl->known_addresses.insert(address);
impl->new_addresses.clear();
}
/// FIXME Updating may take a long time because we cannot manage timeouts of getaddrinfo(...) and getnameinfo(...).
/// DROP DNS CACHE will wait on update_mutex (possibly while holding drop_mutex)
std::lock_guard lock(impl->update_mutex);
updateCacheImpl(
&DNSResolver::updateHost, impl->known_hosts, max_consecutive_failures, "Cached hosts not found: {}", "Cached hosts dropped: {}");
updateCacheImpl(
&DNSResolver::updateAddress,
impl->known_addresses,
max_consecutive_failures,
"Cached addresses not found: {}",
"Cached addresses dropped: {}");
LOG_DEBUG(log, "Updated DNS cache");
}
bool DNSResolver::updateHost(const String & host)
{
const auto old_value = resolveIPAddressWithCache(host);
auto new_value = getResolvedIPAddressesWithFiltering(host);
const bool result = old_value != new_value;
impl->cache_host.set(host, std::make_shared<DNSResolver::CacheEntry>(std::move(new_value), std::chrono::system_clock::now()));
return result;
}
bool DNSResolver::updateAddress(const Poco::Net::IPAddress & address)
{
const auto old_value = reverseResolveWithCache(address);
auto new_value = reverseResolveImpl(address);
const bool result = old_value != new_value;
impl->cache_address.set(address, std::make_shared<std::unordered_set<String>>(std::move(new_value)));
return result;
}
void DNSResolver::addToNewHosts(const String & host)
{
std::lock_guard lock(impl->drop_mutex);
UInt8 consecutive_failures = 0;
impl->new_hosts.insert({host, consecutive_failures});
}
void DNSResolver::addToNewAddresses(const Poco::Net::IPAddress & address)
{
std::lock_guard lock(impl->drop_mutex);
UInt8 consecutive_failures = 0;
impl->new_addresses.insert({address, consecutive_failures});
}
std::vector<std::pair<std::string, DNSResolver::CacheEntry>> DNSResolver::cacheEntries() const
{
std::lock_guard lock(impl->drop_mutex);
std::vector<std::pair<std::string, DNSResolver::CacheEntry>> entries;
for (auto & [key, entry] : impl->cache_host.dump())
{
entries.emplace_back(std::move(key), *entry);
}
return entries;
}
DNSResolver::~DNSResolver() = default;
DNSResolver & DNSResolver::instance()
{
static DNSResolver ret;
return ret;
}
}