]> git.ipfire.org Git - thirdparty/pdns.git/blame - pdns/dnsdist.hh
Merge pull request #4740 from Habbie/fix-show-zone-ds
[thirdparty/pdns.git] / pdns / dnsdist.hh
CommitLineData
12471842
PL
1/*
2 * This file is part of PowerDNS or dnsdist.
3 * Copyright -- PowerDNS.COM B.V. and its contributors
4 *
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.
8 *
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.
12 *
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.
17 *
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.
21 */
df111b53 22#pragma once
11e1e08b 23#include "config.h"
df111b53 24#include "ext/luawrapper/include/LuaContext.hpp"
25#include <time.h>
26#include "misc.hh"
27#include "iputils.hh"
28#include "dnsname.hh"
29#include <atomic>
30#include <boost/circular_buffer.hpp>
e16fd59c 31#include <boost/variant.hpp>
df111b53 32#include <mutex>
33#include <thread>
bffca8b9 34#include <unistd.h>
ecbe9133 35#include "sholder.hh"
11e1e08b 36#include "dnscrypt.hh"
886e2cf2 37#include "dnsdist-cache.hh"
85c7ca75 38#include "gettime.hh"
87b515ed
RG
39#include "dnsdist-dynbpf.hh"
40#include "bpf-filter.hh"
1ea747c0 41
d8c19b98
RG
42#ifdef HAVE_PROTOBUF
43#include <boost/uuid/uuid.hpp>
44#include <boost/uuid/uuid_generators.hpp>
45#endif
46
42fae326 47void* carbonDumpThread();
61d1b966 48uint64_t uptimeOfProcess(const std::string& str);
bd1c631b 49
78ffa782 50struct DynBlock
51{
52 DynBlock& operator=(const DynBlock& rhs)
53 {
54 reason=rhs.reason;
55 until=rhs.until;
71c94675 56 domain=rhs.domain;
78ffa782 57 blocks.store(rhs.blocks);
58 return *this;
59 }
71c94675 60
78ffa782 61 string reason;
62 struct timespec until;
71c94675 63 DNSName domain;
78ffa782 64 mutable std::atomic<unsigned int> blocks;
65};
66
67extern GlobalStateHolder<NetmaskTree<DynBlock>> g_dynblockNMG;
f758857a 68
69extern vector<pair<struct timeval, std::string> > g_confDelta;
70
e48090d1 71struct DNSDistStats
72{
6ad8b29a 73 using stat_t=std::atomic<uint64_t>; // aww yiss ;-)
e48090d1 74 stat_t responses{0};
75 stat_t servfailResponses{0};
76 stat_t queries{0};
e73ec7d3 77 stat_t nonCompliantQueries{0};
d08b1cdf 78 stat_t nonCompliantResponses{0};
643a182a 79 stat_t rdQueries{0};
2efd427d 80 stat_t emptyQueries{0};
e48090d1 81 stat_t aclDrops{0};
82 stat_t blockFilter{0};
bd1c631b 83 stat_t dynBlocked{0};
e48090d1 84 stat_t ruleDrop{0};
85 stat_t ruleNXDomain{0};
dd46e5e3 86 stat_t ruleRefused{0};
e48090d1 87 stat_t selfAnswered{0};
88 stat_t downstreamTimeouts{0};
89 stat_t downstreamSendErrors{0};
6ad8b29a 90 stat_t truncFail{0};
b8bc7e61 91 stat_t noPolicy{0};
886e2cf2
RG
92 stat_t cacheHits{0};
93 stat_t cacheMisses{0};
42fae326 94 stat_t latency0_1{0}, latency1_10{0}, latency10_50{0}, latency50_100{0}, latency100_1000{0}, latencySlow{0};
e48090d1 95
e16fd59c 96 double latencyAvg100{0}, latencyAvg1000{0}, latencyAvg10000{0}, latencyAvg1000000{0};
a1a787dc 97 typedef std::function<uint64_t(const std::string&)> statfunction_t;
98 typedef boost::variant<stat_t*, double*, statfunction_t> entry_t;
e16fd59c 99 std::vector<std::pair<std::string, entry_t>> entries{
dd46e5e3
RG
100 {"responses", &responses},
101 {"servfail-responses", &servfailResponses},
102 {"queries", &queries},
103 {"acl-drops", &aclDrops},
104 {"block-filter", &blockFilter},
105 {"rule-drop", &ruleDrop},
106 {"rule-nxdomain", &ruleNXDomain},
107 {"rule-refused", &ruleRefused},
108 {"self-answered", &selfAnswered},
109 {"downstream-timeouts", &downstreamTimeouts},
110 {"downstream-send-errors", &downstreamSendErrors},
111 {"trunc-failures", &truncFail},
112 {"no-policy", &noPolicy},
113 {"latency0-1", &latency0_1},
114 {"latency1-10", &latency1_10},
115 {"latency10-50", &latency10_50},
116 {"latency50-100", &latency50_100},
117 {"latency100-1000", &latency100_1000},
118 {"latency-slow", &latencySlow},
119 {"latency-avg100", &latencyAvg100},
120 {"latency-avg1000", &latencyAvg1000},
121 {"latency-avg10000", &latencyAvg10000},
122 {"latency-avg1000000", &latencyAvg1000000},
61d1b966 123 {"uptime", uptimeOfProcess},
a9b6db56 124 {"real-memory-usage", getRealMemoryUsage},
a2aa00ed 125 {"noncompliant-queries", &nonCompliantQueries},
d08b1cdf 126 {"noncompliant-responses", &nonCompliantResponses},
643a182a 127 {"rdqueries", &rdQueries},
2efd427d 128 {"empty-queries", &emptyQueries},
886e2cf2
RG
129 {"cache-hits", &cacheHits},
130 {"cache-misses", &cacheMisses},
4f99f3d3
RG
131 {"cpu-user-msec", getCPUTimeUser},
132 {"cpu-sys-msec", getCPUTimeSystem},
dd46e5e3
RG
133 {"fd-usage", getOpenFileDescriptors},
134 {"dyn-blocked", &dynBlocked},
bd1c631b 135 {"dyn-block-nmg-size", [](const std::string&) { return g_dynblockNMG.getLocal()->size(); }}
42fae326 136 };
e48090d1 137};
138
e16fd59c 139
e48090d1 140extern struct DNSDistStats g_stats;
141
638184e9 142
df111b53 143struct StopWatch
144{
58307a85
RG
145 StopWatch(bool realTime=false): d_needRealTime(realTime)
146 {
147 }
df111b53 148 struct timespec d_start{0,0};
58307a85
RG
149 bool d_needRealTime{false};
150
df111b53 151 void start() {
58307a85 152 if(gettime(&d_start, d_needRealTime) < 0)
df111b53 153 unixDie("Getting timestamp");
154
155 }
156
157 double udiff() const {
158 struct timespec now;
58307a85 159 if(gettime(&now, d_needRealTime) < 0)
df111b53 160 unixDie("Getting timestamp");
161
162 return 1000000.0*(now.tv_sec - d_start.tv_sec) + (now.tv_nsec - d_start.tv_nsec)/1000.0;
163 }
164
165 double udiffAndSet() {
166 struct timespec now;
58307a85 167 if(gettime(&now, d_needRealTime) < 0)
df111b53 168 unixDie("Getting timestamp");
169
170 auto ret= 1000000.0*(now.tv_sec - d_start.tv_sec) + (now.tv_nsec - d_start.tv_nsec)/1000.0;
171 d_start = now;
172 return ret;
173 }
174
175};
176
177class QPSLimiter
178{
179public:
180 QPSLimiter()
181 {
182 }
183
184 QPSLimiter(unsigned int rate, unsigned int burst) : d_rate(rate), d_burst(burst), d_tokens(burst)
185 {
186 d_passthrough=false;
187 d_prev.start();
188 }
189
190 unsigned int getRate() const
191 {
192 return d_passthrough? 0 : d_rate;
193 }
194
195 int getPassed() const
196 {
197 return d_passed;
198 }
199 int getBlocked() const
200 {
201 return d_blocked;
202 }
203
ecbe9133 204 bool check() const // this is not quite fair
df111b53 205 {
206 if(d_passthrough)
207 return true;
208 auto delta = d_prev.udiffAndSet();
209
210 d_tokens += 1.0*d_rate * (delta/1000000.0);
211
212 if(d_tokens > d_burst)
213 d_tokens = d_burst;
214
215 bool ret=false;
216 if(d_tokens >= 1.0) { // we need this because burst=1 is weird otherwise
217 ret=true;
218 --d_tokens;
219 d_passed++;
220 }
221 else
222 d_blocked++;
223
224 return ret;
225 }
226private:
227 bool d_passthrough{true};
228 unsigned int d_rate;
229 unsigned int d_burst;
ecbe9133 230 mutable double d_tokens;
231 mutable StopWatch d_prev;
232 mutable unsigned int d_passed{0};
233 mutable unsigned int d_blocked{0};
df111b53 234};
235
df111b53 236struct IDState
237{
58307a85 238 IDState() : origFD(-1), sentTime(true), delayMsec(0) { origDest.sin4.sin_family = 0;}
df111b53 239 IDState(const IDState& orig)
240 {
241 origFD = orig.origFD;
242 origID = orig.origID;
243 origRemote = orig.origRemote;
549d63c9 244 origDest = orig.origDest;
7b3865cd 245 delayMsec = orig.delayMsec;
df111b53 246 age.store(orig.age.load());
247 }
248
2bf26975 249 int origFD; // set to <0 to indicate this state is empty // 4
250
251 ComboAddress origRemote; // 28
549d63c9 252 ComboAddress origDest; // 28
2bf26975 253 StopWatch sentTime; // 16
254 DNSName qname; // 80
11e1e08b
RG
255#ifdef HAVE_DNSCRYPT
256 std::shared_ptr<DnsCryptQuery> dnsCryptQuery{0};
d8c19b98
RG
257#endif
258#ifdef HAVE_PROTOBUF
259 boost::uuids::uuid uniqueId;
11e1e08b 260#endif
886e2cf2
RG
261 std::shared_ptr<DNSDistPacketCache> packetCache{nullptr};
262 uint32_t cacheKey; // 8
2bf26975 263 std::atomic<uint16_t> age; // 4
264 uint16_t qtype; // 2
886e2cf2 265 uint16_t qclass; // 2
2bf26975 266 uint16_t origID; // 2
aeb36780 267 uint16_t origFlags; // 2
7b3865cd 268 int delayMsec;
ca404e94 269 bool ednsAdded{false};
ff73f02b 270 bool ecsAdded{false};
886e2cf2 271 bool skipCache{false};
7cea4e39 272 bool destHarvested{false}; // if true, origDest holds the original dest addr, otherwise the listening addr
df111b53 273};
274
275struct Rings {
276 Rings()
277 {
df111b53 278 queryRing.set_capacity(10000);
279 respRing.set_capacity(10000);
0e41337b 280 pthread_rwlock_init(&queryLock, 0);
df111b53 281 }
0ba5eecf 282 struct Query
283 {
284 struct timespec when;
285 ComboAddress requestor;
286 DNSName name;
03ebf8b2 287 uint16_t size;
0ba5eecf 288 uint16_t qtype;
3fcaeeac 289 struct dnsheader dh;
0ba5eecf 290 };
291 boost::circular_buffer<Query> queryRing;
df111b53 292 struct Response
293 {
80a216c9 294 struct timespec when;
295 ComboAddress requestor;
df111b53 296 DNSName name;
297 uint16_t qtype;
df111b53 298 unsigned int usec;
80a216c9 299 unsigned int size;
3fcaeeac 300 struct dnsheader dh;
2d11d1b2 301 ComboAddress ds; // who handled it
df111b53 302 };
303 boost::circular_buffer<Response> respRing;
304 std::mutex respMutex;
0e41337b 305 pthread_rwlock_t queryLock;
03ebf8b2 306
7fc00937 307 std::unordered_map<int, vector<boost::variant<string,double> > > getTopBandwidth(unsigned int numentries);
a683e8bd 308 size_t numDistinctRequestors();
df111b53 309};
310
0e41337b 311extern Rings g_rings;
df111b53 312
786e4d8c
RS
313typedef std::unordered_map<string, unsigned int> QueryCountRecords;
314typedef std::function<std::tuple<bool, string>(DNSQuestion dq)> QueryCountFilter;
315struct QueryCount {
316 QueryCount()
317 {
318 pthread_rwlock_init(&queryLock, 0);
319 }
320 QueryCountRecords records;
321 QueryCountFilter filter;
322 pthread_rwlock_t queryLock;
323 bool enabled{false};
324};
325
326extern QueryCount g_qcount;
327
8a5d5053 328struct ClientState
329{
330 ComboAddress local;
11e1e08b
RG
331#ifdef HAVE_DNSCRYPT
332 DnsCryptContext* dnscryptCtx{0};
333#endif
963bef8d 334 std::atomic<uint64_t> queries{0};
a36ce055
RG
335 int udpFD{-1};
336 int tcpFD{-1};
8429ad04
RG
337
338 int getSocket() const
339 {
340 return udpFD != -1 ? udpFD : tcpFD;
341 }
342
343#ifdef HAVE_EBPF
344 shared_ptr<BPFFilter> d_filter;
345
346 void detachFilter()
347 {
348 if (d_filter) {
349 d_filter->removeSocket(getSocket());
350 d_filter = nullptr;
351 }
352 }
353
354 void attachFilter(shared_ptr<BPFFilter> bpf)
355 {
356 detachFilter();
357
358 bpf->addSocket(getSocket());
359 d_filter = bpf;
360 }
361#endif /* HAVE_EBPF */
8a5d5053 362};
363
364class TCPClientCollection {
365 std::vector<int> d_tcpclientthreads;
a9bf3ec4 366 std::atomic<uint64_t> d_pos{0};
8a5d5053 367public:
a9bf3ec4 368 std::atomic<uint64_t> d_queued{0}, d_numthreads{0};
6c1ca990 369 uint64_t d_maxthreads{0};
8a5d5053 370
a9bf3ec4 371 TCPClientCollection(size_t maxThreads)
8a5d5053 372 {
6c1ca990 373 d_maxthreads = maxThreads;
a9bf3ec4 374 d_tcpclientthreads.reserve(maxThreads);
8a5d5053 375 }
376
a9bf3ec4 377 int getThread()
8a5d5053 378 {
6c1ca990 379 uint64_t pos = d_pos++;
8a5d5053 380 ++d_queued;
381 return d_tcpclientthreads[pos % d_numthreads];
382 }
383 void addTCPClientThread();
384};
385
a9bf3ec4 386extern std::shared_ptr<TCPClientCollection> g_tcpclientthreads;
8a5d5053 387
df111b53 388struct DownstreamState
389{
fbe2a2e0
RG
390 DownstreamState(const ComboAddress& remote_, const ComboAddress& sourceAddr_, unsigned int sourceItf);
391 DownstreamState(const ComboAddress& remote_): DownstreamState(remote_, ComboAddress(), 0) {}
6a62c0e3
RG
392 ~DownstreamState()
393 {
394 if (fd >= 0)
395 close(fd);
396 }
df111b53 397
f99e3aaf 398 int fd{-1};
df111b53 399 std::thread tid;
400 ComboAddress remote;
401 QPSLimiter qps;
402 vector<IDState> idStates;
fbe2a2e0
RG
403 ComboAddress sourceAddr;
404 DNSName checkName{"a.root-servers.net."};
405 QType checkType{QType::A};
df111b53 406 std::atomic<uint64_t> idOffset{0};
407 std::atomic<uint64_t> sendErrors{0};
408 std::atomic<uint64_t> outstanding{0};
409 std::atomic<uint64_t> reuseds{0};
410 std::atomic<uint64_t> queries{0};
411 struct {
412 std::atomic<uint64_t> sendErrors{0};
413 std::atomic<uint64_t> reuseds{0};
414 std::atomic<uint64_t> queries{0};
415 } prev;
18eeccc9 416 string name;
df111b53 417 double queryLoad{0.0};
418 double dropRate{0.0};
419 double latencyUsec{0.0};
420 int order{1};
421 int weight{1};
3f6d07a4
RG
422 int tcpRecvTimeout{30};
423 int tcpSendTimeout{30};
fbe2a2e0 424 unsigned int sourceItf{0};
3f6d07a4 425 uint16_t retries{5};
9e87dcb8
RG
426 uint8_t currentCheckFailures{0};
427 uint8_t maxCheckFailures{1};
df111b53 428 StopWatch sw;
429 set<string> pools;
430 enum class Availability { Up, Down, Auto} availability{Availability::Auto};
fbe2a2e0 431 bool mustResolve{false};
df111b53 432 bool upStatus{false};
ca404e94 433 bool useECS{false};
21830638 434 bool setCD{false};
df111b53 435 bool isUp() const
436 {
437 if(availability == Availability::Down)
438 return false;
439 if(availability == Availability::Up)
440 return true;
441 return upStatus;
442 }
443 void setUp() { availability = Availability::Up; }
444 void setDown() { availability = Availability::Down; }
445 void setAuto() { availability = Availability::Auto; }
18eeccc9
RG
446 string getName() const {
447 if (name.empty()) {
448 return remote.toStringWithPort();
449 }
450 return name;
451 }
a7940c06 452 string getNameWithAddr() const {
453 if (name.empty()) {
454 return remote.toStringWithPort();
455 }
456 return name + " (" + remote.toStringWithPort()+ ")";
457 }
458
df111b53 459};
460using servers_t =vector<std::shared_ptr<DownstreamState>>;
df111b53 461
ff0902ec
RG
462extern uint16_t g_ECSSourcePrefixV4;
463extern uint16_t g_ECSSourcePrefixV6;
464extern bool g_ECSOverride;
465
497a6e3a
RG
466struct DNSQuestion
467{
ff0902ec 468 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), ecsPrefixLength(rem->sin4.sin_family == AF_INET ? g_ECSSourcePrefixV4 : g_ECSSourcePrefixV6), tcp(isTcp), ecsOverride(g_ECSOverride) { }
497a6e3a 469
d8c19b98
RG
470#ifdef HAVE_PROTOBUF
471 boost::uuids::uuid uniqueId;
472#endif
497a6e3a
RG
473 const DNSName* qname;
474 const uint16_t qtype;
cec47783 475 const uint16_t qclass;
497a6e3a
RG
476 const ComboAddress* local;
477 const ComboAddress* remote;
478 struct dnsheader* dh;
479 size_t size;
480 uint16_t len;
ff0902ec 481 uint16_t ecsPrefixLength;
497a6e3a 482 const bool tcp;
886e2cf2 483 bool skipCache{false};
ff0902ec
RG
484 bool ecsOverride;
485 bool useECS{true};
497a6e3a
RG
486};
487
58307a85
RG
488struct DNSResponse : DNSQuestion
489{
490 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_) { }
491
492 const struct timespec* queryTime;
493};
494
e91084ce 495typedef std::function<bool(const DNSQuestion*)> blockfilter_t;
da4e7813 496template <class T> using NumberedVector = std::vector<std::pair<unsigned int, T> >;
497
498void* responderThread(std::shared_ptr<DownstreamState> state);
499extern std::mutex g_luamutex;
500extern LuaContext g_lua;
501extern std::string g_outputBuffer; // locking for this is ok, as locked by g_luamutex
502
0940e4eb 503class DNSRule
504{
505public:
497a6e3a 506 virtual bool matches(const DNSQuestion* dq) const =0;
0940e4eb 507 virtual string toString() const = 0;
508 mutable std::atomic<uint64_t> d_matches{0};
509};
510
511/* so what could you do:
512 drop,
513 fake up nxdomain,
514 provide actual answer,
515 allow & and stop processing,
516 continue processing,
517 modify header: (servfail|refused|notimp), set TC=1,
518 send to pool */
519
520class DNSAction
521{
522public:
dd46e5e3 523 enum class Action { Drop, Nxdomain, Refused, Spoof, Allow, HeaderModify, Pool, Delay, None};
497a6e3a 524 virtual Action operator()(DNSQuestion*, string* ruleresult) const =0;
0940e4eb 525 virtual string toString() const = 0;
cf6874ba 526 virtual std::unordered_map<string, double> getStats() const
527 {
528 return {{}};
529 }
0940e4eb 530};
531
8146444b
RG
532class DNSResponseAction
533{
534public:
788c3243 535 enum class Action { Allow, Delay, Drop, HeaderModify, None };
58307a85 536 virtual Action operator()(DNSResponse*, string* ruleresult) const =0;
8146444b
RG
537 virtual string toString() const = 0;
538};
539
da4e7813 540using NumberedServerVector = NumberedVector<shared_ptr<DownstreamState>>;
497a6e3a 541typedef std::function<shared_ptr<DownstreamState>(const NumberedServerVector& servers, const DNSQuestion*)> policyfunc_t;
df111b53 542
543struct ServerPolicy
544{
545 string name;
70a57b05 546 policyfunc_t policy;
df111b53 547};
548
886e2cf2
RG
549struct ServerPool
550{
551 const std::shared_ptr<DNSDistPacketCache> getCache() const { return packetCache; };
552
553 NumberedVector<shared_ptr<DownstreamState>> servers;
554 std::shared_ptr<DNSDistPacketCache> packetCache{nullptr};
555};
556using pools_t=map<std::string,std::shared_ptr<ServerPool>>;
557void addServerToPool(pools_t& pools, const string& poolName, std::shared_ptr<DownstreamState> server);
558void removeServerFromPool(pools_t& pools, const string& poolName, std::shared_ptr<DownstreamState> server);
559
42fae326 560struct CarbonConfig
561{
d617b22c 562 ComboAddress server;
42fae326 563 std::string ourname;
d617b22c 564 unsigned int interval;
42fae326 565};
566
ca404e94
RG
567enum ednsHeaderFlags {
568 EDNS_HEADER_FLAG_NONE = 0,
569 EDNS_HEADER_FLAG_DO = 32768
570};
571
71c94675 572/* Quest in life: serve as a rapid block list. If you add a DNSName to a root SuffixMatchNode,
573 anything part of that domain will return 'true' in check */
574template<typename T>
575struct SuffixMatchTree
576{
577 SuffixMatchTree(const std::string& name_="", bool endNode_=false) : name(name_), endNode(endNode_)
578 {}
579
580 SuffixMatchTree(const SuffixMatchTree& rhs)
581 {
582 name = rhs.name;
583 d_human = rhs.d_human;
584 children = rhs.children;
585 endNode = rhs.endNode;
586 d_value = rhs.d_value;
587 }
588 std::string name;
589 std::string d_human;
590 mutable std::set<SuffixMatchTree> children;
591 mutable bool endNode;
592 mutable T d_value;
593 bool operator<(const SuffixMatchTree& rhs) const
594 {
595 return strcasecmp(name.c_str(), rhs.name.c_str()) < 0;
596 }
597 typedef SuffixMatchTree value_type;
598
599 template<typename V>
600 void visit(const V& v) const {
601 for(const auto& c : children)
602 c.visit(v);
603 if(endNode)
604 v(*this);
605 }
606
607 void add(const DNSName& name, const T& t)
608 {
609 add(name.getRawLabels(), t);
610 }
611
612 void add(std::vector<std::string> labels, const T& value) const
613 {
614 if(labels.empty()) { // this allows insertion of the root
615 endNode=true;
616 d_value=value;
617 }
618 else if(labels.size()==1) {
619 SuffixMatchTree newChild(*labels.begin(), true);
620 newChild.d_value=value;
621 children.insert(newChild);
622 }
623 else {
624 SuffixMatchTree newnode(*labels.rbegin(), false);
625 auto res=children.insert(newnode);
626 if(!res.second) {
627 children.erase(newnode);
628 res=children.insert(newnode);
629 }
630 labels.pop_back();
631 res.first->add(labels, value);
632 }
633 }
634
635 T* lookup(const DNSName& name) const
636 {
637 if(children.empty()) { // speed up empty set
638 if(endNode)
639 return &d_value;
640 return 0;
641 }
642 return lookup(name.getRawLabels());
643 }
644
645 T* lookup(std::vector<std::string> labels) const
646 {
647 if(labels.empty()) { // optimization
648 if(endNode)
649 return &d_value;
650 return 0;
651 }
652
653 SuffixMatchTree smn(*labels.rbegin());
654 auto child = children.find(smn);
655 if(child == children.end()) {
656 if(endNode)
657 return &d_value;
658 return 0;
659 }
660 labels.pop_back();
661 return child->lookup(labels);
662 }
663
664};
665
666extern GlobalStateHolder<SuffixMatchTree<DynBlock>> g_dynblockSMT;
dd46e5e3 667extern DNSAction::Action g_dynBlockAction;
71c94675 668
d617b22c 669extern GlobalStateHolder<vector<CarbonConfig> > g_carbon;
ecbe9133 670extern GlobalStateHolder<ServerPolicy> g_policy;
671extern GlobalStateHolder<servers_t> g_dstates;
886e2cf2 672extern GlobalStateHolder<pools_t> g_pools;
0940e4eb 673extern GlobalStateHolder<vector<pair<std::shared_ptr<DNSRule>, std::shared_ptr<DNSAction> > > > g_rulactions;
8146444b 674extern GlobalStateHolder<vector<pair<std::shared_ptr<DNSRule>, std::shared_ptr<DNSResponseAction> > > > g_resprulactions;
638184e9 675extern GlobalStateHolder<NetmaskGroup> g_ACL;
2e72cc0e 676
ecbe9133 677extern ComboAddress g_serverControl; // not changed during runtime
678
9e284f31 679extern std::vector<std::tuple<ComboAddress, bool, bool, int>> g_locals; // not changed at runtime (we hope XXX)
963bef8d 680extern vector<ClientState*> g_frontends;
ecbe9133 681extern std::string g_key; // in theory needs locking
6ad8b29a 682extern bool g_truncateTC;
b29edbee 683extern bool g_fixupCase;
3f6d07a4
RG
684extern int g_tcpRecvTimeout;
685extern int g_tcpSendTimeout;
e41f8165
RG
686extern uint16_t g_maxOutstanding;
687extern std::atomic<bool> g_configurationDone;
6c1ca990
RG
688extern uint64_t g_maxTCPClientThreads;
689extern uint64_t g_maxTCPQueuedConnections;
886e2cf2 690extern std::atomic<uint16_t> g_cacheCleaningDelay;
9e87dcb8 691extern bool g_verboseHealthChecks;
1ea747c0 692extern uint32_t g_staleCacheEntriesTTL;
56d68fad
RG
693extern bool g_apiReadWrite;
694extern std::string g_apiConfigDirectory;
ca404e94 695
ca4252e0
RG
696struct ConsoleKeyword {
697 std::string name;
698 bool function;
699 std::string parameters;
700 std::string description;
701 std::string toString() const
702 {
703 std::string res(name);
704 if (function) {
705 res += "(" + parameters + ")";
706 }
707 res += ": ";
708 res += description;
709 return res;
710 }
711};
712extern const std::vector<ConsoleKeyword> g_consoleKeywords;
713
87b515ed
RG
714#ifdef HAVE_EBPF
715extern shared_ptr<BPFFilter> g_defaultBPFFilter;
8429ad04 716extern std::vector<std::shared_ptr<DynBPFFilter> > g_dynBPFFilters;
87b515ed
RG
717#endif /* HAVE_EBPF */
718
ecbe9133 719struct dnsheader;
720
721void controlThread(int fd, ComboAddress local);
839f3021 722vector<std::function<void(void)>> setupLua(bool client, const std::string& config);
886e2cf2
RG
723std::shared_ptr<ServerPool> getPool(const pools_t& pools, const std::string& poolName);
724std::shared_ptr<ServerPool> createPoolIfNotExists(pools_t& pools, const string& poolName);
725const NumberedServerVector& getDownstreamCandidates(const pools_t& pools, const std::string& poolName);
da4e7813 726
497a6e3a 727std::shared_ptr<DownstreamState> firstAvailable(const NumberedServerVector& servers, const DNSQuestion* dq);
ecbe9133 728
497a6e3a
RG
729std::shared_ptr<DownstreamState> leastOutstanding(const NumberedServerVector& servers, const DNSQuestion* dq);
730std::shared_ptr<DownstreamState> wrandom(const NumberedServerVector& servers, const DNSQuestion* dq);
731std::shared_ptr<DownstreamState> whashed(const NumberedServerVector& servers, const DNSQuestion* dq);
732std::shared_ptr<DownstreamState> roundrobin(const NumberedServerVector& servers, const DNSQuestion* dq);
520eb5a0 733int getEDNSZ(const char* packet, unsigned int len);
6ca7a40a 734void spoofResponseFromString(DNSQuestion& dq, const string& spoofContent);
ca404e94 735uint16_t getEDNSOptionCode(const char * packet, size_t len);
002decab 736void dnsdistWebserverThread(int sock, const ComboAddress& local, const string& password, const string& apiKey, const boost::optional<std::map<std::string, std::string> >&);
6885d4bf 737bool getMsgLen32(int fd, uint32_t* len);
738bool putMsgLen32(int fd, uint32_t len);
d8d85a30 739void* tcpAcceptorThread(void* p);
80a216c9 740
886e2cf2 741void moreLua(bool client);
ffb07158 742void doClient(ComboAddress server, const std::string& command);
743void doConsole();
744void controlClientThread(int fd, ComboAddress client);
745extern "C" {
746char** my_completion( const char * text , int start, int end);
747}
f758857a 748void setLuaNoSideEffect(); // if nothing has been declared, set that there are no side effects
749void setLuaSideEffect(); // set to report a side effect, cancelling all _no_ side effect calls
750bool getLuaNoSideEffect(); // set if there were only explicit declarations of _no_ side effect
751void resetLuaSideEffect(); // reset to indeterminate state
11e1e08b 752
fcffc585 753bool responseContentMatches(const char* response, const uint16_t responseLen, const DNSName& qname, const uint16_t qtype, const uint16_t qclass, const ComboAddress& remote);
71c94675 754bool processQuery(LocalStateHolder<NetmaskTree<DynBlock> >& localDynBlockNMG,
755 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);
788c3243 756bool processResponse(LocalStateHolder<vector<pair<std::shared_ptr<DNSRule>, std::shared_ptr<DNSResponseAction> > > >& localRespRulactions, DNSResponse& dr, int* delayMsec);
ff73f02b 757bool 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);
0f72fd5c 758void restoreFlags(struct dnsheader* dh, uint16_t origFlags);
fcffc585 759
11e1e08b 760#ifdef HAVE_DNSCRYPT
9e284f31 761extern std::vector<std::tuple<ComboAddress,DnsCryptContext,bool,int>> g_dnsCryptLocals;
11e1e08b
RG
762
763int handleDnsCryptQuery(DnsCryptContext* ctx, char* packet, uint16_t len, std::shared_ptr<DnsCryptQuery>& query, uint16_t* decryptedQueryLen, bool tcp, std::vector<uint8_t>& reponse);
0f72fd5c 764bool encryptResponse(char* response, uint16_t* responseLen, size_t responseSize, bool tcp, std::shared_ptr<DnsCryptQuery> dnsCryptQuery);
11e1e08b 765#endif