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
87 typedef map<Thing,entry> cont_t;
89 bool shouldThrottle(time_t now, const Thing& t)
91 if(now > d_last_clean + 300 ) {
94 for(typename cont_t::iterator i=d_cont.begin();i!=d_cont.end();) {
95 if( i->second.ttd < now) {
103 typename cont_t::iterator i=d_cont.find(t);
106 if(now > i->second.ttd || i->second.count == 0) {
112 return true; // still listed, still blocked
114 void throttle(time_t now, const Thing& t, time_t ttl=0, unsigned int tries=0)
116 typename cont_t::iterator i=d_cont.find(t);
117 entry e={ now+(ttl ? ttl : d_ttl), tries ? tries : d_limit};
119 if(i==d_cont.end()) {
122 else if(i->second.ttd > e.ttd || (i->second.count) < e.count)
126 unsigned int size() const
128 return (unsigned int)d_cont.size();
131 const cont_t& getThrottleMap() const
142 unsigned int d_limit;
149 /** Class that implements a decaying EWMA.
150 This class keeps an exponentially weighted moving average which, additionally, decays over time.
151 The decaying is only done on get.
156 DecayingEwma() : d_val(0.0)
159 d_last.tv_sec = d_last.tv_usec = 0;
163 DecayingEwma(const DecayingEwma& orig) : d_last(orig.d_last), d_lastget(orig.d_lastget), d_val(orig.d_val), d_needinit(orig.d_needinit)
167 void submit(int val, const struct timeval* tv)
169 struct timeval now=*tv;
178 float diff= makeFloat(d_last - now);
181 double factor=exp(diff)/2.0; // might be '0.5', or 0.0001
182 d_val=(float)((1-factor)*val+ (float)factor*d_val);
186 double get(const struct timeval* tv)
188 struct timeval now=*tv;
189 float diff=makeFloat(d_lastget-now);
191 float factor=exp(diff/60.0f); // is 1.0 or less
192 return d_val*=factor;
195 double peek(void) const
200 bool stale(time_t limit) const
202 return limit > d_lastget.tv_sec;
206 struct timeval d_last; // stores time
207 struct timeval d_lastget; // stores time
212 template<class Thing> class Counters : public boost::noncopyable
218 unsigned long value(const Thing& t) const
220 typename cont_t::const_iterator i=d_cont.find(t);
222 if(i==d_cont.end()) {
225 return (unsigned long)i->second;
227 unsigned long incr(const Thing& t)
229 typename cont_t::iterator i=d_cont.find(t);
231 if(i==d_cont.end()) {
236 if (i->second < std::numeric_limits<unsigned long>::max())
238 return (unsigned long)i->second;
241 unsigned long decr(const Thing& t)
243 typename cont_t::iterator i=d_cont.find(t);
245 if(i!=d_cont.end() && --i->second == 0) {
249 return (unsigned long)i->second;
251 void clear(const Thing& t)
253 typename cont_t::iterator i=d_cont.find(t);
255 if(i!=d_cont.end()) {
265 return d_cont.size();
268 typedef map<Thing,unsigned long> cont_t;
273 class SyncRes : public boost::noncopyable
276 enum LogMode { LogNone, Log, Store};
277 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;
281 EDNSStatus() : mode(UNKNOWN), modeSetAt(0) {}
282 enum EDNSMode { UNKNOWN=0, EDNSOK=1, EDNSIGNORANT=2, NOEDNS=3 } mode;
286 //! This represents a number of decaying Ewmas, used to store performance per nameserver-name.
287 /** Modelled to work mostly like the underlying DecayingEwma. After you've called get,
288 d_best is filled out with the best address for this collection */
289 struct DecayingEwmaCollection
291 void submit(const ComboAddress& remote, int usecs, const struct timeval* now)
293 d_collection[remote].submit(usecs, now);
296 double get(const struct timeval* now)
298 if(d_collection.empty())
300 double ret=std::numeric_limits<double>::max();
302 for (auto& entry : d_collection) {
303 if((tmp = entry.second.get(now)) < ret) {
312 bool stale(time_t limit) const
314 for(const auto& entry : d_collection)
315 if(!entry.second.stale(limit))
320 void purge(const std::map<ComboAddress, double>& keep)
322 for (auto iter = d_collection.begin(); iter != d_collection.end(); ) {
323 if (keep.find(iter->first) != keep.end()) {
327 iter = d_collection.erase(iter);
332 typedef std::map<ComboAddress, DecayingEwma> collection_t;
333 collection_t d_collection;
337 typedef map<DNSName, DecayingEwmaCollection> nsspeeds_t;
338 typedef map<ComboAddress, EDNSStatus> ednsstatus_t;
340 vState getDSRecords(const DNSName& zone, dsmap_t& ds, bool onlyTA, unsigned int depth, bool bogusOnNXD=true, bool* foundCut=nullptr);
345 typedef multi_index_container <
349 composite_key< DNSRecord,
350 member<DNSRecord, DNSName, &DNSRecord::d_name>,
351 member<DNSRecord, uint16_t, &DNSRecord::d_type>
353 composite_key_compare<std::less<DNSName>, std::less<uint16_t> >
359 vector<ComboAddress> d_servers;
361 bool d_rdForward{false};
363 int getRecords(const DNSName& qname, uint16_t qtype, std::vector<DNSRecord>& records) const;
366 return d_servers.empty();
368 bool isForward() const
372 bool shouldRecurse() const
376 const DNSName& getName() const
382 void addSOA(std::vector<DNSRecord>& records) const;
385 typedef map<DNSName, AuthDomain> domainmap_t;
386 typedef Throttle<boost::tuple<ComboAddress,DNSName,uint16_t> > throttle_t;
387 typedef Counters<ComboAddress> fails_t;
389 struct ThreadLocalStorage {
393 ednsstatus_t ednsstatus;
395 std::shared_ptr<domainmap_t> domainmap;
398 static void setDefaultLogMode(LogMode lm)
402 static uint64_t doEDNSDump(int fd);
403 static uint64_t doDumpNSSpeeds(int fd);
404 static uint64_t doDumpThrottleMap(int fd);
405 static int getRootNS(struct timeval now, asyncresolve_t asyncCallback);
406 static void clearDelegationOnly()
408 s_delegationOnly.clear();
410 static void addDelegationOnly(const DNSName& name)
412 s_delegationOnly.insert(name);
414 static void addDontQuery(const std::string& mask)
417 s_dontQuery = std::unique_ptr<NetmaskGroup>(new NetmaskGroup());
419 s_dontQuery->addMask(mask);
421 static void addDontQuery(const Netmask& mask)
424 s_dontQuery = std::unique_ptr<NetmaskGroup>(new NetmaskGroup());
426 s_dontQuery->addMask(mask);
428 static void clearDontQuery()
430 s_dontQuery = nullptr;
432 static void parseEDNSSubnetWhitelist(const std::string& wlist);
433 static void parseEDNSSubnetAddFor(const std::string& subnetlist);
434 static void addEDNSLocalSubnet(const std::string& subnet)
436 s_ednslocalsubnets.addMask(subnet);
438 static void addEDNSRemoteSubnet(const std::string& subnet)
440 s_ednsremotesubnets.addMask(subnet);
442 static void addEDNSDomain(const DNSName& domain)
444 s_ednsdomains.add(domain);
446 static void clearEDNSLocalSubnets()
448 s_ednslocalsubnets.clear();
450 static void clearEDNSRemoteSubnets()
452 s_ednsremotesubnets.clear();
454 static void clearEDNSDomains()
456 s_ednsdomains = SuffixMatchNode();
458 static void pruneNSSpeeds(time_t limit)
460 for(auto i = t_sstorage.nsSpeeds.begin(), end = t_sstorage.nsSpeeds.end(); i != end; ) {
461 if(i->second.stale(limit)) {
462 i = t_sstorage.nsSpeeds.erase(i);
469 static uint64_t getNSSpeedsSize()
471 return t_sstorage.nsSpeeds.size();
473 static void submitNSSpeed(const DNSName& server, const ComboAddress& ca, uint32_t usec, const struct timeval* now)
475 t_sstorage.nsSpeeds[server].submit(ca, usec, now);
477 static void clearNSSpeeds()
479 t_sstorage.nsSpeeds.clear();
481 static EDNSStatus::EDNSMode getEDNSStatus(const ComboAddress& server)
483 const auto& it = t_sstorage.ednsstatus.find(server);
484 if (it == t_sstorage.ednsstatus.end())
485 return EDNSStatus::UNKNOWN;
487 return it->second.mode;
489 static uint64_t getEDNSStatusesSize()
491 return t_sstorage.ednsstatus.size();
493 static void clearEDNSStatuses()
495 t_sstorage.ednsstatus.clear();
497 static uint64_t getThrottledServersSize()
499 return t_sstorage.throttle.size();
501 static void clearThrottle()
503 t_sstorage.throttle.clear();
505 static bool isThrottled(time_t now, const ComboAddress& server, const DNSName& target, uint16_t qtype)
507 return t_sstorage.throttle.shouldThrottle(now, boost::make_tuple(server, target, qtype));
509 static bool isThrottled(time_t now, const ComboAddress& server)
511 return t_sstorage.throttle.shouldThrottle(now, boost::make_tuple(server, "", 0));
513 static void doThrottle(time_t now, const ComboAddress& server, time_t duration, unsigned int tries)
515 t_sstorage.throttle.throttle(now, boost::make_tuple(server, "", 0), duration, tries);
517 static uint64_t getFailedServersSize()
519 return t_sstorage.fails.size();
521 static void clearFailedServers()
523 t_sstorage.fails.clear();
525 static unsigned long getServerFailsCount(const ComboAddress& server)
527 return t_sstorage.fails.value(server);
530 static void clearNegCache()
532 t_sstorage.negcache.clear();
535 static uint64_t getNegCacheSize()
537 return t_sstorage.negcache.size();
540 static void pruneNegCache(unsigned int maxEntries)
542 t_sstorage.negcache.prune(maxEntries);
545 static uint64_t wipeNegCache(const DNSName& name, bool subtree = false)
547 return t_sstorage.negcache.wipe(name, subtree);
550 static void setDomainMap(std::shared_ptr<domainmap_t> newMap)
552 t_sstorage.domainmap = newMap;
555 static const std::shared_ptr<domainmap_t> getDomainMap()
557 return t_sstorage.domainmap;
560 static void setECSScopeZeroAddress(const Netmask& scopeZeroMask)
562 s_ecsScopeZero.source = scopeZeroMask;
565 explicit SyncRes(const struct timeval& now);
567 int beginResolve(const DNSName &qname, const QType &qtype, uint16_t qclass, vector<DNSRecord>&ret);
571 d_prefix="["+itoa(id)+"] ";
574 void setLogMode(LogMode lm)
581 return d_lm != LogNone;
584 void setCacheOnly(bool state=true)
589 void setDoEDNS0(bool state=true)
594 void setDoDNSSEC(bool state=true)
599 void setDNSSECValidationRequested(bool requested=true)
601 d_DNSSECValidationRequested = requested;
604 bool isDNSSECValidationRequested() const
606 return d_DNSSECValidationRequested;
609 bool shouldValidate() const
611 return d_DNSSECValidationRequested && !d_wasOutOfBand;
614 void setWantsRPZ(bool state=true)
619 bool getWantsRPZ() const
624 string getTrace() const
626 return d_trace.str();
629 void setLuaEngine(shared_ptr<RecursorLua4> pdl)
634 bool wasVariable() const
636 return d_wasVariable;
639 bool wasOutOfBand() const
641 return d_wasOutOfBand;
644 struct timeval getNow() const
649 void setSkipCNAMECheck(bool skip = false)
651 d_skipCNAMECheck = skip;
654 void setQuerySource(const ComboAddress& requestor, boost::optional<const EDNSSubnetOpts&> incomingECS);
657 void setInitialRequestId(boost::optional<const boost::uuids::uuid&> initialRequestId)
659 d_initialRequestId = initialRequestId;
662 void setOutgoingProtobufServers(std::shared_ptr<std::vector<std::shared_ptr<RemoteLogger>>>& servers)
664 d_outgoingProtobufServers = servers;
668 void setAsyncCallback(asyncresolve_t func)
670 d_asyncResolve = func;
673 vState getValidationState() const
675 return d_queryValidationState;
678 static thread_local ThreadLocalStorage t_sstorage;
680 static std::atomic<uint64_t> s_queries;
681 static std::atomic<uint64_t> s_outgoingtimeouts;
682 static std::atomic<uint64_t> s_outgoing4timeouts;
683 static std::atomic<uint64_t> s_outgoing6timeouts;
684 static std::atomic<uint64_t> s_throttledqueries;
685 static std::atomic<uint64_t> s_dontqueries;
686 static std::atomic<uint64_t> s_authzonequeries;
687 static std::atomic<uint64_t> s_outqueries;
688 static std::atomic<uint64_t> s_tcpoutqueries;
689 static std::atomic<uint64_t> s_nodelegated;
690 static std::atomic<uint64_t> s_unreachables;
691 static std::atomic<uint64_t> s_ecsqueries;
692 static std::atomic<uint64_t> s_ecsresponses;
694 static string s_serverID;
695 static unsigned int s_minimumTTL;
696 static unsigned int s_maxqperq;
697 static unsigned int s_maxtotusec;
698 static unsigned int s_maxdepth;
699 static unsigned int s_maxnegttl;
700 static unsigned int s_maxcachettl;
701 static unsigned int s_packetcachettl;
702 static unsigned int s_packetcacheservfailttl;
703 static unsigned int s_serverdownmaxfails;
704 static unsigned int s_serverdownthrottletime;
705 static uint8_t s_ecsipv4limit;
706 static uint8_t s_ecsipv6limit;
707 static bool s_doIPv6;
708 static bool s_noEDNSPing;
709 static bool s_noEDNS;
710 static bool s_rootNXTrust;
711 static bool s_nopacketcache;
713 std::unordered_map<std::string,bool> d_discardedPolicies;
714 DNSFilterEngine::Policy d_appliedPolicy;
715 unsigned int d_authzonequeries;
716 unsigned int d_outqueries;
717 unsigned int d_tcpoutqueries;
718 unsigned int d_throttledqueries;
719 unsigned int d_timeouts;
720 unsigned int d_unreachables;
721 unsigned int d_totUsec;
724 ComboAddress d_requestor;
725 ComboAddress d_cacheRemote;
727 static std::unordered_set<DNSName> s_delegationOnly;
728 static NetmaskGroup s_ednslocalsubnets;
729 static NetmaskGroup s_ednsremotesubnets;
730 static SuffixMatchNode s_ednsdomains;
731 static EDNSSubnetOpts s_ecsScopeZero;
733 static std::unique_ptr<NetmaskGroup> s_dontQuery;
735 struct GetBestNSAnswer
738 set<pair<DNSName,DNSName> > bestns;
739 uint8_t qtype; // only A and AAAA anyhow
740 bool operator<(const GetBestNSAnswer &b) const
742 return boost::tie(qname, qtype, bestns) <
743 boost::tie(b.qname, b.qtype, b.bestns);
747 typedef std::map<DNSName,vState> zonesStates_t;
749 int doResolveAt(NsSet &nameservers, DNSName auth, bool flawedNSSet, const DNSName &qname, const QType &qtype, vector<DNSRecord>&ret,
750 unsigned int depth, set<GetBestNSAnswer>&beenthere, vState& state);
751 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);
752 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);
754 int doResolve(const DNSName &qname, const QType &qtype, vector<DNSRecord>&ret, unsigned int depth, set<GetBestNSAnswer>& beenthere, vState& state);
755 bool doOOBResolve(const AuthDomain& domain, const DNSName &qname, const QType &qtype, vector<DNSRecord>&ret, int& res);
756 bool doOOBResolve(const DNSName &qname, const QType &qtype, vector<DNSRecord>&ret, unsigned int depth, int &res);
757 domainmap_t::const_iterator getBestAuthZone(DNSName* qname) const;
758 bool doCNAMECacheCheck(const DNSName &qname, const QType &qtype, vector<DNSRecord>&ret, unsigned int depth, int &res, vState& state, bool wasAuthZone, bool wasForwardRecurse);
759 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);
760 void getBestNSFromCache(const DNSName &qname, const QType &qtype, vector<DNSRecord>&bestns, bool* flawedNSSet, unsigned int depth, set<GetBestNSAnswer>& beenthere);
761 DNSName getBestNSNamesFromCache(const DNSName &qname, const QType &qtype, NsSet& nsset, bool* flawedNSSet, unsigned int depth, set<GetBestNSAnswer>&beenthere);
763 inline vector<DNSName> shuffleInSpeedOrder(NsSet &nameservers, const string &prefix);
764 inline vector<ComboAddress> shuffleForwardSpeed(const vector<ComboAddress> &rnameservers, const string &prefix, const bool wasRd);
765 bool moreSpecificThan(const DNSName& a, const DNSName &b) const;
766 vector<ComboAddress> getAddrs(const DNSName &qname, unsigned int depth, set<GetBestNSAnswer>& beenthere, bool cacheOnly);
768 bool nameserversBlockedByRPZ(const DNSFilterEngine& dfe, const NsSet& nameservers);
769 bool nameserverIPBlockedByRPZ(const DNSFilterEngine& dfe, const ComboAddress&);
770 bool throttledOrBlocked(const std::string& prefix, const ComboAddress& remoteIP, const DNSName& qname, const QType& qtype, bool pierceDontQuery);
772 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);
773 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);
774 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);
776 bool doSpecialNamesResolve(const DNSName &qname, const QType &qtype, const uint16_t qclass, vector<DNSRecord> &ret);
778 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;
780 boost::optional<Netmask> getEDNSSubnetMask(const DNSName&dn, const ComboAddress& rem);
782 bool validationEnabled() const;
783 uint32_t computeLowestTTD(const std::vector<DNSRecord>& records, const std::vector<std::shared_ptr<RRSIGRecordContent> >& signatures, uint32_t signaturesTTL) const;
784 void updateValidationState(vState& state, const vState stateUpdate);
785 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);
786 vState validateDNSKeys(const DNSName& zone, const std::vector<DNSRecord>& dnskeys, const std::vector<std::shared_ptr<RRSIGRecordContent> >& signatures, unsigned int depth);
787 vState getDNSKeys(const DNSName& signer, skeyset_t& keys, unsigned int depth);
788 dState getDenialValidationState(const NegCache::NegCacheEntry& ne, const vState state, const dState expectedState, bool referralToUnsigned);
789 void updateDenialValidationState(vState& neValidationState, const DNSName& neName, vState& state, const dState denialState, const dState expectedState, bool allowOptOut);
790 void computeNegCacheValidationStatus(const NegCache::NegCacheEntry* ne, const DNSName& qname, const QType& qtype, const int res, vState& state, unsigned int depth);
791 vState getTA(const DNSName& zone, dsmap_t& ds);
792 bool haveExactValidationStatus(const DNSName& domain);
793 vState getValidationStatus(const DNSName& subdomain, bool allowIndeterminate=true);
795 bool lookForCut(const DNSName& qname, unsigned int depth, const vState existingState, vState& newState);
796 void computeZoneCuts(const DNSName& begin, const DNSName& end, unsigned int depth);
798 void setUpdatingRootNS()
800 d_updatingRootNS = true;
803 zonesStates_t d_cutStates;
804 ostringstream d_trace;
805 shared_ptr<RecursorLua4> d_pdl;
806 boost::optional<Netmask> d_outgoingECSNetwork;
807 std::shared_ptr<std::vector<std::shared_ptr<RemoteLogger>>> d_outgoingProtobufServers{nullptr};
809 boost::optional<const boost::uuids::uuid&> d_initialRequestId;
811 asyncresolve_t d_asyncResolve{nullptr};
812 struct timeval d_now;
814 vState d_queryValidationState{Indeterminate};
816 /* When d_cacheonly is set to true, we will only check the cache.
817 * This is set when the RD bit is unset in the incoming query
821 bool d_DNSSECValidationRequested{false};
822 bool d_doEDNS0{true};
823 bool d_requireAuthData{true};
824 bool d_skipCNAMECheck{false};
825 bool d_updatingRootNS{false};
826 bool d_wantsRPZ{true};
827 bool d_wasOutOfBand{false};
828 bool d_wasVariable{false};
834 /* external functions, opaque to us */
835 int asendtcp(const string& data, Socket* sock);
836 int arecvtcp(string& data, size_t len, Socket* sock, bool incompleteOkay);
841 PacketID() : id(0), type(0), sock(0), inNeeded(0), inIncompleteOkay(false), outPos(0), nearMisses(0), fd(-1)
846 uint16_t id; // wait for a specific id/remote pair
847 uint16_t type; // and this is its type
848 ComboAddress remote; // this is the remote
849 DNSName domain; // this is the question
851 Socket* sock; // or wait for an event on a TCP fd
852 string inMSG; // they'll go here
853 size_t inNeeded; // if this is set, we'll read until inNeeded bytes are read
854 bool inIncompleteOkay;
856 string outMSG; // the outgoing message that needs to be sent
857 string::size_type outPos; // how far we are along in the outMSG
859 typedef set<uint16_t > chain_t;
860 mutable chain_t chain;
861 mutable uint32_t nearMisses; // number of near misses - host correct, id wrong
864 bool operator<(const PacketID& b) const
866 int ourSock= sock ? sock->getHandle() : 0;
867 int bSock = b.sock ? b.sock->getHandle() : 0;
868 if( tie(remote, ourSock, type) < tie(b.remote, bSock, b.type))
870 if( tie(remote, ourSock, type) > tie(b.remote, bSock, b.type))
873 return tie(domain, fd, id) < tie(b.domain, b.fd, b.id);
877 struct PacketIDBirthdayCompare: public std::binary_function<PacketID, PacketID, bool>
879 bool operator()(const PacketID& a, const PacketID& b) const
881 int ourSock= a.sock ? a.sock->getHandle() : 0;
882 int bSock = b.sock ? b.sock->getHandle() : 0;
883 if( tie(a.remote, ourSock, a.type) < tie(b.remote, bSock, b.type))
885 if( tie(a.remote, ourSock, a.type) > tie(b.remote, bSock, b.type))
888 return a.domain < b.domain;
891 extern thread_local std::unique_ptr<MemRecursorCache> t_RC;
892 extern thread_local std::unique_ptr<RecursorPacketCache> t_packetCache;
893 typedef MTasker<PacketID,string> MT_t;
898 std::atomic<uint64_t> servFails;
899 std::atomic<uint64_t> nxDomains;
900 std::atomic<uint64_t> noErrors;
901 std::atomic<uint64_t> answers0_1, answers1_10, answers10_100, answers100_1000, answersSlow;
902 std::atomic<uint64_t> auth4Answers0_1, auth4Answers1_10, auth4Answers10_100, auth4Answers100_1000, auth4AnswersSlow;
903 std::atomic<uint64_t> auth6Answers0_1, auth6Answers1_10, auth6Answers10_100, auth6Answers100_1000, auth6AnswersSlow;
904 std::atomic<uint64_t> ourtime0_1, ourtime1_2, ourtime2_4, ourtime4_8, ourtime8_16, ourtime16_32, ourtimeSlow;
905 double avgLatencyUsec{0};
906 double avgLatencyOursUsec{0};
907 std::atomic<uint64_t> qcounter; // not increased for unauth packets
908 std::atomic<uint64_t> ipv6qcounter;
909 std::atomic<uint64_t> tcpqcounter;
910 std::atomic<uint64_t> unauthorizedUDP; // when this is increased, qcounter isn't
911 std::atomic<uint64_t> unauthorizedTCP; // when this is increased, qcounter isn't
912 std::atomic<uint64_t> policyDrops;
913 std::atomic<uint64_t> tcpClientOverflow;
914 std::atomic<uint64_t> clientParseError;
915 std::atomic<uint64_t> serverParseError;
916 std::atomic<uint64_t> tooOldDrops;
917 std::atomic<uint64_t> truncatedDrops;
918 std::atomic<uint64_t> queryPipeFullDrops;
919 std::atomic<uint64_t> unexpectedCount;
920 std::atomic<uint64_t> caseMismatchCount;
921 std::atomic<uint64_t> spoofCount;
922 std::atomic<uint64_t> resourceLimits;
923 std::atomic<uint64_t> overCapacityDrops;
924 std::atomic<uint64_t> ipv6queries;
925 std::atomic<uint64_t> chainResends;
926 std::atomic<uint64_t> nsSetInvalidations;
927 std::atomic<uint64_t> ednsPingMatches;
928 std::atomic<uint64_t> ednsPingMismatches;
929 std::atomic<uint64_t> noPingOutQueries, noEdnsOutQueries;
930 std::atomic<uint64_t> packetCacheHits;
931 std::atomic<uint64_t> noPacketError;
932 std::atomic<uint64_t> ignoredCount;
933 std::atomic<uint64_t> emptyQueriesCount;
935 std::atomic<uint64_t> dnssecQueries;
936 unsigned int maxMThreadStackUsage;
937 std::atomic<uint64_t> dnssecValidations; // should be the sum of all dnssecResult* stats
938 std::map<vState, std::atomic<uint64_t> > dnssecResults;
939 std::map<DNSFilterEngine::PolicyKind, std::atomic<uint64_t> > policyResults;
942 //! represents a running TCP/IP client session
943 class TCPConnection : public boost::noncopyable
946 TCPConnection(int fd, const ComboAddress& addr);
955 const ComboAddress d_remote;
956 size_t queriesCount{0};
957 enum stateenum {BYTE0, BYTE1, GETQUESTION, DONE} state{BYTE0};
959 uint16_t bytesread{0};
961 static unsigned int getCurrentConnections() { return s_currentConnections; }
964 static AtomicCounter s_currentConnections; //!< total number of current TCP connections
967 class ImmediateServFailException
970 ImmediateServFailException(string r){reason=r;};
972 string reason; //! Print this to tell the user what went wrong
975 typedef boost::circular_buffer<ComboAddress> addrringbuf_t;
976 extern thread_local std::unique_ptr<addrringbuf_t> t_servfailremotes, t_largeanswerremotes, t_remotes, t_bogusremotes, t_timeouts;
978 extern thread_local std::unique_ptr<boost::circular_buffer<pair<DNSName,uint16_t> > > t_queryring, t_servfailqueryring, t_bogusqueryring;
979 extern thread_local std::shared_ptr<NetmaskGroup> t_allowFrom;
980 string doQueueReloadLuaScript(vector<string>::const_iterator begin, vector<string>::const_iterator end);
981 string doTraceRegex(vector<string>::const_iterator begin, vector<string>::const_iterator end);
983 extern RecursorStats g_stats;
984 extern unsigned int g_networkTimeoutMsec;
985 extern unsigned int g_numThreads;
986 extern uint16_t g_outgoingEDNSBufsize;
987 extern std::atomic<uint32_t> g_maxCacheEntries, g_maxPacketCacheEntries;
988 extern bool g_lowercaseOutgoing;
991 std::string reloadAuthAndForwards();
992 ComboAddress parseIPAndPort(const std::string& input, uint16_t port);
993 ComboAddress getQueryLocalAddress(int family, uint16_t port);
994 typedef boost::function<void*(void)> pipefunc_t;
995 void broadcastFunction(const pipefunc_t& func);
996 void distributeAsyncFunction(const std::string& question, const pipefunc_t& func);
998 int directResolve(const DNSName& qname, const QType& qtype, int qclass, vector<DNSRecord>& ret);
1000 template<class T> T broadcastAccFunction(const boost::function<T*()>& func);
1002 std::shared_ptr<SyncRes::domainmap_t> parseAuthAndForwards();
1003 uint64_t* pleaseGetNsSpeedsSize();
1004 uint64_t* pleaseGetCacheSize();
1005 uint64_t* pleaseGetNegCacheSize();
1006 uint64_t* pleaseGetCacheHits();
1007 uint64_t* pleaseGetCacheMisses();
1008 uint64_t* pleaseGetConcurrentQueries();
1009 uint64_t* pleaseGetThrottleSize();
1010 uint64_t* pleaseGetPacketCacheHits();
1011 uint64_t* pleaseGetPacketCacheSize();
1012 uint64_t* pleaseWipeCache(const DNSName& canon, bool subtree=false);
1013 uint64_t* pleaseWipePacketCache(const DNSName& canon, bool subtree);
1014 uint64_t* pleaseWipeAndCountNegCache(const DNSName& canon, bool subtree=false);
1015 void doCarbonDump(void*);
1016 void primeHints(void);
1018 extern __thread struct timeval g_now;
1020 #ifdef HAVE_PROTOBUF
1021 extern thread_local std::unique_ptr<boost::uuids::random_generator> t_uuidGenerator;