-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathDnsStore.cpp
More file actions
43 lines (39 loc) · 1.46 KB
/
Copy pathDnsStore.cpp
File metadata and controls
43 lines (39 loc) · 1.46 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
#include "DnsStore.h"
#include <iostream>
using namespace std;
using tcp = boost::asio::ip::tcp;
void DnsStore::place(const string& domain, const vector<size_t>& ttl, const vector<tcp::endpoint>& results) {
const auto now = chrono::system_clock::now();
if (ttl.size() != results.size()) throw logic_error{ "TTL length must be same as results length." };
lock_guard<mutex> lock{ rw_mutex };
for(size_t index{}; index<ttl.size(); index++) {
store.emplace(domain, make_pair(now + chrono::seconds(ttl[index]), results[index]));
reverse_store.emplace(results[index].address().to_string(), domain);
}
}
optional<vector<tcp::endpoint>> DnsStore::get(const string& domain) {
lock_guard<mutex> lock{ rw_mutex };
const auto now = chrono::system_clock::now();
const auto cache_range = store.equal_range(domain);
auto iter = cache_range.first;
const auto end = cache_range.second;
vector<tcp::endpoint> result;
bool stale{};
while (iter != end) {
const auto&[domain, entry] = *iter;
const auto&[ttl, endpoint] = entry;
if (ttl <= now) {
result.emplace_back(endpoint);
} else {
stale = true;
}
++iter;
}
if (stale) store.erase(domain);
return result.empty() ? optional<vector<tcp::endpoint>>{} : result;
}
optional<string> DnsStore::reverse(const std::string& ip) {
lock_guard<mutex> lock{ rw_mutex };
const auto result = reverse_store.find(ip);
return result == reverse_store.end() ? optional<string>{} : result->second;
}