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>
71 template<class Thing> class Throttle : public boost::noncopyable
74 Throttle() : d_limit(3), d_ttl(60), d_last_clean(time(nullptr))
83 typedef map<Thing,entry> cont_t;
85 bool shouldThrottle(time_t now, const Thing& t)
87 if(now > d_last_clean + 300 ) {
90 for(typename cont_t::iterator i=d_cont.begin();i!=d_cont.end();) {
91 if( i->second.ttd < now) {
99 typename cont_t::iterator i=d_cont.find(t);
102 if(now > i->second.ttd || i->second.count == 0) {
108 return true; // still listed, still blocked
110 void throttle(time_t now, const Thing& t, time_t ttl=0, unsigned int tries=0)
112 typename cont_t::iterator i=d_cont.find(t);
113 entry e={ now+(ttl ? ttl : d_ttl), tries ? tries : d_limit};
115 if(i==d_cont.end()) {
118 else if(i->second.ttd > e.ttd || (i->second.count) < e.count)
122 unsigned int size() const
124 return (unsigned int)d_cont.size();
127 const cont_t& getThrottleMap() const
138 unsigned int d_limit;
145 /** Class that implements a decaying EWMA.
146 This class keeps an exponentially weighted moving average which, additionally, decays over time.
147 The decaying is only done on get.
152 DecayingEwma() : d_val(0.0)
155 d_last.tv_sec = d_last.tv_usec = 0;
159 DecayingEwma(const DecayingEwma& orig) : d_last(orig.d_last), d_lastget(orig.d_lastget), d_val(orig.d_val), d_needinit(orig.d_needinit)
163 void submit(int val, const struct timeval* tv)
165 struct timeval now=*tv;
174 float diff= makeFloat(d_last - now);
177 double factor=exp(diff)/2.0; // might be '0.5', or 0.0001
178 d_val=(float)((1-factor)*val+ (float)factor*d_val);
182 double get(const struct timeval* tv)
184 struct timeval now=*tv;
185 float diff=makeFloat(d_lastget-now);
187 float factor=exp(diff/60.0f); // is 1.0 or less
188 return d_val*=factor;
191 double peek(void) const
196 bool stale(time_t limit) const
198 return limit > d_lastget.tv_sec;
202 struct timeval d_last; // stores time
203 struct timeval d_lastget; // stores time
208 template<class Thing> class Counters : public boost::noncopyable
214 unsigned long value(const Thing& t) const
216 typename cont_t::const_iterator i=d_cont.find(t);
218 if(i==d_cont.end()) {
221 return (unsigned long)i->second;
223 unsigned long incr(const Thing& t)
225 typename cont_t::iterator i=d_cont.find(t);
227 if(i==d_cont.end()) {
232 if (i->second < std::numeric_limits<unsigned long>::max())
234 return (unsigned long)i->second;
237 unsigned long decr(const Thing& t)
239 typename cont_t::iterator i=d_cont.find(t);
241 if(i!=d_cont.end() && --i->second == 0) {
245 return (unsigned long)i->second;
247 void clear(const Thing& t)
249 typename cont_t::iterator i=d_cont.find(t);
251 if(i!=d_cont.end()) {
261 return d_cont.size();
264 typedef map<Thing,unsigned long> cont_t;
269 class SyncRes : public boost::noncopyable
272 enum LogMode { LogNone, Log, Store};
273 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, LWResult *lwr, bool* chained)> asyncresolve_t;
277 EDNSStatus() : mode(UNKNOWN), modeSetAt(0) {}
278 enum EDNSMode { UNKNOWN=0, EDNSOK=1, EDNSIGNORANT=2, NOEDNS=3 } mode;
282 //! This represents a number of decaying Ewmas, used to store performance per nameserver-name.
283 /** Modelled to work mostly like the underlying DecayingEwma. After you've called get,
284 d_best is filled out with the best address for this collection */
285 struct DecayingEwmaCollection
287 void submit(const ComboAddress& remote, int usecs, const struct timeval* now)
289 d_collection[remote].submit(usecs, now);
292 double get(const struct timeval* now)
294 if(d_collection.empty())
296 double ret=std::numeric_limits<double>::max();
298 for (auto& entry : d_collection) {
299 if((tmp = entry.second.get(now)) < ret) {
308 bool stale(time_t limit) const
310 for(const auto& entry : d_collection)
311 if(!entry.second.stale(limit))
316 void purge(const std::map<ComboAddress, double>& keep)
318 for (auto iter = d_collection.begin(); iter != d_collection.end(); ) {
319 if (keep.find(iter->first) != keep.end()) {
323 iter = d_collection.erase(iter);
328 typedef std::map<ComboAddress, DecayingEwma> collection_t;
329 collection_t d_collection;
333 typedef map<DNSName, DecayingEwmaCollection> nsspeeds_t;
334 typedef map<ComboAddress, EDNSStatus> ednsstatus_t;
336 vState getDSRecords(const DNSName& zone, dsmap_t& ds, bool onlyTA, unsigned int depth, bool bogusOnNXD=true, bool* foundCut=nullptr);
341 typedef multi_index_container <
345 composite_key< DNSRecord,
346 member<DNSRecord, DNSName, &DNSRecord::d_name>,
347 member<DNSRecord, uint16_t, &DNSRecord::d_type>
349 composite_key_compare<std::less<DNSName>, std::less<uint16_t> >
355 vector<ComboAddress> d_servers;
357 bool d_rdForward{false};
359 int getRecords(const DNSName& qname, uint16_t qtype, std::vector<DNSRecord>& records) const;
362 return d_servers.empty();
364 bool isForward() const
368 bool shouldRecurse() const
372 const DNSName& getName() const
378 void addSOA(std::vector<DNSRecord>& records) const;
381 typedef map<DNSName, AuthDomain> domainmap_t;
382 typedef Throttle<boost::tuple<ComboAddress,DNSName,uint16_t> > throttle_t;
383 typedef Counters<ComboAddress> fails_t;
385 struct ThreadLocalStorage {
389 ednsstatus_t ednsstatus;
391 std::shared_ptr<domainmap_t> domainmap;
394 static void setDefaultLogMode(LogMode lm)
398 static uint64_t doEDNSDump(int fd);
399 static uint64_t doDumpNSSpeeds(int fd);
400 static uint64_t doDumpThrottleMap(int fd);
401 static int getRootNS(struct timeval now, asyncresolve_t asyncCallback);
402 static void clearDelegationOnly()
404 s_delegationOnly.clear();
406 static void addDelegationOnly(const DNSName& name)
408 s_delegationOnly.insert(name);
410 static void addDontQuery(const std::string& mask)
413 s_dontQuery = std::unique_ptr<NetmaskGroup>(new NetmaskGroup());
415 s_dontQuery->addMask(mask);
417 static void addDontQuery(const Netmask& mask)
420 s_dontQuery = std::unique_ptr<NetmaskGroup>(new NetmaskGroup());
422 s_dontQuery->addMask(mask);
424 static void clearDontQuery()
426 s_dontQuery = nullptr;
428 static void parseEDNSSubnetWhitelist(const std::string& wlist);
429 static void parseEDNSSubnetAddFor(const std::string& subnetlist);
430 static void addEDNSLocalSubnet(const std::string& subnet)
432 s_ednslocalsubnets.addMask(subnet);
434 static void addEDNSRemoteSubnet(const std::string& subnet)
436 s_ednsremotesubnets.addMask(subnet);
438 static void addEDNSDomain(const DNSName& domain)
440 s_ednsdomains.add(domain);
442 static void clearEDNSLocalSubnets()
444 s_ednslocalsubnets.clear();
446 static void clearEDNSRemoteSubnets()
448 s_ednsremotesubnets.clear();
450 static void clearEDNSDomains()
452 s_ednsdomains = SuffixMatchNode();
454 static void pruneNSSpeeds(time_t limit)
456 for(auto i = t_sstorage.nsSpeeds.begin(), end = t_sstorage.nsSpeeds.end(); i != end; ) {
457 if(i->second.stale(limit)) {
458 i = t_sstorage.nsSpeeds.erase(i);
465 static uint64_t getNSSpeedsSize()
467 return t_sstorage.nsSpeeds.size();
469 static void submitNSSpeed(const DNSName& server, const ComboAddress& ca, uint32_t usec, const struct timeval* now)
471 t_sstorage.nsSpeeds[server].submit(ca, usec, now);
473 static void clearNSSpeeds()
475 t_sstorage.nsSpeeds.clear();
477 static EDNSStatus::EDNSMode getEDNSStatus(const ComboAddress& server)
479 const auto& it = t_sstorage.ednsstatus.find(server);
480 if (it == t_sstorage.ednsstatus.end())
481 return EDNSStatus::UNKNOWN;
483 return it->second.mode;
485 static uint64_t getEDNSStatusesSize()
487 return t_sstorage.ednsstatus.size();
489 static void clearEDNSStatuses()
491 t_sstorage.ednsstatus.clear();
493 static uint64_t getThrottledServersSize()
495 return t_sstorage.throttle.size();
497 static void clearThrottle()
499 t_sstorage.throttle.clear();
501 static bool isThrottled(time_t now, const ComboAddress& server, const DNSName& target, uint16_t qtype)
503 return t_sstorage.throttle.shouldThrottle(now, boost::make_tuple(server, target, qtype));
505 static bool isThrottled(time_t now, const ComboAddress& server)
507 return t_sstorage.throttle.shouldThrottle(now, boost::make_tuple(server, "", 0));
509 static void doThrottle(time_t now, const ComboAddress& server, time_t duration, unsigned int tries)
511 t_sstorage.throttle.throttle(now, boost::make_tuple(server, "", 0), duration, tries);
513 static uint64_t getFailedServersSize()
515 return t_sstorage.fails.size();
517 static void clearFailedServers()
519 t_sstorage.fails.clear();
521 static unsigned long getServerFailsCount(const ComboAddress& server)
523 return t_sstorage.fails.value(server);
526 static void clearNegCache()
528 t_sstorage.negcache.clear();
531 static uint64_t getNegCacheSize()
533 return t_sstorage.negcache.size();
536 static void pruneNegCache(unsigned int maxEntries)
538 t_sstorage.negcache.prune(maxEntries);
541 static uint64_t wipeNegCache(const DNSName& name, bool subtree = false)
543 return t_sstorage.negcache.wipe(name, subtree);
546 static void setDomainMap(std::shared_ptr<domainmap_t> newMap)
548 t_sstorage.domainmap = newMap;
551 static const std::shared_ptr<domainmap_t> getDomainMap()
553 return t_sstorage.domainmap;
556 static void setECSScopeZeroAddress(const Netmask& scopeZeroMask)
558 s_ecsScopeZero.source = scopeZeroMask;
561 static void clearECSStats()
563 s_ecsqueries.store(0);
564 s_ecsresponses.store(0);
566 for (size_t idx = 0; idx < 32; idx++) {
567 SyncRes::s_ecsResponsesBySubnetSize4[idx].store(0);
570 for (size_t idx = 0; idx < 128; idx++) {
571 SyncRes::s_ecsResponsesBySubnetSize6[idx].store(0);
575 explicit SyncRes(const struct timeval& now);
577 int beginResolve(const DNSName &qname, const QType &qtype, uint16_t qclass, vector<DNSRecord>&ret);
581 d_prefix="["+itoa(id)+"] ";
584 void setLogMode(LogMode lm)
591 return d_lm != LogNone;
594 void setCacheOnly(bool state=true)
599 void setDoEDNS0(bool state=true)
604 void setDoDNSSEC(bool state=true)
609 void setDNSSECValidationRequested(bool requested=true)
611 d_DNSSECValidationRequested = requested;
614 bool isDNSSECValidationRequested() const
616 return d_DNSSECValidationRequested;
619 bool shouldValidate() const
621 return d_DNSSECValidationRequested && !d_wasOutOfBand;
624 void setWantsRPZ(bool state=true)
629 bool getWantsRPZ() const
634 string getTrace() const
636 return d_trace.str();
639 void setLuaEngine(shared_ptr<RecursorLua4> pdl)
644 bool wasVariable() const
646 return d_wasVariable;
649 bool wasOutOfBand() const
651 return d_wasOutOfBand;
654 struct timeval getNow() const
659 void setSkipCNAMECheck(bool skip = false)
661 d_skipCNAMECheck = skip;
664 void setQuerySource(const ComboAddress& requestor, boost::optional<const EDNSSubnetOpts&> incomingECS);
667 void setInitialRequestId(boost::optional<const boost::uuids::uuid&> initialRequestId)
669 d_initialRequestId = initialRequestId;
672 void setOutgoingProtobufServers(std::shared_ptr<std::vector<std::unique_ptr<RemoteLogger>>>& servers)
674 d_outgoingProtobufServers = servers;
678 void setAsyncCallback(asyncresolve_t func)
680 d_asyncResolve = func;
683 vState getValidationState() const
685 return d_queryValidationState;
688 static thread_local ThreadLocalStorage t_sstorage;
690 static std::atomic<uint64_t> s_queries;
691 static std::atomic<uint64_t> s_outgoingtimeouts;
692 static std::atomic<uint64_t> s_outgoing4timeouts;
693 static std::atomic<uint64_t> s_outgoing6timeouts;
694 static std::atomic<uint64_t> s_throttledqueries;
695 static std::atomic<uint64_t> s_dontqueries;
696 static std::atomic<uint64_t> s_authzonequeries;
697 static std::atomic<uint64_t> s_outqueries;
698 static std::atomic<uint64_t> s_tcpoutqueries;
699 static std::atomic<uint64_t> s_nodelegated;
700 static std::atomic<uint64_t> s_unreachables;
701 static std::atomic<uint64_t> s_ecsqueries;
702 static std::atomic<uint64_t> s_ecsresponses;
703 static std::map<uint8_t, std::atomic<uint64_t>> s_ecsResponsesBySubnetSize4;
704 static std::map<uint8_t, std::atomic<uint64_t>> s_ecsResponsesBySubnetSize6;
706 static string s_serverID;
707 static unsigned int s_minimumTTL;
708 static unsigned int s_maxqperq;
709 static unsigned int s_maxtotusec;
710 static unsigned int s_maxdepth;
711 static unsigned int s_maxnegttl;
712 static unsigned int s_maxbogusttl;
713 static unsigned int s_maxcachettl;
714 static unsigned int s_packetcachettl;
715 static unsigned int s_packetcacheservfailttl;
716 static unsigned int s_serverdownmaxfails;
717 static unsigned int s_serverdownthrottletime;
718 static uint8_t s_ecsipv4limit;
719 static uint8_t s_ecsipv6limit;
720 static bool s_doIPv6;
721 static bool s_noEDNSPing;
722 static bool s_noEDNS;
723 static bool s_rootNXTrust;
724 static bool s_nopacketcache;
726 std::unordered_map<std::string,bool> d_discardedPolicies;
727 DNSFilterEngine::Policy d_appliedPolicy;
728 unsigned int d_authzonequeries;
729 unsigned int d_outqueries;
730 unsigned int d_tcpoutqueries;
731 unsigned int d_throttledqueries;
732 unsigned int d_timeouts;
733 unsigned int d_unreachables;
734 unsigned int d_totUsec;
737 ComboAddress d_requestor;
738 ComboAddress d_cacheRemote;
740 static std::unordered_set<DNSName> s_delegationOnly;
741 static NetmaskGroup s_ednslocalsubnets;
742 static NetmaskGroup s_ednsremotesubnets;
743 static SuffixMatchNode s_ednsdomains;
744 static EDNSSubnetOpts s_ecsScopeZero;
746 static std::unique_ptr<NetmaskGroup> s_dontQuery;
748 struct GetBestNSAnswer
751 set<pair<DNSName,DNSName> > bestns;
752 uint8_t qtype; // only A and AAAA anyhow
753 bool operator<(const GetBestNSAnswer &b) const
755 return boost::tie(qname, qtype, bestns) <
756 boost::tie(b.qname, b.qtype, b.bestns);
760 typedef std::map<DNSName,vState> zonesStates_t;
762 int doResolveAt(NsSet &nameservers, DNSName auth, bool flawedNSSet, const DNSName &qname, const QType &qtype, vector<DNSRecord>&ret,
763 unsigned int depth, set<GetBestNSAnswer>&beenthere, vState& state);
764 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);
765 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);
767 int doResolve(const DNSName &qname, const QType &qtype, vector<DNSRecord>&ret, unsigned int depth, set<GetBestNSAnswer>& beenthere, vState& state);
768 bool doOOBResolve(const AuthDomain& domain, const DNSName &qname, const QType &qtype, vector<DNSRecord>&ret, int& res);
769 bool doOOBResolve(const DNSName &qname, const QType &qtype, vector<DNSRecord>&ret, unsigned int depth, int &res);
770 domainmap_t::const_iterator getBestAuthZone(DNSName* qname) const;
771 bool doCNAMECacheCheck(const DNSName &qname, const QType &qtype, vector<DNSRecord>&ret, unsigned int depth, int &res, vState& state, bool wasAuthZone, bool wasForwardRecurse);
772 bool doCacheCheck(const DNSName &qname, const DNSName& authname, bool wasForwardedOrAuthZone, bool wasAuthZone, bool wasForwardRecurse, const QType &qtype, vector<DNSRecord>&ret, unsigned int depth, int &res, vState& state);
773 void getBestNSFromCache(const DNSName &qname, const QType &qtype, vector<DNSRecord>&bestns, bool* flawedNSSet, unsigned int depth, set<GetBestNSAnswer>& beenthere);
774 DNSName getBestNSNamesFromCache(const DNSName &qname, const QType &qtype, NsSet& nsset, bool* flawedNSSet, unsigned int depth, set<GetBestNSAnswer>&beenthere);
776 inline vector<DNSName> shuffleInSpeedOrder(NsSet &nameservers, const string &prefix);
777 inline vector<ComboAddress> shuffleForwardSpeed(const vector<ComboAddress> &rnameservers, const string &prefix, const bool wasRd);
778 bool moreSpecificThan(const DNSName& a, const DNSName &b) const;
779 vector<ComboAddress> getAddrs(const DNSName &qname, unsigned int depth, set<GetBestNSAnswer>& beenthere, bool cacheOnly);
781 bool nameserversBlockedByRPZ(const DNSFilterEngine& dfe, const NsSet& nameservers);
782 bool nameserverIPBlockedByRPZ(const DNSFilterEngine& dfe, const ComboAddress&);
783 bool throttledOrBlocked(const std::string& prefix, const ComboAddress& remoteIP, const DNSName& qname, const QType& qtype, bool pierceDontQuery);
785 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, bool cacheOnly);
787 void sanitizeRecords(const std::string& prefix, LWResult& lwr, const DNSName& qname, const QType& qtype, const DNSName& auth, bool wasForwarded, bool rdQuery);
788 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, unsigned int& wildcardLabelsCount, bool sendRDQuery);
789 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, const bool needWildcardProof, const unsigned int wildcardLabelsCount);
791 bool doSpecialNamesResolve(const DNSName &qname, const QType &qtype, const uint16_t qclass, vector<DNSRecord> &ret);
793 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, bool* chained) const;
795 boost::optional<Netmask> getEDNSSubnetMask(const DNSName&dn, const ComboAddress& rem);
797 bool validationEnabled() const;
798 uint32_t computeLowestTTD(const std::vector<DNSRecord>& records, const std::vector<std::shared_ptr<RRSIGRecordContent> >& signatures, uint32_t signaturesTTL) const;
799 void updateValidationState(vState& state, const vState stateUpdate);
800 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);
801 vState validateDNSKeys(const DNSName& zone, const std::vector<DNSRecord>& dnskeys, const std::vector<std::shared_ptr<RRSIGRecordContent> >& signatures, unsigned int depth);
802 vState getDNSKeys(const DNSName& signer, skeyset_t& keys, unsigned int depth);
803 dState getDenialValidationState(const NegCache::NegCacheEntry& ne, const vState state, const dState expectedState, bool referralToUnsigned);
804 void updateDenialValidationState(vState& neValidationState, const DNSName& neName, vState& state, const dState denialState, const dState expectedState, bool allowOptOut);
805 void computeNegCacheValidationStatus(const NegCache::NegCacheEntry* ne, const DNSName& qname, const QType& qtype, const int res, vState& state, unsigned int depth);
806 vState getTA(const DNSName& zone, dsmap_t& ds);
807 bool haveExactValidationStatus(const DNSName& domain);
808 vState getValidationStatus(const DNSName& subdomain, bool allowIndeterminate=true);
809 void updateValidationStatusInCache(const DNSName &qname, const QType& qt, bool aa, vState newState) const;
811 bool lookForCut(const DNSName& qname, unsigned int depth, const vState existingState, vState& newState);
812 void computeZoneCuts(const DNSName& begin, const DNSName& end, unsigned int depth);
814 void setUpdatingRootNS()
816 d_updatingRootNS = true;
819 zonesStates_t d_cutStates;
820 ostringstream d_trace;
821 shared_ptr<RecursorLua4> d_pdl;
822 boost::optional<Netmask> d_outgoingECSNetwork;
823 std::shared_ptr<std::vector<std::unique_ptr<RemoteLogger>>> d_outgoingProtobufServers{nullptr};
825 boost::optional<const boost::uuids::uuid&> d_initialRequestId;
827 asyncresolve_t d_asyncResolve{nullptr};
828 struct timeval d_now;
830 vState d_queryValidationState{Indeterminate};
832 /* When d_cacheonly is set to true, we will only check the cache.
833 * This is set when the RD bit is unset in the incoming query
837 bool d_DNSSECValidationRequested{false};
838 bool d_doEDNS0{true};
839 bool d_requireAuthData{true};
840 bool d_skipCNAMECheck{false};
841 bool d_updatingRootNS{false};
842 bool d_wantsRPZ{true};
843 bool d_wasOutOfBand{false};
844 bool d_wasVariable{false};
850 /* external functions, opaque to us */
851 int asendtcp(const string& data, Socket* sock);
852 int arecvtcp(string& data, size_t len, Socket* sock, bool incompleteOkay);
857 PacketID() : id(0), type(0), sock(0), inNeeded(0), inIncompleteOkay(false), outPos(0), nearMisses(0), fd(-1)
862 uint16_t id; // wait for a specific id/remote pair
863 uint16_t type; // and this is its type
864 ComboAddress remote; // this is the remote
865 DNSName domain; // this is the question
867 Socket* sock; // or wait for an event on a TCP fd
868 string inMSG; // they'll go here
869 size_t inNeeded; // if this is set, we'll read until inNeeded bytes are read
870 bool inIncompleteOkay;
872 string outMSG; // the outgoing message that needs to be sent
873 string::size_type outPos; // how far we are along in the outMSG
875 typedef set<uint16_t > chain_t;
876 mutable chain_t chain;
877 mutable uint32_t nearMisses; // number of near misses - host correct, id wrong
880 bool operator<(const PacketID& b) const
882 int ourSock= sock ? sock->getHandle() : 0;
883 int bSock = b.sock ? b.sock->getHandle() : 0;
884 if( tie(remote, ourSock, type) < tie(b.remote, bSock, b.type))
886 if( tie(remote, ourSock, type) > tie(b.remote, bSock, b.type))
889 return tie(domain, fd, id) < tie(b.domain, b.fd, b.id);
893 struct PacketIDBirthdayCompare: public std::binary_function<PacketID, PacketID, bool>
895 bool operator()(const PacketID& a, const PacketID& b) const
897 int ourSock= a.sock ? a.sock->getHandle() : 0;
898 int bSock = b.sock ? b.sock->getHandle() : 0;
899 if( tie(a.remote, ourSock, a.type) < tie(b.remote, bSock, b.type))
901 if( tie(a.remote, ourSock, a.type) > tie(b.remote, bSock, b.type))
904 return a.domain < b.domain;
907 extern thread_local std::unique_ptr<MemRecursorCache> t_RC;
908 extern thread_local std::unique_ptr<RecursorPacketCache> t_packetCache;
909 typedef MTasker<PacketID,string> MT_t;
914 std::atomic<uint64_t> servFails;
915 std::atomic<uint64_t> nxDomains;
916 std::atomic<uint64_t> noErrors;
917 std::atomic<uint64_t> answers0_1, answers1_10, answers10_100, answers100_1000, answersSlow;
918 std::atomic<uint64_t> auth4Answers0_1, auth4Answers1_10, auth4Answers10_100, auth4Answers100_1000, auth4AnswersSlow;
919 std::atomic<uint64_t> auth6Answers0_1, auth6Answers1_10, auth6Answers10_100, auth6Answers100_1000, auth6AnswersSlow;
920 std::atomic<uint64_t> ourtime0_1, ourtime1_2, ourtime2_4, ourtime4_8, ourtime8_16, ourtime16_32, ourtimeSlow;
921 double avgLatencyUsec{0};
922 double avgLatencyOursUsec{0};
923 std::atomic<uint64_t> qcounter; // not increased for unauth packets
924 std::atomic<uint64_t> ipv6qcounter;
925 std::atomic<uint64_t> tcpqcounter;
926 std::atomic<uint64_t> unauthorizedUDP; // when this is increased, qcounter isn't
927 std::atomic<uint64_t> unauthorizedTCP; // when this is increased, qcounter isn't
928 std::atomic<uint64_t> policyDrops;
929 std::atomic<uint64_t> tcpClientOverflow;
930 std::atomic<uint64_t> clientParseError;
931 std::atomic<uint64_t> serverParseError;
932 std::atomic<uint64_t> tooOldDrops;
933 std::atomic<uint64_t> truncatedDrops;
934 std::atomic<uint64_t> queryPipeFullDrops;
935 std::atomic<uint64_t> unexpectedCount;
936 std::atomic<uint64_t> caseMismatchCount;
937 std::atomic<uint64_t> spoofCount;
938 std::atomic<uint64_t> resourceLimits;
939 std::atomic<uint64_t> overCapacityDrops;
940 std::atomic<uint64_t> ipv6queries;
941 std::atomic<uint64_t> chainResends;
942 std::atomic<uint64_t> nsSetInvalidations;
943 std::atomic<uint64_t> ednsPingMatches;
944 std::atomic<uint64_t> ednsPingMismatches;
945 std::atomic<uint64_t> noPingOutQueries, noEdnsOutQueries;
946 std::atomic<uint64_t> packetCacheHits;
947 std::atomic<uint64_t> noPacketError;
948 std::atomic<uint64_t> ignoredCount;
949 std::atomic<uint64_t> emptyQueriesCount;
951 std::atomic<uint64_t> dnssecQueries;
952 std::atomic<uint64_t> dnssecAuthenticDataQueries;
953 std::atomic<uint64_t> dnssecCheckDisabledQueries;
954 std::atomic<uint64_t> variableResponses;
955 unsigned int maxMThreadStackUsage;
956 std::atomic<uint64_t> dnssecValidations; // should be the sum of all dnssecResult* stats
957 std::map<vState, std::atomic<uint64_t> > dnssecResults;
958 std::map<DNSFilterEngine::PolicyKind, std::atomic<uint64_t> > policyResults;
961 //! represents a running TCP/IP client session
962 class TCPConnection : public boost::noncopyable
965 TCPConnection(int fd, const ComboAddress& addr);
974 const ComboAddress d_remote;
975 size_t queriesCount{0};
976 enum stateenum {BYTE0, BYTE1, GETQUESTION, DONE} state{BYTE0};
978 uint16_t bytesread{0};
980 static unsigned int getCurrentConnections() { return s_currentConnections; }
983 static AtomicCounter s_currentConnections; //!< total number of current TCP connections
986 class ImmediateServFailException
989 ImmediateServFailException(string r) : reason(r) {};
991 string reason; //! Print this to tell the user what went wrong
994 typedef boost::circular_buffer<ComboAddress> addrringbuf_t;
995 extern thread_local std::unique_ptr<addrringbuf_t> t_servfailremotes, t_largeanswerremotes, t_remotes, t_bogusremotes, t_timeouts;
997 extern thread_local std::unique_ptr<boost::circular_buffer<pair<DNSName,uint16_t> > > t_queryring, t_servfailqueryring, t_bogusqueryring;
998 extern thread_local std::shared_ptr<NetmaskGroup> t_allowFrom;
999 string doQueueReloadLuaScript(vector<string>::const_iterator begin, vector<string>::const_iterator end);
1000 string doTraceRegex(vector<string>::const_iterator begin, vector<string>::const_iterator end);
1002 extern RecursorStats g_stats;
1003 extern unsigned int g_networkTimeoutMsec;
1004 extern unsigned int g_numThreads;
1005 extern uint16_t g_outgoingEDNSBufsize;
1006 extern std::atomic<uint32_t> g_maxCacheEntries, g_maxPacketCacheEntries;
1007 extern bool g_lowercaseOutgoing;
1010 std::string reloadAuthAndForwards();
1011 ComboAddress parseIPAndPort(const std::string& input, uint16_t port);
1012 ComboAddress getQueryLocalAddress(int family, uint16_t port);
1013 typedef boost::function<void*(void)> pipefunc_t;
1014 void broadcastFunction(const pipefunc_t& func);
1015 void distributeAsyncFunction(const std::string& question, const pipefunc_t& func);
1017 int directResolve(const DNSName& qname, const QType& qtype, int qclass, vector<DNSRecord>& ret);
1019 template<class T> T broadcastAccFunction(const boost::function<T*()>& func);
1021 std::shared_ptr<SyncRes::domainmap_t> parseAuthAndForwards();
1022 uint64_t* pleaseGetNsSpeedsSize();
1023 uint64_t* pleaseGetCacheSize();
1024 uint64_t* pleaseGetNegCacheSize();
1025 uint64_t* pleaseGetCacheHits();
1026 uint64_t* pleaseGetCacheMisses();
1027 uint64_t* pleaseGetConcurrentQueries();
1028 uint64_t* pleaseGetThrottleSize();
1029 uint64_t* pleaseGetPacketCacheHits();
1030 uint64_t* pleaseGetPacketCacheSize();
1031 uint64_t* pleaseWipeCache(const DNSName& canon, bool subtree=false);
1032 uint64_t* pleaseWipePacketCache(const DNSName& canon, bool subtree);
1033 uint64_t* pleaseWipeAndCountNegCache(const DNSName& canon, bool subtree=false);
1034 void doCarbonDump(void*);
1035 void primeHints(void);
1037 extern __thread struct timeval g_now;