./pdns/query-local-address.hh
./pdns/rcpgenerator.cc
./pdns/rcpgenerator.hh
-./pdns/rec-carbon.cc
-./pdns/rec-lua-conf.cc
-./pdns/rec-lua-conf.hh
-./pdns/rec-snmp.cc
-./pdns/rec-snmp.hh
-./pdns/rec_channel.cc
-./pdns/rec_channel.hh
-./pdns/rec_channel_rec.cc
-./pdns/rec_control.cc
./pdns/receiver.cc
-./pdns/recpacketcache.cc
-./pdns/recpacketcache.hh
-./pdns/recursor_cache.cc
-./pdns/recursor_cache.hh
./pdns/remote_logger.cc
./pdns/remote_logger.hh
./pdns/resolve-context.hh
./pdns/saxfr.cc
./pdns/sdig.cc
./pdns/secpoll-auth.cc
-./pdns/secpoll-recursor.cc
-./pdns/secpoll-recursor.hh
./pdns/secpoll.cc
./pdns/secpoll.hh
./pdns/serialtweaker.cc
./pdns/test-packetcache_hh.cc
./pdns/test-proxy_protocol_cc.cc
./pdns/test-rcpgenerator_cc.cc
-./pdns/test-recpacketcache_cc.cc
./pdns/test-sha_hh.cc
./pdns/test-sholder_hh.cc
./pdns/test-signers.cc
./pdns/unix_utility.cc
./pdns/utility.hh
./pdns/uuid-utils.cc
-./pdns/validate-recursor.cc
-./pdns/validate-recursor.hh
./pdns/validate.cc
./pdns/validate.hh
./pdns/version.cc
./pdns/ws-api.hh
./pdns/ws-auth.cc
./pdns/ws-auth.hh
-./pdns/ws-recursor.cc
-./pdns/ws-recursor.hh
./pdns/xpf.cc
./pdns/xpf.hh
./pdns/zone2json.cc
void doCarbonDump(void*)
{
-try
-{
- static thread_local auto configHolder = g_carbonConfig.getLocal();
+ try {
+ static thread_local auto configHolder = g_carbonConfig.getLocal();
- auto config = *configHolder;
- if (config.servers.empty()) {
- return;
- }
+ auto config = *configHolder;
+ if (config.servers.empty()) {
+ return;
+ }
- if (config.namespace_name.empty()) {
- config.namespace_name = "pdns";
- }
+ if (config.namespace_name.empty()) {
+ config.namespace_name = "pdns";
+ }
- if (config.hostname.empty()) {
- try {
- config.hostname = getCarbonHostName();
+ if (config.hostname.empty()) {
+ try {
+ config.hostname = getCarbonHostName();
+ }
+ catch (const std::exception& e) {
+ throw std::runtime_error(std::string("The 'carbon-ourname' setting has not been set and we are unable to determine the system's hostname: ") + e.what());
+ }
}
- catch(const std::exception& e) {
- throw std::runtime_error(std::string("The 'carbon-ourname' setting has not been set and we are unable to determine the system's hostname: ") + e.what());
+ if (config.instance_name.empty()) {
+ config.instance_name = "recursor";
}
- }
- if (config.instance_name.empty()) {
- config.instance_name = "recursor";
- }
- registerAllStats();
- PacketBuffer msg;
- for (const auto& carbonServer: config.servers) {
- ComboAddress remote(carbonServer, 2003);
- Socket s(remote.sin4.sin_family, SOCK_STREAM);
- s.setNonBlocking();
- std::shared_ptr<TLSCtx> tlsCtx{nullptr};
- const struct timeval timeout{g_networkTimeoutMsec / 1000, static_cast<suseconds_t>(g_networkTimeoutMsec) % 1000 * 1000};
- auto handler = std::make_shared<TCPIOHandler>("", s.releaseHandle(), timeout, tlsCtx, time(nullptr));
- handler->tryConnect(SyncRes::s_tcp_fast_open_connect, remote);// we do the connect so the first attempt happens while we gather stats
+ registerAllStats();
+ PacketBuffer msg;
+ for (const auto& carbonServer : config.servers) {
+ ComboAddress remote(carbonServer, 2003);
+ Socket s(remote.sin4.sin_family, SOCK_STREAM);
+ s.setNonBlocking();
+ std::shared_ptr<TLSCtx> tlsCtx{nullptr};
+ const struct timeval timeout
+ {
+ g_networkTimeoutMsec / 1000, static_cast<suseconds_t>(g_networkTimeoutMsec) % 1000 * 1000
+ };
+ auto handler = std::make_shared<TCPIOHandler>("", s.releaseHandle(), timeout, tlsCtx, time(nullptr));
+ handler->tryConnect(SyncRes::s_tcp_fast_open_connect, remote); // we do the connect so the first attempt happens while we gather stats
- if(msg.empty()) {
- auto all = getAllStatsMap(StatComponent::Carbon);
+ if (msg.empty()) {
+ auto all = getAllStatsMap(StatComponent::Carbon);
- ostringstream str;
- time_t now=time(0);
+ ostringstream str;
+ time_t now = time(0);
- for(const auto& val : all) {
- str<<config.namespace_name<<'.'<<config.hostname<<'.'<<config.instance_name<<'.'<<val.first<<' '<<val.second.d_value<<' '<<now<<"\r\n";
+ for (const auto& val : all) {
+ str << config.namespace_name << '.' << config.hostname << '.' << config.instance_name << '.' << val.first << ' ' << val.second.d_value << ' ' << now << "\r\n";
+ }
+ const string& x = str.str();
+ msg.insert(msg.end(), x.cbegin(), x.cend());
}
- const string& x = str.str();
- msg.insert(msg.end(), x.cbegin(), x.cend());
- }
- auto ret = asendtcp(msg, handler); // this will actually do the right thing waiting on the connect
- if (ret == LWResult::Result::Timeout) {
- g_log<<Logger::Warning<<"Timeout connecting/writing carbon data to "<<remote.toStringWithPort()<<endl;
- }
- else if (ret != LWResult::Result::Success) {
- g_log<<Logger::Warning<<"Error writing carbon data to "<<remote.toStringWithPort()<<": "<<stringerror()<<endl;
+ auto ret = asendtcp(msg, handler); // this will actually do the right thing waiting on the connect
+ if (ret == LWResult::Result::Timeout) {
+ g_log << Logger::Warning << "Timeout connecting/writing carbon data to " << remote.toStringWithPort() << endl;
+ }
+ else if (ret != LWResult::Result::Success) {
+ g_log << Logger::Warning << "Error writing carbon data to " << remote.toStringWithPort() << ": " << stringerror() << endl;
+ }
+ handler->close();
}
- handler->close();
}
- }
-catch (const PDNSException& e)
-{
- g_log<<Logger::Error<<"Error in carbon thread: "<<e.reason<<endl;
-}
-catch(const std::exception& e)
-{
- g_log<<Logger::Error<<"Error in carbon thread: "<<e.what()<<endl;
-}
-catch(...)
-{
- g_log<<Logger::Error<<"Unknown error in carbon thread"<<endl;
-}
+ catch (const PDNSException& e) {
+ g_log << Logger::Error << "Error in carbon thread: " << e.reason << endl;
+ }
+ catch (const std::exception& e) {
+ g_log << Logger::Error << "Error in carbon thread: " << e.what() << endl;
+ }
+ catch (...) {
+ g_log << Logger::Error << "Unknown error in carbon thread" << endl;
+ }
}
#include "validate-recursor.hh"
#include "root-dnssec.hh"
-GlobalStateHolder<LuaConfigItems> g_luaconfs;
+GlobalStateHolder<LuaConfigItems> g_luaconfs;
/* SO HOW DOES THIS WORK! AND PLEASE PAY ATTENTION!
This function can be called at any time. It is expected to overwrite all the contents
LuaConfigItems::LuaConfigItems()
{
DNSName root("."); // don't use g_rootdnsname here, it might not exist yet
- for (const auto &dsRecord : rootDSs) {
- auto ds=std::dynamic_pointer_cast<DSRecordContent>(DSRecordContent::make(dsRecord));
+ for (const auto& dsRecord : rootDSs) {
+ auto ds = std::dynamic_pointer_cast<DSRecordContent>(DSRecordContent::make(dsRecord));
dsAnchors[root].insert(*ds);
}
}
typename C::value_type::second_type constGet(const C& c, const std::string& name)
{
auto iter = c.find(name);
- if(iter == c.end())
+ if (iter == c.end())
return 0;
return iter->second;
}
-typedef std::unordered_map<std::string, boost::variant<bool, uint32_t, std::string, std::vector<std::pair<int, std::string>> > > rpzOptions_t;
+typedef std::unordered_map<std::string, boost::variant<bool, uint32_t, std::string, std::vector<std::pair<int, std::string>>>> rpzOptions_t;
static void parseRPZParameters(rpzOptions_t& have, std::shared_ptr<DNSFilterEngine::Zone>& zone, std::string& polName, boost::optional<DNSFilterEngine::Policy>& defpol, bool& defpolOverrideLocal, uint32_t& maxTTL)
{
polName = boost::get<std::string>(have["policyName"]);
}
if (have.count("defpol")) {
- defpol=DNSFilterEngine::Policy();
+ defpol = DNSFilterEngine::Policy();
defpol->d_kind = (DNSFilterEngine::PolicyKind)boost::get<uint32_t>(have["defpol"]);
defpol->setName(polName);
- if(defpol->d_kind == DNSFilterEngine::PolicyKind::Custom) {
+ if (defpol->d_kind == DNSFilterEngine::PolicyKind::Custom) {
defpol->d_custom.push_back(DNSRecordContent::mastermake(QType::CNAME, QClass::IN,
boost::get<string>(have["defcontent"])));
- if(have.count("defttl"))
+ if (have.count("defttl"))
defpol->d_ttl = static_cast<int32_t>(boost::get<uint32_t>(have["defttl"]));
else
defpol->d_ttl = -1; // get it from the zone
}
}
-typedef std::unordered_map<std::string, boost::variant<bool, uint64_t, std::string, std::vector<std::pair<int,std::string> > > > protobufOptions_t;
+typedef std::unordered_map<std::string, boost::variant<bool, uint64_t, std::string, std::vector<std::pair<int, std::string>>>> protobufOptions_t;
static void parseProtobufOptions(boost::optional<protobufOptions_t> vars, ProtobufExportConfig& config)
{
if (vars->count("exportTypes")) {
config.exportTypes.clear();
- auto types = boost::get<std::vector<std::pair<int, std::string>>>((*vars)["exportTypes"]);
+ auto types = boost::get<std::vector<std::pair<int, std::string>>>((*vars)["exportTypes"]);
for (const auto& pair : types) {
const auto type = pair.second;
bool found = false;
}
#ifdef HAVE_FSTRM
-typedef std::unordered_map<std::string, boost::variant<bool, uint64_t, std::string, std::vector<std::pair<int,std::string> > > > frameStreamOptions_t;
+typedef std::unordered_map<std::string, boost::variant<bool, uint64_t, std::string, std::vector<std::pair<int, std::string>>>> frameStreamOptions_t;
static void parseFrameStreamOptions(boost::optional<frameStreamOptions_t> vars, FrameStreamExportConfig& config)
{
bool defpolOverrideLocal = true;
std::shared_ptr<DNSFilterEngine::Zone> zone = std::make_shared<DNSFilterEngine::Zone>();
TSIGTriplet tt;
- uint32_t refresh=0;
+ uint32_t refresh = 0;
size_t maxReceivedXFRMBytes = 0;
uint16_t axfrTimeout = 20;
uint32_t maxTTL = std::numeric_limits<uint32_t>::max();
auto& have = *options;
parseRPZParameters(have, zone, polName, defpol, defpolOverrideLocal, maxTTL);
- if(have.count("tsigname")) {
- tt.name=DNSName(toLower(boost::get<string>(have["tsigname"])));
- tt.algo=DNSName(toLower(boost::get<string>(have[ "tsigalgo"])));
- if(B64Decode(boost::get<string>(have[ "tsigsecret"]), tt.secret))
+ if (have.count("tsigname")) {
+ tt.name = DNSName(toLower(boost::get<string>(have["tsigname"])));
+ tt.algo = DNSName(toLower(boost::get<string>(have["tsigalgo"])));
+ if (B64Decode(boost::get<string>(have["tsigsecret"]), tt.secret))
throw std::runtime_error("TSIG secret is not valid Base-64 encoded");
}
- if(have.count("refresh")) {
+ if (have.count("refresh")) {
refresh = boost::get<uint32_t>(have["refresh"]);
if (refresh == 0) {
- g_log<<Logger::Warning<<"rpzPrimary refresh value of 0 ignored"<<endl;
+ g_log << Logger::Warning << "rpzPrimary refresh value of 0 ignored" << endl;
}
}
- if(have.count("maxReceivedMBytes")) {
+ if (have.count("maxReceivedMBytes")) {
maxReceivedXFRMBytes = static_cast<size_t>(boost::get<uint32_t>(have["maxReceivedMBytes"]));
}
- if(have.count("localAddress")) {
+ if (have.count("localAddress")) {
localAddress = ComboAddress(boost::get<string>(have["localAddress"]));
}
- if(have.count("axfrTimeout")) {
+ if (have.count("axfrTimeout")) {
axfrTimeout = static_cast<uint16_t>(boost::get<uint32_t>(have["axfrTimeout"]));
}
- if(have.count("seedFile")) {
+ if (have.count("seedFile")) {
seedFile = boost::get<std::string>(have["seedFile"]);
}
- if(have.count("dumpFile")) {
+ if (have.count("dumpFile")) {
dumpFile = boost::get<std::string>(have["dumpFile"]);
}
}
// We were passed a localAddress, check if its AF matches the primaries'
for (const auto& primary : primaries) {
if (localAddress.sin4.sin_family != primary.sin4.sin_family) {
- throw PDNSException("Primary address("+primary.toString()+") is not of the same Address Family as the local address ("+localAddress.toString()+").");
+ throw PDNSException("Primary address(" + primary.toString() + ") is not of the same Address Family as the local address (" + localAddress.toString() + ").");
}
}
}
zoneIdx = lci.dfe.addZone(zone);
if (!seedFile.empty()) {
- g_log<<Logger::Info<<"Pre-loading RPZ zone "<<zoneName<<" from seed file '"<<seedFile<<"'"<<endl;
+ g_log << Logger::Info << "Pre-loading RPZ zone " << zoneName << " from seed file '" << seedFile << "'" << endl;
try {
sr = loadRPZFromFile(seedFile, zone, defpol, defpolOverrideLocal, maxTTL);
throw PDNSException("The RPZ zone " + zoneName + " loaded from the seed file (" + zone->getDomain().toString() + ") has no SOA record");
}
}
- catch(const PDNSException& e) {
- g_log<<Logger::Warning<<"Unable to pre-load RPZ zone "<<zoneName<<" from seed file '"<<seedFile<<"': "<<e.reason<<endl;
+ catch (const PDNSException& e) {
+ g_log << Logger::Warning << "Unable to pre-load RPZ zone " << zoneName << " from seed file '" << seedFile << "': " << e.reason << endl;
zone->clear();
}
- catch(const std::exception& e) {
- g_log<<Logger::Warning<<"Unable to pre-load RPZ zone "<<zoneName<<" from seed file '"<<seedFile<<"': "<<e.what()<<endl;
+ catch (const std::exception& e) {
+ g_log << Logger::Warning << "Unable to pre-load RPZ zone " << zoneName << " from seed file '" << seedFile << "': " << e.what() << endl;
zone->clear();
}
}
}
- catch(const std::exception& e) {
- g_log<<Logger::Error<<"Problem configuring 'rpzPrimary': "<<e.what()<<endl;
- exit(1); // FIXME proper exit code?
+ catch (const std::exception& e) {
+ g_log << Logger::Error << "Problem configuring 'rpzPrimary': " << e.what() << endl;
+ exit(1); // FIXME proper exit code?
}
- catch(const PDNSException& e) {
- g_log<<Logger::Error<<"Problem configuring 'rpzPrimary': "<<e.reason<<endl;
- exit(1); // FIXME proper exit code?
+ catch (const PDNSException& e) {
+ g_log << Logger::Error << "Problem configuring 'rpzPrimary': " << e.reason << endl;
+ exit(1); // FIXME proper exit code?
}
delayedThreads.rpzPrimaryThreads.push_back(std::make_tuple(primaries, defpol, defpolOverrideLocal, maxTTL, zoneIdx, tt, maxReceivedXFRMBytes, localAddress, axfrTimeout, refresh, sr, dumpFile));
LuaConfigItems lci;
LuaContext Lua;
- if(fname.empty())
+ if (fname.empty())
return;
ifstream ifs(fname);
- if(!ifs)
- throw PDNSException("Cannot open file '"+fname+"': "+stringerror());
+ if (!ifs)
+ throw PDNSException("Cannot open file '" + fname + "': " + stringerror());
auto luaconfsLocal = g_luaconfs.getLocal();
lci.generation = luaconfsLocal->generation + 1;
// pdnslog here is compatible with pdnslog in lua-base4.cc.
- Lua.writeFunction("pdnslog", [](const std::string& msg, boost::optional<int> loglevel) { g_log << (Logger::Urgency)loglevel.get_value_or(Logger::Warning) << msg<<endl; });
+ Lua.writeFunction("pdnslog", [](const std::string& msg, boost::optional<int> loglevel) { g_log << (Logger::Urgency)loglevel.get_value_or(Logger::Warning) << msg << endl; });
std::unordered_map<string, std::unordered_map<string, int>> pdns_table;
pdns_table["loglevels"] = std::unordered_map<string, int>{
{"Alert", LOG_ALERT},
{"Info", LOG_INFO},
{"Notice", LOG_NOTICE},
{"Warning", LOG_WARNING},
- {"Error", LOG_ERR}
- };
+ {"Error", LOG_ERR}};
Lua.writeVariable("pdns", pdns_table);
Lua.writeFunction("clearSortlist", [&lci]() { lci.sortlist.clear(); });
-
+
/* we can get: "1.2.3.4"
{"1.2.3.4", "4.5.6.7"}
{"1.2.3.4", {"4.5.6.7", "8.9.10.11"}}
*/
- map<string,DNSFilterEngine::PolicyKind> pmap{
- {"NoAction", DNSFilterEngine::PolicyKind::NoAction},
+ map<string, DNSFilterEngine::PolicyKind> pmap{
+ {"NoAction", DNSFilterEngine::PolicyKind::NoAction},
{"Drop", DNSFilterEngine::PolicyKind::Drop},
{"NXDOMAIN", DNSFilterEngine::PolicyKind::NXDOMAIN},
{"NODATA", DNSFilterEngine::PolicyKind::NODATA},
{"Truncate", DNSFilterEngine::PolicyKind::Truncate},
- {"Custom", DNSFilterEngine::PolicyKind::Custom}
- };
+ {"Custom", DNSFilterEngine::PolicyKind::Custom}};
Lua.writeVariable("Policy", pmap);
Lua.writeFunction("rpzFile", [&lci](const string& filename, boost::optional<rpzOptions_t> options) {
- try {
- boost::optional<DNSFilterEngine::Policy> defpol;
- bool defpolOverrideLocal = true;
- std::string polName("rpzFile");
- std::shared_ptr<DNSFilterEngine::Zone> zone = std::make_shared<DNSFilterEngine::Zone>();
- uint32_t maxTTL = std::numeric_limits<uint32_t>::max();
- if (options) {
- auto& have = *options;
- parseRPZParameters(have, zone, polName, defpol, defpolOverrideLocal, maxTTL);
- }
- g_log<<Logger::Warning<<"Loading RPZ from file '"<<filename<<"'"<<endl;
- zone->setName(polName);
- loadRPZFromFile(filename, zone, defpol, defpolOverrideLocal, maxTTL);
- lci.dfe.addZone(zone);
- g_log<<Logger::Warning<<"Done loading RPZ from file '"<<filename<<"'"<<endl;
- }
- catch(const std::exception& e) {
- g_log<<Logger::Error<<"Unable to load RPZ zone from '"<<filename<<"': "<<e.what()<<endl;
+ try {
+ boost::optional<DNSFilterEngine::Policy> defpol;
+ bool defpolOverrideLocal = true;
+ std::string polName("rpzFile");
+ std::shared_ptr<DNSFilterEngine::Zone> zone = std::make_shared<DNSFilterEngine::Zone>();
+ uint32_t maxTTL = std::numeric_limits<uint32_t>::max();
+ if (options) {
+ auto& have = *options;
+ parseRPZParameters(have, zone, polName, defpol, defpolOverrideLocal, maxTTL);
}
- });
+ g_log << Logger::Warning << "Loading RPZ from file '" << filename << "'" << endl;
+ zone->setName(polName);
+ loadRPZFromFile(filename, zone, defpol, defpolOverrideLocal, maxTTL);
+ lci.dfe.addZone(zone);
+ g_log << Logger::Warning << "Done loading RPZ from file '" << filename << "'" << endl;
+ }
+ catch (const std::exception& e) {
+ g_log << Logger::Error << "Unable to load RPZ zone from '" << filename << "': " << e.what() << endl;
+ }
+ });
- Lua.writeFunction("rpzMaster", [&lci, &delayedThreads](const boost::variant<string, std::vector<std::pair<int, string> > >& primaries_, const string& zoneName, boost::optional<rpzOptions_t> options) {
- g_log<<Logger::Warning<<"'rpzMaster' is deprecated and will be removed in a future release, use 'rpzPrimary' instead"<< endl;
+ Lua.writeFunction("rpzMaster", [&lci, &delayedThreads](const boost::variant<string, std::vector<std::pair<int, string>>>& primaries_, const string& zoneName, boost::optional<rpzOptions_t> options) {
+ g_log << Logger::Warning << "'rpzMaster' is deprecated and will be removed in a future release, use 'rpzPrimary' instead" << endl;
rpzPrimary(lci, delayedThreads, primaries_, zoneName, options);
- });
- Lua.writeFunction("rpzPrimary", [&lci, &delayedThreads](const boost::variant<string, std::vector<std::pair<int, string> > >& primaries_, const string& zoneName, boost::optional<rpzOptions_t> options) {
+ });
+ Lua.writeFunction("rpzPrimary", [&lci, &delayedThreads](const boost::variant<string, std::vector<std::pair<int, string>>>& primaries_, const string& zoneName, boost::optional<rpzOptions_t> options) {
rpzPrimary(lci, delayedThreads, primaries_, zoneName, options);
- });
+ });
typedef std::unordered_map<std::string, boost::variant<uint32_t, std::string>> zoneToCacheOptions_t;
delayedThreads.ztcConfigs.push_back(conf);
}
catch (const std::exception& e) {
- g_log<<Logger::Error<<"Problem configuring zoneToCache for zone '" << zoneName << "': " << e.what() << endl;
+ g_log << Logger::Error << "Problem configuring zoneToCache for zone '" << zoneName << "': " << e.what() << endl;
}
});
- typedef vector<pair<int,boost::variant<string, vector<pair<int, string> > > > > argvec_t;
- Lua.writeFunction("addSortList",
- [&lci](const std::string& formask_,
- const boost::variant<string, argvec_t>& masks,
- boost::optional<int> order_)
- {
- try {
- Netmask formask(formask_);
- int order = order_ ? (*order_) : lci.sortlist.getMaxOrder(formask)+1;
- if(auto str = boost::get<string>(&masks))
- lci.sortlist.addEntry(formask, Netmask(*str), order);
- else {
-
- auto vec = boost::get<argvec_t>(&masks);
- for(const auto& e : *vec) {
- if(auto s = boost::get<string>(&e.second)) {
- lci.sortlist.addEntry(formask, Netmask(*s), order);
- }
- else {
- const auto& v =boost::get<vector<pair<int, string> > >(e.second);
- for(const auto& entry : v)
- lci.sortlist.addEntry(formask, Netmask(entry.second), order);
- }
- ++order;
- }
- }
- }
- catch(std::exception& e) {
- g_log<<Logger::Error<<"Error in addSortList: "<<e.what()<<endl;
- }
- });
+ typedef vector<pair<int, boost::variant<string, vector<pair<int, string>>>>> argvec_t;
+ Lua.writeFunction("addSortList",
+ [&lci](const std::string& formask_,
+ const boost::variant<string, argvec_t>& masks,
+ boost::optional<int> order_) {
+ try {
+ Netmask formask(formask_);
+ int order = order_ ? (*order_) : lci.sortlist.getMaxOrder(formask) + 1;
+ if (auto str = boost::get<string>(&masks))
+ lci.sortlist.addEntry(formask, Netmask(*str), order);
+ else {
+
+ auto vec = boost::get<argvec_t>(&masks);
+ for (const auto& e : *vec) {
+ if (auto s = boost::get<string>(&e.second)) {
+ lci.sortlist.addEntry(formask, Netmask(*s), order);
+ }
+ else {
+ const auto& v = boost::get<vector<pair<int, string>>>(e.second);
+ for (const auto& entry : v)
+ lci.sortlist.addEntry(formask, Netmask(entry.second), order);
+ }
+ ++order;
+ }
+ }
+ }
+ catch (std::exception& e) {
+ g_log << Logger::Error << "Error in addSortList: " << e.what() << endl;
+ }
+ });
Lua.writeFunction("addTA", [&lci](const std::string& who, const std::string& what) {
- warnIfDNSSECDisabled("Warning: adding Trust Anchor for DNSSEC (addTA), but dnssec is set to 'off'!");
- DNSName zone(who);
- auto ds = std::dynamic_pointer_cast<DSRecordContent>(DSRecordContent::make(what));
- lci.dsAnchors[zone].insert(*ds);
+ warnIfDNSSECDisabled("Warning: adding Trust Anchor for DNSSEC (addTA), but dnssec is set to 'off'!");
+ DNSName zone(who);
+ auto ds = std::dynamic_pointer_cast<DSRecordContent>(DSRecordContent::make(what));
+ lci.dsAnchors[zone].insert(*ds);
});
Lua.writeFunction("clearTA", [&lci](boost::optional<string> who) {
- warnIfDNSSECDisabled("Warning: removing Trust Anchor for DNSSEC (clearTA), but dnssec is set to 'off'!");
- if(who)
- lci.dsAnchors.erase(DNSName(*who));
- else
- lci.dsAnchors.clear();
- });
+ warnIfDNSSECDisabled("Warning: removing Trust Anchor for DNSSEC (clearTA), but dnssec is set to 'off'!");
+ if (who)
+ lci.dsAnchors.erase(DNSName(*who));
+ else
+ lci.dsAnchors.clear();
+ });
/* Remove in 4.3 */
Lua.writeFunction("addDS", [&lci](const std::string& who, const std::string& what) {
- warnIfDNSSECDisabled("Warning: adding Trust Anchor for DNSSEC (addDS), but dnssec is set to 'off'!");
- g_log<<Logger::Warning<<"addDS is deprecated and will be removed in the future, switch to addTA"<<endl;
- DNSName zone(who);
- auto ds = std::dynamic_pointer_cast<DSRecordContent>(DSRecordContent::make(what));
- lci.dsAnchors[zone].insert(*ds);
+ warnIfDNSSECDisabled("Warning: adding Trust Anchor for DNSSEC (addDS), but dnssec is set to 'off'!");
+ g_log << Logger::Warning << "addDS is deprecated and will be removed in the future, switch to addTA" << endl;
+ DNSName zone(who);
+ auto ds = std::dynamic_pointer_cast<DSRecordContent>(DSRecordContent::make(what));
+ lci.dsAnchors[zone].insert(*ds);
});
/* Remove in 4.3 */
Lua.writeFunction("clearDS", [&lci](boost::optional<string> who) {
- g_log<<Logger::Warning<<"clearDS is deprecated and will be removed in the future, switch to clearTA"<<endl;
- warnIfDNSSECDisabled("Warning: removing Trust Anchor for DNSSEC (clearDS), but dnssec is set to 'off'!");
- if(who)
- lci.dsAnchors.erase(DNSName(*who));
- else
- lci.dsAnchors.clear();
- });
+ g_log << Logger::Warning << "clearDS is deprecated and will be removed in the future, switch to clearTA" << endl;
+ warnIfDNSSECDisabled("Warning: removing Trust Anchor for DNSSEC (clearDS), but dnssec is set to 'off'!");
+ if (who)
+ lci.dsAnchors.erase(DNSName(*who));
+ else
+ lci.dsAnchors.clear();
+ });
Lua.writeFunction("addNTA", [&lci](const std::string& who, const boost::optional<std::string> why) {
- warnIfDNSSECDisabled("Warning: adding Negative Trust Anchor for DNSSEC (addNTA), but dnssec is set to 'off'!");
- if(why)
- lci.negAnchors[DNSName(who)] = static_cast<string>(*why);
- else
- lci.negAnchors[DNSName(who)] = "";
- });
+ warnIfDNSSECDisabled("Warning: adding Negative Trust Anchor for DNSSEC (addNTA), but dnssec is set to 'off'!");
+ if (why)
+ lci.negAnchors[DNSName(who)] = static_cast<string>(*why);
+ else
+ lci.negAnchors[DNSName(who)] = "";
+ });
Lua.writeFunction("clearNTA", [&lci](boost::optional<string> who) {
- warnIfDNSSECDisabled("Warning: removing Negative Trust Anchor for DNSSEC (clearNTA), but dnssec is set to 'off'!");
- if(who)
- lci.negAnchors.erase(DNSName(*who));
- else
- lci.negAnchors.clear();
- });
+ warnIfDNSSECDisabled("Warning: removing Negative Trust Anchor for DNSSEC (clearNTA), but dnssec is set to 'off'!");
+ if (who)
+ lci.negAnchors.erase(DNSName(*who));
+ else
+ lci.negAnchors.clear();
+ });
Lua.writeFunction("readTrustAnchorsFromFile", [&lci](const std::string& fnamearg, const boost::optional<uint32_t> interval) {
- uint32_t realInterval = 24;
- if (interval) {
- realInterval = static_cast<uint32_t>(*interval);
- }
- warnIfDNSSECDisabled("Warning: reading Trust Anchors from file (readTrustAnchorsFromFile), but dnssec is set to 'off'!");
- lci.trustAnchorFileInfo.fname = fnamearg;
- lci.trustAnchorFileInfo.interval = realInterval;
- updateTrustAnchorsFromFile(fnamearg, lci.dsAnchors);
- });
+ uint32_t realInterval = 24;
+ if (interval) {
+ realInterval = static_cast<uint32_t>(*interval);
+ }
+ warnIfDNSSECDisabled("Warning: reading Trust Anchors from file (readTrustAnchorsFromFile), but dnssec is set to 'off'!");
+ lci.trustAnchorFileInfo.fname = fnamearg;
+ lci.trustAnchorFileInfo.interval = realInterval;
+ updateTrustAnchorsFromFile(fnamearg, lci.dsAnchors);
+ });
Lua.writeFunction("setProtobufMasks", [&lci](const uint8_t maskV4, uint8_t maskV6) {
- lci.protobufMaskV4 = maskV4;
- lci.protobufMaskV6 = maskV6;
- });
+ lci.protobufMaskV4 = maskV4;
+ lci.protobufMaskV6 = maskV6;
+ });
Lua.writeFunction("protobufServer", [&lci](boost::variant<const std::string, const std::unordered_map<int, std::string>> servers, boost::optional<protobufOptions_t> vars) {
- if (!lci.protobufExportConfig.enabled) {
+ if (!lci.protobufExportConfig.enabled) {
- lci.protobufExportConfig.enabled = true;
+ lci.protobufExportConfig.enabled = true;
- try {
- if (servers.type() == typeid(std::string)) {
- auto server = boost::get<const std::string>(servers);
-
- lci.protobufExportConfig.servers.emplace_back(server);
- }
- else {
- auto serversMap = boost::get<const std::unordered_map<int,std::string>>(servers);
- for (const auto& serverPair : serversMap) {
- lci.protobufExportConfig.servers.emplace_back(serverPair.second);
- }
- }
+ try {
+ if (servers.type() == typeid(std::string)) {
+ auto server = boost::get<const std::string>(servers);
- parseProtobufOptions(vars, lci.protobufExportConfig);
- }
- catch(std::exception& e) {
- g_log<<Logger::Error<<"Error while adding protobuf logger: "<<e.what()<<endl;
- }
- catch(PDNSException& e) {
- g_log<<Logger::Error<<"Error while adding protobuf logger: "<<e.reason<<endl;
- }
+ lci.protobufExportConfig.servers.emplace_back(server);
}
else {
- g_log<<Logger::Error<<"Only one protobufServer() directive can be configured, we already have "<<lci.protobufExportConfig.servers.at(0).toString()<<endl;
+ auto serversMap = boost::get<const std::unordered_map<int, std::string>>(servers);
+ for (const auto& serverPair : serversMap) {
+ lci.protobufExportConfig.servers.emplace_back(serverPair.second);
+ }
}
- });
- Lua.writeFunction("outgoingProtobufServer", [&lci](boost::variant<const std::string, const std::unordered_map<int, std::string>> servers, boost::optional<protobufOptions_t> vars) {
- if (!lci.outgoingProtobufExportConfig.enabled) {
+ parseProtobufOptions(vars, lci.protobufExportConfig);
+ }
+ catch (std::exception& e) {
+ g_log << Logger::Error << "Error while adding protobuf logger: " << e.what() << endl;
+ }
+ catch (PDNSException& e) {
+ g_log << Logger::Error << "Error while adding protobuf logger: " << e.reason << endl;
+ }
+ }
+ else {
+ g_log << Logger::Error << "Only one protobufServer() directive can be configured, we already have " << lci.protobufExportConfig.servers.at(0).toString() << endl;
+ }
+ });
- lci.outgoingProtobufExportConfig.enabled = true;
+ Lua.writeFunction("outgoingProtobufServer", [&lci](boost::variant<const std::string, const std::unordered_map<int, std::string>> servers, boost::optional<protobufOptions_t> vars) {
+ if (!lci.outgoingProtobufExportConfig.enabled) {
- try {
- if (servers.type() == typeid(std::string)) {
- auto server = boost::get<const std::string>(servers);
+ lci.outgoingProtobufExportConfig.enabled = true;
- lci.outgoingProtobufExportConfig.servers.emplace_back(server);
- }
- else {
- auto serversMap = boost::get<const std::unordered_map<int,std::string>>(servers);
- for (const auto& serverPair : serversMap) {
- lci.outgoingProtobufExportConfig.servers.emplace_back(serverPair.second);
- }
- }
+ try {
+ if (servers.type() == typeid(std::string)) {
+ auto server = boost::get<const std::string>(servers);
- parseProtobufOptions(vars, lci.outgoingProtobufExportConfig);
- }
- catch(std::exception& e) {
- g_log<<Logger::Error<<"Error while starting outgoing protobuf logger: "<<e.what()<<endl;
- }
- catch(PDNSException& e) {
- g_log<<Logger::Error<<"Error while starting outgoing protobuf logger: "<<e.reason<<endl;
+ lci.outgoingProtobufExportConfig.servers.emplace_back(server);
+ }
+ else {
+ auto serversMap = boost::get<const std::unordered_map<int, std::string>>(servers);
+ for (const auto& serverPair : serversMap) {
+ lci.outgoingProtobufExportConfig.servers.emplace_back(serverPair.second);
}
+ }
+
+ parseProtobufOptions(vars, lci.outgoingProtobufExportConfig);
}
- else {
- g_log<<Logger::Error<<"Only one outgoingProtobufServer() directive can be configured, we already have "<<lci.outgoingProtobufExportConfig.servers.at(0).toString()<<endl;
+ catch (std::exception& e) {
+ g_log << Logger::Error << "Error while starting outgoing protobuf logger: " << e.what() << endl;
+ }
+ catch (PDNSException& e) {
+ g_log << Logger::Error << "Error while starting outgoing protobuf logger: " << e.reason << endl;
}
- });
+ }
+ else {
+ g_log << Logger::Error << "Only one outgoingProtobufServer() directive can be configured, we already have " << lci.outgoingProtobufExportConfig.servers.at(0).toString() << endl;
+ }
+ });
#ifdef HAVE_FSTRM
Lua.writeFunction("dnstapFrameStreamServer", [&lci](boost::variant<const std::string, const std::unordered_map<int, std::string>> servers, boost::optional<frameStreamOptions_t> vars) {
- if (!lci.frameStreamExportConfig.enabled) {
-
- lci.frameStreamExportConfig.enabled = true;
-
- try {
- if (servers.type() == typeid(std::string)) {
- auto server = boost::get<const std::string>(servers);
- if (!boost::starts_with(server, "/")) {
- ComboAddress parsecheck(server);
- }
- lci.frameStreamExportConfig.servers.emplace_back(server);
- }
- else {
- auto serversMap = boost::get<const std::unordered_map<int,std::string>>(servers);
- for (const auto& serverPair : serversMap) {
- lci.frameStreamExportConfig.servers.emplace_back(serverPair.second);
- }
- }
-
- parseFrameStreamOptions(vars, lci.frameStreamExportConfig);
- }
- catch(std::exception& e) {
- g_log<<Logger::Error<<"Error reading config for dnstap framestream logger: "<<e.what()<<endl;
+ if (!lci.frameStreamExportConfig.enabled) {
+
+ lci.frameStreamExportConfig.enabled = true;
+
+ try {
+ if (servers.type() == typeid(std::string)) {
+ auto server = boost::get<const std::string>(servers);
+ if (!boost::starts_with(server, "/")) {
+ ComboAddress parsecheck(server);
}
- catch(PDNSException& e) {
- g_log<<Logger::Error<<"Error reading config for dnstap framestream logger: "<<e.reason<<endl;
+ lci.frameStreamExportConfig.servers.emplace_back(server);
+ }
+ else {
+ auto serversMap = boost::get<const std::unordered_map<int, std::string>>(servers);
+ for (const auto& serverPair : serversMap) {
+ lci.frameStreamExportConfig.servers.emplace_back(serverPair.second);
}
+ }
+
+ parseFrameStreamOptions(vars, lci.frameStreamExportConfig);
}
- else {
- g_log<<Logger::Error<<"Only one dnstapFrameStreamServer() directive can be configured, we already have "<<lci.frameStreamExportConfig.servers.at(0)<<endl;
+ catch (std::exception& e) {
+ g_log << Logger::Error << "Error reading config for dnstap framestream logger: " << e.what() << endl;
+ }
+ catch (PDNSException& e) {
+ g_log << Logger::Error << "Error reading config for dnstap framestream logger: " << e.reason << endl;
}
- });
+ }
+ else {
+ g_log << Logger::Error << "Only one dnstapFrameStreamServer() directive can be configured, we already have " << lci.frameStreamExportConfig.servers.at(0) << endl;
+ }
+ });
#endif /* HAVE_FSTRM */
try {
Lua.executeCode(ifs);
g_luaconfs.setState(std::move(lci));
}
- catch(const LuaContext::ExecutionErrorException& e) {
- g_log<<Logger::Error<<"Unable to load Lua script from '"+fname+"': ";
+ catch (const LuaContext::ExecutionErrorException& e) {
+ g_log << Logger::Error << "Unable to load Lua script from '" + fname + "': ";
try {
std::rethrow_if_nested(e);
- } catch(const std::exception& exp) {
+ }
+ catch (const std::exception& exp) {
// exp is the exception that was thrown from inside the lambda
g_log << exp.what() << std::endl;
}
- catch(const PDNSException& exp) {
+ catch (const PDNSException& exp) {
// exp is the exception that was thrown from inside the lambda
g_log << exp.reason << std::endl;
}
throw;
-
}
- catch(std::exception& err) {
- g_log<<Logger::Error<<"Unable to load Lua script from '"+fname+"': "<<err.what()<<endl;
+ catch (std::exception& err) {
+ g_log << Logger::Error << "Unable to load Lua script from '" + fname + "': " << err.what() << endl;
throw;
}
-
}
void startLuaConfigDelayedThreads(const luaConfigDelayedThreads& delayedThreads, uint64_t generation)
std::thread t(RPZIXFRTracker, std::get<0>(rpzPrimary), std::get<1>(rpzPrimary), std::get<2>(rpzPrimary), std::get<3>(rpzPrimary), std::get<4>(rpzPrimary), std::get<5>(rpzPrimary), std::get<6>(rpzPrimary) * 1024 * 1024, std::get<7>(rpzPrimary), std::get<8>(rpzPrimary), std::get<9>(rpzPrimary), std::get<10>(rpzPrimary), std::get<11>(rpzPrimary), generation);
t.detach();
}
- catch(const std::exception& e) {
- g_log<<Logger::Error<<"Problem starting RPZIXFRTracker thread: "<<e.what()<<endl;
+ catch (const std::exception& e) {
+ g_log << Logger::Error << "Problem starting RPZIXFRTracker thread: " << e.what() << endl;
exit(1);
}
- catch(const PDNSException& e) {
- g_log<<Logger::Error<<"Problem starting RPZIXFRTracker thread: "<<e.reason<<endl;
+ catch (const PDNSException& e) {
+ g_log << Logger::Error << "Problem starting RPZIXFRTracker thread: " << e.reason << endl;
exit(1);
}
}
- for (const auto& ztcConfig: delayedThreads.ztcConfigs) {
+ for (const auto& ztcConfig : delayedThreads.ztcConfigs) {
try {
std::thread t(RecZoneToCache::ZoneToCache, ztcConfig, generation);
t.detach();
}
- catch(const std::exception& e) {
- g_log<<Logger::Error<<"Problem starting zoneToCache thread: "<<e.what()<<endl;
+ catch (const std::exception& e) {
+ g_log << Logger::Error << "Problem starting zoneToCache thread: " << e.what() << endl;
exit(1);
}
- catch(const PDNSException& e) {
- g_log<<Logger::Error<<"Problem starting zoneToCache thread: "<<e.reason<<endl;
+ catch (const PDNSException& e) {
+ g_log << Logger::Error << "Problem starting zoneToCache thread: " << e.reason << endl;
exit(1);
}
}
struct ProtobufExportConfig
{
- std::set<uint16_t> exportTypes = { QType::A, QType::AAAA, QType::CNAME };
+ std::set<uint16_t> exportTypes = {QType::A, QType::AAAA, QType::CNAME};
std::vector<ComboAddress> servers;
uint64_t maxQueuedEntries{100};
uint16_t timeout{2};
unsigned reopenInterval{0};
};
-struct TrustAnchorFileInfo {
+struct TrustAnchorFileInfo
+{
uint32_t interval{24};
std::string fname;
};
-class LuaConfigItems
+class LuaConfigItems
{
public:
LuaConfigItems();
SortList sortlist;
DNSFilterEngine dfe;
TrustAnchorFileInfo trustAnchorFileInfo; // Used to update the Trust Anchors from file periodically
- map<DNSName,dsmap_t> dsAnchors;
- map<DNSName,std::string> negAnchors;
+ map<DNSName, dsmap_t> dsAnchors;
+ map<DNSName, std::string> negAnchors;
ProtobufExportConfig protobufExportConfig;
ProtobufExportConfig outgoingProtobufExportConfig;
FrameStreamExportConfig frameStreamExportConfig;
struct luaConfigDelayedThreads
{
// Please make sure that the tuple below only contains value types since they are used as parameters in a thread ct
- std::vector<std::tuple<std::vector<ComboAddress>, boost::optional<DNSFilterEngine::Policy>, bool, uint32_t, size_t, TSIGTriplet, size_t, ComboAddress, uint16_t, uint32_t, std::shared_ptr<SOARecordContent>, std::string> > rpzPrimaryThreads;
+ std::vector<std::tuple<std::vector<ComboAddress>, boost::optional<DNSFilterEngine::Policy>, bool, uint32_t, size_t, TSIGTriplet, size_t, ComboAddress, uint16_t, uint32_t, std::shared_ptr<SOARecordContent>, std::string>> rpzPrimaryThreads;
std::vector<RecZoneToCache::Config> ztcConfigs;
};
void loadRecursorLuaConfig(const std::string& fname, luaConfigDelayedThreads& delayedThreads);
void startLuaConfigDelayedThreads(const luaConfigDelayedThreads& delayedThreads, uint64_t generation);
-
#define RECURSOR_TRAPS_OID RECURSOR_OID, 10, 0
#define RECURSOR_TRAP_OBJECTS_OID RECURSOR_OID, 11
-static const oid trapReasonOID[] = { RECURSOR_TRAP_OBJECTS_OID, 1, 0 };
-static const oid customTrapOID[] = { RECURSOR_TRAPS_OID, 1 };
+static const oid trapReasonOID[] = {RECURSOR_TRAP_OBJECTS_OID, 1, 0};
+static const oid customTrapOID[] = {RECURSOR_TRAPS_OID, 1};
-static const oid questionsOID[] = { RECURSOR_STATS_OID, 1 };
-static const oid ipv6QuestionsOID[] = { RECURSOR_STATS_OID, 2 };
-static const oid tcpQuestionsOID[] = { RECURSOR_STATS_OID, 3 };
-static const oid cacheHitsOID[] = { RECURSOR_STATS_OID, 4 };
-static const oid cacheMissesOID[] = { RECURSOR_STATS_OID, 5 };
-static const oid cacheEntriesOID[] = { RECURSOR_STATS_OID, 6 };
-static const oid cacheBytesOID[] = { RECURSOR_STATS_OID, 7 };
-static const oid packetcacheHitsOID[] = { RECURSOR_STATS_OID, 8 };
-static const oid packetcacheMissesOID[] = { RECURSOR_STATS_OID, 9 };
-static const oid packetcacheEntriesOID[] = { RECURSOR_STATS_OID, 10 };
-static const oid packetcacheBytesOID[] = { RECURSOR_STATS_OID, 11 };
-static const oid mallocBytesOID[] = { RECURSOR_STATS_OID, 12 };
-static const oid servfailAnswersOID[] = { RECURSOR_STATS_OID, 13 };
-static const oid nxdomainAnswersOID[] = { RECURSOR_STATS_OID, 14 };
-static const oid noerrorAnswersOID[] = { RECURSOR_STATS_OID, 15 };
-static const oid unauthorizedUdpOID[] = { RECURSOR_STATS_OID, 16 };
-static const oid unauthorizedTcpOID[] = { RECURSOR_STATS_OID, 17 };
-static const oid tcpClientOverflowOID[] = { RECURSOR_STATS_OID, 18 };
-static const oid clientParseErrorsOID[] = { RECURSOR_STATS_OID, 19 };
-static const oid serverParseErrorsOID[] = { RECURSOR_STATS_OID, 20 };
-static const oid tooOldDropsOID[] = { RECURSOR_STATS_OID, 21 };
-static const oid answers01OID[] = { RECURSOR_STATS_OID, 22 };
-static const oid answers110OID[] = { RECURSOR_STATS_OID, 23 };
-static const oid answers10100OID[] = { RECURSOR_STATS_OID, 24 };
-static const oid answers1001000OID[] = { RECURSOR_STATS_OID, 25 };
-static const oid answersSlowOID[] = { RECURSOR_STATS_OID, 26 };
-static const oid auth4Answers01OID[] = { RECURSOR_STATS_OID, 27 };
-static const oid auth4Answers110OID[] = { RECURSOR_STATS_OID, 28 };
-static const oid auth4Answers10100OID[] = { RECURSOR_STATS_OID, 29 };
-static const oid auth4Answers1001000OID[] = { RECURSOR_STATS_OID, 30 };
-static const oid auth4AnswersslowOID[] = { RECURSOR_STATS_OID, 31 };
-static const oid auth6Answers01OID[] = { RECURSOR_STATS_OID, 32 };
-static const oid auth6Answers110OID[] = { RECURSOR_STATS_OID, 33 };
-static const oid auth6Answers10100OID[] = { RECURSOR_STATS_OID, 34 };
-static const oid auth6Answers1001000OID[] = { RECURSOR_STATS_OID, 35 };
-static const oid auth6AnswersSlowOID[] = { RECURSOR_STATS_OID, 36 };
-static const oid qaLatencyOID[] = { RECURSOR_STATS_OID, 37 };
-static const oid unexpectedPacketsOID[] = { RECURSOR_STATS_OID, 38 };
-static const oid caseMismatchesOID[] = { RECURSOR_STATS_OID, 39 };
-static const oid spoofPreventsOID[] = { RECURSOR_STATS_OID, 40 };
-static const oid nssetInvalidationsOID[] = { RECURSOR_STATS_OID, 41 };
-static const oid resourceLimitsOID[] = { RECURSOR_STATS_OID, 42 };
-static const oid overCapacityDropsOID[] = { RECURSOR_STATS_OID, 43 };
-static const oid policyDropsOID[] = { RECURSOR_STATS_OID, 44 };
-static const oid noPacketErrorOID[] = { RECURSOR_STATS_OID, 45 };
-static const oid dlgOnlyDropsOID[] = { RECURSOR_STATS_OID, 46 };
-static const oid ignoredPacketsOID[] = { RECURSOR_STATS_OID, 47 };
-static const oid maxMthreadStackOID[] = { RECURSOR_STATS_OID, 48 };
-static const oid negcacheEntriesOID[] = { RECURSOR_STATS_OID, 49 };
-static const oid throttleEntriesOID[] = { RECURSOR_STATS_OID, 50 };
-static const oid nsspeedsEntriesOID[] = { RECURSOR_STATS_OID, 51 };
-static const oid failedHostEntriesOID[] = { RECURSOR_STATS_OID, 52 };
-static const oid concurrentQueriesOID[] = { RECURSOR_STATS_OID, 53 };
-static const oid securityStatusOID[] = { RECURSOR_STATS_OID, 54 };
-static const oid outgoingTimeoutsOID[] = { RECURSOR_STATS_OID, 55 };
-static const oid outgoing4TimeoutsOID[] = { RECURSOR_STATS_OID, 56 };
-static const oid outgoing6TimeoutsOID[] = { RECURSOR_STATS_OID, 57 };
-static const oid tcpOutqueriesOID[] = { RECURSOR_STATS_OID, 58 };
-static const oid allOutqueriesOID[] = { RECURSOR_STATS_OID, 59 };
-static const oid ipv6OutqueriesOID[] = { RECURSOR_STATS_OID, 60 };
-static const oid throttledOutqueriesOID[] = { RECURSOR_STATS_OID, 61 };
-static const oid dontOutqueriesOID[] = { RECURSOR_STATS_OID, 62 };
-static const oid unreachablesOID[] = { RECURSOR_STATS_OID, 63 };
-static const oid chainResendsOID[] = { RECURSOR_STATS_OID, 64 };
-static const oid tcpClientsOID[] = { RECURSOR_STATS_OID, 65 };
+static const oid questionsOID[] = {RECURSOR_STATS_OID, 1};
+static const oid ipv6QuestionsOID[] = {RECURSOR_STATS_OID, 2};
+static const oid tcpQuestionsOID[] = {RECURSOR_STATS_OID, 3};
+static const oid cacheHitsOID[] = {RECURSOR_STATS_OID, 4};
+static const oid cacheMissesOID[] = {RECURSOR_STATS_OID, 5};
+static const oid cacheEntriesOID[] = {RECURSOR_STATS_OID, 6};
+static const oid cacheBytesOID[] = {RECURSOR_STATS_OID, 7};
+static const oid packetcacheHitsOID[] = {RECURSOR_STATS_OID, 8};
+static const oid packetcacheMissesOID[] = {RECURSOR_STATS_OID, 9};
+static const oid packetcacheEntriesOID[] = {RECURSOR_STATS_OID, 10};
+static const oid packetcacheBytesOID[] = {RECURSOR_STATS_OID, 11};
+static const oid mallocBytesOID[] = {RECURSOR_STATS_OID, 12};
+static const oid servfailAnswersOID[] = {RECURSOR_STATS_OID, 13};
+static const oid nxdomainAnswersOID[] = {RECURSOR_STATS_OID, 14};
+static const oid noerrorAnswersOID[] = {RECURSOR_STATS_OID, 15};
+static const oid unauthorizedUdpOID[] = {RECURSOR_STATS_OID, 16};
+static const oid unauthorizedTcpOID[] = {RECURSOR_STATS_OID, 17};
+static const oid tcpClientOverflowOID[] = {RECURSOR_STATS_OID, 18};
+static const oid clientParseErrorsOID[] = {RECURSOR_STATS_OID, 19};
+static const oid serverParseErrorsOID[] = {RECURSOR_STATS_OID, 20};
+static const oid tooOldDropsOID[] = {RECURSOR_STATS_OID, 21};
+static const oid answers01OID[] = {RECURSOR_STATS_OID, 22};
+static const oid answers110OID[] = {RECURSOR_STATS_OID, 23};
+static const oid answers10100OID[] = {RECURSOR_STATS_OID, 24};
+static const oid answers1001000OID[] = {RECURSOR_STATS_OID, 25};
+static const oid answersSlowOID[] = {RECURSOR_STATS_OID, 26};
+static const oid auth4Answers01OID[] = {RECURSOR_STATS_OID, 27};
+static const oid auth4Answers110OID[] = {RECURSOR_STATS_OID, 28};
+static const oid auth4Answers10100OID[] = {RECURSOR_STATS_OID, 29};
+static const oid auth4Answers1001000OID[] = {RECURSOR_STATS_OID, 30};
+static const oid auth4AnswersslowOID[] = {RECURSOR_STATS_OID, 31};
+static const oid auth6Answers01OID[] = {RECURSOR_STATS_OID, 32};
+static const oid auth6Answers110OID[] = {RECURSOR_STATS_OID, 33};
+static const oid auth6Answers10100OID[] = {RECURSOR_STATS_OID, 34};
+static const oid auth6Answers1001000OID[] = {RECURSOR_STATS_OID, 35};
+static const oid auth6AnswersSlowOID[] = {RECURSOR_STATS_OID, 36};
+static const oid qaLatencyOID[] = {RECURSOR_STATS_OID, 37};
+static const oid unexpectedPacketsOID[] = {RECURSOR_STATS_OID, 38};
+static const oid caseMismatchesOID[] = {RECURSOR_STATS_OID, 39};
+static const oid spoofPreventsOID[] = {RECURSOR_STATS_OID, 40};
+static const oid nssetInvalidationsOID[] = {RECURSOR_STATS_OID, 41};
+static const oid resourceLimitsOID[] = {RECURSOR_STATS_OID, 42};
+static const oid overCapacityDropsOID[] = {RECURSOR_STATS_OID, 43};
+static const oid policyDropsOID[] = {RECURSOR_STATS_OID, 44};
+static const oid noPacketErrorOID[] = {RECURSOR_STATS_OID, 45};
+static const oid dlgOnlyDropsOID[] = {RECURSOR_STATS_OID, 46};
+static const oid ignoredPacketsOID[] = {RECURSOR_STATS_OID, 47};
+static const oid maxMthreadStackOID[] = {RECURSOR_STATS_OID, 48};
+static const oid negcacheEntriesOID[] = {RECURSOR_STATS_OID, 49};
+static const oid throttleEntriesOID[] = {RECURSOR_STATS_OID, 50};
+static const oid nsspeedsEntriesOID[] = {RECURSOR_STATS_OID, 51};
+static const oid failedHostEntriesOID[] = {RECURSOR_STATS_OID, 52};
+static const oid concurrentQueriesOID[] = {RECURSOR_STATS_OID, 53};
+static const oid securityStatusOID[] = {RECURSOR_STATS_OID, 54};
+static const oid outgoingTimeoutsOID[] = {RECURSOR_STATS_OID, 55};
+static const oid outgoing4TimeoutsOID[] = {RECURSOR_STATS_OID, 56};
+static const oid outgoing6TimeoutsOID[] = {RECURSOR_STATS_OID, 57};
+static const oid tcpOutqueriesOID[] = {RECURSOR_STATS_OID, 58};
+static const oid allOutqueriesOID[] = {RECURSOR_STATS_OID, 59};
+static const oid ipv6OutqueriesOID[] = {RECURSOR_STATS_OID, 60};
+static const oid throttledOutqueriesOID[] = {RECURSOR_STATS_OID, 61};
+static const oid dontOutqueriesOID[] = {RECURSOR_STATS_OID, 62};
+static const oid unreachablesOID[] = {RECURSOR_STATS_OID, 63};
+static const oid chainResendsOID[] = {RECURSOR_STATS_OID, 64};
+static const oid tcpClientsOID[] = {RECURSOR_STATS_OID, 65};
#ifdef __linux__
-static const oid udpRecvbufErrorsOID[] = { RECURSOR_STATS_OID, 66 };
-static const oid udpSndbufErrorsOID[] = { RECURSOR_STATS_OID, 67 };
-static const oid udpNoportErrorsOID[] = { RECURSOR_STATS_OID, 68 };
-static const oid udpinErrorsOID[] = { RECURSOR_STATS_OID, 69 };
+static const oid udpRecvbufErrorsOID[] = {RECURSOR_STATS_OID, 66};
+static const oid udpSndbufErrorsOID[] = {RECURSOR_STATS_OID, 67};
+static const oid udpNoportErrorsOID[] = {RECURSOR_STATS_OID, 68};
+static const oid udpinErrorsOID[] = {RECURSOR_STATS_OID, 69};
#endif /* __linux__ */
-static const oid ednsPingMatchesOID[] = { RECURSOR_STATS_OID, 70 };
-static const oid ednsPingMismatchesOID[] = { RECURSOR_STATS_OID, 71 };
-static const oid dnssecQueriesOID[] = { RECURSOR_STATS_OID, 72 };
-static const oid nopingOutqueriesOID[] = { RECURSOR_STATS_OID, 73 };
-static const oid noednsOutqueriesOID[] = { RECURSOR_STATS_OID, 74 };
-static const oid uptimeOID[] = { RECURSOR_STATS_OID, 75 };
-static const oid realMemoryUsageOID[] = { RECURSOR_STATS_OID, 76 };
-static const oid fdUsageOID[] = { RECURSOR_STATS_OID, 77 };
-static const oid userMsecOID[] = { RECURSOR_STATS_OID, 78 };
-static const oid sysMsecOID[] = { RECURSOR_STATS_OID, 79 };
-static const oid dnssecValidationsOID[] = { RECURSOR_STATS_OID, 80 };
-static const oid dnssecResultInsecureOID[] = { RECURSOR_STATS_OID, 81 };
-static const oid dnssecResultSecureOID[] = { RECURSOR_STATS_OID, 82 };
-static const oid dnssecResultBogusOID[] = { RECURSOR_STATS_OID, 83 };
-static const oid dnssecResultIndeterminateOID[] = { RECURSOR_STATS_OID, 84 };
-static const oid dnssecResultNtaOID[] = { RECURSOR_STATS_OID, 85 };
-static const oid policyResultNoactionOID[] = { RECURSOR_STATS_OID, 86 };
-static const oid policyResultDropOID[] = { RECURSOR_STATS_OID, 87 };
-static const oid policyResultNxdomainOID[] = { RECURSOR_STATS_OID, 88 };
-static const oid policyResultNodataOID[] = { RECURSOR_STATS_OID, 89 };
-static const oid policyResultTruncateOID[] = { RECURSOR_STATS_OID, 90 };
-static const oid policyResultCustomOID[] = { RECURSOR_STATS_OID, 91 };
-static const oid queryPipeFullDropsOID[] = { RECURSOR_STATS_OID, 92 };
-static const oid truncatedDropsOID[] = { RECURSOR_STATS_OID, 93 };
-static const oid emptyQueriesOID[] = { RECURSOR_STATS_OID, 94 };
-static const oid dnssecAuthenticDataQueriesOID[] = { RECURSOR_STATS_OID, 95 };
-static const oid dnssecCheckDisabledQueriesOID[] = { RECURSOR_STATS_OID, 96 };
-static const oid variableResponsesOID[] = { RECURSOR_STATS_OID, 97 };
-static const oid specialMemoryUsageOID[] = { RECURSOR_STATS_OID, 98 };
-static const oid rebalancedQueriesOID[] = { RECURSOR_STATS_OID, 99 };
-static const oid qnameMinFallbackSuccessOID[] = { RECURSOR_STATS_OID, 100 };
-static const oid proxyProtocolInvalidOID[] = { RECURSOR_STATS_OID, 101 };
-static const oid recordCacheContendedOID[] = { RECURSOR_STATS_OID, 102 };
-static const oid recordCacheAcquiredOID[] = { RECURSOR_STATS_OID, 103 };
-static const oid nodLookupsDroppedOversizeOID[] = { RECURSOR_STATS_OID, 104 };
-static const oid taskQueuePushedOID[] = { RECURSOR_STATS_OID, 105 };
-static const oid taskQueueExpiredOID[] = { RECURSOR_STATS_OID, 106 };
-static const oid taskQueueSizeOID[] = { RECURSOR_STATS_OID, 107 };
-static const oid aggressiveNSECCacheEntriesOID[] = { RECURSOR_STATS_OID, 108 };
-static const oid aggressiveNSECCacheNSECHitsOID[] = { RECURSOR_STATS_OID, 109 };
-static const oid aggressiveNSECCacheNSEC3HitsOID[] = { RECURSOR_STATS_OID, 110 };
-static const oid aggressiveNSECCacheNSECWCHitsOID[] = { RECURSOR_STATS_OID, 111 };
-static const oid aggressiveNSECCacheNSEC3WCHitsOID[] = { RECURSOR_STATS_OID, 112 };
-static const oid dotOutqueriesOID [] = { RECURSOR_STATS_OID, 113 };
-static const oid dns64PrefixAnswers [] = { RECURSOR_STATS_OID, 114 };
-static const oid almostExpiredPushed [] = { RECURSOR_STATS_OID, 115 };
-static const oid almostExpiredRun [] = { RECURSOR_STATS_OID, 116 };
-static const oid almostExpiredExceptions [] = { RECURSOR_STATS_OID, 117 };
+static const oid ednsPingMatchesOID[] = {RECURSOR_STATS_OID, 70};
+static const oid ednsPingMismatchesOID[] = {RECURSOR_STATS_OID, 71};
+static const oid dnssecQueriesOID[] = {RECURSOR_STATS_OID, 72};
+static const oid nopingOutqueriesOID[] = {RECURSOR_STATS_OID, 73};
+static const oid noednsOutqueriesOID[] = {RECURSOR_STATS_OID, 74};
+static const oid uptimeOID[] = {RECURSOR_STATS_OID, 75};
+static const oid realMemoryUsageOID[] = {RECURSOR_STATS_OID, 76};
+static const oid fdUsageOID[] = {RECURSOR_STATS_OID, 77};
+static const oid userMsecOID[] = {RECURSOR_STATS_OID, 78};
+static const oid sysMsecOID[] = {RECURSOR_STATS_OID, 79};
+static const oid dnssecValidationsOID[] = {RECURSOR_STATS_OID, 80};
+static const oid dnssecResultInsecureOID[] = {RECURSOR_STATS_OID, 81};
+static const oid dnssecResultSecureOID[] = {RECURSOR_STATS_OID, 82};
+static const oid dnssecResultBogusOID[] = {RECURSOR_STATS_OID, 83};
+static const oid dnssecResultIndeterminateOID[] = {RECURSOR_STATS_OID, 84};
+static const oid dnssecResultNtaOID[] = {RECURSOR_STATS_OID, 85};
+static const oid policyResultNoactionOID[] = {RECURSOR_STATS_OID, 86};
+static const oid policyResultDropOID[] = {RECURSOR_STATS_OID, 87};
+static const oid policyResultNxdomainOID[] = {RECURSOR_STATS_OID, 88};
+static const oid policyResultNodataOID[] = {RECURSOR_STATS_OID, 89};
+static const oid policyResultTruncateOID[] = {RECURSOR_STATS_OID, 90};
+static const oid policyResultCustomOID[] = {RECURSOR_STATS_OID, 91};
+static const oid queryPipeFullDropsOID[] = {RECURSOR_STATS_OID, 92};
+static const oid truncatedDropsOID[] = {RECURSOR_STATS_OID, 93};
+static const oid emptyQueriesOID[] = {RECURSOR_STATS_OID, 94};
+static const oid dnssecAuthenticDataQueriesOID[] = {RECURSOR_STATS_OID, 95};
+static const oid dnssecCheckDisabledQueriesOID[] = {RECURSOR_STATS_OID, 96};
+static const oid variableResponsesOID[] = {RECURSOR_STATS_OID, 97};
+static const oid specialMemoryUsageOID[] = {RECURSOR_STATS_OID, 98};
+static const oid rebalancedQueriesOID[] = {RECURSOR_STATS_OID, 99};
+static const oid qnameMinFallbackSuccessOID[] = {RECURSOR_STATS_OID, 100};
+static const oid proxyProtocolInvalidOID[] = {RECURSOR_STATS_OID, 101};
+static const oid recordCacheContendedOID[] = {RECURSOR_STATS_OID, 102};
+static const oid recordCacheAcquiredOID[] = {RECURSOR_STATS_OID, 103};
+static const oid nodLookupsDroppedOversizeOID[] = {RECURSOR_STATS_OID, 104};
+static const oid taskQueuePushedOID[] = {RECURSOR_STATS_OID, 105};
+static const oid taskQueueExpiredOID[] = {RECURSOR_STATS_OID, 106};
+static const oid taskQueueSizeOID[] = {RECURSOR_STATS_OID, 107};
+static const oid aggressiveNSECCacheEntriesOID[] = {RECURSOR_STATS_OID, 108};
+static const oid aggressiveNSECCacheNSECHitsOID[] = {RECURSOR_STATS_OID, 109};
+static const oid aggressiveNSECCacheNSEC3HitsOID[] = {RECURSOR_STATS_OID, 110};
+static const oid aggressiveNSECCacheNSECWCHitsOID[] = {RECURSOR_STATS_OID, 111};
+static const oid aggressiveNSECCacheNSEC3WCHitsOID[] = {RECURSOR_STATS_OID, 112};
+static const oid dotOutqueriesOID[] = {RECURSOR_STATS_OID, 113};
+static const oid dns64PrefixAnswers[] = {RECURSOR_STATS_OID, 114};
+static const oid almostExpiredPushed[] = {RECURSOR_STATS_OID, 115};
+static const oid almostExpiredRun[] = {RECURSOR_STATS_OID, 116};
+static const oid almostExpiredExceptions[] = {RECURSOR_STATS_OID, 117};
static std::unordered_map<oid, std::string> s_statsMap;
boost::optional<uint64_t> value = getStatByName(it->second);
if (value) {
return RecursorSNMPAgent::setCounter64Value(requests, *value);
- } else {
+ }
+ else {
return RecursorSNMPAgent::setCounter64Value(requests, 0);
}
}
static void registerCounter64Stat(const std::string& name, const oid statOID[], size_t statOIDLength)
{
if (statOIDLength != OID_LENGTH(questionsOID)) {
- g_log<<Logger::Error<<"Invalid OID for SNMP Counter64 statistic "<<name<<endl;
+ g_log << Logger::Error << "Invalid OID for SNMP Counter64 statistic " << name << endl;
return;
}
if (s_statsMap.find(statOID[statOIDLength - 1]) != s_statsMap.end()) {
- g_log<<Logger::Error<<"OID for SNMP Counter64 statistic "<<name<<" has already been registered"<<endl;
+ g_log << Logger::Error << "OID for SNMP Counter64 statistic " << name << " has already been registered" << endl;
return;
}
s_statsMap[statOID[statOIDLength - 1]] = name.c_str();
netsnmp_register_scalar(netsnmp_create_handler_registration(name.c_str(),
- isStatDisabled(StatComponent::SNMP, name) ?
- handleDisabledCounter64Stats : handleCounter64Stats,
+ isStatDisabled(StatComponent::SNMP, name) ? handleDisabledCounter64Stats : handleCounter64Stats,
statOID,
statOIDLength,
HANDLER_CAN_RONLY));
snmpTrapOIDLen,
ASN_OBJECT_ID,
customTrapOID,
- OID_LENGTH(customTrapOID) * sizeof(oid));
+ OID_LENGTH(customTrapOID) * sizeof(oid));
snmp_varlist_add_variable(&varList,
trapReasonOID,
return true;
}
-
-RecursorSNMPAgent::RecursorSNMPAgent(const std::string& name, const std::string& masterSocket): SNMPAgent(name, masterSocket)
+RecursorSNMPAgent::RecursorSNMPAgent(const std::string& name, const std::string& masterSocket) :
+ SNMPAgent(name, masterSocket)
{
#ifdef HAVE_NET_SNMP
/* This is done so that the statistics maps are
class RecursorSNMPAgent;
-class RecursorSNMPAgent: public SNMPAgent
+class RecursorSNMPAgent : public SNMPAgent
{
public:
RecursorSNMPAgent(const std::string& name, const std::string& daemonSocket);
RecursorControlChannel::RecursorControlChannel()
{
- d_fd=-1;
- *d_local.sun_path=0;
- d_local.sun_family=0;
+ d_fd = -1;
+ *d_local.sun_path = 0;
+ d_local.sun_family = 0;
}
-RecursorControlChannel::~RecursorControlChannel()
+RecursorControlChannel::~RecursorControlChannel()
{
- if(d_fd > 0)
+ if (d_fd > 0)
close(d_fd);
- if(*d_local.sun_path)
+ if (*d_local.sun_path)
unlink(d_local.sun_path);
}
static void setSocketBuffer(int fd, int optname, uint32_t size)
{
- uint32_t psize=0;
- socklen_t len=sizeof(psize);
+ uint32_t psize = 0;
+ socklen_t len = sizeof(psize);
if (getsockopt(fd, SOL_SOCKET, optname, (void*)&psize, &len))
- throw PDNSException("Unable to getsocket buffer size: "+stringerror());
+ throw PDNSException("Unable to getsocket buffer size: " + stringerror());
if (psize > size)
return;
-
+
// failure to raise is not fatal
(void)setsockopt(fd, SOL_SOCKET, optname, (const void*)&size, sizeof(size));
}
-
static void setSocketReceiveBuffer(int fd, uint32_t size)
{
setSocketBuffer(fd, SO_RCVBUF, size);
int RecursorControlChannel::listen(const string& fname)
{
- d_fd=socket(AF_UNIX,SOCK_DGRAM,0);
+ d_fd = socket(AF_UNIX, SOCK_DGRAM, 0);
setCloseOnExec(d_fd);
- if(d_fd < 0)
- throw PDNSException("Creating UNIX domain socket: "+stringerror());
-
- int tmp=1;
- if(setsockopt(d_fd, SOL_SOCKET, SO_REUSEADDR,(char*)&tmp,sizeof tmp)<0)
- throw PDNSException("Setsockopt failed: "+stringerror());
-
- int err=unlink(fname.c_str());
- if(err < 0 && errno!=ENOENT)
- throw PDNSException("Can't remove (previous) controlsocket '"+fname+"': "+stringerror() + " (try --socket-dir)");
-
- if(makeUNsockaddr(fname, &d_local))
- throw PDNSException("Unable to bind to controlsocket, path '"+fname+"' is not a valid UNIX socket path.");
-
- if(bind(d_fd, (sockaddr*)&d_local,sizeof(d_local))<0)
- throw PDNSException("Unable to bind to controlsocket '"+fname+"': "+stringerror());
+ if (d_fd < 0)
+ throw PDNSException("Creating UNIX domain socket: " + stringerror());
+
+ int tmp = 1;
+ if (setsockopt(d_fd, SOL_SOCKET, SO_REUSEADDR, (char*)&tmp, sizeof tmp) < 0)
+ throw PDNSException("Setsockopt failed: " + stringerror());
+
+ int err = unlink(fname.c_str());
+ if (err < 0 && errno != ENOENT)
+ throw PDNSException("Can't remove (previous) controlsocket '" + fname + "': " + stringerror() + " (try --socket-dir)");
+
+ if (makeUNsockaddr(fname, &d_local))
+ throw PDNSException("Unable to bind to controlsocket, path '" + fname + "' is not a valid UNIX socket path.");
+
+ if (bind(d_fd, (sockaddr*)&d_local, sizeof(d_local)) < 0)
+ throw PDNSException("Unable to bind to controlsocket '" + fname + "': " + stringerror());
// receive buf should be size of max datagram plus address size
setSocketReceiveBuffer(d_fd, 60 * 1024);
setSocketSendBuffer(d_fd, 64 * 1024);
-
+
return d_fd;
}
{
struct sockaddr_un remote;
- d_fd=socket(AF_UNIX,SOCK_DGRAM,0);
+ d_fd = socket(AF_UNIX, SOCK_DGRAM, 0);
setCloseOnExec(d_fd);
- if(d_fd < 0)
- throw PDNSException("Creating UNIX domain socket: "+stringerror());
+ if (d_fd < 0)
+ throw PDNSException("Creating UNIX domain socket: " + stringerror());
try {
- int tmp=1;
- if(setsockopt(d_fd, SOL_SOCKET, SO_REUSEADDR,(char*)&tmp,sizeof tmp)<0)
- throw PDNSException("Setsockopt failed: "+stringerror());
-
- string localname=path+"/lsockXXXXXX";
- *d_local.sun_path=0;
+ int tmp = 1;
+ if (setsockopt(d_fd, SOL_SOCKET, SO_REUSEADDR, (char*)&tmp, sizeof tmp) < 0)
+ throw PDNSException("Setsockopt failed: " + stringerror());
+
+ string localname = path + "/lsockXXXXXX";
+ *d_local.sun_path = 0;
if (makeUNsockaddr(localname, &d_local))
- throw PDNSException("Unable to bind to local temporary file, path '"+localname+"' is not a valid UNIX socket path.");
+ throw PDNSException("Unable to bind to local temporary file, path '" + localname + "' is not a valid UNIX socket path.");
- if(mkstemp(d_local.sun_path) < 0)
- throw PDNSException("Unable to generate local temporary file in directory '"+path+"': "+stringerror());
+ if (mkstemp(d_local.sun_path) < 0)
+ throw PDNSException("Unable to generate local temporary file in directory '" + path + "': " + stringerror());
- int err=unlink(d_local.sun_path);
- if(err < 0 && errno!=ENOENT)
- throw PDNSException("Unable to remove local controlsocket: "+stringerror());
+ int err = unlink(d_local.sun_path);
+ if (err < 0 && errno != ENOENT)
+ throw PDNSException("Unable to remove local controlsocket: " + stringerror());
- if(bind(d_fd, (sockaddr*)&d_local,sizeof(d_local))<0)
- throw PDNSException("Unable to bind to local temporary file: "+stringerror());
+ if (bind(d_fd, (sockaddr*)&d_local, sizeof(d_local)) < 0)
+ throw PDNSException("Unable to bind to local temporary file: " + stringerror());
- if(chmod(d_local.sun_path,0666)<0) // make sure that pdns can reply!
- throw PDNSException("Unable to chmod local temporary socket: "+stringerror());
+ if (chmod(d_local.sun_path, 0666) < 0) // make sure that pdns can reply!
+ throw PDNSException("Unable to chmod local temporary socket: " + stringerror());
- string remotename=path+"/"+fname;
+ string remotename = path + "/" + fname;
if (makeUNsockaddr(remotename, &remote))
- throw PDNSException("Unable to connect to controlsocket, path '"+remotename+"' is not a valid UNIX socket path.");
+ throw PDNSException("Unable to connect to controlsocket, path '" + remotename + "' is not a valid UNIX socket path.");
- if(::connect(d_fd, (sockaddr*)&remote, sizeof(remote)) < 0) {
- if(*d_local.sun_path)
- unlink(d_local.sun_path);
- throw PDNSException("Unable to connect to remote '"+string(remote.sun_path)+"': "+stringerror());
+ if (::connect(d_fd, (sockaddr*)&remote, sizeof(remote)) < 0) {
+ if (*d_local.sun_path)
+ unlink(d_local.sun_path);
+ throw PDNSException("Unable to connect to remote '" + string(remote.sun_path) + "': " + stringerror());
}
// receive buf should be size of max datagram plus address size
setSocketReceiveBuffer(d_fd, 60 * 1024);
setSocketSendBuffer(d_fd, 64 * 1024);
-
- } catch (...) {
+ }
+ catch (...) {
close(d_fd);
- d_fd=-1;
- d_local.sun_path[0]=0;
+ d_fd = -1;
+ d_local.sun_path[0] = 0;
throw;
}
}
static void sendfd(int s, int fd, const string* remote)
{
- struct msghdr msg;
- struct cmsghdr *cmsg;
- union {
+ struct msghdr msg;
+ struct cmsghdr* cmsg;
+ union
+ {
struct cmsghdr hdr;
- unsigned char buf[CMSG_SPACE(sizeof(int))];
+ unsigned char buf[CMSG_SPACE(sizeof(int))];
} cmsgbuf;
struct iovec io_vector[1];
char ch = 'X';
-
+
io_vector[0].iov_base = &ch;
io_vector[0].iov_len = 1;
cmsg->cmsg_len = CMSG_LEN(sizeof(int));
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
- *(int *)CMSG_DATA(cmsg) = fd;
+ *(int*)CMSG_DATA(cmsg) = fd;
if (sendmsg(s, &msg, 0) == -1) {
- throw PDNSException("Unable to send fd message over control channel: "+stringerror());
+ throw PDNSException("Unable to send fd message over control channel: " + stringerror());
}
}
void RecursorControlChannel::send(const Answer& msg, const std::string* remote, unsigned int timeout, int fd)
{
int ret = waitForRWData(d_fd, false, timeout, 0);
- if(ret == 0) {
+ if (ret == 0) {
throw PDNSException("Timeout sending message over control channel");
}
- else if(ret < 0) {
+ else if (ret < 0) {
throw PDNSException("Error sending message over control channel:" + stringerror());
}
- if(remote) {
+ if (remote) {
struct sockaddr_un remoteaddr;
memset(&remoteaddr, 0, sizeof(remoteaddr));
-
- remoteaddr.sun_family=AF_UNIX;
- strncpy(remoteaddr.sun_path, remote->c_str(), sizeof(remoteaddr.sun_path)-1);
- remoteaddr.sun_path[sizeof(remoteaddr.sun_path)-1] = '\0';
-
- if(::sendto(d_fd, &msg.d_ret, sizeof(msg.d_ret), 0, (struct sockaddr*) &remoteaddr, sizeof(remoteaddr) ) < 0)
- throw PDNSException("Unable to send message over control channel '"+string(remoteaddr.sun_path)+"': "+stringerror());
- if(::sendto(d_fd, msg.d_str.c_str(), msg.d_str.length(), 0, (struct sockaddr*) &remoteaddr, sizeof(remoteaddr) ) < 0)
- throw PDNSException("Unable to send message over control channel '"+string(remoteaddr.sun_path)+"': "+stringerror());
+
+ remoteaddr.sun_family = AF_UNIX;
+ strncpy(remoteaddr.sun_path, remote->c_str(), sizeof(remoteaddr.sun_path) - 1);
+ remoteaddr.sun_path[sizeof(remoteaddr.sun_path) - 1] = '\0';
+
+ if (::sendto(d_fd, &msg.d_ret, sizeof(msg.d_ret), 0, (struct sockaddr*)&remoteaddr, sizeof(remoteaddr)) < 0)
+ throw PDNSException("Unable to send message over control channel '" + string(remoteaddr.sun_path) + "': " + stringerror());
+ if (::sendto(d_fd, msg.d_str.c_str(), msg.d_str.length(), 0, (struct sockaddr*)&remoteaddr, sizeof(remoteaddr)) < 0)
+ throw PDNSException("Unable to send message over control channel '" + string(remoteaddr.sun_path) + "': " + stringerror());
}
else {
- if(::send(d_fd, &msg.d_ret, sizeof(msg.d_ret), 0) < 0)
- throw PDNSException("Unable to send message over control channel: "+stringerror());
- if(::send(d_fd, msg.d_str.c_str(), msg.d_str.length(), 0) < 0)
- throw PDNSException("Unable to send message over control channel: "+stringerror());
+ if (::send(d_fd, &msg.d_ret, sizeof(msg.d_ret), 0) < 0)
+ throw PDNSException("Unable to send message over control channel: " + stringerror());
+ if (::send(d_fd, msg.d_str.c_str(), msg.d_str.length(), 0) < 0)
+ throw PDNSException("Unable to send message over control channel: " + stringerror());
}
if (fd != -1) {
sendfd(d_fd, fd, remote);
throw PDNSException("Unable to receive return status over control channel1: " + stringerror());
}
if ((len = ::recvfrom(d_fd, buffer, sizeof(buffer), 0, (struct sockaddr*)&remoteaddr, &addrlen)) < 0) {
- throw PDNSException("Unable to receive message over control channel2: "+stringerror());
+ throw PDNSException("Unable to receive message over control channel2: " + stringerror());
}
- if(remote) {
- *remote=remoteaddr.sun_path;
+ if (remote) {
+ *remote = remoteaddr.sun_path;
}
return {err, string(buffer, buffer + len)};
}
-
RecursorControlParser()
{
}
- static void nop(void){}
+ static void nop(void) {}
typedef void func_t(void);
RecursorControlChannel::Answer getAnswer(int s, const std::string& question, func_t** func);
};
+enum class StatComponent
+{
+ API,
+ Carbon,
+ RecControl,
+ SNMP
+};
-enum class StatComponent { API, Carbon, RecControl, SNMP };
-
-struct StatsMapEntry {
+struct StatsMapEntry
+{
std::string d_prometheusName;
std::string d_value;
};
{
private:
static std::pair<std::string, std::string> prefixAndTrailingNum(const std::string& a);
+
public:
bool operator()(const std::string& a, const std::string& b) const;
};
extern GlobalStateHolder<CarbonConfig> g_carbonConfig;
-std::vector<std::pair<DNSName, uint16_t> >* pleaseGetQueryRing();
-std::vector<std::pair<DNSName, uint16_t> >* pleaseGetServfailQueryRing();
-std::vector<std::pair<DNSName, uint16_t> >* pleaseGetBogusQueryRing();
+std::vector<std::pair<DNSName, uint16_t>>* pleaseGetQueryRing();
+std::vector<std::pair<DNSName, uint16_t>>* pleaseGetServfailQueryRing();
+std::vector<std::pair<DNSName, uint16_t>>* pleaseGetBogusQueryRing();
std::vector<ComboAddress>* pleaseGetRemotes();
std::vector<ComboAddress>* pleaseGetServfailRemotes();
std::vector<ComboAddress>* pleaseGetBogusRemotes();
static map<string, const uint32_t*> d_get32bitpointers;
static map<string, const pdns::stat_t*> d_getatomics;
-static map<string, std::function<uint64_t()>> d_get64bitmembers;
+static map<string, std::function<uint64_t()>> d_get64bitmembers;
static map<string, std::function<StatsMap()>> d_getmultimembers;
-struct dynmetrics {
- std::atomic<unsigned long> *d_ptr;
+struct dynmetrics
+{
+ std::atomic<unsigned long>* d_ptr;
std::string d_prometheusName;
};
std::vector<std::string> disabledStats;
stringtok(disabledStats, stats, ", ");
auto& map = s_disabledStats[component];
- for (const auto &st : disabledStats) {
+ for (const auto& st : disabledStats) {
map.insert(st);
}
}
static std::string getPrometheusName(const std::string& arg)
{
std::string name = arg;
- std::replace_if(name.begin(), name.end(), [](char c){
- return !isalnum(static_cast<unsigned char>(c));}, '_');
+ std::replace_if(
+ name.begin(), name.end(), [](char c) { return !isalnum(static_cast<unsigned char>(c)); }, '_');
return "pdns_recursor_" + name;
}
std::string name(str);
if (!prometheusName.empty()) {
name = prometheusName;
- } else {
+ }
+ else {
name = getPrometheusName(name);
}
auto ret = dynmetrics{new std::atomic<unsigned long>(), name};
- (*dm)[str]= ret;
+ (*dm)[str] = ret;
return ret.d_ptr;
}
{
boost::optional<uint64_t> ret;
- if(d_get32bitpointers.count(name))
+ if (d_get32bitpointers.count(name))
return *d_get32bitpointers.find(name)->second;
- if(d_getatomics.count(name))
+ if (d_getatomics.count(name))
return d_getatomics.find(name)->second->load();
- if(d_get64bitmembers.count(name))
+ if (d_get64bitmembers.count(name))
return d_get64bitmembers.find(name)->second();
{
}
}
- for(const auto& themultimember : d_getmultimembers) {
+ for (const auto& themultimember : d_getmultimembers) {
const auto items = themultimember.second();
const auto item = items.find(name);
if (item != items.end()) {
StatsMap ret;
const auto& disabledlistMap = s_disabledStats.at(component);
- for(const auto& the32bits : d_get32bitpointers) {
+ for (const auto& the32bits : d_get32bitpointers) {
if (disabledlistMap.count(the32bits.first) == 0) {
ret.emplace(the32bits.first, StatsMapEntry{getPrometheusName(the32bits.first), std::to_string(*the32bits.second)});
}
}
- for(const auto& atomic : d_getatomics) {
+ for (const auto& atomic : d_getatomics) {
if (disabledlistMap.count(atomic.first) == 0) {
ret.emplace(atomic.first, StatsMapEntry{getPrometheusName(atomic.first), std::to_string(atomic.second->load())});
}
}
- for(const auto& the64bitmembers : d_get64bitmembers) {
+ for (const auto& the64bitmembers : d_get64bitmembers) {
if (disabledlistMap.count(the64bitmembers.first) == 0) {
ret.emplace(the64bitmembers.first, StatsMapEntry{getPrometheusName(the64bitmembers.first), std::to_string(the64bitmembers.second())});
}
}
- for(const auto& themultimember : d_getmultimembers) {
+ for (const auto& themultimember : d_getmultimembers) {
if (disabledlistMap.count(themultimember.first) == 0) {
ret.merge(themultimember.second());
}
}
{
- for(const auto& a : *(d_dynmetrics.lock())) {
+ for (const auto& a : *(d_dynmetrics.lock())) {
if (disabledlistMap.count(a.first) == 0) {
ret.emplace(a.first, StatsMapEntry{a.second.d_prometheusName, std::to_string(*a.second.d_ptr)});
}
return ret;
}
-template<typename T>
+template <typename T>
static string doGet(T begin, T end)
{
string ret;
- for(T i=begin; i != end; ++i) {
- boost::optional<uint64_t> num=get(*i);
- if(num)
- ret+=std::to_string(*num)+"\n";
+ for (T i = begin; i != end; ++i) {
+ boost::optional<uint64_t> num = get(*i);
+ if (num)
+ ret += std::to_string(*num) + "\n";
else
- ret+="UNKNOWN\n";
+ ret += "UNKNOWN\n";
}
return ret;
}
-template<typename T>
+template <typename T>
string static doGetParameter(T begin, T end)
{
string ret;
string parm;
using boost::replace_all;
- for(T i=begin; i != end; ++i) {
- if(::arg().parmIsset(*i)) {
- parm=::arg()[*i];
+ for (T i = begin; i != end; ++i) {
+ if (::arg().parmIsset(*i)) {
+ parm = ::arg()[*i];
replace_all(parm, "\\", "\\\\");
replace_all(parm, "\"", "\\\"");
replace_all(parm, "\n", "\\n");
- ret += *i +"=\""+ parm +"\"\n";
+ ret += *i + "=\"" + parm + "\"\n";
}
else
- ret += *i +" not known\n";
+ ret += *i + " not known\n";
}
return ret;
}
getfd(int s)
{
int fd = -1;
- struct msghdr msg;
- struct cmsghdr *cmsg;
- union {
+ struct msghdr msg;
+ struct cmsghdr* cmsg;
+ union
+ {
struct cmsghdr hdr;
- unsigned char buf[CMSG_SPACE(sizeof(int))];
+ unsigned char buf[CMSG_SPACE(sizeof(int))];
} cmsgbuf;
struct iovec io_vector[1];
char ch;
}
for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL;
cmsg = CMSG_NXTHDR(&msg, cmsg)) {
- if (cmsg->cmsg_len == CMSG_LEN(sizeof(int)) &&
- cmsg->cmsg_level == SOL_SOCKET &&
- cmsg->cmsg_type == SCM_RIGHTS) {
- fd = *(int *)CMSG_DATA(cmsg);
+ if (cmsg->cmsg_len == CMSG_LEN(sizeof(int)) && cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
+ fd = *(int*)CMSG_DATA(cmsg);
break;
}
}
return FDWrapper(fd);
}
-
static uint64_t dumpNegCache(int fd)
{
int newfd = dup(fd);
if (newfd == -1) {
return 0;
}
- auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fdopen(newfd, "w"), fclose);
+ auto fp = std::unique_ptr<FILE, int (*)(FILE*)>(fdopen(newfd, "w"), fclose);
if (!fp) {
return 0;
}
if (newfd == -1) {
return 0;
}
- auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fdopen(newfd, "w"), fclose);
+ auto fp = std::unique_ptr<FILE, int (*)(FILE*)>(fdopen(newfd, "w"), fclose);
if (!fp) {
return 0;
}
auto fdw = getfd(s);
if (fdw < 0) {
- return { 1, name + ": error opening dump file for writing: " + stringerror() + "\n" };
+ return {1, name + ": error opening dump file for writing: " + stringerror() + "\n"};
}
uint64_t total = 0;
try {
int fd = fdw;
- total = broadcastAccFunction<uint64_t>([function, fd]{ return function(fd); });
+ total = broadcastAccFunction<uint64_t>([function, fd] { return function(fd); });
}
- catch(std::exception& e)
- {
- return { 1, name + ": error dumping data: " + string(e.what()) + "\n" };
+ catch (std::exception& e) {
+ return {1, name + ": error dumping data: " + string(e.what()) + "\n"};
}
- catch(PDNSException& e)
- {
- return { 1, name + ": error dumping data: " + e.reason + "\n" };
+ catch (PDNSException& e) {
+ return {1, name + ": error dumping data: " + e.reason + "\n"};
}
- return { 0, name + ": dumped " + std::to_string(total) + " records\n" };
+ return {0, name + ": dumped " + std::to_string(total) + " records\n"};
}
// Does not follow the generic dump to file pattern, has a more complex lambda
auto fdw = getfd(s);
if (fdw < 0) {
- return { 1, "Error opening dump file for writing: " + stringerror() + "\n" };
+ return {1, "Error opening dump file for writing: " + stringerror() + "\n"};
}
uint64_t total = 0;
try {
int fd = fdw;
- total = g_recCache->doDump(fd) + dumpNegCache(fd) + broadcastAccFunction<uint64_t>([fd]{ return pleaseDump(fd); }) + dumpAggressiveNSECCache(fd);
+ total = g_recCache->doDump(fd) + dumpNegCache(fd) + broadcastAccFunction<uint64_t>([fd] { return pleaseDump(fd); }) + dumpAggressiveNSECCache(fd);
+ }
+ catch (...) {
}
- catch(...){}
- return { 0, "dumped " + std::to_string(total) + " records\n" };
+ return {0, "dumped " + std::to_string(total) + " records\n"};
}
// Does not follow the generic dump to file pattern, has an argument
-template<typename T>
+template <typename T>
static RecursorControlChannel::Answer doDumpRPZ(int s, T begin, T end)
{
auto fdw = getfd(s);
if (fdw < 0) {
- return { 1, "Error opening dump file for writing: " + stringerror() + "\n" };
+ return {1, "Error opening dump file for writing: " + stringerror() + "\n"};
}
T i = begin;
if (i == end) {
- return { 1, "No zone name specified\n" };
+ return {1, "No zone name specified\n"};
}
string zoneName = *i;
auto luaconf = g_luaconfs.getLocal();
const auto zone = luaconf->dfe.getZone(zoneName);
if (!zone) {
- return { 1, "No RPZ zone named " + zoneName + "\n" };
+ return {1, "No RPZ zone named " + zoneName + "\n"};
}
-
- auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fdopen(fdw, "w"), fclose);
+ auto fp = std::unique_ptr<FILE, int (*)(FILE*)>(fdopen(fdw, "w"), fclose);
if (!fp) {
int err = errno;
- return { 1, "converting file descriptor: " + stringerror(err) + "\n" };
+ return {1, "converting file descriptor: " + stringerror(err) + "\n"};
}
zone->dump(fp.get());
return new uint64_t(t_packetCache->doWipePacketCache(canon, qtype, subtree));
}
-template<typename T>
+template <typename T>
static string doWipeCache(T begin, T end, uint16_t qtype)
{
- vector<pair<DNSName, bool> > toWipe;
- for(T i=begin; i != end; ++i) {
+ vector<pair<DNSName, bool>> toWipe;
+ for (T i = begin; i != end; ++i) {
DNSName canon;
- bool subtree=false;
+ bool subtree = false;
try {
- if(boost::ends_with(*i, "$")) {
- canon=DNSName(i->substr(0, i->size()-1));
- subtree=true;
- } else {
- canon=DNSName(*i);
+ if (boost::ends_with(*i, "$")) {
+ canon = DNSName(i->substr(0, i->size() - 1));
+ subtree = true;
}
- } catch (std::exception &e) {
+ else {
+ canon = DNSName(*i);
+ }
+ }
+ catch (std::exception& e) {
return "Error: " + std::string(e.what()) + ", nothing wiped\n";
}
toWipe.emplace_back(canon, subtree);
}
- int count=0, pcount=0, countNeg=0;
+ int count = 0, pcount = 0, countNeg = 0;
for (auto wipe : toWipe) {
try {
count += g_recCache->doWipeCache(wipe.first, wipe.second, qtype);
- pcount += broadcastAccFunction<uint64_t>([=]{ return pleaseWipePacketCache(wipe.first, wipe.second, qtype);});
+ pcount += broadcastAccFunction<uint64_t>([=] { return pleaseWipePacketCache(wipe.first, wipe.second, qtype); });
countNeg += g_negCache->wipe(wipe.first, wipe.second);
if (g_aggressiveNSECCache) {
g_aggressiveNSECCache->removeZoneInfo(wipe.first, wipe.second);
}
}
catch (const std::exception& e) {
- g_log<<Logger::Warning<<", failed: "<<e.what()<<endl;
+ g_log << Logger::Warning << ", failed: " << e.what() << endl;
}
}
- return "wiped " + std::to_string(count)+" records, " + std::to_string(countNeg)+" negative records, " + std::to_string(pcount)+" packets\n";
+ return "wiped " + std::to_string(count) + " records, " + std::to_string(countNeg) + " negative records, " + std::to_string(pcount) + " packets\n";
}
-template<typename T>
+template <typename T>
static string doSetCarbonServer(T begin, T end)
{
auto config = g_carbonConfig.getCopy();
if (begin != end) {
config.hostname = *begin;
ret += "set carbon-ourname to '" + *begin + "'\n";
- } else {
+ }
+ else {
g_carbonConfig.setState(std::move(config));
return ret;
}
if (begin != end) {
config.namespace_name = *begin;
ret += "set carbon-namespace to '" + *begin + "'\n";
- } else {
+ }
+ else {
g_carbonConfig.setState(std::move(config));
return ret;
}
return ret;
}
-template<typename T>
+template <typename T>
static string doSetDnssecLogBogus(T begin, T end)
{
- if(checkDNSSECDisabled())
+ if (checkDNSSECDisabled())
return "DNSSEC is disabled in the configuration, not changing the Bogus logging setting\n";
if (begin == end)
if (pdns_iequals(*begin, "on") || pdns_iequals(*begin, "yes")) {
if (!g_dnssecLogBogus) {
- g_log<<Logger::Warning<<"Enabling DNSSEC Bogus logging, requested via control channel"<<endl;
+ g_log << Logger::Warning << "Enabling DNSSEC Bogus logging, requested via control channel" << endl;
g_dnssecLogBogus = true;
return "DNSSEC Bogus logging enabled\n";
}
if (pdns_iequals(*begin, "off") || pdns_iequals(*begin, "no")) {
if (g_dnssecLogBogus) {
- g_log<<Logger::Warning<<"Disabling DNSSEC Bogus logging, requested via control channel"<<endl;
+ g_log << Logger::Warning << "Disabling DNSSEC Bogus logging, requested via control channel" << endl;
g_dnssecLogBogus = false;
return "DNSSEC Bogus logging disabled\n";
}
return "DNSSEC Bogus logging was already disabled\n";
}
- return "Unknown DNSSEC Bogus setting: '" + *begin +"'\n";
+ return "Unknown DNSSEC Bogus setting: '" + *begin + "'\n";
}
-template<typename T>
+template <typename T>
static string doAddNTA(T begin, T end)
{
- if(checkDNSSECDisabled())
+ if (checkDNSSECDisabled())
return "DNSSEC is disabled in the configuration, not adding a Negative Trust Anchor\n";
- if(begin == end)
+ if (begin == end)
return "No NTA specified, doing nothing\n";
DNSName who;
try {
who = DNSName(*begin);
}
- catch(std::exception &e) {
+ catch (std::exception& e) {
string ret("Can't add Negative Trust Anchor: ");
ret += e.what();
ret += "\n";
if (begin != end)
why += " ";
}
- g_log<<Logger::Warning<<"Adding Negative Trust Anchor for "<<who<<" with reason '"<<why<<"', requested via control channel"<<endl;
+ g_log << Logger::Warning << "Adding Negative Trust Anchor for " << who << " with reason '" << why << "', requested via control channel" << endl;
g_luaconfs.modify([who, why](LuaConfigItems& lci) {
- lci.negAnchors[who] = why;
- });
+ lci.negAnchors[who] = why;
+ });
try {
g_recCache->doWipeCache(who, true, 0xffff);
- broadcastAccFunction<uint64_t>([=]{return pleaseWipePacketCache(who, true, 0xffff);});
+ broadcastAccFunction<uint64_t>([=] { return pleaseWipePacketCache(who, true, 0xffff); });
g_negCache->wipe(who, true);
if (g_aggressiveNSECCache) {
g_aggressiveNSECCache->removeZoneInfo(who, true);
}
}
catch (std::exception& e) {
- g_log<<Logger::Warning<<", failed: "<<e.what()<<endl;
+ g_log << Logger::Warning << ", failed: " << e.what() << endl;
return "Unable to clear caches while adding Negative Trust Anchor for " + who.toStringRootDot() + ": " + e.what() + "\n";
}
return "Added Negative Trust Anchor for " + who.toLogString() + " with reason '" + why + "'\n";
}
-template<typename T>
+template <typename T>
static string doClearNTA(T begin, T end)
{
- if(checkDNSSECDisabled())
+ if (checkDNSSECDisabled())
return "DNSSEC is disabled in the configuration, not removing a Negative Trust Anchor\n";
- if(begin == end)
+ if (begin == end)
return "No Negative Trust Anchor specified, doing nothing.\n";
- if (begin + 1 == end && *begin == "*"){
- g_log<<Logger::Warning<<"Clearing all Negative Trust Anchors, requested via control channel"<<endl;
+ if (begin + 1 == end && *begin == "*") {
+ g_log << Logger::Warning << "Clearing all Negative Trust Anchors, requested via control channel" << endl;
g_luaconfs.modify([](LuaConfigItems& lci) {
- lci.negAnchors.clear();
- });
+ lci.negAnchors.clear();
+ });
return "Cleared all Negative Trust Anchors.\n";
}
try {
who = DNSName(*begin);
}
- catch(std::exception &e) {
+ catch (std::exception& e) {
string ret("Error: ");
ret += e.what();
ret += ". No Negative Anchors removed\n";
string removed("");
bool first(true);
try {
- for (auto const &entry : toRemove) {
- g_log<<Logger::Warning<<"Clearing Negative Trust Anchor for "<<entry<<", requested via control channel"<<endl;
+ for (auto const& entry : toRemove) {
+ g_log << Logger::Warning << "Clearing Negative Trust Anchor for " << entry << ", requested via control channel" << endl;
g_luaconfs.modify([entry](LuaConfigItems& lci) {
- lci.negAnchors.erase(entry);
- });
+ lci.negAnchors.erase(entry);
+ });
g_recCache->doWipeCache(entry, true, 0xffff);
- broadcastAccFunction<uint64_t>([=]{return pleaseWipePacketCache(entry, true, 0xffff);});
+ broadcastAccFunction<uint64_t>([=] { return pleaseWipePacketCache(entry, true, 0xffff); });
g_negCache->wipe(entry, true);
if (g_aggressiveNSECCache) {
g_aggressiveNSECCache->removeZoneInfo(entry, true);
removed += " " + entry.toStringRootDot();
}
}
- catch(std::exception &e) {
- g_log<<Logger::Warning<<", failed: "<<e.what()<<endl;
+ catch (std::exception& e) {
+ g_log << Logger::Warning << ", failed: " << e.what() << endl;
return "Unable to clear caches while clearing Negative Trust Anchor for " + who.toStringRootDot() + ": " + e.what() + "\n";
}
static string getNTAs()
{
- if(checkDNSSECDisabled())
+ if (checkDNSSECDisabled())
return "DNSSEC is disabled in the configuration\n";
string ret("Configured Negative Trust Anchors:\n");
return ret;
}
-template<typename T>
+template <typename T>
static string doAddTA(T begin, T end)
{
- if(checkDNSSECDisabled())
+ if (checkDNSSECDisabled())
return "DNSSEC is disabled in the configuration, not adding a Trust Anchor\n";
- if(begin == end)
+ if (begin == end)
return "No TA specified, doing nothing\n";
DNSName who;
try {
who = DNSName(*begin);
}
- catch(std::exception &e) {
+ catch (std::exception& e) {
string ret("Can't add Trust Anchor: ");
ret += e.what();
ret += "\n";
}
try {
- g_log<<Logger::Warning<<"Adding Trust Anchor for "<<who<<" with data '"<<what<<"', requested via control channel";
+ g_log << Logger::Warning << "Adding Trust Anchor for " << who << " with data '" << what << "', requested via control channel";
g_luaconfs.modify([who, what](LuaConfigItems& lci) {
- auto ds=std::dynamic_pointer_cast<DSRecordContent>(DSRecordContent::make(what));
+ auto ds = std::dynamic_pointer_cast<DSRecordContent>(DSRecordContent::make(what));
lci.dsAnchors[who].insert(*ds);
- });
+ });
g_recCache->doWipeCache(who, true, 0xffff);
- broadcastAccFunction<uint64_t>([=]{return pleaseWipePacketCache(who, true, 0xffff);});
+ broadcastAccFunction<uint64_t>([=] { return pleaseWipePacketCache(who, true, 0xffff); });
g_negCache->wipe(who, true);
if (g_aggressiveNSECCache) {
g_aggressiveNSECCache->removeZoneInfo(who, true);
}
- g_log<<Logger::Warning<<endl;
+ g_log << Logger::Warning << endl;
return "Added Trust Anchor for " + who.toStringRootDot() + " with data " + what + "\n";
}
- catch(std::exception &e) {
- g_log<<Logger::Warning<<", failed: "<<e.what()<<endl;
+ catch (std::exception& e) {
+ g_log << Logger::Warning << ", failed: " << e.what() << endl;
return "Unable to add Trust Anchor for " + who.toStringRootDot() + ": " + e.what() + "\n";
}
}
-template<typename T>
+template <typename T>
static string doClearTA(T begin, T end)
{
- if(checkDNSSECDisabled())
+ if (checkDNSSECDisabled())
return "DNSSEC is disabled in the configuration, not removing a Trust Anchor\n";
- if(begin == end)
+ if (begin == end)
return "No Trust Anchor to clear\n";
vector<DNSName> toRemove;
try {
who = DNSName(*begin);
}
- catch(std::exception &e) {
+ catch (std::exception& e) {
string ret("Error: ");
ret += e.what();
ret += ". No Anchors removed\n";
string removed("");
bool first(true);
try {
- for (auto const &entry : toRemove) {
- g_log<<Logger::Warning<<"Removing Trust Anchor for "<<entry<<", requested via control channel"<<endl;
+ for (auto const& entry : toRemove) {
+ g_log << Logger::Warning << "Removing Trust Anchor for " << entry << ", requested via control channel" << endl;
g_luaconfs.modify([entry](LuaConfigItems& lci) {
- lci.dsAnchors.erase(entry);
- });
+ lci.dsAnchors.erase(entry);
+ });
g_recCache->doWipeCache(entry, true, 0xffff);
- broadcastAccFunction<uint64_t>([=]{return pleaseWipePacketCache(entry, true, 0xffff);});
+ broadcastAccFunction<uint64_t>([=] { return pleaseWipePacketCache(entry, true, 0xffff); });
g_negCache->wipe(entry, true);
if (g_aggressiveNSECCache) {
g_aggressiveNSECCache->removeZoneInfo(entry, true);
}
}
catch (std::exception& e) {
- g_log<<Logger::Warning<<", failed: "<<e.what()<<endl;
+ g_log << Logger::Warning << ", failed: " << e.what() << endl;
return "Unable to clear caches while clearing Trust Anchor for " + who.toStringRootDot() + ": " + e.what() + "\n";
}
static string getTAs()
{
- if(checkDNSSECDisabled())
+ if (checkDNSSECDisabled())
return "DNSSEC is disabled in the configuration\n";
string ret("Configured Trust Anchors:\n");
for (auto anchor : luaconf->dsAnchors) {
ret += anchor.first.toLogString() + "\n";
for (auto e : anchor.second) {
- ret+="\t\t"+e.getZoneRepresentation() + "\n";
+ ret += "\t\t" + e.getZoneRepresentation() + "\n";
}
}
return ret;
}
-template<typename T>
+template <typename T>
static string setMinimumTTL(T begin, T end)
{
- if(end-begin != 1)
+ if (end - begin != 1)
return "Need to supply new minimum TTL number\n";
try {
SyncRes::s_minimumTTL = pdns_stou(*begin);
}
}
-template<typename T>
+template <typename T>
static string setMinimumECSTTL(T begin, T end)
{
- if(end-begin != 1)
+ if (end - begin != 1)
return "Need to supply new ECS minimum TTL number\n";
try {
SyncRes::s_minimumECSTTL = pdns_stou(*begin);
}
}
-template<typename T>
+template <typename T>
static string setMaxCacheEntries(T begin, T end)
{
- if(end-begin != 1)
+ if (end - begin != 1)
return "Need to supply new cache size\n";
try {
g_maxCacheEntries = pdns_stou(*begin);
}
}
-template<typename T>
+template <typename T>
static string setMaxPacketCacheEntries(T begin, T end)
{
- if(end-begin != 1)
+ if (end - begin != 1)
return "Need to supply new packet cache size\n";
try {
g_maxPacketCacheEntries = pdns_stou(*begin);
}
}
-
static uint64_t getSysTimeMsec()
{
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
- return (ru.ru_stime.tv_sec*1000ULL + ru.ru_stime.tv_usec/1000);
+ return (ru.ru_stime.tv_sec * 1000ULL + ru.ru_stime.tv_usec / 1000);
}
static uint64_t getUserTimeMsec()
{
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
- return (ru.ru_utime.tv_sec*1000ULL + ru.ru_utime.tv_usec/1000);
+ return (ru.ru_utime.tv_sec * 1000ULL + ru.ru_utime.tv_usec / 1000);
}
/* This is a pretty weird set of functions. To get per-thread cpu usage numbers,
static ThreadTimes* pleaseGetThreadCPUMsec()
{
- uint64_t ret=0;
+ uint64_t ret = 0;
#ifdef RUSAGE_THREAD
struct rusage ru;
getrusage(RUSAGE_THREAD, &ru);
- ret = (ru.ru_utime.tv_sec*1000ULL + ru.ru_utime.tv_usec/1000);
- ret += (ru.ru_stime.tv_sec*1000ULL + ru.ru_stime.tv_usec/1000);
+ ret = (ru.ru_utime.tv_sec * 1000ULL + ru.ru_utime.tv_usec / 1000);
+ ret += (ru.ru_stime.tv_sec * 1000ULL + ru.ru_stime.tv_usec / 1000);
#endif
return new ThreadTimes{ret, vector<uint64_t>()};
}
static ThreadTimes tt;
std::lock_guard<std::mutex> l(s_mut);
- if(last != time(nullptr)) {
- tt = broadcastAccFunction<ThreadTimes>(pleaseGetThreadCPUMsec);
- last = time(nullptr);
+ if (last != time(nullptr)) {
+ tt = broadcastAccFunction<ThreadTimes>(pleaseGetThreadCPUMsec);
+ last = time(nullptr);
}
return tt.times.at(n);
struct timeval now;
gettimeofday(&now, 0);
- ostr << getMT()->d_waiters.size() <<" currently outstanding questions\n";
+ ostr << getMT()->d_waiters.size() << " currently outstanding questions\n";
boost::format fmt("%1% %|40t|%2% %|47t|%3% %|63t|%4% %|68t|%5% %|78t|%6%\n");
ostr << (fmt % "qname" % "qtype" % "remote" % "tcp" % "chained" % "spent(ms)");
- unsigned int n=0;
- for(const auto& mthread : getMT()->d_waiters) {
+ unsigned int n = 0;
+ for (const auto& mthread : getMT()->d_waiters) {
const std::shared_ptr<PacketID>& pident = mthread.key;
const double spent = g_networkTimeoutMsec - (DiffTime(now, mthread.ttd) * 1000);
- ostr << (fmt
- % pident->domain.toLogString() /* ?? */ % DNSRecordContent::NumberToType(pident->type)
+ ostr << (fmt
+ % pident->domain.toLogString() /* ?? */ % DNSRecordContent::NumberToType(pident->type)
% pident->remote.toString() % (pident->tcpsock ? 'Y' : 'n')
% (pident->fd == -1 ? 'Y' : 'n')
- % (spent > 0 ? spent : '0')
- );
+ % (spent > 0 ? spent : '0'));
++n;
if (n >= 100)
break;
}
- ostr <<" - done\n";
+ ostr << " - done\n";
return new string(ostr.str());
}
static uint64_t* pleaseGetFailedHostsSize()
{
- uint64_t tmp=(SyncRes::getThrottledServersSize());
+ uint64_t tmp = (SyncRes::getThrottledServersSize());
return new uint64_t(tmp);
}
static uint64_t doGetMallocated()
{
// this turned out to be broken
-/* struct mallinfo mi = mallinfo();
+ /* struct mallinfo mi = mallinfo();
return mi.uordblks; */
return 0;
}
for (const auto& bucket : data) {
snprintf(buf, sizeof(buf), "%g", bucket.d_boundary / 1e6);
- std::string pname = pbasename + "seconds_bucket{" + "le=\"" +
- (bucket.d_boundary == std::numeric_limits<uint64_t>::max() ? "+Inf" : buf) + "\"}";
+ std::string pname = pbasename + "seconds_bucket{" + "le=\"" + (bucket.d_boundary == std::numeric_limits<uint64_t>::max() ? "+Inf" : buf) + "\"}";
entries.emplace(bucket.d_name, StatsMapEntry{pname, std::to_string(bucket.d_count)});
}
return entries;
}
-static StatsMap toStatsMap(const string& name, const pdns::AtomicHistogram& histogram4, const pdns::AtomicHistogram& histogram6)
+static StatsMap toStatsMap(const string& name, const pdns::AtomicHistogram& histogram4, const pdns::AtomicHistogram& histogram6)
{
const string pbasename = getPrometheusName(name);
StatsMap entries;
const auto& data4 = histogram4.getCumulativeBuckets();
for (const auto& bucket : data4) {
snprintf(buf, sizeof(buf), "%g", bucket.d_boundary / 1e6);
- pname = pbasename + "seconds_bucket{ipversion=\"v4\",le=\"" +
- (bucket.d_boundary == std::numeric_limits<uint64_t>::max() ? "+Inf" : buf) + "\"}";
+ pname = pbasename + "seconds_bucket{ipversion=\"v4\",le=\"" + (bucket.d_boundary == std::numeric_limits<uint64_t>::max() ? "+Inf" : buf) + "\"}";
entries.emplace(bucket.d_name + "4", StatsMapEntry{pname, std::to_string(bucket.d_count)});
}
snprintf(buf, sizeof(buf), "%g", histogram4.getSum() / 1e6);
const auto& data6 = histogram6.getCumulativeBuckets();
for (const auto& bucket : data6) {
snprintf(buf, sizeof(buf), "%g", bucket.d_boundary / 1e6);
- pname = pbasename + "seconds_bucket{ipversion=\"v6\",le=\"" +
- (bucket.d_boundary == std::numeric_limits<uint64_t>::max() ? "+Inf" : buf) + "\"}";
+ pname = pbasename + "seconds_bucket{ipversion=\"v6\",le=\"" + (bucket.d_boundary == std::numeric_limits<uint64_t>::max() ? "+Inf" : buf) + "\"}";
entries.emplace(bucket.d_name + "6", StatsMapEntry{pname, std::to_string(bucket.d_count)});
}
snprintf(buf, sizeof(buf), "%g", histogram6.getSum() / 1e6);
StatsMap entries;
uint64_t total = 0;
- for (const auto& entry: *map.lock()) {
- auto &key = entry.first;
+ for (const auto& entry : *map.lock()) {
+ auto& key = entry.first;
auto count = entry.second.load();
std::string sname, pname;
if (key.empty()) {
sname = name + "-filter";
pname = pbasename + "{type=\"filter\"}";
- } else {
+ }
+ else {
sname = name + "-rpz-" + key;
pname = pbasename + "{type=\"rpz\",policyname=\"" + key + "\"}";
}
addGetStat("tcp-questions", &g_stats.tcpqcounter);
addGetStat("cache-hits", doGetCacheHits);
- addGetStat("cache-misses", doGetCacheMisses);
+ addGetStat("cache-misses", doGetCacheMisses);
addGetStat("cache-entries", doGetCacheSize);
addGetStat("max-cache-entries", []() { return g_maxCacheEntries.load(); });
- addGetStat("max-packetcache-entries", []() { return g_maxPacketCacheEntries.load();});
- addGetStat("cache-bytes", doGetCacheBytes);
- addGetStat("record-cache-contended", []() { return g_recCache->stats().first;});
- addGetStat("record-cache-acquired", []() { return g_recCache->stats().second;});
-
+ addGetStat("max-packetcache-entries", []() { return g_maxPacketCacheEntries.load(); });
+ addGetStat("cache-bytes", doGetCacheBytes);
+ addGetStat("record-cache-contended", []() { return g_recCache->stats().first; });
+ addGetStat("record-cache-acquired", []() { return g_recCache->stats().second; });
+
addGetStat("packetcache-hits", doGetPacketCacheHits);
- addGetStat("packetcache-misses", doGetPacketCacheMisses);
- addGetStat("packetcache-entries", doGetPacketCacheSize);
- addGetStat("packetcache-bytes", doGetPacketCacheBytes);
+ addGetStat("packetcache-misses", doGetPacketCacheMisses);
+ addGetStat("packetcache-entries", doGetPacketCacheSize);
+ addGetStat("packetcache-bytes", doGetPacketCacheBytes);
- addGetStat("aggressive-nsec-cache-entries", [](){ return g_aggressiveNSECCache ? g_aggressiveNSECCache->getEntriesCount() : 0; });
- addGetStat("aggressive-nsec-cache-nsec-hits", [](){ return g_aggressiveNSECCache ? g_aggressiveNSECCache->getNSECHits() : 0; });
- addGetStat("aggressive-nsec-cache-nsec3-hits", [](){ return g_aggressiveNSECCache ? g_aggressiveNSECCache->getNSEC3Hits() : 0; });
- addGetStat("aggressive-nsec-cache-nsec-wc-hits", [](){ return g_aggressiveNSECCache ? g_aggressiveNSECCache->getNSECWildcardHits() : 0; });
- addGetStat("aggressive-nsec-cache-nsec3-wc-hits", [](){ return g_aggressiveNSECCache ? g_aggressiveNSECCache->getNSEC3WildcardHits() : 0; });
+ addGetStat("aggressive-nsec-cache-entries", []() { return g_aggressiveNSECCache ? g_aggressiveNSECCache->getEntriesCount() : 0; });
+ addGetStat("aggressive-nsec-cache-nsec-hits", []() { return g_aggressiveNSECCache ? g_aggressiveNSECCache->getNSECHits() : 0; });
+ addGetStat("aggressive-nsec-cache-nsec3-hits", []() { return g_aggressiveNSECCache ? g_aggressiveNSECCache->getNSEC3Hits() : 0; });
+ addGetStat("aggressive-nsec-cache-nsec-wc-hits", []() { return g_aggressiveNSECCache ? g_aggressiveNSECCache->getNSECWildcardHits() : 0; });
+ addGetStat("aggressive-nsec-cache-nsec3-wc-hits", []() { return g_aggressiveNSECCache ? g_aggressiveNSECCache->getNSEC3WildcardHits() : 0; });
addGetStat("malloc-bytes", doGetMallocated);
-
+
addGetStat("servfail-answers", &g_stats.servFails);
addGetStat("nxdomain-answers", &g_stats.nxDomains);
addGetStat("noerror-answers", &g_stats.noErrors);
addGetStat("ecs-queries", &SyncRes::s_ecsqueries);
addGetStat("ecs-responses", &SyncRes::s_ecsresponses);
addGetStat("chain-resends", &g_stats.chainResends);
- addGetStat("tcp-clients", []{return TCPConnection::getCurrentConnections();});
+ addGetStat("tcp-clients", [] { return TCPConnection::getCurrentConnections(); });
#ifdef __linux__
- addGetStat("udp-recvbuf-errors", []{return udpErrorStats("udp-recvbuf-errors");});
- addGetStat("udp-sndbuf-errors", []{return udpErrorStats("udp-sndbuf-errors");});
- addGetStat("udp-noport-errors", []{return udpErrorStats("udp-noport-errors");});
- addGetStat("udp-in-errors", []{return udpErrorStats("udp-in-errors");});
+ addGetStat("udp-recvbuf-errors", [] { return udpErrorStats("udp-recvbuf-errors"); });
+ addGetStat("udp-sndbuf-errors", [] { return udpErrorStats("udp-sndbuf-errors"); });
+ addGetStat("udp-noport-errors", [] { return udpErrorStats("udp-noport-errors"); });
+ addGetStat("udp-in-errors", [] { return udpErrorStats("udp-in-errors"); });
#endif
addGetStat("edns-ping-matches", &g_stats.ednsPingMatches);
addGetStat("noedns-outqueries", &g_stats.noEdnsOutQueries);
addGetStat("uptime", calculateUptime);
- addGetStat("real-memory-usage", []{ return getRealMemoryUsage(string()); });
- addGetStat("special-memory-usage", []{ return getSpecialMemoryUsage(string()); });
- addGetStat("fd-usage", []{ return getOpenFileDescriptors(string()); });
+ addGetStat("real-memory-usage", [] { return getRealMemoryUsage(string()); });
+ addGetStat("special-memory-usage", [] { return getSpecialMemoryUsage(string()); });
+ addGetStat("fd-usage", [] { return getOpenFileDescriptors(string()); });
// addGetStat("query-rate", getQueryRate);
addGetStat("user-msec", getUserTimeMsec);
addGetStat("sys-msec", getSysTimeMsec);
#ifdef __linux__
- addGetStat("cpu-iowait", []{ return getCPUIOWait(string()); });
- addGetStat("cpu-steal", []{ return getCPUSteal(string()); });
+ addGetStat("cpu-iowait", [] { return getCPUIOWait(string()); });
+ addGetStat("cpu-steal", [] { return getCPUSteal(string()); });
#endif
addGetStat("cpu-msec", []() { return toCPUStatsMap("cpu-msec"); });
#ifdef MALLOC_TRACE
- addGetStat("memory-allocs", []{ return g_mtracer->getAllocs(string()); });
- addGetStat("memory-alloc-flux", []{ return g_mtracer->getAllocFlux(string()); });
- addGetStat("memory-allocated", []{ return g_mtracer->getTotAllocated(string()); });
+ addGetStat("memory-allocs", [] { return g_mtracer->getAllocs(string()); });
+ addGetStat("memory-alloc-flux", [] { return g_mtracer->getAllocFlux(string()); });
+ addGetStat("memory-allocated", [] { return g_mtracer->getTotAllocated(string()); });
#endif
addGetStat("dnssec-validations", &g_stats.dnssecValidations);
addGetStat("dnssec-result-insecure", &g_stats.dnssecResults[vState::Insecure]);
addGetStat("dnssec-result-secure", &g_stats.dnssecResults[vState::Secure]);
addGetStat("dnssec-result-bogus", []() {
- std::set<vState> const bogusStates = { vState::BogusNoValidDNSKEY, vState::BogusInvalidDenial, vState::BogusUnableToGetDSs, vState::BogusUnableToGetDNSKEYs, vState::BogusSelfSignedDS, vState::BogusNoRRSIG, vState::BogusNoValidRRSIG, vState::BogusMissingNegativeIndication, vState::BogusSignatureNotYetValid, vState::BogusSignatureExpired, vState::BogusUnsupportedDNSKEYAlgo, vState::BogusUnsupportedDSDigestType, vState::BogusNoZoneKeyBitSet, vState::BogusRevokedDNSKEY, vState::BogusInvalidDNSKEYProtocol };
+ std::set<vState> const bogusStates = {vState::BogusNoValidDNSKEY, vState::BogusInvalidDenial, vState::BogusUnableToGetDSs, vState::BogusUnableToGetDNSKEYs, vState::BogusSelfSignedDS, vState::BogusNoRRSIG, vState::BogusNoValidRRSIG, vState::BogusMissingNegativeIndication, vState::BogusSignatureNotYetValid, vState::BogusSignatureExpired, vState::BogusUnsupportedDNSKEYAlgo, vState::BogusUnsupportedDSDigestType, vState::BogusNoZoneKeyBitSet, vState::BogusRevokedDNSKEY, vState::BogusInvalidDNSKEYProtocol};
uint64_t total = 0;
for (const auto& state : bogusStates) {
total += g_stats.dnssecResults[state];
if (::arg()["x-dnssec-names"].length() > 0) {
addGetStat("x-dnssec-result-bogus", []() {
- std::set<vState> const bogusStates = { vState::BogusNoValidDNSKEY, vState::BogusInvalidDenial, vState::BogusUnableToGetDSs, vState::BogusUnableToGetDNSKEYs, vState::BogusSelfSignedDS, vState::BogusNoRRSIG, vState::BogusNoValidRRSIG, vState::BogusMissingNegativeIndication, vState::BogusSignatureNotYetValid, vState::BogusSignatureExpired, vState::BogusUnsupportedDNSKEYAlgo, vState::BogusUnsupportedDSDigestType, vState::BogusNoZoneKeyBitSet, vState::BogusRevokedDNSKEY, vState::BogusInvalidDNSKEYProtocol };
+ std::set<vState> const bogusStates = {vState::BogusNoValidDNSKEY, vState::BogusInvalidDenial, vState::BogusUnableToGetDSs, vState::BogusUnableToGetDNSKEYs, vState::BogusSelfSignedDS, vState::BogusNoRRSIG, vState::BogusNoValidRRSIG, vState::BogusMissingNegativeIndication, vState::BogusSignatureNotYetValid, vState::BogusSignatureExpired, vState::BogusUnsupportedDNSKEYAlgo, vState::BogusUnsupportedDSDigestType, vState::BogusNoZoneKeyBitSet, vState::BogusRevokedDNSKEY, vState::BogusInvalidDNSKEYProtocol};
uint64_t total = 0;
for (const auto& state : bogusStates) {
total += g_stats.xdnssecResults[state];
addGetStat("nod-lookups-dropped-oversize", &g_stats.nodLookupsDroppedOversize);
- addGetStat("taskqueue-pushed", []() { return getTaskPushes(); });
- addGetStat("taskqueue-expired", []() { return getTaskExpired(); });
- addGetStat("taskqueue-size", []() { return getTaskSize(); });
+ addGetStat("taskqueue-pushed", []() { return getTaskPushes(); });
+ addGetStat("taskqueue-expired", []() { return getTaskExpired(); });
+ addGetStat("taskqueue-size", []() { return getTaskSize(); });
- addGetStat("dns64-prefix-answers", &g_stats.dns64prefixanswers);
+ addGetStat("dns64-prefix-answers", &g_stats.dns64prefixanswers);
- addGetStat("almost-expired-pushed", []() { return getAlmostExpiredTasksPushed(); });
- addGetStat("almost-expired-run", []() { return getAlmostExpiredTasksRun(); });
- addGetStat("almost-expired-exceptions", []() { return getAlmostExpiredTaskExceptions(); });
+ addGetStat("almost-expired-pushed", []() { return getAlmostExpiredTasksPushed(); });
+ addGetStat("almost-expired-run", []() { return getAlmostExpiredTasksRun(); });
+ addGetStat("almost-expired-exceptions", []() { return getAlmostExpiredTaskExceptions(); });
- addGetStat("idle-tcpout-connections", getCurrentIdleTCPConnections);
+ addGetStat("idle-tcpout-connections", getCurrentIdleTCPConnections);
/* make sure that the ECS stats are properly initialized */
SyncRes::clearECSStats();
void registerAllStats()
{
static std::once_flag s_once;
- std::call_once(s_once, []() { try {
- registerAllStats1();
- }
- catch (...) {
- g_log << Logger::Critical << "Could not add stat entries" << endl;
- exit(1);
- }
+ std::call_once(s_once, []() {
+ try {
+ registerAllStats1();
+ }
+ catch (...) {
+ g_log << Logger::Critical << "Could not add stat entries" << endl;
+ exit(1);
+ }
});
}
void doExitGeneric(bool nicely)
{
- g_log<<Logger::Error<<"Exiting on user request"<<endl;
+ g_log << Logger::Error << "Exiting on user request" << endl;
extern RecursorControlChannel s_rcc;
s_rcc.~RecursorControlChannel();
extern string s_pidfname;
- if(!s_pidfname.empty())
+ if (!s_pidfname.empty())
unlink(s_pidfname.c_str()); // we can at least try..
- if(nicely) {
+ if (nicely) {
RecursorControlChannel::stop = true;
- } else {
+ }
+ else {
_exit(1);
}
}
doExitGeneric(true);
}
-vector<pair<DNSName, uint16_t> >* pleaseGetQueryRing()
+vector<pair<DNSName, uint16_t>>* pleaseGetQueryRing()
{
- typedef pair<DNSName,uint16_t> query_t;
- vector<query_t >* ret = new vector<query_t>();
- if(!t_queryring)
+ typedef pair<DNSName, uint16_t> query_t;
+ vector<query_t>* ret = new vector<query_t>();
+ if (!t_queryring)
return ret;
ret->reserve(t_queryring->size());
- for(const query_t& q : *t_queryring) {
+ for (const query_t& q : *t_queryring) {
ret->push_back(q);
}
return ret;
}
-vector<pair<DNSName,uint16_t> >* pleaseGetServfailQueryRing()
+vector<pair<DNSName, uint16_t>>* pleaseGetServfailQueryRing()
{
- typedef pair<DNSName,uint16_t> query_t;
+ typedef pair<DNSName, uint16_t> query_t;
vector<query_t>* ret = new vector<query_t>();
- if(!t_servfailqueryring)
+ if (!t_servfailqueryring)
return ret;
ret->reserve(t_servfailqueryring->size());
- for(const query_t& q : *t_servfailqueryring) {
+ for (const query_t& q : *t_servfailqueryring) {
ret->push_back(q);
}
return ret;
}
-vector<pair<DNSName,uint16_t> >* pleaseGetBogusQueryRing()
+vector<pair<DNSName, uint16_t>>* pleaseGetBogusQueryRing()
{
- typedef pair<DNSName,uint16_t> query_t;
+ typedef pair<DNSName, uint16_t> query_t;
vector<query_t>* ret = new vector<query_t>();
- if(!t_bogusqueryring)
+ if (!t_bogusqueryring)
return ret;
ret->reserve(t_bogusqueryring->size());
- for(const query_t& q : *t_bogusqueryring) {
+ for (const query_t& q : *t_bogusqueryring) {
ret->push_back(q);
}
return ret;
}
-
-
typedef boost::function<vector<ComboAddress>*()> pleaseremotefunc_t;
-typedef boost::function<vector<pair<DNSName,uint16_t> >*()> pleasequeryfunc_t;
+typedef boost::function<vector<pair<DNSName, uint16_t>>*()> pleasequeryfunc_t;
vector<ComboAddress>* pleaseGetRemotes()
{
vector<ComboAddress>* ret = new vector<ComboAddress>();
- if(!t_remotes)
+ if (!t_remotes)
return ret;
ret->reserve(t_remotes->size());
- for(const ComboAddress& ca : *t_remotes) {
+ for (const ComboAddress& ca : *t_remotes) {
ret->push_back(ca);
}
return ret;
vector<ComboAddress>* pleaseGetServfailRemotes()
{
vector<ComboAddress>* ret = new vector<ComboAddress>();
- if(!t_servfailremotes)
+ if (!t_servfailremotes)
return ret;
ret->reserve(t_servfailremotes->size());
- for(const ComboAddress& ca : *t_servfailremotes) {
+ for (const ComboAddress& ca : *t_servfailremotes) {
ret->push_back(ca);
}
return ret;
vector<ComboAddress>* pleaseGetBogusRemotes()
{
vector<ComboAddress>* ret = new vector<ComboAddress>();
- if(!t_bogusremotes)
+ if (!t_bogusremotes)
return ret;
ret->reserve(t_bogusremotes->size());
- for(const ComboAddress& ca : *t_bogusremotes) {
+ for (const ComboAddress& ca : *t_bogusremotes) {
ret->push_back(ca);
}
return ret;
vector<ComboAddress>* pleaseGetLargeAnswerRemotes()
{
vector<ComboAddress>* ret = new vector<ComboAddress>();
- if(!t_largeanswerremotes)
+ if (!t_largeanswerremotes)
return ret;
ret->reserve(t_largeanswerremotes->size());
- for(const ComboAddress& ca : *t_largeanswerremotes) {
+ for (const ComboAddress& ca : *t_largeanswerremotes) {
ret->push_back(ca);
}
return ret;
vector<ComboAddress>* pleaseGetTimeouts()
{
vector<ComboAddress>* ret = new vector<ComboAddress>();
- if(!t_timeouts)
+ if (!t_timeouts)
return ret;
ret->reserve(t_timeouts->size());
- for(const ComboAddress& ca : *t_timeouts) {
+ for (const ComboAddress& ca : *t_timeouts) {
ret->push_back(ca);
}
return ret;
typedef map<ComboAddress, int, ComboAddress::addressOnlyLessThan> counts_t;
counts_t counts;
- vector<ComboAddress> remotes=broadcastAccFunction<vector<ComboAddress> >(func);
-
- unsigned int total=0;
- for(const ComboAddress& ca : remotes) {
+ vector<ComboAddress> remotes = broadcastAccFunction<vector<ComboAddress>>(func);
+
+ unsigned int total = 0;
+ for (const ComboAddress& ca : remotes) {
total++;
counts[ca]++;
}
-
+
typedef std::multimap<int, ComboAddress> rcounts_t;
rcounts_t rcounts;
rcounts.emplace(-c.second, c.first);
ostringstream ret;
- ret<<"Over last "<<total<<" entries:\n";
+ ret << "Over last " << total << " entries:\n";
boost::format fmt("%.02f%%\t%s\n");
- int limit=0, accounted=0;
- if(total) {
- for(rcounts_t::const_iterator i=rcounts.begin(); i != rcounts.end() && limit < 20; ++i, ++limit) {
- ret<< fmt % (-100.0*i->first/total) % i->second.toString();
- accounted+= -i->first;
+ int limit = 0, accounted = 0;
+ if (total) {
+ for (rcounts_t::const_iterator i = rcounts.begin(); i != rcounts.end() && limit < 20; ++i, ++limit) {
+ ret << fmt % (-100.0 * i->first / total) % i->second.toString();
+ accounted += -i->first;
}
- ret<< '\n' << fmt % (100.0*(total-accounted)/total) % "rest";
+ ret << '\n'
+ << fmt % (100.0 * (total - accounted) / total) % "rest";
}
return ret.str();
}
// XXX DNSName Pain - this function should benefit from native DNSName methods
DNSName getRegisteredName(const DNSName& dom)
{
- auto parts=dom.getRawLabels();
- if(parts.size()<=2)
+ auto parts = dom.getRawLabels();
+ if (parts.size() <= 2)
return dom;
reverse(parts.begin(), parts.end());
- for(string& str : parts) { str=toLower(str); };
+ for (string& str : parts) {
+ str = toLower(str);
+ };
- // uk co migweb
+ // uk co migweb
string last;
- while(!parts.empty()) {
- if(parts.size()==1 || binary_search(g_pubs.begin(), g_pubs.end(), parts)) {
-
- string ret=last;
- if(!ret.empty())
- ret+=".";
-
- for(auto p = parts.crbegin(); p != parts.crend(); ++p) {
- ret+=(*p)+".";
+ while (!parts.empty()) {
+ if (parts.size() == 1 || binary_search(g_pubs.begin(), g_pubs.end(), parts)) {
+
+ string ret = last;
+ if (!ret.empty())
+ ret += ".";
+
+ for (auto p = parts.crbegin(); p != parts.crend(); ++p) {
+ ret += (*p) + ".";
}
return DNSName(ret);
}
- last=parts[parts.size()-1];
- parts.resize(parts.size()-1);
+ last = parts[parts.size() - 1];
+ parts.resize(parts.size() - 1);
}
return DNSName("??");
}
return name;
}
-static string doGenericTopQueries(pleasequeryfunc_t func, boost::function<DNSName(const DNSName&)> filter=nopFilter)
+static string doGenericTopQueries(pleasequeryfunc_t func, boost::function<DNSName(const DNSName&)> filter = nopFilter)
{
- typedef pair<DNSName,uint16_t> query_t;
+ typedef pair<DNSName, uint16_t> query_t;
typedef map<query_t, int> counts_t;
counts_t counts;
- vector<query_t> queries=broadcastAccFunction<vector<query_t> >(func);
-
- unsigned int total=0;
- for(const query_t& q : queries) {
+ vector<query_t> queries = broadcastAccFunction<vector<query_t>>(func);
+
+ unsigned int total = 0;
+ for (const query_t& q : queries) {
total++;
- counts[pair(filter(q.first),q.second)]++;
+ counts[pair(filter(q.first), q.second)]++;
}
typedef std::multimap<int, query_t> rcounts_t;
rcounts.emplace(-c.second, c.first);
ostringstream ret;
- ret<<"Over last "<<total<<" entries:\n";
+ ret << "Over last " << total << " entries:\n";
boost::format fmt("%.02f%%\t%s\n");
- int limit=0, accounted=0;
- if(total) {
- for(rcounts_t::const_iterator i=rcounts.begin(); i != rcounts.end() && limit < 20; ++i, ++limit) {
- ret<< fmt % (-100.0*i->first/total) % (i->second.first.toLogString()+"|"+DNSRecordContent::NumberToType(i->second.second));
- accounted+= -i->first;
+ int limit = 0, accounted = 0;
+ if (total) {
+ for (rcounts_t::const_iterator i = rcounts.begin(); i != rcounts.end() && limit < 20; ++i, ++limit) {
+ ret << fmt % (-100.0 * i->first / total) % (i->second.first.toLogString() + "|" + DNSRecordContent::NumberToType(i->second.second));
+ accounted += -i->first;
}
- ret<< '\n' << fmt % (100.0*(total-accounted)/total) % "rest";
+ ret << '\n'
+ << fmt % (100.0 * (total - accounted) / total) % "rest";
}
-
return ret.str();
}
return new string("pong\n");
}
-static string getDontThrottleNames() {
+static string getDontThrottleNames()
+{
auto dtn = g_dontThrottleNames.getLocal();
return dtn->toString() + "\n";
}
-static string getDontThrottleNetmasks() {
+static string getDontThrottleNetmasks()
+{
auto dtn = g_dontThrottleNetmasks.getLocal();
return dtn->toString() + "\n";
}
-template<typename T>
-static string addDontThrottleNames(T begin, T end) {
+template <typename T>
+static string addDontThrottleNames(T begin, T end)
+{
if (begin == end) {
return "No names specified, keeping existing list\n";
}
auto d = DNSName(*begin);
toAdd.push_back(d);
}
- catch(const std::exception &e) {
- return "Problem parsing '" + *begin + "': "+ e.what() + ", nothing added\n";
+ catch (const std::exception& e) {
+ return "Problem parsing '" + *begin + "': " + e.what() + ", nothing added\n";
}
begin++;
}
string ret = "Added";
auto dnt = g_dontThrottleNames.getCopy();
bool first = true;
- for (auto const &d : toAdd) {
+ for (auto const& d : toAdd) {
if (!first) {
ret += ",";
}
g_dontThrottleNames.setState(std::move(dnt));
ret += " to the list of nameservers that may not be throttled";
- g_log<<Logger::Info<<ret<<", requested via control channel"<<endl;
+ g_log << Logger::Info << ret << ", requested via control channel" << endl;
return ret + "\n";
}
-template<typename T>
-static string addDontThrottleNetmasks(T begin, T end) {
+template <typename T>
+static string addDontThrottleNetmasks(T begin, T end)
+{
if (begin == end) {
return "No netmasks specified, keeping existing list\n";
}
auto n = Netmask(*begin);
toAdd.push_back(n);
}
- catch(const std::exception &e) {
- return "Problem parsing '" + *begin + "': "+ e.what() + ", nothing added\n";
+ catch (const std::exception& e) {
+ return "Problem parsing '" + *begin + "': " + e.what() + ", nothing added\n";
}
- catch(const PDNSException &e) {
- return "Problem parsing '" + *begin + "': "+ e.reason + ", nothing added\n";
+ catch (const PDNSException& e) {
+ return "Problem parsing '" + *begin + "': " + e.reason + ", nothing added\n";
}
begin++;
}
string ret = "Added";
auto dnt = g_dontThrottleNetmasks.getCopy();
bool first = true;
- for (auto const &t : toAdd) {
+ for (auto const& t : toAdd) {
if (!first) {
ret += ",";
}
g_dontThrottleNetmasks.setState(std::move(dnt));
ret += " to the list of nameserver netmasks that may not be throttled";
- g_log<<Logger::Info<<ret<<", requested via control channel"<<endl;
+ g_log << Logger::Info << ret << ", requested via control channel" << endl;
return ret + "\n";
}
-template<typename T>
-static string clearDontThrottleNames(T begin, T end) {
- if(begin == end)
+template <typename T>
+static string clearDontThrottleNames(T begin, T end)
+{
+ if (begin == end)
return "No names specified, doing nothing.\n";
- if (begin + 1 == end && *begin == "*"){
+ if (begin + 1 == end && *begin == "*") {
SuffixMatchNode smn;
g_dontThrottleNames.setState(std::move(smn));
string ret = "Cleared list of nameserver names that may not be throttled";
- g_log<<Logger::Warning<<ret<<", requested via control channel"<<endl;
+ g_log << Logger::Warning << ret << ", requested via control channel" << endl;
return ret + "\n";
}
}
toRemove.push_back(DNSName(*begin));
}
- catch (const std::exception &e) {
- return "Problem parsing '" + *begin + "': "+ e.what() + ", nothing removed\n";
+ catch (const std::exception& e) {
+ return "Problem parsing '" + *begin + "': " + e.what() + ", nothing removed\n";
}
begin++;
}
string ret = "Removed";
bool first = true;
auto dnt = g_dontThrottleNames.getCopy();
- for (const auto &name : toRemove) {
+ for (const auto& name : toRemove) {
if (!first) {
ret += ",";
}
g_dontThrottleNames.setState(std::move(dnt));
ret += " from the list of nameservers that may not be throttled";
- g_log<<Logger::Info<<ret<<", requested via control channel"<<endl;
+ g_log << Logger::Info << ret << ", requested via control channel" << endl;
return ret + "\n";
}
-template<typename T>
-static string clearDontThrottleNetmasks(T begin, T end) {
- if(begin == end)
+template <typename T>
+static string clearDontThrottleNetmasks(T begin, T end)
+{
+ if (begin == end)
return "No netmasks specified, doing nothing.\n";
- if (begin + 1 == end && *begin == "*"){
+ if (begin + 1 == end && *begin == "*") {
auto nmg = g_dontThrottleNetmasks.getCopy();
nmg.clear();
g_dontThrottleNetmasks.setState(std::move(nmg));
string ret = "Cleared list of nameserver addresses that may not be throttled";
- g_log<<Logger::Warning<<ret<<", requested via control channel"<<endl;
+ g_log << Logger::Warning << ret << ", requested via control channel" << endl;
return ret + "\n";
}
auto n = Netmask(*begin);
toRemove.push_back(n);
}
- catch(const std::exception &e) {
- return "Problem parsing '" + *begin + "': "+ e.what() + ", nothing added\n";
+ catch (const std::exception& e) {
+ return "Problem parsing '" + *begin + "': " + e.what() + ", nothing added\n";
}
- catch(const PDNSException &e) {
- return "Problem parsing '" + *begin + "': "+ e.reason + ", nothing added\n";
+ catch (const PDNSException& e) {
+ return "Problem parsing '" + *begin + "': " + e.reason + ", nothing added\n";
}
begin++;
}
string ret = "Removed";
bool first = true;
auto dnt = g_dontThrottleNetmasks.getCopy();
- for (const auto &mask : toRemove) {
+ for (const auto& mask : toRemove) {
if (!first) {
ret += ",";
}
g_dontThrottleNetmasks.setState(std::move(dnt));
ret += " from the list of nameservers that may not be throttled";
- g_log<<Logger::Info<<ret<<", requested via control channel"<<endl;
+ g_log << Logger::Info << ret << ", requested via control channel" << endl;
return ret + "\n";
}
RecursorControlChannel::Answer RecursorControlParser::getAnswer(int s, const string& question, RecursorControlParser::func_t** command)
{
- *command=nop;
+ *command = nop;
vector<string> words;
stringtok(words, question);
- if(words.empty())
+ if (words.empty())
return {1, "invalid command\n"};
- string cmd=toLower(words[0]);
- vector<string>::const_iterator begin=words.begin()+1, end=words.end();
+ string cmd = toLower(words[0]);
+ vector<string>::const_iterator begin = words.begin() + 1, end = words.end();
// should probably have a smart dispatcher here, like auth has
- if(cmd=="help")
+ if (cmd == "help")
return {0,
-"add-dont-throttle-names [N...] add names that are not allowed to be throttled\n"
-"add-dont-throttle-netmasks [N...]\n"
-" add netmasks that are not allowed to be throttled\n"
-"add-nta DOMAIN [REASON] add a Negative Trust Anchor for DOMAIN with the comment REASON\n"
-"add-ta DOMAIN DSRECORD add a Trust Anchor for DOMAIN with data DSRECORD\n"
-"current-queries show currently active queries\n"
-"clear-dont-throttle-names [N...] remove names that are not allowed to be throttled. If N is '*', remove all\n"
-"clear-dont-throttle-netmasks [N...]\n"
-" remove netmasks that are not allowed to be throttled. If N is '*', remove all\n"
-"clear-nta [DOMAIN]... Clear the Negative Trust Anchor for DOMAINs, if no DOMAIN is specified, remove all\n"
-"clear-ta [DOMAIN]... Clear the Trust Anchor for DOMAINs\n"
-"dump-cache <filename> dump cache contents to the named file\n"
-"dump-edns [status] <filename> dump EDNS status to the named file\n"
-"dump-failedservers <filename> dump the failed servers to the named file\n"
-"dump-non-resolving <filename> dump non-resolving nameservers addresses to the named file\n"
-"dump-nsspeeds <filename> dump nsspeeds statistics to the named file\n"
-"dump-rpz <zone name> <filename> dump the content of a RPZ zone to the named file\n"
-"dump-throttlemap <filename> dump the contents of the throttle map to the named file\n"
-"get [key1] [key2] .. get specific statistics\n"
-"get-all get all statistics\n"
-"get-dont-throttle-names get the list of names that are not allowed to be throttled\n"
-"get-dont-throttle-netmasks get the list of netmasks that are not allowed to be throttled\n"
-"get-ntas get all configured Negative Trust Anchors\n"
-"get-tas get all configured Trust Anchors\n"
-"get-parameter [key1] [key2] .. get configuration parameters\n"
-"get-qtypelist get QType statistics\n"
-" notice: queries from cache aren't being counted yet\n"
-"hash-password [work-factor] ask for a password then return the hashed version\n"
-"help get this list\n"
-"ping check that all threads are alive\n"
-"quit stop the recursor daemon\n"
-"quit-nicely stop the recursor daemon nicely\n"
-"reload-acls reload ACLS\n"
-"reload-lua-script [filename] (re)load Lua script\n"
-"reload-lua-config [filename] (re)load Lua configuration file\n"
-"reload-zones reload all auth and forward zones\n"
-"set-ecs-minimum-ttl value set ecs-minimum-ttl-override\n"
-"set-max-cache-entries value set new maximum cache size\n"
-"set-max-packetcache-entries val set new maximum packet cache size\n"
-"set-minimum-ttl value set minimum-ttl-override\n"
-"set-carbon-server set a carbon server for telemetry\n"
-"set-dnssec-log-bogus SETTING enable (SETTING=yes) or disable (SETTING=no) logging of DNSSEC validation failures\n"
-"set-event-trace-enabled SETTING set logging of event trace messages, 0 = disabled, 1 = protobuf, 2 = log file, 3 = both\n"
-"trace-regex [regex] emit resolution trace for matching queries (empty regex to clear trace)\n"
-"top-largeanswer-remotes show top remotes receiving large answers\n"
-"top-queries show top queries\n"
-"top-pub-queries show top queries grouped by public suffix list\n"
-"top-remotes show top remotes\n"
-"top-timeouts show top downstream timeouts\n"
-"top-servfail-queries show top queries receiving servfail answers\n"
-"top-bogus-queries show top queries validating as bogus\n"
-"top-pub-servfail-queries show top queries receiving servfail answers grouped by public suffix list\n"
-"top-pub-bogus-queries show top queries validating as bogus grouped by public suffix list\n"
-"top-servfail-remotes show top remotes receiving servfail answers\n"
-"top-bogus-remotes show top remotes receiving bogus answers\n"
-"unload-lua-script unload Lua script\n"
-"version return Recursor version number\n"
-"wipe-cache domain0 [domain1] .. wipe domain data from cache\n"
-"wipe-cache-typed type domain0 [domain1] .. wipe domain data with qtype from cache\n"};
+ "add-dont-throttle-names [N...] add names that are not allowed to be throttled\n"
+ "add-dont-throttle-netmasks [N...]\n"
+ " add netmasks that are not allowed to be throttled\n"
+ "add-nta DOMAIN [REASON] add a Negative Trust Anchor for DOMAIN with the comment REASON\n"
+ "add-ta DOMAIN DSRECORD add a Trust Anchor for DOMAIN with data DSRECORD\n"
+ "current-queries show currently active queries\n"
+ "clear-dont-throttle-names [N...] remove names that are not allowed to be throttled. If N is '*', remove all\n"
+ "clear-dont-throttle-netmasks [N...]\n"
+ " remove netmasks that are not allowed to be throttled. If N is '*', remove all\n"
+ "clear-nta [DOMAIN]... Clear the Negative Trust Anchor for DOMAINs, if no DOMAIN is specified, remove all\n"
+ "clear-ta [DOMAIN]... Clear the Trust Anchor for DOMAINs\n"
+ "dump-cache <filename> dump cache contents to the named file\n"
+ "dump-edns [status] <filename> dump EDNS status to the named file\n"
+ "dump-failedservers <filename> dump the failed servers to the named file\n"
+ "dump-non-resolving <filename> dump non-resolving nameservers addresses to the named file\n"
+ "dump-nsspeeds <filename> dump nsspeeds statistics to the named file\n"
+ "dump-rpz <zone name> <filename> dump the content of a RPZ zone to the named file\n"
+ "dump-throttlemap <filename> dump the contents of the throttle map to the named file\n"
+ "get [key1] [key2] .. get specific statistics\n"
+ "get-all get all statistics\n"
+ "get-dont-throttle-names get the list of names that are not allowed to be throttled\n"
+ "get-dont-throttle-netmasks get the list of netmasks that are not allowed to be throttled\n"
+ "get-ntas get all configured Negative Trust Anchors\n"
+ "get-tas get all configured Trust Anchors\n"
+ "get-parameter [key1] [key2] .. get configuration parameters\n"
+ "get-qtypelist get QType statistics\n"
+ " notice: queries from cache aren't being counted yet\n"
+ "hash-password [work-factor] ask for a password then return the hashed version\n"
+ "help get this list\n"
+ "ping check that all threads are alive\n"
+ "quit stop the recursor daemon\n"
+ "quit-nicely stop the recursor daemon nicely\n"
+ "reload-acls reload ACLS\n"
+ "reload-lua-script [filename] (re)load Lua script\n"
+ "reload-lua-config [filename] (re)load Lua configuration file\n"
+ "reload-zones reload all auth and forward zones\n"
+ "set-ecs-minimum-ttl value set ecs-minimum-ttl-override\n"
+ "set-max-cache-entries value set new maximum cache size\n"
+ "set-max-packetcache-entries val set new maximum packet cache size\n"
+ "set-minimum-ttl value set minimum-ttl-override\n"
+ "set-carbon-server set a carbon server for telemetry\n"
+ "set-dnssec-log-bogus SETTING enable (SETTING=yes) or disable (SETTING=no) logging of DNSSEC validation failures\n"
+ "set-event-trace-enabled SETTING set logging of event trace messages, 0 = disabled, 1 = protobuf, 2 = log file, 3 = both\n"
+ "trace-regex [regex] emit resolution trace for matching queries (empty regex to clear trace)\n"
+ "top-largeanswer-remotes show top remotes receiving large answers\n"
+ "top-queries show top queries\n"
+ "top-pub-queries show top queries grouped by public suffix list\n"
+ "top-remotes show top remotes\n"
+ "top-timeouts show top downstream timeouts\n"
+ "top-servfail-queries show top queries receiving servfail answers\n"
+ "top-bogus-queries show top queries validating as bogus\n"
+ "top-pub-servfail-queries show top queries receiving servfail answers grouped by public suffix list\n"
+ "top-pub-bogus-queries show top queries validating as bogus grouped by public suffix list\n"
+ "top-servfail-remotes show top remotes receiving servfail answers\n"
+ "top-bogus-remotes show top remotes receiving bogus answers\n"
+ "unload-lua-script unload Lua script\n"
+ "version return Recursor version number\n"
+ "wipe-cache domain0 [domain1] .. wipe domain data from cache\n"
+ "wipe-cache-typed type domain0 [domain1] .. wipe domain data with qtype from cache\n"};
if (cmd == "get-all") {
return {0, getAllStats()};
return {0, doGetParameter(begin, end)};
}
if (cmd == "quit") {
- *command=&doExit;
+ *command = &doExit;
return {0, "bye\n"};
}
if (cmd == "version") {
- return {0, getPDNSVersion()+"\n"};
+ return {0, getPDNSVersion() + "\n"};
}
if (cmd == "quit-nicely") {
- *command=&doExitNicely;
+ *command = &doExitNicely;
return {0, "bye nicely\n"};
}
if (cmd == "dump-cache") {
luaConfigDelayedThreads delayedLuaThreads;
loadRecursorLuaConfig(::arg()["lua-config-file"], delayedLuaThreads);
startLuaConfigDelayedThreads(delayedLuaThreads, g_luaconfs.getCopy().generation);
- g_log<<Logger::Warning<<"Reloaded Lua configuration file '"<<::arg()["lua-config-file"]<<"', requested via control channel"<<endl;
- return {0, "Reloaded Lua configuration file '"+::arg()["lua-config-file"]+"'\n"};
+ g_log << Logger::Warning << "Reloaded Lua configuration file '" << ::arg()["lua-config-file"] << "', requested via control channel" << endl;
+ return {0, "Reloaded Lua configuration file '" + ::arg()["lua-config-file"] + "'\n"};
}
- catch(std::exception& e) {
- return {1, "Unable to load Lua script from '"+::arg()["lua-config-file"]+"': "+e.what()+"\n"};
+ catch (std::exception& e) {
+ return {1, "Unable to load Lua script from '" + ::arg()["lua-config-file"] + "': " + e.what() + "\n"};
}
- catch(const PDNSException& e) {
- return {1, "Unable to load Lua script from '"+::arg()["lua-config-file"]+"': "+e.reason+"\n"};
+ catch (const PDNSException& e) {
+ return {1, "Unable to load Lua script from '" + ::arg()["lua-config-file"] + "': " + e.reason + "\n"};
}
}
if (cmd == "set-carbon-server") {
}
if (cmd == "reload-acls") {
if (!::arg()["chroot"].empty()) {
- g_log<<Logger::Error<<"Unable to reload ACL when chroot()'ed, requested via control channel"<<endl;
+ g_log << Logger::Error << "Unable to reload ACL when chroot()'ed, requested via control channel" << endl;
return {1, "Unable to reload ACL when chroot()'ed, please restart\n"};
}
try {
parseACLs();
}
- catch(std::exception& e) {
- g_log<<Logger::Error<<"Reloading ACLs failed (Exception: "<<e.what()<<")"<<endl;
+ catch (std::exception& e) {
+ g_log << Logger::Error << "Reloading ACLs failed (Exception: " << e.what() << ")" << endl;
return {1, e.what() + string("\n")};
}
- catch(PDNSException& ae) {
- g_log<<Logger::Error<<"Reloading ACLs failed (PDNSException: "<<ae.reason<<")"<<endl;
+ catch (PDNSException& ae) {
+ g_log << Logger::Error << "Reloading ACLs failed (PDNSException: " << ae.reason << ")" << endl;
return {1, ae.reason + string("\n")};
}
return {0, "ok\n"};
}
if (cmd == "reload-zones") {
if (!::arg()["chroot"].empty()) {
- g_log<<Logger::Error<<"Unable to reload zones and forwards when chroot()'ed, requested via control channel"<<endl;
+ g_log << Logger::Error << "Unable to reload zones and forwards when chroot()'ed, requested via control channel" << endl;
return {1, "Unable to reload zones and forwards when chroot()'ed, please restart\n"};
}
return {0, reloadAuthAndForwards()};
return {0, setEventTracing(begin, end)};
}
- return {1, "Unknown command '"+cmd+"', try 'help'\n"};
+ return {1, "Unknown command '" + cmd + "', try 'help'\n"};
}
#include "namespaces.hh"
#include "rec_channel.hh"
-ArgvMap &arg()
+ArgvMap& arg()
{
static ArgvMap arg;
return arg;
static void initArguments(int argc, char** argv)
{
- arg().set("config-dir","Location of configuration directory (recursor.conf)")=SYSCONFDIR;
-
- arg().set("socket-dir",string("Where the controlsocket will live, ")+LOCALSTATEDIR+"/pdns-recursor when unset and not chrooted" )="";
- arg().set("chroot","switch to chroot jail")="";
- arg().set("process","When controlling multiple recursors, the target process number")="";
- arg().set("timeout", "Number of seconds to wait for the recursor to respond")="5";
- arg().set("config-name","Name of this virtual configuration - will rename the binary image")="";
- arg().setCmd("help","Provide this helpful message");
- arg().setCmd("version","Show the version of this program");
-
- arg().laxParse(argc,argv);
- if(arg().mustDo("help") || arg().getCommands().empty()) {
- cout<<"syntax: rec_control [options] command, options as below: "<<endl<<endl;
- cout<<arg().helpstring(arg()["help"])<<endl;
- cout<<"In addition, 'rec_control help' can be used to retrieve a list\nof available commands from PowerDNS"<<endl;
+ arg().set("config-dir", "Location of configuration directory (recursor.conf)") = SYSCONFDIR;
+
+ arg().set("socket-dir", string("Where the controlsocket will live, ") + LOCALSTATEDIR + "/pdns-recursor when unset and not chrooted") = "";
+ arg().set("chroot", "switch to chroot jail") = "";
+ arg().set("process", "When controlling multiple recursors, the target process number") = "";
+ arg().set("timeout", "Number of seconds to wait for the recursor to respond") = "5";
+ arg().set("config-name", "Name of this virtual configuration - will rename the binary image") = "";
+ arg().setCmd("help", "Provide this helpful message");
+ arg().setCmd("version", "Show the version of this program");
+
+ arg().laxParse(argc, argv);
+ if (arg().mustDo("help") || arg().getCommands().empty()) {
+ cout << "syntax: rec_control [options] command, options as below: " << endl
+ << endl;
+ cout << arg().helpstring(arg()["help"]) << endl;
+ cout << "In addition, 'rec_control help' can be used to retrieve a list\nof available commands from PowerDNS" << endl;
exit(arg().mustDo("help") ? 0 : 99);
}
- if(arg().mustDo("version")) {
- cout<<"rec_control version "<<VERSION<<endl;
+ if (arg().mustDo("version")) {
+ cout << "rec_control version " << VERSION << endl;
exit(0);
}
- string configname=::arg()["config-dir"]+"/recursor.conf";
+ string configname = ::arg()["config-dir"] + "/recursor.conf";
if (::arg()["config-name"] != "")
- configname=::arg()["config-dir"]+"/recursor-"+::arg()["config-name"]+".conf";
-
+ configname = ::arg()["config-dir"] + "/recursor-" + ::arg()["config-name"] + ".conf";
+
cleanSlashes(configname);
arg().laxFile(configname.c_str());
- arg().laxParse(argc,argv); // make sure the commandline wins
+ arg().laxParse(argc, argv); // make sure the commandline wins
if (::arg()["socket-dir"].empty()) {
if (::arg()["chroot"].empty())
::arg().set("socket-dir") = std::string(LOCALSTATEDIR) + "/pdns-recursor";
else
::arg().set("socket-dir") = ::arg()["chroot"] + "/";
- } else if (!::arg()["chroot"].empty()) {
+ }
+ else if (!::arg()["chroot"].empty()) {
::arg().set("socket-dir") = ::arg()["chroot"] + "/" + ::arg()["socket-dir"];
}
}
"dump-failedservers",
"dump-rpz",
"dump-throttlemap",
- "dump-non-resolving"
- };
+ "dump-non-resolving"};
try {
initArguments(argc, argv);
- string sockname="pdns_recursor";
+ string sockname = "pdns_recursor";
if (arg()["config-name"] != "")
- sockname+="-"+arg()["config-name"];
+ sockname += "-" + arg()["config-name"];
- if(!arg()["process"].empty())
- sockname+="."+arg()["process"];
+ if (!arg()["process"].empty())
+ sockname += "." + arg()["process"];
sockname.append(".controlsocket");
- const vector<string>&commands=arg().getCommands();
+ const vector<string>& commands = arg().getCommands();
if (commands.size() >= 1 && commands.at(0) == "hash-password") {
uint64_t workFactor = CredentialsHolder::s_defaultWorkFactor;
if (i + 2 < commands.size()) {
++i;
command += " " + commands[i]; // add rpzname and continue with filename
- } else {
+ }
+ else {
throw PDNSException("Command needs a zone and file argument");
}
}
++i;
if (commands[i] == "-") {
fd = STDOUT_FILENO;
- } else {
+ }
+ else {
fd = open(commands[i].c_str(), O_CREAT | O_EXCL | O_WRONLY, 0660);
}
if (fd == -1) {
int err = errno;
throw PDNSException("Error opening dump file for writing: " + stringerror(err));
}
- } else {
+ }
+ else {
throw PDNSException("Command needs a file argument");
}
}
auto receive = rccS.recv(0, timeout);
if (receive.d_ret != 0) {
cerr << receive.d_str;
- } else {
+ }
+ else {
cout << receive.d_str;
}
return receive.d_ret;
}
- catch(PDNSException& ae) {
- cerr<<"Fatal: "<<ae.reason<<"\n";
+ catch (PDNSException& ae) {
+ cerr << "Fatal: " << ae.reason << "\n";
return 1;
}
}
-
int RecursorPacketCache::doWipePacketCache(const DNSName& name, uint16_t qtype, bool subtree)
{
- int count=0;
+ int count = 0;
auto& idx = d_packetCache.get<NameTag>();
- for(auto iter = idx.lower_bound(name); iter != idx.end(); ) {
- if(subtree) {
- if(!iter->d_name.isPartOf(name)) { // this is case insensitive
- break;
+ for (auto iter = idx.lower_bound(name); iter != idx.end();) {
+ if (subtree) {
+ if (!iter->d_name.isPartOf(name)) { // this is case insensitive
+ break;
}
}
else {
- if(iter->d_name != name)
- break;
+ if (iter->d_name != name)
+ break;
}
- if(qtype==0xffff || iter->d_type == qtype) {
- iter=idx.erase(iter);
+ if (qtype == 0xffff || iter->d_type == qtype) {
+ iter = idx.erase(iter);
count++;
}
else
return false;
}
- static const std::unordered_set<uint16_t> optionsToSkip{ EDNSOptionCode::COOKIE, EDNSOptionCode::ECS };
+ static const std::unordered_set<uint16_t> optionsToSkip{EDNSOptionCode::COOKIE, EDNSOptionCode::ECS};
return queryMatches(iter->d_query, queryPacket, qname, optionsToSkip);
}
bool RecursorPacketCache::checkResponseMatches(std::pair<packetCache_t::index<HashTag>::type::iterator, packetCache_t::index<HashTag>::type::iterator> range, const std::string& queryPacket, const DNSName& qname, uint16_t qtype, uint16_t qclass, time_t now, std::string* responsePacket, uint32_t* age, vState* valState, OptPBData* pbdata)
{
- for(auto iter = range.first ; iter != range.second ; ++iter) {
+ for (auto iter = range.first; iter != range.second; ++iter) {
// the possibility is VERY real that we get hits that are not right - birthday paradox
if (!qrMatch(iter, queryPacket, qname, qtype, qclass)) {
continue;
if (pbdata != nullptr) {
if (iter->d_pbdata) {
*pbdata = iter->d_pbdata;
- } else {
+ }
+ else {
*pbdata = boost::none;
}
}
const auto& idx = d_packetCache.get<HashTag>();
auto range = idx.equal_range(tie(tag, *qhash, tcp));
- if(range.first == range.second) {
+ if (range.first == range.second) {
d_misses++;
return false;
}
}
bool RecursorPacketCache::getResponsePacket(unsigned int tag, const std::string& queryPacket, DNSName& qname, uint16_t* qtype, uint16_t* qclass, time_t now,
- std::string* responsePacket, uint32_t* age, vState* valState, uint32_t* qhash, OptPBData *pbdata, bool tcp)
+ std::string* responsePacket, uint32_t* age, vState* valState, uint32_t* qhash, OptPBData* pbdata, bool tcp)
{
*qhash = canHashPacket(queryPacket, s_skipOptions);
const auto& idx = d_packetCache.get<HashTag>();
auto range = idx.equal_range(tie(tag, *qhash, tcp));
- if(range.first == range.second) {
+ if (range.first == range.second) {
d_misses++;
return false;
}
return checkResponseMatches(range, queryPacket, qname, *qtype, *qclass, now, responsePacket, age, valState, pbdata);
}
-
void RecursorPacketCache::insertResponsePacket(unsigned int tag, uint32_t qhash, std::string&& query, const DNSName& qname, uint16_t qtype, uint16_t qclass, std::string&& responsePacket, time_t now, uint32_t ttl, const vState& valState, OptPBData&& pbdata, bool tcp)
{
auto& idx = d_packetCache.get<HashTag>();
auto range = idx.equal_range(tie(tag, qhash, tcp));
auto iter = range.first;
- for( ; iter != range.second ; ++iter) {
- if (iter->d_type != qtype || iter->d_class != qclass || iter->d_name != qname ) {
+ for (; iter != range.second; ++iter) {
+ if (iter->d_type != qtype || iter->d_class != qclass || iter->d_name != qname) {
continue;
}
break;
}
- if(iter == range.second) { // nothing to refresh
+ if (iter == range.second) { // nothing to refresh
struct Entry e(qname, std::move(responsePacket), std::move(query), tcp);
e.d_qhash = qhash;
e.d_type = qtype;
uint64_t RecursorPacketCache::bytes()
{
- uint64_t sum=0;
- for(const auto& e : d_packetCache) {
+ uint64_t sum = 0;
+ for (const auto& e : d_packetCache) {
sum += sizeof(e) + e.d_packet.length() + 4;
}
return sum;
uint64_t RecursorPacketCache::doDump(int fd)
{
- auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fdopen(dup(fd), "w"), fclose);
+ auto fp = std::unique_ptr<FILE, int (*)(FILE*)>(fdopen(dup(fd), "w"), fclose);
if (!fp) { // dup probably failed
return 0;
}
try {
fprintf(fp.get(), "%s %" PRId64 " %s ; tag %d %s\n", i.d_name.toString().c_str(), static_cast<int64_t>(i.d_ttd - now), DNSRecordContent::NumberToType(i.d_type).c_str(), i.d_tag, i.d_tcp ? "tcp" : "udp");
}
- catch(...) {
+ catch (...) {
fprintf(fp.get(), "; error printing '%s'\n", i.d_name.empty() ? "EMPTY" : i.d_name.toString().c_str());
}
}
you can use a query as a key too. But query and answer must compare as identical!
This precludes doing anything smart with EDNS directly from the packet */
-class RecursorPacketCache: public PacketCache
+class RecursorPacketCache : public PacketCache
{
public:
static unsigned int s_refresh_ttlperc;
- struct PBData {
+ struct PBData
+ {
std::string d_message;
std::string d_response;
bool d_tagged;
bool getResponsePacket(unsigned int tag, const std::string& queryPacket, time_t now, std::string* responsePacket, uint32_t* age, uint32_t* qhash);
bool getResponsePacket(unsigned int tag, const std::string& queryPacket, const DNSName& qname, uint16_t qtype, uint16_t qclass, time_t now, std::string* responsePacket, uint32_t* age, uint32_t* qhash);
bool getResponsePacket(unsigned int tag, const std::string& queryPacket, const DNSName& qname, uint16_t qtype, uint16_t qclass, time_t now, std::string* responsePacket, uint32_t* age, vState* valState, uint32_t* qhash, OptPBData* pbdata, bool tcp);
- bool getResponsePacket(unsigned int tag, const std::string& queryPacket, DNSName& qname, uint16_t *qtype, uint16_t* qclass, time_t now, std::string* responsePacket, uint32_t* age, vState* valState, uint32_t* qhash, OptPBData* pbdata, bool tcp);
-
+ bool getResponsePacket(unsigned int tag, const std::string& queryPacket, DNSName& qname, uint16_t* qtype, uint16_t* qclass, time_t now, std::string* responsePacket, uint32_t* age, vState* valState, uint32_t* qhash, OptPBData* pbdata, bool tcp);
+
void insertResponsePacket(unsigned int tag, uint32_t qhash, std::string&& query, const DNSName& qname, uint16_t qtype, uint16_t qclass, std::string&& responsePacket, time_t now, uint32_t ttl, const vState& valState, OptPBData&& pbdata, bool tcp);
- void doPruneTo(size_t maxSize=250000);
+ void doPruneTo(size_t maxSize = 250000);
uint64_t doDump(int fd);
- int doWipePacketCache(const DNSName& name, uint16_t qtype=0xffff, bool subtree=false);
-
+ int doWipePacketCache(const DNSName& name, uint16_t qtype = 0xffff, bool subtree = false);
+
void prune();
uint64_t d_hits, d_misses;
uint64_t size();
uint64_t bytes();
private:
- struct HashTag {};
- struct NameTag {};
- struct Entry
+ struct HashTag
+ {
+ };
+ struct NameTag
{
- Entry(const DNSName& qname, std::string&& packet, std::string&& query, bool tcp): d_name(qname), d_packet(std::move(packet)), d_query(std::move(query)), d_tcp(tcp)
+ };
+ struct Entry
+ {
+ Entry(const DNSName& qname, std::string&& packet, std::string&& query, bool tcp) :
+ d_name(qname), d_packet(std::move(packet)), d_query(std::move(query)), d_tcp(tcp)
{
}
mutable std::string d_query;
mutable OptPBData d_pbdata;
mutable time_t d_ttd;
- mutable time_t d_creation; // so we can 'age' our packets
+ mutable time_t d_creation; // so we can 'age' our packets
uint32_t d_qhash;
uint32_t d_tag;
uint16_t d_type;
uint16_t d_class;
mutable vState d_vstate;
mutable bool d_submitted{false}; // whether this entry has been queued for refetch
- bool d_tcp; // whether this entry was created from a TCP query
+ bool d_tcp; // whether this entry was created from a TCP query
inline bool operator<(const struct Entry& rhs) const;
time_t getTTD() const
return d_ttd;
}
- uint32_t getOrigTTL() const {
+ uint32_t getOrigTTL() const
+ {
return d_ttd - d_creation;
}
};
- struct SequencedTag{};
+ struct SequencedTag
+ {
+ };
typedef multi_index_container<
Entry,
- indexed_by <
+ indexed_by<
hashed_non_unique<tag<HashTag>,
composite_key<Entry,
member<Entry, uint32_t, &Entry::d_tag>,
member<Entry, uint32_t, &Entry::d_qhash>,
- member<Entry, bool, &Entry::d_tcp>
- >
- >,
+ member<Entry, bool, &Entry::d_tcp>>>,
sequenced<tag<SequencedTag>>,
- ordered_non_unique<tag<NameTag>, member<Entry,DNSName, &Entry::d_name>, CanonDNSNameCompare>
- >
- > packetCache_t;
+ ordered_non_unique<tag<NameTag>, member<Entry, DNSName, &Entry::d_name>, CanonDNSNameCompare>>>
+ packetCache_t;
packetCache_t d_packetCache;
#include "cachecleaner.hh"
#include "rec-taskqueue.hh"
-MemRecursorCache::MemRecursorCache(size_t mapsCount) : d_maps(mapsCount)
+MemRecursorCache::MemRecursorCache(size_t mapsCount) :
+ d_maps(mapsCount)
{
}
return count;
}
-pair<uint64_t,uint64_t> MemRecursorCache::stats()
+pair<uint64_t, uint64_t> MemRecursorCache::stats()
{
uint64_t c = 0, a = 0;
for (auto& mc : d_maps) {
c += content->d_contended_count;
a += content->d_acquired_count;
}
- return pair<uint64_t,uint64_t>(c, a);
+ return pair<uint64_t, uint64_t>(c, a);
}
size_t MemRecursorCache::ecsIndexSize()
if (res) {
res->reserve(res->size() + entry->d_records.size());
- for(const auto& k : entry->d_records) {
+ for (const auto& k : entry->d_records) {
DNSRecord dr;
dr.d_name = qname;
dr.d_type = entry->d_qtype;
return ttd;
}
-MemRecursorCache::cache_t::const_iterator MemRecursorCache::getEntryUsingECSIndex(MapCombo::LockedContent& map, time_t now, const DNSName &qname, const QType qtype, bool requireAuth, const ComboAddress& who)
+MemRecursorCache::cache_t::const_iterator MemRecursorCache::getEntryUsingECSIndex(MapCombo::LockedContent& map, time_t now, const DNSName& qname, const QType qtype, bool requireAuth, const ComboAddress& who)
{
// MUTEX SHOULD BE ACQUIRED (as indicated by the reference to the content which is protected by a lock)
auto ecsIndexKey = tie(qname, qtype);
return map.d_map.end();
}
-MemRecursorCache::Entries MemRecursorCache::getEntries(MapCombo::LockedContent& map, const DNSName &qname, const QType qt, const OptTag& rtag )
+MemRecursorCache::Entries MemRecursorCache::getEntries(MapCombo::LockedContent& map, const DNSName& qname, const QType qt, const OptTag& rtag)
{
// MUTEX SHOULD BE ACQUIRED
if (!map.d_cachecachevalid || map.d_cachedqname != qname || map.d_cachedrtag != rtag) {
return map.d_cachecache;
}
-
bool MemRecursorCache::entryMatches(MemRecursorCache::OrderedTagIterator_t& entry, const QType qt, bool requireAuth, const ComboAddress& who)
{
// This code assumes that if a routing tag is present, it matches
if (requireAuth && !entry->d_auth)
return false;
- bool match = (entry->d_qtype == qt || qt == QType::ANY ||
- (qt == QType::ADDR && (entry->d_qtype == QType::A || entry->d_qtype == QType::AAAA)))
+ bool match = (entry->d_qtype == qt || qt == QType::ANY || (qt == QType::ADDR && (entry->d_qtype == QType::A || entry->d_qtype == QType::AAAA)))
&& (entry->d_netmask.empty() || entry->d_netmask.match(who));
return match;
}
if (almostExpired && qname != g_rootdnsname) {
if (refresh) {
return -1;
- } else {
+ }
+ else {
if (!entry->d_submitted) {
pushAlmostExpiredTask(qname, qtype, entry->d_ttd);
entry->d_submitted = true;
return ttl;
}
// returns -1 for no hits
-time_t MemRecursorCache::get(time_t now, const DNSName &qname, const QType qt, bool requireAuth, vector<DNSRecord>* res, const ComboAddress& who, bool refresh, const OptTag& routingTag, vector<std::shared_ptr<RRSIGRecordContent>>* signatures, std::vector<std::shared_ptr<DNSRecord>>* authorityRecs, bool* variable, vState* state, bool* wasAuth, DNSName* fromAuthZone)
+time_t MemRecursorCache::get(time_t now, const DNSName& qname, const QType qt, bool requireAuth, vector<DNSRecord>* res, const ComboAddress& who, bool refresh, const OptTag& routingTag, vector<std::shared_ptr<RRSIGRecordContent>>* signatures, std::vector<std::shared_ptr<DNSRecord>>* authorityRecs, bool* variable, vState* state, bool* wasAuth, DNSName* fromAuthZone)
{
boost::optional<vState> cachedState{boost::none};
uint32_t origTTL;
- if(res) {
+ if (res) {
res->clear();
}
const uint16_t qtype = qt.getCode();
time_t ttdAAAA = handleHit(*map, entryAAAA, qname, origTTL, res, signatures, authorityRecs, variable, cachedState, wasAuth, fromAuthZone);
if (ret > 0) {
ret = std::min(ret, ttdAAAA);
- } else {
+ }
+ else {
ret = ttdAAAA;
}
}
if (entries.first != entries.second) {
OrderedTagIterator_t firstIndexIterator;
- for (auto i=entries.first; i != entries.second; ++i) {
+ for (auto i = entries.first; i != entries.second; ++i) {
firstIndexIterator = map->d_map.project<OrderedTag>(i);
if (i->d_ttd <= now) {
*state = *cachedState;
}
return fakeTTD(firstIndexIterator, qname, qtype, ttd, now, origTTL, refresh);
- } else {
+ }
+ else {
return -1;
}
}
bool found = false;
time_t ttd;
- for (auto i=entries.first; i != entries.second; ++i) {
+ for (auto i = entries.first; i != entries.second; ++i) {
firstIndexIterator = map->d_map.project<OrderedTag>(i);
if (i->d_ttd <= now) {
return -1;
}
-void MemRecursorCache::replace(time_t now, const DNSName &qname, const QType qt, const vector<DNSRecord>& content, const vector<shared_ptr<RRSIGRecordContent>>& signatures, const std::vector<std::shared_ptr<DNSRecord>>& authorityRecs, bool auth, const DNSName& authZone, boost::optional<Netmask> ednsmask, const OptTag& routingTag, vState state, boost::optional<ComboAddress> from)
+void MemRecursorCache::replace(time_t now, const DNSName& qname, const QType qt, const vector<DNSRecord>& content, const vector<shared_ptr<RRSIGRecordContent>>& signatures, const std::vector<std::shared_ptr<DNSRecord>>& authorityRecs, bool auth, const DNSName& authZone, boost::optional<Netmask> ednsmask, const OptTag& routingTag, vState state, boost::optional<ComboAddress> from)
{
auto& mc = getMap(qname);
auto map = mc.lock();
}
}
- time_t maxTTD=std::numeric_limits<time_t>::max();
- CacheEntry ce=*stored; // this is a COPY
- ce.d_qtype=qt.getCode();
+ time_t maxTTD = std::numeric_limits<time_t>::max();
+ CacheEntry ce = *stored; // this is a COPY
+ ce.d_qtype = qt.getCode();
- if(!auth && ce.d_auth) { // unauth data came in, we have some auth data, but is it fresh?
- if(ce.d_ttd > now) { // we still have valid data, ignore unauth data
+ if (!auth && ce.d_auth) { // unauth data came in, we have some auth data, but is it fresh?
+ if (ce.d_ttd > now) { // we still have valid data, ignore unauth data
return;
}
else {
- ce.d_auth = false; // new data won't be auth
+ ce.d_auth = false; // new data won't be auth
}
}
ce.d_authZone = authZone;
if (from) {
ce.d_from = *from;
- } else {
+ }
+ else {
ce.d_from = ComboAddress();
}
for (const auto& i : content) {
/* Yes, we have altered the d_ttl value by adding time(nullptr) to it
prior to calling this function, so the TTL actually holds a TTD. */
- ce.d_ttd = min(maxTTD, static_cast<time_t>(i.d_ttl)); // XXX this does weird things if TTLs differ in the set
+ ce.d_ttd = min(maxTTD, static_cast<time_t>(i.d_ttl)); // XXX this does weird things if TTLs differ in the set
ce.d_orig_ttl = ce.d_ttd - now;
ce.d_records.push_back(i.d_content);
}
i = idx.erase(i);
count++;
--mc.d_entriesCount;
- } else {
+ }
+ else {
++i;
}
}
auto map = mc.lock();
map->d_cachecachevalid = false;
auto& idx = map->d_map.get<OrderedTag>();
- for (auto i = idx.lower_bound(name); i != idx.end(); ) {
+ for (auto i = idx.lower_bound(name); i != idx.end();) {
if (!i->d_qname.isPartOf(name))
break;
if (i->d_qtype == qtype || qtype == 0xffff) {
count++;
i = idx.erase(i);
--mc.d_entriesCount;
- } else {
+ }
+ else {
++i;
}
}
auto& ecsIdx = map->d_ecsIndex.get<OrderedTag>();
- for (auto i = ecsIdx.lower_bound(name); i != ecsIdx.end(); ) {
+ for (auto i = ecsIdx.lower_bound(name); i != ecsIdx.end();) {
if (!i->d_qname.isPartOf(name))
break;
if (i->d_qtype == qtype || qtype == 0xffff) {
i = ecsIdx.erase(i);
- } else {
+ }
+ else {
++i;
}
}
CacheEntry ce = *iter;
if (ce.d_ttd < now)
- return false; // would be dead anyhow
+ return false; // would be dead anyhow
uint32_t maxTTL = static_cast<uint32_t>(ce.d_ttd - now);
if (maxTTL > newTTL) {
return false;
}
-bool MemRecursorCache::updateValidationStatus(time_t now, const DNSName &qname, const QType qt, const ComboAddress& who, const OptTag& routingTag, bool requireAuth, vState newState, boost::optional<time_t> capTTD)
+bool MemRecursorCache::updateValidationStatus(time_t now, const DNSName& qname, const QType qt, const ComboAddress& who, const OptTag& routingTag, bool requireAuth, vState newState, boost::optional<time_t> capTTD)
{
uint16_t qtype = qt.getCode();
if (qtype == QType::ANY) {
auto entries = getEntries(*map, qname, qt, routingTag);
- for(auto i = entries.first; i != entries.second; ++i) {
+ for (auto i = entries.first; i != entries.second; ++i) {
auto firstIndexIterator = map->d_map.project<OrderedTag>(i);
if (!entryMatches(firstIndexIterator, qtype, requireAuth, who)) {
if (newfd == -1) {
return 0;
}
- auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fdopen(newfd, "w"), fclose);
- if(!fp) { // dup probably failed
+ auto fp = std::unique_ptr<FILE, int (*)(FILE*)>(fdopen(newfd, "w"), fclose);
+ if (!fp) { // dup probably failed
close(newfd);
return 0;
}
try {
fprintf(fp.get(), "%s %" PRIu32 " %" PRId64 " IN %s %s ; (%s) auth=%i zone=%s from=%s %s %s\n", i.d_qname.toString().c_str(), i.d_orig_ttl, static_cast<int64_t>(i.d_ttd - now), i.d_qtype.toString().c_str(), j->getZoneRepresentation().c_str(), vStateToString(i.d_state).c_str(), i.d_auth, i.d_authZone.toLogString().c_str(), i.d_from.toString().c_str(), i.d_netmask.empty() ? "" : i.d_netmask.toString().c_str(), !i.d_rtag ? "" : i.d_rtag.get().c_str());
}
- catch(...) {
+ catch (...) {
fprintf(fp.get(), "; error printing '%s'\n", i.d_qname.empty() ? "EMPTY" : i.d_qname.toString().c_str());
}
}
- for (const auto &sig : i.d_signatures) {
+ for (const auto& sig : i.d_signatures) {
count++;
try {
fprintf(fp.get(), "%s %" PRIu32 " %" PRId64 " IN RRSIG %s ; %s\n", i.d_qname.toString().c_str(), i.d_orig_ttl, static_cast<int64_t>(i.d_ttd - now), sig->getZoneRepresentation().c_str(), i.d_netmask.empty() ? "" : i.d_netmask.toString().c_str());
}
- catch(...) {
+ catch (...) {
fprintf(fp.get(), "; error printing '%s'\n", i.d_qname.empty() ? "EMPTY" : i.d_qname.toString().c_str());
}
}
pruneMutexCollectionsVector<SequencedTag>(*this, d_maps, keep, cacheSize);
}
-namespace boost {
- size_t hash_value(const MemRecursorCache::OptTag& o)
- {
- return o ? hash_value(o.get()) : 0xcafebaaf;
- }
+namespace boost
+{
+size_t hash_value(const MemRecursorCache::OptTag& o)
+{
+ return o ? hash_value(o.get()) : 0xcafebaaf;
+}
}
size_t size() const;
size_t bytes();
- pair<uint64_t,uint64_t> stats();
+ pair<uint64_t, uint64_t> stats();
size_t ecsIndexSize();
typedef boost::optional<std::string> OptTag;
- time_t get(time_t, const DNSName &qname, const QType qt, bool requireAuth, vector<DNSRecord>* res, const ComboAddress& who, bool refresh = false, const OptTag& routingTag = boost::none, vector<std::shared_ptr<RRSIGRecordContent>>* signatures=nullptr, std::vector<std::shared_ptr<DNSRecord>>* authorityRecs=nullptr, bool* variable=nullptr, vState* state=nullptr, bool* wasAuth=nullptr, DNSName* fromAuthZone=nullptr);
+ time_t get(time_t, const DNSName& qname, const QType qt, bool requireAuth, vector<DNSRecord>* res, const ComboAddress& who, bool refresh = false, const OptTag& routingTag = boost::none, vector<std::shared_ptr<RRSIGRecordContent>>* signatures = nullptr, std::vector<std::shared_ptr<DNSRecord>>* authorityRecs = nullptr, bool* variable = nullptr, vState* state = nullptr, bool* wasAuth = nullptr, DNSName* fromAuthZone = nullptr);
- void replace(time_t, const DNSName &qname, const QType qt, const vector<DNSRecord>& content, const vector<shared_ptr<RRSIGRecordContent>>& signatures, const std::vector<std::shared_ptr<DNSRecord>>& authorityRecs, bool auth, const DNSName& authZone, boost::optional<Netmask> ednsmask=boost::none, const OptTag& routingTag = boost::none, vState state=vState::Indeterminate, boost::optional<ComboAddress> from=boost::none);
+ void replace(time_t, const DNSName& qname, const QType qt, const vector<DNSRecord>& content, const vector<shared_ptr<RRSIGRecordContent>>& signatures, const std::vector<std::shared_ptr<DNSRecord>>& authorityRecs, bool auth, const DNSName& authZone, boost::optional<Netmask> ednsmask = boost::none, const OptTag& routingTag = boost::none, vState state = vState::Indeterminate, boost::optional<ComboAddress> from = boost::none);
void doPrune(size_t keep);
uint64_t doDump(int fd);
- size_t doWipeCache(const DNSName& name, bool sub, QType qtype=0xffff);
+ size_t doWipeCache(const DNSName& name, bool sub, QType qtype = 0xffff);
bool doAgeCache(time_t now, const DNSName& name, QType qtype, uint32_t newTTL);
- bool updateValidationStatus(time_t now, const DNSName &qname, QType qt, const ComboAddress& who, const OptTag& routingTag, bool requireAuth, vState newState, boost::optional<time_t> capTTD);
+ bool updateValidationStatus(time_t now, const DNSName& qname, QType qt, const ComboAddress& who, const OptTag& routingTag, bool requireAuth, vState newState, boost::optional<time_t> capTTD);
pdns::stat_t cacheHits{0}, cacheMisses{0};
private:
-
struct CacheEntry
{
- CacheEntry(const boost::tuple<DNSName, QType, OptTag, Netmask>& key, bool auth):
+ CacheEntry(const boost::tuple<DNSName, QType, OptTag, Netmask>& key, bool auth) :
d_qname(key.get<0>()), d_netmask(key.get<3>().getNormalized()), d_rtag(key.get<2>()), d_state(vState::Indeterminate), d_ttd(0), d_qtype(key.get<1>()), d_auth(auth), d_submitted(false)
{
}
uint32_t d_orig_ttl;
QType d_qtype;
bool d_auth;
- mutable bool d_submitted; // whether this entry has been queued for refetch
+ mutable bool d_submitted; // whether this entry has been queued for refetch
};
/* The ECS Index (d_ecsIndex) keeps track of whether there is any ECS-specific
class ECSIndexEntry
{
public:
- ECSIndexEntry(const DNSName& qname, QType qtype): d_nmt(), d_qname(qname), d_qtype(qtype)
+ ECSIndexEntry(const DNSName& qname, QType qtype) :
+ d_nmt(), d_qname(qname), d_qtype(qtype)
{
}
QType d_qtype;
};
- struct HashedTag {};
- struct SequencedTag {};
- struct NameAndRTagOnlyHashedTag {};
- struct OrderedTag {};
+ struct HashedTag
+ {
+ };
+ struct SequencedTag
+ {
+ };
+ struct NameAndRTagOnlyHashedTag
+ {
+ };
+ struct OrderedTag
+ {
+ };
typedef multi_index_container<
CacheEntry,
- indexed_by <
- ordered_unique<tag<OrderedTag>,
+ indexed_by<
+ ordered_unique<tag<OrderedTag>,
+ composite_key<
+ CacheEntry,
+ member<CacheEntry, DNSName, &CacheEntry::d_qname>,
+ member<CacheEntry, QType, &CacheEntry::d_qtype>,
+ member<CacheEntry, OptTag, &CacheEntry::d_rtag>,
+ member<CacheEntry, Netmask, &CacheEntry::d_netmask>>,
+ composite_key_compare<CanonDNSNameCompare, std::less<QType>, std::less<OptTag>, std::less<Netmask>>>,
+ sequenced<tag<SequencedTag>>,
+ hashed_non_unique<tag<NameAndRTagOnlyHashedTag>,
composite_key<
- CacheEntry,
- member<CacheEntry,DNSName,&CacheEntry::d_qname>,
- member<CacheEntry,QType,&CacheEntry::d_qtype>,
- member<CacheEntry,OptTag,&CacheEntry::d_rtag>,
- member<CacheEntry,Netmask,&CacheEntry::d_netmask>
- >,
- composite_key_compare<CanonDNSNameCompare, std::less<QType>, std::less<OptTag>, std::less<Netmask> >
- >,
- sequenced<tag<SequencedTag> >,
- hashed_non_unique<tag<NameAndRTagOnlyHashedTag>,
- composite_key<
- CacheEntry,
- member<CacheEntry,DNSName,&CacheEntry::d_qname>,
- member<CacheEntry,OptTag,&CacheEntry::d_rtag>
- >
- >
- >
- > cache_t;
+ CacheEntry,
+ member<CacheEntry, DNSName, &CacheEntry::d_qname>,
+ member<CacheEntry, OptTag, &CacheEntry::d_rtag>>>>>
+ cache_t;
typedef MemRecursorCache::cache_t::index<MemRecursorCache::OrderedTag>::type::iterator OrderedTagIterator_t;
typedef MemRecursorCache::cache_t::index<MemRecursorCache::NameAndRTagOnlyHashedTag>::type::iterator NameAndRTagOnlyHashedTagIterator_t;
typedef multi_index_container<
ECSIndexEntry,
- indexed_by <
- hashed_unique <tag<HashedTag>,
- composite_key<
- ECSIndexEntry,
- member<ECSIndexEntry,DNSName,&ECSIndexEntry::d_qname>,
- member<ECSIndexEntry,QType,&ECSIndexEntry::d_qtype>
- >
- >,
+ indexed_by<
+ hashed_unique<tag<HashedTag>,
+ composite_key<
+ ECSIndexEntry,
+ member<ECSIndexEntry, DNSName, &ECSIndexEntry::d_qname>,
+ member<ECSIndexEntry, QType, &ECSIndexEntry::d_qtype>>>,
ordered_unique<tag<OrderedTag>,
- composite_key<
- ECSIndexEntry,
- member<ECSIndexEntry,DNSName,&ECSIndexEntry::d_qname>,
- member<ECSIndexEntry,QType,&ECSIndexEntry::d_qtype>
- >,
- composite_key_compare<CanonDNSNameCompare, std::less<QType> >
- >
- >
- > ecsIndex_t;
+ composite_key<
+ ECSIndexEntry,
+ member<ECSIndexEntry, DNSName, &ECSIndexEntry::d_qname>,
+ member<ECSIndexEntry, QType, &ECSIndexEntry::d_qtype>>,
+ composite_key_compare<CanonDNSNameCompare, std::less<QType>>>>>
+ ecsIndex_t;
typedef std::pair<NameAndRTagOnlyHashedTagIterator_t, NameAndRTagOnlyHashedTagIterator_t> Entries;
struct MapCombo
{
MapCombo() {}
- MapCombo(const MapCombo &) = delete;
- MapCombo & operator=(const MapCombo &) = delete;
+ MapCombo(const MapCombo&) = delete;
+ MapCombo& operator=(const MapCombo&) = delete;
struct LockedContent
{
cache_t d_map;
};
vector<MapCombo> d_maps;
- MapCombo& getMap(const DNSName &qname)
+ MapCombo& getMap(const DNSName& qname)
{
return d_maps.at(qname.hash() % d_maps.size());
}
static time_t fakeTTD(OrderedTagIterator_t& entry, const DNSName& qname, QType qtype, time_t ret, time_t now, uint32_t origTTL, bool refresh);
bool entryMatches(OrderedTagIterator_t& entry, QType qt, bool requireAuth, const ComboAddress& who);
- Entries getEntries(MapCombo::LockedContent& content, const DNSName &qname, const QType qt, const OptTag& rtag);
- cache_t::const_iterator getEntryUsingECSIndex(MapCombo::LockedContent& content, time_t now, const DNSName &qname, QType qtype, bool requireAuth, const ComboAddress& who);
+ Entries getEntries(MapCombo::LockedContent& content, const DNSName& qname, const QType qt, const OptTag& rtag);
+ cache_t::const_iterator getEntryUsingECSIndex(MapCombo::LockedContent& content, time_t now, const DNSName& qname, QType qtype, bool requireAuth, const ComboAddress& who);
time_t handleHit(MapCombo::LockedContent& content, OrderedTagIterator_t& entry, const DNSName& qname, uint32_t& origTTL, vector<DNSRecord>* res, vector<std::shared_ptr<RRSIGRecordContent>>* signatures, std::vector<std::shared_ptr<DNSRecord>>* authorityRecs, bool* variable, boost::optional<vState>& state, bool* wasAuth, DNSName* authZone);
}
};
-namespace boost {
- size_t hash_value(const MemRecursorCache::OptTag& rtag);
+namespace boost
+{
+size_t hash_value(const MemRecursorCache::OptTag& rtag);
}
#include "secpoll.hh"
#include <stdint.h>
-#ifndef PACKAGEVERSION
+#ifndef PACKAGEVERSION
#define PACKAGEVERSION getPDNSVersion()
#endif
void doSecPoll(time_t* last_secpoll)
{
- if(::arg()["security-poll-suffix"].empty())
+ if (::arg()["security-poll-suffix"].empty())
return;
string pkgv(PACKAGEVERSION);
/* update last_secpoll right now, even if it fails
we don't want to retry right away and hammer the server */
- *last_secpoll=now.tv_sec;
+ *last_secpoll = now.tv_sec;
SyncRes sr(now);
if (g_dnssecmode != DNSSECMode::Off) {
vector<DNSRecord> ret;
- string version = "recursor-" +pkgv;
- string qstring(version.substr(0, 63)+ ".security-status."+::arg()["security-poll-suffix"]);
+ string version = "recursor-" + pkgv;
+ string qstring(version.substr(0, 63) + ".security-status." + ::arg()["security-poll-suffix"]);
- if(*qstring.rbegin()!='.')
- qstring+='.';
+ if (*qstring.rbegin() != '.')
+ qstring += '.';
boost::replace_all(qstring, "+", "_");
boost::replace_all(qstring, "~", "_");
}
if (vStateIsBogus(state)) {
- g_log<<Logger::Error<<"Failed to retrieve security status update for '" +pkgv+ "' on '"<<query<<"', DNSSEC validation result was Bogus!"<<endl;
- if(g_security_status == 1) // If we were OK, go to unknown
+ g_log << Logger::Error << "Failed to retrieve security status update for '" + pkgv + "' on '" << query << "', DNSSEC validation result was Bogus!" << endl;
+ if (g_security_status == 1) // If we were OK, go to unknown
g_security_status = 0;
return;
}
if (res == RCode::NXDomain && !isReleaseVersion(pkgv)) {
- g_log<<Logger::Warning<<"Not validating response for security status update, this is a non-release version"<<endl;
+ g_log << Logger::Warning << "Not validating response for security status update, this is a non-release version" << endl;
return;
}
try {
processSecPoll(res, ret, security_status, security_message);
- } catch(const PDNSException &pe) {
+ }
+ catch (const PDNSException& pe) {
g_security_status = security_status;
- g_log<<Logger::Warning<<"Failed to retrieve security status update for '" << pkgv << "' on '"<< query << "': "<<pe.reason<<endl;
+ g_log << Logger::Warning << "Failed to retrieve security status update for '" << pkgv << "' on '" << query << "': " << pe.reason << endl;
return;
}
g_security_message = security_message;
- if(g_security_status != 1 && security_status == 1) {
- g_log<<Logger::Warning << "Polled security status of version "<<pkgv<<", no known issues reported: " <<g_security_message<<endl;
+ if (g_security_status != 1 && security_status == 1) {
+ g_log << Logger::Warning << "Polled security status of version " << pkgv << ", no known issues reported: " << g_security_message << endl;
}
- if(security_status == 2) {
- g_log<<Logger::Error<<"PowerDNS Security Update Recommended: "<<g_security_message<<endl;
+ if (security_status == 2) {
+ g_log << Logger::Error << "PowerDNS Security Update Recommended: " << g_security_message << endl;
}
- if(security_status == 3) {
- g_log<<Logger::Error<<"PowerDNS Security Update Mandatory: "<<g_security_message<<endl;
+ if (security_status == 3) {
+ g_log << Logger::Error << "PowerDNS Security Update Mandatory: " << g_security_message << endl;
}
g_security_status = security_status;
#include "namespaces.hh"
#include <stdint.h>
-void doSecPoll(time_t* );
+void doSecPoll(time_t*);
extern uint32_t g_security_status;
extern std::string g_security_message;
#include "recpacketcache.hh"
#include <utility>
-
BOOST_AUTO_TEST_SUITE(test_recpacketcache_cc)
-BOOST_AUTO_TEST_CASE(test_recPacketCacheSimple) {
+BOOST_AUTO_TEST_CASE(test_recPacketCacheSimple)
+{
RecursorPacketCache rpc;
string fpacket;
- unsigned int tag=0;
- uint32_t age=0;
- uint32_t qhash=0;
- uint32_t ttd=3600;
+ unsigned int tag = 0;
+ uint32_t age = 0;
+ uint32_t qhash = 0;
+ uint32_t ttd = 3600;
BOOST_CHECK_EQUAL(rpc.size(), 0U);
- ::arg().set("rng")="auto";
- ::arg().set("entropy-source")="/dev/urandom";
+ ::arg().set("rng") = "auto";
+ ::arg().set("entropy-source") = "/dev/urandom";
DNSName qname("www.powerdns.com");
vector<uint8_t> packet;
DNSPacketWriter pw(packet, qname, QType::A);
- pw.getHeader()->rd=true;
- pw.getHeader()->qr=false;
- pw.getHeader()->id=dns_random_uint16();
+ pw.getHeader()->rd = true;
+ pw.getHeader()->qr = false;
+ pw.getHeader()->id = dns_random_uint16();
string qpacket((const char*)&packet[0], packet.size());
pw.startRecord(qname, QType::A, ttd);
BOOST_CHECK_EQUAL(fpacket, rpacket);
packet.clear();
- qname+=DNSName("co.uk");
+ qname += DNSName("co.uk");
DNSPacketWriter pw2(packet, qname, QType::A);
- pw2.getHeader()->rd=true;
- pw2.getHeader()->qr=false;
- pw2.getHeader()->id=dns_random_uint16();
+ pw2.getHeader()->rd = true;
+ pw2.getHeader()->qr = false;
+ pw2.getHeader()->id = dns_random_uint16();
qpacket.assign((const char*)&packet[0], packet.size());
found = rpc.getResponsePacket(tag, qpacket, time(nullptr), &fpacket, &age, &qhash);
BOOST_CHECK_EQUAL(rpc.size(), 0U);
}
-BOOST_AUTO_TEST_CASE(test_recPacketCacheSimplePost2038) {
+BOOST_AUTO_TEST_CASE(test_recPacketCacheSimplePost2038)
+{
RecursorPacketCache rpc;
string fpacket;
- unsigned int tag=0;
- uint32_t age=0;
- uint32_t qhash=0;
- uint32_t ttd=3600;
+ unsigned int tag = 0;
+ uint32_t age = 0;
+ uint32_t qhash = 0;
+ uint32_t ttd = 3600;
BOOST_CHECK_EQUAL(rpc.size(), 0U);
- ::arg().set("rng")="auto";
- ::arg().set("entropy-source")="/dev/urandom";
+ ::arg().set("rng") = "auto";
+ ::arg().set("entropy-source") = "/dev/urandom";
DNSName qname("www.powerdns.com");
vector<uint8_t> packet;
DNSPacketWriter pw(packet, qname, QType::A);
- pw.getHeader()->rd=true;
- pw.getHeader()->qr=false;
- pw.getHeader()->id=dns_random_uint16();
+ pw.getHeader()->rd = true;
+ pw.getHeader()->qr = false;
+ pw.getHeader()->id = dns_random_uint16();
string qpacket((const char*)&packet[0], packet.size());
pw.startRecord(qname, QType::A, ttd);
found = rpc.getResponsePacket(tag, qpacket, qname, QType::A, QClass::IN, future + 3601, &fpacket, &age, &qhash2);
BOOST_CHECK_EQUAL(found, false);
-
packet.clear();
- qname+=DNSName("co.uk");
+ qname += DNSName("co.uk");
DNSPacketWriter pw2(packet, qname, QType::A);
- pw2.getHeader()->rd=true;
- pw2.getHeader()->qr=false;
- pw2.getHeader()->id=dns_random_uint16();
+ pw2.getHeader()->rd = true;
+ pw2.getHeader()->qr = false;
+ pw2.getHeader()->id = dns_random_uint16();
qpacket.assign((const char*)&packet[0], packet.size());
found = rpc.getResponsePacket(tag, qpacket, future, &fpacket, &age, &qhash);
BOOST_CHECK_EQUAL(rpc.size(), 0U);
}
-BOOST_AUTO_TEST_CASE(test_recPacketCache_Tags) {
+BOOST_AUTO_TEST_CASE(test_recPacketCache_Tags)
+{
/* Insert a response with tag1, the exact same query with a different tag
should lead to a miss. Inserting a different response with the second tag
should not override the first one, and we should get a hit for the
*/
RecursorPacketCache rpc;
string fpacket;
- const unsigned int tag1=0;
- const unsigned int tag2=42;
- uint32_t age=0;
- uint32_t qhash=0;
- uint32_t temphash=0;
- uint32_t ttd=3600;
+ const unsigned int tag1 = 0;
+ const unsigned int tag2 = 42;
+ uint32_t age = 0;
+ uint32_t qhash = 0;
+ uint32_t temphash = 0;
+ uint32_t ttd = 3600;
BOOST_CHECK_EQUAL(rpc.size(), 0U);
- ::arg().set("rng")="auto";
- ::arg().set("entropy-source")="/dev/urandom";
+ ::arg().set("rng") = "auto";
+ ::arg().set("entropy-source") = "/dev/urandom";
DNSName qname("www.powerdns.com");
vector<uint8_t> packet;
DNSPacketWriter pw(packet, qname, QType::A);
- pw.getHeader()->rd=true;
- pw.getHeader()->qr=false;
- pw.getHeader()->id=dns_random_uint16();
+ pw.getHeader()->rd = true;
+ pw.getHeader()->qr = false;
+ pw.getHeader()->id = dns_random_uint16();
string qpacket(reinterpret_cast<const char*>(&packet[0]), packet.size());
pw.startRecord(qname, QType::A, ttd);
BOOST_CHECK_EQUAL(fpacket, r2packet);
}
-BOOST_AUTO_TEST_CASE(test_recPacketCache_TCP) {
+BOOST_AUTO_TEST_CASE(test_recPacketCache_TCP)
+{
/* Insert a response with UDP, the exact same query with a TCP flag
should lead to a miss.
*/
RecursorPacketCache rpc;
string fpacket;
- uint32_t age=0;
- uint32_t qhash=0;
- uint32_t temphash=0;
- uint32_t ttd=3600;
+ uint32_t age = 0;
+ uint32_t qhash = 0;
+ uint32_t temphash = 0;
+ uint32_t ttd = 3600;
BOOST_CHECK_EQUAL(rpc.size(), 0U);
- ::arg().set("rng")="auto";
- ::arg().set("entropy-source")="/dev/urandom";
+ ::arg().set("rng") = "auto";
+ ::arg().set("entropy-source") = "/dev/urandom";
DNSName qname("www.powerdns.com");
vector<uint8_t> packet;
DNSPacketWriter pw(packet, qname, QType::A);
- pw.getHeader()->rd=true;
- pw.getHeader()->qr=false;
- pw.getHeader()->id=dns_random_uint16();
+ pw.getHeader()->rd = true;
+ pw.getHeader()->qr = false;
+ pw.getHeader()->id = dns_random_uint16();
string qpacket(reinterpret_cast<const char*>(&packet[0]), packet.size());
pw.startRecord(qname, QType::A, ttd);
DNSSECMode g_dnssecmode{DNSSECMode::ProcessNoValidate};
bool g_dnssecLogBogus;
-bool checkDNSSECDisabled() {
+bool checkDNSSECDisabled()
+{
return warnIfDNSSECDisabled("");
}
-bool warnIfDNSSECDisabled(const string& msg) {
- if(g_dnssecmode == DNSSECMode::Off) {
+bool warnIfDNSSECDisabled(const string& msg)
+{
+ if (g_dnssecmode == DNSSECMode::Off) {
if (!msg.empty())
- g_log<<Logger::Warning<<msg<<endl;
+ g_log << Logger::Warning << msg << endl;
return true;
}
return false;
}
// Returns true if dsAnchors were modified
-bool updateTrustAnchorsFromFile(const std::string &fname, map<DNSName, dsmap_t> &dsAnchors) {
- map<DNSName,dsmap_t> newDSAnchors;
+bool updateTrustAnchorsFromFile(const std::string& fname, map<DNSName, dsmap_t>& dsAnchors)
+{
+ map<DNSName, dsmap_t> newDSAnchors;
try {
auto zp = ZoneParserTNG(fname);
zp.disableGenerate();
DNSResourceRecord rr;
DNSRecord dr;
- while(zp.get(rr)) {
+ while (zp.get(rr)) {
dr = DNSRecord(rr);
if (rr.qtype == QType::DS) {
auto dsr = getRR<DSRecordContent>(dr);
if (rr.qtype == QType::DNSKEY) {
auto dnskeyr = getRR<DNSKEYRecordContent>(dr);
if (dnskeyr == nullptr) {
- throw PDNSException("Unable to parse DNSKEY record '" + rr.qname.toString() + " " + rr.getZoneRepresentation() +"'");
+ throw PDNSException("Unable to parse DNSKEY record '" + rr.qname.toString() + " " + rr.getZoneRepresentation() + "'");
}
auto dsr = makeDSFromDNSKey(rr.qname, *dnskeyr, DNSSECKeeper::DIGEST_SHA256);
newDSAnchors[rr.qname].insert(dsr);
}
}
if (dsAnchors == newDSAnchors) {
- g_log<<Logger::Debug<<"Read Trust Anchors from file, no changes detected"<<endl;
+ g_log << Logger::Debug << "Read Trust Anchors from file, no changes detected" << endl;
return false;
}
- g_log<<Logger::Info<<"Read changed Trust Anchors from file, updating"<<endl;
+ g_log << Logger::Info << "Read changed Trust Anchors from file, updating" << endl;
dsAnchors = newDSAnchors;
return true;
}
- catch (const std::exception &e) {
+ catch (const std::exception& e) {
throw PDNSException("Error while reading Trust Anchors from file '" + fname + "': " + e.what());
}
catch (...) {
ValidateAll: DNSSEC issue -> servfail
*/
-enum class DNSSECMode { Off, Process, ProcessNoValidate, ValidateForLog, ValidateAll };
+enum class DNSSECMode
+{
+ Off,
+ Process,
+ ProcessNoValidate,
+ ValidateForLog,
+ ValidateAll
+};
extern DNSSECMode g_dnssecmode;
extern bool g_dnssecLogBogus;
bool warnIfDNSSECDisabled(const string& msg);
vState increaseDNSSECStateCounter(const vState& state);
vState increaseXDNSSECStateCounter(const vState& state);
-bool updateTrustAnchorsFromFile(const std::string &fname, map<DNSName, dsmap_t> &dsAnchors);
+bool updateTrustAnchorsFromFile(const std::string& fname, map<DNSName, dsmap_t>& dsAnchors);
using json11::Json;
-void productServerStatisticsFetch(map<string,string>& out)
+void productServerStatisticsFetch(map<string, string>& out)
{
auto stats = getAllStatsMap(StatComponent::API);
- map<string,string> ret;
- for (const auto& entry: stats) {
+ map<string, string> ret;
+ for (const auto& entry : stats) {
ret.emplace(entry.first, entry.second.d_value);
}
out.swap(ret);
string filename = ::arg()["api-config-dir"] + "/" + filebasename + ".conf";
ofstream ofconf(filename.c_str());
if (!ofconf) {
- throw ApiException("Could not open config fragment file '"+filename+"' for writing: "+stringerror());
+ throw ApiException("Could not open config fragment file '" + filename + "' for writing: " + stringerror());
}
ofconf << "# Generated by pdns-recursor REST API, DO NOT EDIT" << endl;
ofconf << content << endl;
for (auto value : jlist.array_items()) {
try {
nmg.addMask(value.string_value());
- } catch (const NetmaskException &e) {
+ }
+ catch (const NetmaskException& e) {
throw ApiException(e.reason);
}
}
parseACLs();
// fall through to GET
- } else if (req->method != "GET") {
+ }
+ else if (req->method != "GET") {
throw HttpMethodNotAllowedException();
}
vector<string> entries;
t_allowFrom->toStringVector(&entries);
- resp->setJsonBody(Json::object {
- { "name", "allow-from" },
- { "value", entries },
+ resp->setJsonBody(Json::object{
+ {"name", "allow-from"},
+ {"value", entries},
});
}
{
auto iter = SyncRes::t_sstorage.domainmap->find(zonename);
if (iter == SyncRes::t_sstorage.domainmap->end())
- throw ApiException("Could not find domain '"+zonename.toLogString()+"'");
+ throw ApiException("Could not find domain '" + zonename.toLogString() + "'");
const SyncRes::AuthDomain& zone = iter->second;
Json::array servers;
- for(const ComboAddress& server : zone.d_servers) {
+ for (const ComboAddress& server : zone.d_servers) {
servers.push_back(server.toStringWithPort());
}
Json::array records;
- for(const SyncRes::AuthDomain::records_t::value_type& dr : zone.d_records) {
- records.push_back(Json::object {
- { "name", dr.d_name.toString() },
- { "type", DNSRecordContent::NumberToType(dr.d_type) },
- { "ttl", (double)dr.d_ttl },
- { "content", dr.d_content->getZoneRepresentation() }
- });
+ for (const SyncRes::AuthDomain::records_t::value_type& dr : zone.d_records) {
+ records.push_back(Json::object{
+ {"name", dr.d_name.toString()},
+ {"type", DNSRecordContent::NumberToType(dr.d_type)},
+ {"ttl", (double)dr.d_ttl},
+ {"content", dr.d_content->getZoneRepresentation()}});
}
// id is the canonical lookup key, which doesn't actually match the name (in some cases)
string zoneId = apiZoneNameToId(iter->first);
Json::object doc = {
- { "id", zoneId },
- { "url", "/api/v1/servers/localhost/zones/" + zoneId },
- { "name", iter->first.toString() },
- { "kind", zone.d_servers.empty() ? "Native" : "Forwarded" },
- { "servers", servers },
- { "recursion_desired", zone.d_servers.empty() ? false : zone.d_rdForward },
- { "records", records }
- };
+ {"id", zoneId},
+ {"url", "/api/v1/servers/localhost/zones/" + zoneId},
+ {"name", iter->first.toString()},
+ {"kind", zone.d_servers.empty() ? "Native" : "Forwarded"},
+ {"servers", servers},
+ {"recursion_desired", zone.d_servers.empty() ? false : zone.d_rdForward},
+ {"records", records}};
resp->setJsonBody(doc);
}
if (kind == "NATIVE") {
if (rd)
throw ApiException("kind=Native and recursion_desired are mutually exclusive");
- if(!singleIPTarget.empty()) {
+ if (!singleIPTarget.empty()) {
try {
- ComboAddress rem(singleIPTarget);
- if(rem.sin4.sin_family != AF_INET)
- throw ApiException("");
- singleIPTarget = rem.toString();
+ ComboAddress rem(singleIPTarget);
+ if (rem.sin4.sin_family != AF_INET)
+ throw ApiException("");
+ singleIPTarget = rem.toString();
}
- catch(...) {
- throw ApiException("Single IP target '"+singleIPTarget+"' is invalid");
+ catch (...) {
+ throw ApiException("Single IP target '" + singleIPTarget + "' is invalid");
}
}
string zonefilename = ::arg()["api-config-dir"] + "/" + confbasename + ".zone";
ofstream ofzone(zonefilename.c_str());
if (!ofzone) {
- throw ApiException("Could not open '"+zonefilename+"' for writing: "+stringerror());
+ throw ApiException("Could not open '" + zonefilename + "' for writing: " + stringerror());
}
ofzone << "; Generated by pdns-recursor REST API, DO NOT EDIT" << endl;
- ofzone << zonename << "\tIN\tSOA\tlocal.zone.\thostmaster."<<zonename<<" 1 1 1 1 1" << endl;
- if(!singleIPTarget.empty()) {
- ofzone <<zonename << "\t3600\tIN\tA\t"<<singleIPTarget<<endl;
- ofzone <<"*."<<zonename << "\t3600\tIN\tA\t"<<singleIPTarget<<endl;
+ ofzone << zonename << "\tIN\tSOA\tlocal.zone.\thostmaster." << zonename << " 1 1 1 1 1" << endl;
+ if (!singleIPTarget.empty()) {
+ ofzone << zonename << "\t3600\tIN\tA\t" << singleIPTarget << endl;
+ ofzone << "*." << zonename << "\t3600\tIN\tA\t" << singleIPTarget << endl;
}
ofzone.close();
apiWriteConfigFile(confbasename, "auth-zones+=" + zonename.toString() + "=" + zonefilename);
- } else if (kind == "FORWARDED") {
+ }
+ else if (kind == "FORWARDED") {
string serverlist;
for (auto value : document["servers"].array_items()) {
string server = value.string_value();
serverlist += ";";
}
serverlist += ca.toStringWithPort();
- } catch (const PDNSException &e) {
+ }
+ catch (const PDNSException& e) {
throw ApiException(e.reason);
}
}
if (rd) {
apiWriteConfigFile(confbasename, "forward-zones-recurse+=" + zonename.toString() + "=" + serverlist);
- } else {
+ }
+ else {
apiWriteConfigFile(confbasename, "forward-zones+=" + zonename.toString() + "=" + serverlist);
}
- } else {
+ }
+ else {
throw ApiException("invalid kind");
}
}
return;
}
- if(req->method != "GET")
+ if (req->method != "GET")
throw HttpMethodNotAllowedException();
Json::array doc;
- for(const SyncRes::domainmap_t::value_type& val : *SyncRes::t_sstorage.domainmap) {
+ for (const SyncRes::domainmap_t::value_type& val : *SyncRes::t_sstorage.domainmap) {
const SyncRes::AuthDomain& zone = val.second;
Json::array servers;
- for(const ComboAddress& server : zone.d_servers) {
+ for (const ComboAddress& server : zone.d_servers) {
servers.push_back(server.toStringWithPort());
}
// id is the canonical lookup key, which doesn't actually match the name (in some cases)
string zoneId = apiZoneNameToId(val.first);
- doc.push_back(Json::object {
- { "id", zoneId },
- { "url", "/api/v1/servers/localhost/zones/" + zoneId },
- { "name", val.first.toString() },
- { "kind", zone.d_servers.empty() ? "Native" : "Forwarded" },
- { "servers", servers },
- { "recursion_desired", zone.d_servers.empty() ? false : zone.d_rdForward }
- });
+ doc.push_back(Json::object{
+ {"id", zoneId},
+ {"url", "/api/v1/servers/localhost/zones/" + zoneId},
+ {"name", val.first.toString()},
+ {"kind", zone.d_servers.empty() ? "Native" : "Forwarded"},
+ {"servers", servers},
+ {"recursion_desired", zone.d_servers.empty() ? false : zone.d_rdForward}});
}
resp->setJsonBody(doc);
}
SyncRes::domainmap_t::const_iterator iter = SyncRes::t_sstorage.domainmap->find(zonename);
if (iter == SyncRes::t_sstorage.domainmap->end())
- throw ApiException("Could not find domain '"+zonename.toLogString()+"'");
+ throw ApiException("Could not find domain '" + zonename.toLogString() + "'");
- if(req->method == "PUT") {
+ if (req->method == "PUT") {
Json document = req->json();
doDeleteZone(zonename);
resp->body = "";
resp->status = 204; // No Content, but indicate success
}
- else if(req->method == "DELETE") {
+ else if (req->method == "DELETE") {
if (!doDeleteZone(zonename)) {
throw ApiException("Deleting domain failed");
}
// empty body on success
resp->body = "";
resp->status = 204; // No Content: declare that the zone is gone now
- } else if(req->method == "GET") {
+ }
+ else if (req->method == "GET") {
fillZone(zonename, resp);
- } else {
+ }
+ else {
throw HttpMethodNotAllowedException();
}
}
-static void apiServerSearchData(HttpRequest* req, HttpResponse* resp) {
- if(req->method != "GET")
+static void apiServerSearchData(HttpRequest* req, HttpResponse* resp)
+{
+ if (req->method != "GET")
throw HttpMethodNotAllowedException();
string q = req->getvars["q"];
throw ApiException("Query q can't be blank");
Json::array doc;
- for(const SyncRes::domainmap_t::value_type& val : *SyncRes::t_sstorage.domainmap) {
+ for (const SyncRes::domainmap_t::value_type& val : *SyncRes::t_sstorage.domainmap) {
string zoneId = apiZoneNameToId(val.first);
string zoneName = val.first.toString();
if (pdns_ci_find(zoneName, q) != string::npos) {
- doc.push_back(Json::object {
- { "type", "zone" },
- { "zone_id", zoneId },
- { "name", zoneName }
- });
+ doc.push_back(Json::object{
+ {"type", "zone"},
+ {"zone_id", zoneId},
+ {"name", zoneName}});
}
// if zone name is an exact match, don't bother with returning all records/comments in it
const SyncRes::AuthDomain& zone = val.second;
- for(const SyncRes::AuthDomain::records_t::value_type& rr : zone.d_records) {
+ for (const SyncRes::AuthDomain::records_t::value_type& rr : zone.d_records) {
if (pdns_ci_find(rr.d_name.toString(), q) == string::npos && pdns_ci_find(rr.d_content->getZoneRepresentation(), q) == string::npos)
continue;
- doc.push_back(Json::object {
- { "type", "record" },
- { "zone_id", zoneId },
- { "zone_name", zoneName },
- { "name", rr.d_name.toString() },
- { "content", rr.d_content->getZoneRepresentation() }
- });
+ doc.push_back(Json::object{
+ {"type", "record"},
+ {"zone_id", zoneId},
+ {"zone_name", zoneName},
+ {"name", rr.d_name.toString()},
+ {"content", rr.d_content->getZoneRepresentation()}});
}
}
resp->setJsonBody(doc);
}
-static void apiServerCacheFlush(HttpRequest* req, HttpResponse* resp) {
- if(req->method != "PUT")
+static void apiServerCacheFlush(HttpRequest* req, HttpResponse* resp)
+{
+ if (req->method != "PUT")
throw HttpMethodNotAllowedException();
DNSName canon = apiNameToDNSName(req->getvars["domain"]);
}
int count = g_recCache->doWipeCache(canon, subtree, qtype);
- count += broadcastAccFunction<uint64_t>([=]{return pleaseWipePacketCache(canon, subtree, qtype);});
+ count += broadcastAccFunction<uint64_t>([=] { return pleaseWipePacketCache(canon, subtree, qtype); });
count += g_negCache->wipe(canon, subtree);
- resp->setJsonBody(Json::object {
- { "count", count },
- { "result", "Flushed cache." }
- });
+ resp->setJsonBody(Json::object{
+ {"count", count},
+ {"result", "Flushed cache."}});
}
-static void apiServerRPZStats(HttpRequest* req, HttpResponse* resp) {
- if(req->method != "GET")
+static void apiServerRPZStats(HttpRequest* req, HttpResponse* resp)
+{
+ if (req->method != "GET")
throw HttpMethodNotAllowedException();
auto luaconf = g_luaconfs.getLocal();
Json::object ret;
- for (size_t i=0; i < numZones; i++) {
+ for (size_t i = 0; i < numZones; i++) {
auto zone = luaconf->dfe.getZone(i);
if (zone == nullptr)
continue;
resp->setJsonBody(ret);
}
+static void prometheusMetrics(HttpRequest* req, HttpResponse* resp)
+{
+ static MetricDefinitionStorage s_metricDefinitions;
-static void prometheusMetrics(HttpRequest *req, HttpResponse *resp) {
- static MetricDefinitionStorage s_metricDefinitions;
-
- if (req->method != "GET")
- throw HttpMethodNotAllowedException();
-
- registerAllStats();
-
- std::ostringstream output;
-
- // Argument controls disabling of any stats. So
- // stats-api-disabled-list will be used to block returned stats.
- auto varmap = getAllStatsMap(StatComponent::API);
- for (const auto& tup : varmap) {
- std::string metricName = tup.first;
- std::string prometheusMetricName = tup.second.d_prometheusName;
- std::string helpname = tup.second.d_prometheusName;
- MetricDefinition metricDetails;
-
- if (s_metricDefinitions.getMetricDetails(metricName, metricDetails)) {
- std::string prometheusTypeName = s_metricDefinitions.getPrometheusStringMetricType(
- metricDetails.d_prometheusType);
-
- if (prometheusTypeName.empty()) {
- continue;
- }
- if (metricDetails.d_prometheusType == PrometheusMetricType::multicounter) {
- helpname = prometheusMetricName.substr(0, prometheusMetricName.find('{'));
- }
- else if (metricDetails.d_prometheusType == PrometheusMetricType::histogram) {
- helpname = prometheusMetricName.substr(0, prometheusMetricName.find('{'));
- // name is XXX_count, strip the _count part
- helpname = helpname.substr(0, helpname.length() - 6);
- }
- output << "# TYPE " << helpname << " " << prometheusTypeName << "\n";
- output << "# HELP " << helpname << " " << metricDetails.d_description << "\n";
- }
- output << prometheusMetricName << " " << tup.second.d_value << "\n";
- }
+ if (req->method != "GET")
+ throw HttpMethodNotAllowedException();
- output << "# HELP pdns_recursor_info " << "Info from pdns_recursor, value is always 1" << "\n";
- output << "# TYPE pdns_recursor_info " << "gauge" << "\n";
- output << "pdns_recursor_info{version=\"" << VERSION << "\"} " << "1" << "\n";
+ registerAllStats();
- resp->body = output.str();
- resp->headers["Content-Type"] = "text/plain";
- resp->status = 200;
-}
+ std::ostringstream output;
+
+ // Argument controls disabling of any stats. So
+ // stats-api-disabled-list will be used to block returned stats.
+ auto varmap = getAllStatsMap(StatComponent::API);
+ for (const auto& tup : varmap) {
+ std::string metricName = tup.first;
+ std::string prometheusMetricName = tup.second.d_prometheusName;
+ std::string helpname = tup.second.d_prometheusName;
+ MetricDefinition metricDetails;
+
+ if (s_metricDefinitions.getMetricDetails(metricName, metricDetails)) {
+ std::string prometheusTypeName = s_metricDefinitions.getPrometheusStringMetricType(
+ metricDetails.d_prometheusType);
+
+ if (prometheusTypeName.empty()) {
+ continue;
+ }
+ if (metricDetails.d_prometheusType == PrometheusMetricType::multicounter) {
+ helpname = prometheusMetricName.substr(0, prometheusMetricName.find('{'));
+ }
+ else if (metricDetails.d_prometheusType == PrometheusMetricType::histogram) {
+ helpname = prometheusMetricName.substr(0, prometheusMetricName.find('{'));
+ // name is XXX_count, strip the _count part
+ helpname = helpname.substr(0, helpname.length() - 6);
+ }
+ output << "# TYPE " << helpname << " " << prometheusTypeName << "\n";
+ output << "# HELP " << helpname << " " << metricDetails.d_description << "\n";
+ }
+ output << prometheusMetricName << " " << tup.second.d_value << "\n";
+ }
+ output << "# HELP pdns_recursor_info "
+ << "Info from pdns_recursor, value is always 1"
+ << "\n";
+ output << "# TYPE pdns_recursor_info "
+ << "gauge"
+ << "\n";
+ output << "pdns_recursor_info{version=\"" << VERSION << "\"} "
+ << "1"
+ << "\n";
+
+ resp->body = output.str();
+ resp->headers["Content-Type"] = "text/plain";
+ resp->status = 200;
+}
#include "htmlfiles.h"
{
resp->headers["Cache-Control"] = "max-age=86400";
- if(req->url.path == "/")
+ if (req->url.path == "/")
req->url.path = "/index.html";
const string charset = "; charset=utf-8";
- if(boost::ends_with(req->url.path, ".html"))
+ if (boost::ends_with(req->url.path, ".html"))
resp->headers["Content-Type"] = "text/html" + charset;
- else if(boost::ends_with(req->url.path, ".css"))
+ else if (boost::ends_with(req->url.path, ".css"))
resp->headers["Content-Type"] = "text/css" + charset;
- else if(boost::ends_with(req->url.path,".js"))
+ else if (boost::ends_with(req->url.path, ".js"))
resp->headers["Content-Type"] = "application/javascript" + charset;
- else if(boost::ends_with(req->url.path, ".png"))
+ else if (boost::ends_with(req->url.path, ".png"))
resp->headers["Content-Type"] = "image/png";
resp->headers["X-Content-Type-Options"] = "nosniff";
resp->headers["X-XSS-Protection"] = "1; mode=block";
// resp->headers["Content-Security-Policy"] = "default-src 'self'; style-src 'self' 'unsafe-inline'";
- if (!req->url.path.empty() && g_urlmap.count(req->url.path.c_str()+1)) {
- resp->body = g_urlmap.at(req->url.path.c_str()+1);
+ if (!req->url.path.empty() && g_urlmap.count(req->url.path.c_str() + 1)) {
+ resp->body = g_urlmap.at(req->url.path.c_str() + 1);
resp->status = 200;
- } else {
+ }
+ else {
resp->status = 404;
}
}
MetricDefinition(PrometheusMetricType::counter,
"Stolen time, which is the time spent by the whole system in other operating systems when running in a virtualized environment, in units of USER_HZ")},
- { "dnssec-result-bogus-invalid-denial",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because a valid denial of existence proof could not be found")},
-
- { "dnssec-result-bogus-invalid-dnskey-protocol",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because all DNSKEYs had invalid protocols")},
-
- { "dnssec-result-bogus-missing-negative-indication",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because a NODATA or NXDOMAIN answer lacked the required SOA and/or NSEC(3) records")},
-
- { "dnssec-result-bogus-no-rrsig",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because required RRSIG records were not present in an answer")},
-
- { "dnssec-result-bogus-no-valid-dnskey",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because a valid DNSKEY could not be found")},
-
- { "dnssec-result-bogus-no-valid-rrsig",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because only invalid RRSIG records were present in an answer")},
-
- { "dnssec-result-bogus-no-zone-key-bit-set",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because no DNSKEY with the Zone Key bit set was found")},
-
- { "dnssec-result-bogus-revoked-dnskey",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because all DNSKEYs were revoked")},
-
- { "dnssec-result-bogus-self-signed-ds",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because a DS record was signed by itself")},
-
- { "dnssec-result-bogus-signature-expired",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because the signature expired time in the RRSIG was in the past")},
-
- { "dnssec-result-bogus-signature-not-yet-valid",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because the signature inception time in the RRSIG was not yet valid")},
-
- { "dnssec-result-bogus-unable-to-get-dnskeys",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because a valid DNSKEY could not be retrieved")},
-
- { "dnssec-result-bogus-unable-to-get-dss",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because a valid DS could not be retrieved")},
- { "dnssec-result-bogus-unsupported-dnskey-algo",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because a DNSKEY RRset contained only unsupported DNSSEC algorithms")},
-
- { "dnssec-result-bogus-unsupported-ds-digest-type",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because a DS RRset contained only unsupported digest types")},
- { "x-dnssec-result-bogus-invalid-denial",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because a valid denial of existence proof could not be found")},
-
- { "x-dnssec-result-bogus-invalid-dnskey-protocol",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because all DNSKEYs had invalid protocols")},
-
- { "x-dnssec-result-bogus-missing-negative-indication",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because a NODATA or NXDOMAIN answer lacked the required SOA and/or NSEC(3) records")},
-
- { "x-dnssec-result-bogus-no-rrsig",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because required RRSIG records were not present in an answer")},
-
- { "x-dnssec-result-bogus-no-valid-dnskey",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because a valid DNSKEY could not be found")},
-
- { "x-dnssec-result-bogus-no-valid-rrsig",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because only invalid RRSIG records were present in an answer")},
-
- { "x-dnssec-result-bogus-no-zone-key-bit-set",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because no DNSKEY with the Zone Key bit set was found")},
-
- { "x-dnssec-result-bogus-revoked-dnskey",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because all DNSKEYs were revoked")},
-
- { "x-dnssec-result-bogus-self-signed-ds",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because a DS record was signed by itself")},
-
- { "x-dnssec-result-bogus-signature-expired",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because the signature expired time in the RRSIG was in the past")},
-
- { "x-dnssec-result-bogus-signature-not-yet-valid",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because the signature inception time in the RRSIG was not yet valid")},
-
- { "x-dnssec-result-bogus-unable-to-get-dnskeys",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because a valid DNSKEY could not be retrieved")},
-
- { "x-dnssec-result-bogus-unable-to-get-dss",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because a valid DS could not be retrieved")},
- { "x-dnssec-result-bogus-unsupported-dnskey-algo",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because a DNSKEY RRset contained only unsupported DNSSEC algorithms")},
-
- { "x-dnssec-result-bogus-unsupported-ds-digest-type",
- MetricDefinition(PrometheusMetricType::counter,
- "number of DNSSEC validations that had the Bogus state because a DS RRset contained only unsupported digest types")},
-
- { "proxy-protocol-invalid",
- MetricDefinition(PrometheusMetricType::counter,
- "invalid proxy-protocol headers received")},
-
- { "record-cache-acquired",
- MetricDefinition(PrometheusMetricType::counter,
- "number of record cache lock acquisitions")},
-
- { "record-cache-contended",
- MetricDefinition(PrometheusMetricType::counter,
- "number of contented record cache lock acquisitions")},
-
- { "taskqueue-expired",
- MetricDefinition(PrometheusMetricType::counter,
- "number of tasks expired before they could be run")},
-
- { "taskqueue-pushed",
- MetricDefinition(PrometheusMetricType::counter,
- "number of tasks pushed to the taskqueues")},
-
- { "taskqueue-size",
- MetricDefinition(PrometheusMetricType::gauge,
- "number of tasks currently in the taskqueue")},
-
- { "dot-outqueries",
- MetricDefinition(PrometheusMetricType::counter,
- "Number of outgoing DoT queries since starting")},
-
- { "dns64-prefix-answers",
- MetricDefinition(PrometheusMetricType::counter,
- "Number of AAAA and PTR generated by a matching dns64-prefix")},
- { "aggressive-nsec-cache-entries",
- MetricDefinition(PrometheusMetricType::counter,
- "Number of entries in the aggressive NSEC cache")},
-
- { "aggressive-nsec-cache-nsec-hits",
- MetricDefinition(PrometheusMetricType::counter,
- "Number of NSEC-related hits from the aggressive NSEC cache")},
-
- { "aggressive-nsec-cache-nsec-wc-hits",
- MetricDefinition(PrometheusMetricType::counter,
- "Number of answers synthesized from the NSEC aggressive cache")},
-
- { "aggressive-nsec-cache-nsec3-hits",
- MetricDefinition(PrometheusMetricType::counter,
- "Number of NSEC3-related hits from the aggressive NSEC cache")},
-
- { "aggressive-nsec-cache-nsec3-wc-hits",
- MetricDefinition(PrometheusMetricType::counter,
- "Number of answers synthesized from the NSEC3 aggressive cache")},
+ {"dnssec-result-bogus-invalid-denial",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because a valid denial of existence proof could not be found")},
+
+ {"dnssec-result-bogus-invalid-dnskey-protocol",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because all DNSKEYs had invalid protocols")},
+
+ {"dnssec-result-bogus-missing-negative-indication",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because a NODATA or NXDOMAIN answer lacked the required SOA and/or NSEC(3) records")},
+
+ {"dnssec-result-bogus-no-rrsig",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because required RRSIG records were not present in an answer")},
+
+ {"dnssec-result-bogus-no-valid-dnskey",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because a valid DNSKEY could not be found")},
+
+ {"dnssec-result-bogus-no-valid-rrsig",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because only invalid RRSIG records were present in an answer")},
+
+ {"dnssec-result-bogus-no-zone-key-bit-set",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because no DNSKEY with the Zone Key bit set was found")},
+
+ {"dnssec-result-bogus-revoked-dnskey",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because all DNSKEYs were revoked")},
+
+ {"dnssec-result-bogus-self-signed-ds",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because a DS record was signed by itself")},
+
+ {"dnssec-result-bogus-signature-expired",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because the signature expired time in the RRSIG was in the past")},
+
+ {"dnssec-result-bogus-signature-not-yet-valid",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because the signature inception time in the RRSIG was not yet valid")},
+
+ {"dnssec-result-bogus-unable-to-get-dnskeys",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because a valid DNSKEY could not be retrieved")},
+
+ {"dnssec-result-bogus-unable-to-get-dss",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because a valid DS could not be retrieved")},
+ {"dnssec-result-bogus-unsupported-dnskey-algo",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because a DNSKEY RRset contained only unsupported DNSSEC algorithms")},
+
+ {"dnssec-result-bogus-unsupported-ds-digest-type",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because a DS RRset contained only unsupported digest types")},
+ {"x-dnssec-result-bogus-invalid-denial",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because a valid denial of existence proof could not be found")},
+
+ {"x-dnssec-result-bogus-invalid-dnskey-protocol",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because all DNSKEYs had invalid protocols")},
+
+ {"x-dnssec-result-bogus-missing-negative-indication",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because a NODATA or NXDOMAIN answer lacked the required SOA and/or NSEC(3) records")},
+
+ {"x-dnssec-result-bogus-no-rrsig",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because required RRSIG records were not present in an answer")},
+
+ {"x-dnssec-result-bogus-no-valid-dnskey",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because a valid DNSKEY could not be found")},
+
+ {"x-dnssec-result-bogus-no-valid-rrsig",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because only invalid RRSIG records were present in an answer")},
+
+ {"x-dnssec-result-bogus-no-zone-key-bit-set",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because no DNSKEY with the Zone Key bit set was found")},
+
+ {"x-dnssec-result-bogus-revoked-dnskey",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because all DNSKEYs were revoked")},
+
+ {"x-dnssec-result-bogus-self-signed-ds",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because a DS record was signed by itself")},
+
+ {"x-dnssec-result-bogus-signature-expired",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because the signature expired time in the RRSIG was in the past")},
+
+ {"x-dnssec-result-bogus-signature-not-yet-valid",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because the signature inception time in the RRSIG was not yet valid")},
+
+ {"x-dnssec-result-bogus-unable-to-get-dnskeys",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because a valid DNSKEY could not be retrieved")},
+
+ {"x-dnssec-result-bogus-unable-to-get-dss",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because a valid DS could not be retrieved")},
+ {"x-dnssec-result-bogus-unsupported-dnskey-algo",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because a DNSKEY RRset contained only unsupported DNSSEC algorithms")},
+
+ {"x-dnssec-result-bogus-unsupported-ds-digest-type",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of DNSSEC validations that had the Bogus state because a DS RRset contained only unsupported digest types")},
+
+ {"proxy-protocol-invalid",
+ MetricDefinition(PrometheusMetricType::counter,
+ "invalid proxy-protocol headers received")},
+
+ {"record-cache-acquired",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of record cache lock acquisitions")},
+
+ {"record-cache-contended",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of contented record cache lock acquisitions")},
+
+ {"taskqueue-expired",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of tasks expired before they could be run")},
+
+ {"taskqueue-pushed",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of tasks pushed to the taskqueues")},
+
+ {"taskqueue-size",
+ MetricDefinition(PrometheusMetricType::gauge,
+ "number of tasks currently in the taskqueue")},
+
+ {"dot-outqueries",
+ MetricDefinition(PrometheusMetricType::counter,
+ "Number of outgoing DoT queries since starting")},
+
+ {"dns64-prefix-answers",
+ MetricDefinition(PrometheusMetricType::counter,
+ "Number of AAAA and PTR generated by a matching dns64-prefix")},
+ {"aggressive-nsec-cache-entries",
+ MetricDefinition(PrometheusMetricType::counter,
+ "Number of entries in the aggressive NSEC cache")},
+
+ {"aggressive-nsec-cache-nsec-hits",
+ MetricDefinition(PrometheusMetricType::counter,
+ "Number of NSEC-related hits from the aggressive NSEC cache")},
+
+ {"aggressive-nsec-cache-nsec-wc-hits",
+ MetricDefinition(PrometheusMetricType::counter,
+ "Number of answers synthesized from the NSEC aggressive cache")},
+
+ {"aggressive-nsec-cache-nsec3-hits",
+ MetricDefinition(PrometheusMetricType::counter,
+ "Number of NSEC3-related hits from the aggressive NSEC cache")},
+
+ {"aggressive-nsec-cache-nsec3-wc-hits",
+ MetricDefinition(PrometheusMetricType::counter,
+ "Number of answers synthesized from the NSEC3 aggressive cache")},
// For cumulative histogram, state the xxx_count name where xxx matches the name in rec_channel_rec
- { "cumul-clientanswers-count",
- MetricDefinition(PrometheusMetricType::histogram,
- "histogram of our answer times to clients")},
+ {"cumul-clientanswers-count",
+ MetricDefinition(PrometheusMetricType::histogram,
+ "histogram of our answer times to clients")},
// For cumulative histogram, state the xxx_count name where xxx matches the name in rec_channel_rec
- { "cumul-authanswers-count4",
- MetricDefinition(PrometheusMetricType::histogram,
- "histogram of answer times of authoritative servers")},
- { "almost-expired-pushed",
- MetricDefinition(PrometheusMetricType::counter,
- "number of almost-expired tasks pushed")},
+ {"cumul-authanswers-count4",
+ MetricDefinition(PrometheusMetricType::histogram,
+ "histogram of answer times of authoritative servers")},
+ {"almost-expired-pushed",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of almost-expired tasks pushed")},
- { "almost-expired-run",
- MetricDefinition(PrometheusMetricType::counter,
- "number of almost-expired tasks run to completion")},
+ {"almost-expired-run",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of almost-expired tasks run to completion")},
- { "almost-expired-exceptions",
- MetricDefinition(PrometheusMetricType::counter,
- "number of almost-expired tasks that caused an exception")},
+ {"almost-expired-exceptions",
+ MetricDefinition(PrometheusMetricType::counter,
+ "number of almost-expired tasks that caused an exception")},
// For multicounters, state the first
- { "policy-hits",
- MetricDefinition(PrometheusMetricType::multicounter,
- "Number of filter or RPZ policy hits")},
+ {"policy-hits",
+ MetricDefinition(PrometheusMetricType::multicounter,
+ "Number of filter or RPZ policy hits")},
- { "idle-tcpout-connections",
- MetricDefinition(PrometheusMetricType::gauge,
- "Number of connections in the TCP idle outgoing connections pool")},
+ {"idle-tcpout-connections",
+ MetricDefinition(PrometheusMetricType::gauge,
+ "Number of connections in the TCP idle outgoing connections pool")},
};
MetricDefinition metricDetails;
if (!s_metricDefinitions.getMetricDetails(metricName, metricDetails)) {
- g_log<<Logger::Debug << "{ \"" << metricName << "\", MetricDefinition(PrometheusMetricType::counter, \"\")}," << endl;
+ g_log << Logger::Debug << "{ \"" << metricName << "\", MetricDefinition(PrometheusMetricType::counter, \"\")}," << endl;
}
}
}
d_ws->bind();
// legacy dispatch
- d_ws->registerApiHandler("/jsonstat", [this](HttpRequest* req, HttpResponse* resp){jsonstat(req, resp);}, true);
+ d_ws->registerApiHandler(
+ "/jsonstat", [this](HttpRequest* req, HttpResponse* resp) { jsonstat(req, resp); }, true);
d_ws->registerApiHandler("/api/v1/servers/localhost/cache/flush", &apiServerCacheFlush);
d_ws->registerApiHandler("/api/v1/servers/localhost/config/allow-from", &apiServerConfigAllowFrom);
d_ws->registerApiHandler("/api/v1/servers/localhost/config", &apiServerConfig);
d_ws->registerApiHandler("/api", &apiDiscovery);
for (const auto& u : g_urlmap) {
- d_ws->registerWebHandler("/"+u.first, serveStuff);
+ d_ws->registerWebHandler("/" + u.first, serveStuff);
}
d_ws->registerWebHandler("/", serveStuff);
d_ws->go();
}
-void RecursorWebServer::jsonstat(HttpRequest* req, HttpResponse *resp)
+void RecursorWebServer::jsonstat(HttpRequest* req, HttpResponse* resp)
{
string command;
- if(req->getvars.count("command")) {
+ if (req->getvars.count("command")) {
command = req->getvars["command"];
req->getvars.erase("command");
}
map<string, string> stats;
- if(command == "get-query-ring") {
- typedef pair<DNSName,uint16_t> query_t;
+ if (command == "get-query-ring") {
+ typedef pair<DNSName, uint16_t> query_t;
vector<query_t> queries;
- bool filter=!req->getvars["public-filtered"].empty();
+ bool filter = !req->getvars["public-filtered"].empty();
- if(req->getvars["name"]=="servfail-queries")
- queries=broadcastAccFunction<vector<query_t> >(pleaseGetServfailQueryRing);
- else if(req->getvars["name"]=="bogus-queries")
- queries=broadcastAccFunction<vector<query_t> >(pleaseGetBogusQueryRing);
- else if(req->getvars["name"]=="queries")
- queries=broadcastAccFunction<vector<query_t> >(pleaseGetQueryRing);
+ if (req->getvars["name"] == "servfail-queries")
+ queries = broadcastAccFunction<vector<query_t>>(pleaseGetServfailQueryRing);
+ else if (req->getvars["name"] == "bogus-queries")
+ queries = broadcastAccFunction<vector<query_t>>(pleaseGetBogusQueryRing);
+ else if (req->getvars["name"] == "queries")
+ queries = broadcastAccFunction<vector<query_t>>(pleaseGetQueryRing);
- typedef map<query_t,unsigned int> counts_t;
+ typedef map<query_t, unsigned int> counts_t;
counts_t counts;
- unsigned int total=0;
- for(const query_t& q : queries) {
+ unsigned int total = 0;
+ for (const query_t& q : queries) {
total++;
- if(filter)
- counts[pair(getRegisteredName(q.first), q.second)]++;
+ if (filter)
+ counts[pair(getRegisteredName(q.first), q.second)]++;
else
- counts[pair(q.first, q.second)]++;
+ counts[pair(q.first, q.second)]++;
}
typedef std::multimap<int, query_t> rcounts_t;
rcounts_t rcounts;
- for(counts_t::const_iterator i=counts.begin(); i != counts.end(); ++i)
+ for (counts_t::const_iterator i = counts.begin(); i != counts.end(); ++i)
rcounts.emplace(-i->second, i->first);
Json::array entries;
- unsigned int tot=0, totIncluded=0;
- for(const rcounts_t::value_type& q : rcounts) {
- totIncluded-=q.first;
- entries.push_back(Json::array {
- -q.first, q.second.first.toLogString(), DNSRecordContent::NumberToType(q.second.second)
- });
- if(tot++>=100)
- break;
+ unsigned int tot = 0, totIncluded = 0;
+ for (const rcounts_t::value_type& q : rcounts) {
+ totIncluded -= q.first;
+ entries.push_back(Json::array{
+ -q.first, q.second.first.toLogString(), DNSRecordContent::NumberToType(q.second.second)});
+ if (tot++ >= 100)
+ break;
}
- if(queries.size() != totIncluded) {
- entries.push_back(Json::array {
- (int)(queries.size() - totIncluded), "", ""
- });
+ if (queries.size() != totIncluded) {
+ entries.push_back(Json::array{
+ (int)(queries.size() - totIncluded), "", ""});
}
- resp->setJsonBody(Json::object { { "entries", entries } });
+ resp->setJsonBody(Json::object{{"entries", entries}});
return;
}
- else if(command == "get-remote-ring") {
+ else if (command == "get-remote-ring") {
vector<ComboAddress> queries;
- if(req->getvars["name"]=="remotes")
- queries=broadcastAccFunction<vector<ComboAddress> >(pleaseGetRemotes);
- else if(req->getvars["name"]=="servfail-remotes")
- queries=broadcastAccFunction<vector<ComboAddress> >(pleaseGetServfailRemotes);
- else if(req->getvars["name"]=="bogus-remotes")
- queries=broadcastAccFunction<vector<ComboAddress> >(pleaseGetBogusRemotes);
- else if(req->getvars["name"]=="large-answer-remotes")
- queries=broadcastAccFunction<vector<ComboAddress> >(pleaseGetLargeAnswerRemotes);
- else if(req->getvars["name"]=="timeouts")
- queries=broadcastAccFunction<vector<ComboAddress> >(pleaseGetTimeouts);
-
- typedef map<ComboAddress,unsigned int,ComboAddress::addressOnlyLessThan> counts_t;
+ if (req->getvars["name"] == "remotes")
+ queries = broadcastAccFunction<vector<ComboAddress>>(pleaseGetRemotes);
+ else if (req->getvars["name"] == "servfail-remotes")
+ queries = broadcastAccFunction<vector<ComboAddress>>(pleaseGetServfailRemotes);
+ else if (req->getvars["name"] == "bogus-remotes")
+ queries = broadcastAccFunction<vector<ComboAddress>>(pleaseGetBogusRemotes);
+ else if (req->getvars["name"] == "large-answer-remotes")
+ queries = broadcastAccFunction<vector<ComboAddress>>(pleaseGetLargeAnswerRemotes);
+ else if (req->getvars["name"] == "timeouts")
+ queries = broadcastAccFunction<vector<ComboAddress>>(pleaseGetTimeouts);
+
+ typedef map<ComboAddress, unsigned int, ComboAddress::addressOnlyLessThan> counts_t;
counts_t counts;
- unsigned int total=0;
- for(const ComboAddress& q : queries) {
+ unsigned int total = 0;
+ for (const ComboAddress& q : queries) {
total++;
counts[q]++;
}
typedef std::multimap<int, ComboAddress> rcounts_t;
rcounts_t rcounts;
- for(counts_t::const_iterator i=counts.begin(); i != counts.end(); ++i)
+ for (counts_t::const_iterator i = counts.begin(); i != counts.end(); ++i)
rcounts.emplace(-i->second, i->first);
Json::array entries;
- unsigned int tot=0, totIncluded=0;
- for(const rcounts_t::value_type& q : rcounts) {
- totIncluded-=q.first;
- entries.push_back(Json::array {
- -q.first, q.second.toString()
- });
- if(tot++>=100)
- break;
+ unsigned int tot = 0, totIncluded = 0;
+ for (const rcounts_t::value_type& q : rcounts) {
+ totIncluded -= q.first;
+ entries.push_back(Json::array{
+ -q.first, q.second.toString()});
+ if (tot++ >= 100)
+ break;
}
- if(queries.size() != totIncluded) {
- entries.push_back(Json::array {
- (int)(queries.size() - totIncluded), ""
- });
+ if (queries.size() != totIncluded) {
+ entries.push_back(Json::array{
+ (int)(queries.size() - totIncluded), ""});
}
- resp->setJsonBody(Json::object { { "entries", entries } });
+ resp->setJsonBody(Json::object{{"entries", entries}});
return;
- } else {
- resp->setErrorResult("Command '"+command+"' not found", 404);
+ }
+ else {
+ resp->setErrorResult("Command '" + command + "' not found", 404);
}
}
+void AsyncServerNewConnectionMT(void* p)
+{
+ AsyncServer* server = (AsyncServer*)p;
-void AsyncServerNewConnectionMT(void *p) {
- AsyncServer *server = (AsyncServer*)p;
-
try {
auto socket = server->accept(); // this is actually a shared_ptr
if (socket) {
server->d_asyncNewConnectionCallback(socket);
}
- } catch (NetworkError &e) {
+ }
+ catch (NetworkError& e) {
// we're running in a shared process/thread, so can't just terminate/abort.
- g_log<<Logger::Warning<<"Network error in web thread: "<<e.what()<<endl;
+ g_log << Logger::Warning << "Network error in web thread: " << e.what() << endl;
return;
}
catch (...) {
- g_log<<Logger::Warning<<"Unknown error in web thread"<<endl;
+ g_log << Logger::Warning << "Unknown error in web thread" << endl;
return;
}
-
}
void AsyncServer::asyncWaitForConnections(FDMultiplexer* fdm, const newconnectioncb_t& callback)
{
d_asyncNewConnectionCallback = callback;
- fdm->addReadFD(d_server_socket.getHandle(), [this] (int, boost::any&){ newConnection();});
+ fdm->addReadFD(d_server_socket.getHandle(), [this](int, boost::any&) { newConnection(); });
}
void AsyncServer::newConnection()
}
// This is an entry point from FDM, so it needs to catch everything.
-void AsyncWebServer::serveConnection(std::shared_ptr<Socket> client) const {
+void AsyncWebServer::serveConnection(std::shared_ptr<Socket> client) const
+{
if (!client->acl(d_acl)) {
return;
}
yarl.initialize(&req);
client->setNonBlocking();
- const struct timeval timeout{g_networkTimeoutMsec / 1000, static_cast<suseconds_t>(g_networkTimeoutMsec) % 1000 * 1000};
+ const struct timeval timeout
+ {
+ g_networkTimeoutMsec / 1000, static_cast<suseconds_t>(g_networkTimeoutMsec) % 1000 * 1000
+ };
std::shared_ptr<TLSCtx> tlsCtx{nullptr};
auto handler = std::make_shared<TCPIOHandler>("", client->releaseHandle(), timeout, tlsCtx, time(nullptr));
PacketBuffer data;
try {
- while(!req.complete) {
+ while (!req.complete) {
auto ret = arecvtcp(data, 16384, handler, true);
if (ret == LWResult::Result::Success) {
string str(reinterpret_cast<const char*>(data.data()), data.size());
req.complete = yarl.feed(str);
- } else {
+ }
+ else {
// read error OR EOF
break;
}
}
yarl.finalize();
- } catch (YaHTTP::ParseError &e) {
+ }
+ catch (YaHTTP::ParseError& e) {
// request stays incomplete
- g_log<<Logger::Warning<<logprefix<<"Unable to parse request: "<<e.what()<<endl;
+ g_log << Logger::Warning << logprefix << "Unable to parse request: " << e.what() << endl;
}
if (d_loglevel >= WebServer::LogLevel::None) {
WebServer::handleRequest(req, resp);
ostringstream ss;
resp.write(ss);
- const string &s = ss.str();
+ const string& s = ss.str();
reply.insert(reply.end(), s.cbegin(), s.cend());
logResponse(resp, remote, logprefix);
// now send the reply
if (asendtcp(reply, handler) != LWResult::Result::Success || reply.empty()) {
- g_log<<Logger::Error<<logprefix<<"Failed sending reply to HTTP client"<<endl;
+ g_log << Logger::Error << logprefix << "Failed sending reply to HTTP client" << endl;
}
handler->close(); // needed to signal "done" to client
}
- catch(PDNSException &e) {
- g_log<<Logger::Error<<logprefix<<"Exception: "<<e.reason<<endl;
+ catch (PDNSException& e) {
+ g_log << Logger::Error << logprefix << "Exception: " << e.reason << endl;
}
- catch(std::exception &e) {
- if(strstr(e.what(), "timeout")==0)
- g_log<<Logger::Error<<logprefix<<"STL Exception: "<<e.what()<<endl;
+ catch (std::exception& e) {
+ if (strstr(e.what(), "timeout") == 0)
+ g_log << Logger::Error << logprefix << "STL Exception: " << e.what() << endl;
}
- catch(...) {
- g_log<<Logger::Error<<logprefix<<"Unknown exception"<<endl;
+ catch (...) {
+ g_log << Logger::Error << logprefix << "Unknown exception" << endl;
}
if (d_loglevel >= WebServer::LogLevel::Normal) {
- g_log<<Logger::Notice<<logprefix<<remote<<" \""<<req.method<<" "<<req.url.path<<" HTTP/"<<req.versionStr(req.version)<<"\" "<<resp.status<<" "<<reply.size()<<endl;
+ g_log << Logger::Notice << logprefix << remote << " \"" << req.method << " " << req.url.path << " HTTP/" << req.versionStr(req.version) << "\" " << resp.status << " " << reply.size() << endl;
}
}
-void AsyncWebServer::go() {
+void AsyncWebServer::go()
+{
if (!d_server)
return;
auto server = std::dynamic_pointer_cast<AsyncServer>(d_server);
if (!server)
return;
- server->asyncWaitForConnections(d_fdm, [this](const std::shared_ptr<Socket>& c){serveConnection(c);});
+ server->asyncWaitForConnections(d_fdm, [this](const std::shared_ptr<Socket>& c) { serveConnection(c); });
}
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#pragma once
-#include <boost/utility.hpp>
+#include <boost/utility.hpp>
#include "namespaces.hh"
#include "mplexer.hh"
#include "webserver.hh"
class HttpRequest;
class HttpResponse;
-class AsyncServer : public Server {
+class AsyncServer : public Server
+{
public:
- AsyncServer(const string &localaddress, int port) : Server(localaddress, port)
+ AsyncServer(const string& localaddress, int port) :
+ Server(localaddress, port)
{
d_server_socket.setNonBlocking();
};
- friend void AsyncServerNewConnectionMT(void *p);
+ friend void AsyncServerNewConnectionMT(void* p);
- typedef boost::function< void(std::shared_ptr<Socket>) > newconnectioncb_t;
+ typedef boost::function<void(std::shared_ptr<Socket>)> newconnectioncb_t;
void asyncWaitForConnections(FDMultiplexer* fdm, const newconnectioncb_t& callback);
private:
class AsyncWebServer : public WebServer
{
public:
- AsyncWebServer(FDMultiplexer* fdm, const string &listenaddress, int port) :
- WebServer(listenaddress, port), d_fdm(fdm) { };
+ AsyncWebServer(FDMultiplexer* fdm, const string& listenaddress, int port) :
+ WebServer(listenaddress, port), d_fdm(fdm){};
void go();
private:
void serveConnection(std::shared_ptr<Socket> socket) const;
protected:
- virtual std::shared_ptr<Server> createServer() override {
+ virtual std::shared_ptr<Server> createServer() override
+ {
return std::make_shared<AsyncServer>(d_listenaddress, d_port);
};
};
{
public:
explicit RecursorWebServer(FDMultiplexer* fdm);
- void jsonstat(HttpRequest* req, HttpResponse *resp);
+ void jsonstat(HttpRequest* req, HttpResponse* resp);
private:
std::unique_ptr<AsyncWebServer> d_ws{nullptr};