]> git.ipfire.org Git - thirdparty/pdns.git/commitdiff
Reformat with clang-format 10998/head
authorOtto Moerbeek <otto.moerbeek@open-xchange.com>
Tue, 11 Jan 2022 10:39:46 +0000 (11:39 +0100)
committerOtto Moerbeek <otto.moerbeek@open-xchange.com>
Tue, 11 Jan 2022 10:51:19 +0000 (11:51 +0100)
pdns/pdns_recursor.cc
pdns/recursordist/Makefile.am
pdns/recursordist/rec-main.cc
pdns/recursordist/rec-main.hh
pdns/recursordist/rec-tcp.cc

index 94fc94fc73ad8b7f5a66851c6a0a1c5219b073a5..fc5d5156b3fa73ba274c7ac7dc38f0ea876e2421 100644 (file)
@@ -48,7 +48,6 @@ thread_local std::shared_ptr<Regex> t_traceRegex;
 thread_local std::shared_ptr<std::vector<std::unique_ptr<RemoteLogger>>> t_protobufServers{nullptr};
 thread_local std::shared_ptr<std::vector<std::unique_ptr<RemoteLogger>>> t_outgoingProtobufServers{nullptr};
 
-
 thread_local std::unique_ptr<MT_t> MT; // the big MTasker
 std::unique_ptr<MemRecursorCache> g_recCache;
 std::unique_ptr<NegCache> g_negCache;
@@ -56,13 +55,12 @@ std::unique_ptr<NegCache> g_negCache;
 thread_local std::unique_ptr<RecursorPacketCache> t_packetCache;
 thread_local FDMultiplexer* t_fdm{nullptr};
 thread_local std::unique_ptr<addrringbuf_t> t_remotes, t_servfailremotes, t_largeanswerremotes, t_bogusremotes;
-thread_local std::unique_ptr<boost::circular_buffer<pair<DNSName, uint16_t> > > t_queryring, t_servfailqueryring, t_bogusqueryring;
+thread_local std::unique_ptr<boost::circular_buffer<pair<DNSName, uint16_t>>> t_queryring, t_servfailqueryring, t_bogusqueryring;
 thread_local std::shared_ptr<NetmaskGroup> t_allowFrom;
 thread_local std::shared_ptr<NetmaskGroup> t_allowNotifyFrom;
 thread_local std::shared_ptr<notifyset_t> t_allowNotifyFor;
 __thread struct timeval g_now; // timestamp, updated (too) frequently
 
-
 typedef map<int, ComboAddress> listenSocketsAddresses_t; // is shared across all threads right now
 
 static listenSocketsAddresses_t g_listenSocketsAddresses; // is shared across all threads right now
@@ -104,105 +102,104 @@ GlobalStateHolder<SuffixMatchNode> g_DoTToAuthNames;
 uint64_t g_latencyStatSize;
 
 LWResult::Result UDPClientSocks::getSocket(const ComboAddress& toaddr, int* fd)
-  {
-    *fd = makeClientSocket(toaddr.sin4.sin_family);
-    if(*fd < 0) { // temporary error - receive exception otherwise
-      return LWResult::Result::OSLimitError;
-    }
-
-    if(connect(*fd, (struct sockaddr*)(&toaddr), toaddr.getSocklen()) < 0) {
-      int err = errno;
-      try {
-        closesocket(*fd);
-      }
-      catch(const PDNSException& e) {
-        g_log<<Logger::Error<<"Error closing UDP socket after connect() failed: "<<e.reason<<endl;
-      }
-
-      if (err == ENETUNREACH) { // Seth "My Interfaces Are Like A Yo Yo" Arnold special
-        return LWResult::Result::OSLimitError;
-      }
-
-      return LWResult::Result::PermanentError;
-    }
-
-    d_numsocks++;
-    return LWResult::Result::Success;
+{
+  *fd = makeClientSocket(toaddr.sin4.sin_family);
+  if (*fd < 0) { // temporary error - receive exception otherwise
+    return LWResult::Result::OSLimitError;
   }
 
-  // return a socket to the pool, or simply erase it
-void UDPClientSocks::returnSocket(int fd)
-  {
+  if (connect(*fd, (struct sockaddr*)(&toaddr), toaddr.getSocklen()) < 0) {
+    int err = errno;
     try {
-      t_fdm->removeReadFD(fd);
+      closesocket(*fd);
     }
-    catch(const FDMultiplexerException& e) {
-      // we sometimes return a socket that has not yet been assigned to t_fdm
+    catch (const PDNSException& e) {
+      g_log << Logger::Error << "Error closing UDP socket after connect() failed: " << e.reason << endl;
     }
 
-    try {
-      closesocket(fd);
-    }
-    catch(const PDNSException& e) {
-      g_log<<Logger::Error<<"Error closing returned UDP socket: "<<e.reason<<endl;
+    if (err == ENETUNREACH) { // Seth "My Interfaces Are Like A Yo Yo" Arnold special
+      return LWResult::Result::OSLimitError;
     }
 
-    --d_numsocks;
+    return LWResult::Result::PermanentError;
   }
 
+  d_numsocks++;
+  return LWResult::Result::Success;
+}
 
-  // returns -1 for errors which might go away, throws for ones that won't
+// return a socket to the pool, or simply erase it
+void UDPClientSocks::returnSocket(int fd)
+{
+  try {
+    t_fdm->removeReadFD(fd);
+  }
+  catch (const FDMultiplexerException& e) {
+    // we sometimes return a socket that has not yet been assigned to t_fdm
+  }
+
+  try {
+    closesocket(fd);
+  }
+  catch (const PDNSException& e) {
+    g_log << Logger::Error << "Error closing returned UDP socket: " << e.reason << endl;
+  }
+
+  --d_numsocks;
+}
+
+// returns -1 for errors which might go away, throws for ones that won't
 int UDPClientSocks::makeClientSocket(int family)
-  {
-    int ret = socket(family, SOCK_DGRAM, 0); // turns out that setting CLO_EXEC and NONBLOCK from here is not a performance win on Linux (oddly enough)
+{
+  int ret = socket(family, SOCK_DGRAM, 0); // turns out that setting CLO_EXEC and NONBLOCK from here is not a performance win on Linux (oddly enough)
 
-    if (ret < 0 && errno ==  EMFILE) { // this is not a catastrophic error
-      return ret;
-    }
-    if (ret < 0) {
-      throw PDNSException("Making a socket for resolver (family = " + std::to_string(family) + "): " + stringerror());
-    }
+  if (ret < 0 && errno == EMFILE) { // this is not a catastrophic error
+    return ret;
+  }
+  if (ret < 0) {
+    throw PDNSException("Making a socket for resolver (family = " + std::to_string(family) + "): " + stringerror());
+  }
 
-    // The loop below runs the body with [tries-1 tries-2 ... 1]. Last iteration with tries == 1 is special: it uses a kernel
-    // allocated UDP port.
-#if !defined( __OpenBSD__)
-    int tries = 10;
+  // The loop below runs the body with [tries-1 tries-2 ... 1]. Last iteration with tries == 1 is special: it uses a kernel
+  // allocated UDP port.
+#if !defined(__OpenBSD__)
+  int tries = 10;
 #else
-    int tries = 2; // hit the reliable kernel random case for OpenBSD immediately (because it will match tries==1 below), using sysctl net.inet.udp.baddynamic to exclude ports
+  int tries = 2; // hit the reliable kernel random case for OpenBSD immediately (because it will match tries==1 below), using sysctl net.inet.udp.baddynamic to exclude ports
 #endif
-    ComboAddress sin;
-    while (--tries) {
-      in_port_t port;
-
-      if (tries == 1) {  // last iteration: fall back to kernel 'random'
-        port = 0;
-      } else {
-        do {
-          port = s_minUdpSourcePort + dns_random(s_maxUdpSourcePort - s_minUdpSourcePort + 1);
-        } while (s_avoidUdpSourcePorts.count(port));
-      }
+  ComboAddress sin;
+  while (--tries) {
+    in_port_t port;
 
-      sin = pdns::getQueryLocalAddress(family, port); // does htons for us
-      if (::bind(ret, reinterpret_cast<struct sockaddr*>(&sin), sin.getSocklen()) >= 0)
-        break;
+    if (tries == 1) { // last iteration: fall back to kernel 'random'
+      port = 0;
     }
-
-    if (!tries) {
-      closesocket(ret);
-      throw PDNSException("Resolver binding to local query client socket on " + sin.toString() + ": " + stringerror());
+    else {
+      do {
+        port = s_minUdpSourcePort + dns_random(s_maxUdpSourcePort - s_minUdpSourcePort + 1);
+      } while (s_avoidUdpSourcePorts.count(port));
     }
 
-    try {
-      setReceiveSocketErrors(ret, family);
-      setNonBlocking(ret);
-    }
-    catch (...) {
-      closesocket(ret);
-      throw;
-    }
-    return ret;
+    sin = pdns::getQueryLocalAddress(family, port); // does htons for us
+    if (::bind(ret, reinterpret_cast<struct sockaddr*>(&sin), sin.getSocklen()) >= 0)
+      break;
+  }
+
+  if (!tries) {
+    closesocket(ret);
+    throw PDNSException("Resolver binding to local query client socket on " + sin.toString() + ": " + stringerror());
   }
 
+  try {
+    setReceiveSocketErrors(ret, family);
+    setNonBlocking(ret);
+  }
+  catch (...) {
+    closesocket(ret);
+    throw;
+  }
+  return ret;
+}
 
 static void handleGenUDPQueryResponse(int fd, FDMultiplexer::funcparam_t& var)
 {
@@ -212,14 +209,13 @@ static void handleGenUDPQueryResponse(int fd, FDMultiplexer::funcparam_t& var)
   ComboAddress fromaddr;
   socklen_t addrlen = sizeof(fromaddr);
 
-  ssize_t ret = recvfrom(fd, resp.data(), resp.size(), 0, (sockaddr *)&fromaddr, &addrlen);
+  ssize_t ret = recvfrom(fd, resp.data(), resp.size(), 0, (sockaddr*)&fromaddr, &addrlen);
   if (fromaddr != pident->remote) {
-    g_log<<Logger::Notice<<"Response received from the wrong remote host ("<<fromaddr.toStringWithPort()<<" instead of "<<pident->remote.toStringWithPort()<<"), discarding"<<endl;
-
+    g_log << Logger::Notice << "Response received from the wrong remote host (" << fromaddr.toStringWithPort() << " instead of " << pident->remote.toStringWithPort() << "), discarding" << endl;
   }
 
   t_fdm->removeReadFD(fd);
-  if(ret >= 0) {
+  if (ret >= 0) {
     MT->sendEvent(pident, &resp);
   }
   else {
@@ -246,12 +242,12 @@ PacketBuffer GenUDPQueryResponse(const ComboAddress& dest, const string& query)
   t_fdm->addReadFD(s.getHandle(), handleGenUDPQueryResponse, pident);
 
   PacketBuffer data;
-  int ret=MT->waitEvent(pident, &data, g_networkTimeoutMsec);
+  int ret = MT->waitEvent(pident, &data, g_networkTimeoutMsec);
 
-  if (!ret || ret==-1) { // timeout
+  if (!ret || ret == -1) { // timeout
     t_fdm->removeReadFD(s.getHandle());
   }
-  else if(data.empty()) {// error, EOF or other
+  else if (data.empty()) { // error, EOF or other
     // we could special case this
     return data;
   }
@@ -260,11 +256,10 @@ PacketBuffer GenUDPQueryResponse(const ComboAddress& dest, const string& query)
 
 static void handleUDPServerResponse(int fd, FDMultiplexer::funcparam_t&);
 
-
 thread_local std::unique_ptr<UDPClientSocks> t_udpclientsocks;
 
 /* these two functions are used by LWRes */
-LWResult::Result asendto(const char *data, size_t len, int flags,
+LWResult::Result asendto(const chardata, size_t len, int flags,
                          const ComboAddress& toaddr, uint16_t id, const DNSName& domain, uint16_t qtype, int* fd)
 {
 
@@ -275,15 +270,15 @@ LWResult::Result asendto(const char *data, size_t len, int flags,
 
   // see if there is an existing outstanding request we can chain on to, using partial equivalence function looking for the same
   // query (qname and qtype) to the same host, but with a different message ID
-  pair<MT_t::waiters_t::iterator, MT_t::waiters_t::iterator> chain=MT->d_waiters.equal_range(pident, PacketIDBirthdayCompare());
+  pair<MT_t::waiters_t::iterator, MT_t::waiters_t::iterator> chain = MT->d_waiters.equal_range(pident, PacketIDBirthdayCompare());
 
-  for(; chain.first != chain.second; chain.first++) {
+  for (; chain.first != chain.second; chain.first++) {
     // Line below detected an issue with the two ways of ordering PackeIDs (birtday and non-birthday)
     assert(chain.first->key->domain == pident->domain);
-    if(chain.first->key->fd > -1 && !chain.first->key->closed) { // don't chain onto existing chained waiter or a chain already processed
-      //cerr << "Insert " << id << ' ' << pident << " into chain for  " << chain.first->key << endl;
+    if (chain.first->key->fd > -1 && !chain.first->key->closed) { // don't chain onto existing chained waiter or a chain already processed
+      // cerr << "Insert " << id << ' ' << pident << " into chain for  " << chain.first->key << endl;
       chain.first->key->chain.insert(id); // we can chain
-      *fd = -1;                            // gets used in waitEvent / sendEvent later on
+      *fd = -1; // gets used in waitEvent / sendEvent later on
       return LWResult::Result::Success;
     }
   }
@@ -293,8 +288,8 @@ LWResult::Result asendto(const char *data, size_t len, int flags,
     return ret;
   }
 
-  pident->fd=*fd;
-  pident->id=id;
+  pident->fd = *fd;
+  pident->id = id;
 
   t_fdm->addReadFD(*fd, handleUDPServerResponse, pident);
   ssize_t sent = send(*fd, data, len, 0);
@@ -310,7 +305,7 @@ LWResult::Result asendto(const char *data, size_t len, int flags,
   return LWResult::Result::Success;
 }
 
-LWResult::Result arecvfrom(PacketBuffer& packet, int flags, const ComboAddress& fromaddr, size_t *d_len,
+LWResult::Result arecvfrom(PacketBuffer& packet, int flags, const ComboAddress& fromaddr, size_td_len,
                            uint16_t id, const DNSName& domain, uint16_t qtype, int fd, const struct timeval* now)
 {
   static const unsigned int nearMissLimit = ::arg().asNum("spoof-nearmiss-max");
@@ -322,7 +317,7 @@ LWResult::Result arecvfrom(PacketBuffer& packet, int flags, const ComboAddress&
   pident->type = qtype;
   pident->remote = fromaddr;
 
-  int ret=MT->waitEvent(pident, &packet, g_networkTimeoutMsec, now);
+  int ret = MT->waitEvent(pident, &packet, g_networkTimeoutMsec, now);
 
   /* -1 means error, 0 means timeout, 1 means a result from handleUDPServerResponse() which might still be an error */
   if (ret > 0) {
@@ -331,12 +326,12 @@ LWResult::Result arecvfrom(PacketBuffer& packet, int flags, const ComboAddress&
       return LWResult::Result::PermanentError;
     }
 
-    *d_len=packet.size();
+    *d_len = packet.size();
 
     if (nearMissLimit > 0 && pident->nearMisses > nearMissLimit) {
       /* we have received more than nearMissLimit answers on the right IP and port, from the right source (we are using connected sockets),
          for the correct qname and qtype, but with an unexpected message ID. That looks like a spoofing attempt. */
-      g_log<<Logger::Error<<"Too many ("<<pident->nearMisses<<" > "<<nearMissLimit<<") answers with a wrong message ID for '"<<domain<<"' from "<<fromaddr.toString()<<", assuming spoof attempt."<<endl;
+      g_log << Logger::Error << "Too many (" << pident->nearMisses << " > " << nearMissLimit << ") answers with a wrong message ID for '" << domain << "' from " << fromaddr.toString() << ", assuming spoof attempt." << endl;
       g_stats.spoofCount++;
       return LWResult::Result::Spoofed;
     }
@@ -353,20 +348,16 @@ LWResult::Result arecvfrom(PacketBuffer& packet, int flags, const ComboAddress&
   return ret == 0 ? LWResult::Result::Timeout : LWResult::Result::PermanentError;
 }
 
-
-
-
-
 // the idea is, only do things that depend on the *response* here. Incoming accounting is on incoming.
 static void updateResponseStats(int res, const ComboAddress& remote, unsigned int packetsize, const DNSName* query, uint16_t qtype)
 {
-  if(packetsize > 1000 && t_largeanswerremotes)
+  if (packetsize > 1000 && t_largeanswerremotes)
     t_largeanswerremotes->push_back(remote);
-  switch(res) {
+  switch (res) {
   case RCode::ServFail:
-    if(t_servfailremotes) {
+    if (t_servfailremotes) {
       t_servfailremotes->push_back(remote);
-      if(query && t_servfailqueryring) // packet cache
+      if (query && t_servfailqueryring) // packet cache
         t_servfailqueryring->push_back({*query, qtype});
     }
     g_stats.servFails++;
@@ -381,16 +372,13 @@ static void updateResponseStats(int res, const ComboAddress& remote, unsigned in
 }
 
 static string makeLoginfo(const std::unique_ptr<DNSComboWriter>& dc)
-try
-{
-  return "("+dc->d_mdp.d_qname.toLogString()+"/"+DNSRecordContent::NumberToType(dc->d_mdp.d_qtype)+" from "+(dc->getRemote())+")";
+try {
+  return "(" + dc->d_mdp.d_qname.toLogString() + "/" + DNSRecordContent::NumberToType(dc->d_mdp.d_qtype) + " from " + (dc->getRemote()) + ")";
 }
-catch(...)
-{
+catch (...) {
   return "Exception making error message for exception";
 }
 
-
 /**
  * Chases the CNAME provided by the PolicyCustom RPZ policy.
  *
@@ -408,7 +396,7 @@ static void handleRPZCustom(const DNSRecord& spoofed, const QType& qtype, SyncRe
     vector<DNSRecord> ans;
     res = sr.beginResolve(DNSName(spoofed.d_content->getZoneRepresentation()), qtype, QClass::IN, ans);
     for (const auto& rec : ans) {
-      if(rec.d_place == DNSResourceRecord::ANSWER) {
+      if (rec.d_place == DNSResourceRecord::ANSWER) {
         ret.push_back(rec);
       }
     }
@@ -421,14 +409,14 @@ static bool addRecordToPacket(DNSPacketWriter& pw, const DNSRecord& rec, uint32_
 {
   pw.startRecord(rec.d_name, rec.d_type, (rec.d_ttl > ttlCap ? ttlCap : rec.d_ttl), rec.d_class, rec.d_place);
 
-  if(rec.d_type != QType::OPT) // their TTL ain't real
+  if (rec.d_type != QType::OPT) // their TTL ain't real
     minTTL = min(minTTL, rec.d_ttl);
 
   rec.d_content->toPacket(pw);
-  if(pw.size() > static_cast<size_t>(maxAnswerSize)) {
+  if (pw.size() > static_cast<size_t>(maxAnswerSize)) {
     pw.rollback();
-    if(rec.d_place != DNSResourceRecord::ADDITIONAL) {
-      pw.getHeader()->tc=1;
+    if (rec.d_place != DNSResourceRecord::ADDITIONAL) {
+      pw.getHeader()->tc = 1;
       pw.truncate();
     }
     return false;
@@ -443,14 +431,18 @@ static bool addRecordToPacket(DNSPacketWriter& pw, const DNSRecord& rec, uint32_
  * that. You can also signal that the TCP connection must be closed
  * once the in-flight connections drop to zero.
  **/
-class RunningResolveGuard {
+class RunningResolveGuard
+{
 public:
-  RunningResolveGuard(std::unique_ptr<DNSComboWriter>& dc) : d_dc(dc) {
+  RunningResolveGuard(std::unique_ptr<DNSComboWriter>& dc) :
+    d_dc(dc)
+  {
     if (d_dc->d_tcp && !d_dc->d_tcpConnection) {
       throw std::runtime_error("incoming TCP case without TCP connection");
     }
   }
-  ~RunningResolveGuard() {
+  ~RunningResolveGuard()
+  {
     if (!d_handled && d_dc->d_tcp) {
       try {
         finishTCPReply(d_dc, false, true);
@@ -459,20 +451,28 @@ public:
       }
     }
   }
-  void setHandled() {
+  void setHandled()
+  {
     d_handled = true;
   }
-  void setDropOnIdle() {
+  void setDropOnIdle()
+  {
     if (d_dc->d_tcp) {
       d_dc->d_tcpConnection->setDropOnIdle();
     }
   }
+
 private:
   std::unique_ptr<DNSComboWriter>& d_dc;
   bool d_handled{false};
 };
 
-enum class PolicyResult : uint8_t { NoAction, HaveAnswer, Drop };
+enum class PolicyResult : uint8_t
+{
+  NoAction,
+  HaveAnswer,
+  Drop
+};
 
 static PolicyResult handlePolicyHit(const DNSFilterEngine::Policy& appliedPolicy, const std::unique_ptr<DNSComboWriter>& dc, SyncRes& sr, int& res, vector<DNSRecord>& ret, DNSPacketWriter& pw, RunningResolveGuard& tcpGuard)
 {
@@ -482,7 +482,7 @@ static PolicyResult handlePolicyHit(const DNSFilterEngine::Policy& appliedPolicy
     ++(g_stats.policyHits.lock()->operator[](appliedPolicy.getName()));
   }
 
-  if (sr.doLog() &&  appliedPolicy.d_type != DNSFilterEngine::PolicyType::None) {
+  if (sr.doLog() && appliedPolicy.d_type != DNSFilterEngine::PolicyType::None) {
     g_log << Logger::Warning << dc->d_mdp.d_qname << "|" << QType(dc->d_mdp.d_qtype) << appliedPolicy.getLogString() << endl;
   }
 
@@ -494,7 +494,7 @@ static PolicyResult handlePolicyHit(const DNSFilterEngine::Policy& appliedPolicy
   switch (appliedPolicy.d_kind) {
 
   case DNSFilterEngine::PolicyKind::NoAction:
-      return PolicyResult::NoAction;
+    return PolicyResult::NoAction;
 
   case DNSFilterEngine::PolicyKind::Drop:
     tcpGuard.setDropOnIdle();
@@ -531,7 +531,7 @@ static PolicyResult handlePolicyHit(const DNSFilterEngine::Policy& appliedPolicy
         }
         catch (const ImmediateServFailException& e) {
           if (g_logCommonErrors) {
-            g_log << Logger::Notice << "Sending SERVFAIL to " << dc->getRemote() << " during resolve of the custom filter policy '" << appliedPolicy.getName() << "' while resolving '"<<dc->d_mdp.d_qname<<"' because: "<<e.reason<<endl;
+            g_log << Logger::Notice << "Sending SERVFAIL to " << dc->getRemote() << " during resolve of the custom filter policy '" << appliedPolicy.getName() << "' while resolving '" << dc->d_mdp.d_qname << "' because: " << e.reason << endl;
           }
           res = RCode::ServFail;
           break;
@@ -552,7 +552,6 @@ static PolicyResult handlePolicyHit(const DNSFilterEngine::Policy& appliedPolicy
   return PolicyResult::NoAction;
 }
 
-
 #ifdef NOD_ENABLED
 static bool nodCheckNewDomain(const shared_ptr<Logr::Logger>& nodlogger, const DNSName& dname)
 {
@@ -563,7 +562,7 @@ static bool nodCheckNewDomain(const shared_ptr<Logr::Logger>& nodlogger, const D
     if (t_nodDBp && t_nodDBp->isNewDomain(dname)) {
       if (g_nodLog) {
         // This should probably log to a dedicated log file
-        SLOG(g_log<<Logger::Notice<<"Newly observed domain nod="<<dname<<endl,
+        SLOG(g_log << Logger::Notice << "Newly observed domain nod=" << dname << endl,
              nodlogger->info(Logr::Notice, "New domain observed"));
       }
       ret = true;
@@ -580,7 +579,7 @@ static void sendNODLookup(const shared_ptr<Logr::Logger>& nodlogger, const DNSNa
     try {
       qname = dname + g_nodLookupDomain;
     }
-    catch(const std::range_error &e) {
+    catch (const std::range_error& e) {
       nodlogger->v(10)->error(Logr::Error, "DNSName too long", "Unable to send NOD lookup");
       ++g_stats.nodLookupsDroppedOversize;
       return;
@@ -594,22 +593,19 @@ static void sendNODLookup(const shared_ptr<Logr::Logger>& nodlogger, const DNSNa
 static bool udrCheckUniqueDNSRecord(const shared_ptr<Logr::Logger>& nodlogger, const DNSName& dname, uint16_t qtype, const DNSRecord& record)
 {
   bool ret = false;
-  if (record.d_place == DNSResourceRecord::ANSWER ||
-      record.d_place == DNSResourceRecord::ADDITIONAL) {
+  if (record.d_place == DNSResourceRecord::ANSWER || record.d_place == DNSResourceRecord::ADDITIONAL) {
     // Create a string that represent a triplet of (qname, qtype and RR[type, name, content])
     std::stringstream ss;
-    ss << dname.toDNSStringLC() << ":" << qtype <<  ":" << qtype << ":" << record.d_type << ":" << record.d_name.toDNSStringLC() << ":" << record.d_content->getZoneRepresentation();
+    ss << dname.toDNSStringLC() << ":" << qtype << ":" << qtype << ":" << record.d_type << ":" << record.d_name.toDNSStringLC() << ":" << record.d_content->getZoneRepresentation();
     if (t_udrDBp && t_udrDBp->isUniqueResponse(ss.str())) {
-      if (g_udrLog) {  
+      if (g_udrLog) {
         // This should also probably log to a dedicated file.
-        SLOG(g_log<<Logger::Notice<<"Unique response observed: qname="<<dname<<" qtype="<<QType(qtype)<< " rrtype=" << QType(record.d_type) << " rrname=" << record.d_name << " rrcontent=" << record.d_content->getZoneRepresentation() << endl,
+        SLOG(g_log << Logger::Notice << "Unique response observed: qname=" << dname << " qtype=" << QType(qtype) << " rrtype=" << QType(record.d_type) << " rrname=" << record.d_name << " rrcontent=" << record.d_content->getZoneRepresentation() << endl,
              nodlogger->info(Logr::Debug, "New response observed",
                              "qtype", Logging::Loggable(qtype),
                              "rrtype", Logging::Loggable(QType(record.d_type)),
                              "rrname", Logging::Loggable(record.d_name),
-                             "rrcontent", Logging::Loggable(record.d_content->getZoneRepresentation())
-               );
-          );
+                             "rrcontent", Logging::Loggable(record.d_content->getZoneRepresentation())););
       }
       ret = true;
     }
@@ -622,23 +618,23 @@ int followCNAMERecords(vector<DNSRecord>& ret, const QType qtype, int rcode)
 {
   vector<DNSRecord> resolved;
   DNSName target;
-  for(const DNSRecord& rr :  ret) {
-    if(rr.d_type == QType::CNAME) {
+  for (const DNSRecord& rr : ret) {
+    if (rr.d_type == QType::CNAME) {
       auto rec = getRR<CNAMERecordContent>(rr);
-      if(rec) {
-        target=rec->getTarget();
+      if (rec) {
+        target = rec->getTarget();
         break;
       }
     }
   }
 
-  if(target.empty()) {
+  if (target.empty()) {
     return rcode;
   }
 
   rcode = directResolve(target, qtype, QClass::IN, resolved, t_pdl);
 
-  for(DNSRecord& rr :  resolved) {
+  for (DNSRecord& rr : resolved) {
     ret.push_back(std::move(rr));
   }
   return rcode;
@@ -660,23 +656,23 @@ int getFakeAAAARecords(const DNSName& qname, ComboAddress prefix, vector<DNSReco
   // Remove double CNAME records
   std::set<DNSName> seenCNAMEs;
   ret.erase(std::remove_if(
-        ret.begin(),
-        ret.end(),
-        [&seenCNAMEs](DNSRecord& rr) {
-          if (rr.d_type == QType::CNAME) {
-            auto target = getRR<CNAMERecordContent>(rr);
-            if (target == nullptr) {
-              return false;
-            }
-            if (seenCNAMEs.count(target->getTarget()) > 0) {
-              // We've had this CNAME before, remove it
-              return true;
-            }
-            seenCNAMEs.insert(target->getTarget());
-          }
-          return false;
-        }),
-      ret.end());
+              ret.begin(),
+              ret.end(),
+              [&seenCNAMEs](DNSRecord& rr) {
+                if (rr.d_type == QType::CNAME) {
+                  auto target = getRR<CNAMERecordContent>(rr);
+                  if (target == nullptr) {
+                    return false;
+                  }
+                  if (seenCNAMEs.count(target->getTarget()) > 0) {
+                    // We've had this CNAME before, remove it
+                    return true;
+                  }
+                  seenCNAMEs.insert(target->getTarget());
+                }
+                return false;
+              }),
+            ret.end());
 
   bool seenA = false;
   for (DNSRecord& rr : ret) {
@@ -695,12 +691,12 @@ int getFakeAAAARecords(const DNSName& qname, ComboAddress prefix, vector<DNSReco
     // We've seen an A in the ANSWER section, so there is no need to keep any
     // SOA in the AUTHORITY section as this is not a NODATA response.
     ret.erase(std::remove_if(
-          ret.begin(),
-          ret.end(),
-          [](DNSRecord& rr) {
-            return (rr.d_type == QType::SOA && rr.d_place == DNSResourceRecord::AUTHORITY);
-          }),
-        ret.end());
+                ret.begin(),
+                ret.end(),
+                [](DNSRecord& rr) {
+                  return (rr.d_type == QType::SOA && rr.d_place == DNSResourceRecord::AUTHORITY);
+                }),
+              ret.end());
   }
   g_stats.dns64prefixanswers++;
   return rcode;
@@ -719,8 +715,7 @@ int getFakePTRRecords(const DNSName& qname, vector<DNSRecord>& ret)
 
   string newquery;
   for (int n = 0; n < 4; ++n) {
-    newquery +=
-      std::to_string(stoll(parts[n*2], 0, 16) + 16*stoll(parts[n*2+1], 0, 16));
+    newquery += std::to_string(stoll(parts[n * 2], 0, 16) + 16 * stoll(parts[n * 2 + 1], 0, 16));
     newquery.append(1, '.');
   }
   newquery += "in-addr.arpa.";
@@ -770,18 +765,18 @@ bool isAllowNotifyForZone(DNSName qname)
   return false;
 }
 
-void startDoResolve(void *p)
+void startDoResolve(voidp)
 {
-  auto dc=std::unique_ptr<DNSComboWriter>(reinterpret_cast<DNSComboWriter*>(p));
+  auto dc = std::unique_ptr<DNSComboWriter>(reinterpret_cast<DNSComboWriter*>(p));
   try {
     if (t_queryring)
       t_queryring->push_back({dc->d_mdp.d_qname, dc->d_mdp.d_qtype});
 
     uint16_t maxanswersize = dc->d_tcp ? 65535 : min(static_cast<uint16_t>(512), g_udpTruncationThreshold);
     EDNSOpts edo;
-    std::vector<pair<uint16_t, string> > ednsOpts;
+    std::vector<pair<uint16_t, string>> ednsOpts;
     bool variableAnswer = dc->d_variable;
-    bool haveEDNS=false;
+    bool haveEDNS = false;
     bool paddingAllowed = false;
     bool addPaddingToResponse = false;
 #ifdef NOD_ENABLED
@@ -793,8 +788,8 @@ void startDoResolve(void *p)
 #endif /* NOD_ENABLED */
     DNSPacketWriter::optvect_t returnedEdnsOptions; // Here we stuff all the options for the return packet
     uint8_t ednsExtRCode = 0;
-    if(getEDNSOpts(dc->d_mdp, &edo)) {
-      haveEDNS=true;
+    if (getEDNSOpts(dc->d_mdp, &edo)) {
+      haveEDNS = true;
       if (edo.d_version != 0) {
         ednsExtRCode = ERCode::BADVERS;
       }
@@ -818,15 +813,16 @@ void startDoResolve(void *p)
       for (const auto& o : edo.d_options) {
         if (o.first == EDNSOptionCode::ECS && g_useIncomingECS && !dc->d_ecsParsed) {
           dc->d_ecsFound = getEDNSSubnetOptsFromString(o.second, &dc->d_ednssubnet);
-        } else if (o.first == EDNSOptionCode::NSID) {
+        }
+        else if (o.first == EDNSOptionCode::NSID) {
           const static string mode_server_id = ::arg()["server-id"];
-          if (mode_server_id != "disabled" && !mode_server_id.empty() &&
-              maxanswersize > (EDNSOptionCodeSize + EDNSOptionLengthSize + mode_server_id.size())) {
+          if (mode_server_id != "disabled" && !mode_server_id.empty() && maxanswersize > (EDNSOptionCodeSize + EDNSOptionLengthSize + mode_server_id.size())) {
             returnedEdnsOptions.emplace_back(EDNSOptionCode::NSID, mode_server_id);
             variableAnswer = true; // Can't packetcache an answer with NSID
             maxanswersize -= EDNSOptionCodeSize + EDNSOptionLengthSize + mode_server_id.size();
           }
-        } else if (paddingAllowed && !addPaddingToResponse && g_paddingMode == PaddingMode::PaddedQueries && o.first == EDNSOptionCode::PADDING) {
+        }
+        else if (paddingAllowed && !addPaddingToResponse && g_paddingMode == PaddingMode::PaddedQueries && o.first == EDNSOptionCode::PADDING) {
           addPaddingToResponse = true;
         }
       }
@@ -863,13 +859,13 @@ void startDoResolve(void *p)
 
     DNSPacketWriter pw(packet, dc->d_mdp.d_qname, dc->d_mdp.d_qtype, dc->d_mdp.d_qclass, dc->d_mdp.d_header.opcode);
 
-    pw.getHeader()->aa=0;
-    pw.getHeader()->ra=1;
-    pw.getHeader()->qr=1;
-    pw.getHeader()->tc=0;
-    pw.getHeader()->id=dc->d_mdp.d_header.id;
-    pw.getHeader()->rd=dc->d_mdp.d_header.rd;
-    pw.getHeader()->cd=dc->d_mdp.d_header.cd;
+    pw.getHeader()->aa = 0;
+    pw.getHeader()->ra = 1;
+    pw.getHeader()->qr = 1;
+    pw.getHeader()->tc = 0;
+    pw.getHeader()->id = dc->d_mdp.d_header.id;
+    pw.getHeader()->rd = dc->d_mdp.d_header.rd;
+    pw.getHeader()->cd = dc->d_mdp.d_header.cd;
 
     /* This is the lowest TTL seen in the records of the response,
        so we can't cache it for longer than this value.
@@ -881,16 +877,16 @@ void startDoResolve(void *p)
     sr.d_eventTrace = std::move(dc->d_eventTrace);
     sr.setId(MT->getTid());
 
-    bool DNSSECOK=false;
-    if(t_pdl) {
+    bool DNSSECOK = false;
+    if (t_pdl) {
       sr.setLuaEngine(t_pdl);
     }
-    if(g_dnssecmode != DNSSECMode::Off) {
+    if (g_dnssecmode != DNSSECMode::Off) {
       sr.setDoDNSSEC(true);
 
       // Does the requestor want DNSSEC records?
-      if(edo.d_extFlags & EDNSOpts::DNSSECOK) {
-        DNSSECOK=true;
+      if (edo.d_extFlags & EDNSOpts::DNSSECOK) {
+        DNSSECOK = true;
         g_stats.dnssecQueries++;
       }
       if (dc->d_mdp.d_header.cd) {
@@ -908,11 +904,12 @@ void startDoResolve(void *p)
            DNSSEC data via the DO bit. */
         ++g_stats.dnssecAuthenticDataQueries;
       }
-    } else {
+    }
+    else {
       // Ignore the client-set CD flag
-      pw.getHeader()->cd=0;
+      pw.getHeader()->cd = 0;
     }
-    sr.setDNSSECValidationRequested(g_dnssecmode == DNSSECMode::ValidateAll || g_dnssecmode==DNSSECMode::ValidateForLog || ((dc->d_mdp.d_header.ad || DNSSECOK) && g_dnssecmode==DNSSECMode::Process));
+    sr.setDNSSECValidationRequested(g_dnssecmode == DNSSECMode::ValidateAll || g_dnssecmode == DNSSECMode::ValidateForLog || ((dc->d_mdp.d_header.ad || DNSSECOK) && g_dnssecmode == DNSSECMode::Process));
 
     sr.setInitialRequestId(dc->d_uuid);
     sr.setOutgoingProtobufServers(t_outgoingProtobufServers);
@@ -922,7 +919,7 @@ void startDoResolve(void *p)
     sr.setQuerySource(dc->d_source, g_useIncomingECS && !dc->d_ednssubnet.source.empty() ? boost::optional<const EDNSSubnetOpts&>(dc->d_ednssubnet) : boost::none);
     sr.setQueryReceivedOverTCP(dc->d_tcp);
 
-    bool tracedQuery=false; // we could consider letting Lua know about this too
+    bool tracedQuery = false; // we could consider letting Lua know about this too
     bool shouldNotValidate = false;
 
     /* preresolve expects res (dq.rcode) to be set to RCode::NoError by default */
@@ -950,32 +947,32 @@ void startDoResolve(void *p)
 
     RunningResolveGuard tcpGuard(dc);
 
-    if(ednsExtRCode != 0 || dc->d_mdp.d_header.opcode == Opcode::Notify) {
+    if (ednsExtRCode != 0 || dc->d_mdp.d_header.opcode == Opcode::Notify) {
       goto sendit;
     }
 
-    if(dc->d_mdp.d_qtype==QType::ANY && !dc->d_tcp && g_anyToTcp) {
+    if (dc->d_mdp.d_qtype == QType::ANY && !dc->d_tcp && g_anyToTcp) {
       pw.getHeader()->tc = 1;
       res = 0;
       variableAnswer = true;
       goto sendit;
     }
 
-    if(t_traceRegex && t_traceRegex->match(dc->d_mdp.d_qname.toString())) {
+    if (t_traceRegex && t_traceRegex->match(dc->d_mdp.d_qname.toString())) {
       sr.setLogMode(SyncRes::Store);
-      tracedQuery=true;
+      tracedQuery = true;
     }
 
-    if(!g_quiet || tracedQuery) {
-      g_log<<Logger::Warning<<t_id<<" ["<<MT->getTid()<<"/"<<MT->numProcesses()<<"] " << (dc->d_tcp ? "TCP " : "") << "question for '"<<dc->d_mdp.d_qname<<"|"
-           <<QType(dc->d_mdp.d_qtype)<<"' from "<<dc->getRemote();
-      if(!dc->d_ednssubnet.source.empty()) {
-        g_log<<" (ecs "<<dc->d_ednssubnet.source.toString()<<")";
+    if (!g_quiet || tracedQuery) {
+      g_log << Logger::Warning << t_id << " [" << MT->getTid() << "/" << MT->numProcesses() << "] " << (dc->d_tcp ? "TCP " : "") << "question for '" << dc->d_mdp.d_qname << "|"
+            << QType(dc->d_mdp.d_qtype) << "' from " << dc->getRemote();
+      if (!dc->d_ednssubnet.source.empty()) {
+        g_log << " (ecs " << dc->d_ednssubnet.source.toString() << ")";
       }
-      g_log<<endl;
+      g_log << endl;
     }
 
-    if(!dc->d_mdp.d_header.rd) {
+    if (!dc->d_mdp.d_header.rd) {
       sr.setCacheOnly();
     }
 
@@ -1073,12 +1070,12 @@ void startDoResolve(void *p)
       catch (const ImmediateQueryDropException& e) {
         // XXX We need to export a protobuf message (and do a NOD lookup) if requested!
         g_stats.policyDrops++;
-        g_log<<Logger::Debug<<"Dropping query because of a filtering policy "<<makeLoginfo(dc)<<endl;
+        g_log << Logger::Debug << "Dropping query because of a filtering policy " << makeLoginfo(dc) << endl;
         return;
       }
-      catch (const ImmediateServFailException &e) {
-        if(g_logCommonErrors) {
-          g_log<<Logger::Notice<<"Sending SERVFAIL to "<<dc->getRemote()<<" during resolve of '"<<dc->d_mdp.d_qname<<"' because: "<<e.reason<<endl;
+      catch (const ImmediateServFailExceptione) {
+        if (g_logCommonErrors) {
+          g_log << Logger::Notice << "Sending SERVFAIL to " << dc->getRemote() << " during resolve of '" << dc->d_mdp.d_qname << "' because: " << e.reason << endl;
         }
         res = RCode::ServFail;
       }
@@ -1131,8 +1128,8 @@ void startDoResolve(void *p)
               shouldNotValidate = true;
             }
           }
-       }
-       else if (res == RCode::NXDomain && t_pdl && t_pdl->nxdomain(dq, res, sr.d_eventTrace)) {
+        }
+        else if (res == RCode::NXDomain && t_pdl && t_pdl->nxdomain(dq, res, sr.d_eventTrace)) {
           shouldNotValidate = true;
           auto policyResult = handlePolicyHit(appliedPolicy, dc, sr, res, ret, pw, tcpGuard);
           if (policyResult == PolicyResult::HaveAnswer) {
@@ -1180,29 +1177,28 @@ void startDoResolve(void *p)
     }
 
   haveAnswer:;
-    if(tracedQuery || res == -1 || res == RCode::ServFail || pw.getHeader()->rcode == RCode::ServFail)
-    { 
+    if (tracedQuery || res == -1 || res == RCode::ServFail || pw.getHeader()->rcode == RCode::ServFail) {
       string trace(sr.getTrace());
-      if(!trace.empty()) {
+      if (!trace.empty()) {
         vector<string> lines;
         boost::split(lines, trace, boost::is_any_of("\n"));
-        for(const string& line : lines) {
-          if(!line.empty())
-            g_log<<Logger::Warning<< line << endl;
+        for (const string& line : lines) {
+          if (!line.empty())
+            g_log << Logger::Warning << line << endl;
         }
       }
     }
 
-    if(res == -1) {
-      pw.getHeader()->rcode=RCode::ServFail;
+    if (res == -1) {
+      pw.getHeader()->rcode = RCode::ServFail;
       // no commit here, because no record
       g_stats.servFails++;
     }
     else {
-      pw.getHeader()->rcode=res;
+      pw.getHeader()->rcode = res;
 
       // Does the validation mode or query demand validation?
-      if(!shouldNotValidate && sr.isDNSSECValidationRequested()) {
+      if (!shouldNotValidate && sr.isDNSSECValidationRequested()) {
         try {
           auto state = sr.getValidationState();
 
@@ -1214,75 +1210,66 @@ void startDoResolve(void *p)
             }
           }
 
-          if(state == vState::Secure) {
-            if(sr.doLog()) {
-              g_log<<Logger::Warning<<"Answer to "<<dc->d_mdp.d_qname<<"|"<<QType(dc->d_mdp.d_qtype)<<x_marker<<" for "<<dc->getRemote()<<" validates correctly"<<endl;
+          if (state == vState::Secure) {
+            if (sr.doLog()) {
+              g_log << Logger::Warning << "Answer to " << dc->d_mdp.d_qname << "|" << QType(dc->d_mdp.d_qtype) << x_marker << " for " << dc->getRemote() << " validates correctly" << endl;
             }
 
             // Is the query source interested in the value of the ad-bit?
             if (dc->d_mdp.d_header.ad || DNSSECOK)
-              pw.getHeader()->ad=1;
+              pw.getHeader()->ad = 1;
           }
-          else if(state == vState::Insecure) {
-            if(sr.doLog()) {
-              g_log<<Logger::Warning<<"Answer to "<<dc->d_mdp.d_qname<<"|"<<QType(dc->d_mdp.d_qtype)<<x_marker<<" for "<<dc->getRemote()<<" validates as Insecure"<<endl;
+          else if (state == vState::Insecure) {
+            if (sr.doLog()) {
+              g_log << Logger::Warning << "Answer to " << dc->d_mdp.d_qname << "|" << QType(dc->d_mdp.d_qtype) << x_marker << " for " << dc->getRemote() << " validates as Insecure" << endl;
             }
 
-            pw.getHeader()->ad=0;
+            pw.getHeader()->ad = 0;
           }
           else if (vStateIsBogus(state)) {
-            if(t_bogusremotes)
+            if (t_bogusremotes)
               t_bogusremotes->push_back(dc->d_source);
-            if(t_bogusqueryring)
+            if (t_bogusqueryring)
               t_bogusqueryring->push_back({dc->d_mdp.d_qname, dc->d_mdp.d_qtype});
-            if(g_dnssecLogBogus || sr.doLog() || g_dnssecmode == DNSSECMode::ValidateForLog) {
-               g_log<<Logger::Warning<<"Answer to "<<dc->d_mdp.d_qname<<"|"<<QType(dc->d_mdp.d_qtype)<<x_marker<<" for "<<dc->getRemote()<<" validates as "<<vStateToString(state)<<endl;
+            if (g_dnssecLogBogus || sr.doLog() || g_dnssecmode == DNSSECMode::ValidateForLog) {
+              g_log << Logger::Warning << "Answer to " << dc->d_mdp.d_qname << "|" << QType(dc->d_mdp.d_qtype) << x_marker << " for " << dc->getRemote() << " validates as " << vStateToString(state) << endl;
             }
 
             // Does the query or validation mode sending out a SERVFAIL on validation errors?
-            if(!pw.getHeader()->cd && (g_dnssecmode == DNSSECMode::ValidateAll || dc->d_mdp.d_header.ad || DNSSECOK)) {
-              if(sr.doLog()) {
-                g_log<<Logger::Warning<<"Sending out SERVFAIL for "<<dc->d_mdp.d_qname<<"|"<<QType(dc->d_mdp.d_qtype)<<" because recursor or query demands it for Bogus results"<<endl;
+            if (!pw.getHeader()->cd && (g_dnssecmode == DNSSECMode::ValidateAll || dc->d_mdp.d_header.ad || DNSSECOK)) {
+              if (sr.doLog()) {
+                g_log << Logger::Warning << "Sending out SERVFAIL for " << dc->d_mdp.d_qname << "|" << QType(dc->d_mdp.d_qtype) << " because recursor or query demands it for Bogus results" << endl;
               }
 
-              pw.getHeader()->rcode=RCode::ServFail;
+              pw.getHeader()->rcode = RCode::ServFail;
               goto sendit;
-            } else {
-              if(sr.doLog()) {
-                g_log<<Logger::Warning<<"Not sending out SERVFAIL for "<<dc->d_mdp.d_qname<<"|"<<QType(dc->d_mdp.d_qtype)<<x_marker<<" Bogus validation since neither config nor query demands this"<<endl;
+            }
+            else {
+              if (sr.doLog()) {
+                g_log << Logger::Warning << "Not sending out SERVFAIL for " << dc->d_mdp.d_qname << "|" << QType(dc->d_mdp.d_qtype) << x_marker << " Bogus validation since neither config nor query demands this" << endl;
               }
             }
           }
         }
-        catch(const ImmediateServFailException &e) {
-          if(g_logCommonErrors)
-            g_log<<Logger::Notice<<"Sending SERVFAIL to "<<dc->getRemote()<<" during validation of '"<<dc->d_mdp.d_qname<<"|"<<QType(dc->d_mdp.d_qtype)<<"' because: "<<e.reason<<endl;
-          pw.getHeader()->rcode=RCode::ServFail;
+        catch (const ImmediateServFailException& e) {
+          if (g_logCommonErrors)
+            g_log << Logger::Notice << "Sending SERVFAIL to " << dc->getRemote() << " during validation of '" << dc->d_mdp.d_qname << "|" << QType(dc->d_mdp.d_qtype) << "' because: " << e.reason << endl;
+          pw.getHeader()->rcode = RCode::ServFail;
           goto sendit;
         }
       }
 
-      if(ret.size()) {
+      if (ret.size()) {
         pdns::orderAndShuffle(ret);
-       if(auto sl = luaconfsLocal->sortlist.getOrderCmp(dc->d_source)) {
-         stable_sort(ret.begin(), ret.end(), *sl);
-         variableAnswer=true;
-       }
+        if (auto sl = luaconfsLocal->sortlist.getOrderCmp(dc->d_source)) {
+          stable_sort(ret.begin(), ret.end(), *sl);
+          variableAnswer = true;
+        }
       }
 
       bool needCommit = false;
-      for(auto i=ret.cbegin(); i!=ret.cend(); ++i) {
-        if( ! DNSSECOK &&
-            ( i->d_type == QType::NSEC3 ||
-              (
-                ( i->d_type == QType::RRSIG || i->d_type==QType::NSEC ) &&
-                (
-                  ( dc->d_mdp.d_qtype != i->d_type &&  dc->d_mdp.d_qtype != QType::ANY ) ||
-                  i->d_place != DNSResourceRecord::ANSWER
-                )
-              )
-            )
-          ) {
+      for (auto i = ret.cbegin(); i != ret.cend(); ++i) {
+        if (!DNSSECOK && (i->d_type == QType::NSEC3 || ((i->d_type == QType::RRSIG || i->d_type == QType::NSEC) && ((dc->d_mdp.d_qtype != i->d_type && dc->d_mdp.d_qtype != QType::ANY) || i->d_place != DNSResourceRecord::ANSWER)))) {
           continue;
         }
 
@@ -1292,21 +1279,21 @@ void startDoResolve(void *p)
         }
         needCommit = true;
 
-       bool udr = false;
+        bool udr = false;
 #ifdef NOD_ENABLED
-       if (g_udrEnabled) {
-         udr = udrCheckUniqueDNSRecord(nodlogger, dc->d_mdp.d_qname, dc->d_mdp.d_qtype, *i);
+        if (g_udrEnabled) {
+          udr = udrCheckUniqueDNSRecord(nodlogger, dc->d_mdp.d_qname, dc->d_mdp.d_qtype, *i);
           if (!hasUDR && udr)
             hasUDR = true;
-       }
+        }
 #endif /* NOD ENABLED */
 
         if (t_protobufServers) {
           pbMessage.addRR(*i, luaconfsLocal->protobufExportConfig.exportTypes, udr);
         }
       }
-      if(needCommit)
-       pw.commit();
+      if (needCommit)
+        pw.commit();
     }
   sendit:;
 
@@ -1476,8 +1463,7 @@ void startDoResolve(void *p)
 
     if (!SyncRes::s_nopacketcache && !variableAnswer && !sr.wasVariable()) {
       const auto& hdr = pw.getHeader();
-      if ((hdr->rcode != RCode::NoError && hdr->rcode != RCode::NXDomain) ||
-          (hdr->ancount == 0 && hdr->nscount == 0)) {
+      if ((hdr->rcode != RCode::NoError && hdr->rcode != RCode::NXDomain) || (hdr->ancount == 0 && hdr->nscount == 0)) {
         minTTL = min(minTTL, SyncRes::s_packetcacheservfailttl);
       }
       minTTL = min(minTTL, SyncRes::s_packetcachettl);
@@ -1494,9 +1480,9 @@ void startDoResolve(void *p)
       struct iovec iov;
       cmsgbuf_aligned cbuf;
       fillMSGHdr(&msgh, &iov, &cbuf, 0, (char*)&*packet.begin(), packet.size(), &dc->d_remote);
-      msgh.msg_control=NULL;
+      msgh.msg_control = NULL;
 
-      if(g_fromtosockets.count(dc->d_socket)) {
+      if (g_fromtosockets.count(dc->d_socket)) {
         addCMsgSrcAddr(&msgh, &cbuf, &dc->d_local, 0);
       }
       int sendErr = sendOnNBSocket(dc->d_socket, &msgh);
@@ -1504,7 +1490,6 @@ void startDoResolve(void *p)
         g_log << Logger::Warning << "Sending UDP reply to client " << dc->getRemote() << " failed with: "
               << strerror(sendErr) << endl;
       }
-
     }
     else {
       bool hadError = sendResponseOverTCP(dc, packet);
@@ -1546,7 +1531,7 @@ void startDoResolve(void *p)
 #ifdef NOD_ENABLED
       if (g_nodEnabled) {
         if (nod) {
-         pbMessage.setNewlyObservedDomain(true);
+          pbMessage.setNewlyObservedDomain(true);
           pbMessage.addPolicyTag(g_nod_pbtag);
         }
         if (hasUDR) {
@@ -1570,15 +1555,13 @@ void startDoResolve(void *p)
     // Now it always uses an integral number of microseconds, except for averages, which use doubles
     uint64_t spentUsec = uSec(sr.getNow() - dc->d_now);
     if (!g_quiet) {
-      g_log<<Logger::Error<<t_id<<" ["<<MT->getTid()<<"/"<<MT->numProcesses()<<"] answer to "<<(dc->d_mdp.d_header.rd?"":"non-rd ")<<"question '"<<dc->d_mdp.d_qname<<"|"<<DNSRecordContent::NumberToType(dc->d_mdp.d_qtype);
-      g_log<<"': "<<ntohs(pw.getHeader()->ancount)<<" answers, "<<ntohs(pw.getHeader()->arcount)<<" additional, took "<<sr.d_outqueries<<" packets, "<<
-       sr.d_totUsec/1000.0<<" netw ms, "<< spentUsec/1000.0<<" tot ms, "<<
-       sr.d_throttledqueries<<" throttled, "<<sr.d_timeouts<<" timeouts, "<<sr.d_tcpoutqueries<<"/"<<sr.d_dotoutqueries<<" tcp/dot connections, rcode="<< res;
+      g_log << Logger::Error << t_id << " [" << MT->getTid() << "/" << MT->numProcesses() << "] answer to " << (dc->d_mdp.d_header.rd ? "" : "non-rd ") << "question '" << dc->d_mdp.d_qname << "|" << DNSRecordContent::NumberToType(dc->d_mdp.d_qtype);
+      g_log << "': " << ntohs(pw.getHeader()->ancount) << " answers, " << ntohs(pw.getHeader()->arcount) << " additional, took " << sr.d_outqueries << " packets, " << sr.d_totUsec / 1000.0 << " netw ms, " << spentUsec / 1000.0 << " tot ms, " << sr.d_throttledqueries << " throttled, " << sr.d_timeouts << " timeouts, " << sr.d_tcpoutqueries << "/" << sr.d_dotoutqueries << " tcp/dot connections, rcode=" << res;
 
-      if(!shouldNotValidate && sr.isDNSSECValidationRequested()) {
-       g_log<< ", dnssec="<<sr.getValidationState();
+      if (!shouldNotValidate && sr.isDNSSECValidationRequested()) {
+        g_log << ", dnssec=" << sr.getValidationState();
       }
-      g_log<<endl;
+      g_log << endl;
     }
 
     if (dc->d_mdp.d_header.opcode == Opcode::Query) {
@@ -1599,7 +1582,7 @@ void startDoResolve(void *p)
     // no worries, we do this for packet cache hits elsewhere
 
     if (spentUsec >= sr.d_totUsec) {
-      uint64_t ourtime = spentUsec - sr.d_totUsec; 
+      uint64_t ourtime = spentUsec - sr.d_totUsec;
       g_stats.ourtime(ourtime);
       newLat = ourtime; // usec
       g_stats.avgLatencyOursUsec = (1.0 - 1.0 / g_latencyStatSize) * g_stats.avgLatencyOursUsec + newLat / g_latencyStatSize;
@@ -1613,26 +1596,29 @@ void startDoResolve(void *p)
 
     //    cout<<dc->d_mdp.d_qname<<"\t"<<MT->getUsec()<<"\t"<<sr.d_outqueries<<endl;
   }
-  catch (const PDNSException &ae) {
-    g_log<<Logger::Error<<"startDoResolve problem "<<makeLoginfo(dc)<<": "<<ae.reason<<endl;
+  catch (const PDNSExceptionae) {
+    g_log << Logger::Error << "startDoResolve problem " << makeLoginfo(dc) << ": " << ae.reason << endl;
   }
-  catch (const MOADNSException &mde) {
-    g_log<<Logger::Error<<"DNS parser error "<<makeLoginfo(dc) <<": "<<dc->d_mdp.d_qname<<", "<<mde.what()<<endl;
+  catch (const MOADNSExceptionmde) {
+    g_log << Logger::Error << "DNS parser error " << makeLoginfo(dc) << ": " << dc->d_mdp.d_qname << ", " << mde.what() << endl;
   }
   catch (const std::exception& e) {
-    g_log<<Logger::Error<<"STL error "<< makeLoginfo(dc)<<": "<<e.what();
+    g_log << Logger::Error << "STL error " << makeLoginfo(dc) << ": " << e.what();
 
     // Luawrapper nests the exception from Lua, so we unnest it here
     try {
-        std::rethrow_if_nested(e);
-    } catch(const std::exception& ne) {
-        g_log<<". Extra info: "<<ne.what();
-    } catch(...) {}
+      std::rethrow_if_nested(e);
+    }
+    catch (const std::exception& ne) {
+      g_log << ". Extra info: " << ne.what();
+    }
+    catch (...) {
+    }
 
-    g_log<<endl;
+    g_log << endl;
   }
-  catch(...) {
-    g_log<<Logger::Error<<"Any other exception in a resolver context "<< makeLoginfo(dc) <<endl;
+  catch (...) {
+    g_log << Logger::Error << "Any other exception in a resolver context " << makeLoginfo(dc) << endl;
   }
 
   runTaskOnce(g_logCommonErrors);
@@ -1640,19 +1626,18 @@ void startDoResolve(void *p)
   g_stats.maxMThreadStackUsage = max(MT->getMaxStackUsage(), g_stats.maxMThreadStackUsage.load());
 }
 
-
 void getQNameAndSubnet(const std::string& question, DNSName* dnsname, uint16_t* qtype, uint16_t* qclass,
-                              bool& foundECS, EDNSSubnetOpts* ednssubnet, EDNSOptionViewMap* options,
-                              bool& foundXPF, ComboAddress* xpfSource, ComboAddress* xpfDest)
+                       bool& foundECS, EDNSSubnetOpts* ednssubnet, EDNSOptionViewMap* options,
+                       bool& foundXPF, ComboAddress* xpfSource, ComboAddress* xpfDest)
 {
   const bool lookForXPF = xpfSource != nullptr && g_xpfRRCode != 0;
   const bool lookForECS = ednssubnet != nullptr;
   const struct dnsheader* dh = reinterpret_cast<const struct dnsheader*>(question.c_str());
   size_t questionLen = question.length();
-  unsigned int consumed=0;
-  *dnsname=DNSName(question.c_str(), questionLen, sizeof(dnsheader), false, qtype, qclass, &consumed);
+  unsigned int consumed = 0;
+  *dnsname = DNSName(question.c_str(), questionLen, sizeof(dnsheader), false, qtype, qclass, &consumed);
 
-  size_t pos= sizeof(dnsheader)+consumed+4;
+  size_t pos = sizeof(dnsheader) + consumed + 4;
   const size_t headerSize = /* root */ 1 + sizeof(dnsrecordheader);
   const uint16_t arcount = ntohs(dh->arcount);
 
@@ -1671,7 +1656,7 @@ void getQNameAndSubnet(const std::string& question, DNSName* dnsname, uint16_t*
     }
 
     /* OPT root label (1) followed by type (2) */
-    if(lookForECS && ntohs(drh->d_type) == QType::OPT) {
+    if (lookForECS && ntohs(drh->d_type) == QType::OPT) {
       if (!options) {
         size_t ecsStartPosition = 0;
         size_t ecsLen = 0;
@@ -1679,21 +1664,21 @@ void getQNameAndSubnet(const std::string& question, DNSName* dnsname, uint16_t*
         int res = getEDNSOption(reinterpret_cast<const char*>(&question.at(pos - sizeof(drh->d_clen))), questionLen - pos + sizeof(drh->d_clen), EDNSOptionCode::ECS, &ecsStartPosition, &ecsLen);
         if (res == 0 && ecsLen > 4) {
           EDNSSubnetOpts eso;
-          if(getEDNSSubnetOptsFromString(&question.at(pos - sizeof(drh->d_clen) + ecsStartPosition + 4), ecsLen - 4, &eso)) {
-            *ednssubnet=eso;
+          if (getEDNSSubnetOptsFromString(&question.at(pos - sizeof(drh->d_clen) + ecsStartPosition + 4), ecsLen - 4, &eso)) {
+            *ednssubnet = eso;
             foundECS = true;
           }
         }
       }
       else {
         /* we need to pass the record len */
-        int res = getEDNSOptions(reinterpret_cast<const char*>(&question.at(pos -sizeof(drh->d_clen))), questionLen - pos + (sizeof(drh->d_clen)), *options);
+        int res = getEDNSOptions(reinterpret_cast<const char*>(&question.at(pos - sizeof(drh->d_clen))), questionLen - pos + (sizeof(drh->d_clen)), *options);
         if (res == 0) {
           const auto& it = options->find(EDNSOptionCode::ECS);
           if (it != options->end() && !it->second.values.empty() && it->second.values.at(0).content != nullptr && it->second.values.at(0).size > 0) {
             EDNSSubnetOpts eso;
-            if(getEDNSSubnetOptsFromString(it->second.values.at(0).content, it->second.values.at(0).size, &eso)) {
-              *ednssubnet=eso;
+            if (getEDNSSubnetOptsFromString(it->second.values.at(0).content, it->second.values.at(0).size, &eso)) {
+              *ednssubnet = eso;
               foundECS = true;
             }
           }
@@ -1713,18 +1698,19 @@ void getQNameAndSubnet(const std::string& question, DNSName* dnsname, uint16_t*
 }
 
 bool checkForCacheHit(bool qnameParsed, unsigned int tag, const string& data,
-                             DNSName& qname, uint16_t& qtype, uint16_t& qclass,
-                             const struct timeval& now,
-                             string& response, uint32_t& qhash,
-                             RecursorPacketCache::OptPBData& pbData, bool tcp, const ComboAddress& source) 
+                      DNSName& qname, uint16_t& qtype, uint16_t& qclass,
+                      const struct timeval& now,
+                      string& response, uint32_t& qhash,
+                      RecursorPacketCache::OptPBData& pbData, bool tcp, const ComboAddress& source)
 {
   bool cacheHit = false;
   uint32_t age;
   vState valState;
-  
+
   if (qnameParsed) {
     cacheHit = !SyncRes::s_nopacketcache && t_packetCache->getResponsePacket(tag, data, qname, qtype, qclass, now.tv_sec, &response, &age, &valState, &qhash, &pbData, tcp);
-  } else {
+  }
+  else {
     cacheHit = !SyncRes::s_nopacketcache && t_packetCache->getResponsePacket(tag, data, qname, &qtype, &qclass, now.tv_sec, &response, &age, &valState, &qhash, &pbData, tcp);
   }
 
@@ -1742,7 +1728,7 @@ bool checkForCacheHit(bool qnameParsed, unsigned int tag, const string& data,
     SyncRes::s_queries++;
     ageDNSPacket(response, age);
     if (response.length() >= sizeof(struct dnsheader)) {
-      const struct dnsheader *dh = reinterpret_cast<const dnsheader*>(response.data());
+      const struct dnsheaderdh = reinterpret_cast<const dnsheader*>(response.data());
       updateResponseStats(dh->rcode, source, response.length(), 0, 0);
     }
     g_stats.avgLatencyUsec = (1.0 - 1.0 / g_latencyStatSize) * g_stats.avgLatencyUsec + 0.0; // we assume 0 usec
@@ -1760,7 +1746,7 @@ bool checkForCacheHit(bool qnameParsed, unsigned int tag, const string& data,
 static void* pleaseWipeCaches(const DNSName& canon, bool subtree, uint16_t qtype)
 {
   auto res = wipeCaches(canon, subtree, qtype);
-  g_log<<Logger::Info<<"Wiped caches for "<<canon<<": "<<res.record_count<<" records; "<<res.negative_record_count<<" negative records; "<<res.packet_count<<" packets"<<endl;
+  g_log << Logger::Info << "Wiped caches for " << canon << ": " << res.record_count << " records; " << res.negative_record_count << " negative records; " << res.packet_count << " packets" << endl;
   return nullptr;
 }
 
@@ -1769,9 +1755,9 @@ void requestWipeCaches(const DNSName& canon)
   // send a message to the handler thread asking it
   // to wipe all of the caches
   ThreadMSG* tmsg = new ThreadMSG();
-  tmsg->func = [=]{ return pleaseWipeCaches(canon, true, 0xffff); };
+  tmsg->func = [=] { return pleaseWipeCaches(canon, true, 0xffff); };
   tmsg->wantAnswer = false;
-  if(write(s_threadInfos[0].pipes.writeToThread, &tmsg, sizeof(tmsg)) != sizeof(tmsg)) {
+  if (write(s_threadInfos[0].pipes.writeToThread, &tmsg, sizeof(tmsg)) != sizeof(tmsg)) {
     delete tmsg;
 
     unixDie("write to thread pipe returned wrong size or error");
@@ -1783,28 +1769,27 @@ bool expectProxyProtocol(const ComboAddress& from)
   return g_proxyProtocolACL.match(from);
 }
 
-
 static string* doProcessUDPQuestion(const std::string& question, const ComboAddress& fromaddr, const ComboAddress& destaddr, ComboAddress source, ComboAddress destination, struct timeval tv, int fd, std::vector<ProxyProtocolValue>& proxyProtocolValues, RecEventTrace& eventTrace)
 {
   ++s_threadInfos[t_id].numberOfDistributedQueries;
   gettimeofday(&g_now, nullptr);
   if (tv.tv_sec) {
     struct timeval diff = g_now - tv;
-    double delta=(diff.tv_sec*1000 + diff.tv_usec/1000.0);
+    double delta = (diff.tv_sec * 1000 + diff.tv_usec / 1000.0);
 
-    if(delta > 1000.0) {
+    if (delta > 1000.0) {
       g_stats.tooOldDrops++;
       return nullptr;
     }
   }
 
   ++g_stats.qcounter;
-  if(fromaddr.sin4.sin_family==AF_INET6)
-     g_stats.ipv6qcounter++;
+  if (fromaddr.sin4.sin_family == AF_INET6)
+    g_stats.ipv6qcounter++;
 
   string response;
   const struct dnsheader* dh = (struct dnsheader*)question.c_str();
-  unsigned int ctag=0;
+  unsigned int ctag = 0;
   uint32_t qhash = 0;
   bool needECS = false;
   bool needXPF = g_XPFAcl.match(fromaddr);
@@ -1822,7 +1807,8 @@ static string* doProcessUDPQuestion(const std::string& question, const ComboAddr
   if (checkProtobufExport(luaconfsLocal)) {
     uniqueId = getUniqueID();
     needECS = true;
-  } else if (checkOutgoingProtobufExport(luaconfsLocal)) {
+  }
+  else if (checkOutgoingProtobufExport(luaconfsLocal)) {
     uniqueId = getUniqueID();
   }
   logQuery = t_protobufServers && luaconfsLocal->protobufExportConfig.logQueries;
@@ -1843,9 +1829,9 @@ static string* doProcessUDPQuestion(const std::string& question, const ComboAddr
   bool responsePaddingDisabled = false;
   DNSName qname;
   try {
-    uint16_t qtype=0;
-    uint16_t qclass=0;
-    bool qnameParsed=false;
+    uint16_t qtype = 0;
+    uint16_t qclass = 0;
+    bool qnameParsed = false;
 #ifdef MALLOC_TRACE
     /*
     static uint64_t last=0;
@@ -1858,7 +1844,7 @@ static string* doProcessUDPQuestion(const std::string& question, const ComboAddr
     */
 #endif
 
-    if(needECS || needXPF || (t_pdl && (t_pdl->d_gettag || t_pdl->d_gettag_ffi)) || dh->opcode == Opcode::Notify) {
+    if (needECS || needXPF || (t_pdl && (t_pdl->d_gettag || t_pdl->d_gettag_ffi)) || dh->opcode == Opcode::Notify) {
       try {
         EDNSOptionViewMap ednsOptions;
         bool xpfFound = false;
@@ -1872,7 +1858,7 @@ static string* doProcessUDPQuestion(const std::string& question, const ComboAddr
         qnameParsed = true;
         ecsParsed = true;
 
-        if(t_pdl) {
+        if (t_pdl) {
           try {
             if (t_pdl->d_gettag_ffi) {
               RecursorLua4::FFIParams params(qname, qtype, destination, source, ednssubnet.source, data, policyTags, records, ednsOptions, proxyProtocolValues, requestorId, deviceId, deviceName, routingTag, rcode, ttlCap, variable, false, logQuery, logResponse, followCNAMEs, extendedErrorCode, extendedErrorExtra, responsePaddingDisabled, meta);
@@ -1887,17 +1873,16 @@ static string* doProcessUDPQuestion(const std::string& question, const ComboAddr
               eventTrace.add(RecEventTrace::LuaGetTag, ctag, false);
             }
           }
-          catch (const std::exception& e)  {
+          catch (const std::exception& e) {
             if (g_logCommonErrors) {
-              g_log<<Logger::Warning<<"Error parsing a query packet qname='"<<qname<<"' for tag determination, setting tag=0: "<<e.what()<<endl;
+              g_log << Logger::Warning << "Error parsing a query packet qname='" << qname << "' for tag determination, setting tag=0: " << e.what() << endl;
             }
           }
         }
       }
-      catch (const std::exception& e)
-      {
+      catch (const std::exception& e) {
         if (g_logCommonErrors) {
-          g_log<<Logger::Warning<<"Error parsing a query packet for tag determination, setting tag=0: "<<e.what()<<endl;
+          g_log << Logger::Warning << "Error parsing a query packet for tag determination, setting tag=0: " << e.what() << endl;
         }
       }
     }
@@ -1913,7 +1898,7 @@ static string* doProcessUDPQuestion(const std::string& question, const ComboAddr
       ctag = g_paddingTag;
     }
 
-    if(dh->opcode == Opcode::Query) {
+    if (dh->opcode == Opcode::Query) {
       /* It might seem like a good idea to skip the packet cache lookup if we know that the answer is not cacheable,
          but it means that the hash would not be computed. If some script decides at a later time to mark back the answer
          as cacheable we would cache it with a wrong tag, so better safe than sorry. */
@@ -1922,15 +1907,15 @@ static string* doProcessUDPQuestion(const std::string& question, const ComboAddr
       eventTrace.add(RecEventTrace::PCacheCheck, cacheHit, false);
       if (cacheHit) {
         if (!g_quiet) {
-          g_log<<Logger::Notice<<t_id<< " question answered from packet cache tag="<<ctag<<" from "<<source.toStringWithPort()<<(source != fromaddr ? " (via "+fromaddr.toStringWithPort()+")" : "")<<endl;
+          g_log << Logger::Notice << t_id << " question answered from packet cache tag=" << ctag << " from " << source.toStringWithPort() << (source != fromaddr ? " (via " + fromaddr.toStringWithPort() + ")" : "") << endl;
         }
         struct msghdr msgh;
         struct iovec iov;
         cmsgbuf_aligned cbuf;
         fillMSGHdr(&msgh, &iov, &cbuf, 0, (char*)response.c_str(), response.length(), const_cast<ComboAddress*>(&fromaddr));
-        msgh.msg_control=NULL;
+        msgh.msg_control = NULL;
 
-        if(g_fromtosockets.count(fd)) {
+        if (g_fromtosockets.count(fd)) {
           addCMsgSrcAddr(&msgh, &cbuf, &destaddr, 0);
         }
         int sendErr = sendOnNBSocket(fd, &msgh);
@@ -1958,7 +1943,7 @@ static string* doProcessUDPQuestion(const std::string& question, const ComboAddr
   }
   catch (const std::exception& e) {
     if (g_logCommonErrors) {
-      g_log<<Logger::Error<<"Error processing or aging answer packet: "<<e.what()<<endl;
+      g_log << Logger::Error << "Error processing or aging answer packet: " << e.what() << endl;
     }
     return 0;
   }
@@ -1967,17 +1952,17 @@ static string* doProcessUDPQuestion(const std::string& question, const ComboAddr
     bool ipf = t_pdl->ipfilter(source, destination, *dh, eventTrace);
     if (ipf) {
       if (!g_quiet) {
-        g_log<<Logger::Notice<<t_id<<" ["<<MT->getTid()<<"/"<<MT->numProcesses()<<"] DROPPED question from "<<source.toStringWithPort()<<(source != fromaddr ? " (via "+fromaddr.toStringWithPort()+")" : "")<<" based on policy"<<endl;
+        g_log << Logger::Notice << t_id << " [" << MT->getTid() << "/" << MT->numProcesses() << "] DROPPED question from " << source.toStringWithPort() << (source != fromaddr ? " (via " + fromaddr.toStringWithPort() + ")" : "") << " based on policy" << endl;
       }
       g_stats.policyDrops++;
       return 0;
     }
   }
 
-  if(dh->opcode == Opcode::Notify) {
-    if(!isAllowNotifyForZone(qname)) {
-      if(!g_quiet) {
-        g_log<<Logger::Error<<"["<<MT->getTid()<<"] dropping UDP NOTIFY from "<<source.toStringWithPort()<<(source != fromaddr ? " (via "+fromaddr.toStringWithPort()+")" : "")<<", for "<<qname.toLogString()<<", zone not matched by allow-notify-for"<<endl;
+  if (dh->opcode == Opcode::Notify) {
+    if (!isAllowNotifyForZone(qname)) {
+      if (!g_quiet) {
+        g_log << Logger::Error << "[" << MT->getTid() << "] dropping UDP NOTIFY from " << source.toStringWithPort() << (source != fromaddr ? " (via " + fromaddr.toStringWithPort() + ")" : "") << ", for " << qname.toLogString() << ", zone not matched by allow-notify-for" << endl;
       }
 
       g_stats.zoneDisallowedNotify++;
@@ -1985,7 +1970,7 @@ static string* doProcessUDPQuestion(const std::string& question, const ComboAddr
     }
 
     if (!g_quiet) {
-      g_log<<Logger::Notice<<t_id<< " got NOTIFY for "<<qname.toLogString()<<" from "<<source.toStringWithPort()<<(source != fromaddr ? " (via "+fromaddr.toStringWithPort()+")" : "")<<endl;
+      g_log << Logger::Notice << t_id << " got NOTIFY for " << qname.toLogString() << " from " << source.toStringWithPort() << (source != fromaddr ? " (via " + fromaddr.toStringWithPort() + ")" : "") << endl;
     }
 
     requestWipeCaches(qname);
@@ -1997,9 +1982,9 @@ static string* doProcessUDPQuestion(const std::string& question, const ComboAddr
     variable = true;
   }
 
-  if(MT->numProcesses() > g_maxMThreads) {
-    if(!g_quiet)
-      g_log<<Logger::Notice<<t_id<<" ["<<MT->getTid()<<"/"<<MT->numProcesses()<<"] DROPPED question from "<<source.toStringWithPort()<<(source != fromaddr ? " (via "+fromaddr.toStringWithPort()+")" : "")<<", over capacity"<<endl;
+  if (MT->numProcesses() > g_maxMThreads) {
+    if (!g_quiet)
+      g_log << Logger::Notice << t_id << " [" << MT->getTid() << "/" << MT->numProcesses() << "] DROPPED question from " << source.toStringWithPort() << (source != fromaddr ? " (via " + fromaddr.toStringWithPort() + ")" : "") << ", over capacity" << endl;
 
     g_stats.overCapacityDrops++;
     return 0;
@@ -2007,13 +1992,13 @@ static string* doProcessUDPQuestion(const std::string& question, const ComboAddr
 
   auto dc = std::make_unique<DNSComboWriter>(question, g_now, std::move(policyTags), std::move(data), std::move(records));
   dc->setSocket(fd);
-  dc->d_tag=ctag;
-  dc->d_qhash=qhash;
+  dc->d_tag = ctag;
+  dc->d_qhash = qhash;
   dc->setRemote(fromaddr);
   dc->setSource(source);
   dc->setLocal(destaddr);
   dc->setDestination(destination);
-  dc->d_tcp=false;
+  dc->d_tcp = false;
   dc->d_ecsFound = ecsFound;
   dc->d_ecsParsed = ecsParsed;
   dc->d_ednssubnet = ednssubnet;
@@ -2037,12 +2022,11 @@ static string* doProcessUDPQuestion(const std::string& question, const ComboAddr
   dc->d_meta = std::move(meta);
 
   dc->d_eventTrace = std::move(eventTrace);
-  MT->makeThread(startDoResolve, (void*) dc.release()); // deletes dc
+  MT->makeThread(startDoResolve, (void*)dc.release()); // deletes dc
 
   return 0;
 }
 
-
 static void handleNewUDPQuestion(int fd, FDMultiplexer::funcparam_t& var)
 {
   ssize_t len;
@@ -2058,14 +2042,14 @@ static void handleNewUDPQuestion(int fd, FDMultiplexer::funcparam_t& var)
   std::vector<ProxyProtocolValue> proxyProtocolValues;
   RecEventTrace eventTrace;
 
-  for(size_t queriesCounter = 0; queriesCounter < s_maxUDPQueriesPerRound; queriesCounter++) {
+  for (size_t queriesCounter = 0; queriesCounter < s_maxUDPQueriesPerRound; queriesCounter++) {
     bool proxyProto = false;
     proxyProtocolValues.clear();
     data.resize(maxIncomingQuerySize);
-    fromaddr.sin6.sin6_family=AF_INET6; // this makes sure fromaddr is big enough
+    fromaddr.sin6.sin6_family = AF_INET6; // this makes sure fromaddr is big enough
     fillMSGHdr(&msgh, &iov, &cbuf, sizeof(cbuf), &data[0], data.size(), &fromaddr);
 
-    if((len=recvmsg(fd, &msgh, 0)) >= 0) {
+    if ((len = recvmsg(fd, &msgh, 0)) >= 0) {
       eventTrace.clear();
       eventTrace.setEnabled(SyncRes::s_event_trace_enabled);
       eventTrace.add(RecEventTrace::ReqRecv);
@@ -2075,7 +2059,7 @@ static void handleNewUDPQuestion(int fd, FDMultiplexer::funcparam_t& var)
       if (msgh.msg_flags & MSG_TRUNC) {
         g_stats.truncatedDrops++;
         if (!g_quiet) {
-          g_log<<Logger::Error<<"Ignoring truncated query from "<<fromaddr.toString()<<endl;
+          g_log << Logger::Error << "Ignoring truncated query from " << fromaddr.toString() << endl;
         }
         return;
       }
@@ -2088,13 +2072,13 @@ static void handleNewUDPQuestion(int fd, FDMultiplexer::funcparam_t& var)
         if (used <= 0) {
           ++g_stats.proxyProtocolInvalidCount;
           if (!g_quiet) {
-            g_log<<Logger::Error<<"Ignoring invalid proxy protocol ("<<std::to_string(len)<<", "<<std::to_string(used)<<") query from "<<fromaddr.toStringWithPort()<<endl;
+            g_log << Logger::Error << "Ignoring invalid proxy protocol (" << std::to_string(len) << ", " << std::to_string(used) << ") query from " << fromaddr.toStringWithPort() << endl;
           }
           return;
         }
         else if (static_cast<size_t>(used) > g_proxyProtocolMaximumSize) {
           if (g_quiet) {
-            g_log<<Logger::Error<<"Proxy protocol header in UDP packet from "<< fromaddr.toStringWithPort() << " is larger than proxy-protocol-maximum-size (" << used << "), dropping"<< endl;
+            g_log << Logger::Error << "Proxy protocol header in UDP packet from " << fromaddr.toStringWithPort() << " is larger than proxy-protocol-maximum-size (" << used << "), dropping" << endl;
           }
           ++g_stats.proxyProtocolInvalidCount;
           return;
@@ -2105,7 +2089,8 @@ static void handleNewUDPQuestion(int fd, FDMultiplexer::funcparam_t& var)
       else if (len > 512) {
         /* we only allow UDP packets larger than 512 for those with a proxy protocol header */
         g_stats.truncatedDrops++;
-        if (!g_quiet) {          g_log<<Logger::Error<<"Ignoring truncated query from "<<fromaddr.toStringWithPort()<<endl;
+        if (!g_quiet) {
+          g_log << Logger::Error << "Ignoring truncated query from " << fromaddr.toStringWithPort() << endl;
         }
         return;
       }
@@ -2113,7 +2098,7 @@ static void handleNewUDPQuestion(int fd, FDMultiplexer::funcparam_t& var)
       if (data.size() < sizeof(dnsheader)) {
         g_stats.ignoredCount++;
         if (!g_quiet) {
-          g_log<<Logger::Error<<"Ignoring too-short ("<<std::to_string(data.size())<<") query from "<<fromaddr.toString()<<endl;
+          g_log << Logger::Error << "Ignoring too-short (" << std::to_string(data.size()) << ") query from " << fromaddr.toString() << endl;
         }
         return;
       }
@@ -2122,13 +2107,13 @@ static void handleNewUDPQuestion(int fd, FDMultiplexer::funcparam_t& var)
         source = fromaddr;
       }
 
-      if(t_remotes) {
+      if (t_remotes) {
         t_remotes->push_back(fromaddr);
       }
 
-      if(t_allowFrom && !t_allowFrom->match(&source)) {
-        if(!g_quiet) {
-          g_log<<Logger::Error<<"["<<MT->getTid()<<"] dropping UDP query from "<<source.toString()<<", address not matched by allow-from"<<endl;
+      if (t_allowFrom && !t_allowFrom->match(&source)) {
+        if (!g_quiet) {
+          g_log << Logger::Error << "[" << MT->getTid() << "] dropping UDP query from " << source.toString() << ", address not matched by allow-from" << endl;
         }
 
         g_stats.unauthorizedUDP++;
@@ -2136,9 +2121,9 @@ static void handleNewUDPQuestion(int fd, FDMultiplexer::funcparam_t& var)
       }
 
       BOOST_STATIC_ASSERT(offsetof(sockaddr_in, sin_port) == offsetof(sockaddr_in6, sin6_port));
-      if(!fromaddr.sin4.sin_port) { // also works for IPv6
-        if(!g_quiet) {
-          g_log<<Logger::Error<<"["<<MT->getTid()<<"] dropping UDP query from "<<fromaddr.toStringWithPort()<<", can't deal with port 0"<<endl;
+      if (!fromaddr.sin4.sin_port) { // also works for IPv6
+        if (!g_quiet) {
+          g_log << Logger::Error << "[" << MT->getTid() << "] dropping UDP query from " << fromaddr.toStringWithPort() << ", can't deal with port 0" << endl;
         }
 
         g_stats.clientParseError++; // not quite the best place to put it, but needs to go somewhere
@@ -2146,31 +2131,31 @@ static void handleNewUDPQuestion(int fd, FDMultiplexer::funcparam_t& var)
       }
 
       try {
-        dnsheader* dh=(dnsheader*)&data[0];
+        dnsheader* dh = (dnsheader*)&data[0];
 
-        if(dh->qr) {
+        if (dh->qr) {
           g_stats.ignoredCount++;
-          if(g_logCommonErrors) {
-            g_log<<Logger::Error<<"Ignoring answer from "<<fromaddr.toString()<<" on server socket!"<<endl;
+          if (g_logCommonErrors) {
+            g_log << Logger::Error << "Ignoring answer from " << fromaddr.toString() << " on server socket!" << endl;
           }
         }
-        else if(dh->opcode != Opcode::Query && dh->opcode != Opcode::Notify) {
+        else if (dh->opcode != Opcode::Query && dh->opcode != Opcode::Notify) {
           g_stats.ignoredCount++;
-          if(g_logCommonErrors) {
-            g_log<<Logger::Error<<"Ignoring unsupported opcode "<<Opcode::to_s(dh->opcode)<<" from "<<fromaddr.toString()<<" on server socket!"<<endl;
+          if (g_logCommonErrors) {
+            g_log << Logger::Error << "Ignoring unsupported opcode " << Opcode::to_s(dh->opcode) << " from " << fromaddr.toString() << " on server socket!" << endl;
           }
         }
         else if (dh->qdcount == 0) {
           g_stats.emptyQueriesCount++;
-          if(g_logCommonErrors) {
-            g_log<<Logger::Error<<"Ignoring empty (qdcount == 0) query from "<<fromaddr.toString()<<" on server socket!"<<endl;
+          if (g_logCommonErrors) {
+            g_log << Logger::Error << "Ignoring empty (qdcount == 0) query from " << fromaddr.toString() << " on server socket!" << endl;
           }
         }
         else {
-          if(dh->opcode == Opcode::Notify) {
-            if(!t_allowNotifyFrom || !t_allowNotifyFrom->match(&source)) {
-              if(!g_quiet) {
-                g_log<<Logger::Error<<"["<<MT->getTid()<<"] dropping UDP NOTIFY from "<<source.toString()<<", address not matched by allow-notify-from"<<endl;
+          if (dh->opcode == Opcode::Notify) {
+            if (!t_allowNotifyFrom || !t_allowNotifyFrom->match(&source)) {
+              if (!g_quiet) {
+                g_log << Logger::Error << "[" << MT->getTid() << "] dropping UDP NOTIFY from " << source.toString() << ", address not matched by allow-notify-from" << endl;
               }
 
               g_stats.sourceDisallowedNotify++;
@@ -2178,19 +2163,19 @@ static void handleNewUDPQuestion(int fd, FDMultiplexer::funcparam_t& var)
             }
           }
 
-          struct timeval tv={0,0};
+          struct timeval tv = {0, 0};
           HarvestTimestamp(&msgh, &tv);
           ComboAddress dest;
           dest.reset(); // this makes sure we ignore this address if not returned by recvmsg above
           auto loc = rplookup(g_listenSocketsAddresses, fd);
-          if(HarvestDestinationAddress(&msgh, &dest)) {
+          if (HarvestDestinationAddress(&msgh, &dest)) {
             // but.. need to get port too
-            if(loc) {
+            if (loc) {
               dest.sin4.sin_port = loc->sin4.sin_port;
             }
           }
           else {
-            if(loc) {
+            if (loc) {
               dest = *loc;
             }
             else {
@@ -2203,7 +2188,7 @@ static void handleNewUDPQuestion(int fd, FDMultiplexer::funcparam_t& var)
             destination = dest;
           }
 
-          if(g_weDistributeQueries) {
+          if (g_weDistributeQueries) {
             std::string localdata = data;
             distributeAsyncFunction(data, [localdata, fromaddr, dest, source, destination, tv, fd, proxyProtocolValues, eventTrace]() mutable {
               return doProcessUDPQuestion(localdata, fromaddr, dest, source, destination, tv, fd, proxyProtocolValues, eventTrace);
@@ -2214,22 +2199,22 @@ static void handleNewUDPQuestion(int fd, FDMultiplexer::funcparam_t& var)
           }
         }
       }
-      catch(const MOADNSException &mde) {
+      catch (const MOADNSException& mde) {
         g_stats.clientParseError++;
-        if(g_logCommonErrors) {
-          g_log<<Logger::Error<<"Unable to parse packet from remote UDP client "<<fromaddr.toString() <<": "<<mde.what()<<endl;
+        if (g_logCommonErrors) {
+          g_log << Logger::Error << "Unable to parse packet from remote UDP client " << fromaddr.toString() << ": " << mde.what() << endl;
         }
       }
-      catch(const std::runtime_error& e) {
+      catch (const std::runtime_error& e) {
         g_stats.clientParseError++;
-        if(g_logCommonErrors) {
-          g_log<<Logger::Error<<"Unable to parse packet from remote UDP client "<<fromaddr.toString() <<": "<<e.what()<<endl;
+        if (g_logCommonErrors) {
+          g_log << Logger::Error << "Unable to parse packet from remote UDP client " << fromaddr.toString() << ": " << e.what() << endl;
         }
       }
     }
     else {
       // cerr<<t_id<<" had error: "<<stringerror()<<endl;
-      if(firstQuery && errno == EAGAIN) {
+      if (firstQuery && errno == EAGAIN) {
         g_stats.noPacketError++;
       }
 
@@ -2240,51 +2225,51 @@ static void handleNewUDPQuestion(int fd, FDMultiplexer::funcparam_t& var)
 
 void makeUDPServerSockets(deferredAdd_t& deferredAdds)
 {
-  int one=1;
-  vector<string>locals;
-  stringtok(locals,::arg()["local-address"]," ,");
+  int one = 1;
+  vector<string> locals;
+  stringtok(locals, ::arg()["local-address"], " ,");
 
-  if(locals.empty())
+  if (locals.empty())
     throw PDNSException("No local address specified");
 
-  for(vector<string>::const_iterator i=locals.begin();i!=locals.end();++i) {
+  for (vector<string>::const_iterator i = locals.begin(); i != locals.end(); ++i) {
     ServiceTuple st;
-    st.port=::arg().asNum("local-port");
+    st.port = ::arg().asNum("local-port");
     parseService(*i, st);
 
     ComboAddress sin;
 
     sin.reset();
     sin.sin4.sin_family = AF_INET;
-    if(!IpToU32(st.host.c_str() , (uint32_t*)&sin.sin4.sin_addr.s_addr)) {
+    if (!IpToU32(st.host.c_str(), (uint32_t*)&sin.sin4.sin_addr.s_addr)) {
       sin.sin6.sin6_family = AF_INET6;
-      if(makeIPv6sockaddr(st.host, &sin.sin6) < 0)
-        throw PDNSException("Unable to resolve local address for UDP server on '"+ st.host +"'");
+      if (makeIPv6sockaddr(st.host, &sin.sin6) < 0)
+        throw PDNSException("Unable to resolve local address for UDP server on '" + st.host + "'");
     }
 
-    int fd=socket(sin.sin4.sin_family, SOCK_DGRAM, 0);
-    if(fd < 0) {
-      throw PDNSException("Making a UDP server socket for resolver: "+stringerror());
+    int fd = socket(sin.sin4.sin_family, SOCK_DGRAM, 0);
+    if (fd < 0) {
+      throw PDNSException("Making a UDP server socket for resolver: " + stringerror());
     }
     if (!setSocketTimestamps(fd))
-      g_log<<Logger::Warning<<"Unable to enable timestamp reporting for socket"<<endl;
+      g_log << Logger::Warning << "Unable to enable timestamp reporting for socket" << endl;
 
-    if(IsAnyAddress(sin)) {
-      if(sin.sin4.sin_family == AF_INET)
-        if(!setsockopt(fd, IPPROTO_IP, GEN_IP_PKTINFO, &one, sizeof(one)))     // linux supports this, so why not - might fail on other systems
+    if (IsAnyAddress(sin)) {
+      if (sin.sin4.sin_family == AF_INET)
+        if (!setsockopt(fd, IPPROTO_IP, GEN_IP_PKTINFO, &one, sizeof(one))) // linux supports this, so why not - might fail on other systems
           g_fromtosockets.insert(fd);
 #ifdef IPV6_RECVPKTINFO
-      if(sin.sin4.sin_family == AF_INET6)
-        if(!setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &one, sizeof(one)))
+      if (sin.sin4.sin_family == AF_INET6)
+        if (!setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &one, sizeof(one)))
           g_fromtosockets.insert(fd);
 #endif
-      if(sin.sin6.sin6_family == AF_INET6 && setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &one, sizeof(one)) < 0) {
+      if (sin.sin6.sin6_family == AF_INET6 && setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &one, sizeof(one)) < 0) {
         int err = errno;
-             g_log<<Logger::Error<<"Failed to set IPv6 socket to IPv6 only, continuing anyhow: "<<strerror(err)<<endl;
+        g_log << Logger::Error << "Failed to set IPv6 socket to IPv6 only, continuing anyhow: " << strerror(err) << endl;
       }
     }
-    if( ::arg().mustDo("non-local-bind") )
-       Utility::setBindAny(AF_INET6, fd);
+    if (::arg().mustDo("non-local-bind"))
+      Utility::setBindAny(AF_INET6, fd);
 
     setCloseOnExec(fd);
 
@@ -2292,11 +2277,10 @@ void makeUDPServerSockets(deferredAdd_t& deferredAdds)
       setSocketReceiveBuffer(fd, 250000);
     }
     catch (const std::exception& e) {
-      g_log<<Logger::Error<<e.what()<<endl;
+      g_log << Logger::Error << e.what() << endl;
     }
     sin.sin4.sin_port = htons(st.port);
 
-  
     if (g_reusePort) {
 #if defined(SO_REUSEPORT_LB)
       try {
@@ -2318,32 +2302,30 @@ void makeUDPServerSockets(deferredAdd_t& deferredAdds)
     try {
       setSocketIgnorePMTU(fd, sin.sin4.sin_family);
     }
-    catch(const std::exception& e) {
-      g_log<<Logger::Warning<<"Failed to set IP_MTU_DISCOVER on UDP server socket: "<<e.what()<<endl;
+    catch (const std::exception& e) {
+      g_log << Logger::Warning << "Failed to set IP_MTU_DISCOVER on UDP server socket: " << e.what() << endl;
     }
 
-    socklen_t socklen=sin.getSocklen();
-    if (::bind(fd, (struct sockaddr *)&sin, socklen)<0)
-      throw PDNSException("Resolver binding to server socket on port "+ std::to_string(st.port) +" for "+ st.host+": "+stringerror());
+    socklen_t socklen = sin.getSocklen();
+    if (::bind(fd, (struct sockaddr*)&sin, socklen) < 0)
+      throw PDNSException("Resolver binding to server socket on port " + std::to_string(st.port) + " for " + st.host + ": " + stringerror());
 
     setNonBlocking(fd);
 
     deferredAdds.emplace_back(fd, handleNewUDPQuestion);
-    g_listenSocketsAddresses[fd]=sin;  // this is written to only from the startup thread, not from the workers
-    if(sin.sin4.sin_family == AF_INET)
-      g_log<<Logger::Info<<"Listening for UDP queries on "<< sin.toString() <<":"<<st.port<<endl;
+    g_listenSocketsAddresses[fd] = sin; // this is written to only from the startup thread, not from the workers
+    if (sin.sin4.sin_family == AF_INET)
+      g_log << Logger::Info << "Listening for UDP queries on " << sin.toString() << ":" << st.port << endl;
     else
-      g_log<<Logger::Info<<"Listening for UDP queries on ["<< sin.toString() <<"]:"<<st.port<<endl;
+      g_log << Logger::Info << "Listening for UDP queries on [" << sin.toString() << "]:" << st.port << endl;
   }
 }
 
-
-
 static bool trySendingQueryToWorker(unsigned int target, ThreadMSG* tmsg)
 {
   auto& targetInfo = s_threadInfos[target];
-  if(!targetInfo.isWorker) {
-    g_log<<Logger::Error<<"distributeAsyncFunction() tried to assign a query to a non-worker thread"<<endl;
+  if (!targetInfo.isWorker) {
+    g_log << Logger::Error << "distributeAsyncFunction() tried to assign a query to a non-worker thread" << endl;
     _exit(1);
   }
 
@@ -2360,7 +2342,8 @@ static bool trySendingQueryToWorker(unsigned int target, ThreadMSG* tmsg)
     int error = errno;
     if (error == EAGAIN || error == EWOULDBLOCK) {
       return false;
-    } else {
+    }
+    else {
       delete tmsg;
       unixDie("write to thread pipe returned wrong size or error:" + std::to_string(error));
     }
@@ -2403,8 +2386,7 @@ static unsigned int selectWorker(unsigned int hash)
     do {
       // cerr<<"worker "<<worker<<" is above the target load, selecting another one"<<endl;
       worker = (worker + 1) % g_numWorkerThreads;
-    }
-    while(load[worker] > targetLoad);
+    } while (load[worker] > targetLoad);
   }
 
   return /* skip handler */ 1 + g_numDistributorThreads + worker;
@@ -2414,7 +2396,7 @@ static unsigned int selectWorker(unsigned int hash)
 void distributeAsyncFunction(const string& packet, const pipefunc_t& func)
 {
   if (!isDistributorThread()) {
-    g_log<<Logger::Error<<"distributeAsyncFunction() has been called by a worker ("<<t_id<<")"<<endl;
+    g_log << Logger::Error << "distributeAsyncFunction() has been called by a worker (" << t_id << ")" << endl;
     _exit(1);
   }
 
@@ -2440,17 +2422,15 @@ void distributeAsyncFunction(const string& packet, const pipefunc_t& func)
   }
 }
 
-
-
 // resend event to everybody chained onto it
 static void doResends(MT_t::waiters_t::iterator& iter, const std::shared_ptr<PacketID>& resend, const PacketBuffer& content)
 {
   // We close the chain for new entries, since they won't be processed anyway
   iter->key->closed = true;
 
-  if(iter->key->chain.empty())
+  if (iter->key->chain.empty())
     return;
-  for(PacketID::chain_t::iterator i=iter->key->chain.begin(); i != iter->key->chain.end() ; ++i) {
+  for (PacketID::chain_t::iterator i = iter->key->chain.begin(); i != iter->key->chain.end(); ++i) {
     auto r = std::make_shared<PacketID>(*resend);
     r->fd = -1;
     r->id = *i;
@@ -2466,25 +2446,24 @@ static void handleUDPServerResponse(int fd, FDMultiplexer::funcparam_t& var)
   PacketBuffer packet;
   packet.resize(g_outgoingEDNSBufsize);
   ComboAddress fromaddr;
-  socklen_t addrlen=sizeof(fromaddr);
+  socklen_t addrlen = sizeof(fromaddr);
 
-  len=recvfrom(fd, &packet.at(0), packet.size(), 0, (sockaddr *)&fromaddr, &addrlen);
+  len = recvfrom(fd, &packet.at(0), packet.size(), 0, (sockaddr*)&fromaddr, &addrlen);
 
-  if(len < (ssize_t) sizeof(dnsheader)) {
-    if(len < 0)
+  if (len < (ssize_t)sizeof(dnsheader)) {
+    if (len < 0)
       ; //      cerr<<"Error on fd "<<fd<<": "<<stringerror()<<"\n";
     else {
       g_stats.serverParseError++;
-      if(g_logCommonErrors)
-        g_log<<Logger::Error<<"Unable to parse packet from remote UDP server "<< fromaddr.toString() <<
-          ": packet smaller than DNS header"<<endl;
+      if (g_logCommonErrors)
+        g_log << Logger::Error << "Unable to parse packet from remote UDP server " << fromaddr.toString() << ": packet smaller than DNS header" << endl;
     }
 
     t_udpclientsocks->returnSocket(fd);
     PacketBuffer empty;
 
-    MT_t::waiters_t::iterator iter=MT->d_waiters.find(pid);
-    if(iter != MT->d_waiters.end())
+    MT_t::waiters_t::iterator iter = MT->d_waiters.find(pid);
+    if (iter != MT->d_waiters.end())
       doResends(iter, pid, empty);
 
     MT->sendEvent(pid, &empty); // this denotes error (does lookup again.. at least L1 will be hot)
@@ -2500,41 +2479,40 @@ static void handleUDPServerResponse(int fd, FDMultiplexer::funcparam_t& var)
   pident->id = dh.id;
   pident->fd = fd;
 
-  if(!dh.qr && g_logCommonErrors) {
-    g_log<<Logger::Notice<<"Not taking data from question on outgoing socket from "<< fromaddr.toStringWithPort()  <<endl;
+  if (!dh.qr && g_logCommonErrors) {
+    g_log << Logger::Notice << "Not taking data from question on outgoing socket from " << fromaddr.toStringWithPort() << endl;
   }
 
-  if(!dh.qdcount || // UPC, Nominum, very old BIND on FormErr, NSD
-     !dh.qr) {      // one weird server
+  if (!dh.qdcount || // UPC, Nominum, very old BIND on FormErr, NSD
+      !dh.qr) { // one weird server
     pident->domain.clear();
     pident->type = 0;
   }
   else {
     try {
-      if(len > 12)
-        pident->domain=DNSName(reinterpret_cast<const char *>(packet.data()), len, 12, false, &pident->type); // don't copy this from above - we need to do the actual read
+      if (len > 12)
+        pident->domain = DNSName(reinterpret_cast<const char*>(packet.data()), len, 12, false, &pident->type); // don't copy this from above - we need to do the actual read
     }
-    catch(std::exception& e) {
+    catch (std::exception& e) {
       g_stats.serverParseError++; // won't be fed to lwres.cc, so we have to increment
-      g_log<<Logger::Warning<<"Error in packet from remote nameserver "<< fromaddr.toStringWithPort() << ": "<<e.what() << endl;
+      g_log << Logger::Warning << "Error in packet from remote nameserver " << fromaddr.toStringWithPort() << ": " << e.what() << endl;
       return;
     }
   }
 
-  MT_t::waiters_t::iterator iter=MT->d_waiters.find(pident);
-  if(iter != MT->d_waiters.end()) {
+  MT_t::waiters_t::iterator iter = MT->d_waiters.find(pident);
+  if (iter != MT->d_waiters.end()) {
     doResends(iter, pident, packet);
   }
 
 retryWithName:
 
-  if(!MT->sendEvent(pident, &packet)) {
+  if (!MT->sendEvent(pident, &packet)) {
     /* we did not find a match for this response, something is wrong */
 
     // we do a full scan for outstanding queries on unexpected answers. not too bad since we only accept them on the right port number, which is hard enough to guess
     for (MT_t::waiters_t::iterator mthread = MT->d_waiters.begin(); mthread != MT->d_waiters.end(); ++mthread) {
-      if (pident->fd == mthread->key->fd && mthread->key->remote == pident->remote &&  mthread->key->type == pident->type &&
-         pident->domain == mthread->key->domain) {
+      if (pident->fd == mthread->key->fd && mthread->key->remote == pident->remote && mthread->key->type == pident->type && pident->domain == mthread->key->domain) {
         /* we are expecting an answer from that exact source, on that exact port (since we are using connected sockets), for that qname/qtype,
            but with a different message ID. That smells like a spoofing attempt. For now we will just increase the counter and will deal with
            that later. */
@@ -2542,8 +2520,7 @@ retryWithName:
       }
 
       // be a bit paranoid here since we're weakening our matching
-      if(pident->domain.empty() && !mthread->key->domain.empty() && !pident->type && mthread->key->type &&
-         pident->id  == mthread->key->id && mthread->key->remote == pident->remote) {
+      if (pident->domain.empty() && !mthread->key->domain.empty() && !pident->type && mthread->key->type && pident->id == mthread->key->id && mthread->key->remote == pident->remote) {
         // cerr<<"Empty response, rest matches though, sending to a waiter"<<endl;
         pident->domain = mthread->key->domain;
         pident->type = mthread->key->type;
@@ -2551,13 +2528,12 @@ retryWithName:
       }
     }
     g_stats.unexpectedCount++; // if we made it here, it really is an unexpected answer
-    if(g_logCommonErrors) {
-      g_log<<Logger::Warning<<"Discarding unexpected packet from "<<fromaddr.toStringWithPort()<<": "<< (pident->domain.empty() ? "<empty>" : pident->domain.toString())<<", "<<pident->type<<", "<<MT->d_waiters.size()<<" waiters"<<endl;
+    if (g_logCommonErrors) {
+      g_log << Logger::Warning << "Discarding unexpected packet from " << fromaddr.toStringWithPort() << ": " << (pident->domain.empty() ? "<empty>" : pident->domain.toString()) << ", " << pident->type << ", " << MT->d_waiters.size() << " waiters" << endl;
     }
   }
-  else if(fd >= 0) {
+  else if (fd >= 0) {
     /* we either found a waiter (1) or encountered an issue (-1), it's up to us to clean the socket anyway */
     t_udpclientsocks->returnSocket(fd);
   }
 }
-
index 420c5de448e32eb985c88b803ea51198d74d8723..776bf3ffe6d4195cd9ca5dd1d7551493bf9d1c19 100644 (file)
@@ -160,8 +160,8 @@ pdns_recursor_SOURCES = \
        rcpgenerator.cc rcpgenerator.hh \
        rec-carbon.cc \
        rec-eventtrace.cc rec-eventtrace.hh \
-       ec-main.hh rec-main.cc \
        rec-lua-conf.hh rec-lua-conf.cc \
+       rec-main.hh rec-main.cc \
        rec-protozero.cc rec-protozero.hh \
        rec-snmp.hh rec-snmp.cc \
        rec-taskqueue.cc rec-taskqueue.hh \
index accab8a169939e30588f66d33f1bb7baebc80a94..0a5895f9272aacef17dc2ec93851e6e474b4f666 100644 (file)
@@ -60,7 +60,7 @@ thread_local std::shared_ptr<std::vector<std::unique_ptr<FrameStreamLogger>>> t_
 thread_local uint64_t t_frameStreamServersGeneration;
 #endif /* HAVE_FSTRM */
 
-string s_programname="pdns_recursor";
+string s_programname = "pdns_recursor";
 string s_pidfname;
 RecursorControlChannel s_rcc; // only active in the handler thread
 
@@ -108,7 +108,7 @@ deferredAdd_t g_deferredAdds;
    and finally the workers */
 std::vector<RecThreadInfo> s_threadInfos;
 
-ArgvMap &arg()
+ArgvMaparg()
 {
   static ArgvMap theArg;
   return theArg;
@@ -117,19 +117,19 @@ ArgvMap &arg()
 static FDMultiplexer* getMultiplexer()
 {
   FDMultiplexer* ret;
-  for(const auto& i : FDMultiplexer::getMultiplexerMap()) {
+  for (const auto& i : FDMultiplexer::getMultiplexerMap()) {
     try {
-      ret=i.second();
+      ret = i.second();
       return ret;
     }
-    catch(FDMultiplexerException &fe) {
-      g_log<<Logger::Error<<"Non-fatal error initializing possible multiplexer ("<<fe.what()<<"), falling back"<<endl;
+    catch (FDMultiplexerException& fe) {
+      g_log << Logger::Error << "Non-fatal error initializing possible multiplexer (" << fe.what() << "), falling back" << endl;
     }
-    catch(...) {
-      g_log<<Logger::Error<<"Non-fatal error initializing possible multiplexer"<<endl;
+    catch (...) {
+      g_log << Logger::Error << "Non-fatal error initializing possible multiplexer" << endl;
     }
   }
-  g_log<<Logger::Error<<"No working multiplexer found!"<<endl;
+  g_log << Logger::Error << "No working multiplexer found!" << endl;
   _exit(1);
 }
 
@@ -139,16 +139,16 @@ static std::shared_ptr<std::vector<std::unique_ptr<RemoteLogger>>> startProtobuf
 
   for (const auto& server : config.servers) {
     try {
-      auto logger = make_unique<RemoteLogger>(server, config.timeout, 100*config.maxQueuedEntries, config.reconnectWaitTime, config.asyncConnect);
+      auto logger = make_unique<RemoteLogger>(server, config.timeout, 100 * config.maxQueuedEntries, config.reconnectWaitTime, config.asyncConnect);
       logger->setLogQueries(config.logQueries);
       logger->setLogResponses(config.logResponses);
       result->emplace_back(std::move(logger));
     }
-    catch(const std::exception& e) {
-      g_log<<Logger::Error<<"Error while starting protobuf logger to '"<<server<<": "<<e.what()<<endl;
+    catch (const std::exception& e) {
+      g_log << Logger::Error << "Error while starting protobuf logger to '" << server << ": " << e.what() << endl;
     }
-    catch(const PDNSException& e) {
-      g_log<<Logger::Error<<"Error while starting protobuf logger to '"<<server<<": "<<e.reason<<endl;
+    catch (const PDNSException& e) {
+      g_log << Logger::Error << "Error while starting protobuf logger to '" << server << ": " << e.reason << endl;
     }
   }
 
@@ -170,8 +170,7 @@ bool checkProtobufExport(LocalStateHolder<LuaConfigItems>& luaconfsLocal)
 
   /* if the server was not running, or if it was running according to a
      previous configuration */
-  if (!t_protobufServers ||
-      t_protobufServersGeneration < luaconfsLocal->generation) {
+  if (!t_protobufServers || t_protobufServersGeneration < luaconfsLocal->generation) {
 
     if (t_protobufServers) {
       for (auto& server : *t_protobufServers) {
@@ -202,8 +201,7 @@ bool checkOutgoingProtobufExport(LocalStateHolder<LuaConfigItems>& luaconfsLocal
 
   /* if the server was not running, or if it was running according to a
      previous configuration */
-  if (!t_outgoingProtobufServers ||
-      t_outgoingProtobufServersGeneration < luaconfsLocal->generation) {
+  if (!t_outgoingProtobufServers || t_outgoingProtobufServersGeneration < luaconfsLocal->generation) {
 
     if (t_outgoingProtobufServers) {
       for (auto& server : *t_outgoingProtobufServers) {
@@ -264,12 +262,12 @@ void protobufLogResponse(pdns::ProtoZero::RecMessage& message)
 }
 
 void protobufLogResponse(const struct dnsheader* dh, LocalStateHolder<LuaConfigItems>& luaconfsLocal,
-                                const RecursorPacketCache::OptPBData& pbData, const struct timeval& tv,
-                                bool tcp, const ComboAddress& source, const ComboAddress& destination,
-                                const EDNSSubnetOpts& ednssubnet,
-                                const boost::uuids::uuid& uniqueId, const string& requestorId, const string& deviceId,
-                                const string& deviceName, const std::map<std::string, RecursorLua4::MetaValue>& meta,
-                                const RecEventTrace& eventTrace)
+                         const RecursorPacketCache::OptPBData& pbData, const struct timeval& tv,
+                         bool tcp, const ComboAddress& source, const ComboAddress& destination,
+                         const EDNSSubnetOpts& ednssubnet,
+                         const boost::uuids::uuid& uniqueId, const string& requestorId, const string& deviceId,
+                         const string& deviceName, const std::map<std::string, RecursorLua4::MetaValue>& meta,
+                         const RecEventTrace& eventTrace)
 {
   pdns::ProtoZero::RecMessage pbMessage(pbData ? pbData->d_message : "", pbData ? pbData->d_response : "", 64, 10); // The extra bytes we are going to add
   // Normally we take the immutable string from the cache and append a few values, but if it's not there (can this happen?)
@@ -325,14 +323,14 @@ static std::shared_ptr<std::vector<std::unique_ptr<FrameStreamLogger>>> startFra
 
   for (const auto& server : config.servers) {
     try {
-      std::unordered_map<string,unsigned> options;
+      std::unordered_map<string, unsigned> options;
       options["bufferHint"] = config.bufferHint;
       options["flushTimeout"] = config.flushTimeout;
       options["inputQueueSize"] = config.inputQueueSize;
       options["outputQueueSize"] = config.outputQueueSize;
       options["queueNotifyThreshold"] = config.queueNotifyThreshold;
       options["reopenInterval"] = config.reopenInterval;
-      FrameStreamLogger *fsl = nullptr;
+      FrameStreamLoggerfsl = nullptr;
       try {
         ComboAddress address(server);
         fsl = new FrameStreamLogger(address.sin4.sin_family, address.toStringWithPort(), true, options);
@@ -344,11 +342,11 @@ static std::shared_ptr<std::vector<std::unique_ptr<FrameStreamLogger>>> startFra
       fsl->setLogResponses(config.logResponses);
       result->emplace_back(fsl);
     }
-    catch(const std::exception& e) {
-      g_log<<Logger::Error<<"Error while starting dnstap framestream logger to '"<<server<<": "<<e.what()<<endl;
+    catch (const std::exception& e) {
+      g_log << Logger::Error << "Error while starting dnstap framestream logger to '" << server << ": " << e.what() << endl;
     }
-    catch(const PDNSException& e) {
-      g_log<<Logger::Error<<"Error while starting dnstap framestream logger to '"<<server<<": "<<e.reason<<endl;
+    catch (const PDNSException& e) {
+      g_log << Logger::Error << "Error while starting dnstap framestream logger to '" << server << ": " << e.reason << endl;
     }
   }
 
@@ -368,8 +366,7 @@ bool checkFrameStreamExport(LocalStateHolder<LuaConfigItems>& luaconfsLocal)
 
   /* if the server was not running, or if it was running according to a
      previous configuration */
-  if (!t_frameStreamServers ||
-      t_frameStreamServersGeneration < luaconfsLocal->generation) {
+  if (!t_frameStreamServers || t_frameStreamServersGeneration < luaconfsLocal->generation) {
 
     if (t_frameStreamServers) {
       // dt's take care of cleanup
@@ -384,32 +381,32 @@ bool checkFrameStreamExport(LocalStateHolder<LuaConfigItems>& luaconfsLocal)
 }
 #endif /* HAVE_FSTRM */
 
-static void makeControlChannelSocket(int processNum=-1)
+static void makeControlChannelSocket(int processNum = -1)
 {
-  string sockname=::arg()["socket-dir"]+"/"+s_programname;
-  if(processNum >= 0)
-    sockname += "."+std::to_string(processNum);
-  sockname+=".controlsocket";
+  string sockname = ::arg()["socket-dir"] + "/" + s_programname;
+  if (processNum >= 0)
+    sockname += "." + std::to_string(processNum);
+  sockname += ".controlsocket";
   s_rcc.listen(sockname);
 
   int sockowner = -1;
   int sockgroup = -1;
 
   if (!::arg().isEmpty("socket-group"))
-    sockgroup=::arg().asGid("socket-group");
+    sockgroup = ::arg().asGid("socket-group");
   if (!::arg().isEmpty("socket-owner"))
-    sockowner=::arg().asUid("socket-owner");
+    sockowner = ::arg().asUid("socket-owner");
 
   if (sockgroup > -1 || sockowner > -1) {
-    if(chown(sockname.c_str(), sockowner, sockgroup) < 0) {
+    if (chown(sockname.c_str(), sockowner, sockgroup) < 0) {
       unixDie("Failed to chown control socket");
     }
   }
 
   // do mode change if socket-mode is given
-  if(!::arg().isEmpty("socket-mode")) {
-    mode_t sockmode=::arg().asMode("socket-mode");
-    if(chmod(sockname.c_str(), sockmode) < 0) {
+  if (!::arg().isEmpty("socket-mode")) {
+    mode_t sockmode = ::arg().asMode("socket-mode");
+    if (chmod(sockname.c_str(), sockmode) < 0) {
       unixDie("Failed to chmod control socket");
     }
   }
@@ -417,11 +414,11 @@ static void makeControlChannelSocket(int processNum=-1)
 
 static void writePid(void)
 {
-  if(!::arg().mustDo("write-pid"))
+  if (!::arg().mustDo("write-pid"))
     return;
   ofstream of(s_pidfname.c_str(), std::ios_base::app);
-  if(of)
-    of<< Utility::getpid() <<endl;
+  if (of)
+    of << Utility::getpid() << endl;
   else {
     int err = errno;
     g_log << Logger::Error << "Writing pid for " << Utility::getpid() << " to " << s_pidfname << " failed: "
@@ -429,14 +426,14 @@ static void writePid(void)
   }
 }
 
-static std::map<unsigned int, std::set<int> > parseCPUMap()
+static std::map<unsigned int, std::set<int>> parseCPUMap()
 {
-  std::map<unsigned int, std::set<int> > result;
+  std::map<unsigned int, std::set<int>> result;
 
   const std::string value = ::arg()["cpu-map"];
 
   if (!value.empty() && !isSettingThreadCPUAffinitySupported()) {
-    g_log<<Logger::Warning<<"CPU mapping requested but not supported, skipping"<<endl;
+    g_log << Logger::Warning << "CPU mapping requested but not supported, skipping" << endl;
     return result;
   }
 
@@ -444,7 +441,7 @@ static std::map<unsigned int, std::set<int> > parseCPUMap()
 
   stringtok(parts, value, " \t");
 
-  for(const auto& part : parts) {
+  for (const auto& part : parts) {
     if (part.find('=') == string::npos)
       continue;
 
@@ -458,38 +455,38 @@ static std::map<unsigned int, std::set<int> > parseCPUMap()
 
       stringtok(cpus, headers.second, ",");
 
-      for(const auto& cpu : cpus) {
+      for (const auto& cpu : cpus) {
         int cpuId = std::stoi(cpu);
 
         result[threadId].insert(cpuId);
       }
     }
-    catch(const std::exception& e) {
-      g_log<<Logger::Error<<"Error parsing cpu-map entry '"<<part<<"': "<<e.what()<<endl;
+    catch (const std::exception& e) {
+      g_log << Logger::Error << "Error parsing cpu-map entry '" << part << "': " << e.what() << endl;
     }
   }
 
   return result;
 }
 
-static void setCPUMap(const std::map<unsigned int, std::set<int> >& cpusMap, unsigned int n, pthread_t tid)
+static void setCPUMap(const std::map<unsigned int, std::set<int>>& cpusMap, unsigned int n, pthread_t tid)
 {
   const auto& cpuMapping = cpusMap.find(n);
   if (cpuMapping != cpusMap.cend()) {
     int rc = mapThreadToCPUList(tid, cpuMapping->second);
     if (rc == 0) {
-      g_log<<Logger::Info<<"CPU affinity for worker "<<n<<" has been set to CPU map:";
+      g_log << Logger::Info << "CPU affinity for worker " << n << " has been set to CPU map:";
       for (const auto cpu : cpuMapping->second) {
-        g_log<<Logger::Info<<" "<<cpu;
+        g_log << Logger::Info << " " << cpu;
       }
-      g_log<<Logger::Info<<endl;
+      g_log << Logger::Info << endl;
     }
     else {
-      g_log<<Logger::Warning<<"Error setting CPU affinity for worker "<<n<<" to CPU map:";
+      g_log << Logger::Warning << "Error setting CPU affinity for worker " << n << " to CPU map:";
       for (const auto cpu : cpuMapping->second) {
-        g_log<<Logger::Info<<" "<<cpu;
+        g_log << Logger::Info << " " << cpu;
       }
-      g_log<<Logger::Info<<strerror(rc)<<endl;
+      g_log << Logger::Info << strerror(rc) << endl;
     }
   }
 }
@@ -506,9 +503,10 @@ static void checkSocketDir(void)
   else if (!S_ISDIR(st.st_mode)) {
     msg = "it is not a directory";
   }
-  else if (access(dir.c_str(),  R_OK | W_OK | X_OK) != 0) {
+  else if (access(dir.c_str(), R_OK | W_OK | X_OK) != 0) {
     msg = "cannot read, write or search";
-  } else {
+  }
+  else {
     return;
   }
   g_log << Logger::Error << "Problem with socket directory " << dir << ": " << msg << "; see https://docs.powerdns.com/recursor/upgrade.html#x-to-4-3-0" << endl;
@@ -525,11 +523,11 @@ static void setupNODThread()
       t_nodDBp->setCacheDir(::arg()["new-domain-history-dir"]);
     }
     catch (const PDNSException& e) {
-      g_log<<Logger::Error<<"new-domain-history-dir (" << ::arg()["new-domain-history-dir"] << ") is not readable or does not exist"<<endl;
+      g_log << Logger::Error << "new-domain-history-dir (" << ::arg()["new-domain-history-dir"] << ") is not readable or does not exist" << endl;
       _exit(1);
     }
     if (!t_nodDBp->init()) {
-      g_log<<Logger::Error<<"Could not initialize domain tracking"<<endl;
+      g_log << Logger::Error << "Could not initialize domain tracking" << endl;
       _exit(1);
     }
     std::thread t(nod::NODDB::startHousekeepingThread, t_nodDBp, std::this_thread::get_id());
@@ -543,11 +541,11 @@ static void setupNODThread()
       t_udrDBp->setCacheDir(::arg()["unique-response-history-dir"]);
     }
     catch (const PDNSException& e) {
-      g_log<<Logger::Error<<"unique-response-history-dir (" << ::arg()["unique-response-history-dir"] << ") is not readable or does not exist"<<endl;
+      g_log << Logger::Error << "unique-response-history-dir (" << ::arg()["unique-response-history-dir"] << ") is not readable or does not exist" << endl;
       _exit(1);
     }
     if (!t_udrDBp->init()) {
-      g_log<<Logger::Error<<"Could not initialize unique response tracking"<<endl;
+      g_log << Logger::Error << "Could not initialize unique response tracking" << endl;
       _exit(1);
     }
     std::thread t(nod::UniqueResponseDB::startHousekeepingThread, t_udrDBp, std::this_thread::get_id());
@@ -560,7 +558,7 @@ static void parseNODIgnorelist(const std::string& wlist)
 {
   vector<string> parts;
   stringtok(parts, wlist, ",; ");
-  for(const auto& a : parts) {
+  for (const auto& a : parts) {
     g_nodDomainWL.add(DNSName(a));
   }
 }
@@ -582,18 +580,18 @@ static void setupNODGlobal()
 
 static void daemonize(void)
 {
-  if(fork())
+  if (fork())
     exit(0); // bye bye
 
   setsid();
 
-  int i=open("/dev/null",O_RDWR); /* open stdin */
-  if(i < 0)
-    g_log<<Logger::Critical<<"Unable to open /dev/null: "<<stringerror()<<endl;
+  int i = open("/dev/null", O_RDWR); /* open stdin */
+  if (i < 0)
+    g_log << Logger::Critical << "Unable to open /dev/null: " << stringerror() << endl;
   else {
-    dup2(i,0); /* stdin */
-    dup2(i,1); /* stderr */
-    dup2(i,2); /* stderr */
+    dup2(i, 0); /* stdin */
+    dup2(i, 1); /* stderr */
+    dup2(i, 2); /* stderr */
     close(i);
   }
 }
@@ -605,52 +603,52 @@ static void termIntHandler(int)
 
 static void usr1Handler(int)
 {
-  statsWanted=true;
+  statsWanted = true;
 }
 
 static void usr2Handler(int)
 {
-  g_quiet= !g_quiet;
+  g_quiet = !g_quiet;
   SyncRes::setDefaultLogMode(g_quiet ? SyncRes::LogNone : SyncRes::Log);
-  ::arg().set("quiet")=g_quiet ? "" : "no";
+  ::arg().set("quiet") = g_quiet ? "" : "no";
 }
 
 static void checkLinuxIPv6Limits()
 {
 #ifdef __linux__
   string line;
-  if(readFileIfThere("/proc/sys/net/ipv6/route/max_size", &line)) {
-    int lim=std::stoi(line);
-    if(lim < 16384) {
-      g_log<<Logger::Error<<"If using IPv6, please raise sysctl net.ipv6.route.max_size, currently set to "<<lim<<" which is < 16384"<<endl;
+  if (readFileIfThere("/proc/sys/net/ipv6/route/max_size", &line)) {
+    int lim = std::stoi(line);
+    if (lim < 16384) {
+      g_log << Logger::Error << "If using IPv6, please raise sysctl net.ipv6.route.max_size, currently set to " << lim << " which is < 16384" << endl;
     }
   }
 #endif
 }
 static void checkOrFixFDS()
 {
-  unsigned int availFDs=getFilenumLimit(); 
-  unsigned int wantFDs = g_maxMThreads * g_numWorkerThreads +25; // even healthier margin then before
+  unsigned int availFDs = getFilenumLimit();
+  unsigned int wantFDs = g_maxMThreads * g_numWorkerThreads + 25; // even healthier margin then before
   wantFDs += g_numWorkerThreads * TCPOutConnectionManager::s_maxIdlePerThread;
 
-  if(wantFDs > availFDs) {
-    unsigned int hardlimit= getFilenumLimit(true);
-    if(hardlimit >= wantFDs) {
+  if (wantFDs > availFDs) {
+    unsigned int hardlimit = getFilenumLimit(true);
+    if (hardlimit >= wantFDs) {
       setFilenumLimit(wantFDs);
-      g_log<<Logger::Warning<<"Raised soft limit on number of filedescriptors to "<<wantFDs<<" to match max-mthreads and threads settings"<<endl;
+      g_log << Logger::Warning << "Raised soft limit on number of filedescriptors to " << wantFDs << " to match max-mthreads and threads settings" << endl;
     }
     else {
       int newval = (hardlimit - 25 - TCPOutConnectionManager::s_maxIdlePerThread) / g_numWorkerThreads;
-      g_log<<Logger::Warning<<"Insufficient number of filedescriptors available for max-mthreads*threads setting! ("<<hardlimit<<" < "<<wantFDs<<"), reducing max-mthreads to "<<newval<<endl;
+      g_log << Logger::Warning << "Insufficient number of filedescriptors available for max-mthreads*threads setting! (" << hardlimit << " < " << wantFDs << "), reducing max-mthreads to " << newval << endl;
       g_maxMThreads = newval;
       setFilenumLimit(hardlimit);
     }
   }
 }
-//static std::string s_timestampFormat = "%m-%dT%H:%M:%S";
+// static std::string s_timestampFormat = "%m-%dT%H:%M:%S";
 static std::string s_timestampFormat = "%s";
 
-static const char* toTimestampStringMilli(const struct timeval& tv, char *buf, size_t sz)
+static const char* toTimestampStringMilli(const struct timeval& tv, charbuf, size_t sz)
 {
   struct tm tm;
   size_t len = strftime(buf, sz, s_timestampFormat.c_str(), localtime_r(&tv.tv_sec, &tm));
@@ -662,7 +660,8 @@ static const char* toTimestampStringMilli(const struct timeval& tv, char *buf, s
   return buf;
 }
 
-static void loggerBackend(const Logging::Entry& entry) {
+static void loggerBackend(const Logging::Entry& entry)
+{
   static thread_local std::stringstream buf;
 
   buf.str("");
@@ -680,7 +679,7 @@ static void loggerBackend(const Logging::Entry& entry) {
   }
   char timebuf[64];
   buf << " ts=" << std::quoted(toTimestampStringMilli(entry.d_timestamp, timebuf, sizeof(timebuf)));
-  for (auto const& v: entry.values) {
+  for (auto const& v : entry.values) {
     buf << " ";
     buf << v.first << "=" << std::quoted(v.second);
   }
@@ -691,32 +690,32 @@ void makeThreadPipes()
 {
   auto pipeBufferSize = ::arg().asNum("distribution-pipe-buffer-size");
   if (pipeBufferSize > 0) {
-    g_log<<Logger::Info<<"Resizing the buffer of the distribution pipe to "<<pipeBufferSize<<endl;
+    g_log << Logger::Info << "Resizing the buffer of the distribution pipe to " << pipeBufferSize << endl;
   }
 
   /* thread 0 is the handler / SNMP, worker threads start at 1 */
-  for(unsigned int n = 0; n <= (g_numWorkerThreads + g_numDistributorThreads); ++n) {
+  for (unsigned int n = 0; n <= (g_numWorkerThreads + g_numDistributorThreads); ++n) {
     auto& threadInfos = s_threadInfos.at(n);
 
     int fd[2];
-    if(pipe(fd) < 0)
+    if (pipe(fd) < 0)
       unixDie("Creating pipe for inter-thread communications");
 
     threadInfos.pipes.readToThread = fd[0];
     threadInfos.pipes.writeToThread = fd[1];
 
     // handler thread only gets first pipe, not the others
-    if(n==0) {
+    if (n == 0) {
       continue;
     }
 
-    if(pipe(fd) < 0)
+    if (pipe(fd) < 0)
       unixDie("Creating pipe for inter-thread communications");
 
     threadInfos.pipes.readFromThread = fd[0];
     threadInfos.pipes.writeFromThread = fd[1];
 
-    if(pipe(fd) < 0)
+    if (pipe(fd) < 0)
       unixDie("Creating pipe for inter-thread communications");
 
     threadInfos.pipes.readQueriesToThread = fd[0];
@@ -725,10 +724,10 @@ void makeThreadPipes()
     if (pipeBufferSize > 0) {
       if (!setPipeBufferSize(threadInfos.pipes.writeQueriesToThread, pipeBufferSize)) {
         int err = errno;
-        g_log<<Logger::Warning<<"Error resizing the buffer of the distribution pipe for thread "<<n<<" to "<<pipeBufferSize<<": "<<strerror(err)<<endl;
+        g_log << Logger::Warning << "Error resizing the buffer of the distribution pipe for thread " << n << " to " << pipeBufferSize << ": " << strerror(err) << endl;
         auto existingSize = getPipeBufferSize(threadInfos.pipes.writeQueriesToThread);
         if (existingSize > 0) {
-          g_log<<Logger::Warning<<"The current size of the distribution pipe's buffer for thread "<<n<<" is "<<existingSize<<endl;
+          g_log << Logger::Warning << "The current size of the distribution pipe's buffer for thread " << n << " is " << existingSize << endl;
         }
       }
     }
@@ -762,88 +761,83 @@ static void doStats(void)
   auto taskExpired = getTaskExpired();
   auto taskSize = getTaskSize();
 
-  if(g_stats.qcounter && (cacheHits + cacheMisses) && SyncRes::s_queries && SyncRes::s_outqueries) {
-    g_log<<Logger::Notice<<"stats: "<<g_stats.qcounter<<" questions, "<<
-      cacheSize << " cache entries, "<<
-      negCacheSize<<" negative entries, "<<
-      ratePercentage(cacheHits, cacheHits + cacheMisses)<<"% cache hits"<<endl;
-    g_log << Logger::Notice<< "stats: cache contended/acquired " << rc_stats.first << '/' << rc_stats.second << " = " << r << '%' << endl;
-
-    g_log<<Logger::Notice<<"stats: throttle map: "
-      << broadcastAccFunction<uint64_t>(pleaseGetThrottleSize) <<", ns speeds: "
-      << broadcastAccFunction<uint64_t>(pleaseGetNsSpeedsSize)<<", failed ns: "
-      << broadcastAccFunction<uint64_t>(pleaseGetFailedServersSize)<<", ednsmap: "
-      <<broadcastAccFunction<uint64_t>(pleaseGetEDNSStatusesSize)<<endl;
-    g_log<<Logger::Notice<<"stats: outpacket/query ratio "<<ratePercentage(SyncRes::s_outqueries, SyncRes::s_queries)<<"%";
-    g_log<<Logger::Notice<<", "<<ratePercentage(SyncRes::s_throttledqueries, SyncRes::s_outqueries+SyncRes::s_throttledqueries)<<"% throttled"<<endl;
-    g_log<<Logger::Notice<<"stats: "<<SyncRes::s_tcpoutqueries<<"/"<<SyncRes::s_dotoutqueries << "/" << getCurrentIdleTCPConnections() << " outgoing tcp/dot/idle connections, "<<
-      broadcastAccFunction<uint64_t>(pleaseGetConcurrentQueries)<<" queries running, "<<SyncRes::s_outgoingtimeouts<<" outgoing timeouts "<<endl;
+  if (g_stats.qcounter && (cacheHits + cacheMisses) && SyncRes::s_queries && SyncRes::s_outqueries) {
+    g_log << Logger::Notice << "stats: " << g_stats.qcounter << " questions, " << cacheSize << " cache entries, " << negCacheSize << " negative entries, " << ratePercentage(cacheHits, cacheHits + cacheMisses) << "% cache hits" << endl;
+    g_log << Logger::Notice << "stats: cache contended/acquired " << rc_stats.first << '/' << rc_stats.second << " = " << r << '%' << endl;
+
+    g_log << Logger::Notice << "stats: throttle map: "
+          << broadcastAccFunction<uint64_t>(pleaseGetThrottleSize) << ", ns speeds: "
+          << broadcastAccFunction<uint64_t>(pleaseGetNsSpeedsSize) << ", failed ns: "
+          << broadcastAccFunction<uint64_t>(pleaseGetFailedServersSize) << ", ednsmap: "
+          << broadcastAccFunction<uint64_t>(pleaseGetEDNSStatusesSize) << endl;
+    g_log << Logger::Notice << "stats: outpacket/query ratio " << ratePercentage(SyncRes::s_outqueries, SyncRes::s_queries) << "%";
+    g_log << Logger::Notice << ", " << ratePercentage(SyncRes::s_throttledqueries, SyncRes::s_outqueries + SyncRes::s_throttledqueries) << "% throttled" << endl;
+    g_log << Logger::Notice << "stats: " << SyncRes::s_tcpoutqueries << "/" << SyncRes::s_dotoutqueries << "/" << getCurrentIdleTCPConnections() << " outgoing tcp/dot/idle connections, " << broadcastAccFunction<uint64_t>(pleaseGetConcurrentQueries) << " queries running, " << SyncRes::s_outgoingtimeouts << " outgoing timeouts " << endl;
 
     uint64_t pcSize = broadcastAccFunction<uint64_t>(pleaseGetPacketCacheSize);
     uint64_t pcHits = broadcastAccFunction<uint64_t>(pleaseGetPacketCacheHits);
-    g_log<<Logger::Notice<<"stats: " <<  pcSize <<
-      " packet cache entries, "<< ratePercentage(pcHits, SyncRes::s_queries) << "% packet cache hits"<<endl;
+    g_log << Logger::Notice << "stats: " << pcSize << " packet cache entries, " << ratePercentage(pcHits, SyncRes::s_queries) << "% packet cache hits" << endl;
 
     size_t idx = 0;
     for (const auto& threadInfo : s_threadInfos) {
-      if(threadInfo.isWorker) {
-        g_log<<Logger::Notice<<"stats: thread "<<idx<<" has been distributed "<<threadInfo.numberOfDistributedQueries<<" queries"<<endl;
+      if (threadInfo.isWorker) {
+        g_log << Logger::Notice << "stats: thread " << idx << " has been distributed " << threadInfo.numberOfDistributedQueries << " queries" << endl;
         ++idx;
       }
     }
 
-    g_log<<Logger::Notice<<"stats: tasks pushed/expired/queuesize: " << taskPushes << '/' << taskExpired << '/' << taskSize << endl; 
+    g_log << Logger::Notice << "stats: tasks pushed/expired/queuesize: " << taskPushes << '/' << taskExpired << '/' << taskSize << endl;
     time_t now = time(0);
-    if(lastOutputTime && lastQueryCount && now != lastOutputTime) {
-      g_log<<Logger::Notice<<"stats: "<< (SyncRes::s_queries - lastQueryCount) / (now - lastOutputTime) <<" qps (average over "<< (now - lastOutputTime) << " seconds)"<<endl;
+    if (lastOutputTime && lastQueryCount && now != lastOutputTime) {
+      g_log << Logger::Notice << "stats: " << (SyncRes::s_queries - lastQueryCount) / (now - lastOutputTime) << " qps (average over " << (now - lastOutputTime) << " seconds)" << endl;
     }
     lastOutputTime = now;
     lastQueryCount = SyncRes::s_queries;
   }
-  else if(statsWanted)
-    g_log<<Logger::Notice<<"stats: no stats yet!"<<endl;
+  else if (statsWanted)
+    g_log << Logger::Notice << "stats: no stats yet!" << endl;
 
-  statsWanted=false;
+  statsWanted = false;
 }
 
 static std::shared_ptr<NetmaskGroup> parseACL(const std::string& aclFile, const std::string& aclSetting)
 {
   auto result = std::make_shared<NetmaskGroup>();
 
-  if(!::arg()[aclFile].empty()) {
+  if (!::arg()[aclFile].empty()) {
     string line;
     ifstream ifs(::arg()[aclFile].c_str());
-    if(!ifs) {
-      throw runtime_error("Could not open '"+::arg()[aclFile]+"': "+stringerror());
+    if (!ifs) {
+      throw runtime_error("Could not open '" + ::arg()[aclFile] + "': " + stringerror());
     }
 
     string::size_type pos;
-    while(getline(ifs,line)) {
-      pos=line.find('#');
-      if(pos!=string::npos)
+    while (getline(ifs, line)) {
+      pos = line.find('#');
+      if (pos != string::npos)
         line.resize(pos);
       boost::trim(line);
-      if(line.empty())
+      if (line.empty())
         continue;
 
       result->addMask(line);
     }
-    g_log<<Logger::Info<<"Done parsing "<<result->size()<<" "<<aclSetting<<" ranges from file '"<<::arg()[aclFile]<<"' - overriding '"<<aclSetting<<"' setting"<<endl;
+    g_log << Logger::Info << "Done parsing " << result->size() << " " << aclSetting << " ranges from file '" << ::arg()[aclFile] << "' - overriding '" << aclSetting << "' setting" << endl;
 
     return result;
   }
-  else if(!::arg()[aclSetting].empty()) {
+  else if (!::arg()[aclSetting].empty()) {
     vector<string> ips;
     stringtok(ips, ::arg()[aclSetting], ", ");
 
-    g_log<<Logger::Info<<aclSetting<<": ";
-    for(vector<string>::const_iterator i = ips.begin(); i!= ips.end(); ++i) {
+    g_log << Logger::Info << aclSetting << ": ";
+    for (vector<string>::const_iterator i = ips.begin(); i != ips.end(); ++i) {
       result->addMask(*i);
-      if(i!=ips.begin())
-        g_log<<Logger::Info<<", ";
-      g_log<<Logger::Info<<*i;
+      if (i != ips.begin())
+        g_log << Logger::Info << ", ";
+      g_log << Logger::Info << *i;
     }
-    g_log<<Logger::Info<<endl;
+    g_log << Logger::Info << endl;
 
     return result;
   }
@@ -873,19 +867,19 @@ void parseACLs()
 {
   static bool l_initialized;
 
-  if(l_initialized) { // only reload configuration file on second call
-    string configname=::arg()["config-dir"]+"/recursor.conf";
-    if(::arg()["config-name"]!="") {
-      configname=::arg()["config-dir"]+"/recursor-"+::arg()["config-name"]+".conf";
+  if (l_initialized) { // only reload configuration file on second call
+    string configname = ::arg()["config-dir"] + "/recursor.conf";
+    if (::arg()["config-name"] != "") {
+      configname = ::arg()["config-dir"] + "/recursor-" + ::arg()["config-name"] + ".conf";
     }
     cleanSlashes(configname);
 
-    if(!::arg().preParseFile(configname.c_str(), "allow-from-file"))
-      throw runtime_error("Unable to re-parse configuration file '"+configname+"'");
+    if (!::arg().preParseFile(configname.c_str(), "allow-from-file"))
+      throw runtime_error("Unable to re-parse configuration file '" + configname + "'");
     ::arg().preParseFile(configname.c_str(), "allow-from", LOCAL_NETS);
 
-    if(!::arg().preParseFile(configname.c_str(), "allow-notify-from-file"))
-      throw runtime_error("Unable to re-parse configuration file '"+configname+"'");
+    if (!::arg().preParseFile(configname.c_str(), "allow-notify-from-file"))
+      throw runtime_error("Unable to re-parse configuration file '" + configname + "'");
     ::arg().preParseFile(configname.c_str(), "allow-notify-from");
 
     ::arg().preParseFile(configname.c_str(), "include-dir");
@@ -895,16 +889,16 @@ void parseACLs()
     std::vector<std::string> extraConfigs;
     ::arg().gatherIncludes(extraConfigs);
 
-    for(const std::string& fn : extraConfigs) {
-      if(!::arg().preParseFile(fn.c_str(), "allow-from-file", ::arg()["allow-from-file"]))
-        throw runtime_error("Unable to re-parse configuration file include '"+fn+"'");
-      if(!::arg().preParseFile(fn.c_str(), "allow-from", ::arg()["allow-from"]))
-        throw runtime_error("Unable to re-parse configuration file include '"+fn+"'");
+    for (const std::string& fn : extraConfigs) {
+      if (!::arg().preParseFile(fn.c_str(), "allow-from-file", ::arg()["allow-from-file"]))
+        throw runtime_error("Unable to re-parse configuration file include '" + fn + "'");
+      if (!::arg().preParseFile(fn.c_str(), "allow-from", ::arg()["allow-from"]))
+        throw runtime_error("Unable to re-parse configuration file include '" + fn + "'");
 
-      if(!::arg().preParseFile(fn.c_str(), "allow-notify-from-file", ::arg()["allow-notify-from-file"]))
-        throw runtime_error("Unable to re-parse configuration file include '"+fn+"'");
-      if(!::arg().preParseFile(fn.c_str(), "allow-notify-from", ::arg()["allow-notify-from"]))
-        throw runtime_error("Unable to re-parse configuration file include '"+fn+"'");
+      if (!::arg().preParseFile(fn.c_str(), "allow-notify-from-file", ::arg()["allow-notify-from-file"]))
+        throw runtime_error("Unable to re-parse configuration file include '" + fn + "'");
+      if (!::arg().preParseFile(fn.c_str(), "allow-notify-from", ::arg()["allow-notify-from"]))
+        throw runtime_error("Unable to re-parse configuration file include '" + fn + "'");
     }
 
     ::arg().preParse(g_argc, g_argv, "allow-from-file");
@@ -916,24 +910,23 @@ void parseACLs()
 
   auto allowFrom = parseACL("allow-from-file", "allow-from");
 
-  if(allowFrom->size() == 0) {
-    if(::arg()["local-address"]!="127.0.0.1" && ::arg().asNum("local-port")==53)
-      g_log<<Logger::Warning<<"WARNING: Allowing queries from all IP addresses - this can be a security risk!"<<endl;
+  if (allowFrom->size() == 0) {
+    if (::arg()["local-address"] != "127.0.0.1" && ::arg().asNum("local-port") == 53)
+      g_log << Logger::Warning << "WARNING: Allowing queries from all IP addresses - this can be a security risk!" << endl;
     allowFrom = nullptr;
   }
 
   g_initialAllowFrom = allowFrom;
-  broadcastFunction([=]{ return pleaseSupplantAllowFrom(allowFrom); });
+  broadcastFunction([=] { return pleaseSupplantAllowFrom(allowFrom); });
 
   auto allowNotifyFrom = parseACL("allow-notify-from-file", "allow-notify-from");
 
   g_initialAllowNotifyFrom = allowNotifyFrom;
-  broadcastFunction([=]{ return pleaseSupplantAllowNotifyFrom(allowNotifyFrom); });
+  broadcastFunction([=] { return pleaseSupplantAllowNotifyFrom(allowNotifyFrom); });
 
   l_initialized = true;
 }
 
-
 void broadcastFunction(const pipefunc_t& func)
 {
   /* This function might be called by the worker with t_id 0 during startup
@@ -951,7 +944,7 @@ void broadcastFunction(const pipefunc_t& func)
 
   unsigned int n = 0;
   for (const auto& threadInfo : s_threadInfos) {
-    if(n++ == t_id) {
+    if (n++ == t_id) {
       func(); // don't write to ourselves!
       continue;
     }
@@ -959,35 +952,36 @@ void broadcastFunction(const pipefunc_t& func)
     ThreadMSG* tmsg = new ThreadMSG();
     tmsg->func = func;
     tmsg->wantAnswer = true;
-    if(write(threadInfo.pipes.writeToThread, &tmsg, sizeof(tmsg)) != sizeof(tmsg)) {
+    if (write(threadInfo.pipes.writeToThread, &tmsg, sizeof(tmsg)) != sizeof(tmsg)) {
       delete tmsg;
 
       unixDie("write to thread pipe returned wrong size or error");
     }
 
     string* resp = nullptr;
-    if(read(threadInfo.pipes.readFromThread, &resp, sizeof(resp)) != sizeof(resp))
+    if (read(threadInfo.pipes.readFromThread, &resp, sizeof(resp)) != sizeof(resp))
       unixDie("read from thread pipe returned wrong size or error");
 
-    if(resp) {
+    if (resp) {
       delete resp;
       resp = nullptr;
     }
   }
 }
 
-template<class T> void *voider(const boost::function<T*()>& func)
+template <class T>
+void* voider(const boost::function<T*()>& func)
 {
   return func();
 }
 
-static vector<ComboAddress>& operator+=(vector<ComboAddress>&a, const vector<ComboAddress>& b)
+static vector<ComboAddress>& operator+=(vector<ComboAddress>& a, const vector<ComboAddress>& b)
 {
   a.insert(a.end(), b.begin(), b.end());
   return a;
 }
 
-static vector<pair<DNSName, uint16_t> >& operator+=(vector<pair<DNSName, uint16_t> >&a, const vector<pair<DNSName, uint16_t> >& b)
+static vector<pair<DNSName, uint16_t>>& operator+=(vector<pair<DNSName, uint16_t>>& a, const vector<pair<DNSName, uint16_t>>& b)
 {
   a.insert(a.end(), b.begin(), b.end());
   return a;
@@ -997,15 +991,16 @@ static vector<pair<DNSName, uint16_t> >& operator+=(vector<pair<DNSName, uint16_
   This function should only be called by the handler to gather metrics, wipe the cache,
   reload the Lua script (not the Lua config) or change the current trace regex,
   and by the SNMP thread to gather metrics. */
-template<class T> T broadcastAccFunction(const boost::function<T*()>& func)
+template <class T>
+T broadcastAccFunction(const boost::function<T*()>& func)
 {
   if (!isHandlerThread()) {
-    g_log<<Logger::Error<<"broadcastAccFunction has been called by a worker ("<<t_id<<")"<<endl;
+    g_log << Logger::Error << "broadcastAccFunction has been called by a worker (" << t_id << ")" << endl;
     _exit(1);
   }
 
   unsigned int n = 0;
-  T ret=T();
+  T ret = T();
   for (const auto& threadInfo : s_threadInfos) {
     if (n++ == t_id) {
       continue;
@@ -1013,19 +1008,19 @@ template<class T> T broadcastAccFunction(const boost::function<T*()>& func)
 
     const auto& tps = threadInfo.pipes;
     ThreadMSG* tmsg = new ThreadMSG();
-    tmsg->func = [func]{ return voider<T>(func); };
+    tmsg->func = [func] { return voider<T>(func); };
     tmsg->wantAnswer = true;
 
-    if(write(tps.writeToThread, &tmsg, sizeof(tmsg)) != sizeof(tmsg)) {
+    if (write(tps.writeToThread, &tmsg, sizeof(tmsg)) != sizeof(tmsg)) {
       delete tmsg;
       unixDie("write to thread pipe returned wrong size or error");
     }
 
     T* resp = nullptr;
-    if(read(tps.readFromThread, &resp, sizeof(resp)) != sizeof(resp))
+    if (read(tps.readFromThread, &resp, sizeof(resp)) != sizeof(resp))
       unixDie("read from thread pipe returned wrong size or error");
 
-    if(resp) {
+    if (resp) {
       ret += *resp;
       delete resp;
       resp = nullptr;
@@ -1035,13 +1030,13 @@ template<class T> T broadcastAccFunction(const boost::function<T*()>& func)
 }
 
 template string broadcastAccFunction(const boost::function<string*()>& fun); // explicit instantiation
-template RecursorControlChannel::Answer broadcastAccFunction(const boost::function<RecursorControlChannel::Answer *()>& fun); // explicit instantiation
+template RecursorControlChannel::Answer broadcastAccFunction(const boost::function<RecursorControlChannel::Answer*()>& fun); // explicit instantiation
 template uint64_t broadcastAccFunction(const boost::function<uint64_t*()>& fun); // explicit instantiation
-template vector<ComboAddress> broadcastAccFunction(const boost::function<vector<ComboAddress> *()>& fun); // explicit instantiation
-template vector<pair<DNSName,uint16_t> > broadcastAccFunction(const boost::function<vector<pair<DNSName, uint16_t> > *()>& fun); // explicit instantiation
+template vector<ComboAddress> broadcastAccFunction(const boost::function<vector<ComboAddress>*()>& fun); // explicit instantiation
+template vector<pair<DNSName, uint16_t>> broadcastAccFunction(const boost::function<vector<pair<DNSName, uint16_t>>*()>& fun); // explicit instantiation
 template ThreadTimes broadcastAccFunction(const boost::function<ThreadTimes*()>& fun);
 
-static int serviceMain(int argc, char*argv[])
+static int serviceMain(int argc, char* argv[])
 {
   int ret = EXIT_SUCCESS;
 
@@ -1051,68 +1046,67 @@ static int serviceMain(int argc, char*argv[])
   g_log.disableSyslog(::arg().mustDo("disable-syslog"));
   g_log.setTimestamps(::arg().mustDo("log-timestamp"));
 
-  if(!::arg()["logging-facility"].empty()) {
-    int val=logFacilityToLOG(::arg().asNum("logging-facility") );
-    if(val >= 0)
+  if (!::arg()["logging-facility"].empty()) {
+    int val = logFacilityToLOG(::arg().asNum("logging-facility"));
+    if (val >= 0)
       g_log.setFacility(val);
     else
-      g_log<<Logger::Error<<"Unknown logging facility "<<::arg().asNum("logging-facility") <<endl;
+      g_log << Logger::Error << "Unknown logging facility " << ::arg().asNum("logging-facility") << endl;
   }
 
   showProductVersion();
 
-  g_disthashseed=dns_random(0xffffffff);
+  g_disthashseed = dns_random(0xffffffff);
 
   checkLinuxIPv6Limits();
   try {
     pdns::parseQueryLocalAddress(::arg()["query-local-address"]);
   }
-  catch(std::exception& e) {
-    g_log<<Logger::Error<<"Assigning local query addresses: "<<e.what();
+  catch (std::exception& e) {
+    g_log << Logger::Error << "Assigning local query addresses: " << e.what();
     exit(99);
   }
 
-  if(pdns::isQueryLocalAddressFamilyEnabled(AF_INET)) {
-    SyncRes::s_doIPv4=true;
-    g_log<<Logger::Warning<<"Enabling IPv4 transport for outgoing queries"<<endl;
+  if (pdns::isQueryLocalAddressFamilyEnabled(AF_INET)) {
+    SyncRes::s_doIPv4 = true;
+    g_log << Logger::Warning << "Enabling IPv4 transport for outgoing queries" << endl;
   }
   else {
-    g_log<<Logger::Warning<<"NOT using IPv4 for outgoing queries - add an IPv4 address (like '0.0.0.0') to query-local-address to enable"<<endl;
+    g_log << Logger::Warning << "NOT using IPv4 for outgoing queries - add an IPv4 address (like '0.0.0.0') to query-local-address to enable" << endl;
   }
 
-
-  if(pdns::isQueryLocalAddressFamilyEnabled(AF_INET6)) {
-    SyncRes::s_doIPv6=true;
-    g_log<<Logger::Warning<<"Enabling IPv6 transport for outgoing queries"<<endl;
+  if (pdns::isQueryLocalAddressFamilyEnabled(AF_INET6)) {
+    SyncRes::s_doIPv6 = true;
+    g_log << Logger::Warning << "Enabling IPv6 transport for outgoing queries" << endl;
   }
   else {
-    g_log<<Logger::Warning<<"NOT using IPv6 for outgoing queries - add an IPv6 address (like '::') to query-local-address to enable"<<endl;
+    g_log << Logger::Warning << "NOT using IPv6 for outgoing queries - add an IPv6 address (like '::') to query-local-address to enable" << endl;
   }
 
   if (!SyncRes::s_doIPv6 && !SyncRes::s_doIPv4) {
-    g_log<<Logger::Error<<"No outgoing addresses configured! Can not continue"<<endl;
+    g_log << Logger::Error << "No outgoing addresses configured! Can not continue" << endl;
     exit(99);
   }
 
   // keep this ABOVE loadRecursorLuaConfig!
-  if(::arg()["dnssec"]=="off")
-    g_dnssecmode=DNSSECMode::Off;
-  else if(::arg()["dnssec"]=="process-no-validate")
-    g_dnssecmode=DNSSECMode::ProcessNoValidate;
-  else if(::arg()["dnssec"]=="process")
-    g_dnssecmode=DNSSECMode::Process;
-  else if(::arg()["dnssec"]=="validate")
-    g_dnssecmode=DNSSECMode::ValidateAll;
-  else if(::arg()["dnssec"]=="log-fail")
-    g_dnssecmode=DNSSECMode::ValidateForLog;
+  if (::arg()["dnssec"] == "off")
+    g_dnssecmode = DNSSECMode::Off;
+  else if (::arg()["dnssec"] == "process-no-validate")
+    g_dnssecmode = DNSSECMode::ProcessNoValidate;
+  else if (::arg()["dnssec"] == "process")
+    g_dnssecmode = DNSSECMode::Process;
+  else if (::arg()["dnssec"] == "validate")
+    g_dnssecmode = DNSSECMode::ValidateAll;
+  else if (::arg()["dnssec"] == "log-fail")
+    g_dnssecmode = DNSSECMode::ValidateForLog;
   else {
-    g_log<<Logger::Error<<"Unknown DNSSEC mode "<<::arg()["dnssec"]<<endl;
+    g_log << Logger::Error << "Unknown DNSSEC mode " << ::arg()["dnssec"] << endl;
     exit(1);
   }
 
   g_signatureInceptionSkew = ::arg().asNum("signature-inception-skew");
   if (g_signatureInceptionSkew < 0) {
-    g_log<<Logger::Error<<"A negative value for 'signature-inception-skew' is not allowed"<<endl;
+    g_log << Logger::Error << "A negative value for 'signature-inception-skew' is not allowed" << endl;
     exit(1);
   }
 
@@ -1126,50 +1120,50 @@ static int serviceMain(int argc, char*argv[])
   try {
     loadRecursorLuaConfig(::arg()["lua-config-file"], delayedLuaThreads);
   }
-  catch (PDNSException &e) {
-    g_log<<Logger::Error<<"Cannot load Lua configuration: "<<e.reason<<endl;
+  catch (PDNSExceptione) {
+    g_log << Logger::Error << "Cannot load Lua configuration: " << e.reason << endl;
     exit(1);
   }
 
   parseACLs();
   initPublicSuffixList(::arg()["public-suffix-list-file"]);
 
-  if(!::arg()["dont-query"].empty()) {
+  if (!::arg()["dont-query"].empty()) {
     vector<string> ips;
     stringtok(ips, ::arg()["dont-query"], ", ");
     ips.push_back("0.0.0.0");
     ips.push_back("::");
 
-    g_log<<Logger::Warning<<"Will not send queries to: ";
-    for(vector<string>::const_iterator i = ips.begin(); i!= ips.end(); ++i) {
+    g_log << Logger::Warning << "Will not send queries to: ";
+    for (vector<string>::const_iterator i = ips.begin(); i != ips.end(); ++i) {
       SyncRes::addDontQuery(*i);
-      if(i!=ips.begin())
-        g_log<<Logger::Warning<<", ";
-      g_log<<Logger::Warning<<*i;
+      if (i != ips.begin())
+        g_log << Logger::Warning << ", ";
+      g_log << Logger::Warning << *i;
     }
-    g_log<<Logger::Warning<<endl;
+    g_log << Logger::Warning << endl;
   }
 
   /* this needs to be done before parseACLs(), which call broadcastFunction() */
   g_weDistributeQueries = ::arg().mustDo("pdns-distributes-queries");
-  if(g_weDistributeQueries) {
-    g_log<<Logger::Warning<<"PowerDNS Recursor itself will distribute queries over threads"<<endl;
+  if (g_weDistributeQueries) {
+    g_log << Logger::Warning << "PowerDNS Recursor itself will distribute queries over threads" << endl;
   }
 
-  g_outgoingEDNSBufsize=::arg().asNum("edns-outgoing-bufsize");
+  g_outgoingEDNSBufsize = ::arg().asNum("edns-outgoing-bufsize");
 
-  if(::arg()["trace"]=="fail") {
+  if (::arg()["trace"] == "fail") {
     SyncRes::setDefaultLogMode(SyncRes::Store);
   }
-  else if(::arg().mustDo("trace")) {
+  else if (::arg().mustDo("trace")) {
     SyncRes::setDefaultLogMode(SyncRes::Log);
-    ::arg().set("quiet")="no";
-    g_quiet=false;
-    g_dnssecLOG=true;
+    ::arg().set("quiet") = "no";
+    g_quiet = false;
+    g_dnssecLOG = true;
   }
   string myHostname = getHostname();
-  if (myHostname == "UNKNOWN"){
-    g_log<<Logger::Warning<<"Unable to get the hostname, NSID and id.server values will be empty"<<endl;
+  if (myHostname == "UNKNOWN") {
+    g_log << Logger::Warning << "Unable to get the hostname, NSID and id.server values will be empty" << endl;
     myHostname = "";
   }
 
@@ -1178,23 +1172,23 @@ static int serviceMain(int argc, char*argv[])
 
   SyncRes::s_nopacketcache = ::arg().mustDo("disable-packetcache");
 
-  SyncRes::s_maxnegttl=::arg().asNum("max-negative-ttl");
-  SyncRes::s_maxbogusttl=::arg().asNum("max-cache-bogus-ttl");
-  SyncRes::s_maxcachettl=max(::arg().asNum("max-cache-ttl"), 15);
-  SyncRes::s_packetcachettl=::arg().asNum("packetcache-ttl");
+  SyncRes::s_maxnegttl = ::arg().asNum("max-negative-ttl");
+  SyncRes::s_maxbogusttl = ::arg().asNum("max-cache-bogus-ttl");
+  SyncRes::s_maxcachettl = max(::arg().asNum("max-cache-ttl"), 15);
+  SyncRes::s_packetcachettl = ::arg().asNum("packetcache-ttl");
   // Cap the packetcache-servfail-ttl to the packetcache-ttl
   uint32_t packetCacheServFailTTL = ::arg().asNum("packetcache-servfail-ttl");
-  SyncRes::s_packetcacheservfailttl=(packetCacheServFailTTL > SyncRes::s_packetcachettl) ? SyncRes::s_packetcachettl : packetCacheServFailTTL;
-  SyncRes::s_serverdownmaxfails=::arg().asNum("server-down-max-fails");
-  SyncRes::s_serverdownthrottletime=::arg().asNum("server-down-throttle-time");
-  SyncRes::s_nonresolvingnsmaxfails=::arg().asNum("non-resolving-ns-max-fails");
-  SyncRes::s_nonresolvingnsthrottletime=::arg().asNum("non-resolving-ns-throttle-time");
-  SyncRes::s_serverID=::arg()["server-id"];
-  SyncRes::s_maxqperq=::arg().asNum("max-qperq");
-  SyncRes::s_maxnsaddressqperq=::arg().asNum("max-ns-address-qperq");
-  SyncRes::s_maxtotusec=1000*::arg().asNum("max-total-msec");
-  SyncRes::s_maxdepth=::arg().asNum("max-recursion-depth");
-  SyncRes::s_rootNXTrust = ::arg().mustDo( "root-nx-trust");
+  SyncRes::s_packetcacheservfailttl = (packetCacheServFailTTL > SyncRes::s_packetcachettl) ? SyncRes::s_packetcachettl : packetCacheServFailTTL;
+  SyncRes::s_serverdownmaxfails = ::arg().asNum("server-down-max-fails");
+  SyncRes::s_serverdownthrottletime = ::arg().asNum("server-down-throttle-time");
+  SyncRes::s_nonresolvingnsmaxfails = ::arg().asNum("non-resolving-ns-max-fails");
+  SyncRes::s_nonresolvingnsthrottletime = ::arg().asNum("non-resolving-ns-throttle-time");
+  SyncRes::s_serverID = ::arg()["server-id"];
+  SyncRes::s_maxqperq = ::arg().asNum("max-qperq");
+  SyncRes::s_maxnsaddressqperq = ::arg().asNum("max-ns-address-qperq");
+  SyncRes::s_maxtotusec = 1000 * ::arg().asNum("max-total-msec");
+  SyncRes::s_maxdepth = ::arg().asNum("max-recursion-depth");
+  SyncRes::s_rootNXTrust = ::arg().mustDo("root-nx-trust");
   SyncRes::s_refresh_ttlperc = ::arg().asNum("refresh-on-ttl-perc");
   RecursorPacketCache::s_refresh_ttlperc = SyncRes::s_refresh_ttlperc;
   SyncRes::s_tcp_fast_open = ::arg().asNum("tcp-fast-open");
@@ -1208,7 +1202,7 @@ static int serviceMain(int argc, char*argv[])
     checkTFOconnect();
   }
 
-  if(SyncRes::s_serverID.empty()) {
+  if (SyncRes::s_serverID.empty()) {
     SyncRes::s_serverID = myHostname;
   }
 
@@ -1233,9 +1227,11 @@ static int serviceMain(int argc, char*argv[])
   string value = ::arg()["nothing-below-nxdomain"];
   if (value == "yes") {
     SyncRes::s_hardenNXD = SyncRes::HardenNXD::Yes;
-  } else if (value == "no") {
+  }
+  else if (value == "no") {
     SyncRes::s_hardenNXD = SyncRes::HardenNXD::No;
-  } else if (value != "dnssec") {
+  }
+  else if (value != "dnssec") {
     g_log << Logger::Error << "Unknown nothing-below-nxdomain mode: " << value << endl;
     exit(1);
   }
@@ -1301,9 +1297,9 @@ static int serviceMain(int argc, char*argv[])
 
   std::tie(g_initialDomainMap, g_initialAllowNotifyFor) = parseZoneConfiguration();
 
-  g_latencyStatSize=::arg().asNum("latency-statistic-size");
+  g_latencyStatSize = ::arg().asNum("latency-statistic-size");
 
-  g_logCommonErrors=::arg().mustDo("log-common-errors");
+  g_logCommonErrors = ::arg().mustDo("log-common-errors");
   g_logRPZChanges = ::arg().mustDo("log-rpz-changes");
 
   g_anyToTcp = ::arg().mustDo("any-to-tcp");
@@ -1327,24 +1323,24 @@ static int serviceMain(int argc, char*argv[])
   g_numDistributorThreads = ::arg().asNum("distributor-threads");
   g_numWorkerThreads = ::arg().asNum("threads");
   if (g_numWorkerThreads < 1) {
-    g_log<<Logger::Warning<<"Asked to run with 0 threads, raising to 1 instead"<<endl;
+    g_log << Logger::Warning << "Asked to run with 0 threads, raising to 1 instead" << endl;
     g_numWorkerThreads = 1;
   }
 
   g_numThreads = g_numDistributorThreads + g_numWorkerThreads;
   g_maxMThreads = ::arg().asNum("max-mthreads");
 
-
   int64_t maxInFlight = ::arg().asNum("max-concurrent-requests-per-tcp-connection");
   if (maxInFlight < 1 || maxInFlight > USHRT_MAX || maxInFlight >= g_maxMThreads) {
-    g_log<<Logger::Warning<<"Asked to run with illegal max-concurrent-requests-per-tcp-connection, setting to default (10)"<<endl;
+    g_log << Logger::Warning << "Asked to run with illegal max-concurrent-requests-per-tcp-connection, setting to default (10)" << endl;
     TCPConnection::s_maxInFlight = 10;
-  } else {
+  }
+  else {
     TCPConnection::s_maxInFlight = maxInFlight;
   }
 
   int64_t millis = ::arg().asNum("tcp-out-max-idle-ms");
-  TCPOutConnectionManager::s_maxIdleTime = timeval{millis / 1000, (static_cast<suseconds_t>(millis) % 1000) * 1000 };
+  TCPOutConnectionManager::s_maxIdleTime = timeval{millis / 1000, (static_cast<suseconds_t>(millis) % 1000) * 1000};
   TCPOutConnectionManager::s_maxIdlePerAuth = ::arg().asNum("tcp-out-max-idle-per-auth");
   TCPOutConnectionManager::s_maxQueries = ::arg().asNum("tcp-out-max-queries");
   TCPOutConnectionManager::s_maxIdlePerThread = ::arg().asNum("tcp-out-max-idle-per-thread");
@@ -1360,7 +1356,7 @@ static int serviceMain(int argc, char*argv[])
       g_aggressiveNSECCache = make_unique<AggressiveNSECCache>(::arg().asNum("aggressive-nsec-cache-size"));
     }
     else {
-      g_log<<Logger::Warning<<"Aggressive NSEC/NSEC3 caching is enabled but DNSSEC validation is not set to 'validate', 'log-fail' or 'process', ignoring"<<endl;
+      g_log << Logger::Warning << "Aggressive NSEC/NSEC3 caching is enabled but DNSSEC validation is not set to 'validate', 'log-fail' or 'process', ignoring" << endl;
     }
   }
 
@@ -1368,7 +1364,7 @@ static int serviceMain(int argc, char*argv[])
     SuffixMatchNode dontThrottleNames;
     vector<string> parts;
     stringtok(parts, ::arg()["dont-throttle-names"], " ,");
-    for (const auto &p : parts) {
+    for (const autop : parts) {
       dontThrottleNames.add(DNSName(p));
     }
     g_dontThrottleNames.setState(std::move(dontThrottleNames));
@@ -1376,7 +1372,7 @@ static int serviceMain(int argc, char*argv[])
     parts.clear();
     NetmaskGroup dontThrottleNetmasks;
     stringtok(parts, ::arg()["dont-throttle-netmasks"], " ,");
-    for (const auto &p : parts) {
+    for (const autop : parts) {
       dontThrottleNetmasks.addMask(Netmask(p));
     }
     g_dontThrottleNetmasks.setState(std::move(dontThrottleNetmasks));
@@ -1386,7 +1382,7 @@ static int serviceMain(int argc, char*argv[])
     SuffixMatchNode xdnssecNames;
     vector<string> parts;
     stringtok(parts, ::arg()["x-dnssec-names"], " ,");
-    for (const auto &p : parts) {
+    for (const autop : parts) {
       xdnssecNames.add(DNSName(p));
     }
     g_xdnssec.setState(std::move(xdnssecNames));
@@ -1398,10 +1394,10 @@ static int serviceMain(int argc, char*argv[])
     stringtok(parts, ::arg()["dot-to-auth-names"], " ,");
 #ifndef HAVE_DNS_OVER_TLS
     if (parts.size()) {
-      g_log << Logger::Error << "dot-to-auth-names setting contains names, but Recursor was built without DNS over TLS support. Setting will be ignored."<<endl;
+      g_log << Logger::Error << "dot-to-auth-names setting contains names, but Recursor was built without DNS over TLS support. Setting will be ignored." << endl;
     }
 #endif
-    for (const auto &p : parts) {
+    for (const autop : parts) {
       dotauthNames.add(DNSName(p));
     }
     g_DoTToAuthNames.setState(std::move(dotauthNames));
@@ -1419,7 +1415,7 @@ static int serviceMain(int argc, char*argv[])
   s_balancingFactor = ::arg().asDouble("distribution-load-factor");
   if (s_balancingFactor != 0.0 && s_balancingFactor < 1.0) {
     s_balancingFactor = 0.0;
-    g_log<<Logger::Warning<<"Asked to run with a distribution-load-factor below 1.0, disabling it instead"<<endl;
+    g_log << Logger::Warning << "Asked to run with a distribution-load-factor below 1.0, disabling it instead" << endl;
   }
 
 #ifdef SO_REUSEPORT
@@ -1475,21 +1471,21 @@ static int serviceMain(int argc, char*argv[])
   // Setup newly observed domain globals
   setupNODGlobal();
 #endif /* NOD_ENABLED */
-  
+
   int forks;
-  for(forks = 0; forks < ::arg().asNum("processes") - 1; ++forks) {
-    if(!fork()) // we are child
+  for (forks = 0; forks < ::arg().asNum("processes") - 1; ++forks) {
+    if (!fork()) // we are child
       break;
   }
 
-  if(::arg().mustDo("daemon")) {
-    g_log<<Logger::Warning<<"Calling daemonize, going to background"<<endl;
+  if (::arg().mustDo("daemon")) {
+    g_log << Logger::Warning << "Calling daemonize, going to background" << endl;
     g_log.toConsole(Logger::Critical);
     daemonize();
   }
-  if(Utility::getpid() == 1) {
+  if (Utility::getpid() == 1) {
     /* We are running as pid 1, register sigterm and sigint handler
-     
+
       The Linux kernel will handle SIGTERM and SIGINT for all processes, except PID 1.
       It assumes that the processes running as pid 1 is an "init" like system.
       For years, this was a safe assumption, but containers change that: in
@@ -1501,19 +1497,19 @@ static int serviceMain(int argc, char*argv[])
 
       So TL;DR: If we're running pid 1 (container), we should handle SIGTERM and SIGINT ourselves */
 
-    signal(SIGTERM,termIntHandler);
-    signal(SIGINT,termIntHandler);
-  } 
+    signal(SIGTERM, termIntHandler);
+    signal(SIGINT, termIntHandler);
+  }
 
-  signal(SIGUSR1,usr1Handler);
-  signal(SIGUSR2,usr2Handler);
-  signal(SIGPIPE,SIG_IGN);
+  signal(SIGUSR1, usr1Handler);
+  signal(SIGUSR2, usr2Handler);
+  signal(SIGPIPE, SIG_IGN);
 
   checkOrFixFDS();
 
 #ifdef HAVE_LIBSODIUM
   if (sodium_init() == -1) {
-    g_log<<Logger::Error<<"Unable to initialize sodium crypto library"<<endl;
+    g_log << Logger::Error << "Unable to initialize sodium crypto library" << endl;
     exit(99);
   }
 #endif
@@ -1523,45 +1519,45 @@ static int serviceMain(int argc, char*argv[])
   /* setup rng before chroot */
   dns_random_init();
 
-  if(::arg()["server-id"].empty()) {
+  if (::arg()["server-id"].empty()) {
     ::arg().set("server-id") = myHostname;
   }
 
-  int newgid=0;
-  if(!::arg()["setgid"].empty())
+  int newgid = 0;
+  if (!::arg()["setgid"].empty())
     newgid = strToGID(::arg()["setgid"]);
-  int newuid=0;
-  if(!::arg()["setuid"].empty())
+  int newuid = 0;
+  if (!::arg()["setuid"].empty())
     newuid = strToUID(::arg()["setuid"]);
 
   Utility::dropGroupPrivs(newuid, newgid);
 
   if (!::arg()["chroot"].empty()) {
 #ifdef HAVE_SYSTEMD
-     char *ns;
-     ns = getenv("NOTIFY_SOCKET");
-     if (ns != nullptr) {
-       g_log<<Logger::Error<<"Unable to chroot when running from systemd. Please disable chroot= or set the 'Type' for this service to 'simple'"<<endl;
-       exit(1);
-     }
+    char* ns;
+    ns = getenv("NOTIFY_SOCKET");
+    if (ns != nullptr) {
+      g_log << Logger::Error << "Unable to chroot when running from systemd. Please disable chroot= or set the 'Type' for this service to 'simple'" << endl;
+      exit(1);
+    }
 #endif
-    if (chroot(::arg()["chroot"].c_str())<0 || chdir("/") < 0) {
-       int err = errno;
-       g_log<<Logger::Error<<"Unable to chroot to '"+::arg()["chroot"]+"': "<<strerror (err)<<", exiting"<<endl;
-       exit(1);
+    if (chroot(::arg()["chroot"].c_str()) < 0 || chdir("/") < 0) {
+      int err = errno;
+      g_log << Logger::Error << "Unable to chroot to '" + ::arg()["chroot"] + "': " << strerror(err) << ", exiting" << endl;
+      exit(1);
     }
     else
-      g_log<<Logger::Info<<"Chrooted to '"<<::arg()["chroot"]<<"'"<<endl;
+      g_log << Logger::Info << "Chrooted to '" << ::arg()["chroot"] << "'" << endl;
   }
 
   checkSocketDir();
 
-  s_pidfname=::arg()["socket-dir"]+"/"+s_programname+".pid";
-  if(!s_pidfname.empty())
+  s_pidfname = ::arg()["socket-dir"] + "/" + s_programname + ".pid";
+  if (!s_pidfname.empty())
     unlink(s_pidfname.c_str()); // remove possible old pid file
   writePid();
 
-  makeControlChannelSocket( ::arg().asNum("processes") > 1 ? forks : -1);
+  makeControlChannelSocket(::arg().asNum("processes") > 1 ? forks : -1);
 
   Utility::dropUserPrivs(newuid);
   try {
@@ -1571,8 +1567,8 @@ static int serviceMain(int argc, char*argv[])
     */
     dropCapabilities();
   }
-  catch(const std::exception& e) {
-    g_log<<Logger::Warning<<e.what()<<endl;
+  catch (const std::exception& e) {
+    g_log << Logger::Warning << e.what() << endl;
   }
 
   startLuaConfigDelayedThreads(delayedLuaThreads, g_luaconfs.getCopy().generation);
@@ -1581,10 +1577,10 @@ static int serviceMain(int argc, char*argv[])
 
   makeThreadPipes();
 
-  g_tcpTimeout=::arg().asNum("client-tcp-timeout");
-  g_maxTCPPerClient=::arg().asNum("max-tcp-per-client");
-  g_tcpMaxQueriesPerConn=::arg().asNum("max-tcp-queries-per-connection");
-  s_maxUDPQueriesPerRound=::arg().asNum("max-udp-queries-per-round");
+  g_tcpTimeout = ::arg().asNum("client-tcp-timeout");
+  g_maxTCPPerClient = ::arg().asNum("max-tcp-per-client");
+  g_tcpMaxQueriesPerConn = ::arg().asNum("max-tcp-queries-per-connection");
+  s_maxUDPQueriesPerRound = ::arg().asNum("max-udp-queries-per-round");
 
   g_useKernelTimestamp = ::arg().mustDo("protobuf-use-kernel-timestamp");
 
@@ -1599,7 +1595,7 @@ static int serviceMain(int argc, char*argv[])
   disableStats(StatComponent::SNMP, ::arg()["stats-snmp-disabled-list"]);
 
   if (::arg().mustDo("snmp-agent")) {
-    string setting =  ::arg()["snmp-daemon-socket"];
+    string setting = ::arg()["snmp-daemon-socket"];
     if (setting.empty()) {
       setting = ::arg()["snmp-master-socket"];
     }
@@ -1608,24 +1604,23 @@ static int serviceMain(int argc, char*argv[])
   }
 
   int port = ::arg().asNum("udp-source-port-min");
-  if(port < 1024 || port > 65535){
-    g_log<<Logger::Error<<"Unable to launch, udp-source-port-min is not a valid port number"<<endl;
+  if (port < 1024 || port > 65535) {
+    g_log << Logger::Error << "Unable to launch, udp-source-port-min is not a valid port number" << endl;
     exit(99); // this isn't going to fix itself either
   }
   s_minUdpSourcePort = port;
   port = ::arg().asNum("udp-source-port-max");
-  if(port < 1024 || port > 65535 || port < s_minUdpSourcePort){
-    g_log<<Logger::Error<<"Unable to launch, udp-source-port-max is not a valid port number or is smaller than udp-source-port-min"<<endl;
+  if (port < 1024 || port > 65535 || port < s_minUdpSourcePort) {
+    g_log << Logger::Error << "Unable to launch, udp-source-port-max is not a valid port number or is smaller than udp-source-port-min" << endl;
     exit(99); // this isn't going to fix itself either
   }
   s_maxUdpSourcePort = port;
-  std::vector<string> parts {};
+  std::vector<string> parts{};
   stringtok(parts, ::arg()["udp-source-port-avoid"], ", ");
-  for (const auto &part : parts)
-  {
+  for (const auto& part : parts) {
     port = std::stoi(part);
-    if(port < 1024 || port > 65535){
-      g_log<<Logger::Error<<"Unable to launch, udp-source-port-avoid contains an invalid port number: "<<part<<endl;
+    if (port < 1024 || port > 65535) {
+      g_log << Logger::Error << "Unable to launch, udp-source-port-avoid contains an invalid port number: " << part << endl;
       exit(99); // this isn't going to fix itself either
     }
     s_avoidUdpSourcePorts.insert(port);
@@ -1634,8 +1629,8 @@ static int serviceMain(int argc, char*argv[])
   unsigned int currentThreadId = 1;
   const auto cpusMap = parseCPUMap();
 
-  if(g_numThreads == 1) {
-    g_log<<Logger::Warning<<"Operating unthreaded"<<endl;
+  if (g_numThreads == 1) {
+    g_log << Logger::Warning << "Operating unthreaded" << endl;
 #ifdef HAVE_SYSTEMD
     sd_notify(0, "READY=1");
 #endif
@@ -1651,7 +1646,7 @@ static int serviceMain(int argc, char*argv[])
     infos.isListener = true;
     infos.isWorker = true;
     recursorThread(currentThreadId++, "worker");
-    
+
     handlerInfos.thread.join();
     if (handlerInfos.exitCode != 0) {
       ret = handlerInfos.exitCode;
@@ -1659,31 +1654,30 @@ static int serviceMain(int argc, char*argv[])
   }
   else {
 
-    
     if (g_weDistributeQueries) {
-      for(unsigned int n=0; n < g_numDistributorThreads; ++n) {
+      for (unsigned int n = 0; n < g_numDistributorThreads; ++n) {
         auto& infos = s_threadInfos.at(currentThreadId + n);
         infos.isListener = true;
       }
     }
-    for(unsigned int n=0; n < g_numWorkerThreads; ++n) {
+    for (unsigned int n = 0; n < g_numWorkerThreads; ++n) {
       auto& infos = s_threadInfos.at(currentThreadId + (g_weDistributeQueries ? g_numDistributorThreads : 0) + n);
       infos.isListener = !g_weDistributeQueries;
       infos.isWorker = true;
     }
 
     if (g_weDistributeQueries) {
-      g_log<<Logger::Warning<<"Launching "<< g_numDistributorThreads <<" distributor threads"<<endl;
-      for(unsigned int n=0; n < g_numDistributorThreads; ++n) {
+      g_log << Logger::Warning << "Launching " << g_numDistributorThreads << " distributor threads" << endl;
+      for (unsigned int n = 0; n < g_numDistributorThreads; ++n) {
         auto& infos = s_threadInfos.at(currentThreadId);
         infos.thread = std::thread(recursorThread, currentThreadId++, "distr");
         setCPUMap(cpusMap, currentThreadId, infos.thread.native_handle());
       }
     }
 
-    g_log<<Logger::Warning<<"Launching "<< g_numWorkerThreads <<" worker threads"<<endl;
+    g_log << Logger::Warning << "Launching " << g_numWorkerThreads << " worker threads" << endl;
 
-    for(unsigned int n=0; n < g_numWorkerThreads; ++n) {
+    for (unsigned int n = 0; n < g_numWorkerThreads; ++n) {
       auto& infos = s_threadInfos.at(currentThreadId);
       infos.thread = std::thread(recursorThread, currentThreadId++, "worker");
       setCPUMap(cpusMap, currentThreadId, infos.thread.native_handle());
@@ -1698,7 +1692,7 @@ static int serviceMain(int argc, char*argv[])
     infos.isHandler = true;
     infos.thread = std::thread(recursorThread, 0, "web+stat");
 
-    for (auto & ti : s_threadInfos) {
+    for (auto& ti : s_threadInfos) {
       ti.thread.join();
       if (ti.exitCode != 0) {
         ret = ti.exitCode;
@@ -1713,25 +1707,25 @@ static void handlePipeRequest(int fd, FDMultiplexer::funcparam_t& var)
 {
   ThreadMSG* tmsg = nullptr;
 
-  if(read(fd, &tmsg, sizeof(tmsg)) != sizeof(tmsg)) { // fd == readToThread || fd == readQueriesToThread
+  if (read(fd, &tmsg, sizeof(tmsg)) != sizeof(tmsg)) { // fd == readToThread || fd == readQueriesToThread
     unixDie("read from thread pipe returned wrong size or error");
   }
 
-  void *resp=0;
+  void* resp = 0;
   try {
     resp = tmsg->func();
   }
-  catch(std::exception& e) {
-    if(g_logCommonErrors)
-      g_log<<Logger::Error<<"PIPE function we executed created exception: "<<e.what()<<endl; // but what if they wanted an answer.. we send 0
+  catch (std::exception& e) {
+    if (g_logCommonErrors)
+      g_log << Logger::Error << "PIPE function we executed created exception: " << e.what() << endl; // but what if they wanted an answer.. we send 0
   }
-  catch(PDNSException& e) {
-    if(g_logCommonErrors)
-      g_log<<Logger::Error<<"PIPE function we executed created PDNS exception: "<<e.reason<<endl; // but what if they wanted an answer.. we send 0
+  catch (PDNSException& e) {
+    if (g_logCommonErrors)
+      g_log << Logger::Error << "PIPE function we executed created PDNS exception: " << e.reason << endl; // but what if they wanted an answer.. we send 0
   }
-  if(tmsg->wantAnswer) {
+  if (tmsg->wantAnswer) {
     const auto& threadInfo = s_threadInfos.at(t_id);
-    if(write(threadInfo.pipes.writeFromThread, &resp, sizeof(resp)) != sizeof(resp)) {
+    if (write(threadInfo.pipes.writeFromThread, &resp, sizeof(resp)) != sizeof(resp)) {
       delete tmsg;
       unixDie("write to thread pipe returned wrong size or error");
     }
@@ -1757,20 +1751,20 @@ static void handleRCC(int fd, FDMultiplexer::funcparam_t& var)
     s_rcc.send(clientfd, answer);
     command();
   }
-  catch(const std::exception& e) {
-    g_log<<Logger::Error<<"Error dealing with control socket request: "<<e.what()<<endl;
+  catch (const std::exception& e) {
+    g_log << Logger::Error << "Error dealing with control socket request: " << e.what() << endl;
   }
-  catch(const PDNSException& ae) {
-    g_log<<Logger::Error<<"Error dealing with control socket request: "<<ae.reason<<endl;
+  catch (const PDNSException& ae) {
+    g_log << Logger::Error << "Error dealing with control socket request: " << ae.reason << endl;
   }
 }
-static void houseKeeping(void *)
+static void houseKeeping(void*)
 {
   static thread_local time_t last_rootupdate, last_secpoll, last_trustAnchorUpdate{0};
   static thread_local struct timeval last_prune;
 
-  static thread_local int cleanCounter=0;
-  static thread_local bool s_running;  // houseKeeping can get suspended in secpoll, and be restarted, which makes us do duplicate work
+  static thread_local int cleanCounter = 0;
+  static thread_local bool s_running; // houseKeeping can get suspended in secpoll, and be restarted, which makes us do duplicate work
   static time_t last_RC_prune = 0;
   auto luaconfsLocal = g_luaconfs.getLocal();
 
@@ -1780,10 +1774,10 @@ static void houseKeeping(void *)
   }
 
   try {
-    if(s_running) {
+    if (s_running) {
       return;
     }
-    s_running=true;
+    s_running = true;
 
     runTaskOnce(g_logCommonErrors);
 
@@ -1795,13 +1789,13 @@ static void houseKeeping(void *)
       t_packetCache->doPruneTo(g_maxPacketCacheEntries / (g_numWorkerThreads + g_numDistributorThreads));
 
       time_t limit;
-      if(!((cleanCounter++)%40)) {  // this is a full scan!
-       limit=now.tv_sec-300;
+      if (!((cleanCounter++) % 40)) { // this is a full scan!
+        limit = now.tv_sec - 300;
         SyncRes::pruneNSSpeeds(limit);
       }
       limit = now.tv_sec - SyncRes::s_serverdownthrottletime * 10;
       SyncRes::pruneFailedServers(limit);
-      limit = now.tv_sec - 2*3600;
+      limit = now.tv_sec - 2 * 3600;
       SyncRes::pruneEDNSStatuses(limit);
       SyncRes::pruneThrottledServers();
       SyncRes::pruneNonResolving(now.tv_sec - SyncRes::s_nonresolvingnsthrottletime);
@@ -1809,7 +1803,7 @@ static void houseKeeping(void *)
       t_tcp_manager.cleanup(now);
     }
 
-    if(isHandlerThread()) {
+    if (isHandlerThread()) {
       if (now.tv_sec - last_RC_prune > 5) {
         g_recCache->doPrune(g_maxCacheEntries);
         g_negCache->prune(g_maxCacheEntries / 10);
@@ -1822,91 +1816,82 @@ static void houseKeeping(void *)
       if (now.tv_sec - last_rootupdate > max(SyncRes::s_maxcachettl / 12, 10U)) {
         int res = SyncRes::getRootNS(g_now, nullptr, 0);
         if (!res) {
-          last_rootupdate=now.tv_sec;
+          last_rootupdate = now.tv_sec;
           try {
             primeRootNSZones(g_dnssecmode != DNSSECMode::Off, 0);
           }
           catch (const std::exception& e) {
-            g_log<<Logger::Error<<"Exception while priming the root NS zones: "<<e.what()<<endl;
+            g_log << Logger::Error << "Exception while priming the root NS zones: " << e.what() << endl;
           }
           catch (const PDNSException& e) {
-            g_log<<Logger::Error<<"Exception while priming the root NS zones: "<<e.reason<<endl;
+            g_log << Logger::Error << "Exception while priming the root NS zones: " << e.reason << endl;
           }
           catch (const ImmediateServFailException& e) {
-            g_log<<Logger::Error<<"Exception while priming the root NS zones: "<<e.reason<<endl;
+            g_log << Logger::Error << "Exception while priming the root NS zones: " << e.reason << endl;
           }
           catch (const PolicyHitException& e) {
-            g_log<<Logger::Error<<"Policy hit while priming the root NS zones"<<endl;
+            g_log << Logger::Error << "Policy hit while priming the root NS zones" << endl;
           }
-          catch (...)
-          {
-            g_log<<Logger::Error<<"Exception while priming the root NS zones"<<endl;
+          catch (...) {
+            g_log << Logger::Error << "Exception while priming the root NS zones" << endl;
           }
         }
       }
 
-      if(now.tv_sec - last_secpoll >= 3600) {
-       try {
-         doSecPoll(&last_secpoll);
-       }
-       catch (const std::exception& e)
-        {
-          g_log<<Logger::Error<<"Exception while performing security poll: "<<e.what()<<endl;
+      if (now.tv_sec - last_secpoll >= 3600) {
+        try {
+          doSecPoll(&last_secpoll);
         }
-        catch (const PDNSException& e)
-        {
-          g_log<<Logger::Error<<"Exception while performing security poll: "<<e.reason<<endl;
+        catch (const std::exception& e) {
+          g_log << Logger::Error << "Exception while performing security poll: " << e.what() << endl;
         }
-        catch (const ImmediateServFailException &e)
-        {
-          g_log<<Logger::Error<<"Exception while performing security poll: "<<e.reason<<endl;
+        catch (const PDNSException& e) {
+          g_log << Logger::Error << "Exception while performing security poll: " << e.reason << endl;
+        }
+        catch (const ImmediateServFailException& e) {
+          g_log << Logger::Error << "Exception while performing security poll: " << e.reason << endl;
         }
         catch (const PolicyHitException& e) {
-          g_log<<Logger::Error<<"Policy hit while performing security poll"<<endl;
+          g_log << Logger::Error << "Policy hit while performing security poll" << endl;
         }
-        catch (...)
-        {
-          g_log<<Logger::Error<<"Exception while performing security poll"<<endl;
+        catch (...) {
+          g_log << Logger::Error << "Exception while performing security poll" << endl;
         }
       }
 
-      if (!luaconfsLocal->trustAnchorFileInfo.fname.empty() && luaconfsLocal->trustAnchorFileInfo.interval != 0 &&
-          g_now.tv_sec - last_trustAnchorUpdate >= (luaconfsLocal->trustAnchorFileInfo.interval * 3600)) {
-        g_log<<Logger::Debug<<"Refreshing Trust Anchors from file"<<endl;
+      if (!luaconfsLocal->trustAnchorFileInfo.fname.empty() && luaconfsLocal->trustAnchorFileInfo.interval != 0 && g_now.tv_sec - last_trustAnchorUpdate >= (luaconfsLocal->trustAnchorFileInfo.interval * 3600)) {
+        g_log << Logger::Debug << "Refreshing Trust Anchors from file" << endl;
         try {
           map<DNSName, dsmap_t> dsAnchors;
           if (updateTrustAnchorsFromFile(luaconfsLocal->trustAnchorFileInfo.fname, dsAnchors)) {
             g_luaconfs.modify([&dsAnchors](LuaConfigItems& lci) {
-                lci.dsAnchors = dsAnchors;
+              lci.dsAnchors = dsAnchors;
             });
           }
           last_trustAnchorUpdate = now.tv_sec;
-        } catch (const PDNSException &pe) {
-          g_log<<Logger::Error<<"Unable to update Trust Anchors: "<<pe.reason<<endl;
+        }
+        catch (const PDNSException& pe) {
+          g_log << Logger::Error << "Unable to update Trust Anchors: " << pe.reason << endl;
         }
       }
     }
     s_running = false;
   }
-  catch (const PDNSException& ae)
-  {
+  catch (const PDNSException& ae) {
     s_running = false;
-    g_log<<Logger::Error<<"Fatal error in housekeeping thread: "<<ae.reason<<endl;
+    g_log << Logger::Error << "Fatal error in housekeeping thread: " << ae.reason << endl;
     throw;
   }
-  catch (...)
-  {
+  catch (...) {
     s_running = false;
-    g_log<<Logger::Error<<"Uncaught exception in housekeeping thread"<<endl;
+    g_log << Logger::Error << "Uncaught exception in housekeeping thread" << endl;
     throw;
   }
 }
 
-
 void* recursorThread(unsigned int n, const string& threadName)
-try
-{
-  t_id=n;
+try {
+  t_id = n;
   auto& threadInfo = s_threadInfos.at(t_id);
 
   static string threadPrefix = "pdns-r/";
@@ -1924,10 +1909,10 @@ try
     if (!primeHints()) {
       threadInfo.exitCode = EXIT_FAILURE;
       RecursorControlChannel::stop = 1;
-      g_log<<Logger::Critical<<"Priming cache failed, stopping"<<endl;
+      g_log << Logger::Critical << "Priming cache failed, stopping" << endl;
       return nullptr;
     }
-    g_log<<Logger::Warning<<"Done priming cache with root hints"<<endl;
+    g_log << Logger::Warning << "Done priming cache with root hints" << endl;
   }
 
   t_packetCache = std::make_unique<RecursorPacketCache>();
@@ -1938,24 +1923,24 @@ try
 #endif /* NOD_ENABLED */
 
   /* the listener threads handle TCP queries */
-  if(threadInfo.isWorker || threadInfo.isListener) {
+  if (threadInfo.isWorker || threadInfo.isListener) {
     try {
-      if(!::arg()["lua-dns-script"].empty()) {
+      if (!::arg()["lua-dns-script"].empty()) {
         t_pdl = std::make_shared<RecursorLua4>();
         t_pdl->loadFile(::arg()["lua-dns-script"]);
-        g_log<<Logger::Warning<<"Loaded 'lua' script from '"<<::arg()["lua-dns-script"]<<"'"<<endl;
+        g_log << Logger::Warning << "Loaded 'lua' script from '" << ::arg()["lua-dns-script"] << "'" << endl;
       }
     }
-    catch(std::exception &e) {
-      g_log<<Logger::Error<<"Failed to load 'lua' script from '"<<::arg()["lua-dns-script"]<<"': "<<e.what()<<endl;
+    catch (std::exception& e) {
+      g_log << Logger::Error << "Failed to load 'lua' script from '" << ::arg()["lua-dns-script"] << "': " << e.what() << endl;
       _exit(99);
     }
   }
 
-  unsigned int ringsize=::arg().asNum("stats-ringbuffer-entries") / g_numWorkerThreads;
-  if(ringsize) {
+  unsigned int ringsize = ::arg().asNum("stats-ringbuffer-entries") / g_numWorkerThreads;
+  if (ringsize) {
     t_remotes = std::make_unique<addrringbuf_t>();
-    if(g_weDistributeQueries)
+    if (g_weDistributeQueries)
       t_remotes->set_capacity(::arg().asNum("stats-ringbuffer-entries") / g_numDistributorThreads);
     else
       t_remotes->set_capacity(ringsize);
@@ -1988,24 +1973,24 @@ try
 
   PacketID pident;
 
-  t_fdm=getMultiplexer();
+  t_fdm = getMultiplexer();
 
-  RecursorWebServer *rws = nullptr;
+  RecursorWebServerrws = nullptr;
 
   t_fdm->addReadFD(threadInfo.pipes.readToThread, handlePipeRequest);
 
-  if(threadInfo.isHandler) {
-    if(::arg().mustDo("webserver")) {
-      g_log<<Logger::Warning << "Enabling web server" << endl;
+  if (threadInfo.isHandler) {
+    if (::arg().mustDo("webserver")) {
+      g_log << Logger::Warning << "Enabling web server" << endl;
       try {
         rws = new RecursorWebServer(t_fdm);
       }
-      catch (const PDNSException &e) {
-        g_log<<Logger::Error<<"Unable to start the internal web server: "<<e.reason<<endl;
+      catch (const PDNSExceptione) {
+        g_log << Logger::Error << "Unable to start the internal web server: " << e.reason << endl;
         _exit(99);
       }
     }
-    g_log<<Logger::Info<<"Enabled '"<< t_fdm->getName() << "' multiplexer"<<endl;
+    g_log << Logger::Info << "Enabled '" << t_fdm->getName() << "' multiplexer" << endl;
   }
   else {
     t_fdm->addReadFD(threadInfo.pipes.readQueriesToThread, handlePipeRequest);
@@ -2013,13 +1998,13 @@ try
     if (threadInfo.isListener) {
       if (g_reusePort) {
         /* then every listener has its own FDs */
-        for(const auto& deferred : threadInfo.deferredAdds) {
+        for (const auto& deferred : threadInfo.deferredAdds) {
           t_fdm->addReadFD(deferred.first, deferred.second);
         }
       }
       else {
         /* otherwise all listeners are listening on the same ones */
-        for(const auto& deferred : g_deferredAdds) {
+        for (const auto& deferred : g_deferredAdds) {
           t_fdm->addReadFD(deferred.first, deferred.second);
         }
       }
@@ -2028,22 +2013,23 @@ try
 
   registerAllStats();
 
-  if(threadInfo.isHandler) {
+  if (threadInfo.isHandler) {
     t_fdm->addReadFD(s_rcc.d_fd, handleRCC); // control channel
   }
 
-  unsigned int maxTcpClients=::arg().asNum("max-tcp-clients");
+  unsigned int maxTcpClients = ::arg().asNum("max-tcp-clients");
 
   bool listenOnTCP(true);
 
   time_t last_stat = 0;
-  time_t last_carbon=0, last_lua_maintenance=0;
-  time_t carbonInterval=::arg().asNum("carbon-interval");
-  time_t luaMaintenanceInterval=::arg().asNum("lua-maintenance-interval");
+  time_t last_carbon = 0, last_lua_maintenance = 0;
+  time_t carbonInterval = ::arg().asNum("carbon-interval");
+  time_t luaMaintenanceInterval = ::arg().asNum("lua-maintenance-interval");
   counter.store(0); // used to periodically execute certain tasks
 
   while (!RecursorControlChannel::stop) {
-    while(MT->schedule(&g_now)); // MTasker letting the mthreads do their thing
+    while (MT->schedule(&g_now))
+      ; // MTasker letting the mthreads do their thing
 
     // Use primes, it avoid not being scheduled in cases where the counter has a regular pattern.
     // We want to call handler thread often, it gets scheduled about 2 times per second
@@ -2051,29 +2037,29 @@ try
       MT->makeThread(houseKeeping, 0);
     }
 
-    if(!(counter%55)) {
-      typedef vector<pair<int, FDMultiplexer::funcparam_t> > expired_t;
-      expired_t expired=t_fdm->getTimeouts(g_now);
+    if (!(counter % 55)) {
+      typedef vector<pair<int, FDMultiplexer::funcparam_t>> expired_t;
+      expired_t expired = t_fdm->getTimeouts(g_now);
 
-      for(expired_t::iterator i=expired.begin() ; i != expired.end(); ++i) {
-        shared_ptr<TCPConnection> conn=boost::any_cast<shared_ptr<TCPConnection> >(i->second);
-        if(g_logCommonErrors)
-          g_log<<Logger::Warning<<"Timeout from remote TCP client "<< conn->d_remote.toStringWithPort() <<endl;
+      for (expired_t::iterator i = expired.begin(); i != expired.end(); ++i) {
+        shared_ptr<TCPConnection> conn = boost::any_cast<shared_ptr<TCPConnection>>(i->second);
+        if (g_logCommonErrors)
+          g_log << Logger::Warning << "Timeout from remote TCP client " << conn->d_remote.toStringWithPort() << endl;
         t_fdm->removeReadFD(i->first);
       }
     }
 
     counter++;
 
-    if(threadInfo.isHandler) {
-      if(statsWanted || (g_statisticsInterval > 0 && (g_now.tv_sec - last_stat) >= g_statisticsInterval)) {
+    if (threadInfo.isHandler) {
+      if (statsWanted || (g_statisticsInterval > 0 && (g_now.tv_sec - last_stat) >= g_statisticsInterval)) {
         doStats();
         last_stat = g_now.tv_sec;
       }
 
       Utility::gettimeofday(&g_now, nullptr);
 
-      if((g_now.tv_sec - last_carbon) >= carbonInterval) {
+      if ((g_now.tv_sec - last_carbon) >= carbonInterval) {
         MT->makeThread(doCarbonDump, 0);
         last_carbon = g_now.tv_sec;
       }
@@ -2083,7 +2069,7 @@ try
       /* remember that the listener threads handle TCP queries */
       if (threadInfo.isWorker || threadInfo.isListener) {
         // Only on threads processing queries
-        if(g_now.tv_sec - last_lua_maintenance >= luaMaintenanceInterval) {
+        if (g_now.tv_sec - last_lua_maintenance >= luaMaintenanceInterval) {
           t_pdl->maintenance();
           last_lua_maintenance = g_now.tv_sec;
         }
@@ -2093,21 +2079,21 @@ try
     t_fdm->run(&g_now);
     // 'run' updates g_now for us
 
-    if(threadInfo.isListener) {
-      if(listenOnTCP) {
-        if(TCPConnection::getCurrentConnections() > maxTcpClients) {  // shutdown, too many connections
-          for(const auto fd : threadInfo.tcpSockets) {
+    if (threadInfo.isListener) {
+      if (listenOnTCP) {
+        if (TCPConnection::getCurrentConnections() > maxTcpClients) { // shutdown, too many connections
+          for (const auto fd : threadInfo.tcpSockets) {
             t_fdm->removeReadFD(fd);
           }
-          listenOnTCP=false;
+          listenOnTCP = false;
         }
       }
       else {
-        if(TCPConnection::getCurrentConnections() <= maxTcpClients) {  // reenable
-          for(const auto fd : threadInfo.tcpSockets) {
+        if (TCPConnection::getCurrentConnections() <= maxTcpClients) { // reenable
+          for (const auto fd : threadInfo.tcpSockets) {
             t_fdm->addReadFD(fd, handleNewTCPQuestion);
           }
-          listenOnTCP=true;
+          listenOnTCP = true;
         }
       }
     }
@@ -2116,24 +2102,24 @@ try
   delete t_fdm;
   return 0;
 }
-catch(PDNSException &ae) {
-  g_log<<Logger::Error<<"Exception: "<<ae.reason<<endl;
+catch (PDNSException& ae) {
+  g_log << Logger::Error << "Exception: " << ae.reason << endl;
   return 0;
 }
-catch(std::exception &e) {
-   g_log<<Logger::Error<<"STL Exception: "<<e.what()<<endl;
-   return 0;
+catch (std::exception& e) {
+  g_log << Logger::Error << "STL Exception: " << e.what() << endl;
+  return 0;
 }
-catch(...) {
-   g_log<<Logger::Error<<"any other exception in main: "<<endl;
-   return 0;
+catch (...) {
+  g_log << Logger::Error << "any other exception in main: " << endl;
+  return 0;
 }
 
-int main(int argc, char **argv)
+int main(int argc, char** argv)
 {
   g_argc = argc;
   g_argv = argv;
-  g_stats.startupTime=time(0);
+  g_stats.startupTime = time(0);
   Utility::srandom();
   versionSetProduct(ProductRecursor);
   reportBasicTypes();
@@ -2144,162 +2130,166 @@ int main(int argc, char **argv)
   try {
 #if HAVE_FIBER_SANITIZER
     // Asan needs more stack
-    ::arg().set("stack-size","stack size per mthread")="400000";
+    ::arg().set("stack-size", "stack size per mthread") = "400000";
 #else
-    ::arg().set("stack-size","stack size per mthread")="200000";
+    ::arg().set("stack-size", "stack size per mthread") = "200000";
 #endif
-    ::arg().set("soa-minimum-ttl","Don't change")="0";
-    ::arg().set("no-shuffle","Don't change")="off";
-    ::arg().set("local-port","port to listen on")="53";
-    ::arg().set("local-address","IP addresses to listen on, separated by spaces or commas. Also accepts ports.")="127.0.0.1";
-    ::arg().setSwitch("non-local-bind", "Enable binding to non-local addresses by using FREEBIND / BINDANY socket options")="no";
-    ::arg().set("trace","if we should output heaps of logging. set to 'fail' to only log failing domains")="off";
-    ::arg().set("dnssec", "DNSSEC mode: off/process-no-validate/process (default)/log-fail/validate")="process";
-    ::arg().set("dnssec-log-bogus", "Log DNSSEC bogus validations")="no";
-    ::arg().set("signature-inception-skew", "Allow the signature inception to be off by this number of seconds")="60";
-    ::arg().set("daemon","Operate as a daemon")="no";
-    ::arg().setSwitch("write-pid","Write a PID file")="yes";
-    ::arg().set("loglevel","Amount of logging. Higher is more. Do not set below 3")="6";
-    ::arg().set("disable-syslog","Disable logging to syslog, useful when running inside a supervisor that logs stdout")="no";
-    ::arg().set("log-timestamp","Print timestamps in log lines, useful to disable when running with a tool that timestamps stdout already")="yes";
-    ::arg().set("log-common-errors","If we should log rather common errors")="no";
-    ::arg().set("chroot","switch to chroot jail")="";
-    ::arg().set("setgid","If set, change group id to this gid for more security"
+    ::arg().set("soa-minimum-ttl", "Don't change") = "0";
+    ::arg().set("no-shuffle", "Don't change") = "off";
+    ::arg().set("local-port", "port to listen on") = "53";
+    ::arg().set("local-address", "IP addresses to listen on, separated by spaces or commas. Also accepts ports.") = "127.0.0.1";
+    ::arg().setSwitch("non-local-bind", "Enable binding to non-local addresses by using FREEBIND / BINDANY socket options") = "no";
+    ::arg().set("trace", "if we should output heaps of logging. set to 'fail' to only log failing domains") = "off";
+    ::arg().set("dnssec", "DNSSEC mode: off/process-no-validate/process (default)/log-fail/validate") = "process";
+    ::arg().set("dnssec-log-bogus", "Log DNSSEC bogus validations") = "no";
+    ::arg().set("signature-inception-skew", "Allow the signature inception to be off by this number of seconds") = "60";
+    ::arg().set("daemon", "Operate as a daemon") = "no";
+    ::arg().setSwitch("write-pid", "Write a PID file") = "yes";
+    ::arg().set("loglevel", "Amount of logging. Higher is more. Do not set below 3") = "6";
+    ::arg().set("disable-syslog", "Disable logging to syslog, useful when running inside a supervisor that logs stdout") = "no";
+    ::arg().set("log-timestamp", "Print timestamps in log lines, useful to disable when running with a tool that timestamps stdout already") = "yes";
+    ::arg().set("log-common-errors", "If we should log rather common errors") = "no";
+    ::arg().set("chroot", "switch to chroot jail") = "";
+    ::arg().set("setgid", "If set, change group id to this gid for more security"
 #ifdef HAVE_SYSTEMD
 #define SYSTEMD_SETID_MSG ". When running inside systemd, use the User and Group settings in the unit-file!"
-        SYSTEMD_SETID_MSG
+                SYSTEMD_SETID_MSG
 #endif
-        )="";
-    ::arg().set("setuid","If set, change user id to this uid for more security"
+                )
+      = "";
+    ::arg().set("setuid", "If set, change user id to this uid for more security"
 #ifdef HAVE_SYSTEMD
-        SYSTEMD_SETID_MSG
+                SYSTEMD_SETID_MSG
 #endif
-        )="";
-    ::arg().set("network-timeout", "Wait this number of milliseconds for network i/o")="1500";
-    ::arg().set("threads", "Launch this number of threads")="2";
-    ::arg().set("distributor-threads", "Launch this number of distributor threads, distributing queries to other threads")="0";
-    ::arg().set("processes", "Launch this number of processes (EXPERIMENTAL, DO NOT CHANGE)")="1"; // if we un-experimental this, need to fix openssl rand seeding for multiple PIDs!
-    ::arg().set("config-name","Name of this virtual configuration - will rename the binary image")="";
+                )
+      = "";
+    ::arg().set("network-timeout", "Wait this number of milliseconds for network i/o") = "1500";
+    ::arg().set("threads", "Launch this number of threads") = "2";
+    ::arg().set("distributor-threads", "Launch this number of distributor threads, distributing queries to other threads") = "0";
+    ::arg().set("processes", "Launch this number of processes (EXPERIMENTAL, DO NOT CHANGE)") = "1"; // if we un-experimental this, need to fix openssl rand seeding for multiple PIDs!
+    ::arg().set("config-name", "Name of this virtual configuration - will rename the binary image") = "";
     ::arg().set("api-config-dir", "Directory where REST API stores config and zones") = "";
     ::arg().set("api-key", "Static pre-shared authentication key for access to the REST API") = "";
     ::arg().setSwitch("webserver", "Start a webserver (for REST API)") = "no";
     ::arg().set("webserver-address", "IP Address of webserver to listen on") = "127.0.0.1";
     ::arg().set("webserver-port", "Port of webserver to listen on") = "8082";
     ::arg().set("webserver-password", "Password required for accessing the webserver") = "";
-    ::arg().set("webserver-allow-from","Webserver access is only allowed from these subnets")="127.0.0.1,::1";
+    ::arg().set("webserver-allow-from", "Webserver access is only allowed from these subnets") = "127.0.0.1,::1";
     ::arg().set("webserver-loglevel", "Amount of logging in the webserver (none, normal, detailed)") = "normal";
-    ::arg().setSwitch("webserver-hash-plaintext-credentials","Whether to hash passwords and api keys supplied in plaintext, to prevent keeping the plaintext version in memory at runtime")="no";
-    ::arg().set("carbon-ourname", "If set, overrides our reported hostname for carbon stats")="";
-    ::arg().set("carbon-server", "If set, send metrics in carbon (graphite) format to this server IP address")="";
-    ::arg().set("carbon-interval", "Number of seconds between carbon (graphite) updates")="30";
-    ::arg().set("carbon-namespace", "If set overwrites the first part of the carbon string")="pdns";
-    ::arg().set("carbon-instance", "If set overwrites the instance name default")="recursor";
-
-    ::arg().set("statistics-interval", "Number of seconds between printing of recursor statistics, 0 to disable")="1800";
-    ::arg().set("quiet","Suppress logging of questions and answers")="";
-    ::arg().set("logging-facility","Facility to log messages as. 0 corresponds to local0")="";
-    ::arg().set("config-dir","Location of configuration directory (recursor.conf)")=SYSCONFDIR;
-    ::arg().set("socket-owner","Owner of socket")="";
-    ::arg().set("socket-group","Group of socket")="";
-    ::arg().set("socket-mode", "Permissions for socket")="";
-
-    ::arg().set("socket-dir",string("Where the controlsocket will live, ")+LOCALSTATEDIR+"/pdns-recursor when unset and not chrooted"
+    ::arg().setSwitch("webserver-hash-plaintext-credentials", "Whether to hash passwords and api keys supplied in plaintext, to prevent keeping the plaintext version in memory at runtime") = "no";
+    ::arg().set("carbon-ourname", "If set, overrides our reported hostname for carbon stats") = "";
+    ::arg().set("carbon-server", "If set, send metrics in carbon (graphite) format to this server IP address") = "";
+    ::arg().set("carbon-interval", "Number of seconds between carbon (graphite) updates") = "30";
+    ::arg().set("carbon-namespace", "If set overwrites the first part of the carbon string") = "pdns";
+    ::arg().set("carbon-instance", "If set overwrites the instance name default") = "recursor";
+
+    ::arg().set("statistics-interval", "Number of seconds between printing of recursor statistics, 0 to disable") = "1800";
+    ::arg().set("quiet", "Suppress logging of questions and answers") = "";
+    ::arg().set("logging-facility", "Facility to log messages as. 0 corresponds to local0") = "";
+    ::arg().set("config-dir", "Location of configuration directory (recursor.conf)") = SYSCONFDIR;
+    ::arg().set("socket-owner", "Owner of socket") = "";
+    ::arg().set("socket-group", "Group of socket") = "";
+    ::arg().set("socket-mode", "Permissions for socket") = "";
+
+    ::arg().set("socket-dir", string("Where the controlsocket will live, ") + LOCALSTATEDIR + "/pdns-recursor when unset and not chrooted"
 #ifdef HAVE_SYSTEMD
-      + ". Set to the RUNTIME_DIRECTORY environment variable when that variable has a value (e.g. under systemd).")="";
-   auto runtimeDir = getenv("RUNTIME_DIRECTORY");
-   if (runtimeDir != nullptr) {
-     ::arg().set("socket-dir") = runtimeDir;
-   }
+                  + ". Set to the RUNTIME_DIRECTORY environment variable when that variable has a value (e.g. under systemd).")
+      = "";
+    auto runtimeDir = getenv("RUNTIME_DIRECTORY");
+    if (runtimeDir != nullptr) {
+      ::arg().set("socket-dir") = runtimeDir;
+    }
 #else
-      )="";
+                )
+      = "";
 #endif
-    ::arg().set("query-local-address","Source IP address for sending queries")="0.0.0.0";
-    ::arg().set("client-tcp-timeout","Timeout in seconds when talking to TCP clients")="2";
-    ::arg().set("max-mthreads", "Maximum number of simultaneous Mtasker threads")="2048";
-    ::arg().set("max-tcp-clients","Maximum number of simultaneous TCP clients")="128";
+    ::arg().set("query-local-address", "Source IP address for sending queries") = "0.0.0.0";
+    ::arg().set("client-tcp-timeout", "Timeout in seconds when talking to TCP clients") = "2";
+    ::arg().set("max-mthreads", "Maximum number of simultaneous Mtasker threads") = "2048";
+    ::arg().set("max-tcp-clients", "Maximum number of simultaneous TCP clients") = "128";
     ::arg().set("max-concurrent-requests-per-tcp-connection", "Maximum number of requests handled concurrently per TCP connection") = "10";
-    ::arg().set("server-down-max-fails","Maximum number of consecutive timeouts (and unreachables) to mark a server as down ( 0 => disabled )")="64";
-    ::arg().set("server-down-throttle-time","Number of seconds to throttle all queries to a server after being marked as down")="60";
-    ::arg().set("dont-throttle-names", "Do not throttle nameservers with this name or suffix")="";
-    ::arg().set("dont-throttle-netmasks", "Do not throttle nameservers with this IP netmask")="";
-    ::arg().set("non-resolving-ns-max-fails", "Number of failed address resolves of a nameserver to start throttling it, 0 is disabled")="5";
-    ::arg().set("non-resolving-ns-throttle-time", "Number of seconds to throttle a nameserver with a name failing to resolve")="60";
-
-    ::arg().set("hint-file", "If set, load root hints from this file")="";
-    ::arg().set("max-cache-entries", "If set, maximum number of entries in the main cache")="1000000";
-    ::arg().set("max-negative-ttl", "maximum number of seconds to keep a negative cached entry in memory")="3600";
-    ::arg().set("max-cache-bogus-ttl", "maximum number of seconds to keep a Bogus (positive or negative) cached entry in memory")="3600";
-    ::arg().set("max-cache-ttl", "maximum number of seconds to keep a cached entry in memory")="86400";
-    ::arg().set("packetcache-ttl", "maximum number of seconds to keep a cached entry in packetcache")="3600";
-    ::arg().set("max-packetcache-entries", "maximum number of entries to keep in the packetcache")="500000";
-    ::arg().set("packetcache-servfail-ttl", "maximum number of seconds to keep a cached servfail entry in packetcache")="60";
-    ::arg().set("server-id", "Returned when queried for 'id.server' TXT or NSID, defaults to hostname, set custom or 'disabled'")="";
-    ::arg().set("stats-ringbuffer-entries", "maximum number of packets to store statistics for")="10000";
-    ::arg().set("version-string", "string reported on version.pdns or version.bind")=fullVersionString();
-    ::arg().set("allow-from", "If set, only allow these comma separated netmasks to recurse")=LOCAL_NETS;
-    ::arg().set("allow-from-file", "If set, load allowed netmasks from this file")="";
-    ::arg().set("allow-notify-for", "If set, NOTIFY requests for these zones will be allowed")="";
-    ::arg().set("allow-notify-for-file", "If set, load NOTIFY-allowed zones from this file")="";
-    ::arg().set("allow-notify-from", "If set, NOTIFY requests from these comma separated netmasks will be allowed")="";
-    ::arg().set("allow-notify-from-file", "If set, load NOTIFY-allowed netmasks from this file")="";
-    ::arg().set("entropy-source", "If set, read entropy from this file")="/dev/urandom";
-    ::arg().set("dont-query", "If set, do not query these netmasks for DNS data")=DONT_QUERY;
-    ::arg().set("max-tcp-per-client", "If set, maximum number of TCP sessions per client (IP address)")="0";
-    ::arg().set("max-tcp-queries-per-connection", "If set, maximum number of TCP queries in a TCP connection")="0";
-    ::arg().set("spoof-nearmiss-max", "If non-zero, assume spoofing after this many near misses")="1";
-    ::arg().set("single-socket", "If set, only use a single socket for outgoing queries")="off";
-    ::arg().set("auth-zones", "Zones for which we have authoritative data, comma separated domain=file pairs ")="";
-    ::arg().set("lua-config-file", "More powerful configuration options")="";
-    ::arg().setSwitch("allow-trust-anchor-query", "Allow queries for trustanchor.server CH TXT and negativetrustanchor.server CH TXT")="no";
-
-    ::arg().set("forward-zones", "Zones for which we forward queries, comma separated domain=ip pairs")="";
-    ::arg().set("forward-zones-recurse", "Zones for which we forward queries with recursion bit, comma separated domain=ip pairs")="";
-    ::arg().set("forward-zones-file", "File with (+)domain=ip pairs for forwarding")="";
-    ::arg().set("export-etc-hosts", "If we should serve up contents from /etc/hosts")="off";
-    ::arg().set("export-etc-hosts-search-suffix", "Also serve up the contents of /etc/hosts with this suffix")="";
-    ::arg().set("etc-hosts-file", "Path to 'hosts' file")="/etc/hosts";
-    ::arg().set("serve-rfc1918", "If we should be authoritative for RFC 1918 private IP space")="yes";
-    ::arg().set("lua-dns-script", "Filename containing an optional 'lua' script that will be used to modify dns answers")="";
-    ::arg().set("lua-maintenance-interval", "Number of seconds between calls to the lua user defined maintenance() function")="1";
-    ::arg().set("latency-statistic-size","Number of latency values to calculate the qa-latency average")="10000";
-    ::arg().setSwitch( "disable-packetcache", "Disable packetcache" )= "no";
-    ::arg().set("ecs-ipv4-bits", "Number of bits of IPv4 address to pass for EDNS Client Subnet")="24";
-    ::arg().set("ecs-ipv4-cache-bits", "Maximum number of bits of IPv4 mask to cache ECS response")="24";
-    ::arg().set("ecs-ipv6-bits", "Number of bits of IPv6 address to pass for EDNS Client Subnet")="56";
-    ::arg().set("ecs-ipv6-cache-bits", "Maximum number of bits of IPv6 mask to cache ECS response")="56";
-    ::arg().setSwitch("ecs-ipv4-never-cache", "If we should never cache IPv4 ECS responses")="no";
-    ::arg().setSwitch("ecs-ipv6-never-cache", "If we should never cache IPv6 ECS responses")="no";
-    ::arg().set("ecs-minimum-ttl-override", "The minimum TTL for records in ECS-specific answers")="1";
-    ::arg().set("ecs-cache-limit-ttl", "Minimum TTL to cache ECS response")="0";
-    ::arg().set("edns-subnet-whitelist", "List of netmasks and domains that we should enable EDNS subnet for (deprecated)")="";
-    ::arg().set("edns-subnet-allow-list", "List of netmasks and domains that we should enable EDNS subnet for")="";
-    ::arg().set("ecs-add-for", "List of client netmasks for which EDNS Client Subnet will be added")="0.0.0.0/0, ::/0, " LOCAL_NETS_INVERSE;
-    ::arg().set("ecs-scope-zero-address", "Address to send to allow-listed authoritative servers for incoming queries with ECS prefix-length source of 0")="";
-    ::arg().setSwitch( "use-incoming-edns-subnet", "Pass along received EDNS Client Subnet information")="no";
-    ::arg().setSwitch( "pdns-distributes-queries", "If PowerDNS itself should distribute queries over threads")="yes";
-    ::arg().setSwitch( "root-nx-trust", "If set, believe that an NXDOMAIN from the root means the TLD does not exist")="yes";
-    ::arg().setSwitch( "any-to-tcp","Answer ANY queries with tc=1, shunting to TCP" )="no";
-    ::arg().setSwitch( "lowercase-outgoing","Force outgoing questions to lowercase")="no";
-    ::arg().setSwitch("gettag-needs-edns-options", "If EDNS Options should be extracted before calling the gettag() hook")="no";
-    ::arg().set("udp-truncation-threshold", "Maximum UDP response size before we truncate")="1232";
-    ::arg().set("edns-outgoing-bufsize", "Outgoing EDNS buffer size")="1232";
-    ::arg().set("minimum-ttl-override", "The minimum TTL")="1";
-    ::arg().set("max-qperq", "Maximum outgoing queries per query")="60";
-    ::arg().set("max-ns-address-qperq", "Maximum outgoing NS address queries per query")="10";
-    ::arg().set("max-total-msec", "Maximum total wall-clock time per query in milliseconds, 0 for unlimited")="7000";
-    ::arg().set("max-recursion-depth", "Maximum number of internal recursion calls per query, 0 for unlimited")="40";
-    ::arg().set("max-udp-queries-per-round", "Maximum number of UDP queries processed per recvmsg() round, before returning back to normal processing")="10000";
-    ::arg().set("protobuf-use-kernel-timestamp", "Compute the latency of queries in protobuf messages by using the timestamp set by the kernel when the query was received (when available)")="";
-    ::arg().set("distribution-pipe-buffer-size", "Size in bytes of the internal buffer of the pipe used by the distributor to pass incoming queries to a worker thread")="0";
-
-    ::arg().set("include-dir","Include *.conf files from this directory")="";
-    ::arg().set("security-poll-suffix","Domain name from which to query security update notifications")="secpoll.powerdns.com.";
-
-    ::arg().setSwitch("reuseport","Enable SO_REUSEPORT allowing multiple recursors processes to listen to 1 address")="no";
-
-    ::arg().setSwitch("snmp-agent", "If set, register as an SNMP agent")="no";
-    ::arg().set("snmp-master-socket", "If set and snmp-agent is set, the socket to use to register to the SNMP daemon (deprecated)")="";
-    ::arg().set("snmp-daemon-socket", "If set and snmp-agent is set, the socket to use to register to the SNMP daemon")="";
+    ::arg().set("server-down-max-fails", "Maximum number of consecutive timeouts (and unreachables) to mark a server as down ( 0 => disabled )") = "64";
+    ::arg().set("server-down-throttle-time", "Number of seconds to throttle all queries to a server after being marked as down") = "60";
+    ::arg().set("dont-throttle-names", "Do not throttle nameservers with this name or suffix") = "";
+    ::arg().set("dont-throttle-netmasks", "Do not throttle nameservers with this IP netmask") = "";
+    ::arg().set("non-resolving-ns-max-fails", "Number of failed address resolves of a nameserver to start throttling it, 0 is disabled") = "5";
+    ::arg().set("non-resolving-ns-throttle-time", "Number of seconds to throttle a nameserver with a name failing to resolve") = "60";
+
+    ::arg().set("hint-file", "If set, load root hints from this file") = "";
+    ::arg().set("max-cache-entries", "If set, maximum number of entries in the main cache") = "1000000";
+    ::arg().set("max-negative-ttl", "maximum number of seconds to keep a negative cached entry in memory") = "3600";
+    ::arg().set("max-cache-bogus-ttl", "maximum number of seconds to keep a Bogus (positive or negative) cached entry in memory") = "3600";
+    ::arg().set("max-cache-ttl", "maximum number of seconds to keep a cached entry in memory") = "86400";
+    ::arg().set("packetcache-ttl", "maximum number of seconds to keep a cached entry in packetcache") = "3600";
+    ::arg().set("max-packetcache-entries", "maximum number of entries to keep in the packetcache") = "500000";
+    ::arg().set("packetcache-servfail-ttl", "maximum number of seconds to keep a cached servfail entry in packetcache") = "60";
+    ::arg().set("server-id", "Returned when queried for 'id.server' TXT or NSID, defaults to hostname, set custom or 'disabled'") = "";
+    ::arg().set("stats-ringbuffer-entries", "maximum number of packets to store statistics for") = "10000";
+    ::arg().set("version-string", "string reported on version.pdns or version.bind") = fullVersionString();
+    ::arg().set("allow-from", "If set, only allow these comma separated netmasks to recurse") = LOCAL_NETS;
+    ::arg().set("allow-from-file", "If set, load allowed netmasks from this file") = "";
+    ::arg().set("allow-notify-for", "If set, NOTIFY requests for these zones will be allowed") = "";
+    ::arg().set("allow-notify-for-file", "If set, load NOTIFY-allowed zones from this file") = "";
+    ::arg().set("allow-notify-from", "If set, NOTIFY requests from these comma separated netmasks will be allowed") = "";
+    ::arg().set("allow-notify-from-file", "If set, load NOTIFY-allowed netmasks from this file") = "";
+    ::arg().set("entropy-source", "If set, read entropy from this file") = "/dev/urandom";
+    ::arg().set("dont-query", "If set, do not query these netmasks for DNS data") = DONT_QUERY;
+    ::arg().set("max-tcp-per-client", "If set, maximum number of TCP sessions per client (IP address)") = "0";
+    ::arg().set("max-tcp-queries-per-connection", "If set, maximum number of TCP queries in a TCP connection") = "0";
+    ::arg().set("spoof-nearmiss-max", "If non-zero, assume spoofing after this many near misses") = "1";
+    ::arg().set("single-socket", "If set, only use a single socket for outgoing queries") = "off";
+    ::arg().set("auth-zones", "Zones for which we have authoritative data, comma separated domain=file pairs ") = "";
+    ::arg().set("lua-config-file", "More powerful configuration options") = "";
+    ::arg().setSwitch("allow-trust-anchor-query", "Allow queries for trustanchor.server CH TXT and negativetrustanchor.server CH TXT") = "no";
+
+    ::arg().set("forward-zones", "Zones for which we forward queries, comma separated domain=ip pairs") = "";
+    ::arg().set("forward-zones-recurse", "Zones for which we forward queries with recursion bit, comma separated domain=ip pairs") = "";
+    ::arg().set("forward-zones-file", "File with (+)domain=ip pairs for forwarding") = "";
+    ::arg().set("export-etc-hosts", "If we should serve up contents from /etc/hosts") = "off";
+    ::arg().set("export-etc-hosts-search-suffix", "Also serve up the contents of /etc/hosts with this suffix") = "";
+    ::arg().set("etc-hosts-file", "Path to 'hosts' file") = "/etc/hosts";
+    ::arg().set("serve-rfc1918", "If we should be authoritative for RFC 1918 private IP space") = "yes";
+    ::arg().set("lua-dns-script", "Filename containing an optional 'lua' script that will be used to modify dns answers") = "";
+    ::arg().set("lua-maintenance-interval", "Number of seconds between calls to the lua user defined maintenance() function") = "1";
+    ::arg().set("latency-statistic-size", "Number of latency values to calculate the qa-latency average") = "10000";
+    ::arg().setSwitch("disable-packetcache", "Disable packetcache") = "no";
+    ::arg().set("ecs-ipv4-bits", "Number of bits of IPv4 address to pass for EDNS Client Subnet") = "24";
+    ::arg().set("ecs-ipv4-cache-bits", "Maximum number of bits of IPv4 mask to cache ECS response") = "24";
+    ::arg().set("ecs-ipv6-bits", "Number of bits of IPv6 address to pass for EDNS Client Subnet") = "56";
+    ::arg().set("ecs-ipv6-cache-bits", "Maximum number of bits of IPv6 mask to cache ECS response") = "56";
+    ::arg().setSwitch("ecs-ipv4-never-cache", "If we should never cache IPv4 ECS responses") = "no";
+    ::arg().setSwitch("ecs-ipv6-never-cache", "If we should never cache IPv6 ECS responses") = "no";
+    ::arg().set("ecs-minimum-ttl-override", "The minimum TTL for records in ECS-specific answers") = "1";
+    ::arg().set("ecs-cache-limit-ttl", "Minimum TTL to cache ECS response") = "0";
+    ::arg().set("edns-subnet-whitelist", "List of netmasks and domains that we should enable EDNS subnet for (deprecated)") = "";
+    ::arg().set("edns-subnet-allow-list", "List of netmasks and domains that we should enable EDNS subnet for") = "";
+    ::arg().set("ecs-add-for", "List of client netmasks for which EDNS Client Subnet will be added") = "0.0.0.0/0, ::/0, " LOCAL_NETS_INVERSE;
+    ::arg().set("ecs-scope-zero-address", "Address to send to allow-listed authoritative servers for incoming queries with ECS prefix-length source of 0") = "";
+    ::arg().setSwitch("use-incoming-edns-subnet", "Pass along received EDNS Client Subnet information") = "no";
+    ::arg().setSwitch("pdns-distributes-queries", "If PowerDNS itself should distribute queries over threads") = "yes";
+    ::arg().setSwitch("root-nx-trust", "If set, believe that an NXDOMAIN from the root means the TLD does not exist") = "yes";
+    ::arg().setSwitch("any-to-tcp", "Answer ANY queries with tc=1, shunting to TCP") = "no";
+    ::arg().setSwitch("lowercase-outgoing", "Force outgoing questions to lowercase") = "no";
+    ::arg().setSwitch("gettag-needs-edns-options", "If EDNS Options should be extracted before calling the gettag() hook") = "no";
+    ::arg().set("udp-truncation-threshold", "Maximum UDP response size before we truncate") = "1232";
+    ::arg().set("edns-outgoing-bufsize", "Outgoing EDNS buffer size") = "1232";
+    ::arg().set("minimum-ttl-override", "The minimum TTL") = "1";
+    ::arg().set("max-qperq", "Maximum outgoing queries per query") = "60";
+    ::arg().set("max-ns-address-qperq", "Maximum outgoing NS address queries per query") = "10";
+    ::arg().set("max-total-msec", "Maximum total wall-clock time per query in milliseconds, 0 for unlimited") = "7000";
+    ::arg().set("max-recursion-depth", "Maximum number of internal recursion calls per query, 0 for unlimited") = "40";
+    ::arg().set("max-udp-queries-per-round", "Maximum number of UDP queries processed per recvmsg() round, before returning back to normal processing") = "10000";
+    ::arg().set("protobuf-use-kernel-timestamp", "Compute the latency of queries in protobuf messages by using the timestamp set by the kernel when the query was received (when available)") = "";
+    ::arg().set("distribution-pipe-buffer-size", "Size in bytes of the internal buffer of the pipe used by the distributor to pass incoming queries to a worker thread") = "0";
+
+    ::arg().set("include-dir", "Include *.conf files from this directory") = "";
+    ::arg().set("security-poll-suffix", "Domain name from which to query security update notifications") = "secpoll.powerdns.com.";
+
+    ::arg().setSwitch("reuseport", "Enable SO_REUSEPORT allowing multiple recursors processes to listen to 1 address") = "no";
+
+    ::arg().setSwitch("snmp-agent", "If set, register as an SNMP agent") = "no";
+    ::arg().set("snmp-master-socket", "If set and snmp-agent is set, the socket to use to register to the SNMP daemon (deprecated)") = "";
+    ::arg().set("snmp-daemon-socket", "If set and snmp-agent is set, the socket to use to register to the SNMP daemon") = "";
 
     std::string defaultAPIDisabledStats = "cache-bytes, packetcache-bytes, special-memory-usage";
     for (size_t idx = 0; idx < 32; idx++) {
@@ -2310,75 +2300,75 @@ int main(int argc, char **argv)
     }
     std::string defaultDisabledStats = defaultAPIDisabledStats + ", cumul-clientanswers, cumul-authanswers, policy-hits";
 
-    ::arg().set("stats-api-blacklist", "List of statistics that are disabled when retrieving the complete list of statistics via the API (deprecated)")=defaultAPIDisabledStats;
-    ::arg().set("stats-carbon-blacklist", "List of statistics that are prevented from being exported via Carbon (deprecated)")=defaultDisabledStats;
-    ::arg().set("stats-rec-control-blacklist", "List of statistics that are prevented from being exported via rec_control get-all (deprecated)")=defaultDisabledStats;
-    ::arg().set("stats-snmp-blacklist", "List of statistics that are prevented from being exported via SNMP (deprecated)")=defaultDisabledStats;
+    ::arg().set("stats-api-blacklist", "List of statistics that are disabled when retrieving the complete list of statistics via the API (deprecated)") = defaultAPIDisabledStats;
+    ::arg().set("stats-carbon-blacklist", "List of statistics that are prevented from being exported via Carbon (deprecated)") = defaultDisabledStats;
+    ::arg().set("stats-rec-control-blacklist", "List of statistics that are prevented from being exported via rec_control get-all (deprecated)") = defaultDisabledStats;
+    ::arg().set("stats-snmp-blacklist", "List of statistics that are prevented from being exported via SNMP (deprecated)") = defaultDisabledStats;
 
-    ::arg().set("stats-api-disabled-list", "List of statistics that are disabled when retrieving the complete list of statistics via the API")=defaultAPIDisabledStats;
-    ::arg().set("stats-carbon-disabled-list", "List of statistics that are prevented from being exported via Carbon")=defaultDisabledStats;
-    ::arg().set("stats-rec-control-disabled-list", "List of statistics that are prevented from being exported via rec_control get-all")=defaultDisabledStats;
-    ::arg().set("stats-snmp-disabled-list", "List of statistics that are prevented from being exported via SNMP")=defaultDisabledStats;
+    ::arg().set("stats-api-disabled-list", "List of statistics that are disabled when retrieving the complete list of statistics via the API") = defaultAPIDisabledStats;
+    ::arg().set("stats-carbon-disabled-list", "List of statistics that are prevented from being exported via Carbon") = defaultDisabledStats;
+    ::arg().set("stats-rec-control-disabled-list", "List of statistics that are prevented from being exported via rec_control get-all") = defaultDisabledStats;
+    ::arg().set("stats-snmp-disabled-list", "List of statistics that are prevented from being exported via SNMP") = defaultDisabledStats;
 
-    ::arg().set("tcp-fast-open", "Enable TCP Fast Open support on the listening sockets, using the supplied numerical value as the queue size")="0";
-    ::arg().set("tcp-fast-open-connect", "Enable TCP Fast Open support on outgoing sockets")="no";
-    ::arg().set("nsec3-max-iterations", "Maximum number of iterations allowed for an NSEC3 record")="150";
+    ::arg().set("tcp-fast-open", "Enable TCP Fast Open support on the listening sockets, using the supplied numerical value as the queue size") = "0";
+    ::arg().set("tcp-fast-open-connect", "Enable TCP Fast Open support on outgoing sockets") = "no";
+    ::arg().set("nsec3-max-iterations", "Maximum number of iterations allowed for an NSEC3 record") = "150";
 
-    ::arg().set("cpu-map", "Thread to CPU mapping, space separated thread-id=cpu1,cpu2..cpuN pairs")="";
+    ::arg().set("cpu-map", "Thread to CPU mapping, space separated thread-id=cpu1,cpu2..cpuN pairs") = "";
 
-    ::arg().setSwitch("log-rpz-changes", "Log additions and removals to RPZ zones at Info level")="no";
+    ::arg().setSwitch("log-rpz-changes", "Log additions and removals to RPZ zones at Info level") = "no";
 
-    ::arg().set("xpf-allow-from","XPF information is only processed from these subnets")="";
-    ::arg().set("xpf-rr-code","XPF option code to use")="0";
+    ::arg().set("xpf-allow-from", "XPF information is only processed from these subnets") = "";
+    ::arg().set("xpf-rr-code", "XPF option code to use") = "0";
 
-    ::arg().set("proxy-protocol-from", "A Proxy Protocol header is only allowed from these subnets")="";
-    ::arg().set("proxy-protocol-maximum-size", "The maximum size of a proxy protocol payload, including the TLV values")="512";
+    ::arg().set("proxy-protocol-from", "A Proxy Protocol header is only allowed from these subnets") = "";
+    ::arg().set("proxy-protocol-maximum-size", "The maximum size of a proxy protocol payload, including the TLV values") = "512";
 
-    ::arg().set("dns64-prefix", "DNS64 prefix")="";
+    ::arg().set("dns64-prefix", "DNS64 prefix") = "";
 
-    ::arg().set("udp-source-port-min", "Minimum UDP port to bind on")="1024";
-    ::arg().set("udp-source-port-max", "Maximum UDP port to bind on")="65535";
-    ::arg().set("udp-source-port-avoid", "List of comma separated UDP port number to avoid")="11211";
-    ::arg().set("rng", "Specify random number generator to use. Valid values are auto,sodium,openssl,getrandom,arc4random,urandom.")="auto";
-    ::arg().set("public-suffix-list-file", "Path to the Public Suffix List file, if any")="";
-    ::arg().set("distribution-load-factor", "The load factor used when PowerDNS is distributing queries to worker threads")="0.0";
+    ::arg().set("udp-source-port-min", "Minimum UDP port to bind on") = "1024";
+    ::arg().set("udp-source-port-max", "Maximum UDP port to bind on") = "65535";
+    ::arg().set("udp-source-port-avoid", "List of comma separated UDP port number to avoid") = "11211";
+    ::arg().set("rng", "Specify random number generator to use. Valid values are auto,sodium,openssl,getrandom,arc4random,urandom.") = "auto";
+    ::arg().set("public-suffix-list-file", "Path to the Public Suffix List file, if any") = "";
+    ::arg().set("distribution-load-factor", "The load factor used when PowerDNS is distributing queries to worker threads") = "0.0";
 
-    ::arg().setSwitch("qname-minimization", "Use Query Name Minimization")="yes";
-    ::arg().setSwitch("nothing-below-nxdomain", "When an NXDOMAIN exists in cache for a name with fewer labels than the qname, send NXDOMAIN without doing a lookup (see RFC 8020)")="dnssec";
-    ::arg().set("max-generate-steps", "Maximum number of $GENERATE steps when loading a zone from a file")="0";
-    ::arg().set("max-include-depth", "Maximum nested $INCLUDE depth when loading a zone from a file")="20";
-    ::arg().set("record-cache-shards", "Number of shards in the record cache")="1024";
+    ::arg().setSwitch("qname-minimization", "Use Query Name Minimization") = "yes";
+    ::arg().setSwitch("nothing-below-nxdomain", "When an NXDOMAIN exists in cache for a name with fewer labels than the qname, send NXDOMAIN without doing a lookup (see RFC 8020)") = "dnssec";
+    ::arg().set("max-generate-steps", "Maximum number of $GENERATE steps when loading a zone from a file") = "0";
+    ::arg().set("max-include-depth", "Maximum nested $INCLUDE depth when loading a zone from a file") = "20";
+    ::arg().set("record-cache-shards", "Number of shards in the record cache") = "1024";
     ::arg().set("refresh-on-ttl-perc", "If a record is requested from the cache and only this % of original TTL remains, refetch") = "0";
 
-    ::arg().set("x-dnssec-names", "Collect DNSSEC statistics for names or suffixes in this list in separate x-dnssec counters")="";
+    ::arg().set("x-dnssec-names", "Collect DNSSEC statistics for names or suffixes in this list in separate x-dnssec counters") = "";
 
 #ifdef NOD_ENABLED
-    ::arg().set("new-domain-tracking", "Track newly observed domains (i.e. never seen before).")="no";
-    ::arg().set("new-domain-log", "Log newly observed domains.")="yes";
-    ::arg().set("new-domain-lookup", "Perform a DNS lookup newly observed domains as a subdomain of the configured domain")="";
-    ::arg().set("new-domain-history-dir", "Persist new domain tracking data here to persist between restarts")=string(NODCACHEDIR)+"/nod";
-    ::arg().set("new-domain-whitelist", "List of domains (and implicitly all subdomains) which will never be considered a new domain (deprecated)")="";
-    ::arg().set("new-domain-ignore-list", "List of domains (and implicitly all subdomains) which will never be considered a new domain")="";
-    ::arg().set("new-domain-db-size", "Size of the DB used to track new domains in terms of number of cells. Defaults to 67108864")="67108864";
-    ::arg().set("new-domain-pb-tag", "If protobuf is configured, the tag to use for messages containing newly observed domains. Defaults to 'pdns-nod'")="pdns-nod";
-    ::arg().set("unique-response-tracking", "Track unique responses (tuple of query name, type and RR).")="no";
-    ::arg().set("unique-response-log", "Log unique responses")="yes";
-    ::arg().set("unique-response-history-dir", "Persist unique response tracking data here to persist between restarts")=string(NODCACHEDIR)+"/udr";
-    ::arg().set("unique-response-db-size", "Size of the DB used to track unique responses in terms of number of cells. Defaults to 67108864")="67108864";
-    ::arg().set("unique-response-pb-tag", "If protobuf is configured, the tag to use for messages containing unique DNS responses. Defaults to 'pdns-udr'")="pdns-udr";
+    ::arg().set("new-domain-tracking", "Track newly observed domains (i.e. never seen before).") = "no";
+    ::arg().set("new-domain-log", "Log newly observed domains.") = "yes";
+    ::arg().set("new-domain-lookup", "Perform a DNS lookup newly observed domains as a subdomain of the configured domain") = "";
+    ::arg().set("new-domain-history-dir", "Persist new domain tracking data here to persist between restarts") = string(NODCACHEDIR) + "/nod";
+    ::arg().set("new-domain-whitelist", "List of domains (and implicitly all subdomains) which will never be considered a new domain (deprecated)") = "";
+    ::arg().set("new-domain-ignore-list", "List of domains (and implicitly all subdomains) which will never be considered a new domain") = "";
+    ::arg().set("new-domain-db-size", "Size of the DB used to track new domains in terms of number of cells. Defaults to 67108864") = "67108864";
+    ::arg().set("new-domain-pb-tag", "If protobuf is configured, the tag to use for messages containing newly observed domains. Defaults to 'pdns-nod'") = "pdns-nod";
+    ::arg().set("unique-response-tracking", "Track unique responses (tuple of query name, type and RR).") = "no";
+    ::arg().set("unique-response-log", "Log unique responses") = "yes";
+    ::arg().set("unique-response-history-dir", "Persist unique response tracking data here to persist between restarts") = string(NODCACHEDIR) + "/udr";
+    ::arg().set("unique-response-db-size", "Size of the DB used to track unique responses in terms of number of cells. Defaults to 67108864") = "67108864";
+    ::arg().set("unique-response-pb-tag", "If protobuf is configured, the tag to use for messages containing unique DNS responses. Defaults to 'pdns-udr'") = "pdns-udr";
 #endif /* NOD_ENABLED */
 
-    ::arg().setSwitch("extended-resolution-errors", "If set, send an EDNS Extended Error extension on resolution failures, like DNSSEC validation errors")="no";
+    ::arg().setSwitch("extended-resolution-errors", "If set, send an EDNS Extended Error extension on resolution failures, like DNSSEC validation errors") = "no";
 
-    ::arg().set("aggressive-nsec-cache-size", "The number of records to cache in the aggressive cache. If set to a value greater than 0, and DNSSEC processing or validation is enabled, the recursor will cache NSEC and NSEC3 records to generate negative answers, as defined in rfc8198")="100000";
+    ::arg().set("aggressive-nsec-cache-size", "The number of records to cache in the aggressive cache. If set to a value greater than 0, and DNSSEC processing or validation is enabled, the recursor will cache NSEC and NSEC3 records to generate negative answers, as defined in rfc8198") = "100000";
 
-    ::arg().set("edns-padding-from", "List of netmasks (proxy IP in case of XPF or proxy-protocol presence, client IP otherwise) for which EDNS padding will be enabled in responses, provided that 'edns-padding-mode' applies")="";
-    ::arg().set("edns-padding-mode", "Whether to add EDNS padding to all responses ('always') or only to responses for queries containing the EDNS padding option ('padded-queries-only', the default). In both modes, padding will only be added to responses for queries coming from `edns-padding-from`_ sources")="padded-queries-only";
-    ::arg().set("edns-padding-tag", "Packetcache tag associated to responses sent with EDNS padding, to prevent sending these to clients for which padding is not enabled.")="7830";
+    ::arg().set("edns-padding-from", "List of netmasks (proxy IP in case of XPF or proxy-protocol presence, client IP otherwise) for which EDNS padding will be enabled in responses, provided that 'edns-padding-mode' applies") = "";
+    ::arg().set("edns-padding-mode", "Whether to add EDNS padding to all responses ('always') or only to responses for queries containing the EDNS padding option ('padded-queries-only', the default). In both modes, padding will only be added to responses for queries coming from `edns-padding-from`_ sources") = "padded-queries-only";
+    ::arg().set("edns-padding-tag", "Packetcache tag associated to responses sent with EDNS padding, to prevent sending these to clients for which padding is not enabled.") = "7830";
 
-    ::arg().setSwitch("dot-to-port-853", "Force DoT connection to target port 853 if DoT compiled in")="yes";
-    ::arg().set("dot-to-auth-names", "Use DoT to authoritative servers with these names or suffixes")="";
-    ::arg().set("event-trace-enabled", "If set, event traces are collected and send out via protobuf logging (1), logfile (2) or both(3)")="0";
+    ::arg().setSwitch("dot-to-port-853", "Force DoT connection to target port 853 if DoT compiled in") = "yes";
+    ::arg().set("dot-to-auth-names", "Use DoT to authoritative servers with these names or suffixes") = "";
+    ::arg().set("event-trace-enabled", "If set, event traces are collected and send out via protobuf logging (1), logfile (2) or both(3)") = "0";
 
     ::arg().set("tcp-out-max-idle-ms", "Time TCP/DoT connections are left idle in milliseconds or 0 if no limit") = "10000";
     ::arg().set("tcp-out-max-idle-per-auth", "Maximum number of idle TCP/DoT connections to a specific IP per thread, 0 means do not keep idle connections open") = "10";
@@ -2386,61 +2376,61 @@ int main(int argc, char **argv)
     ::arg().set("tcp-out-max-idle-per-thread", "Maximum number of idle TCP/DoT connections per thread") = "100";
     ::arg().setSwitch("structured-logging", "Prefer structured logging") = "yes";
 
-    ::arg().setCmd("help","Provide a helpful message");
-    ::arg().setCmd("version","Print version string");
-    ::arg().setCmd("config","Output blank configuration");
+    ::arg().setCmd("help", "Provide a helpful message");
+    ::arg().setCmd("version", "Print version string");
+    ::arg().setCmd("config", "Output blank configuration");
     ::arg().setDefaults();
     g_log.toConsole(Logger::Info);
-    ::arg().laxParse(argc,argv); // do a lax parse
+    ::arg().laxParse(argc, argv); // do a lax parse
 
-    if(::arg().mustDo("version")) {
+    if (::arg().mustDo("version")) {
       showProductVersion();
       showBuildConfiguration();
       exit(0);
     }
 
-    string configname=::arg()["config-dir"]+"/recursor.conf";
-    if(::arg()["config-name"]!="") {
-      configname=::arg()["config-dir"]+"/recursor-"+::arg()["config-name"]+".conf";
-      s_programname+="-"+::arg()["config-name"];
+    string configname = ::arg()["config-dir"] + "/recursor.conf";
+    if (::arg()["config-name"] != "") {
+      configname = ::arg()["config-dir"] + "/recursor-" + ::arg()["config-name"] + ".conf";
+      s_programname += "-" + ::arg()["config-name"];
     }
     cleanSlashes(configname);
 
-    if(!::arg().getCommands().empty()) {
-      cerr<<"Fatal: non-option";
+    if (!::arg().getCommands().empty()) {
+      cerr << "Fatal: non-option";
       if (::arg().getCommands().size() > 1) {
-        cerr<<"s";
+        cerr << "s";
       }
-      cerr<<" (";
+      cerr << " (";
       bool first = true;
       for (const auto& c : ::arg().getCommands()) {
         if (!first) {
-          cerr<<", ";
+          cerr << ", ";
         }
         first = false;
-        cerr<<c;
+        cerr << c;
       }
-      cerr<<") on the command line, perhaps a '--setting=123' statement missed the '='?"<<endl;
+      cerr << ") on the command line, perhaps a '--setting=123' statement missed the '='?" << endl;
       exit(99);
     }
 
-    if(::arg().mustDo("config")) {
-      cout<<::arg().configstring(false, true);
+    if (::arg().mustDo("config")) {
+      cout << ::arg().configstring(false, true);
       exit(0);
     }
 
     g_slog = Logging::Logger::create(loggerBackend);
     auto startupLog = g_slog->withName("startup");
 
-    if(!::arg().file(configname.c_str())) {
-      SLOG(g_log<<Logger::Warning<<"Unable to parse configuration file '"<<configname<<"'"<<endl,
+    if (!::arg().file(configname.c_str())) {
+      SLOG(g_log << Logger::Warning << "Unable to parse configuration file '" << configname << "'" << endl,
            startupLog->error("No such file", "Unable to parse configuration file", "config_file", Logging::Loggable(configname)));
     }
 
-    ::arg().parse(argc,argv);
+    ::arg().parse(argc, argv);
 
-    if( !::arg()["chroot"].empty() && !::arg()["api-config-dir"].empty() ) {
-      SLOG(g_log<<Logger::Error<<"Using chroot and enabling the API is not possible"<<endl,
+    if (!::arg()["chroot"].empty() && !::arg()["api-config-dir"].empty()) {
+      SLOG(g_log << Logger::Error << "Using chroot and enabling the API is not possible" << endl,
            startupLog->info("Cannot use chroot and enable the API at the same time"));
       exit(EXIT_FAILURE);
     }
@@ -2452,70 +2442,69 @@ int main(int argc, char **argv)
         ::arg().set("socket-dir") = "/";
     }
 
-    if(::arg().asNum("threads")==1) {
+    if (::arg().asNum("threads") == 1) {
       if (::arg().mustDo("pdns-distributes-queries")) {
-        SLOG(g_log<<Logger::Warning<<"Asked to run with pdns-distributes-queries set but no distributor threads, raising to 1"<<endl,
+        SLOG(g_log << Logger::Warning << "Asked to run with pdns-distributes-queries set but no distributor threads, raising to 1" << endl,
              startupLog->v(1)->info("Only one thread, no need to distribute queries ourselves"));
-        ::arg().set("pdns-distributes-queries")="no";
+        ::arg().set("pdns-distributes-queries") = "no";
       }
     }
 
-    if(::arg().mustDo("pdns-distributes-queries") && ::arg().asNum("distributor-threads") <= 0) {
-      SLOG(g_log<<Logger::Warning<<"Asked to run with pdns-distributes-queries set but no distributor threads, raising to 1"<<endl,
+    if (::arg().mustDo("pdns-distributes-queries") && ::arg().asNum("distributor-threads") <= 0) {
+      SLOG(g_log << Logger::Warning << "Asked to run with pdns-distributes-queries set but no distributor threads, raising to 1" << endl,
            startupLog->v(1)->info("Asked to run with pdns-distributes-queries set but no distributor threads, raising to 1"));
-      ::arg().set("distributor-threads")="1";
+      ::arg().set("distributor-threads") = "1";
     }
 
     if (!::arg().mustDo("pdns-distributes-queries")) {
-      ::arg().set("distributor-threads")="0";
+      ::arg().set("distributor-threads") = "0";
     }
 
-    if(::arg().mustDo("help")) {
-      cout<<"syntax:"<<endl<<endl;
-      cout<<::arg().helpstring(::arg()["help"])<<endl;
+    if (::arg().mustDo("help")) {
+      cout << "syntax:" << endl
+           << endl;
+      cout << ::arg().helpstring(::arg()["help"]) << endl;
       exit(0);
     }
     g_recCache = std::make_unique<MemRecursorCache>(::arg().asNum("record-cache-shards"));
     g_negCache = std::make_unique<NegCache>(::arg().asNum("record-cache-shards"));
 
-    g_quiet=::arg().mustDo("quiet");
+    g_quiet = ::arg().mustDo("quiet");
     Logger::Urgency logUrgency = (Logger::Urgency)::arg().asNum("loglevel");
 
     if (logUrgency < Logger::Error)
       logUrgency = Logger::Error;
-    if(!g_quiet && logUrgency < Logger::Info) { // Logger::Info=6, Logger::Debug=7
-      logUrgency = Logger::Info;                // if you do --quiet=no, you need Info to also see the query log
+    if (!g_quiet && logUrgency < Logger::Info) { // Logger::Info=6, Logger::Debug=7
+      logUrgency = Logger::Info; // if you do --quiet=no, you need Info to also see the query log
     }
     g_log.setLoglevel(logUrgency);
     g_log.toConsole(logUrgency);
 
     ret = serviceMain(argc, argv);
   }
-  catch(PDNSException &ae) {
-    g_log<<Logger::Error<<"Exception: "<<ae.reason<<endl;
-    ret=EXIT_FAILURE;
+  catch (PDNSException& ae) {
+    g_log << Logger::Error << "Exception: " << ae.reason << endl;
+    ret = EXIT_FAILURE;
   }
-  catch(std::exception &e) {
-    g_log<<Logger::Error<<"STL Exception: "<<e.what()<<endl;
-    ret=EXIT_FAILURE;
+  catch (std::exception& e) {
+    g_log << Logger::Error << "STL Exception: " << e.what() << endl;
+    ret = EXIT_FAILURE;
   }
-  catch(...) {
-    g_log<<Logger::Error<<"any other exception in main: "<<endl;
-    ret=EXIT_FAILURE;
+  catch (...) {
+    g_log << Logger::Error << "any other exception in main: " << endl;
+    ret = EXIT_FAILURE;
   }
 
   return ret;
 }
 
-
-
 static RecursorControlChannel::Answer* doReloadLuaScript()
 {
-  string fname= ::arg()["lua-dns-script"];
+  string fname = ::arg()["lua-dns-script"];
   try {
-    if(fname.empty()) {
+    if (fname.empty()) {
       t_pdl.reset();
-      g_log<<Logger::Info<<t_id<<" Unloaded current lua script"<<endl;
+      g_log << Logger::Info << t_id << " Unloaded current lua script" << endl;
       return new RecursorControlChannel::Answer{0, string("unloaded\n")};
     }
     else {
@@ -2523,32 +2512,31 @@ static RecursorControlChannel::Answer* doReloadLuaScript()
       int err = t_pdl->loadFile(fname);
       if (err != 0) {
         string msg = std::to_string(t_id) + " Retaining current script, could not read '" + fname + "': " + stringerror(err);
-        g_log<<Logger::Error<<msg<<endl;
+        g_log << Logger::Error << msg << endl;
         return new RecursorControlChannel::Answer{1, msg + "\n"};
       }
     }
   }
-  catch(std::exception& e) {
-    g_log<<Logger::Error<<t_id<<" Retaining current script, error from '"<<fname<<"': "<< e.what() <<endl;
-    return new RecursorControlChannel::Answer{1, string("retaining current script, error from '"+fname+"': "+e.what()+"\n")};
+  catch (std::exception& e) {
+    g_log << Logger::Error << t_id << " Retaining current script, error from '" << fname << "': " << e.what() << endl;
+    return new RecursorControlChannel::Answer{1, string("retaining current script, error from '" + fname + "': " + e.what() + "\n")};
   }
 
-  g_log<<Logger::Warning<<t_id<<" (Re)loaded lua script from '"<<fname<<"'"<<endl;
-  return new RecursorControlChannel::Answer{0, string("(re)loaded '"+fname+"'\n")};
+  g_log << Logger::Warning << t_id << " (Re)loaded lua script from '" << fname << "'" << endl;
+  return new RecursorControlChannel::Answer{0, string("(re)loaded '" + fname + "'\n")};
 }
 
 RecursorControlChannel::Answer doQueueReloadLuaScript(vector<string>::const_iterator begin, vector<string>::const_iterator end)
 {
-  if(begin != end)
+  if (begin != end)
     ::arg().set("lua-dns-script") = *begin;
 
   return broadcastAccFunction<RecursorControlChannel::Answer>(doReloadLuaScript);
 }
 
 static string* pleaseUseNewTraceRegex(const std::string& newRegex)
-try
-{
-  if(newRegex.empty()) {
+try {
+  if (newRegex.empty()) {
     t_traceRegex.reset();
     return new string("unset\n");
   }
@@ -2557,17 +2545,15 @@ try
     return new string("ok\n");
   }
 }
-catch(PDNSException& ae)
-{
-  return new string(ae.reason+"\n");
+catch (PDNSException& ae) {
+  return new string(ae.reason + "\n");
 }
 
 string doTraceRegex(vector<string>::const_iterator begin, vector<string>::const_iterator end)
 {
-  return broadcastAccFunction<string>([=]{ return pleaseUseNewTraceRegex(begin!=end ? *begin : ""); });
+  return broadcastAccFunction<string>([=] { return pleaseUseNewTraceRegex(begin != end ? *begin : ""); });
 }
 
-
 static uint64_t* pleaseWipePacketCache(const DNSName& canon, bool subtree, uint16_t qtype)
 {
   return new uint64_t(t_packetCache->doWipePacketCache(canon, qtype, subtree));
@@ -2579,14 +2565,14 @@ struct WipeCacheResult wipeCaches(const DNSName& canon, bool subtree, uint16_t q
 
   try {
     res.record_count = g_recCache->doWipeCache(canon, subtree, qtype);
-    res.packet_count = broadcastAccFunction<uint64_t>([=]{ return pleaseWipePacketCache(canon, subtree, qtype);});
+    res.packet_count = broadcastAccFunction<uint64_t>([=] { return pleaseWipePacketCache(canon, subtree, qtype); });
     res.negative_record_count = g_negCache->wipe(canon, subtree);
     if (g_aggressiveNSECCache) {
       g_aggressiveNSECCache->removeZoneInfo(canon, subtree);
     }
   }
   catch (const std::exception& e) {
-    g_log<<Logger::Warning<<", failed: "<<e.what()<<endl;
+    g_log << Logger::Warning << ", failed: " << e.what() << endl;
   }
 
   return res;
index f67da5daed48a0cca22666187c188e84220b51e8..2e86539d2b3e19aa53ccbada2caaa2fd85579e6a 100644 (file)
 #include <boost/container/flat_set.hpp>
 #endif
 
-
 //! used to send information to a newborn mthread
-struct DNSComboWriter {
-  DNSComboWriter(const std::string& query, const struct timeval& now): d_mdp(true, query), d_now(now), d_query(query)
+struct DNSComboWriter
+{
+  DNSComboWriter(const std::string& query, const struct timeval& now) :
+    d_mdp(true, query), d_now(now), d_query(query)
   {
   }
 
-  DNSComboWriter(const std::string& query, const struct timeval& now, std::unordered_set<std::string>&& policyTags, LuaContext::LuaObject&& data, std::vector<DNSRecord>&& records): d_mdp(true, query), d_now(now), d_query(query), d_policyTags(std::move(policyTags)), d_records(std::move(records)), d_data(std::move(data))
+  DNSComboWriter(const std::string& query, const struct timeval& now, std::unordered_set<std::string>&& policyTags, LuaContext::LuaObject&& data, std::vector<DNSRecord>&& records) :
+    d_mdp(true, query), d_now(now), d_query(query), d_policyTags(std::move(policyTags)), d_records(std::move(records)), d_data(std::move(data))
   {
   }
 
   void setRemote(const ComboAddress& sa)
   {
-    d_remote=sa;
+    d_remote = sa;
   }
 
   void setSource(const ComboAddress& sa)
   {
-    d_source=sa;
+    d_source = sa;
   }
 
   void setLocal(const ComboAddress& sa)
   {
-    d_local=sa;
+    d_local = sa;
   }
 
   void setDestination(const ComboAddress& sa)
   {
-    d_destination=sa;
+    d_destination = sa;
   }
 
   void setSocket(int sock)
   {
-    d_socket=sock;
+    d_socket = sock;
   }
 
   string getRemote() const
@@ -107,7 +109,10 @@ struct DNSComboWriter {
   string d_requestorId;
   string d_deviceId;
   string d_deviceName;
-  struct timeval d_kernelTimestamp{0,0};
+  struct timeval d_kernelTimestamp
+  {
+    0, 0
+  };
   std::string d_query;
   std::unordered_set<std::string> d_policyTags;
   std::string d_routingTag;
@@ -142,8 +147,10 @@ extern uint16_t s_maxUdpSourcePort;
 class UDPClientSocks
 {
   unsigned int d_numsocks;
+
 public:
-  UDPClientSocks() : d_numsocks(0)
+  UDPClientSocks() :
+    d_numsocks(0)
   {
   }
 
@@ -151,13 +158,17 @@ public:
 
   // return a socket to the pool, or simply erase it
   void returnSocket(int fd);
+
 private:
-  
   // returns -1 for errors which might go away, throws for ones that won't
   static int makeClientSocket(int family);
 };
 
-enum class PaddingMode { Always, PaddedQueries };
+enum class PaddingMode
+{
+  Always,
+  PaddedQueries
+};
 
 typedef MTasker<std::shared_ptr<PacketID>, PacketBuffer, PacketIDCompare> MT_t;
 extern thread_local std::unique_ptr<MT_t> MT; // the big MTasker
@@ -232,13 +243,12 @@ extern std::set<uint16_t> s_avoidUdpSourcePorts;
 #endif
 
 /* without reuseport, all listeners share the same sockets */
-typedef vector<pair<int, boost::function< void(int, boost::any&) > > > deferredAdd_t;
+typedef vector<pair<int, boost::function<void(int, boost::any&)>>> deferredAdd_t;
 extern deferredAdd_t g_deferredAdds;
 
 typedef map<ComboAddress, uint32_t, ComboAddress::addressOnlyLessThan> tcpClientCounts_t;
 extern thread_local std::unique_ptr<tcpClientCounts_t> t_tcpClientCounts;
 
-
 inline MT_t* getMT()
 {
   return MT ? MT.get() : nullptr;
@@ -260,20 +270,25 @@ static bool sendResponseOverTCP(const std::unique_ptr<DNSComboWriter>& dc, const
   buf[1] = packet.size() % 256;
 
   Utility::iovec iov[2];
-  iov[0].iov_base = (void*)buf;              iov[0].iov_len = 2;
-  iov[1].iov_base = (void*)&*packet.begin(); iov[1].iov_len = packet.size();
+  iov[0].iov_base = (void*)buf;
+  iov[0].iov_len = 2;
+  iov[1].iov_base = (void*)&*packet.begin();
+  iov[1].iov_len = packet.size();
 
   int wret = Utility::writev(dc->d_socket, iov, 2);
   bool hadError = true;
 
   if (wret == 0) {
-    g_log<<Logger::Warning<<"EOF writing TCP answer to "<<dc->getRemote()<<endl;
-  } else if (wret < 0 ) {
+    g_log << Logger::Warning << "EOF writing TCP answer to " << dc->getRemote() << endl;
+  }
+  else if (wret < 0) {
     int err = errno;
     g_log << Logger::Warning << "Error writing TCP answer to " << dc->getRemote() << ": " << strerror(err) << endl;
-  } else if ((unsigned int)wret != 2 + packet.size()) {
-    g_log<<Logger::Warning<<"Oops, partial answer sent to "<<dc->getRemote()<<" for "<<dc->d_mdp.d_qname<<" (size="<< (2 + packet.size()) <<", sent "<<wret<<")"<<endl;
-  } else {
+  }
+  else if ((unsigned int)wret != 2 + packet.size()) {
+    g_log << Logger::Warning << "Oops, partial answer sent to " << dc->getRemote() << " for " << dc->d_mdp.d_qname << " (size=" << (2 + packet.size()) << ", sent " << wret << ")" << endl;
+  }
+  else {
     hadError = false;
   }
 
@@ -356,26 +371,26 @@ void getQNameAndSubnet(const std::string& question, DNSName* dnsname, uint16_t*
 void protobufLogQuery(LocalStateHolder<LuaConfigItems>& luaconfsLocal, const boost::uuids::uuid& uniqueId, const ComboAddress& remote, const ComboAddress& local, const Netmask& ednssubnet, bool tcp, uint16_t id, size_t len, const DNSName& qname, uint16_t qtype, uint16_t qclass, const std::unordered_set<std::string>& policyTags, const std::string& requestorId, const std::string& deviceId, const std::string& deviceName, const std::map<std::string, RecursorLua4::MetaValue>& meta);
 bool isAllowNotifyForZone(DNSName qname);
 bool checkForCacheHit(bool qnameParsed, unsigned int tag, const string& data,
-                             DNSName& qname, uint16_t& qtype, uint16_t& qclass,
-                             const struct timeval& now,
-                             string& response, uint32_t& qhash,
+                      DNSName& qname, uint16_t& qtype, uint16_t& qclass,
+                      const struct timeval& now,
+                      string& response, uint32_t& qhash,
                       RecursorPacketCache::OptPBData& pbData, bool tcp, const ComboAddress& source);
 void protobufLogResponse(pdns::ProtoZero::RecMessage& message);
 void protobufLogResponse(const struct dnsheader* dh, LocalStateHolder<LuaConfigItems>& luaconfsLocal,
-                                const RecursorPacketCache::OptPBData& pbData, const struct timeval& tv,
-                                bool tcp, const ComboAddress& source, const ComboAddress& destination,
-                                const EDNSSubnetOpts& ednssubnet,
-                                const boost::uuids::uuid& uniqueId, const string& requestorId, const string& deviceId,
-                                const string& deviceName, const std::map<std::string, RecursorLua4::MetaValue>& meta,
+                         const RecursorPacketCache::OptPBData& pbData, const struct timeval& tv,
+                         bool tcp, const ComboAddress& source, const ComboAddress& destination,
+                         const EDNSSubnetOpts& ednssubnet,
+                         const boost::uuids::uuid& uniqueId, const string& requestorId, const string& deviceId,
+                         const string& deviceName, const std::map<std::string, RecursorLua4::MetaValue>& meta,
                          const RecEventTrace& eventTrace);
 void requestWipeCaches(const DNSName& canon);
-void startDoResolve(void *p);
+void startDoResolve(voidp);
 bool expectProxyProtocol(const ComboAddress& from);
 void finishTCPReply(std::unique_ptr<DNSComboWriter>& dc, bool hadError, bool updateInFlight);
 void checkFastOpenSysctl(bool active);
 void checkTFOconnect();
 void makeTCPServerSockets(deferredAdd_t& deferredAdds, std::set<int>& tcpSockets);
-void handleNewTCPQuestion(int fd, FDMultiplexer::funcparam_t& );
+void handleNewTCPQuestion(int fd, FDMultiplexer::funcparam_t&);
 
 void makeUDPServerSockets(deferredAdd_t& deferredAdds);
 void* recursorThread(unsigned int n, const string& threadName);
@@ -387,5 +402,5 @@ void* recursorThread(unsigned int n, const string& threadName);
 // and
 // http://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml
 // where such a network may not be considered a valid destination
-#define BAD_NETS   "0.0.0.0/8, 192.0.0.0/24, 192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 240.0.0.0/4, ::/96, ::ffff:0:0/96, 100::/64, 2001:db8::/32"
+#define BAD_NETS "0.0.0.0/8, 192.0.0.0/24, 192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 240.0.0.0/4, ::/96, ::ffff:0:0/96, 100::/64, 2001:db8::/32"
 #define DONT_QUERY LOCAL_NETS ", " BAD_NETS
index 86740f347f294a849544b2338c61855580a6e2ef..d369b9c15a6ddfa646b6f316252448081cea0955 100644 (file)
@@ -41,12 +41,16 @@ thread_local std::unique_ptr<tcpClientCounts_t> t_tcpClientCounts;
 static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var);
 
 #if 0
-#define TCPLOG(tcpsock, x) do { cerr << [](){ timeval t; gettimeofday(&t, nullptr); return t.tv_sec % 10  + t.tv_usec/1000000.0; }() << " FD " << (tcpsock) << ' ' << x; } while (0)
+#define TCPLOG(tcpsock, x)                                 \
+  do {                                                     \
+    cerr << []() { timeval t; gettimeofday(&t, nullptr); return t.tv_sec % 10  + t.tv_usec/1000000.0; }() << " FD " << (tcpsock) << ' ' << x; \
+  } while (0)
 #else
 #define TCPLOG(pid, x)
 #endif
 
-TCPConnection::TCPConnection(int fd, const ComboAddress& addr) : data(2, 0), d_remote(addr), d_fd(fd)
+TCPConnection::TCPConnection(int fd, const ComboAddress& addr) :
+  data(2, 0), d_remote(addr), d_fd(fd)
 {
   ++s_currentConnections;
   (*t_tcpClientCounts)[d_remote]++;
@@ -55,26 +59,24 @@ TCPConnection::TCPConnection(int fd, const ComboAddress& addr) : data(2, 0), d_r
 TCPConnection::~TCPConnection()
 {
   try {
-    if(closesocket(d_fd) < 0)
-      g_log<<Logger::Error<<"Error closing socket for TCPConnection"<<endl;
+    if (closesocket(d_fd) < 0)
+      g_log << Logger::Error << "Error closing socket for TCPConnection" << endl;
   }
-  catch(const PDNSException& e) {
-    g_log<<Logger::Error<<"Error closing TCPConnection socket: "<<e.reason<<endl;
+  catch (const PDNSException& e) {
+    g_log << Logger::Error << "Error closing TCPConnection socket: " << e.reason << endl;
   }
 
-  if(t_tcpClientCounts->count(d_remote) && !(*t_tcpClientCounts)[d_remote]--)
+  if (t_tcpClientCounts->count(d_remote) && !(*t_tcpClientCounts)[d_remote]--)
     t_tcpClientCounts->erase(d_remote);
   --s_currentConnections;
 }
 
-
 static void terminateTCPConnection(int fd)
 {
   try {
     t_fdm->removeReadFD(fd);
   }
-  catch (const FDMultiplexerException& fde)
-  {
+  catch (const FDMultiplexerException& fde) {
   }
 }
 
@@ -129,12 +131,11 @@ void finishTCPReply(std::unique_ptr<DNSComboWriter>& dc, bool hadError, bool upd
     return;
   }
   dc->d_tcpConnection->queriesCount++;
-  if ((g_tcpMaxQueriesPerConn && dc->d_tcpConnection->queriesCount >= g_tcpMaxQueriesPerConn) ||
-      (dc->d_tcpConnection->isDropOnIdle() && dc->d_tcpConnection->d_requestsInFlight == 0)) {
+  if ((g_tcpMaxQueriesPerConn && dc->d_tcpConnection->queriesCount >= g_tcpMaxQueriesPerConn) || (dc->d_tcpConnection->isDropOnIdle() && dc->d_tcpConnection->d_requestsInFlight == 0)) {
     try {
       t_fdm->removeReadFD(dc->d_socket);
     }
-    catch (FDMultiplexerException &) {
+    catch (FDMultiplexerException&) {
     }
     dc->d_socket = -1;
     return;
@@ -156,7 +157,7 @@ void finishTCPReply(std::unique_ptr<DNSComboWriter>& dc, bool hadError, bool upd
   try {
     t_fdm->setReadTTD(dc->d_socket, ttd, g_tcpTimeout);
   }
-  catch (const FDMultiplexerException &) {
+  catch (const FDMultiplexerException&) {
     // but if the FD was removed because of a timeout while we were sending a response,
     // we need to re-arm it. If it was an error it will error again.
     ttd.tv_sec += g_tcpTimeout;
@@ -168,7 +169,8 @@ void finishTCPReply(std::unique_ptr<DNSComboWriter>& dc, bool hadError, bool upd
  * A helper class that by default closes the incoming TCP connection on destruct
  * If you want to keep the connection alive, call keep() on the guard object
  */
-class RunningTCPQuestionGuard {
+class RunningTCPQuestionGuard
+{
 public:
   RunningTCPQuestionGuard(int fd)
   {
@@ -206,7 +208,7 @@ private:
 
 static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
 {
-  shared_ptr<TCPConnection> conn=boost::any_cast<shared_ptr<TCPConnection> >(var);
+  shared_ptr<TCPConnection> conn = boost::any_cast<shared_ptr<TCPConnection>>(var);
 
   RunningTCPQuestionGuard tcpGuard{fd};
 
@@ -222,7 +224,7 @@ static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
     ssize_t remaining = isProxyHeaderComplete(conn->data);
     if (remaining == 0) {
       if (g_logCommonErrors) {
-        g_log<<Logger::Error<<"Unable to consume proxy protocol header in packet from TCP client "<< conn->d_remote.toStringWithPort() <<endl;
+        g_log << Logger::Error << "Unable to consume proxy protocol header in packet from TCP client " << conn->d_remote.toStringWithPort() << endl;
       }
       ++g_stats.proxyProtocolInvalidCount;
       return;
@@ -242,14 +244,14 @@ static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
       size_t used = parseProxyHeader(conn->data, proxy, conn->d_source, conn->d_destination, tcp, conn->proxyProtocolValues);
       if (used <= 0) {
         if (g_logCommonErrors) {
-          g_log<<Logger::Error<<"Unable to parse proxy protocol header in packet from TCP client "<< conn->d_remote.toStringWithPort() <<endl;
+          g_log << Logger::Error << "Unable to parse proxy protocol header in packet from TCP client " << conn->d_remote.toStringWithPort() << endl;
         }
         ++g_stats.proxyProtocolInvalidCount;
         return;
       }
       else if (static_cast<size_t>(used) > g_proxyProtocolMaximumSize) {
         if (g_logCommonErrors) {
-          g_log<<Logger::Error<<"Proxy protocol header in packet from TCP client "<< conn->d_remote.toStringWithPort() << " is larger than proxy-protocol-maximum-size (" << used << "), dropping"<< endl;
+          g_log << Logger::Error << "Proxy protocol header in packet from TCP client " << conn->d_remote.toStringWithPort() << " is larger than proxy-protocol-maximum-size (" << used << "), dropping" << endl;
         }
         ++g_stats.proxyProtocolInvalidCount;
         return;
@@ -260,7 +262,7 @@ static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
       /* note that if the proxy header used a 'LOCAL' command, the original source and destination are untouched so everything should be fine */
       if (t_allowFrom && !t_allowFrom->match(&conn->d_source)) {
         if (!g_quiet) {
-          g_log<<Logger::Error<<"["<<MT->getTid()<<"] dropping TCP query from "<<conn->d_source.toString()<<", address not matched by allow-from"<<endl;
+          g_log << Logger::Error << "[" << MT->getTid() << "] dropping TCP query from " << conn->d_source.toString() << ", address not matched by allow-from" << endl;
         }
 
         ++g_stats.unauthorizedTCP;
@@ -272,15 +274,15 @@ static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
     }
   }
 
-  if (conn->state==TCPConnection::BYTE0) {
-    ssize_t bytes=recv(conn->getFD(), &conn->data[0], 2, 0);
-    if(bytes==1)
-      conn->state=TCPConnection::BYTE1;
-    if(bytes==2) {
-      conn->qlen=(((unsigned char)conn->data[0]) << 8)+ (unsigned char)conn->data[1];
+  if (conn->state == TCPConnection::BYTE0) {
+    ssize_t bytes = recv(conn->getFD(), &conn->data[0], 2, 0);
+    if (bytes == 1)
+      conn->state = TCPConnection::BYTE1;
+    if (bytes == 2) {
+      conn->qlen = (((unsigned char)conn->data[0]) << 8) + (unsigned char)conn->data[1];
       conn->data.resize(conn->qlen);
-      conn->bytesread=0;
-      conn->state=TCPConnection::GETQUESTION;
+      conn->bytesread = 0;
+      conn->state = TCPConnection::GETQUESTION;
     }
     if (bytes <= 0) {
       tcpGuard.handleTCPReadResult(fd, bytes);
@@ -288,57 +290,57 @@ static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
     }
   }
 
-  if (conn->state==TCPConnection::BYTE1) {
-    ssize_t bytes=recv(conn->getFD(), &conn->data[1], 1, 0);
-    if(bytes==1) {
-      conn->state=TCPConnection::GETQUESTION;
-      conn->qlen=(((unsigned char)conn->data[0]) << 8)+ (unsigned char)conn->data[1];
+  if (conn->state == TCPConnection::BYTE1) {
+    ssize_t bytes = recv(conn->getFD(), &conn->data[1], 1, 0);
+    if (bytes == 1) {
+      conn->state = TCPConnection::GETQUESTION;
+      conn->qlen = (((unsigned char)conn->data[0]) << 8) + (unsigned char)conn->data[1];
       conn->data.resize(conn->qlen);
-      conn->bytesread=0;
+      conn->bytesread = 0;
     }
     if (bytes <= 0) {
       if (!tcpGuard.handleTCPReadResult(fd, bytes)) {
-        if(g_logCommonErrors) {
-          g_log<<Logger::Error<<"TCP client "<< conn->d_remote.toStringWithPort() <<" disconnected after first byte"<<endl;
+        if (g_logCommonErrors) {
+          g_log << Logger::Error << "TCP client " << conn->d_remote.toStringWithPort() << " disconnected after first byte" << endl;
         }
       }
       return;
     }
   }
 
-  if(conn->state==TCPConnection::GETQUESTION) {
-    ssize_t bytes=recv(conn->getFD(), &conn->data[conn->bytesread], conn->qlen - conn->bytesread, 0);
+  if (conn->state == TCPConnection::GETQUESTION) {
+    ssize_t bytes = recv(conn->getFD(), &conn->data[conn->bytesread], conn->qlen - conn->bytesread, 0);
     if (bytes <= 0) {
       if (!tcpGuard.handleTCPReadResult(fd, bytes)) {
-        if(g_logCommonErrors) {
-          g_log<<Logger::Error<<"TCP client "<< conn->d_remote.toStringWithPort() <<" disconnected while reading question body"<<endl;
+        if (g_logCommonErrors) {
+          g_log << Logger::Error << "TCP client " << conn->d_remote.toStringWithPort() << " disconnected while reading question body" << endl;
         }
       }
       return;
     }
     else if (bytes > std::numeric_limits<std::uint16_t>::max()) {
-      if(g_logCommonErrors) {
-        g_log<<Logger::Error<<"TCP client "<< conn->d_remote.toStringWithPort() <<" sent an invalid question size while reading question body"<<endl;
+      if (g_logCommonErrors) {
+        g_log << Logger::Error << "TCP client " << conn->d_remote.toStringWithPort() << " sent an invalid question size while reading question body" << endl;
       }
       return;
     }
-    conn->bytesread+=(uint16_t)bytes;
-    if(conn->bytesread==conn->qlen) {
+    conn->bytesread += (uint16_t)bytes;
+    if (conn->bytesread == conn->qlen) {
       conn->state = TCPConnection::BYTE0;
       std::unique_ptr<DNSComboWriter> dc;
       try {
         dc = std::make_unique<DNSComboWriter>(conn->data, g_now);
       }
-      catch(const MOADNSException &mde) {
+      catch (const MOADNSException& mde) {
         g_stats.clientParseError++;
         if (g_logCommonErrors) {
-          g_log<<Logger::Error<<"Unable to parse packet from TCP client "<< conn->d_remote.toStringWithPort() <<endl;
+          g_log << Logger::Error << "Unable to parse packet from TCP client " << conn->d_remote.toStringWithPort() << endl;
         }
         return;
       }
       dc->d_tcpConnection = conn; // carry the torch
       dc->setSocket(conn->getFD()); // this is the only time a copy is made of the actual fd
-      dc->d_tcp=true;
+      dc->d_tcp = true;
       dc->setRemote(conn->d_remote);
       dc->setSource(conn->d_source);
       ComboAddress dest;
@@ -354,10 +356,10 @@ static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
 
       struct timeval start;
       Utility::gettimeofday(&start, nullptr);
+
       DNSName qname;
-      uint16_t qtype=0;
-      uint16_t qclass=0;
+      uint16_t qtype = 0;
+      uint16_t qclass = 0;
       bool needECS = false;
       bool needXPF = g_XPFAcl.match(conn->d_remote);
       string requestorId;
@@ -379,7 +381,7 @@ static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
       checkFrameStreamExport(luaconfsLocal);
 #endif
 
-      if(needECS || needXPF || (t_pdl && (t_pdl->d_gettag_ffi || t_pdl->d_gettag)) || dc->d_mdp.d_header.opcode == Opcode::Notify) {
+      if (needECS || needXPF || (t_pdl && (t_pdl->d_gettag_ffi || t_pdl->d_gettag)) || dc->d_mdp.d_header.opcode == Opcode::Notify) {
 
         try {
           EDNSOptionViewMap ednsOptions;
@@ -391,7 +393,7 @@ static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
                             xpfFound, needXPF ? &dc->d_source : nullptr, needXPF ? &dc->d_destination : nullptr);
           qnameParsed = true;
 
-          if(t_pdl) {
+          if (t_pdl) {
             try {
               if (t_pdl->d_gettag_ffi) {
                 RecursorLua4::FFIParams params(qname, qtype, dc->d_destination, dc->d_source, dc->d_ednssubnet.source, dc->d_data, dc->d_policyTags, dc->d_records, ednsOptions, dc->d_proxyProtocolValues, requestorId, deviceId, deviceName, dc->d_routingTag, dc->d_rcode, dc->d_ttlCap, dc->d_variable, true, logQuery, dc->d_logResponse, dc->d_followCNAMERecords, dc->d_extendedErrorCode, dc->d_extendedErrorExtra, dc->d_responsePaddingDisabled, dc->d_meta);
@@ -405,17 +407,16 @@ static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
                 dc->d_eventTrace.add(RecEventTrace::LuaGetTag, dc->d_tag, false);
               }
             }
-            catch(const std::exception& e)  {
-              if(g_logCommonErrors) {
-                g_log<<Logger::Warning<<"Error parsing a query packet qname='"<<qname<<"' for tag determination, setting tag=0: "<<e.what()<<endl;
+            catch (const std::exception& e) {
+              if (g_logCommonErrors) {
+                g_log << Logger::Warning << "Error parsing a query packet qname='" << qname << "' for tag determination, setting tag=0: " << e.what() << endl;
               }
             }
           }
         }
-        catch(const std::exception& e)
-        {
+        catch (const std::exception& e) {
           if (g_logCommonErrors) {
-            g_log<<Logger::Warning<<"Error parsing a query packet for tag determination, setting tag=0: "<<e.what()<<endl;
+            g_log << Logger::Warning << "Error parsing a query packet for tag determination, setting tag=0: " << e.what() << endl;
           }
         }
       }
@@ -433,7 +434,7 @@ static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
         dc->d_uuid = getUniqueID();
       }
 
-      if(t_protobufServers) {
+      if (t_protobufServers) {
         try {
 
           if (logQuery && !(luaconfsLocal->protobufExportConfig.taggedOnly && dc->d_policyTags.empty())) {
@@ -442,7 +443,7 @@ static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
         }
         catch (const std::exception& e) {
           if (g_logCommonErrors) {
-            g_log<<Logger::Warning<<"Error parsing a TCP query packet for edns subnet: "<<e.what()<<endl;
+            g_log << Logger::Warning << "Error parsing a TCP query packet for edns subnet: " << e.what() << endl;
           }
         }
       }
@@ -451,7 +452,7 @@ static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
         bool ipf = t_pdl->ipfilter(dc->d_source, dc->d_destination, *dh, dc->d_eventTrace);
         if (ipf) {
           if (!g_quiet) {
-            g_log<<Logger::Notice<<t_id<<" ["<<MT->getTid()<<"/"<<MT->numProcesses()<<"] DROPPED TCP question from "<<dc->d_source.toStringWithPort()<<(dc->d_source != dc->d_remote ? " (via "+dc->d_remote.toStringWithPort()+")" : "")<<" based on policy"<<endl;
+            g_log << Logger::Notice << t_id << " [" << MT->getTid() << "/" << MT->numProcesses() << "] DROPPED TCP question from " << dc->d_source.toStringWithPort() << (dc->d_source != dc->d_remote ? " (via " + dc->d_remote.toStringWithPort() + ")" : "") << " based on policy" << endl;
           }
           g_stats.policyDrops++;
           return;
@@ -461,14 +462,14 @@ static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
       if (dc->d_mdp.d_header.qr) {
         g_stats.ignoredCount++;
         if (g_logCommonErrors) {
-          g_log<<Logger::Error<<"Ignoring answer from TCP client "<< dc->getRemote() <<" on server socket!"<<endl;
+          g_log << Logger::Error << "Ignoring answer from TCP client " << dc->getRemote() << " on server socket!" << endl;
         }
         return;
       }
       if (dc->d_mdp.d_header.opcode != Opcode::Query && dc->d_mdp.d_header.opcode != Opcode::Notify) {
         g_stats.ignoredCount++;
         if (g_logCommonErrors) {
-          g_log<<Logger::Error<<"Ignoring unsupported opcode "<<Opcode::to_s(dc->d_mdp.d_header.opcode)<<" from TCP client "<< dc->getRemote() <<" on server socket!"<<endl;
+          g_log << Logger::Error << "Ignoring unsupported opcode " << Opcode::to_s(dc->d_mdp.d_header.opcode) << " from TCP client " << dc->getRemote() << " on server socket!" << endl;
         }
         sendErrorOverTCP(dc, RCode::NotImp);
         tcpGuard.keep();
@@ -477,7 +478,7 @@ static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
       else if (dh->qdcount == 0) {
         g_stats.emptyQueriesCount++;
         if (g_logCommonErrors) {
-          g_log<<Logger::Error<<"Ignoring empty (qdcount == 0) query from "<< dc->getRemote() <<" on server socket!"<<endl;
+          g_log << Logger::Error << "Ignoring empty (qdcount == 0) query from " << dc->getRemote() << " on server socket!" << endl;
         }
         sendErrorOverTCP(dc, RCode::NotImp);
         tcpGuard.keep();
@@ -488,19 +489,19 @@ static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
         ++g_stats.qcounter;
         ++g_stats.tcpqcounter;
 
-        if(dc->d_mdp.d_header.opcode == Opcode::Notify) {
-          if(!t_allowNotifyFrom || !t_allowNotifyFrom->match(dc->d_source)) {
-            if(!g_quiet) {
-              g_log<<Logger::Error<<"["<<MT->getTid()<<"] dropping TCP NOTIFY from "<<dc->d_source.toString()<<", address not matched by allow-notify-from"<<endl;
+        if (dc->d_mdp.d_header.opcode == Opcode::Notify) {
+          if (!t_allowNotifyFrom || !t_allowNotifyFrom->match(dc->d_source)) {
+            if (!g_quiet) {
+              g_log << Logger::Error << "[" << MT->getTid() << "] dropping TCP NOTIFY from " << dc->d_source.toString() << ", address not matched by allow-notify-from" << endl;
             }
 
             g_stats.sourceDisallowedNotify++;
             return;
           }
 
-          if(!isAllowNotifyForZone(qname)) {
-            if(!g_quiet) {
-              g_log<<Logger::Error<<"["<<MT->getTid()<<"] dropping TCP NOTIFY from "<<dc->d_source.toString()<<", for "<<qname.toLogString()<<", zone not matched by allow-notify-for"<<endl;
+          if (!isAllowNotifyForZone(qname)) {
+            if (!g_quiet) {
+              g_log << Logger::Error << "[" << MT->getTid() << "] dropping TCP NOTIFY from " << dc->d_source.toString() << ", for " << qname.toLogString() << ", zone not matched by allow-notify-for" << endl;
             }
 
             g_stats.zoneDisallowedNotify++;
@@ -511,7 +512,7 @@ static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
         string response;
         RecursorPacketCache::OptPBData pbData{boost::none};
 
-        if(dc->d_mdp.d_header.opcode == Opcode::Query) {
+        if (dc->d_mdp.d_header.opcode == Opcode::Query) {
           /* It might seem like a good idea to skip the packet cache lookup if we know that the answer is not cacheable,
              but it means that the hash would not be computed. If some script decides at a later time to mark back the answer
              as cacheable we would cache it with a wrong tag, so better safe than sorry. */
@@ -521,7 +522,7 @@ static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
 
           if (cacheHit) {
             if (!g_quiet) {
-              g_log<<Logger::Notice<<t_id<< " TCP question answered from packet cache tag="<<dc->d_tag<<" from "<<dc->d_source.toStringWithPort()<<(dc->d_source != dc->d_remote ? " (via "+dc->d_remote.toStringWithPort()+")" : "")<<endl;
+              g_log << Logger::Notice << t_id << " TCP question answered from packet cache tag=" << dc->d_tag << " from " << dc->d_source.toStringWithPort() << (dc->d_source != dc->d_remote ? " (via " + dc->d_remote.toStringWithPort() + ")" : "") << endl;
             }
 
             bool hadError = sendResponseOverTCP(dc, response);
@@ -533,7 +534,10 @@ static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
             dc->d_eventTrace.add(RecEventTrace::AnswerSent);
 
             if (t_protobufServers && dc->d_logResponse && !(luaconfsLocal->protobufExportConfig.taggedOnly && pbData && !pbData->d_tagged)) {
-              struct timeval tv{0, 0};
+              struct timeval tv
+              {
+                0, 0
+              };
               protobufLogResponse(dh, luaconfsLocal, pbData, tv, true, dc->d_source, dc->d_destination, dc->d_ednssubnet, dc->d_uuid, dc->d_requestorId, dc->d_deviceId, dc->d_deviceName, dc->d_meta, dc->d_eventTrace);
             }
 
@@ -545,9 +549,9 @@ static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
           } // cache hit
         } // query opcode
 
-        if(dc->d_mdp.d_header.opcode == Opcode::Notify) {
+        if (dc->d_mdp.d_header.opcode == Opcode::Notify) {
           if (!g_quiet) {
-            g_log<<Logger::Notice<<t_id<< " got NOTIFY for "<<qname.toLogString()<<" from "<<dc->d_source.toStringWithPort()<<(dc->d_source != dc->d_remote ? " (via "+dc->d_remote.toStringWithPort()+")" : "")<<endl;
+            g_log << Logger::Notice << t_id << " got NOTIFY for " << qname.toLogString() << " from " << dc->d_source.toStringWithPort() << (dc->d_source != dc->d_remote ? " (via " + dc->d_remote.toStringWithPort() + ")" : "") << endl;
           }
 
           requestWipeCaches(qname);
@@ -563,7 +567,8 @@ static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
         ++conn->d_requestsInFlight;
         if (conn->d_requestsInFlight >= TCPConnection::s_maxInFlight) {
           t_fdm->removeReadFD(fd); // should no longer awake ourselves when there is data to read
-        } else {
+        }
+        else {
           Utility::gettimeofday(&g_now, nullptr); // needed?
           struct timeval ttd = g_now;
           t_fdm->setReadTTD(fd, ttd, g_tcpTimeout);
@@ -579,49 +584,49 @@ static void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
 }
 
 //! Handle new incoming TCP connection
-void handleNewTCPQuestion(int fd, FDMultiplexer::funcparam_t& )
+void handleNewTCPQuestion(int fd, FDMultiplexer::funcparam_t&)
 {
   ComboAddress addr;
-  socklen_t addrlen=sizeof(addr);
-  int newsock=accept(fd, (struct sockaddr*)&addr, &addrlen);
-  if(newsock>=0) {
-    if(MT->numProcesses() > g_maxMThreads) {
+  socklen_t addrlen = sizeof(addr);
+  int newsock = accept(fd, (struct sockaddr*)&addr, &addrlen);
+  if (newsock >= 0) {
+    if (MT->numProcesses() > g_maxMThreads) {
       g_stats.overCapacityDrops++;
       try {
         closesocket(newsock);
       }
-      catch(const PDNSException& e) {
-        g_log<<Logger::Error<<"Error closing TCP socket after an over capacity drop: "<<e.reason<<endl;
+      catch (const PDNSException& e) {
+        g_log << Logger::Error << "Error closing TCP socket after an over capacity drop: " << e.reason << endl;
       }
       return;
     }
 
-    if(t_remotes) {
+    if (t_remotes) {
       t_remotes->push_back(addr);
     }
 
     bool fromProxyProtocolSource = expectProxyProtocol(addr);
-    if(t_allowFrom && !t_allowFrom->match(&addr) && !fromProxyProtocolSource) {
-      if(!g_quiet)
-        g_log<<Logger::Error<<"["<<MT->getTid()<<"] dropping TCP query from "<<addr.toString()<<", address neither matched by allow-from nor proxy-protocol-from"<<endl;
+    if (t_allowFrom && !t_allowFrom->match(&addr) && !fromProxyProtocolSource) {
+      if (!g_quiet)
+        g_log << Logger::Error << "[" << MT->getTid() << "] dropping TCP query from " << addr.toString() << ", address neither matched by allow-from nor proxy-protocol-from" << endl;
 
       g_stats.unauthorizedTCP++;
       try {
         closesocket(newsock);
       }
-      catch(const PDNSException& e) {
-        g_log<<Logger::Error<<"Error closing TCP socket after an ACL drop: "<<e.reason<<endl;
+      catch (const PDNSException& e) {
+        g_log << Logger::Error << "Error closing TCP socket after an ACL drop: " << e.reason << endl;
       }
       return;
     }
 
-    if(g_maxTCPPerClient && t_tcpClientCounts->count(addr) && (*t_tcpClientCounts)[addr] >= g_maxTCPPerClient) {
+    if (g_maxTCPPerClient && t_tcpClientCounts->count(addr) && (*t_tcpClientCounts)[addr] >= g_maxTCPPerClient) {
       g_stats.tcpClientOverflow++;
       try {
         closesocket(newsock); // don't call TCPConnection::closeAndCleanup here - did not enter it in the counts yet!
       }
-      catch(const PDNSException& e) {
-        g_log<<Logger::Error<<"Error closing TCP socket after an overflow drop: "<<e.reason<<endl;
+      catch (const PDNSException& e) {
+        g_log << Logger::Error << "Error closing TCP socket after an overflow drop: " << e.reason << endl;
       }
       return;
     }
@@ -721,7 +726,6 @@ static void TCPIOHandlerStateChange(IOState oldstate, IOState newstate, std::sha
     throw std::runtime_error("TLS async mode not supported");
     break;
   }
-
 }
 
 static void TCPIOHandlerIO(int fd, FDMultiplexer::funcparam_t& var)
@@ -812,7 +816,6 @@ static void TCPIOHandlerIO(int fd, FDMultiplexer::funcparam_t& var)
   TCPIOHandlerStateChange(pid->lowState, newstate, pid);
 }
 
-
 void checkFastOpenSysctl(bool active)
 {
 #ifdef __linux__
@@ -828,7 +831,7 @@ void checkFastOpenSysctl(bool active)
   }
   else {
     g_log << Logger::Notice << "Cannot determine if kernel settings allow fast-open" << endl;
- }
 }
 #else
   g_log << Logger::Notice << "Cannot determine if kernel settings allow fast-open" << endl;
 #endif
@@ -846,8 +849,6 @@ void checkTFOconnect()
   }
 }
 
-
-
 LWResult::Result asendtcp(const PacketBuffer& data, shared_ptr<TCPIOHandler>& handler)
 {
   TCPLOG(handler->getDescriptor(), "asendtcp called " << data.size() << endl);
@@ -949,7 +950,7 @@ LWResult::Result arecvtcp(PacketBuffer& data, const size_t len, shared_ptr<TCPIO
   TCPIOHandlerStateChange(IOState::Done, state, pident);
 
   int ret = MT->waitEvent(pident, &data, g_networkTimeoutMsec);
-  TCPLOG(pident->tcpsock, "arecvtcp " << ret << ' ' << data.size() << ' ' );
+  TCPLOG(pident->tcpsock, "arecvtcp " << ret << ' ' << data.size() << ' ');
   if (ret == 0) {
     TCPLOG(pident->tcpsock, "timeout" << endl);
     TCPIOHandlerStateChange(pident->lowState, IOState::Done, pident);
@@ -960,7 +961,7 @@ LWResult::Result arecvtcp(PacketBuffer& data, const size_t len, shared_ptr<TCPIO
     TCPIOHandlerStateChange(pident->lowState, IOState::Done, pident);
     return LWResult::Result::PermanentError;
   }
-  else if (data.empty()) {// error, EOF or other
+  else if (data.empty()) { // error, EOF or other
     // fd housekeeping done by TCPIOHandlerIO
     TCPLOG(pident->tcpsock, "EOF" << endl);
     return LWResult::Result::PermanentError;
@@ -973,52 +974,52 @@ LWResult::Result arecvtcp(PacketBuffer& data, const size_t len, shared_ptr<TCPIO
 void makeTCPServerSockets(deferredAdd_t& deferredAdds, std::set<int>& tcpSockets)
 {
   int fd;
-  vector<string>locals;
-  stringtok(locals,::arg()["local-address"]," ,");
+  vector<string> locals;
+  stringtok(locals, ::arg()["local-address"], " ,");
 
-  if(locals.empty())
+  if (locals.empty())
     throw PDNSException("No local address specified");
 
-  for(vector<string>::const_iterator i=locals.begin();i!=locals.end();++i) {
+  for (vector<string>::const_iterator i = locals.begin(); i != locals.end(); ++i) {
     ServiceTuple st;
-    st.port=::arg().asNum("local-port");
+    st.port = ::arg().asNum("local-port");
     parseService(*i, st);
 
     ComboAddress sin;
 
     sin.reset();
     sin.sin4.sin_family = AF_INET;
-    if(!IpToU32(st.host, (uint32_t*)&sin.sin4.sin_addr.s_addr)) {
+    if (!IpToU32(st.host, (uint32_t*)&sin.sin4.sin_addr.s_addr)) {
       sin.sin6.sin6_family = AF_INET6;
-      if(makeIPv6sockaddr(st.host, &sin.sin6) < 0)
-        throw PDNSException("Unable to resolve local address for TCP server on '"+ st.host +"'");
+      if (makeIPv6sockaddr(st.host, &sin.sin6) < 0)
+        throw PDNSException("Unable to resolve local address for TCP server on '" + st.host + "'");
     }
 
-    fd=socket(sin.sin6.sin6_family, SOCK_STREAM, 0);
-    if(fd<0)
-      throw PDNSException("Making a TCP server socket for resolver: "+stringerror());
+    fd = socket(sin.sin6.sin6_family, SOCK_STREAM, 0);
+    if (fd < 0)
+      throw PDNSException("Making a TCP server socket for resolver: " + stringerror());
 
     setCloseOnExec(fd);
 
-    int tmp=1;
-    if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof tmp)<0) {
-      g_log<<Logger::Error<<"Setsockopt failed for TCP listening socket"<<endl;
+    int tmp = 1;
+    if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof tmp) < 0) {
+      g_log << Logger::Error << "Setsockopt failed for TCP listening socket" << endl;
       exit(1);
     }
-    if(sin.sin6.sin6_family == AF_INET6 && setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &tmp, sizeof(tmp)) < 0) {
+    if (sin.sin6.sin6_family == AF_INET6 && setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &tmp, sizeof(tmp)) < 0) {
       int err = errno;
-      g_log<<Logger::Error<<"Failed to set IPv6 socket to IPv6 only, continuing anyhow: "<<strerror(err)<<endl;
+      g_log << Logger::Error << "Failed to set IPv6 socket to IPv6 only, continuing anyhow: " << strerror(err) << endl;
     }
 
 #ifdef TCP_DEFER_ACCEPT
-    if(setsockopt(fd, IPPROTO_TCP, TCP_DEFER_ACCEPT, &tmp, sizeof tmp) >= 0) {
-      if(i==locals.begin())
-        g_log<<Logger::Info<<"Enabled TCP data-ready filter for (slight) DoS protection"<<endl;
+    if (setsockopt(fd, IPPROTO_TCP, TCP_DEFER_ACCEPT, &tmp, sizeof tmp) >= 0) {
+      if (i == locals.begin())
+        g_log << Logger::Info << "Enabled TCP data-ready filter for (slight) DoS protection" << endl;
     }
 #endif
 
-    if( ::arg().mustDo("non-local-bind") )
-       Utility::setBindAny(AF_INET, fd);
+    if (::arg().mustDo("non-local-bind"))
+      Utility::setBindAny(AF_INET, fd);
 
     if (g_reusePort) {
 #if defined(SO_REUSEPORT_LB)
@@ -1043,24 +1044,24 @@ void makeTCPServerSockets(deferredAdd_t& deferredAdds, std::set<int>& tcpSockets
 #ifdef TCP_FASTOPEN
       if (setsockopt(fd, IPPROTO_TCP, TCP_FASTOPEN, &SyncRes::s_tcp_fast_open, sizeof SyncRes::s_tcp_fast_open) < 0) {
         int err = errno;
-        g_log<<Logger::Error<<"Failed to enable TCP Fast Open for listening socket: "<<strerror(err)<<endl;
+        g_log << Logger::Error << "Failed to enable TCP Fast Open for listening socket: " << strerror(err) << endl;
       }
 #else
-      g_log<<Logger::Warning<<"TCP Fast Open configured but not supported for listening socket"<<endl;
+      g_log << Logger::Warning << "TCP Fast Open configured but not supported for listening socket" << endl;
 #endif
     }
 
     sin.sin4.sin_port = htons(st.port);
-    socklen_t socklen=sin.sin4.sin_family==AF_INET ? sizeof(sin.sin4) : sizeof(sin.sin6);
-    if (::bind(fd, (struct sockaddr *)&sin, socklen )<0)
-      throw PDNSException("Binding TCP server socket for "+ st.host +": "+stringerror());
+    socklen_t socklen = sin.sin4.sin_family == AF_INET ? sizeof(sin.sin4) : sizeof(sin.sin6);
+    if (::bind(fd, (struct sockaddr*)&sin, socklen) < 0)
+      throw PDNSException("Binding TCP server socket for " + st.host + ": " + stringerror());
 
     setNonBlocking(fd);
     try {
       setSocketSendBuffer(fd, 65000);
     }
     catch (const std::exception& e) {
-      g_log<<Logger::Error<<e.what()<<endl;
+      g_log << Logger::Error << e.what() << endl;
     }
 
     listen(fd, 128);
@@ -1069,9 +1070,9 @@ void makeTCPServerSockets(deferredAdd_t& deferredAdds, std::set<int>& tcpSockets
 
     // we don't need to update g_listenSocketsAddresses since it doesn't work for TCP/IP:
     //  - fd is not that which we know here, but returned from accept()
-    if(sin.sin4.sin_family == AF_INET)
-      g_log<<Logger::Info<<"Listening for TCP queries on "<< sin.toString() <<":"<<st.port<<endl;
+    if (sin.sin4.sin_family == AF_INET)
+      g_log << Logger::Info << "Listening for TCP queries on " << sin.toString() << ":" << st.port << endl;
     else
-      g_log<<Logger::Info<<"Listening for TCP queries on ["<< sin.toString() <<"]:"<<st.port<<endl;
+      g_log << Logger::Info << "Listening for TCP queries on [" << sin.toString() << "]:" << st.port << endl;
   }
 }