]> git.ipfire.org Git - thirdparty/pdns.git/commitdiff
dnsdist: Delint dnsdist-lua.cc and dnsdist-snmp.cc
authorRemi Gacogne <remi.gacogne@powerdns.com>
Tue, 5 Mar 2024 09:47:49 +0000 (10:47 +0100)
committerRemi Gacogne <remi.gacogne@powerdns.com>
Wed, 6 Mar 2024 11:10:05 +0000 (12:10 +0100)
pdns/dnsdistdist/dnsdist-lua.cc
pdns/dnsdistdist/dnsdist-snmp.cc
pdns/dnsdistdist/dnsdist.hh
pdns/dnsdistdist/test-dnsdistlbpolicies_cc.cc

index 73a8567b241aa09ab1d6b2f886751e1e0441590c..55075c8efcd55a54459a880d1d59cf2d68b9b3a2 100644 (file)
@@ -90,8 +90,10 @@ static bool g_included{false};
    has done so before on this invocation, this call won't be part of delta() output */
 void setLuaNoSideEffect()
 {
-  if (g_noLuaSideEffect == false) // there has been a side effect already
+  if (g_noLuaSideEffect == false) {
+    // there has been a side effect already
     return;
+  }
   g_noLuaSideEffect = true;
 }
 
@@ -103,6 +105,7 @@ void setLuaSideEffect()
 bool getLuaNoSideEffect()
 {
   if (g_noLuaSideEffect) {
+    // NOLINTNEXTLINE(readability-simplify-boolean-expr): it's a tribool, not a boolean
     return true;
   }
   return false;
@@ -257,7 +260,7 @@ void checkParameterBound(const std::string& parameter, uint64_t value, size_t ma
 static void LuaThread(const std::string& code)
 {
   setThreadName("dnsdist/lua-bg");
-  LuaContext l;
+  LuaContext context;
 
   // mask SIGTERM on threads so the signal always comes to dnsdist itself
   sigset_t blockSignals;
@@ -269,7 +272,7 @@ static void LuaThread(const std::string& code)
 
   // submitToMainThread is camelcased, threadmessage is not.
   // This follows our tradition of hooks we call being lowercased but functions the user can call being camelcased.
-  l.writeFunction("submitToMainThread", [](std::string cmd, LuaAssociativeTable<std::string> data) {
+  context.writeFunction("submitToMainThread", [](std::string cmd, LuaAssociativeTable<std::string> data) {
     auto lua = g_lua.lock();
     // maybe offer more than `void`
     auto func = lua->readVariable<boost::optional<std::function<void(std::string cmd, LuaAssociativeTable<std::string> data)>>>("threadmessage");
@@ -285,7 +288,7 @@ static void LuaThread(const std::string& code)
 
   for (;;) {
     try {
-      l.executeCode(code);
+      context.executeCode(code);
       errlog("Lua thread exited, restarting in 5 seconds");
     }
     catch (const std::exception& e) {
@@ -294,7 +297,7 @@ static void LuaThread(const std::string& code)
     catch (...) {
       errlog("Lua thread crashed, restarting in 5 seconds");
     }
-    sleep(5);
+    std::this_thread::sleep_for(std::chrono::seconds(5));
   }
 }
 
@@ -400,7 +403,56 @@ static void handleNewServerHealthCheckParameters(boost::optional<newserver_t>& v
   getOptionalIntegerValue("newServer", vars, "rise", config.minRiseSuccesses);
 }
 
-// NOLINTNEXTLINE(readability-function-cognitive-complexity): this function declares Lua bindings, even with a good refactoring it will likely blow up the threshold
+static void handleNewServerSourceParameter(boost::optional<newserver_t>& vars, DownstreamState::Config& config)
+{
+  std::string source;
+  if (getOptionalValue<std::string>(vars, "source", source) > 0) {
+    /* handle source in the following forms:
+       - v4 address ("192.0.2.1")
+       - v6 address ("2001:DB8::1")
+       - interface name ("eth0")
+                              - v4 address and interface name ("192.0.2.1@eth0")
+                              - v6 address and interface name ("2001:DB8::1@eth0")
+    */
+    bool parsed = false;
+    std::string::size_type pos = source.find('@');
+    if (pos == std::string::npos) {
+      /* no '@', try to parse that as a valid v4/v6 address */
+      try {
+        config.sourceAddr = ComboAddress(source);
+        parsed = true;
+      }
+      catch (...) {
+      }
+    }
+
+    if (!parsed) {
+      /* try to parse as interface name, or v4/v6@itf */
+      config.sourceItfName = source.substr(pos == std::string::npos ? 0 : pos + 1);
+      unsigned int itfIdx = if_nametoindex(config.sourceItfName.c_str());
+      if (itfIdx != 0) {
+        if (pos == 0 || pos == std::string::npos) {
+          /* "eth0" or "@eth0" */
+          config.sourceItf = itfIdx;
+        }
+        else {
+          /* "192.0.2.1@eth0" */
+          config.sourceAddr = ComboAddress(source.substr(0, pos));
+          config.sourceItf = itfIdx;
+        }
+#ifdef SO_BINDTODEVICE
+        /* we need to retain CAP_NET_RAW to be able to set SO_BINDTODEVICE in the health checks */
+        g_capabilitiesToRetain.insert("CAP_NET_RAW");
+#endif
+      }
+      else {
+        warnlog("Dismissing source %s because '%s' is not a valid interface name", source, config.sourceItfName);
+      }
+    }
+  }
+}
+
+// NOLINTNEXTLINE(readability-function-cognitive-complexity,readability-function-size): this function declares Lua bindings, even with a good refactoring it will likely blow up the threshold
 static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
 {
   luaCtx.writeFunction("inClientStartup", [client]() {
@@ -419,7 +471,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
                          DownstreamState::Config config;
 
                          std::string serverAddressStr;
-                         if (auto addrStr = boost::get<string>(&pvars)) {
+                         if (auto* addrStr = boost::get<string>(&pvars)) {
                            serverAddressStr = *addrStr;
                            if (qps) {
                              (*vars)["qps"] = std::to_string(*qps);
@@ -430,51 +482,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
                            getOptionalValue<std::string>(vars, "address", serverAddressStr);
                          }
 
-                         std::string source;
-                         if (getOptionalValue<std::string>(vars, "source", source) > 0) {
-                           /* handle source in the following forms:
-                              - v4 address ("192.0.2.1")
-                              - v6 address ("2001:DB8::1")
-                              - interface name ("eth0")
-                              - v4 address and interface name ("192.0.2.1@eth0")
-                              - v6 address and interface name ("2001:DB8::1@eth0")
-                           */
-                           bool parsed = false;
-                           std::string::size_type pos = source.find("@");
-                           if (pos == std::string::npos) {
-                             /* no '@', try to parse that as a valid v4/v6 address */
-                             try {
-                               config.sourceAddr = ComboAddress(source);
-                               parsed = true;
-                             }
-                             catch (...) {
-                             }
-                           }
-
-                           if (parsed == false) {
-                             /* try to parse as interface name, or v4/v6@itf */
-                             config.sourceItfName = source.substr(pos == std::string::npos ? 0 : pos + 1);
-                             unsigned int itfIdx = if_nametoindex(config.sourceItfName.c_str());
-                             if (itfIdx != 0) {
-                               if (pos == 0 || pos == std::string::npos) {
-                                 /* "eth0" or "@eth0" */
-                                 config.sourceItf = itfIdx;
-                               }
-                               else {
-                                 /* "192.0.2.1@eth0" */
-                                 config.sourceAddr = ComboAddress(source.substr(0, pos));
-                                 config.sourceItf = itfIdx;
-                               }
-#ifdef SO_BINDTODEVICE
-                               /* we need to retain CAP_NET_RAW to be able to set SO_BINDTODEVICE in the health checks */
-                               g_capabilitiesToRetain.insert("CAP_NET_RAW");
-#endif
-                             }
-                             else {
-                               warnlog("Dismissing source %s because '%s' is not a valid interface name", source, config.sourceItfName);
-                             }
-                           }
-                         }
+                         handleNewServerSourceParameter(vars, config);
 
                          std::string valueStr;
                          if (getOptionalValue<std::string>(vars, "sockets", valueStr) > 0) {
@@ -551,11 +559,11 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
 
                          if (getOptionalValue<std::string>(vars, "subjectAddr", valueStr) > 0) {
                            try {
-                             ComboAddress ca(valueStr);
-                             config.d_tlsSubjectName = ca.toString();
+                             ComboAddress addr(valueStr);
+                             config.d_tlsSubjectName = addr.toString();
                              config.d_tlsSubjectIsAddr = true;
                            }
-                           catch (const std::exception& e) {
+                           catch (const std::exception&) {
                              errlog("Error creating new server: downstream subjectAddr value must be a valid IP address");
                              return std::shared_ptr<DownstreamState>();
                            }
@@ -605,8 +613,8 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
                            config.pools.insert(valueStr);
                          }
                          else if (getOptionalValue<decltype(pools)>(vars, "pool", pools) > 0) {
-                           for (auto& p : pools) {
-                             config.pools.insert(p.second);
+                           for (auto& pool : pools) {
+                             config.pools.insert(pool.second);
                            }
                          }
 
@@ -653,7 +661,8 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
                            ret->registerXsk(xskSockets);
                            std::string mac;
                            if (getOptionalValue<std::string>(vars, "MACAddr", mac) > 0) {
-                             auto* addr = &ret->d_config.destMACAddr[0];
+                             auto* addr = ret->d_config.destMACAddr.data();
+                             // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
                              sscanf(mac.c_str(), "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", addr, addr + 1, addr + 2, addr + 3, addr + 4, addr + 5);
                            }
                            else {
@@ -703,8 +712,8 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
 
                          auto states = g_dstates.getCopy();
                          states.push_back(ret);
-                         std::stable_sort(states.begin(), states.end(), [](const decltype(ret)& a, const decltype(ret)& b) {
-                           return a->d_config.order < b->d_config.order;
+                         std::stable_sort(states.begin(), states.end(), [](const decltype(ret)& lhs, const decltype(ret)& rhs) {
+                           return lhs->d_config.order < rhs->d_config.order;
                          });
                          g_dstates.setState(states);
                          checkAllParametersConsumed("newServer", vars);
@@ -719,7 +728,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
                          if (auto* rem = boost::get<shared_ptr<DownstreamState>>(&var)) {
                            server = *rem;
                          }
-                         else if (auto str = boost::get<std::string>(&var)) {
+                         else if (auto* str = boost::get<std::string>(&var)) {
                            const auto uuid = getUniqueID(*str);
                            for (auto& state : states) {
                              if (*state->d_config.id == uuid) {
@@ -746,8 +755,8 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
                          server->stop();
                        });
 
-  luaCtx.writeFunction("truncateTC", [](bool tc) { setLuaSideEffect(); g_truncateTC=tc; });
-  luaCtx.writeFunction("fixupCase", [](bool fu) { setLuaSideEffect(); g_fixupCase=fu; });
+  luaCtx.writeFunction("truncateTC", [](bool value) { setLuaSideEffect(); g_truncateTC = value; });
+  luaCtx.writeFunction("fixupCase", [](bool value) { setLuaSideEffect(); g_fixupCase = value; });
 
   luaCtx.writeFunction("addACL", [](const std::string& domain) {
     setLuaSideEffect();
@@ -828,8 +837,9 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
 
   luaCtx.writeFunction("addLocal", [client](const std::string& addr, boost::optional<localbind_t> vars) {
     setLuaSideEffect();
-    if (client)
+    if (client) {
       return;
+    }
 
     if (!checkConfigurationTime("addLocal")) {
       return;
@@ -884,13 +894,14 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
   luaCtx.writeFunction("setACL", [](LuaTypeOrArrayOf<std::string> inp) {
     setLuaSideEffect();
     NetmaskGroup nmg;
-    if (auto str = boost::get<string>(&inp)) {
+    if (auto* str = boost::get<string>(&inp)) {
       nmg.addMask(*str);
     }
-    else
-      for (const auto& p : boost::get<LuaArray<std::string>>(inp)) {
-        nmg.addMask(p.second);
+    else {
+      for (const auto& entry : boost::get<LuaArray<std::string>>(inp)) {
+        nmg.addMask(entry.second);
       }
+    }
     g_ACL.setState(nmg);
   });
 
@@ -903,15 +914,17 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
       throw std::runtime_error("Could not open '" + file + "': " + stringerror());
     }
 
-    string::size_type pos;
+    string::size_type pos = 0;
     string line;
     while (getline(ifs, line)) {
       pos = line.find('#');
-      if (pos != string::npos)
+      if (pos != string::npos) {
         line.resize(pos);
+      }
       boost::trim(line);
-      if (line.empty())
+      if (line.empty()) {
         continue;
+      }
 
       nmg.addMask(line);
     }
@@ -968,29 +981,31 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
         ret << (fmt % "#" % "Name" % "Address" % "State" % "Qps" % "Qlim" % "Ord" % "Wt" % "Queries" % "Drops" % "Drate" % "Lat" % "Outstanding" % "Pools" % "TCP") << endl;
       }
 
-      uint64_t totQPS{0}, totQueries{0}, totDrops{0};
+      uint64_t totQPS{0};
+      uint64_t totQueries{0};
+      uint64_t totDrops{0};
       int counter = 0;
       auto states = g_dstates.getLocal();
-      for (const auto& s : *states) {
-        string status = s->getStatus();
+      for (const auto& backend : *states) {
+        string status = backend->getStatus();
         string pools;
-        for (const auto& p : s->d_config.pools) {
+        for (const auto& pool : backend->d_config.pools) {
           if (!pools.empty()) {
             pools += " ";
           }
-          pools += p;
+          pools += pool;
         }
-        const std::string latency = (s->latencyUsec == 0.0 ? "-" : boost::str(latFmt % (s->latencyUsec / 1000.0)));
-        const std::string latencytcp = (s->latencyUsecTCP == 0.0 ? "-" : boost::str(latFmt % (s->latencyUsecTCP / 1000.0)));
+        const std::string latency = (backend->latencyUsec == 0.0 ? "-" : boost::str(latFmt % (backend->latencyUsec / 1000.0)));
+        const std::string latencytcp = (backend->latencyUsecTCP == 0.0 ? "-" : boost::str(latFmt % (backend->latencyUsecTCP / 1000.0)));
         if (showUUIDs) {
-          ret << (fmt % counter % s->getName() % s->d_config.remote.toStringWithPort() % status % s->queryLoad % s->qps.getRate() % s->d_config.order % s->d_config.d_weight % s->queries.load() % s->reuseds.load() % (s->dropRate) % latency % s->outstanding.load() % pools % *s->d_config.id % latencytcp) << endl;
+          ret << (fmt % counter % backend->getName() % backend->d_config.remote.toStringWithPort() % status % backend->queryLoad % backend->qps.getRate() % backend->d_config.order % backend->d_config.d_weight % backend->queries.load() % backend->reuseds.load() % (backend->dropRate) % latency % backend->outstanding.load() % pools % *backend->d_config.id % latencytcp) << endl;
         }
         else {
-          ret << (fmt % counter % s->getName() % s->d_config.remote.toStringWithPort() % status % s->queryLoad % s->qps.getRate() % s->d_config.order % s->d_config.d_weight % s->queries.load() % s->reuseds.load() % (s->dropRate) % latency % s->outstanding.load() % pools % latencytcp) << endl;
+          ret << (fmt % counter % backend->getName() % backend->d_config.remote.toStringWithPort() % status % backend->queryLoad % backend->qps.getRate() % backend->d_config.order % backend->d_config.d_weight % backend->queries.load() % backend->reuseds.load() % (backend->dropRate) % latency % backend->outstanding.load() % pools % latencytcp) << endl;
         }
-        totQPS += s->queryLoad;
-        totQueries += s->queries.load();
-        totDrops += s->reuseds.load();
+        totQPS += static_cast<uint64_t>(backend->queryLoad);
+        totQueries += backend->queries.load();
+        totDrops += backend->reuseds.load();
         ++counter;
       }
       if (showUUIDs) {
@@ -1016,8 +1031,8 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
     setLuaNoSideEffect();
     LuaArray<std::shared_ptr<DownstreamState>> ret;
     int count = 1;
-    for (const auto& s : g_dstates.getCopy()) {
-      ret.emplace_back(count++, s);
+    for (const auto& backend : g_dstates.getCopy()) {
+      ret.emplace_back(count++, backend);
     }
     return ret;
   });
@@ -1027,12 +1042,12 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
     return *poolServers;
   });
 
-  luaCtx.writeFunction("getServer", [client](boost::variant<int, std::string> i) {
+  luaCtx.writeFunction("getServer", [client](boost::variant<int, std::string> identifier) {
     if (client) {
       return std::make_shared<DownstreamState>(ComboAddress());
     }
     auto states = g_dstates.getCopy();
-    if (auto str = boost::get<std::string>(&i)) {
+    if (auto* str = boost::get<std::string>(&identifier)) {
       const auto uuid = getUniqueID(*str);
       for (auto& state : states) {
         if (*state->d_config.id == uuid) {
@@ -1040,7 +1055,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
         }
       }
     }
-    else if (auto pos = boost::get<int>(&i)) {
+    else if (auto* pos = boost::get<int>(&identifier)) {
       return states.at(*pos);
     }
 
@@ -1080,8 +1095,8 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
       SBind(sock, local);
       SListen(sock, 5);
       auto launch = [sock, local]() {
-        thread t(dnsdistWebserverThread, sock, local);
-        t.detach();
+        thread thr(dnsdistWebserverThread, sock, local);
+        thr.detach();
       };
       if (g_launchWork) {
         g_launchWork->push_back(launch);
@@ -1226,13 +1241,14 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
 #endif
 
     NetmaskGroup nmg;
-    if (auto str = boost::get<string>(&inp)) {
+    if (auto* str = boost::get<string>(&inp)) {
       nmg.addMask(*str);
     }
-    else
-      for (const auto& p : boost::get<LuaArray<std::string>>(inp)) {
-        nmg.addMask(p.second);
+    else {
+      for (const auto& entry : boost::get<LuaArray<std::string>>(inp)) {
+        nmg.addMask(entry.second);
       }
+    }
     g_consoleACL.setState(nmg);
   });
 
@@ -1307,8 +1323,9 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
       g_outputBuffer = string("Unable to decode ") + key + " as Base64";
       errlog("%s", g_outputBuffer);
     }
-    else
+    else {
       g_consoleKey = std::move(newkey);
+    }
   });
 
   luaCtx.writeFunction("clearConsoleHistory", []() {
@@ -1457,7 +1474,14 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
     g_cacheCleaningDelay = delay;
   });
 
-  luaCtx.writeFunction("setCacheCleaningPercentage", [](uint64_t percentage) { if (percentage < 100) g_cacheCleaningPercentage = percentage; else g_cacheCleaningPercentage = 100; });
+  luaCtx.writeFunction("setCacheCleaningPercentage", [](uint64_t percentage) {
+    if (percentage < 100) {
+      g_cacheCleaningPercentage = percentage;
+    }
+    else {
+      g_cacheCleaningPercentage = 100;
+    }
+  });
 
   luaCtx.writeFunction("setECSSourcePrefixV4", [](uint64_t prefix) {
     checkParameterBound("setECSSourcePrefixV4", prefix, std::numeric_limits<uint16_t>::max());
@@ -1475,25 +1499,26 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
   luaCtx.writeFunction("showDynBlocks", []() {
     setLuaNoSideEffect();
     auto slow = g_dynblockNMG.getCopy();
-    struct timespec now;
+    timespec now{};
     gettime(&now);
     boost::format fmt("%-24s %8d %8d %-10s %-20s %-10s %s\n");
     g_outputBuffer = (fmt % "What" % "Seconds" % "Blocks" % "Warning" % "Action" % "eBPF" % "Reason").str();
-    for (const auto& e : slow) {
-      if (now < e.second.until) {
-        uint64_t counter = e.second.blocks;
-        if (g_defaultBPFFilter && e.second.bpf) {
-          counter += g_defaultBPFFilter->getHits(e.first.getNetwork());
+    for (const auto& entry : slow) {
+      if (now < entry.second.until) {
+        uint64_t counter = entry.second.blocks;
+        if (g_defaultBPFFilter && entry.second.bpf) {
+          counter += g_defaultBPFFilter->getHits(entry.first.getNetwork());
         }
-        g_outputBuffer += (fmt % e.first.toString() % (e.second.until.tv_sec - now.tv_sec) % counter % (e.second.warning ? "true" : "false") % DNSAction::typeToString(e.second.action != DNSAction::Action::None ? e.second.action : g_dynBlockAction) % (g_defaultBPFFilter && e.second.bpf ? "*" : "") % e.second.reason).str();
+        g_outputBuffer += (fmt % entry.first.toString() % (entry.second.until.tv_sec - now.tv_sec) % counter % (entry.second.warning ? "true" : "false") % DNSAction::typeToString(entry.second.action != DNSAction::Action::None ? entry.second.action : g_dynBlockAction) % (g_defaultBPFFilter && entry.second.bpf ? "*" : "") % entry.second.reason).str();
       }
     }
     auto slow2 = g_dynblockSMT.getCopy();
     slow2.visit([&now, &fmt](const SuffixMatchTree<DynBlock>& node) {
       if (now < node.d_value.until) {
         string dom("empty");
-        if (!node.d_value.domain.empty())
+        if (!node.d_value.domain.empty()) {
           dom = node.d_value.domain.toString();
+        }
         g_outputBuffer += (fmt % dom % (node.d_value.until.tv_sec - now.tv_sec) % node.d_value.blocks % (node.d_value.warning ? "true" : "false") % DNSAction::typeToString(node.d_value.action != DNSAction::Action::None ? node.d_value.action : g_dynBlockAction) % "" % node.d_value.reason).str();
       }
     });
@@ -1501,9 +1526,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
 
   luaCtx.writeFunction("getDynamicBlocks", []() {
     setLuaNoSideEffect();
-    struct timespec now
-    {
-    };
+    timespec now{};
     gettime(&now);
 
     LuaAssociativeTable<DynBlock> entries;
@@ -1527,9 +1550,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
 
   luaCtx.writeFunction("getDynamicBlocksSMT", []() {
     setLuaNoSideEffect();
-    struct timespec now
-    {
-    };
+    timespec now{};
     gettime(&now);
 
     LuaAssociativeTable<DynBlock> entries;
@@ -1561,24 +1582,24 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
 
 #ifndef DISABLE_DEPRECATED_DYNBLOCK
   luaCtx.writeFunction("addDynBlocks",
-                       [](const std::unordered_map<ComboAddress, unsigned int, ComboAddress::addressOnlyHash, ComboAddress::addressOnlyEqual>& m, const std::string& msg, boost::optional<int> seconds, boost::optional<DNSAction::Action> action) {
-                         if (m.empty()) {
+                       [](const std::unordered_map<ComboAddress, unsigned int, ComboAddress::addressOnlyHash, ComboAddress::addressOnlyEqual>& addrs, const std::string& msg, boost::optional<int> seconds, boost::optional<DNSAction::Action> action) {
+                         if (addrs.empty()) {
                            return;
                          }
                          setLuaSideEffect();
                          auto slow = g_dynblockNMG.getCopy();
-                         struct timespec until, now;
+                         timespec now{};
                          gettime(&now);
-                         until = now;
+                         timespec until{now};
                          int actualSeconds = seconds ? *seconds : 10;
                          until.tv_sec += actualSeconds;
-                         for (const auto& capair : m) {
+                         for (const auto& capair : addrs) {
                            unsigned int count = 0;
                            /* this legacy interface does not support ranges or ports, use DynBlockRulesGroup instead */
                            AddressAndPortRange requestor(capair.first, capair.first.isIPv4() ? 32 : 128, 0);
-                           auto got = slow.lookup(requestor);
+                           auto* got = slow.lookup(requestor);
                            bool expired = false;
-                           if (got) {
+                           if (got != nullptr) {
                              if (until < got->second.until) {
                                // had a longer policy
                                continue;
@@ -1591,12 +1612,12 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
                                expired = true;
                              }
                            }
-                           DynBlock db{msg, until, DNSName(), (action ? *action : DNSAction::Action::None)};
-                           db.blocks = count;
-                           if (!got || expired) {
+                           DynBlock dblock{msg, until, DNSName(), (action ? *action : DNSAction::Action::None)};
+                           dblock.blocks = count;
+                           if (got == nullptr || expired) {
                              warnlog("Inserting dynamic block for %s for %d seconds: %s", capair.first.toString(), actualSeconds, msg);
                            }
-                           slow.insert(requestor).second = std::move(db);
+                           slow.insert(requestor).second = std::move(dblock);
                          }
                          g_dynblockNMG.setState(slow);
                        });
@@ -1621,9 +1642,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
                            return;
                          }
                          setLuaSideEffect();
-                         struct timespec now
-                         {
-                         };
+                         timespec now{};
                          gettime(&now);
                          unsigned int actualSeconds = seconds ? *seconds : 10;
 
@@ -1668,9 +1687,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
                          AddressAndPortRange target(clientIPCA, clientIPMask ? *clientIPMask : (clientIPCA.isIPv4() ? 32 : 128), clientIPPortMask ? *clientIPPortMask : 0);
                          unsigned int actualSeconds = seconds ? *seconds : 10;
 
-                         struct timespec now
-                         {
-                         };
+                         timespec now{};
                          gettime(&now);
                          auto slow = g_dynblockNMG.getCopy();
                          if (dnsdist::DynamicBlocks::addOrRefreshBlock(slow, now, target, msg, actualSeconds, action ? *action : DNSAction::Action::None, false, false)) {
@@ -1679,7 +1696,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
                        });
 
   luaCtx.writeFunction("setDynBlocksPurgeInterval", [](uint64_t interval) {
-    DynBlockMaintenance::s_expiredDynBlocksPurgeInterval = interval;
+    DynBlockMaintenance::s_expiredDynBlocksPurgeInterval = static_cast<time_t>(interval);
   });
 #endif /* DISABLE_DYNBLOCKS */
 
@@ -1970,11 +1987,11 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
     }
   });
 
-  luaCtx.writeFunction("unregisterDynBPFFilter", [](std::shared_ptr<DynBPFFilter> dbpf) {
+  luaCtx.writeFunction("unregisterDynBPFFilter", [](const std::shared_ptr<DynBPFFilter>& dbpf) {
     if (dbpf) {
-      for (auto it = g_dynBPFFilters.begin(); it != g_dynBPFFilters.end(); it++) {
-        if (*it == dbpf) {
-          g_dynBPFFilters.erase(it);
+      for (auto filterIt = g_dynBPFFilters.begin(); filterIt != g_dynBPFFilters.end(); filterIt++) {
+        if (*filterIt == dbpf) {
+          g_dynBPFFilters.erase(filterIt);
           break;
         }
       }
@@ -1983,17 +2000,17 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
 
 #ifndef DISABLE_DYNBLOCKS
 #ifndef DISABLE_DEPRECATED_DYNBLOCK
-  luaCtx.writeFunction("addBPFFilterDynBlocks", [](const std::unordered_map<ComboAddress, unsigned int, ComboAddress::addressOnlyHash, ComboAddress::addressOnlyEqual>& m, std::shared_ptr<DynBPFFilter> dynbpf, boost::optional<int> seconds, boost::optional<std::string> msg) {
+  luaCtx.writeFunction("addBPFFilterDynBlocks", [](const std::unordered_map<ComboAddress, unsigned int, ComboAddress::addressOnlyHash, ComboAddress::addressOnlyEqual>& addrs, const std::shared_ptr<DynBPFFilter>& dynbpf, boost::optional<int> seconds, boost::optional<std::string> msg) {
     if (!dynbpf) {
       return;
     }
     setLuaSideEffect();
-    struct timespec until, now;
+    timespec now{};
     clock_gettime(CLOCK_MONOTONIC, &now);
-    until = now;
+    timespec until{now};
     int actualSeconds = seconds ? *seconds : 10;
     until.tv_sec += actualSeconds;
-    for (const auto& capair : m) {
+    for (const auto& capair : addrs) {
       if (dynbpf->block(capair.first, until)) {
         warnlog("Inserting eBPF dynamic block for %s for %d seconds: %s", capair.first.toString(), actualSeconds, msg ? *msg : "");
       }
@@ -2029,14 +2046,16 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
       return;
     }
 
-    struct stat st;
-    if (stat(dirname.c_str(), &st)) {
+    struct stat dirStat
+    {
+    };
+    if (stat(dirname.c_str(), &dirStat) != 0) {
       errlog("The included directory %s does not exist!", dirname.c_str());
       g_outputBuffer = "The included directory " + dirname + " does not exist!";
       return;
     }
 
-    if (!S_ISDIR(st.st_mode)) {
+    if (!S_ISDIR(dirStat.st_mode)) {
       errlog("The included directory %s is not a directory!", dirname.c_str());
       g_outputBuffer = "The included directory " + dirname + " is not a directory!";
       return;
@@ -2187,15 +2206,16 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
   luaCtx.writeFunction("setTCPInternalPipeBufferSize", [](uint64_t size) { g_tcpInternalPipeBufferSize = size; });
   luaCtx.writeFunction("setTCPFastOpenKey", [](const std::string& keyString) {
     setLuaSideEffect();
-    uint32_t key[4] = {};
+    std::array<uint32_t, 4> key{};
+    // NOLINTNEXTLINE(readability-container-data-pointer)
     auto ret = sscanf(keyString.c_str(), "%" SCNx32 "-%" SCNx32 "-%" SCNx32 "-%" SCNx32, &key[0], &key[1], &key[2], &key[3]);
     if (ret != 4) {
       g_outputBuffer = "Invalid value passed to setTCPFastOpenKey()!\n";
       return;
     }
     extern vector<uint32_t> g_TCPFastOpenKey;
-    for (const auto i : key) {
-      g_TCPFastOpenKey.push_back(i);
+    for (const auto byte : key) {
+      g_TCPFastOpenKey.push_back(byte);
     }
   });
 
@@ -2215,11 +2235,11 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
 
     g_snmpEnabled = true;
     g_snmpTrapsEnabled = enableTraps;
-    g_snmpAgent = new DNSDistSNMPAgent("dnsdist", daemonSocket ? *daemonSocket : std::string());
+    g_snmpAgent = std::make_unique<DNSDistSNMPAgent>("dnsdist", daemonSocket ? *daemonSocket : std::string());
   });
 
   luaCtx.writeFunction("sendCustomTrap", [](const std::string& str) {
-    if (g_snmpAgent && g_snmpTrapsEnabled) {
+    if (g_snmpAgent != nullptr && g_snmpTrapsEnabled) {
       g_snmpAgent->sendCustomTrap(str);
     }
   });
@@ -2233,12 +2253,12 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
 
   luaCtx.writeFunction("setServerPolicyLua", [](const string& name, ServerPolicy::policyfunc_t policy) {
     setLuaSideEffect();
-    g_policy.setState(ServerPolicy{name, policy, true});
+    g_policy.setState(ServerPolicy{name, std::move(policy), true});
   });
 
   luaCtx.writeFunction("setServerPolicyLuaFFI", [](const string& name, ServerPolicy::ffipolicyfunc_t policy) {
     setLuaSideEffect();
-    auto pol = ServerPolicy(name, policy);
+    auto pol = ServerPolicy(name, std::move(policy));
     g_policy.setState(std::move(pol));
   });
 
@@ -2337,12 +2357,12 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
     }
     setLuaSideEffect();
     NetmaskGroup nmg;
-    if (auto str = boost::get<string>(&inp)) {
+    if (auto* str = boost::get<string>(&inp)) {
       nmg.addMask(*str);
     }
     else {
-      for (const auto& p : boost::get<LuaArray<std::string>>(inp)) {
-        nmg.addMask(p.second);
+      for (const auto& entry : boost::get<LuaArray<std::string>>(inp)) {
+        nmg.addMask(entry.second);
       }
     }
     g_proxyProtocolACL = std::move(nmg);
@@ -2471,12 +2491,12 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
         {"log_ftp", LOG_FTP}};
       auto facilityStr = boost::get<std::string>(facility);
       toLowerInPlace(facilityStr);
-      auto it = facilities.find(facilityStr);
-      if (it == facilities.end()) {
+      auto facilityIt = facilities.find(facilityStr);
+      if (facilityIt == facilities.end()) {
         g_outputBuffer = "Unknown facility '" + facilityStr + "' passed to setSyslogFacility()!\n";
         return;
       }
-      setSyslogFacility(it->second);
+      setSyslogFacility(facilityIt->second);
     }
     else {
       setSyslogFacility(boost::get<int>(facility));
@@ -2490,12 +2510,13 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
       return result;
     }
 #if defined(HAVE_DNS_OVER_TLS) || defined(HAVE_DNS_OVER_HTTPS)
-    std::optional<std::string> key, password;
+    std::optional<std::string> key;
+    std::optional<std::string> password;
     if (opts) {
-      if (opts->count("key")) {
+      if (opts->count("key") != 0) {
         key = boost::get<const string>((*opts)["key"]);
       }
-      if (opts->count("password")) {
+      if (opts->count("password") != 0) {
         password = boost::get<const string>((*opts)["password"]);
       }
     }
@@ -2563,8 +2584,8 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
       }
       else if (urls->type() == typeid(LuaArray<std::string>)) {
         auto urlsVect = boost::get<LuaArray<std::string>>(*urls);
-        for (const auto& p : urlsVect) {
-          frontend->d_urls.insert(p.second);
+        for (const auto& url : urlsVect) {
+          frontend->d_urls.insert(url.second);
         }
       }
     }
@@ -3029,7 +3050,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
     }
   });
 
-  luaCtx.registerFunction<void (std::shared_ptr<DOHFrontend>::*)(boost::variant<std::string, std::shared_ptr<TLSCertKeyPair>, LuaArray<std::string>, LuaArray<std::shared_ptr<TLSCertKeyPair>>> certFiles, boost::variant<std::string, LuaArray<std::string>> keyFiles)>("loadNewCertificatesAndKeys", [](std::shared_ptr<DOHFrontend> frontend, boost::variant<std::string, std::shared_ptr<TLSCertKeyPair>, LuaArray<std::string>, LuaArray<std::shared_ptr<TLSCertKeyPair>>> certFiles, boost::variant<std::string, LuaArray<std::string>> keyFiles) {
+  luaCtx.registerFunction<void (std::shared_ptr<DOHFrontend>::*)(boost::variant<std::string, std::shared_ptr<TLSCertKeyPair>, LuaArray<std::string>, LuaArray<std::shared_ptr<TLSCertKeyPair>>> certFiles, boost::variant<std::string, LuaArray<std::string>> keyFiles)>("loadNewCertificatesAndKeys", [](const std::shared_ptr<DOHFrontend>& frontend, const boost::variant<std::string, std::shared_ptr<TLSCertKeyPair>, LuaArray<std::string>, LuaArray<std::shared_ptr<TLSCertKeyPair>>>& certFiles, const boost::variant<std::string, LuaArray<std::string>>& keyFiles) {
 #ifdef HAVE_DNS_OVER_HTTPS
     if (frontend != nullptr) {
       if (loadTLSCertificateAndKeys("DOHFrontend::loadNewCertificatesAndKeys", frontend->d_tlsContext.d_tlsConfig.d_certKeyPairs, certFiles, keyFiles)) {
@@ -3039,19 +3060,19 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
 #endif
   });
 
-  luaCtx.registerFunction<void (std::shared_ptr<DOHFrontend>::*)()>("rotateTicketsKey", [](std::shared_ptr<DOHFrontend> frontend) {
+  luaCtx.registerFunction<void (std::shared_ptr<DOHFrontend>::*)()>("rotateTicketsKey", [](const std::shared_ptr<DOHFrontend>& frontend) {
     if (frontend != nullptr) {
       frontend->rotateTicketsKey(time(nullptr));
     }
   });
 
-  luaCtx.registerFunction<void (std::shared_ptr<DOHFrontend>::*)(const std::string&)>("loadTicketsKeys", [](std::shared_ptr<DOHFrontend> frontend, const std::string& file) {
+  luaCtx.registerFunction<void (std::shared_ptr<DOHFrontend>::*)(const std::string&)>("loadTicketsKeys", [](const std::shared_ptr<DOHFrontend>& frontend, const std::string& file) {
     if (frontend != nullptr) {
       frontend->loadTicketsKeys(file);
     }
   });
 
-  luaCtx.registerFunction<void (std::shared_ptr<DOHFrontend>::*)(const LuaArray<std::shared_ptr<DOHResponseMapEntry>>&)>("setResponsesMap", [](std::shared_ptr<DOHFrontend> frontend, const LuaArray<std::shared_ptr<DOHResponseMapEntry>>& map) {
+  luaCtx.registerFunction<void (std::shared_ptr<DOHFrontend>::*)(const LuaArray<std::shared_ptr<DOHResponseMapEntry>>&)>("setResponsesMap", [](const std::shared_ptr<DOHFrontend>& frontend, const LuaArray<std::shared_ptr<DOHResponseMapEntry>>& map) {
     if (frontend != nullptr) {
       auto newMap = std::make_shared<std::vector<std::shared_ptr<DOHResponseMapEntry>>>();
       newMap->reserve(map.size());
@@ -3064,7 +3085,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
     }
   });
 
-  luaCtx.writeFunction("addTLSLocal", [client](const std::string& addr, boost::variant<std::string, std::shared_ptr<TLSCertKeyPair>, LuaArray<std::string>, LuaArray<std::shared_ptr<TLSCertKeyPair>>> certFiles, LuaTypeOrArrayOf<std::string> keyFiles, boost::optional<localbind_t> vars) {
+  luaCtx.writeFunction("addTLSLocal", [client](const std::string& addr, const boost::variant<std::string, std::shared_ptr<TLSCertKeyPair>, LuaArray<std::string>, LuaArray<std::shared_ptr<TLSCertKeyPair>>>& certFiles, const LuaTypeOrArrayOf<std::string>& keyFiles, boost::optional<localbind_t> vars) {
     if (client) {
       return;
     }
@@ -3288,7 +3309,7 @@ static void setupLuaConfig(LuaContext& luaCtx, bool client, bool configCheck)
     frontend->setupTLS();
   });
 
-  luaCtx.registerFunction<void (std::shared_ptr<TLSFrontend>::*)(boost::variant<std::string, std::shared_ptr<TLSCertKeyPair>, LuaArray<std::string>, LuaArray<std::shared_ptr<TLSCertKeyPair>>> certFiles, LuaTypeOrArrayOf<std::string> keyFiles)>("loadNewCertificatesAndKeys", [](std::shared_ptr<TLSFrontend>& frontend, boost::variant<std::string, std::shared_ptr<TLSCertKeyPair>, LuaArray<std::string>, LuaArray<std::shared_ptr<TLSCertKeyPair>>> certFiles, LuaTypeOrArrayOf<std::string> keyFiles) {
+  luaCtx.registerFunction<void (std::shared_ptr<TLSFrontend>::*)(const boost::variant<std::string, std::shared_ptr<TLSCertKeyPair>, LuaArray<std::string>, LuaArray<std::shared_ptr<TLSCertKeyPair>>>&, const LuaTypeOrArrayOf<std::string>&)>("loadNewCertificatesAndKeys", [](std::shared_ptr<TLSFrontend>& frontend, const boost::variant<std::string, std::shared_ptr<TLSCertKeyPair>, LuaArray<std::string>, LuaArray<std::shared_ptr<TLSCertKeyPair>>>& certFiles, const LuaTypeOrArrayOf<std::string>& keyFiles) {
 #ifdef HAVE_DNS_OVER_TLS
     if (loadTLSCertificateAndKeys("TLSFrontend::loadNewCertificatesAndKeys", frontend->d_tlsConfig.d_certKeyPairs, certFiles, keyFiles)) {
       frontend->setupTLS();
@@ -3501,9 +3522,7 @@ vector<std::function<void(void)>> setupLua(LuaContext& luaCtx, bool client, bool
     if (configCheck) {
       throw std::runtime_error("Unable to read configuration file from " + config);
     }
-    else {
-      warnlog("Unable to read configuration from '%s'", config);
-    }
+    warnlog("Unable to read configuration from '%s'", config);
   }
   else {
     vinfolog("Read configuration from '%s'", config);
index 6081d11f9ec525904ec7e97b53eec9620521f38b..34e9c7cdd3858adf8a35ad82cf2b430735239926 100644 (file)
@@ -5,7 +5,7 @@
 
 bool g_snmpEnabled{false};
 bool g_snmpTrapsEnabled{false};
-DNSDistSNMPAgent* g_snmpAgent{nullptr};
+std::unique_ptr<DNSDistSNMPAgent> g_snmpAgent{nullptr};
 
 #ifdef HAVE_NET_SNMP
 
@@ -15,46 +15,51 @@ DNSDistSNMPAgent* g_snmpAgent{nullptr};
 #define DNSDIST_TRAPS_OID DNSDIST_OID, 10, 0
 #define DNSDIST_TRAP_OBJECTS_OID DNSDIST_OID, 11
 
-static const oid queriesOID[] = {DNSDIST_STATS_OID, 1};
-static const oid responsesOID[] = {DNSDIST_STATS_OID, 2};
-static const oid servfailResponsesOID[] = {DNSDIST_STATS_OID, 3};
-static const oid aclDropsOID[] = {DNSDIST_STATS_OID, 4};
+using OIDStat = std::array<oid, 10>;
+using OIDTrap = std::array<oid, 11>;
+using OIDTrapObject = std::array<oid, 11>;
+using OIDStatTable = std::array<oid, 12>;
+
+static const OIDStat queriesOID{DNSDIST_STATS_OID, 1};
+static const OIDStat responsesOID{DNSDIST_STATS_OID, 2};
+static const OIDStat servfailResponsesOID{DNSDIST_STATS_OID, 3};
+static const OIDStat aclDropsOID{DNSDIST_STATS_OID, 4};
 // 5 was BlockFilter, removed in 1.2.0
-static const oid ruleDropOID[] = {DNSDIST_STATS_OID, 6};
-static const oid ruleNXDomainOID[] = {DNSDIST_STATS_OID, 7};
-static const oid ruleRefusedOID[] = {DNSDIST_STATS_OID, 8};
-static const oid selfAnsweredOID[] = {DNSDIST_STATS_OID, 9};
-static const oid downstreamTimeoutsOID[] = {DNSDIST_STATS_OID, 10};
-static const oid downstreamSendErrorsOID[] = {DNSDIST_STATS_OID, 11};
-static const oid truncFailOID[] = {DNSDIST_STATS_OID, 12};
-static const oid noPolicyOID[] = {DNSDIST_STATS_OID, 13};
-static const oid latency0_1OID[] = {DNSDIST_STATS_OID, 14};
-static const oid latency1_10OID[] = {DNSDIST_STATS_OID, 15};
-static const oid latency10_50OID[] = {DNSDIST_STATS_OID, 16};
-static const oid latency50_100OID[] = {DNSDIST_STATS_OID, 17};
-static const oid latency100_1000OID[] = {DNSDIST_STATS_OID, 18};
-static const oid latencySlowOID[] = {DNSDIST_STATS_OID, 19};
-static const oid latencyAvg100OID[] = {DNSDIST_STATS_OID, 20};
-static const oid latencyAvg1000OID[] = {DNSDIST_STATS_OID, 21};
-static const oid latencyAvg10000OID[] = {DNSDIST_STATS_OID, 22};
-static const oid latencyAvg1000000OID[] = {DNSDIST_STATS_OID, 23};
-static const oid uptimeOID[] = {DNSDIST_STATS_OID, 24};
-static const oid realMemoryUsageOID[] = {DNSDIST_STATS_OID, 25};
-static const oid nonCompliantQueriesOID[] = {DNSDIST_STATS_OID, 26};
-static const oid nonCompliantResponsesOID[] = {DNSDIST_STATS_OID, 27};
-static const oid rdQueriesOID[] = {DNSDIST_STATS_OID, 28};
-static const oid emptyQueriesOID[] = {DNSDIST_STATS_OID, 29};
-static const oid cacheHitsOID[] = {DNSDIST_STATS_OID, 30};
-static const oid cacheMissesOID[] = {DNSDIST_STATS_OID, 31};
-static const oid cpuUserMSecOID[] = {DNSDIST_STATS_OID, 32};
-static const oid cpuSysMSecOID[] = {DNSDIST_STATS_OID, 33};
-static const oid fdUsageOID[] = {DNSDIST_STATS_OID, 34};
-static const oid dynBlockedOID[] = {DNSDIST_STATS_OID, 35};
-static const oid dynBlockedNMGSizeOID[] = {DNSDIST_STATS_OID, 36};
-static const oid ruleServFailOID[] = {DNSDIST_STATS_OID, 37};
-static const oid securityStatusOID[] = {DNSDIST_STATS_OID, 38};
-static const oid specialMemoryUsageOID[] = {DNSDIST_STATS_OID, 39};
-static const oid ruleTruncatedOID[] = {DNSDIST_STATS_OID, 40};
+static const OIDStat ruleDropOID{DNSDIST_STATS_OID, 6};
+static const OIDStat ruleNXDomainOID{DNSDIST_STATS_OID, 7};
+static const OIDStat ruleRefusedOID{DNSDIST_STATS_OID, 8};
+static const OIDStat selfAnsweredOID{DNSDIST_STATS_OID, 9};
+static const OIDStat downstreamTimeoutsOID{DNSDIST_STATS_OID, 10};
+static const OIDStat downstreamSendErrorsOID{DNSDIST_STATS_OID, 11};
+static const OIDStat truncFailOID{DNSDIST_STATS_OID, 12};
+static const OIDStat noPolicyOID{DNSDIST_STATS_OID, 13};
+static const OIDStat latency0_1OID{DNSDIST_STATS_OID, 14};
+static const OIDStat latency1_10OID{DNSDIST_STATS_OID, 15};
+static const OIDStat latency10_50OID{DNSDIST_STATS_OID, 16};
+static const OIDStat latency50_100OID{DNSDIST_STATS_OID, 17};
+static const OIDStat latency100_1000OID{DNSDIST_STATS_OID, 18};
+static const OIDStat latencySlowOID{DNSDIST_STATS_OID, 19};
+static const OIDStat latencyAvg100OID{DNSDIST_STATS_OID, 20};
+static const OIDStat latencyAvg1000OID{DNSDIST_STATS_OID, 21};
+static const OIDStat latencyAvg10000OID{DNSDIST_STATS_OID, 22};
+static const OIDStat latencyAvg1000000OID{DNSDIST_STATS_OID, 23};
+static const OIDStat uptimeOID{DNSDIST_STATS_OID, 24};
+static const OIDStat realMemoryUsageOID{DNSDIST_STATS_OID, 25};
+static const OIDStat nonCompliantQueriesOID{DNSDIST_STATS_OID, 26};
+static const OIDStat nonCompliantResponsesOID{DNSDIST_STATS_OID, 27};
+static const OIDStat rdQueriesOID{DNSDIST_STATS_OID, 28};
+static const OIDStat emptyQueriesOID{DNSDIST_STATS_OID, 29};
+static const OIDStat cacheHitsOID{DNSDIST_STATS_OID, 30};
+static const OIDStat cacheMissesOID{DNSDIST_STATS_OID, 31};
+static const OIDStat cpuUserMSecOID{DNSDIST_STATS_OID, 32};
+static const OIDStat cpuSysMSecOID{DNSDIST_STATS_OID, 33};
+static const OIDStat fdUsageOID{DNSDIST_STATS_OID, 34};
+static const OIDStat dynBlockedOID{DNSDIST_STATS_OID, 35};
+static const OIDStat dynBlockedNMGSizeOID{DNSDIST_STATS_OID, 36};
+static const OIDStat ruleServFailOID{DNSDIST_STATS_OID, 37};
+static const OIDStat securityStatusOID{DNSDIST_STATS_OID, 38};
+static const OIDStat specialMemoryUsageOID{DNSDIST_STATS_OID, 39};
+static const OIDStat ruleTruncatedOID{DNSDIST_STATS_OID, 40};
 
 static std::unordered_map<oid, dnsdist::metrics::Stats::entry_t> s_statsMap;
 
@@ -76,35 +81,36 @@ static int handleCounter64Stats(netsnmp_mib_handler* handler,
     return SNMP_ERR_GENERR;
   }
 
-  const auto& it = s_statsMap.find(reginfo->rootoid[reginfo->rootoid_len - 2]);
-  if (it == s_statsMap.end()) {
+  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic): net-snmp API
+  const auto& stIt = s_statsMap.find(reginfo->rootoid[reginfo->rootoid_len - 2]);
+  if (stIt == s_statsMap.end()) {
     return SNMP_ERR_GENERR;
   }
 
-  if (const auto& val = std::get_if<pdns::stat_t*>(&it->second)) {
+  if (const auto& val = std::get_if<pdns::stat_t*>(&stIt->second)) {
     return DNSDistSNMPAgent::setCounter64Value(requests, (*val)->load());
   }
 
   return SNMP_ERR_GENERR;
 }
 
-static void registerCounter64Stat(const char* name, const oid statOID[], size_t statOIDLength, pdns::stat_t* ptr)
+static void registerCounter64Stat(const char* name, const OIDStat& statOID, pdns::stat_t* ptr)
 {
-  if (statOIDLength != OID_LENGTH(queriesOID)) {
+  if (statOID.size() != OID_LENGTH(queriesOID)) {
     errlog("Invalid OID for SNMP Counter64 statistic %s", name);
     return;
   }
 
-  if (s_statsMap.find(statOID[statOIDLength - 1]) != s_statsMap.end()) {
+  if (s_statsMap.find(statOID.at(statOID.size() - 1)) != s_statsMap.end()) {
     errlog("OID for SNMP Counter64 statistic %s has already been registered", name);
     return;
   }
 
-  s_statsMap[statOID[statOIDLength - 1]] = ptr;
+  s_statsMap[statOID.at(statOID.size() - 1)] = ptr;
   netsnmp_register_scalar(netsnmp_create_handler_registration(name,
                                                               handleCounter64Stats,
-                                                              statOID,
-                                                              statOIDLength,
+                                                              statOID.data(),
+                                                              statOID.size(),
                                                               HANDLER_CAN_RONLY));
 }
 
@@ -121,12 +127,13 @@ static int handleFloatStats(netsnmp_mib_handler* handler,
     return SNMP_ERR_GENERR;
   }
 
-  const auto& it = s_statsMap.find(reginfo->rootoid[reginfo->rootoid_len - 2]);
-  if (it == s_statsMap.end()) {
+  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic): net-snmp API
+  const auto& stIt = s_statsMap.find(reginfo->rootoid[reginfo->rootoid_len - 2]);
+  if (stIt == s_statsMap.end()) {
     return SNMP_ERR_GENERR;
   }
 
-  if (const auto& val = std::get_if<double*>(&it->second)) {
+  if (const auto& val = std::get_if<double*>(&stIt->second)) {
     std::string str(std::to_string(**val));
     snmp_set_var_typed_value(requests->requestvb,
                              ASN_OCTET_STR,
@@ -138,23 +145,23 @@ static int handleFloatStats(netsnmp_mib_handler* handler,
   return SNMP_ERR_GENERR;
 }
 
-static void registerFloatStat(const char* name, const oid statOID[], size_t statOIDLength, double* ptr)
+static void registerFloatStat(const char* name, const OIDStat& statOID, double* ptr)
 {
-  if (statOIDLength != OID_LENGTH(queriesOID)) {
+  if (statOID.size() != OID_LENGTH(queriesOID)) {
     errlog("Invalid OID for SNMP Float statistic %s", name);
     return;
   }
 
-  if (s_statsMap.find(statOID[statOIDLength - 1]) != s_statsMap.end()) {
+  if (s_statsMap.find(statOID.at(statOID.size() - 1)) != s_statsMap.end()) {
     errlog("OID for SNMP Float statistic %s has already been registered", name);
     return;
   }
 
-  s_statsMap[statOID[statOIDLength - 1]] = ptr;
+  s_statsMap[statOID.at(statOID.size() - 1)] = ptr;
   netsnmp_register_scalar(netsnmp_create_handler_registration(name,
                                                               handleFloatStats,
-                                                              statOID,
-                                                              statOIDLength,
+                                                              statOID.data(),
+                                                              statOID.size(),
                                                               HANDLER_CAN_RONLY));
 }
 
@@ -171,71 +178,71 @@ static int handleGauge64Stats(netsnmp_mib_handler* handler,
     return SNMP_ERR_GENERR;
   }
 
-  const auto& it = s_statsMap.find(reginfo->rootoid[reginfo->rootoid_len - 2]);
-  if (it == s_statsMap.end()) {
+  // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic): net-snmp API
+  const auto& stIt = s_statsMap.find(reginfo->rootoid[reginfo->rootoid_len - 2]);
+  if (stIt == s_statsMap.end()) {
     return SNMP_ERR_GENERR;
   }
 
   std::string str;
-  uint64_t value = (*std::get_if<dnsdist::metrics::Stats::statfunction_t>(&it->second))(str);
+  uint64_t value = (*std::get_if<dnsdist::metrics::Stats::statfunction_t>(&stIt->second))(str);
   return DNSDistSNMPAgent::setCounter64Value(requests, value);
 }
 
-static void registerGauge64Stat(const char* name, const oid statOID[], size_t statOIDLength, dnsdist::metrics::Stats::statfunction_t ptr)
+static void registerGauge64Stat(const char* name, const OIDStat& statOID, const dnsdist::metrics::Stats::statfunction_t& ptr)
 {
-  if (statOIDLength != OID_LENGTH(queriesOID)) {
+  if (statOID.size() != OID_LENGTH(queriesOID)) {
     errlog("Invalid OID for SNMP Gauge64 statistic %s", name);
     return;
   }
 
-  if (s_statsMap.find(statOID[statOIDLength - 1]) != s_statsMap.end()) {
+  if (s_statsMap.find(statOID.at(statOID.size() - 1)) != s_statsMap.end()) {
     errlog("OID for SNMP Gauge64 statistic %s has already been registered", name);
     return;
   }
 
-  s_statsMap[statOID[statOIDLength - 1]] = ptr;
+  s_statsMap[statOID.at(statOID.size() - 1)] = ptr;
   netsnmp_register_scalar(netsnmp_create_handler_registration(name,
                                                               handleGauge64Stats,
-                                                              statOID,
-                                                              statOIDLength,
+                                                              statOID.data(),
+                                                              statOID.size(),
                                                               HANDLER_CAN_RONLY));
 }
 
 /* column number definitions for table backendStatTable */
-#define COLUMN_BACKENDID 1
-#define COLUMN_BACKENDNAME 2
-#define COLUMN_BACKENDLATENCY 3
-#define COLUMN_BACKENDWEIGHT 4
-#define COLUMN_BACKENDOUTSTANDING 5
-#define COLUMN_BACKENDQPSLIMIT 6
-#define COLUMN_BACKENDREUSED 7
-#define COLUMN_BACKENDSTATE 8
-#define COLUMN_BACKENDADDRESS 9
-#define COLUMN_BACKENDPOOLS 10
-#define COLUMN_BACKENDQPS 11
-#define COLUMN_BACKENDQUERIES 12
-#define COLUMN_BACKENDORDER 13
-
-static const oid backendStatTableOID[] = {DNSDIST_STATS_TABLE_OID};
-static const oid backendNameOID[] = {DNSDIST_STATS_TABLE_OID, 1, 2};
-static const oid backendStateOID[] = {DNSDIST_STATS_TABLE_OID, 1, 8};
-static const oid backendAddressOID[] = {DNSDIST_STATS_TABLE_OID, 1, 9};
-
-static const oid socketFamilyOID[] = {DNSDIST_TRAP_OBJECTS_OID, 1, 0};
-static const oid socketProtocolOID[] = {DNSDIST_TRAP_OBJECTS_OID, 2, 0};
-static const oid fromAddressOID[] = {DNSDIST_TRAP_OBJECTS_OID, 3, 0};
-static const oid toAddressOID[] = {DNSDIST_TRAP_OBJECTS_OID, 4, 0};
-static const oid queryTypeOID[] = {DNSDIST_TRAP_OBJECTS_OID, 5, 0};
-static const oid querySizeOID[] = {DNSDIST_TRAP_OBJECTS_OID, 6, 0};
-static const oid queryIDOID[] = {DNSDIST_TRAP_OBJECTS_OID, 7, 0};
-static const oid qNameOID[] = {DNSDIST_TRAP_OBJECTS_OID, 8, 0};
-static const oid qClassOID[] = {DNSDIST_TRAP_OBJECTS_OID, 9, 0};
-static const oid qTypeOID[] = {DNSDIST_TRAP_OBJECTS_OID, 10, 0};
-static const oid trapReasonOID[] = {DNSDIST_TRAP_OBJECTS_OID, 11, 0};
-
-static const oid backendStatusChangeTrapOID[] = {DNSDIST_TRAPS_OID, 1};
-static const oid actionTrapOID[] = {DNSDIST_TRAPS_OID, 2};
-static const oid customTrapOID[] = {DNSDIST_TRAPS_OID, 3};
+static constexpr unsigned int COLUMN_BACKENDNAME = 2;
+static constexpr unsigned int COLUMN_BACKENDLATENCY = 3;
+static constexpr unsigned int COLUMN_BACKENDWEIGHT = 4;
+static constexpr unsigned int COLUMN_BACKENDOUTSTANDING = 5;
+static constexpr unsigned int COLUMN_BACKENDQPSLIMIT = 6;
+static constexpr unsigned int COLUMN_BACKENDREUSED = 7;
+static constexpr unsigned int COLUMN_BACKENDSTATE = 8;
+static constexpr unsigned int COLUMN_BACKENDADDRESS = 9;
+static constexpr unsigned int COLUMN_BACKENDPOOLS = 10;
+static constexpr unsigned int COLUMN_BACKENDQPS = 11;
+static constexpr unsigned int COLUMN_BACKENDQUERIES = 12;
+static constexpr unsigned int COLUMN_BACKENDORDER = 13;
+
+static const std::array<oid, 9> backendStatTableOID{DNSDIST_STATS_TABLE_OID};
+static const OIDStatTable backendNameOID{DNSDIST_STATS_TABLE_OID, 1, 2};
+static const OIDStatTable backendStateOID{DNSDIST_STATS_TABLE_OID, 1, 8};
+static const OIDStatTable backendAddressOID{DNSDIST_STATS_TABLE_OID, 1, 9};
+
+static const OIDTrapObject socketFamilyOID{DNSDIST_TRAP_OBJECTS_OID, 1, 0};
+static const OIDTrapObject socketProtocolOID{DNSDIST_TRAP_OBJECTS_OID, 2, 0};
+static const OIDTrapObject fromAddressOID{DNSDIST_TRAP_OBJECTS_OID, 3, 0};
+static const OIDTrapObject toAddressOID{DNSDIST_TRAP_OBJECTS_OID, 4, 0};
+static const OIDTrapObject queryTypeOID{DNSDIST_TRAP_OBJECTS_OID, 5, 0};
+static const OIDTrapObject querySizeOID{DNSDIST_TRAP_OBJECTS_OID, 6, 0};
+static const OIDTrapObject queryIDOID{DNSDIST_TRAP_OBJECTS_OID, 7, 0};
+static const OIDTrapObject qNameOID{DNSDIST_TRAP_OBJECTS_OID, 8, 0};
+static const OIDTrapObject qClassOID{DNSDIST_TRAP_OBJECTS_OID, 9, 0};
+static const OIDTrapObject qTypeOID{DNSDIST_TRAP_OBJECTS_OID, 10, 0};
+static const OIDTrapObject trapReasonOID{DNSDIST_TRAP_OBJECTS_OID, 11, 0};
+
+static const OIDTrap backendStatusChangeTrapOID{DNSDIST_TRAPS_OID, 1};
+static const OIDTrap actionTrapOID{DNSDIST_TRAPS_OID, 2};
+static const OIDTrap customTrapOID{DNSDIST_TRAPS_OID, 3};
 
 static servers_t s_servers;
 static size_t s_currentServerIdx = 0;
@@ -246,11 +253,11 @@ static netsnmp_variable_list* backendStatTable_get_next_data_point(void** loop_c
                                                                    netsnmp_iterator_info* mydata)
 {
   if (s_currentServerIdx >= s_servers.size()) {
-    return NULL;
+    return nullptr;
   }
 
   *my_data_context = (void*)(s_servers[s_currentServerIdx]).get();
-  snmp_set_var_typed_integer(put_index_data, ASN_UNSIGNED, s_currentServerIdx);
+  snmp_set_var_typed_integer(put_index_data, ASN_UNSIGNED, static_cast<long>(s_currentServerIdx));
   s_currentServerIdx++;
 
   return put_index_data;
@@ -283,15 +290,15 @@ static int backendStatTable_handler(netsnmp_mib_handler* handler,
                                     netsnmp_agent_request_info* reqinfo,
                                     netsnmp_request_info* requests)
 {
-  netsnmp_request_info* request;
+  netsnmp_request_info* request{nullptr};
 
   switch (reqinfo->mode) {
   case MODE_GET:
-    for (request = requests; request; request = request->next) {
+    for (request = requests; request != nullptr; request = request->next) {
       netsnmp_table_request_info* table_info = netsnmp_extract_table_info(request);
-      const DownstreamState* server = (const DownstreamState*)netsnmp_extract_iterator_context(request);
-
-      if (!server) {
+      // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): net-snmp API
+      const auto* server = reinterpret_cast<const DownstreamState*>(netsnmp_extract_iterator_context(request));
+      if (server == nullptr) {
         continue;
       }
 
@@ -304,7 +311,7 @@ static int backendStatTable_handler(netsnmp_mib_handler* handler,
         break;
       case COLUMN_BACKENDLATENCY:
         DNSDistSNMPAgent::setCounter64Value(request,
-                                            server->getRelevantLatencyUsec() / 1000.0);
+                                            static_cast<uint64_t>(server->getRelevantLatencyUsec() / 1000.0));
         break;
       case COLUMN_BACKENDWEIGHT:
         DNSDistSNMPAgent::setCounter64Value(request,
@@ -339,11 +346,11 @@ static int backendStatTable_handler(netsnmp_mib_handler* handler,
       }
       case COLUMN_BACKENDPOOLS: {
         std::string pools;
-        for (const auto& p : server->d_config.pools) {
+        for (const auto& pool : server->d_config.pools) {
           if (!pools.empty()) {
             pools += " ";
           }
-          pools += p;
+          pools += pool;
         }
         snmp_set_var_typed_value(request->requestvb,
                                  ASN_OCTET_STR,
@@ -352,7 +359,7 @@ static int backendStatTable_handler(netsnmp_mib_handler* handler,
         break;
       }
       case COLUMN_BACKENDQPS:
-        DNSDistSNMPAgent::setCounter64Value(request, server->queryLoad.load());
+        DNSDistSNMPAgent::setCounter64Value(request, static_cast<uint64_t>(server->queryLoad.load()));
         break;
       case COLUMN_BACKENDQUERIES:
         DNSDistSNMPAgent::setCounter64Value(request, server->queries.load());
@@ -384,26 +391,26 @@ bool DNSDistSNMPAgent::sendBackendStatusChangeTrap(const DownstreamState& dss)
                             snmpTrapOID.data(),
                             snmpTrapOID.size(),
                             ASN_OBJECT_ID,
-                            backendStatusChangeTrapOID,
-                            OID_LENGTH(backendStatusChangeTrapOID) * sizeof(oid));
+                            backendStatusChangeTrapOID.data(),
+                            backendStatusChangeTrapOID.size() * sizeof(oid));
 
   snmp_varlist_add_variable(&varList,
-                            backendNameOID,
-                            OID_LENGTH(backendNameOID),
+                            backendNameOID.data(),
+                            backendNameOID.size(),
                             ASN_OCTET_STR,
                             dss.getName().c_str(),
                             dss.getName().size());
 
   snmp_varlist_add_variable(&varList,
-                            backendAddressOID,
-                            OID_LENGTH(backendAddressOID),
+                            backendAddressOID.data(),
+                            backendAddressOID.size(),
                             ASN_OCTET_STR,
                             backendAddress.c_str(),
                             backendAddress.size());
 
   snmp_varlist_add_variable(&varList,
-                            backendStateOID,
-                            OID_LENGTH(backendStateOID),
+                            backendStateOID.data(),
+                            backendStateOID.size(),
                             ASN_OCTET_STR,
                             backendStatus.c_str(),
                             backendStatus.size());
@@ -423,12 +430,12 @@ bool DNSDistSNMPAgent::sendCustomTrap(const std::string& reason)
                             snmpTrapOID.data(),
                             snmpTrapOID.size(),
                             ASN_OBJECT_ID,
-                            customTrapOID,
-                            OID_LENGTH(customTrapOID) * sizeof(oid));
+                            customTrapOID.data(),
+                            customTrapOID.size() * sizeof(oid));
 
   snmp_varlist_add_variable(&varList,
-                            trapReasonOID,
-                            OID_LENGTH(trapReasonOID),
+                            trapReasonOID.data(),
+                            trapReasonOID.size(),
                             ASN_OCTET_STR,
                             reason.c_str(),
                             reason.size());
@@ -439,19 +446,19 @@ bool DNSDistSNMPAgent::sendCustomTrap(const std::string& reason)
 #endif /* HAVE_NET_SNMP */
 }
 
-bool DNSDistSNMPAgent::sendDNSTrap(const DNSQuestion& dq, const std::string& reason)
+bool DNSDistSNMPAgent::sendDNSTrap(const DNSQuestion& dnsQuestion, const std::string& reason)
 {
 #ifdef HAVE_NET_SNMP
-  std::string local = dq.ids.origDest.toString();
-  std::string remote = dq.ids.origRemote.toString();
-  std::string qname = dq.ids.qname.toStringNoDot();
-  const uint32_t socketFamily = dq.ids.origRemote.isIPv4() ? 1 : 2;
-  const uint32_t socketProtocol = dq.overTCP() ? 2 : 1;
-  const uint32_t queryType = dq.getHeader()->qr ? 2 : 1;
-  const uint32_t querySize = (uint32_t)dq.getData().size();
-  const uint32_t queryID = (uint32_t)ntohs(dq.getHeader()->id);
-  const uint32_t qType = (uint32_t)dq.ids.qtype;
-  const uint32_t qClass = (uint32_t)dq.ids.qclass;
+  std::string local = dnsQuestion.ids.origDest.toString();
+  std::string remote = dnsQuestion.ids.origRemote.toString();
+  std::string qname = dnsQuestion.ids.qname.toStringNoDot();
+  const uint32_t socketFamily = dnsQuestion.ids.origRemote.isIPv4() ? 1 : 2;
+  const uint32_t socketProtocol = dnsQuestion.overTCP() ? 2 : 1;
+  const uint32_t queryType = dnsQuestion.getHeader()->qr ? 2 : 1;
+  const auto querySize = static_cast<uint32_t>(dnsQuestion.getData().size());
+  const auto queryID = static_cast<uint32_t>(ntohs(dnsQuestion.getHeader()->id));
+  const auto qType = static_cast<uint32_t>(dnsQuestion.ids.qtype);
+  const auto qClass = static_cast<uint32_t>(dnsQuestion.ids.qclass);
 
   netsnmp_variable_list* varList = nullptr;
 
@@ -459,82 +466,89 @@ bool DNSDistSNMPAgent::sendDNSTrap(const DNSQuestion& dq, const std::string& rea
                             snmpTrapOID.data(),
                             snmpTrapOID.size(),
                             ASN_OBJECT_ID,
-                            actionTrapOID,
-                            OID_LENGTH(actionTrapOID) * sizeof(oid));
+                            actionTrapOID.data(),
+                            actionTrapOID.size() * sizeof(oid));
 
   snmp_varlist_add_variable(&varList,
-                            socketFamilyOID,
-                            OID_LENGTH(socketFamilyOID),
+                            socketFamilyOID.data(),
+                            socketFamilyOID.size(),
                             ASN_INTEGER,
+                            // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): net-snmp API
                             reinterpret_cast<const u_char*>(&socketFamily),
                             sizeof(socketFamily));
 
   snmp_varlist_add_variable(&varList,
-                            socketProtocolOID,
-                            OID_LENGTH(socketProtocolOID),
+                            socketProtocolOID.data(),
+                            socketProtocolOID.size(),
                             ASN_INTEGER,
+                            // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): net-snmp API
                             reinterpret_cast<const u_char*>(&socketProtocol),
                             sizeof(socketProtocol));
 
   snmp_varlist_add_variable(&varList,
-                            fromAddressOID,
-                            OID_LENGTH(fromAddressOID),
+                            fromAddressOID.data(),
+                            fromAddressOID.size(),
                             ASN_OCTET_STR,
                             remote.c_str(),
                             remote.size());
 
   snmp_varlist_add_variable(&varList,
-                            toAddressOID,
-                            OID_LENGTH(toAddressOID),
+                            toAddressOID.data(),
+                            toAddressOID.size(),
                             ASN_OCTET_STR,
                             local.c_str(),
                             local.size());
 
   snmp_varlist_add_variable(&varList,
-                            queryTypeOID,
-                            OID_LENGTH(queryTypeOID),
+                            queryTypeOID.data(),
+                            queryTypeOID.size(),
                             ASN_INTEGER,
+                            // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): net-snmp API
                             reinterpret_cast<const u_char*>(&queryType),
                             sizeof(queryType));
 
   snmp_varlist_add_variable(&varList,
-                            querySizeOID,
-                            OID_LENGTH(querySizeOID),
+                            querySizeOID.data(),
+                            querySizeOID.size(),
                             ASN_UNSIGNED,
+                            // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): net-snmp API
                             reinterpret_cast<const u_char*>(&querySize),
                             sizeof(querySize));
 
   snmp_varlist_add_variable(&varList,
-                            queryIDOID,
-                            OID_LENGTH(queryIDOID),
+                            queryIDOID.data(),
+                            queryIDOID.size(),
                             ASN_UNSIGNED,
+                            // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): net-snmp API
                             reinterpret_cast<const u_char*>(&queryID),
                             sizeof(queryID));
 
   snmp_varlist_add_variable(&varList,
-                            qNameOID,
-                            OID_LENGTH(qNameOID),
+                            qNameOID.data(),
+                            qNameOID.size(),
                             ASN_OCTET_STR,
                             qname.c_str(),
                             qname.size());
 
   snmp_varlist_add_variable(&varList,
-                            qClassOID,
-                            OID_LENGTH(qClassOID),
+                            qClassOID.data(),
+                            qClassOID.size(),
                             ASN_UNSIGNED,
+                            // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): net-snmp API
                             reinterpret_cast<const u_char*>(&qClass),
                             sizeof(qClass));
 
   snmp_varlist_add_variable(&varList,
-                            qTypeOID,
-                            OID_LENGTH(qTypeOID),
+                            qTypeOID.data(),
+                            qTypeOID.size(),
                             ASN_UNSIGNED,
+                            // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast): net-snmp API
                             reinterpret_cast<const u_char*>(&qType),
                             sizeof(qType));
 
   snmp_varlist_add_variable(&varList,
-                            trapReasonOID,
-                            OID_LENGTH(trapReasonOID),
+                            trapReasonOID.data(),
+                            trapReasonOID.size(),
                             ASN_OCTET_STR,
                             reason.c_str(),
                             reason.size());
@@ -550,61 +564,63 @@ DNSDistSNMPAgent::DNSDistSNMPAgent(const std::string& name, const std::string& d
 {
 #ifdef HAVE_NET_SNMP
 
-  registerCounter64Stat("queries", queriesOID, OID_LENGTH(queriesOID), &dnsdist::metrics::g_stats.queries);
-  registerCounter64Stat("responses", responsesOID, OID_LENGTH(responsesOID), &dnsdist::metrics::g_stats.responses);
-  registerCounter64Stat("servfailResponses", servfailResponsesOID, OID_LENGTH(servfailResponsesOID), &dnsdist::metrics::g_stats.servfailResponses);
-  registerCounter64Stat("aclDrops", aclDropsOID, OID_LENGTH(aclDropsOID), &dnsdist::metrics::g_stats.aclDrops);
-  registerCounter64Stat("ruleDrop", ruleDropOID, OID_LENGTH(ruleDropOID), &dnsdist::metrics::g_stats.ruleDrop);
-  registerCounter64Stat("ruleNXDomain", ruleNXDomainOID, OID_LENGTH(ruleNXDomainOID), &dnsdist::metrics::g_stats.ruleNXDomain);
-  registerCounter64Stat("ruleRefused", ruleRefusedOID, OID_LENGTH(ruleRefusedOID), &dnsdist::metrics::g_stats.ruleRefused);
-  registerCounter64Stat("ruleServFail", ruleServFailOID, OID_LENGTH(ruleServFailOID), &dnsdist::metrics::g_stats.ruleServFail);
-  registerCounter64Stat("ruleTruncated", ruleTruncatedOID, OID_LENGTH(ruleTruncatedOID), &dnsdist::metrics::g_stats.ruleTruncated);
-  registerCounter64Stat("selfAnswered", selfAnsweredOID, OID_LENGTH(selfAnsweredOID), &dnsdist::metrics::g_stats.selfAnswered);
-  registerCounter64Stat("downstreamTimeouts", downstreamTimeoutsOID, OID_LENGTH(downstreamTimeoutsOID), &dnsdist::metrics::g_stats.downstreamTimeouts);
-  registerCounter64Stat("downstreamSendErrors", downstreamSendErrorsOID, OID_LENGTH(downstreamSendErrorsOID), &dnsdist::metrics::g_stats.downstreamSendErrors);
-  registerCounter64Stat("truncFail", truncFailOID, OID_LENGTH(truncFailOID), &dnsdist::metrics::g_stats.truncFail);
-  registerCounter64Stat("noPolicy", noPolicyOID, OID_LENGTH(noPolicyOID), &dnsdist::metrics::g_stats.noPolicy);
-  registerCounter64Stat("latency0_1", latency0_1OID, OID_LENGTH(latency0_1OID), &dnsdist::metrics::g_stats.latency0_1);
-  registerCounter64Stat("latency1_10", latency1_10OID, OID_LENGTH(latency1_10OID), &dnsdist::metrics::g_stats.latency1_10);
-  registerCounter64Stat("latency10_50", latency10_50OID, OID_LENGTH(latency10_50OID), &dnsdist::metrics::g_stats.latency10_50);
-  registerCounter64Stat("latency50_100", latency50_100OID, OID_LENGTH(latency50_100OID), &dnsdist::metrics::g_stats.latency50_100);
-  registerCounter64Stat("latency100_1000", latency100_1000OID, OID_LENGTH(latency100_1000OID), &dnsdist::metrics::g_stats.latency100_1000);
-  registerCounter64Stat("latencySlow", latencySlowOID, OID_LENGTH(latencySlowOID), &dnsdist::metrics::g_stats.latencySlow);
-  registerCounter64Stat("nonCompliantQueries", nonCompliantQueriesOID, OID_LENGTH(nonCompliantQueriesOID), &dnsdist::metrics::g_stats.nonCompliantQueries);
-  registerCounter64Stat("nonCompliantResponses", nonCompliantResponsesOID, OID_LENGTH(nonCompliantResponsesOID), &dnsdist::metrics::g_stats.nonCompliantResponses);
-  registerCounter64Stat("rdQueries", rdQueriesOID, OID_LENGTH(rdQueriesOID), &dnsdist::metrics::g_stats.rdQueries);
-  registerCounter64Stat("emptyQueries", emptyQueriesOID, OID_LENGTH(emptyQueriesOID), &dnsdist::metrics::g_stats.emptyQueries);
-  registerCounter64Stat("cacheHits", cacheHitsOID, OID_LENGTH(cacheHitsOID), &dnsdist::metrics::g_stats.cacheHits);
-  registerCounter64Stat("cacheMisses", cacheMissesOID, OID_LENGTH(cacheMissesOID), &dnsdist::metrics::g_stats.cacheMisses);
-  registerCounter64Stat("dynBlocked", dynBlockedOID, OID_LENGTH(dynBlockedOID), &dnsdist::metrics::g_stats.dynBlocked);
-  registerFloatStat("latencyAvg100", latencyAvg100OID, OID_LENGTH(latencyAvg100OID), &dnsdist::metrics::g_stats.latencyAvg100);
-  registerFloatStat("latencyAvg1000", latencyAvg1000OID, OID_LENGTH(latencyAvg1000OID), &dnsdist::metrics::g_stats.latencyAvg1000);
-  registerFloatStat("latencyAvg10000", latencyAvg10000OID, OID_LENGTH(latencyAvg10000OID), &dnsdist::metrics::g_stats.latencyAvg10000);
-  registerFloatStat("latencyAvg1000000", latencyAvg1000000OID, OID_LENGTH(latencyAvg1000000OID), &dnsdist::metrics::g_stats.latencyAvg1000000);
-  registerGauge64Stat("uptime", uptimeOID, OID_LENGTH(uptimeOID), &uptimeOfProcess);
-  registerGauge64Stat("specialMemoryUsage", specialMemoryUsageOID, OID_LENGTH(specialMemoryUsageOID), &getSpecialMemoryUsage);
-  registerGauge64Stat("cpuUserMSec", cpuUserMSecOID, OID_LENGTH(cpuUserMSecOID), &getCPUTimeUser);
-  registerGauge64Stat("cpuSysMSec", cpuSysMSecOID, OID_LENGTH(cpuSysMSecOID), &getCPUTimeSystem);
-  registerGauge64Stat("fdUsage", fdUsageOID, OID_LENGTH(fdUsageOID), &getOpenFileDescriptors);
-  registerGauge64Stat("dynBlockedNMGSize", dynBlockedNMGSizeOID, OID_LENGTH(dynBlockedNMGSizeOID), [](const std::string&) { return g_dynblockNMG.getLocal()->size(); });
-  registerGauge64Stat("securityStatus", securityStatusOID, OID_LENGTH(securityStatusOID), [](const std::string&) { return dnsdist::metrics::g_stats.securityStatus.load(); });
-  registerGauge64Stat("realMemoryUsage", realMemoryUsageOID, OID_LENGTH(realMemoryUsageOID), &getRealMemoryUsage);
-
-  netsnmp_table_registration_info* table_info = SNMP_MALLOC_TYPEDEF(netsnmp_table_registration_info);
+  registerCounter64Stat("queries", queriesOID, &dnsdist::metrics::g_stats.queries);
+  registerCounter64Stat("responses", responsesOID, &dnsdist::metrics::g_stats.responses);
+  registerCounter64Stat("servfailResponses", servfailResponsesOID, &dnsdist::metrics::g_stats.servfailResponses);
+  registerCounter64Stat("aclDrops", aclDropsOID, &dnsdist::metrics::g_stats.aclDrops);
+  registerCounter64Stat("ruleDrop", ruleDropOID, &dnsdist::metrics::g_stats.ruleDrop);
+  registerCounter64Stat("ruleNXDomain", ruleNXDomainOID, &dnsdist::metrics::g_stats.ruleNXDomain);
+  registerCounter64Stat("ruleRefused", ruleRefusedOID, &dnsdist::metrics::g_stats.ruleRefused);
+  registerCounter64Stat("ruleServFail", ruleServFailOID, &dnsdist::metrics::g_stats.ruleServFail);
+  registerCounter64Stat("ruleTruncated", ruleTruncatedOID, &dnsdist::metrics::g_stats.ruleTruncated);
+  registerCounter64Stat("selfAnswered", selfAnsweredOID, &dnsdist::metrics::g_stats.selfAnswered);
+  registerCounter64Stat("downstreamTimeouts", downstreamTimeoutsOID, &dnsdist::metrics::g_stats.downstreamTimeouts);
+  registerCounter64Stat("downstreamSendErrors", downstreamSendErrorsOID, &dnsdist::metrics::g_stats.downstreamSendErrors);
+  registerCounter64Stat("truncFail", truncFailOID, &dnsdist::metrics::g_stats.truncFail);
+  registerCounter64Stat("noPolicy", noPolicyOID, &dnsdist::metrics::g_stats.noPolicy);
+  registerCounter64Stat("latency0_1", latency0_1OID, &dnsdist::metrics::g_stats.latency0_1);
+  registerCounter64Stat("latency1_10", latency1_10OID, &dnsdist::metrics::g_stats.latency1_10);
+  registerCounter64Stat("latency10_50", latency10_50OID, &dnsdist::metrics::g_stats.latency10_50);
+  registerCounter64Stat("latency50_100", latency50_100OID, &dnsdist::metrics::g_stats.latency50_100);
+  registerCounter64Stat("latency100_1000", latency100_1000OID, &dnsdist::metrics::g_stats.latency100_1000);
+  registerCounter64Stat("latencySlow", latencySlowOID, &dnsdist::metrics::g_stats.latencySlow);
+  registerCounter64Stat("nonCompliantQueries", nonCompliantQueriesOID, &dnsdist::metrics::g_stats.nonCompliantQueries);
+  registerCounter64Stat("nonCompliantResponses", nonCompliantResponsesOID, &dnsdist::metrics::g_stats.nonCompliantResponses);
+  registerCounter64Stat("rdQueries", rdQueriesOID, &dnsdist::metrics::g_stats.rdQueries);
+  registerCounter64Stat("emptyQueries", emptyQueriesOID, &dnsdist::metrics::g_stats.emptyQueries);
+  registerCounter64Stat("cacheHits", cacheHitsOID, &dnsdist::metrics::g_stats.cacheHits);
+  registerCounter64Stat("cacheMisses", cacheMissesOID, &dnsdist::metrics::g_stats.cacheMisses);
+  registerCounter64Stat("dynBlocked", dynBlockedOID, &dnsdist::metrics::g_stats.dynBlocked);
+  registerFloatStat("latencyAvg100", latencyAvg100OID, &dnsdist::metrics::g_stats.latencyAvg100);
+  registerFloatStat("latencyAvg1000", latencyAvg1000OID, &dnsdist::metrics::g_stats.latencyAvg1000);
+  registerFloatStat("latencyAvg10000", latencyAvg10000OID, &dnsdist::metrics::g_stats.latencyAvg10000);
+  registerFloatStat("latencyAvg1000000", latencyAvg1000000OID, &dnsdist::metrics::g_stats.latencyAvg1000000);
+  registerGauge64Stat("uptime", uptimeOID, &uptimeOfProcess);
+  registerGauge64Stat("specialMemoryUsage", specialMemoryUsageOID, &getSpecialMemoryUsage);
+  registerGauge64Stat("cpuUserMSec", cpuUserMSecOID, &getCPUTimeUser);
+  registerGauge64Stat("cpuSysMSec", cpuSysMSecOID, &getCPUTimeSystem);
+  registerGauge64Stat("fdUsage", fdUsageOID, &getOpenFileDescriptors);
+  registerGauge64Stat("dynBlockedNMGSize", dynBlockedNMGSizeOID, [](const std::string&) { return g_dynblockNMG.getLocal()->size(); });
+  registerGauge64Stat("securityStatus", securityStatusOID, [](const std::string&) { return dnsdist::metrics::g_stats.securityStatus.load(); });
+  registerGauge64Stat("realMemoryUsage", realMemoryUsageOID, &getRealMemoryUsage);
+
+  // NOLINTNEXTLINE(cppcoreguidelines-owning-memory): net-snmp API
+  auto* table_info = SNMP_MALLOC_TYPEDEF(netsnmp_table_registration_info);
   netsnmp_table_helper_add_indexes(table_info,
                                    ASN_GAUGE, /* index: backendId */
                                    0);
   table_info->min_column = COLUMN_BACKENDNAME;
   table_info->max_column = COLUMN_BACKENDORDER;
-  netsnmp_iterator_info* iinfo = SNMP_MALLOC_TYPEDEF(netsnmp_iterator_info);
+  // NOLINTNEXTLINE(cppcoreguidelines-owning-memory): net-snmp API
+  auto* iinfo = SNMP_MALLOC_TYPEDEF(netsnmp_iterator_info);
   iinfo->get_first_data_point = backendStatTable_get_first_data_point;
   iinfo->get_next_data_point = backendStatTable_get_next_data_point;
   iinfo->table_reginfo = table_info;
 
   netsnmp_register_table_iterator(netsnmp_create_handler_registration("backendStatTable",
                                                                       backendStatTable_handler,
-                                                                      backendStatTableOID,
-                                                                      OID_LENGTH(backendStatTableOID),
+                                                                      backendStatTableOID.data(),
+                                                                      backendStatTableOID.size(),
                                                                       HANDLER_CAN_RONLY),
                                   iinfo);
 
index 064e0e8678815b84ae63f3f63939a2487dc79ed9..5f3bb816288f202f5d98e699a497849ab4c1ac84 100644 (file)
@@ -1248,7 +1248,7 @@ bool checkDNSCryptQuery(const ClientState& cs, PacketBuffer& query, std::unique_
 
 extern bool g_snmpEnabled;
 extern bool g_snmpTrapsEnabled;
-extern DNSDistSNMPAgent* g_snmpAgent;
+extern std::unique_ptr<DNSDistSNMPAgent> g_snmpAgent;
 extern bool g_addEDNSToSelfGeneratedResponses;
 
 extern std::set<std::string> g_capabilitiesToRetain;
index bcb73b26529cd858245f22dd9aae0fd6e933e0c7..fb74a16264e9d60cdcd60d7349af2974d78ae885 100644 (file)
@@ -19,7 +19,7 @@ LockGuarded<LuaContext> g_lua{LuaContext()};
 
 bool g_snmpEnabled{false};
 bool g_snmpTrapsEnabled{false};
-DNSDistSNMPAgent* g_snmpAgent{nullptr};
+std::unique_ptr<DNSDistSNMPAgent> g_snmpAgent{nullptr};
 
 #if BENCH_POLICIES
 bool g_verbose{true};