-
Notifications
You must be signed in to change notification settings - Fork 3
/
DNS-fcrdns.cpp
88 lines (68 loc) · 2.42 KB
/
DNS-fcrdns.cpp
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
#include "DNS-fcrdns.hpp"
#include "IP4.hpp"
#include "IP6.hpp"
#include <algorithm>
#include <glog/logging.h>
// <https://en.wikipedia.org/wiki/Forward-confirmed_reverse_DNS>
namespace DNS {
std::vector<std::string> fcrdns4(Resolver& res, std::string_view addr)
{
auto const reversed{IP4::reverse(addr)};
// The reverse part, check PTR records.
auto const ptrs = res.get_records(RR_type::PTR, reversed + "in-addr.arpa");
std::vector<std::string> fcrdns;
for (auto const& ptr : ptrs) {
if (std::holds_alternative<DNS::RR_PTR>(ptr)) {
// The forward part, check each PTR for matching A record.
auto const addrs =
res.get_strings(RR_type::A, std::get<DNS::RR_PTR>(ptr).str());
if (std::find(begin(addrs), end(addrs), addr) != end(addrs)) {
fcrdns.push_back(std::get<DNS::RR_PTR>(ptr).str());
}
}
}
// Sort 1st by name length: short to long.
std::sort(begin(fcrdns), end(fcrdns),
[](std::string_view a, std::string_view b) {
if (a.length() != b.length())
return a.length() < b.length();
return a < b;
});
auto const last = std::unique(fcrdns.begin(), fcrdns.end());
fcrdns.erase(last, fcrdns.end());
return fcrdns;
}
std::vector<std::string> fcrdns6(Resolver& res, std::string_view addr)
{
auto const reversed{IP6::reverse(addr)};
// The reverse part, check PTR records.
auto const ptrs = res.get_records(RR_type::PTR, reversed + "ip6.arpa");
std::vector<std::string> fcrdns;
for (auto const& ptr : ptrs) {
if (std::holds_alternative<DNS::RR_PTR>(ptr)) {
// The forward part, check each PTR for matching AAAA record.
auto const addrs =
res.get_strings(RR_type::AAAA, std::get<DNS::RR_PTR>(ptr).str());
if (std::find(begin(addrs), end(addrs), addr) != end(addrs)) {
fcrdns.push_back(std::get<DNS::RR_PTR>(ptr).str());
}
}
}
// Sort 1st by name length: short to long.
std::sort(begin(fcrdns), end(fcrdns), [](auto a, auto b) {
if (size(a) != size(b))
return size(a) < size(b);
return a < b;
});
return fcrdns;
}
std::vector<std::string> fcrdns(Resolver& res, std::string_view addr)
{
// <https://en.wikipedia.org/wiki/Forward-confirmed_reverse_DNS>
if (IP4::is_address(addr))
return fcrdns4(res, addr);
if (IP6::is_address(addr))
return fcrdns6(res, addr);
LOG(FATAL) << "not a valid IP address " << addr;
}
} // namespace DNS