]> git.ipfire.org Git - thirdparty/pdns.git/blame - pdns/syncres.hh
Merge pull request #7094 from neilcook/udr
[thirdparty/pdns.git] / pdns / syncres.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 */
32cdc494 22#pragma once
00a19ff7 23#include <string>
aebb81e4 24#include <atomic>
3897b9e1 25#include "utility.hh"
00a19ff7
BH
26#include "dns.hh"
27#include "qtype.hh"
28#include <vector>
29#include <set>
9ea28e46 30#include <unordered_set>
00a19ff7 31#include <map>
eefd15f9
BH
32#include <cmath>
33#include <iostream>
34#include <utility>
c836dc19 35#include "misc.hh"
00a19ff7 36#include "lwres.hh"
4898a348 37#include <boost/optional.hpp>
92011b8f 38#include <boost/circular_buffer.hpp>
d6d5dea7 39#include <boost/utility.hpp>
1d5b3ce6 40#include "sstuff.hh"
9fdf67d5 41#include "recursor_cache.hh"
16beeaa4 42#include "recpacketcache.hh"
1d5b3ce6 43#include <boost/tuple/tuple.hpp>
71dea98d 44#include <boost/optional.hpp>
1d5b3ce6
BH
45#include <boost/tuple/tuple_comparison.hpp>
46#include "mtasker.hh"
a9af3782 47#include "iputils.hh"
849fe8d2 48#include "validate.hh"
b40562da 49#include "ednssubnet.hh"
644dd1da 50#include "filterpo.hh"
39ce10b2 51#include "negcache.hh"
644dd1da 52
20642494 53#ifdef HAVE_CONFIG_H
4898a348 54#include "config.h"
20642494
PL
55#endif
56
4898a348
RG
57#ifdef HAVE_PROTOBUF
58#include <boost/uuid/uuid.hpp>
59#include <boost/uuid/uuid_generators.hpp>
60#endif
61
a3e7b735 62class RecursorLua4;
620db2c8 63
fa1b87ff
PL
64typedef map<
65 DNSName,
66 pair<
67 vector<ComboAddress>,
68 bool
69 >
70> NsSet;
49f076e8 71
bb4bdbaf 72template<class Thing> class Throttle : public boost::noncopyable
49f076e8
BH
73{
74public:
75 Throttle()
76 {
77 d_limit=3;
78 d_ttl=60;
79 d_last_clean=time(0);
80 }
96e2f64f 81
82 struct entry
83 {
84 time_t ttd;
85 unsigned int count;
86 };
87 typedef map<Thing,entry> cont_t;
88
87da00e7 89 bool shouldThrottle(time_t now, const Thing& t)
49f076e8 90 {
cd7bf56b 91 if(now > d_last_clean + 300 ) {
bb4bdbaf 92
49f076e8 93 d_last_clean=now;
594c2ee7 94 for(typename cont_t::iterator i=d_cont.begin();i!=d_cont.end();) {
4957a608
BH
95 if( i->second.ttd < now) {
96 d_cont.erase(i++);
97 }
98 else
99 ++i;
594c2ee7 100 }
49f076e8
BH
101 }
102
49f076e8
BH
103 typename cont_t::iterator i=d_cont.find(t);
104 if(i==d_cont.end())
105 return false;
ccb07d93 106 if(now > i->second.ttd || i->second.count == 0) {
49f076e8 107 d_cont.erase(i);
139c2911 108 return false;
49f076e8 109 }
ccb07d93 110 i->second.count--;
014c60c3
BH
111
112 return true; // still listed, still blocked
49f076e8 113 }
3ddb9247 114 void throttle(time_t now, const Thing& t, time_t ttl=0, unsigned int tries=0)
49f076e8
BH
115 {
116 typename cont_t::iterator i=d_cont.find(t);
87da00e7 117 entry e={ now+(ttl ? ttl : d_ttl), tries ? tries : d_limit};
49f076e8 118
c214232f 119 if(i==d_cont.end()) {
49f076e8 120 d_cont[t]=e;
3ddb9247
PD
121 }
122 else if(i->second.ttd > e.ttd || (i->second.count) < e.count)
c214232f 123 d_cont[t]=e;
8a5602d4 124 }
3ddb9247 125
30ee601a 126 unsigned int size() const
8a5602d4 127 {
705f31ae 128 return (unsigned int)d_cont.size();
49f076e8 129 }
30ee601a 130
96e2f64f 131 const cont_t& getThrottleMap() const
132 {
133 return d_cont;
c1e20fba 134 }
135
30ee601a
RG
136 void clear()
137 {
138 d_cont.clear();
139 }
c1e20fba 140
49f076e8 141private:
b747bce8
AT
142 unsigned int d_limit;
143 time_t d_ttl;
49f076e8 144 time_t d_last_clean;
49f076e8
BH
145 cont_t d_cont;
146};
147
148
eefd15f9 149/** Class that implements a decaying EWMA.
36c5ee42 150 This class keeps an exponentially weighted moving average which, additionally, decays over time.
eefd15f9
BH
151 The decaying is only done on get.
152*/
153class DecayingEwma
154{
155public:
3ddb9247 156 DecayingEwma() : d_val(0.0)
71dea98d
BH
157 {
158 d_needinit=true;
118dcc93 159 d_last.tv_sec = d_last.tv_usec = 0;
71dea98d 160 d_lastget=d_last;
36c5ee42 161 }
d6d5dea7 162
71dea98d 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)
eefd15f9 164 {
71dea98d 165 }
d6d5dea7 166
a712cb56 167 void submit(int val, const struct timeval* tv)
71dea98d 168 {
a712cb56 169 struct timeval now=*tv;
71dea98d
BH
170
171 if(d_needinit) {
172 d_last=now;
21f0f88b 173 d_lastget=now;
71dea98d 174 d_needinit=false;
21f0f88b 175 d_val = val;
71dea98d 176 }
21f0f88b
BH
177 else {
178 float diff= makeFloat(d_last - now);
71dea98d 179
21f0f88b
BH
180 d_last=now;
181 double factor=exp(diff)/2.0; // might be '0.5', or 0.0001
3ddb9247 182 d_val=(float)((1-factor)*val+ (float)factor*d_val);
21f0f88b 183 }
eefd15f9 184 }
d6d5dea7 185
a712cb56 186 double get(const struct timeval* tv)
71dea98d 187 {
a712cb56 188 struct timeval now=*tv;
71dea98d 189 float diff=makeFloat(d_lastget-now);
36c5ee42 190 d_lastget=now;
705f31ae 191 float factor=exp(diff/60.0f); // is 1.0 or less
eefd15f9
BH
192 return d_val*=factor;
193 }
194
30ee601a 195 double peek(void) const
a82ce718
PD
196 {
197 return d_val;
198 }
199
996c89cc 200 bool stale(time_t limit) const
9fdf67d5 201 {
71dea98d 202 return limit > d_lastget.tv_sec;
9fdf67d5
BH
203 }
204
eefd15f9 205private:
71dea98d
BH
206 struct timeval d_last; // stores time
207 struct timeval d_lastget; // stores time
208 float d_val;
209 bool d_needinit;
210};
211
628e2c7b
PA
212template<class Thing> class Counters : public boost::noncopyable
213{
214public:
215 Counters()
216 {
217 }
30ee601a 218 unsigned long value(const Thing& t) const
628e2c7b 219 {
30ee601a 220 typename cont_t::const_iterator i=d_cont.find(t);
628e2c7b
PA
221
222 if(i==d_cont.end()) {
223 return 0;
224 }
225 return (unsigned long)i->second;
226 }
227 unsigned long incr(const Thing& t)
228 {
229 typename cont_t::iterator i=d_cont.find(t);
230
231 if(i==d_cont.end()) {
232 d_cont[t]=1;
233 return 1;
234 }
235 else {
236 if (i->second < std::numeric_limits<unsigned long>::max())
237 i->second++;
238 return (unsigned long)i->second;
239 }
240 }
241 unsigned long decr(const Thing& t)
242 {
243 typename cont_t::iterator i=d_cont.find(t);
244
245 if(i!=d_cont.end() && --i->second == 0) {
246 d_cont.erase(i);
247 return 0;
248 } else
249 return (unsigned long)i->second;
250 }
251 void clear(const Thing& t)
252 {
253 typename cont_t::iterator i=d_cont.find(t);
254
255 if(i!=d_cont.end()) {
256 d_cont.erase(i);
257 }
258 }
30ee601a
RG
259 void clear()
260 {
261 d_cont.clear();
262 }
263 size_t size() const
406f46f9 264 {
265 return d_cont.size();
266 }
628e2c7b
PA
267private:
268 typedef map<Thing,unsigned long> cont_t;
269 cont_t d_cont;
270};
271
71dea98d 272
bb4bdbaf 273class SyncRes : public boost::noncopyable
00a19ff7
BH
274{
275public:
3ddb9247 276 enum LogMode { LogNone, Log, Store};
0bd2e252 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;
77499b05 278
a712cb56
RG
279 struct EDNSStatus
280 {
281 EDNSStatus() : mode(UNKNOWN), modeSetAt(0) {}
282 enum EDNSMode { UNKNOWN=0, EDNSOK=1, EDNSIGNORANT=2, NOEDNS=3 } mode;
283 time_t modeSetAt;
284 };
285
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
290 {
291 void submit(const ComboAddress& remote, int usecs, const struct timeval* now)
292 {
0e4675a9 293 d_collection[remote].submit(usecs, now);
a712cb56
RG
294 }
295
296 double get(const struct timeval* now)
297 {
298 if(d_collection.empty())
299 return 0;
300 double ret=std::numeric_limits<double>::max();
301 double tmp;
0e4675a9
RG
302 for (auto& entry : d_collection) {
303 if((tmp = entry.second.get(now)) < ret) {
a712cb56 304 ret=tmp;
0e4675a9 305 d_best=entry.first;
a712cb56
RG
306 }
307 }
308
309 return ret;
310 }
311
312 bool stale(time_t limit) const
313 {
0e4675a9
RG
314 for(const auto& entry : d_collection)
315 if(!entry.second.stale(limit))
a712cb56
RG
316 return false;
317 return true;
318 }
319
0e4675a9
RG
320 void purge(const std::map<ComboAddress, double>& keep)
321 {
322 for (auto iter = d_collection.begin(); iter != d_collection.end(); ) {
323 if (keep.find(iter->first) != keep.end()) {
324 ++iter;
325 }
326 else {
327 iter = d_collection.erase(iter);
328 }
329 }
330 }
331
332 typedef std::map<ComboAddress, DecayingEwma> collection_t;
a712cb56
RG
333 collection_t d_collection;
334 ComboAddress d_best;
335 };
336
337 typedef map<DNSName, DecayingEwmaCollection> nsspeeds_t;
338 typedef map<ComboAddress, EDNSStatus> ednsstatus_t;
339
1e332f68
PL
340 vState getDSRecords(const DNSName& zone, dsmap_t& ds, bool onlyTA, unsigned int depth, bool bogusOnNXD=true, bool* foundCut=nullptr);
341
3337c2f7 342 class AuthDomain
a712cb56 343 {
3337c2f7 344 public:
a712cb56
RG
345 typedef multi_index_container <
346 DNSRecord,
347 indexed_by <
348 ordered_non_unique<
349 composite_key< DNSRecord,
350 member<DNSRecord, DNSName, &DNSRecord::d_name>,
351 member<DNSRecord, uint16_t, &DNSRecord::d_type>
352 >,
353 composite_key_compare<std::less<DNSName>, std::less<uint16_t> >
354 >
355 >
356 > records_t;
3337c2f7 357
a712cb56 358 records_t d_records;
3337c2f7
RG
359 vector<ComboAddress> d_servers;
360 DNSName d_name;
361 bool d_rdForward{false};
362
363 int getRecords(const DNSName& qname, uint16_t qtype, std::vector<DNSRecord>& records) const;
364 bool isAuth() const
365 {
366 return d_servers.empty();
367 }
368 bool isForward() const
369 {
370 return !isAuth();
371 }
372 bool shouldRecurse() const
373 {
374 return d_rdForward;
375 }
376 const DNSName& getName() const
377 {
378 return d_name;
379 }
380
381 private:
382 void addSOA(std::vector<DNSRecord>& records) const;
a712cb56
RG
383 };
384
385 typedef map<DNSName, AuthDomain> domainmap_t;
386 typedef Throttle<boost::tuple<ComboAddress,DNSName,uint16_t> > throttle_t;
387 typedef Counters<ComboAddress> fails_t;
388
389 struct ThreadLocalStorage {
390 NegCache negcache;
391 nsspeeds_t nsSpeeds;
392 throttle_t throttle;
393 ednsstatus_t ednsstatus;
394 fails_t fails;
395 std::shared_ptr<domainmap_t> domainmap;
396 };
397
9065eb05
RG
398 static void setDefaultLogMode(LogMode lm)
399 {
400 s_lm = lm;
401 }
addde5c1 402 static uint64_t doEDNSDump(int fd);
9065eb05 403 static uint64_t doDumpNSSpeeds(int fd);
c1e20fba 404 static uint64_t doDumpThrottleMap(int fd);
9065eb05
RG
405 static int getRootNS(struct timeval now, asyncresolve_t asyncCallback);
406 static void clearDelegationOnly()
407 {
408 s_delegationOnly.clear();
409 }
410 static void addDelegationOnly(const DNSName& name)
411 {
412 s_delegationOnly.insert(name);
413 }
414 static void addDontQuery(const std::string& mask)
415 {
416 if (!s_dontQuery)
417 s_dontQuery = std::unique_ptr<NetmaskGroup>(new NetmaskGroup());
bb4bdbaf 418
9065eb05
RG
419 s_dontQuery->addMask(mask);
420 }
421 static void addDontQuery(const Netmask& mask)
422 {
423 if (!s_dontQuery)
424 s_dontQuery = std::unique_ptr<NetmaskGroup>(new NetmaskGroup());
425
426 s_dontQuery->addMask(mask);
427 }
428 static void clearDontQuery()
429 {
430 s_dontQuery = nullptr;
431 }
432 static void parseEDNSSubnetWhitelist(const std::string& wlist);
2fe3354d
CH
433 static void parseEDNSSubnetAddFor(const std::string& subnetlist);
434 static void addEDNSLocalSubnet(const std::string& subnet)
9065eb05 435 {
2fe3354d
CH
436 s_ednslocalsubnets.addMask(subnet);
437 }
438 static void addEDNSRemoteSubnet(const std::string& subnet)
439 {
440 s_ednsremotesubnets.addMask(subnet);
9065eb05
RG
441 }
442 static void addEDNSDomain(const DNSName& domain)
443 {
444 s_ednsdomains.add(domain);
445 }
2fe3354d 446 static void clearEDNSLocalSubnets()
9065eb05 447 {
2fe3354d
CH
448 s_ednslocalsubnets.clear();
449 }
450 static void clearEDNSRemoteSubnets()
451 {
452 s_ednsremotesubnets.clear();
9065eb05
RG
453 }
454 static void clearEDNSDomains()
455 {
456 s_ednsdomains = SuffixMatchNode();
457 }
a712cb56
RG
458 static void pruneNSSpeeds(time_t limit)
459 {
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);
463 }
464 else {
465 ++i;
466 }
467 }
468 }
469 static uint64_t getNSSpeedsSize()
470 {
471 return t_sstorage.nsSpeeds.size();
472 }
473 static void submitNSSpeed(const DNSName& server, const ComboAddress& ca, uint32_t usec, const struct timeval* now)
474 {
475 t_sstorage.nsSpeeds[server].submit(ca, usec, now);
476 }
477 static void clearNSSpeeds()
478 {
479 t_sstorage.nsSpeeds.clear();
480 }
481 static EDNSStatus::EDNSMode getEDNSStatus(const ComboAddress& server)
482 {
483 const auto& it = t_sstorage.ednsstatus.find(server);
484 if (it == t_sstorage.ednsstatus.end())
485 return EDNSStatus::UNKNOWN;
486
487 return it->second.mode;
488 }
489 static uint64_t getEDNSStatusesSize()
490 {
491 return t_sstorage.ednsstatus.size();
492 }
493 static void clearEDNSStatuses()
494 {
495 t_sstorage.ednsstatus.clear();
496 }
497 static uint64_t getThrottledServersSize()
498 {
499 return t_sstorage.throttle.size();
500 }
501 static void clearThrottle()
502 {
503 t_sstorage.throttle.clear();
504 }
505 static bool isThrottled(time_t now, const ComboAddress& server, const DNSName& target, uint16_t qtype)
506 {
507 return t_sstorage.throttle.shouldThrottle(now, boost::make_tuple(server, target, qtype));
508 }
509 static bool isThrottled(time_t now, const ComboAddress& server)
510 {
511 return t_sstorage.throttle.shouldThrottle(now, boost::make_tuple(server, "", 0));
512 }
513 static void doThrottle(time_t now, const ComboAddress& server, time_t duration, unsigned int tries)
514 {
515 t_sstorage.throttle.throttle(now, boost::make_tuple(server, "", 0), duration, tries);
516 }
517 static uint64_t getFailedServersSize()
518 {
519 return t_sstorage.fails.size();
520 }
521 static void clearFailedServers()
522 {
523 t_sstorage.fails.clear();
524 }
525 static unsigned long getServerFailsCount(const ComboAddress& server)
526 {
527 return t_sstorage.fails.value(server);
528 }
529
530 static void clearNegCache()
531 {
532 t_sstorage.negcache.clear();
533 }
534
535 static uint64_t getNegCacheSize()
536 {
537 return t_sstorage.negcache.size();
538 }
539
540 static void pruneNegCache(unsigned int maxEntries)
541 {
542 t_sstorage.negcache.prune(maxEntries);
543 }
544
545 static uint64_t wipeNegCache(const DNSName& name, bool subtree = false)
546 {
547 return t_sstorage.negcache.wipe(name, subtree);
548 }
549
550 static void setDomainMap(std::shared_ptr<domainmap_t> newMap)
551 {
552 t_sstorage.domainmap = newMap;
553 }
554
555 static const std::shared_ptr<domainmap_t> getDomainMap()
556 {
557 return t_sstorage.domainmap;
558 }
9065eb05 559
8a3a3822
RG
560 static void setECSScopeZeroAddress(const Netmask& scopeZeroMask)
561 {
562 s_ecsScopeZero.source = scopeZeroMask;
563 }
564
9065eb05 565 explicit SyncRes(const struct timeval& now);
30ee601a 566
e325f20c 567 int beginResolve(const DNSName &qname, const QType &qtype, uint16_t qclass, vector<DNSRecord>&ret);
c836dc19
BH
568 void setId(int id)
569 {
77499b05 570 if(doLog())
9fdf67d5 571 d_prefix="["+itoa(id)+"] ";
c836dc19 572 }
3ddb9247
PD
573
574 void setLogMode(LogMode lm)
77499b05
BH
575 {
576 d_lm = lm;
577 }
578
69cbdef9 579 bool doLog() const
c836dc19 580 {
3ddb9247 581 return d_lm != LogNone;
c836dc19 582 }
77499b05 583
c836dc19
BH
584 void setCacheOnly(bool state=true)
585 {
586 d_cacheonly=state;
587 }
2188dcc3
BH
588
589 void setDoEDNS0(bool state=true)
590 {
591 d_doEDNS0=state;
592 }
593
30ee601a
RG
594 void setDoDNSSEC(bool state=true)
595 {
596 d_doDNSSEC=state;
597 }
598
0c43f455
RG
599 void setDNSSECValidationRequested(bool requested=true)
600 {
601 d_DNSSECValidationRequested = requested;
602 }
603
604 bool isDNSSECValidationRequested() const
605 {
606 return d_DNSSECValidationRequested;
607 }
608
e1636f82
RG
609 bool shouldValidate() const
610 {
611 return d_DNSSECValidationRequested && !d_wasOutOfBand;
612 }
613
30ee601a
RG
614 void setWantsRPZ(bool state=true)
615 {
616 d_wantsRPZ=state;
617 }
618
619 bool getWantsRPZ() const
620 {
621 return d_wantsRPZ;
622 }
623
77499b05
BH
624 string getTrace() const
625 {
626 return d_trace.str();
627 }
628
a3e7b735 629 void setLuaEngine(shared_ptr<RecursorLua4> pdl)
3457a2a0 630 {
631 d_pdl = pdl;
632 }
633
3762e821 634 bool wasVariable() const
635 {
636 return d_wasVariable;
637 }
3457a2a0 638
9fc36e90
PL
639 bool wasOutOfBand() const
640 {
641 return d_wasOutOfBand;
642 }
643
30ee601a
RG
644 struct timeval getNow() const
645 {
646 return d_now;
647 }
648
a672e9de
PL
649 void setSkipCNAMECheck(bool skip = false)
650 {
651 d_skipCNAMECheck = skip;
652 }
653
2fe3354d 654 void setQuerySource(const ComboAddress& requestor, boost::optional<const EDNSSubnetOpts&> incomingECS);
30ee601a
RG
655
656#ifdef HAVE_PROTOBUF
657 void setInitialRequestId(boost::optional<const boost::uuids::uuid&> initialRequestId)
658 {
659 d_initialRequestId = initialRequestId;
660 }
63341e8d
RG
661
662 void setOutgoingProtobufServer(std::shared_ptr<RemoteLogger>& server)
663 {
664 d_outgoingProtobufServer = server;
665 }
30ee601a
RG
666#endif
667
668 void setAsyncCallback(asyncresolve_t func)
669 {
670 d_asyncResolve = func;
671 }
3ddb9247 672
4d2be65d
RG
673 vState getValidationState() const
674 {
675 return d_queryValidationState;
676 }
677
a712cb56
RG
678 static thread_local ThreadLocalStorage t_sstorage;
679
aebb81e4 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;
e9a628a2 686 static std::atomic<uint64_t> s_authzonequeries;
aebb81e4 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;
d6923beb 691 static std::atomic<uint64_t> s_ecsqueries;
692 static std::atomic<uint64_t> s_ecsresponses;
9065eb05 693
9065eb05
RG
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;
a9af3782 699 static unsigned int s_maxnegttl;
c3e753c7 700 static unsigned int s_maxcachettl;
1051f8a9
BH
701 static unsigned int s_packetcachettl;
702 static unsigned int s_packetcacheservfailttl;
628e2c7b
PA
703 static unsigned int s_serverdownmaxfails;
704 static unsigned int s_serverdownthrottletime;
e9f9b8ec
RG
705 static uint8_t s_ecsipv4limit;
706 static uint8_t s_ecsipv6limit;
9065eb05
RG
707 static bool s_doIPv6;
708 static bool s_noEDNSPing;
709 static bool s_noEDNS;
710 static bool s_rootNXTrust;
1051f8a9 711 static bool s_nopacketcache;
3ddb9247 712
a712cb56
RG
713 std::unordered_map<std::string,bool> d_discardedPolicies;
714 DNSFilterEngine::Policy d_appliedPolicy;
f7b8cffa 715 unsigned int d_authzonequeries;
a712cb56
RG
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;
49a699c4 722
00a19ff7 723private:
2fe3354d
CH
724 ComboAddress d_requestor;
725 ComboAddress d_cacheRemote;
a712cb56 726
9065eb05 727 static std::unordered_set<DNSName> s_delegationOnly;
2fe3354d
CH
728 static NetmaskGroup s_ednslocalsubnets;
729 static NetmaskGroup s_ednsremotesubnets;
9065eb05 730 static SuffixMatchNode s_ednsdomains;
8a3a3822 731 static EDNSSubnetOpts s_ecsScopeZero;
9065eb05
RG
732 static LogMode s_lm;
733 static std::unique_ptr<NetmaskGroup> s_dontQuery;
734
735 struct GetBestNSAnswer
736 {
737 DNSName qname;
738 set<pair<DNSName,DNSName> > bestns;
739 uint8_t qtype; // only A and AAAA anyhow
740 bool operator<(const GetBestNSAnswer &b) const
741 {
742 return boost::tie(qname, qtype, bestns) <
743 boost::tie(b.qname, b.qtype, b.bestns);
744 }
745 };
746
70b3fe7a
RG
747 typedef std::map<DNSName,vState> zonesStates_t;
748
fa1b87ff 749 int doResolveAt(NsSet &nameservers, DNSName auth, bool flawedNSSet, const DNSName &qname, const QType &qtype, vector<DNSRecord>&ret,
51b6b728 750 unsigned int depth, set<GetBestNSAnswer>&beenthere, vState& state);
6dfff36f 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);
51b6b728 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);
6dfff36f 753
51b6b728 754 int doResolve(const DNSName &qname, const QType &qtype, vector<DNSRecord>&ret, unsigned int depth, set<GetBestNSAnswer>& beenthere, vState& state);
f7b8cffa 755 bool doOOBResolve(const AuthDomain& domain, const DNSName &qname, const QType &qtype, vector<DNSRecord>&ret, int& res);
7c3398aa 756 bool doOOBResolve(const DNSName &qname, const QType &qtype, vector<DNSRecord>&ret, unsigned int depth, int &res);
69cbdef9 757 domainmap_t::const_iterator getBestAuthZone(DNSName* qname) const;
ad797d94
RG
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);
7c3398aa
RG
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);
c5c066bf 762
fa1b87ff 763 inline vector<DNSName> shuffleInSpeedOrder(NsSet &nameservers, const string &prefix);
cc11d7f4 764 inline vector<ComboAddress> shuffleForwardSpeed(const vector<ComboAddress> &rnameservers, const string &prefix, const bool wasRd);
69cbdef9 765 bool moreSpecificThan(const DNSName& a, const DNSName &b) const;
b4c8789a 766 vector<ComboAddress> getAddrs(const DNSName &qname, unsigned int depth, set<GetBestNSAnswer>& beenthere, bool cacheOnly);
26ca3513 767
69cbdef9
RG
768 bool nameserversBlockedByRPZ(const DNSFilterEngine& dfe, const NsSet& nameservers);
769 bool nameserverIPBlockedByRPZ(const DNSFilterEngine& dfe, const ComboAddress&);
26ca3513
RG
770 bool throttledOrBlocked(const std::string& prefix, const ComboAddress& remoteIP, const DNSName& qname, const QType& qtype, bool pierceDontQuery);
771
b4c8789a 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);
e4894ce0
RG
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);
26ca3513 775
6dfff36f 776 bool doSpecialNamesResolve(const DNSName &qname, const QType &qtype, const uint16_t qclass, vector<DNSRecord> &ret);
db50a7f4 777
deca7d8f 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;
30ee601a 779
2fe3354d 780 boost::optional<Netmask> getEDNSSubnetMask(const DNSName&dn, const ComboAddress& rem);
e9f9b8ec 781
4d2be65d 782 bool validationEnabled() const;
4d2be65d
RG
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);
51b6b728
RG
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);
51b6b728 787 vState getDNSKeys(const DNSName& signer, skeyset_t& keys, unsigned int depth);
28364e4b
RG
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);
4d2be65d 791 vState getTA(const DNSName& zone, dsmap_t& ds);
0735b60f 792 bool haveExactValidationStatus(const DNSName& domain);
5374b03b 793 vState getValidationStatus(const DNSName& subdomain, bool allowIndeterminate=true);
70b3fe7a 794
c405e222 795 bool lookForCut(const DNSName& qname, unsigned int depth, const vState existingState, vState& newState);
51b6b728 796 void computeZoneCuts(const DNSName& begin, const DNSName& end, unsigned int depth);
4d2be65d 797
0b29b9c5
RG
798 void setUpdatingRootNS()
799 {
800 d_updatingRootNS = true;
801 }
802
51b6b728 803 zonesStates_t d_cutStates;
77499b05 804 ostringstream d_trace;
a3e7b735 805 shared_ptr<RecursorLua4> d_pdl;
2fe3354d 806 boost::optional<Netmask> d_outgoingECSNetwork;
63341e8d 807 std::shared_ptr<RemoteLogger> d_outgoingProtobufServer{nullptr};
30ee601a
RG
808#ifdef HAVE_PROTOBUF
809 boost::optional<const boost::uuids::uuid&> d_initialRequestId;
810#endif
811 asyncresolve_t d_asyncResolve{nullptr};
812 struct timeval d_now;
c836dc19 813 string d_prefix;
4d2be65d 814 vState d_queryValidationState{Indeterminate};
b88526ce
PL
815
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
818 */
c836dc19 819 bool d_cacheonly;
30ee601a 820 bool d_doDNSSEC;
0c43f455 821 bool d_DNSSECValidationRequested{false};
30ee601a 822 bool d_doEDNS0{true};
24bb9b58 823 bool d_requireAuthData{true};
30ee601a 824 bool d_skipCNAMECheck{false};
0b29b9c5 825 bool d_updatingRootNS{false};
30ee601a
RG
826 bool d_wantsRPZ{true};
827 bool d_wasOutOfBand{false};
828 bool d_wasVariable{false};
57769f13 829
77499b05 830 LogMode d_lm;
00a19ff7 831};
ac0e821b 832
5c633640 833class Socket;
a9af3782 834/* external functions, opaque to us */
5c633640 835int asendtcp(const string& data, Socket* sock);
a683e8bd 836int arecvtcp(string& data, size_t len, Socket* sock, bool incompleteOkay);
1d5b3ce6
BH
837
838
839struct PacketID
840{
825fa717 841 PacketID() : id(0), type(0), sock(0), inNeeded(0), inIncompleteOkay(false), outPos(0), nearMisses(0), fd(-1)
67770277 842 {
d38e2ba9 843 remote.reset();
67770277 844 }
1d5b3ce6
BH
845
846 uint16_t id; // wait for a specific id/remote pair
91ffe057 847 uint16_t type; // and this is its type
996c89cc 848 ComboAddress remote; // this is the remote
3ddb9247 849 DNSName domain; // this is the question
1d5b3ce6
BH
850
851 Socket* sock; // or wait for an event on a TCP fd
1d5b3ce6 852 string inMSG; // they'll go here
a683e8bd 853 size_t inNeeded; // if this is set, we'll read until inNeeded bytes are read
825fa717 854 bool inIncompleteOkay;
1d5b3ce6
BH
855
856 string outMSG; // the outgoing message that needs to be sent
857 string::size_type outPos; // how far we are along in the outMSG
858
96f81a93
BH
859 typedef set<uint16_t > chain_t;
860 mutable chain_t chain;
91ffe057 861 mutable uint32_t nearMisses; // number of near misses - host correct, id wrong
4ef015cd 862 int fd;
35ce8576 863
1d5b3ce6
BH
864 bool operator<(const PacketID& b) const
865 {
866 int ourSock= sock ? sock->getHandle() : 0;
867 int bSock = b.sock ? b.sock->getHandle() : 0;
787e5eab 868 if( tie(remote, ourSock, type) < tie(b.remote, bSock, b.type))
0d5f0a9f 869 return true;
787e5eab 870 if( tie(remote, ourSock, type) > tie(b.remote, bSock, b.type))
0d5f0a9f
BH
871 return false;
872
c5c066bf 873 return tie(domain, fd, id) < tie(b.domain, b.fd, b.id);
1d5b3ce6
BH
874 }
875};
876
3ddb9247 877struct PacketIDBirthdayCompare: public std::binary_function<PacketID, PacketID, bool>
96f81a93
BH
878{
879 bool operator()(const PacketID& a, const PacketID& b) const
880 {
881 int ourSock= a.sock ? a.sock->getHandle() : 0;
882 int bSock = b.sock ? b.sock->getHandle() : 0;
787e5eab 883 if( tie(a.remote, ourSock, a.type) < tie(b.remote, bSock, b.type))
96f81a93 884 return true;
787e5eab 885 if( tie(a.remote, ourSock, a.type) > tie(b.remote, bSock, b.type))
96f81a93
BH
886 return false;
887
72849e12 888 return a.domain < b.domain;
96f81a93
BH
889 }
890};
f26bf547
RG
891extern thread_local std::unique_ptr<MemRecursorCache> t_RC;
892extern thread_local std::unique_ptr<RecursorPacketCache> t_packetCache;
d2392145 893typedef MTasker<PacketID,string> MT_t;
f165a1f4 894MT_t* getMT();
1d5b3ce6
BH
895
896struct RecursorStats
897{
aebb81e4 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;
19178da9 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};
aebb81e4 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;
ba892c7f 917 std::atomic<uint64_t> truncatedDrops;
cf8cda18 918 std::atomic<uint64_t> queryPipeFullDrops;
aebb81e4 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;
c0f9be19 933 std::atomic<uint64_t> emptyQueriesCount;
5e3de507 934 time_t startupTime;
aebb81e4 935 std::atomic<uint64_t> dnssecQueries;
ec6eacbc 936 unsigned int maxMThreadStackUsage;
849fe8d2
PL
937 std::atomic<uint64_t> dnssecValidations; // should be the sum of all dnssecResult* stats
938 std::map<vState, std::atomic<uint64_t> > dnssecResults;
7a25883a 939 std::map<DNSFilterEngine::PolicyKind, std::atomic<uint64_t> > policyResults;
b3b5459d 940};
996c89cc 941
0e408828 942//! represents a running TCP/IP client session
cd989c87 943class TCPConnection : public boost::noncopyable
0e408828 944{
50a5ef72 945public:
cd989c87
BH
946 TCPConnection(int fd, const ComboAddress& addr);
947 ~TCPConnection();
3ddb9247 948
30ee601a 949 int getFD() const
cd989c87
BH
950 {
951 return d_fd;
952 }
2749c3fe
RG
953
954 std::string data;
955 const ComboAddress d_remote;
956 size_t queriesCount{0};
b841314c
RG
957 enum stateenum {BYTE0, BYTE1, GETQUESTION, DONE} state{BYTE0};
958 uint16_t qlen{0};
959 uint16_t bytesread{0};
0e408828 960
50a5ef72 961 static unsigned int getCurrentConnections() { return s_currentConnections; }
50a5ef72 962private:
cd989c87 963 const int d_fd;
1bc9e6bd 964 static AtomicCounter s_currentConnections; //!< total number of current TCP connections
0e408828
BH
965};
966
44971ca0
PD
967class ImmediateServFailException
968{
969public:
970 ImmediateServFailException(string r){reason=r;};
971
972 string reason; //! Print this to tell the user what went wrong
973};
0e408828 974
f635ed7b 975typedef boost::circular_buffer<ComboAddress> addrringbuf_t;
621ccf89 976extern thread_local std::unique_ptr<addrringbuf_t> t_servfailremotes, t_largeanswerremotes, t_remotes, t_bogusremotes, t_timeouts;
a9af3782 977
66f2e6ad 978extern thread_local std::unique_ptr<boost::circular_buffer<pair<DNSName,uint16_t> > > t_queryring, t_servfailqueryring, t_bogusqueryring;
f26bf547 979extern thread_local std::shared_ptr<NetmaskGroup> t_allowFrom;
674cf0f6 980string doQueueReloadLuaScript(vector<string>::const_iterator begin, vector<string>::const_iterator end);
77499b05 981string doTraceRegex(vector<string>::const_iterator begin, vector<string>::const_iterator end);
18af64a8 982void parseACLs();
1d5b3ce6 983extern RecursorStats g_stats;
a512e3d1 984extern unsigned int g_networkTimeoutMsec;
c3828c03 985extern unsigned int g_numThreads;
b33c2462 986extern uint16_t g_outgoingEDNSBufsize;
a6f7f5fe 987extern std::atomic<uint32_t> g_maxCacheEntries, g_maxPacketCacheEntries;
c1c29961 988extern bool g_lowercaseOutgoing;
12ce523e 989
990
ee1ada80 991std::string reloadAuthAndForwards();
c1d73d94 992ComboAddress parseIPAndPort(const std::string& input, uint16_t port);
1652a63e 993ComboAddress getQueryLocalAddress(int family, uint16_t port);
3427fa8a 994typedef boost::function<void*(void)> pipefunc_t;
b4e76a18 995void broadcastFunction(const pipefunc_t& func);
8171ab83 996void distributeAsyncFunction(const std::string& question, const pipefunc_t& func);
3427fa8a 997
e325f20c 998int directResolve(const DNSName& qname, const QType& qtype, int qclass, vector<DNSRecord>& ret);
3427fa8a 999
b4e76a18 1000template<class T> T broadcastAccFunction(const boost::function<T*()>& func);
3427fa8a 1001
9065eb05 1002std::shared_ptr<SyncRes::domainmap_t> parseAuthAndForwards();
13034931
BH
1003uint64_t* pleaseGetNsSpeedsSize();
1004uint64_t* pleaseGetCacheSize();
1005uint64_t* pleaseGetNegCacheSize();
1006uint64_t* pleaseGetCacheHits();
1007uint64_t* pleaseGetCacheMisses();
1008uint64_t* pleaseGetConcurrentQueries();
1009uint64_t* pleaseGetThrottleSize();
16beeaa4
BH
1010uint64_t* pleaseGetPacketCacheHits();
1011uint64_t* pleaseGetPacketCacheSize();
86f3ca51 1012uint64_t* pleaseWipeCache(const DNSName& canon, bool subtree=false);
1013uint64_t* pleaseWipePacketCache(const DNSName& canon, bool subtree);
1014uint64_t* pleaseWipeAndCountNegCache(const DNSName& canon, bool subtree=false);
2c78bd57 1015void doCarbonDump(void*);
9065eb05 1016void primeHints(void);
795215f2 1017
f703f766 1018extern __thread struct timeval g_now;
f3d6a5c5 1019
4898a348 1020#ifdef HAVE_PROTOBUF
f26bf547 1021extern thread_local std::unique_ptr<boost::uuids::random_generator> t_uuidGenerator;
4898a348 1022#endif