2 * This file is part of PowerDNS or dnsdist.
3 * Copyright -- PowerDNS.COM B.V. and its contributors
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of version 2 of the GNU General Public License as
7 * published by the Free Software Foundation.
9 * In addition, for the avoidance of any doubt, permission is granted to
10 * link this program with OpenSSL and to (re)distribute the binaries
11 * produced as the result of such linking.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
30 #include <unordered_set>
37 #include <boost/optional.hpp>
38 #include <boost/circular_buffer.hpp>
39 #include <boost/utility.hpp>
41 #include "recursor_cache.hh"
42 #include "recpacketcache.hh"
43 #include <boost/tuple/tuple.hpp>
44 #include <boost/optional.hpp>
45 #include <boost/tuple/tuple_comparison.hpp>
48 #include "validate.hh"
49 #include "ednssubnet.hh"
50 #include "filterpo.hh"
51 #include "negcache.hh"
58 #include <boost/uuid/uuid.hpp>
59 #include <boost/uuid/uuid_generators.hpp>
72 template<class Thing> class Throttle : public boost::noncopyable
81 bool shouldThrottle(time_t now, const Thing& t)
83 if(now > d_last_clean + 300 ) {
86 for(typename cont_t::iterator i=d_cont.begin();i!=d_cont.end();) {
87 if( i->second.ttd < now) {
95 typename cont_t::iterator i=d_cont.find(t);
98 if(now > i->second.ttd || i->second.count == 0) {
104 return true; // still listed, still blocked
106 void throttle(time_t now, const Thing& t, time_t ttl=0, unsigned int tries=0)
108 typename cont_t::iterator i=d_cont.find(t);
109 entry e={ now+(ttl ? ttl : d_ttl), tries ? tries : d_limit};
111 if(i==d_cont.end()) {
114 else if(i->second.ttd > e.ttd || (i->second.count) < e.count)
118 unsigned int size() const
120 return (unsigned int)d_cont.size();
128 unsigned int d_limit;
136 typedef map<Thing,entry> cont_t;
141 /** Class that implements a decaying EWMA.
142 This class keeps an exponentially weighted moving average which, additionally, decays over time.
143 The decaying is only done on get.
148 DecayingEwma() : d_val(0.0)
151 d_last.tv_sec = d_last.tv_usec = 0;
155 DecayingEwma(const DecayingEwma& orig) : d_last(orig.d_last), d_lastget(orig.d_lastget), d_val(orig.d_val), d_needinit(orig.d_needinit)
159 void submit(int val, const struct timeval* tv)
161 struct timeval now=*tv;
170 float diff= makeFloat(d_last - now);
173 double factor=exp(diff)/2.0; // might be '0.5', or 0.0001
174 d_val=(float)((1-factor)*val+ (float)factor*d_val);
178 double get(const struct timeval* tv)
180 struct timeval now=*tv;
181 float diff=makeFloat(d_lastget-now);
183 float factor=exp(diff/60.0f); // is 1.0 or less
184 return d_val*=factor;
187 double peek(void) const
192 bool stale(time_t limit) const
194 return limit > d_lastget.tv_sec;
198 struct timeval d_last; // stores time
199 struct timeval d_lastget; // stores time
204 template<class Thing> class Counters : public boost::noncopyable
210 unsigned long value(const Thing& t) const
212 typename cont_t::const_iterator i=d_cont.find(t);
214 if(i==d_cont.end()) {
217 return (unsigned long)i->second;
219 unsigned long incr(const Thing& t)
221 typename cont_t::iterator i=d_cont.find(t);
223 if(i==d_cont.end()) {
228 if (i->second < std::numeric_limits<unsigned long>::max())
230 return (unsigned long)i->second;
233 unsigned long decr(const Thing& t)
235 typename cont_t::iterator i=d_cont.find(t);
237 if(i!=d_cont.end() && --i->second == 0) {
241 return (unsigned long)i->second;
243 void clear(const Thing& t)
245 typename cont_t::iterator i=d_cont.find(t);
247 if(i!=d_cont.end()) {
257 return d_cont.size();
260 typedef map<Thing,unsigned long> cont_t;
265 class SyncRes : public boost::noncopyable
268 enum LogMode { LogNone, Log, Store};
269 typedef std::function<int(const ComboAddress& ip, const DNSName& qdomain, int qtype, bool doTCP, bool sendRDQuery, int EDNS0Level, struct timeval* now, boost::optional<Netmask>& srcmask, boost::optional<const ResolveContext&> context, std::shared_ptr<RemoteLogger> outgoingLogger, LWResult *lwr)> asyncresolve_t;
273 EDNSStatus() : mode(UNKNOWN), modeSetAt(0) {}
274 enum EDNSMode { UNKNOWN=0, EDNSOK=1, EDNSIGNORANT=2, NOEDNS=3 } mode;
278 //! This represents a number of decaying Ewmas, used to store performance per nameserver-name.
279 /** Modelled to work mostly like the underlying DecayingEwma. After you've called get,
280 d_best is filled out with the best address for this collection */
281 struct DecayingEwmaCollection
283 void submit(const ComboAddress& remote, int usecs, const struct timeval* now)
285 collection_t::iterator pos;
286 for(pos=d_collection.begin(); pos != d_collection.end(); ++pos)
287 if(pos->first==remote)
289 if(pos!=d_collection.end()) {
290 pos->second.submit(usecs, now);
294 de.submit(usecs, now);
295 d_collection.push_back(make_pair(remote, de));
299 double get(const struct timeval* now)
301 if(d_collection.empty())
303 double ret=std::numeric_limits<double>::max();
305 for(collection_t::iterator pos=d_collection.begin(); pos != d_collection.end(); ++pos) {
306 if((tmp=pos->second.get(now)) < ret) {
315 bool stale(time_t limit) const
317 for(collection_t::const_iterator pos=d_collection.begin(); pos != d_collection.end(); ++pos)
318 if(!pos->second.stale(limit))
323 typedef vector<pair<ComboAddress, DecayingEwma> > collection_t;
324 collection_t d_collection;
328 typedef map<DNSName, DecayingEwmaCollection> nsspeeds_t;
329 typedef map<ComboAddress, EDNSStatus> ednsstatus_t;
334 typedef multi_index_container <
338 composite_key< DNSRecord,
339 member<DNSRecord, DNSName, &DNSRecord::d_name>,
340 member<DNSRecord, uint16_t, &DNSRecord::d_type>
342 composite_key_compare<std::less<DNSName>, std::less<uint16_t> >
348 vector<ComboAddress> d_servers;
350 bool d_rdForward{false};
352 int getRecords(const DNSName& qname, uint16_t qtype, std::vector<DNSRecord>& records) const;
355 return d_servers.empty();
357 bool isForward() const
361 bool shouldRecurse() const
365 const DNSName& getName() const
371 void addSOA(std::vector<DNSRecord>& records) const;
374 typedef map<DNSName, AuthDomain> domainmap_t;
375 typedef Throttle<boost::tuple<ComboAddress,DNSName,uint16_t> > throttle_t;
376 typedef Counters<ComboAddress> fails_t;
378 struct ThreadLocalStorage {
382 ednsstatus_t ednsstatus;
384 std::shared_ptr<domainmap_t> domainmap;
387 static void setDefaultLogMode(LogMode lm)
391 static void doEDNSDumpAndClose(int fd);
392 static uint64_t doDumpNSSpeeds(int fd);
393 static int getRootNS(struct timeval now, asyncresolve_t asyncCallback);
394 static void clearDelegationOnly()
396 s_delegationOnly.clear();
398 static void addDelegationOnly(const DNSName& name)
400 s_delegationOnly.insert(name);
402 static void addDontQuery(const std::string& mask)
405 s_dontQuery = std::unique_ptr<NetmaskGroup>(new NetmaskGroup());
407 s_dontQuery->addMask(mask);
409 static void addDontQuery(const Netmask& mask)
412 s_dontQuery = std::unique_ptr<NetmaskGroup>(new NetmaskGroup());
414 s_dontQuery->addMask(mask);
416 static void clearDontQuery()
418 s_dontQuery = nullptr;
420 static void parseEDNSSubnetWhitelist(const std::string& wlist);
421 static void addEDNSSubnet(const Netmask& subnet)
423 s_ednssubnets.addMask(subnet);
425 static void addEDNSDomain(const DNSName& domain)
427 s_ednsdomains.add(domain);
429 static void clearEDNSSubnets()
431 s_ednssubnets.clear();
433 static void clearEDNSDomains()
435 s_ednsdomains = SuffixMatchNode();
437 static void pruneNSSpeeds(time_t limit)
439 for(auto i = t_sstorage.nsSpeeds.begin(), end = t_sstorage.nsSpeeds.end(); i != end; ) {
440 if(i->second.stale(limit)) {
441 i = t_sstorage.nsSpeeds.erase(i);
448 static uint64_t getNSSpeedsSize()
450 return t_sstorage.nsSpeeds.size();
452 static void submitNSSpeed(const DNSName& server, const ComboAddress& ca, uint32_t usec, const struct timeval* now)
454 t_sstorage.nsSpeeds[server].submit(ca, usec, now);
456 static void clearNSSpeeds()
458 t_sstorage.nsSpeeds.clear();
460 static EDNSStatus::EDNSMode getEDNSStatus(const ComboAddress& server)
462 const auto& it = t_sstorage.ednsstatus.find(server);
463 if (it == t_sstorage.ednsstatus.end())
464 return EDNSStatus::UNKNOWN;
466 return it->second.mode;
468 static uint64_t getEDNSStatusesSize()
470 return t_sstorage.ednsstatus.size();
472 static void clearEDNSStatuses()
474 t_sstorage.ednsstatus.clear();
476 static uint64_t getThrottledServersSize()
478 return t_sstorage.throttle.size();
480 static void clearThrottle()
482 t_sstorage.throttle.clear();
484 static bool isThrottled(time_t now, const ComboAddress& server, const DNSName& target, uint16_t qtype)
486 return t_sstorage.throttle.shouldThrottle(now, boost::make_tuple(server, target, qtype));
488 static bool isThrottled(time_t now, const ComboAddress& server)
490 return t_sstorage.throttle.shouldThrottle(now, boost::make_tuple(server, "", 0));
492 static void doThrottle(time_t now, const ComboAddress& server, time_t duration, unsigned int tries)
494 t_sstorage.throttle.throttle(now, boost::make_tuple(server, "", 0), duration, tries);
496 static uint64_t getFailedServersSize()
498 return t_sstorage.fails.size();
500 static void clearFailedServers()
502 t_sstorage.fails.clear();
504 static unsigned long getServerFailsCount(const ComboAddress& server)
506 return t_sstorage.fails.value(server);
509 static void clearNegCache()
511 t_sstorage.negcache.clear();
514 static uint64_t getNegCacheSize()
516 return t_sstorage.negcache.size();
519 static void pruneNegCache(unsigned int maxEntries)
521 t_sstorage.negcache.prune(maxEntries);
524 static uint64_t wipeNegCache(const DNSName& name, bool subtree = false)
526 return t_sstorage.negcache.wipe(name, subtree);
529 static void setDomainMap(std::shared_ptr<domainmap_t> newMap)
531 t_sstorage.domainmap = newMap;
534 static const std::shared_ptr<domainmap_t> getDomainMap()
536 return t_sstorage.domainmap;
539 explicit SyncRes(const struct timeval& now);
541 int beginResolve(const DNSName &qname, const QType &qtype, uint16_t qclass, vector<DNSRecord>&ret);
545 d_prefix="["+itoa(id)+"] ";
548 void setLogMode(LogMode lm)
555 return d_lm != LogNone;
558 void setCacheOnly(bool state=true)
563 void setDoEDNS0(bool state=true)
568 void setDoDNSSEC(bool state=true)
573 void setWantsRPZ(bool state=true)
578 bool getWantsRPZ() const
583 void setIncomingECSFound(bool state=true)
585 d_incomingECSFound=state;
588 string getTrace() const
590 return d_trace.str();
593 void setLuaEngine(shared_ptr<RecursorLua4> pdl)
598 bool wasVariable() const
600 return d_wasVariable;
603 bool wasOutOfBand() const
605 return d_wasOutOfBand;
608 struct timeval getNow() const
613 void setSkipCNAMECheck(bool skip = false)
615 d_skipCNAMECheck = skip;
618 void setIncomingECS(boost::optional<const EDNSSubnetOpts&> incomingECS)
620 d_incomingECS = incomingECS;
622 d_incomingECSNetwork = incomingECS->source.getMaskedNetwork();
625 d_incomingECSNetwork = ComboAddress();
630 void setInitialRequestId(boost::optional<const boost::uuids::uuid&> initialRequestId)
632 d_initialRequestId = initialRequestId;
636 void setAsyncCallback(asyncresolve_t func)
638 d_asyncResolve = func;
641 vState getValidationState() const
643 return d_queryValidationState;
646 static thread_local ThreadLocalStorage t_sstorage;
648 static std::atomic<uint64_t> s_queries;
649 static std::atomic<uint64_t> s_outgoingtimeouts;
650 static std::atomic<uint64_t> s_outgoing4timeouts;
651 static std::atomic<uint64_t> s_outgoing6timeouts;
652 static std::atomic<uint64_t> s_throttledqueries;
653 static std::atomic<uint64_t> s_dontqueries;
654 static std::atomic<uint64_t> s_outqueries;
655 static std::atomic<uint64_t> s_tcpoutqueries;
656 static std::atomic<uint64_t> s_nodelegated;
657 static std::atomic<uint64_t> s_unreachables;
658 static std::atomic<uint64_t> s_ecsqueries;
659 static std::atomic<uint64_t> s_ecsresponses;
661 static string s_serverID;
662 static unsigned int s_minimumTTL;
663 static unsigned int s_maxqperq;
664 static unsigned int s_maxtotusec;
665 static unsigned int s_maxdepth;
666 static unsigned int s_maxnegttl;
667 static unsigned int s_maxcachettl;
668 static unsigned int s_packetcachettl;
669 static unsigned int s_packetcacheservfailttl;
670 static unsigned int s_serverdownmaxfails;
671 static unsigned int s_serverdownthrottletime;
672 static uint8_t s_ecsipv4limit;
673 static uint8_t s_ecsipv6limit;
674 static bool s_doIPv6;
675 static bool s_noEDNSPing;
676 static bool s_noEDNS;
677 static bool s_rootNXTrust;
678 static bool s_nopacketcache;
680 std::unordered_map<std::string,bool> d_discardedPolicies;
681 DNSFilterEngine::Policy d_appliedPolicy;
682 unsigned int d_outqueries;
683 unsigned int d_tcpoutqueries;
684 unsigned int d_throttledqueries;
685 unsigned int d_timeouts;
686 unsigned int d_unreachables;
687 unsigned int d_totUsec;
688 ComboAddress d_requestor;
692 static std::unordered_set<DNSName> s_delegationOnly;
693 static NetmaskGroup s_ednssubnets;
694 static SuffixMatchNode s_ednsdomains;
696 static std::unique_ptr<NetmaskGroup> s_dontQuery;
698 struct GetBestNSAnswer
701 set<pair<DNSName,DNSName> > bestns;
702 uint8_t qtype; // only A and AAAA anyhow
703 bool operator<(const GetBestNSAnswer &b) const
705 return boost::tie(qname, qtype, bestns) <
706 boost::tie(b.qname, b.qtype, b.bestns);
710 typedef std::map<DNSName,vState> zonesStates_t;
712 int doResolveAt(NsSet &nameservers, DNSName auth, bool flawedNSSet, const DNSName &qname, const QType &qtype, vector<DNSRecord>&ret,
713 unsigned int depth, set<GetBestNSAnswer>&beenthere, vState& state);
714 bool doResolveAtThisIP(const std::string& prefix, const DNSName& qname, const QType& qtype, LWResult& lwr, boost::optional<Netmask>& ednsmask, const DNSName& auth, bool const sendRDQuery, const DNSName& nsName, const ComboAddress& remoteIP, bool doTCP, bool* truncated);
715 bool processAnswer(unsigned int depth, LWResult& lwr, const DNSName& qname, const QType& qtype, DNSName& auth, bool wasForwarded, const boost::optional<Netmask> ednsmask, bool sendRDQuery, NsSet &nameservers, std::vector<DNSRecord>& ret, const DNSFilterEngine& dfe, bool* gotNewServers, int* rcode, vState& state);
717 int doResolve(const DNSName &qname, const QType &qtype, vector<DNSRecord>&ret, unsigned int depth, set<GetBestNSAnswer>& beenthere, vState& state);
718 bool doOOBResolve(const AuthDomain& domain, const DNSName &qname, const QType &qtype, vector<DNSRecord>&ret, int& res) const;
719 bool doOOBResolve(const DNSName &qname, const QType &qtype, vector<DNSRecord>&ret, unsigned int depth, int &res);
720 domainmap_t::const_iterator getBestAuthZone(DNSName* qname) const;
721 bool doCNAMECacheCheck(const DNSName &qname, const QType &qtype, vector<DNSRecord>&ret, unsigned int depth, int &res, vState& state);
722 bool doCacheCheck(const DNSName &qname, const QType &qtype, vector<DNSRecord>&ret, unsigned int depth, int &res, vState& state);
723 void getBestNSFromCache(const DNSName &qname, const QType &qtype, vector<DNSRecord>&bestns, bool* flawedNSSet, unsigned int depth, set<GetBestNSAnswer>& beenthere);
724 DNSName getBestNSNamesFromCache(const DNSName &qname, const QType &qtype, NsSet& nsset, bool* flawedNSSet, unsigned int depth, set<GetBestNSAnswer>&beenthere);
726 inline vector<DNSName> shuffleInSpeedOrder(NsSet &nameservers, const string &prefix);
727 bool moreSpecificThan(const DNSName& a, const DNSName &b) const;
728 vector<ComboAddress> getAddrs(const DNSName &qname, unsigned int depth, set<GetBestNSAnswer>& beenthere);
730 bool nameserversBlockedByRPZ(const DNSFilterEngine& dfe, const NsSet& nameservers);
731 bool nameserverIPBlockedByRPZ(const DNSFilterEngine& dfe, const ComboAddress&);
732 bool throttledOrBlocked(const std::string& prefix, const ComboAddress& remoteIP, const DNSName& qname, const QType& qtype, bool pierceDontQuery);
734 vector<ComboAddress> retrieveAddressesForNS(const std::string& prefix, const DNSName& qname, vector<DNSName >::const_iterator& tns, const unsigned int depth, set<GetBestNSAnswer>& beenthere, const vector<DNSName >& rnameservers, NsSet& nameservers, bool& sendRDQuery, bool& pierceDontQuery, bool& flawedNSSet);
735 RCode::rcodes_ updateCacheFromRecords(unsigned int depth, LWResult& lwr, const DNSName& qname, const QType& qtype, const DNSName& auth, bool wasForwarded, const boost::optional<Netmask>, vState& state, bool& needWildcardProof);
736 bool processRecords(const std::string& prefix, const DNSName& qname, const QType& qtype, const DNSName& auth, LWResult& lwr, const bool sendRDQuery, vector<DNSRecord>& ret, set<DNSName>& nsset, DNSName& newtarget, DNSName& newauth, bool& realreferral, bool& negindic, vState& state, bool needWildcardProof);
738 bool doSpecialNamesResolve(const DNSName &qname, const QType &qtype, const uint16_t qclass, vector<DNSRecord> &ret);
740 int asyncresolveWrapper(const ComboAddress& ip, bool ednsMANDATORY, const DNSName& domain, int type, bool doTCP, bool sendRDQuery, struct timeval* now, boost::optional<Netmask>& srcmask, LWResult* res) const;
742 boost::optional<Netmask> getEDNSSubnetMask(const ComboAddress& local, const DNSName&dn, const ComboAddress& rem);
744 bool validationEnabled() const;
745 uint32_t computeLowestTTD(const std::vector<DNSRecord>& records, const std::vector<std::shared_ptr<RRSIGRecordContent> >& signatures, uint32_t signaturesTTL) const;
746 void updateValidationState(vState& state, const vState stateUpdate);
747 vState validateRecordsWithSigs(unsigned int depth, const DNSName& qname, const QType& qtype, const DNSName& name, const std::vector<DNSRecord>& records, const std::vector<std::shared_ptr<RRSIGRecordContent> >& signatures);
748 vState validateDNSKeys(const DNSName& zone, const std::vector<DNSRecord>& dnskeys, const std::vector<std::shared_ptr<RRSIGRecordContent> >& signatures, unsigned int depth);
749 vState getDSRecords(const DNSName& zone, dsmap_t& ds, bool onlyTA, unsigned int depth);
750 vState getDNSKeys(const DNSName& signer, skeyset_t& keys, unsigned int depth);
751 void getDenialValidationState(NegCache::NegCacheEntry& ne, vState& state, const dState expectedState, bool allowOptOut);
752 vState getTA(const DNSName& zone, dsmap_t& ds);
753 bool haveExactValidationStatus(const DNSName& domain);
754 vState getValidationStatus(const DNSName& subdomain);
756 void computeZoneCuts(const DNSName& begin, const DNSName& end, unsigned int depth);
758 void setUpdatingRootNS()
760 d_updatingRootNS = true;
763 zonesStates_t d_cutStates;
764 ostringstream d_trace;
765 shared_ptr<RecursorLua4> d_pdl;
766 boost::optional<const EDNSSubnetOpts&> d_incomingECS;
767 ComboAddress d_incomingECSNetwork;
769 boost::optional<const boost::uuids::uuid&> d_initialRequestId;
771 asyncresolve_t d_asyncResolve{nullptr};
772 struct timeval d_now;
774 vState d_queryValidationState{Indeterminate};
776 /* When d_cacheonly is set to true, we will only check the cache.
777 * This is set when the RD bit is unset in the incoming query
781 bool d_doEDNS0{true};
782 bool d_incomingECSFound{false};
783 bool d_requireAuthData{true};
784 bool d_skipCNAMECheck{false};
785 bool d_updatingRootNS{false};
786 bool d_wantsRPZ{true};
787 bool d_wasOutOfBand{false};
788 bool d_wasVariable{false};
794 /* external functions, opaque to us */
795 int asendtcp(const string& data, Socket* sock);
796 int arecvtcp(string& data, size_t len, Socket* sock, bool incompleteOkay);
801 PacketID() : id(0), type(0), sock(0), inNeeded(0), inIncompleteOkay(false), outPos(0), nearMisses(0), fd(-1)
803 memset(&remote, 0, sizeof(remote));
806 uint16_t id; // wait for a specific id/remote pair
807 uint16_t type; // and this is its type
808 ComboAddress remote; // this is the remote
809 DNSName domain; // this is the question
811 Socket* sock; // or wait for an event on a TCP fd
812 string inMSG; // they'll go here
813 size_t inNeeded; // if this is set, we'll read until inNeeded bytes are read
814 bool inIncompleteOkay;
816 string outMSG; // the outgoing message that needs to be sent
817 string::size_type outPos; // how far we are along in the outMSG
819 typedef set<uint16_t > chain_t;
820 mutable chain_t chain;
821 mutable uint32_t nearMisses; // number of near misses - host correct, id wrong
824 bool operator<(const PacketID& b) const
826 int ourSock= sock ? sock->getHandle() : 0;
827 int bSock = b.sock ? b.sock->getHandle() : 0;
828 if( tie(remote, ourSock, type) < tie(b.remote, bSock, b.type))
830 if( tie(remote, ourSock, type) > tie(b.remote, bSock, b.type))
833 return tie(domain, fd, id) < tie(b.domain, b.fd, b.id);
837 struct PacketIDBirthdayCompare: public std::binary_function<PacketID, PacketID, bool>
839 bool operator()(const PacketID& a, const PacketID& b) const
841 int ourSock= a.sock ? a.sock->getHandle() : 0;
842 int bSock = b.sock ? b.sock->getHandle() : 0;
843 if( tie(a.remote, ourSock, a.type) < tie(b.remote, bSock, b.type))
845 if( tie(a.remote, ourSock, a.type) > tie(b.remote, bSock, b.type))
848 return a.domain < b.domain;
851 extern thread_local std::unique_ptr<MemRecursorCache> t_RC;
852 extern thread_local std::unique_ptr<RecursorPacketCache> t_packetCache;
853 typedef MTasker<PacketID,string> MT_t;
858 std::atomic<uint64_t> servFails;
859 std::atomic<uint64_t> nxDomains;
860 std::atomic<uint64_t> noErrors;
861 std::atomic<uint64_t> answers0_1, answers1_10, answers10_100, answers100_1000, answersSlow;
862 std::atomic<uint64_t> auth4Answers0_1, auth4Answers1_10, auth4Answers10_100, auth4Answers100_1000, auth4AnswersSlow;
863 std::atomic<uint64_t> auth6Answers0_1, auth6Answers1_10, auth6Answers10_100, auth6Answers100_1000, auth6AnswersSlow;
864 double avgLatencyUsec;
865 std::atomic<uint64_t> qcounter; // not increased for unauth packets
866 std::atomic<uint64_t> ipv6qcounter;
867 std::atomic<uint64_t> tcpqcounter;
868 std::atomic<uint64_t> unauthorizedUDP; // when this is increased, qcounter isn't
869 std::atomic<uint64_t> unauthorizedTCP; // when this is increased, qcounter isn't
870 std::atomic<uint64_t> policyDrops;
871 std::atomic<uint64_t> tcpClientOverflow;
872 std::atomic<uint64_t> clientParseError;
873 std::atomic<uint64_t> serverParseError;
874 std::atomic<uint64_t> tooOldDrops;
875 std::atomic<uint64_t> unexpectedCount;
876 std::atomic<uint64_t> caseMismatchCount;
877 std::atomic<uint64_t> spoofCount;
878 std::atomic<uint64_t> resourceLimits;
879 std::atomic<uint64_t> overCapacityDrops;
880 std::atomic<uint64_t> ipv6queries;
881 std::atomic<uint64_t> chainResends;
882 std::atomic<uint64_t> nsSetInvalidations;
883 std::atomic<uint64_t> ednsPingMatches;
884 std::atomic<uint64_t> ednsPingMismatches;
885 std::atomic<uint64_t> noPingOutQueries, noEdnsOutQueries;
886 std::atomic<uint64_t> packetCacheHits;
887 std::atomic<uint64_t> noPacketError;
888 std::atomic<uint64_t> ignoredCount;
890 std::atomic<uint64_t> dnssecQueries;
891 unsigned int maxMThreadStackUsage;
892 std::atomic<uint64_t> dnssecValidations; // should be the sum of all dnssecResult* stats
893 std::map<vState, std::atomic<uint64_t> > dnssecResults;
894 std::map<DNSFilterEngine::PolicyKind, std::atomic<uint64_t> > policyResults;
897 //! represents a running TCP/IP client session
898 class TCPConnection : public boost::noncopyable
901 TCPConnection(int fd, const ComboAddress& addr);
908 enum stateenum {BYTE0, BYTE1, GETQUESTION, DONE} state{BYTE0};
910 uint16_t bytesread{0};
911 const ComboAddress d_remote;
912 char data[65535]; // damn
913 size_t queriesCount{0};
915 static unsigned int getCurrentConnections() { return s_currentConnections; }
918 static AtomicCounter s_currentConnections; //!< total number of current TCP connections
921 class ImmediateServFailException
924 ImmediateServFailException(string r){reason=r;};
926 string reason; //! Print this to tell the user what went wrong
929 #if (__GNUC__ == 4 && __GNUC_MINOR__ == 2)
930 typedef boost::circular_buffer<SComboAddress> addrringbuf_t;
932 typedef boost::circular_buffer<ComboAddress> addrringbuf_t;
934 extern thread_local std::unique_ptr<addrringbuf_t> t_servfailremotes, t_largeanswerremotes, t_remotes;
936 extern thread_local std::unique_ptr<boost::circular_buffer<pair<DNSName,uint16_t> > > t_queryring, t_servfailqueryring;
937 extern thread_local std::shared_ptr<NetmaskGroup> t_allowFrom;
938 string doQueueReloadLuaScript(vector<string>::const_iterator begin, vector<string>::const_iterator end);
939 string doTraceRegex(vector<string>::const_iterator begin, vector<string>::const_iterator end);
941 extern RecursorStats g_stats;
942 extern unsigned int g_numThreads;
943 extern uint16_t g_outgoingEDNSBufsize;
946 std::string reloadAuthAndForwards();
947 ComboAddress parseIPAndPort(const std::string& input, uint16_t port);
948 ComboAddress getQueryLocalAddress(int family, uint16_t port);
949 typedef boost::function<void*(void)> pipefunc_t;
950 void broadcastFunction(const pipefunc_t& func, bool skipSelf = false);
951 void distributeAsyncFunction(const std::string& question, const pipefunc_t& func);
953 int directResolve(const DNSName& qname, const QType& qtype, int qclass, vector<DNSRecord>& ret);
955 template<class T> T broadcastAccFunction(const boost::function<T*()>& func, bool skipSelf=false);
957 std::shared_ptr<SyncRes::domainmap_t> parseAuthAndForwards();
958 uint64_t* pleaseGetNsSpeedsSize();
959 uint64_t* pleaseGetCacheSize();
960 uint64_t* pleaseGetNegCacheSize();
961 uint64_t* pleaseGetCacheHits();
962 uint64_t* pleaseGetCacheMisses();
963 uint64_t* pleaseGetConcurrentQueries();
964 uint64_t* pleaseGetThrottleSize();
965 uint64_t* pleaseGetPacketCacheHits();
966 uint64_t* pleaseGetPacketCacheSize();
967 uint64_t* pleaseWipeCache(const DNSName& canon, bool subtree=false);
968 uint64_t* pleaseWipePacketCache(const DNSName& canon, bool subtree);
969 uint64_t* pleaseWipeAndCountNegCache(const DNSName& canon, bool subtree=false);
970 void doCarbonDump(void*);
971 void primeHints(void);
973 extern __thread struct timeval g_now;
976 extern thread_local std::unique_ptr<boost::uuids::random_generator> t_uuidGenerator;