3 #include "ext/luawrapper/include/LuaContext.hpp"
9 #include <boost/circular_buffer.hpp>
10 #include <boost/variant.hpp>
15 #include "dnscrypt.hh"
16 #include "dnsdist-cache.hh"
18 #include "dnsdist-dynbpf.hh"
19 #include "bpf-filter.hh"
22 #include <boost/uuid/uuid.hpp>
23 #include <boost/uuid/uuid_generators.hpp>
26 void* carbonDumpThread();
27 uint64_t uptimeOfProcess(const std::string& str);
31 DynBlock& operator=(const DynBlock& rhs)
36 blocks.store(rhs.blocks);
41 struct timespec until;
43 mutable std::atomic<unsigned int> blocks;
46 extern GlobalStateHolder<NetmaskTree<DynBlock>> g_dynblockNMG;
48 extern vector<pair<struct timeval, std::string> > g_confDelta;
52 using stat_t=std::atomic<uint64_t>; // aww yiss ;-)
54 stat_t servfailResponses{0};
56 stat_t nonCompliantQueries{0};
57 stat_t nonCompliantResponses{0};
59 stat_t emptyQueries{0};
61 stat_t blockFilter{0};
64 stat_t ruleNXDomain{0};
65 stat_t selfAnswered{0};
66 stat_t downstreamTimeouts{0};
67 stat_t downstreamSendErrors{0};
71 stat_t cacheMisses{0};
72 stat_t latency0_1{0}, latency1_10{0}, latency10_50{0}, latency50_100{0}, latency100_1000{0}, latencySlow{0};
74 double latencyAvg100{0}, latencyAvg1000{0}, latencyAvg10000{0}, latencyAvg1000000{0};
75 typedef std::function<uint64_t(const std::string&)> statfunction_t;
76 typedef boost::variant<stat_t*, double*, statfunction_t> entry_t;
77 std::vector<std::pair<std::string, entry_t>> entries{
78 {"responses", &responses}, {"servfail-responses", &servfailResponses},
79 {"queries", &queries}, {"acl-drops", &aclDrops},
80 {"block-filter", &blockFilter}, {"rule-drop", &ruleDrop},
81 {"rule-nxdomain", &ruleNXDomain}, {"self-answered", &selfAnswered},
82 {"downstream-timeouts", &downstreamTimeouts}, {"downstream-send-errors", &downstreamSendErrors},
83 {"trunc-failures", &truncFail}, {"no-policy", &noPolicy},
84 {"latency0-1", &latency0_1}, {"latency1-10", &latency1_10},
85 {"latency10-50", &latency10_50}, {"latency50-100", &latency50_100},
86 {"latency100-1000", &latency100_1000}, {"latency-slow", &latencySlow},
87 {"latency-avg100", &latencyAvg100}, {"latency-avg1000", &latencyAvg1000},
88 {"latency-avg10000", &latencyAvg10000}, {"latency-avg1000000", &latencyAvg1000000},
89 {"uptime", uptimeOfProcess},
90 {"real-memory-usage", getRealMemoryUsage},
91 {"noncompliant-queries", &nonCompliantQueries},
92 {"noncompliant-responses", &nonCompliantResponses},
93 {"rdqueries", &rdQueries},
94 {"empty-queries", &emptyQueries},
95 {"cache-hits", &cacheHits},
96 {"cache-misses", &cacheMisses},
97 {"cpu-user-msec", getCPUTimeUser},
98 {"cpu-sys-msec", getCPUTimeSystem},
99 {"fd-usage", getOpenFileDescriptors}, {"dyn-blocked", &dynBlocked},
100 {"dyn-block-nmg-size", [](const std::string&) { return g_dynblockNMG.getLocal()->size(); }}
105 extern struct DNSDistStats g_stats;
110 StopWatch(bool realTime=false): d_needRealTime(realTime)
113 struct timespec d_start{0,0};
114 bool d_needRealTime{false};
117 if(gettime(&d_start, d_needRealTime) < 0)
118 unixDie("Getting timestamp");
122 double udiff() const {
124 if(gettime(&now, d_needRealTime) < 0)
125 unixDie("Getting timestamp");
127 return 1000000.0*(now.tv_sec - d_start.tv_sec) + (now.tv_nsec - d_start.tv_nsec)/1000.0;
130 double udiffAndSet() {
132 if(gettime(&now, d_needRealTime) < 0)
133 unixDie("Getting timestamp");
135 auto ret= 1000000.0*(now.tv_sec - d_start.tv_sec) + (now.tv_nsec - d_start.tv_nsec)/1000.0;
149 QPSLimiter(unsigned int rate, unsigned int burst) : d_rate(rate), d_burst(burst), d_tokens(burst)
155 unsigned int getRate() const
157 return d_passthrough? 0 : d_rate;
160 int getPassed() const
164 int getBlocked() const
169 bool check() const // this is not quite fair
173 auto delta = d_prev.udiffAndSet();
175 d_tokens += 1.0*d_rate * (delta/1000000.0);
177 if(d_tokens > d_burst)
181 if(d_tokens >= 1.0) { // we need this because burst=1 is weird otherwise
192 bool d_passthrough{true};
194 unsigned int d_burst;
195 mutable double d_tokens;
196 mutable StopWatch d_prev;
197 mutable unsigned int d_passed{0};
198 mutable unsigned int d_blocked{0};
203 IDState() : origFD(-1), sentTime(true), delayMsec(0) { origDest.sin4.sin_family = 0;}
204 IDState(const IDState& orig)
206 origFD = orig.origFD;
207 origID = orig.origID;
208 origRemote = orig.origRemote;
209 origDest = orig.origDest;
210 delayMsec = orig.delayMsec;
211 age.store(orig.age.load());
214 int origFD; // set to <0 to indicate this state is empty // 4
216 ComboAddress origRemote; // 28
217 ComboAddress origDest; // 28
218 StopWatch sentTime; // 16
221 std::shared_ptr<DnsCryptQuery> dnsCryptQuery{0};
224 boost::uuids::uuid uniqueId;
226 std::shared_ptr<DNSDistPacketCache> packetCache{nullptr};
227 uint32_t cacheKey; // 8
228 std::atomic<uint16_t> age; // 4
230 uint16_t qclass; // 2
231 uint16_t origID; // 2
232 uint16_t origFlags; // 2
234 bool ednsAdded{false};
235 bool ecsAdded{false};
236 bool skipCache{false};
242 queryRing.set_capacity(10000);
243 respRing.set_capacity(10000);
244 pthread_rwlock_init(&queryLock, 0);
248 struct timespec when;
249 ComboAddress requestor;
255 boost::circular_buffer<Query> queryRing;
258 struct timespec when;
259 ComboAddress requestor;
265 ComboAddress ds; // who handled it
267 boost::circular_buffer<Response> respRing;
268 std::mutex respMutex;
269 pthread_rwlock_t queryLock;
271 std::unordered_map<int, vector<boost::variant<string,double> > > getTopBandwidth(unsigned int numentries);
272 size_t numDistinctRequestors();
275 extern Rings g_rings;
277 typedef std::unordered_map<string, unsigned int> QueryCountRecords;
278 typedef std::function<std::tuple<bool, string>(DNSQuestion dq)> QueryCountFilter;
282 pthread_rwlock_init(&queryLock, 0);
284 QueryCountRecords records;
285 QueryCountFilter filter;
286 pthread_rwlock_t queryLock;
290 extern QueryCount g_qcount;
296 DnsCryptContext* dnscryptCtx{0};
298 std::atomic<uint64_t> queries{0};
302 int getSocket() const
304 return udpFD != -1 ? udpFD : tcpFD;
308 shared_ptr<BPFFilter> d_filter;
313 d_filter->removeSocket(getSocket());
318 void attachFilter(shared_ptr<BPFFilter> bpf)
322 bpf->addSocket(getSocket());
325 #endif /* HAVE_EBPF */
328 class TCPClientCollection {
329 std::vector<int> d_tcpclientthreads;
330 std::atomic<uint64_t> d_pos{0};
332 std::atomic<uint64_t> d_queued{0}, d_numthreads{0};
333 uint64_t d_maxthreads{0};
335 TCPClientCollection(size_t maxThreads)
337 d_maxthreads = maxThreads;
338 d_tcpclientthreads.reserve(maxThreads);
343 uint64_t pos = d_pos++;
345 return d_tcpclientthreads[pos % d_numthreads];
347 void addTCPClientThread();
350 extern std::shared_ptr<TCPClientCollection> g_tcpclientthreads;
352 struct DownstreamState
354 DownstreamState(const ComboAddress& remote_, const ComboAddress& sourceAddr_, unsigned int sourceItf);
355 DownstreamState(const ComboAddress& remote_): DownstreamState(remote_, ComboAddress(), 0) {}
366 vector<IDState> idStates;
367 ComboAddress sourceAddr;
368 DNSName checkName{"a.root-servers.net."};
369 QType checkType{QType::A};
370 std::atomic<uint64_t> idOffset{0};
371 std::atomic<uint64_t> sendErrors{0};
372 std::atomic<uint64_t> outstanding{0};
373 std::atomic<uint64_t> reuseds{0};
374 std::atomic<uint64_t> queries{0};
376 std::atomic<uint64_t> sendErrors{0};
377 std::atomic<uint64_t> reuseds{0};
378 std::atomic<uint64_t> queries{0};
381 double queryLoad{0.0};
382 double dropRate{0.0};
383 double latencyUsec{0.0};
386 int tcpRecvTimeout{30};
387 int tcpSendTimeout{30};
388 unsigned int sourceItf{0};
390 uint8_t currentCheckFailures{0};
391 uint8_t maxCheckFailures{1};
394 enum class Availability { Up, Down, Auto} availability{Availability::Auto};
395 bool mustResolve{false};
396 bool upStatus{false};
401 if(availability == Availability::Down)
403 if(availability == Availability::Up)
407 void setUp() { availability = Availability::Up; }
408 void setDown() { availability = Availability::Down; }
409 void setAuto() { availability = Availability::Auto; }
410 string getName() const {
412 return remote.toStringWithPort();
416 string getNameWithAddr() const {
418 return remote.toStringWithPort();
420 return name + " (" + remote.toStringWithPort()+ ")";
424 using servers_t =vector<std::shared_ptr<DownstreamState>>;
428 DNSQuestion(const DNSName* name, uint16_t type, uint16_t class_, const ComboAddress* lc, const ComboAddress* rem, struct dnsheader* header, size_t bufferSize, uint16_t queryLen, bool isTcp): qname(name), qtype(type), qclass(class_), local(lc), remote(rem), dh(header), size(bufferSize), len(queryLen), tcp(isTcp) { }
431 boost::uuids::uuid uniqueId;
433 const DNSName* qname;
434 const uint16_t qtype;
435 const uint16_t qclass;
436 const ComboAddress* local;
437 const ComboAddress* remote;
438 struct dnsheader* dh;
442 bool skipCache{false};
445 struct DNSResponse : DNSQuestion
447 DNSResponse(const DNSName* name, uint16_t type, uint16_t class_, const ComboAddress* lc, const ComboAddress* rem, struct dnsheader* header, size_t bufferSize, uint16_t queryLen, bool isTcp, const struct timespec* queryTime_): DNSQuestion(name, type, class_, lc, rem, header, bufferSize, queryLen, isTcp), queryTime(queryTime_) { }
449 const struct timespec* queryTime;
452 typedef std::function<bool(const DNSQuestion*)> blockfilter_t;
453 template <class T> using NumberedVector = std::vector<std::pair<unsigned int, T> >;
455 void* responderThread(std::shared_ptr<DownstreamState> state);
456 extern std::mutex g_luamutex;
457 extern LuaContext g_lua;
458 extern std::string g_outputBuffer; // locking for this is ok, as locked by g_luamutex
463 virtual bool matches(const DNSQuestion* dq) const =0;
464 virtual string toString() const = 0;
465 mutable std::atomic<uint64_t> d_matches{0};
468 /* so what could you do:
471 provide actual answer,
472 allow & and stop processing,
474 modify header: (servfail|refused|notimp), set TC=1,
480 enum class Action { Drop, Nxdomain, Spoof, Allow, HeaderModify, Pool, Delay, None};
481 virtual Action operator()(DNSQuestion*, string* ruleresult) const =0;
482 virtual string toString() const = 0;
483 virtual std::unordered_map<string, double> getStats() const
489 class DNSResponseAction
492 enum class Action { Allow, Delay, Drop, HeaderModify, None };
493 virtual Action operator()(DNSResponse*, string* ruleresult) const =0;
494 virtual string toString() const = 0;
497 using NumberedServerVector = NumberedVector<shared_ptr<DownstreamState>>;
498 typedef std::function<shared_ptr<DownstreamState>(const NumberedServerVector& servers, const DNSQuestion*)> policyfunc_t;
508 const std::shared_ptr<DNSDistPacketCache> getCache() const { return packetCache; };
510 NumberedVector<shared_ptr<DownstreamState>> servers;
511 std::shared_ptr<DNSDistPacketCache> packetCache{nullptr};
513 using pools_t=map<std::string,std::shared_ptr<ServerPool>>;
514 void addServerToPool(pools_t& pools, const string& poolName, std::shared_ptr<DownstreamState> server);
515 void removeServerFromPool(pools_t& pools, const string& poolName, std::shared_ptr<DownstreamState> server);
521 unsigned int interval;
524 enum ednsHeaderFlags {
525 EDNS_HEADER_FLAG_NONE = 0,
526 EDNS_HEADER_FLAG_DO = 32768
529 /* Quest in life: serve as a rapid block list. If you add a DNSName to a root SuffixMatchNode,
530 anything part of that domain will return 'true' in check */
532 struct SuffixMatchTree
534 SuffixMatchTree(const std::string& name_="", bool endNode_=false) : name(name_), endNode(endNode_)
537 SuffixMatchTree(const SuffixMatchTree& rhs)
540 d_human = rhs.d_human;
541 children = rhs.children;
542 endNode = rhs.endNode;
543 d_value = rhs.d_value;
547 mutable std::set<SuffixMatchTree> children;
548 mutable bool endNode;
550 bool operator<(const SuffixMatchTree& rhs) const
552 return strcasecmp(name.c_str(), rhs.name.c_str()) < 0;
554 typedef SuffixMatchTree value_type;
557 void visit(const V& v) const {
558 for(const auto& c : children)
564 void add(const DNSName& name, const T& t)
566 add(name.getRawLabels(), t);
569 void add(std::vector<std::string> labels, const T& value) const
571 if(labels.empty()) { // this allows insertion of the root
575 else if(labels.size()==1) {
576 SuffixMatchTree newChild(*labels.begin(), true);
577 newChild.d_value=value;
578 children.insert(newChild);
581 SuffixMatchTree newnode(*labels.rbegin(), false);
582 auto res=children.insert(newnode);
584 children.erase(newnode);
585 res=children.insert(newnode);
588 res.first->add(labels, value);
592 T* lookup(const DNSName& name) const
594 if(children.empty()) { // speed up empty set
599 return lookup(name.getRawLabels());
602 T* lookup(std::vector<std::string> labels) const
604 if(labels.empty()) { // optimization
610 SuffixMatchTree smn(*labels.rbegin());
611 auto child = children.find(smn);
612 if(child == children.end()) {
618 return child->lookup(labels);
623 extern GlobalStateHolder<SuffixMatchTree<DynBlock>> g_dynblockSMT;
625 extern GlobalStateHolder<vector<CarbonConfig> > g_carbon;
626 extern GlobalStateHolder<ServerPolicy> g_policy;
627 extern GlobalStateHolder<servers_t> g_dstates;
628 extern GlobalStateHolder<pools_t> g_pools;
629 extern GlobalStateHolder<vector<pair<std::shared_ptr<DNSRule>, std::shared_ptr<DNSAction> > > > g_rulactions;
630 extern GlobalStateHolder<vector<pair<std::shared_ptr<DNSRule>, std::shared_ptr<DNSResponseAction> > > > g_resprulactions;
631 extern GlobalStateHolder<NetmaskGroup> g_ACL;
633 extern ComboAddress g_serverControl; // not changed during runtime
635 extern std::vector<std::tuple<ComboAddress, bool, bool, int>> g_locals; // not changed at runtime (we hope XXX)
636 extern vector<ClientState*> g_frontends;
637 extern std::string g_key; // in theory needs locking
638 extern bool g_truncateTC;
639 extern bool g_fixupCase;
640 extern int g_tcpRecvTimeout;
641 extern int g_tcpSendTimeout;
642 extern uint16_t g_maxOutstanding;
643 extern std::atomic<bool> g_configurationDone;
644 extern uint64_t g_maxTCPClientThreads;
645 extern uint64_t g_maxTCPQueuedConnections;
646 extern std::atomic<uint16_t> g_cacheCleaningDelay;
647 extern uint16_t g_ECSSourcePrefixV4;
648 extern uint16_t g_ECSSourcePrefixV6;
649 extern bool g_ECSOverride;
650 extern bool g_verboseHealthChecks;
651 extern uint32_t g_staleCacheEntriesTTL;
653 struct ConsoleKeyword {
656 std::string parameters;
657 std::string description;
658 std::string toString() const
660 std::string res(name);
662 res += "(" + parameters + ")";
669 extern const std::vector<ConsoleKeyword> g_consoleKeywords;
672 extern shared_ptr<BPFFilter> g_defaultBPFFilter;
673 extern std::vector<std::shared_ptr<DynBPFFilter> > g_dynBPFFilters;
674 #endif /* HAVE_EBPF */
678 void controlThread(int fd, ComboAddress local);
679 vector<std::function<void(void)>> setupLua(bool client, const std::string& config);
680 std::shared_ptr<ServerPool> getPool(const pools_t& pools, const std::string& poolName);
681 std::shared_ptr<ServerPool> createPoolIfNotExists(pools_t& pools, const string& poolName);
682 const NumberedServerVector& getDownstreamCandidates(const pools_t& pools, const std::string& poolName);
684 std::shared_ptr<DownstreamState> firstAvailable(const NumberedServerVector& servers, const DNSQuestion* dq);
686 std::shared_ptr<DownstreamState> leastOutstanding(const NumberedServerVector& servers, const DNSQuestion* dq);
687 std::shared_ptr<DownstreamState> wrandom(const NumberedServerVector& servers, const DNSQuestion* dq);
688 std::shared_ptr<DownstreamState> whashed(const NumberedServerVector& servers, const DNSQuestion* dq);
689 std::shared_ptr<DownstreamState> roundrobin(const NumberedServerVector& servers, const DNSQuestion* dq);
690 int getEDNSZ(const char* packet, unsigned int len);
691 void spoofResponseFromString(DNSQuestion& dq, const string& spoofContent);
692 uint16_t getEDNSOptionCode(const char * packet, size_t len);
693 void dnsdistWebserverThread(int sock, const ComboAddress& local, const string& password, const string& apiKey, const boost::optional<std::map<std::string, std::string> >&);
694 bool getMsgLen32(int fd, uint32_t* len);
695 bool putMsgLen32(int fd, uint32_t len);
696 void* tcpAcceptorThread(void* p);
698 void moreLua(bool client);
699 void doClient(ComboAddress server, const std::string& command);
701 void controlClientThread(int fd, ComboAddress client);
703 char** my_completion( const char * text , int start, int end);
705 void setLuaNoSideEffect(); // if nothing has been declared, set that there are no side effects
706 void setLuaSideEffect(); // set to report a side effect, cancelling all _no_ side effect calls
707 bool getLuaNoSideEffect(); // set if there were only explicit declarations of _no_ side effect
708 void resetLuaSideEffect(); // reset to indeterminate state
710 bool responseContentMatches(const char* response, const uint16_t responseLen, const DNSName& qname, const uint16_t qtype, const uint16_t qclass, const ComboAddress& remote);
711 bool processQuery(LocalStateHolder<NetmaskTree<DynBlock> >& localDynBlockNMG,
712 LocalStateHolder<SuffixMatchTree<DynBlock> >& localDynBlockSMT, LocalStateHolder<vector<pair<std::shared_ptr<DNSRule>, std::shared_ptr<DNSAction> > > >& localRulactions, blockfilter_t blockFilter, DNSQuestion& dq, string& poolname, int* delayMsec, const struct timespec& now);
713 bool processResponse(LocalStateHolder<vector<pair<std::shared_ptr<DNSRule>, std::shared_ptr<DNSResponseAction> > > >& localRespRulactions, DNSResponse& dr, int* delayMsec);
714 bool fixUpResponse(char** response, uint16_t* responseLen, size_t* responseSize, const DNSName& qname, uint16_t origFlags, bool ednsAdded, bool ecsAdded, std::vector<uint8_t>& rewrittenResponse, uint16_t addRoom);
715 void restoreFlags(struct dnsheader* dh, uint16_t origFlags);
718 extern std::vector<std::tuple<ComboAddress,DnsCryptContext,bool,int>> g_dnsCryptLocals;
720 int handleDnsCryptQuery(DnsCryptContext* ctx, char* packet, uint16_t len, std::shared_ptr<DnsCryptQuery>& query, uint16_t* decryptedQueryLen, bool tcp, std::vector<uint8_t>& reponse);
721 bool encryptResponse(char* response, uint16_t* responseLen, size_t responseSize, bool tcp, std::shared_ptr<DnsCryptQuery> dnsCryptQuery);