/
syncres.cc
1263 lines (1102 loc) · 46 KB
/
syncres.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
PowerDNS Versatile Database Driven Nameserver
Copyright (C) 2003 - 2013 PowerDNS.COM BV
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published
by the Free Software Foundation
Additionally, the license of this program contains a special
exception which allows to distribute the program in binary form when
it is linked against OpenSSL.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include "utility.hh"
#include "syncres.hh"
#include <iostream>
#include <map>
#include <algorithm>
#include <set>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <utility>
#include <deque>
#include "logger.hh"
#include "misc.hh"
#include "arguments.hh"
#include "lwres.hh"
#include "recursor_cache.hh"
#include "dnsparser.hh"
#include "dns_random.hh"
#include "lock.hh"
#include "cachecleaner.hh"
__thread SyncRes::StaticStorage* t_sstorage;
unsigned int SyncRes::s_maxnegttl;
unsigned int SyncRes::s_maxcachettl;
unsigned int SyncRes::s_packetcachettl;
unsigned int SyncRes::s_packetcacheservfailttl;
unsigned int SyncRes::s_serverdownmaxfails;
unsigned int SyncRes::s_serverdownthrottletime;
unsigned int SyncRes::s_queries;
unsigned int SyncRes::s_outgoingtimeouts;
unsigned int SyncRes::s_outqueries;
unsigned int SyncRes::s_tcpoutqueries;
unsigned int SyncRes::s_throttledqueries;
unsigned int SyncRes::s_dontqueries;
unsigned int SyncRes::s_nodelegated;
unsigned int SyncRes::s_unreachables;
unsigned int SyncRes::s_minimumTTL;
bool SyncRes::s_doIPv6;
bool SyncRes::s_nopacketcache;
string SyncRes::s_serverID;
SyncRes::LogMode SyncRes::s_lm;
#define LOG(x) if(d_lm == Log) { L <<Logger::Warning << x; } else if(d_lm == Store) { d_trace << x; }
bool SyncRes::s_noEDNSPing;
bool SyncRes::s_noEDNS;
bool SyncRes::s_doAdditionalProcessing;
bool SyncRes::s_doAAAAAdditionalProcessing;
SyncRes::SyncRes(const struct timeval& now) : d_outqueries(0), d_tcpoutqueries(0), d_throttledqueries(0), d_timeouts(0), d_unreachables(0),
d_now(now),
d_cacheonly(false), d_nocache(false), d_doEDNS0(false), d_lm(s_lm)
{
if(!t_sstorage) {
t_sstorage = new StaticStorage();
}
}
/** everything begins here - this is the entry point just after receiving a packet */
int SyncRes::beginResolve(const string &qname, const QType &qtype, uint16_t qclass, vector<DNSResourceRecord>&ret)
{
s_queries++;
if( (qtype.getCode() == QType::AXFR))
return -1;
if( (qtype.getCode()==QType::PTR && pdns_iequals(qname, "1.0.0.127.in-addr.arpa.")) ||
(qtype.getCode()==QType::A && qname.length()==10 && pdns_iequals(qname, "localhost."))) {
ret.clear();
DNSResourceRecord rr;
rr.qname=qname;
rr.qtype=qtype;
rr.qclass=QClass::IN;
rr.ttl=86400;
if(qtype.getCode()==QType::PTR)
rr.content="localhost.";
else
rr.content="127.0.0.1";
ret.push_back(rr);
return 0;
}
if(qclass==QClass::CHAOS && qtype.getCode()==QType::TXT &&
(pdns_iequals(qname, "version.bind.") || pdns_iequals(qname, "id.server.") || pdns_iequals(qname, "version.pdns.") )
) {
ret.clear();
DNSResourceRecord rr;
rr.qname=qname;
rr.qtype=qtype;
rr.qclass=qclass;
rr.ttl=86400;
if(pdns_iequals(qname,"version.bind.") || pdns_iequals(qname,"version.pdns."))
rr.content="\""+::arg()["version-string"]+"\"";
else
rr.content="\""+s_serverID+"\"";
ret.push_back(rr);
return 0;
}
if(qclass==QClass::ANY)
qclass=QClass::IN;
else if(qclass!=QClass::IN)
return -1;
set<GetBestNSAnswer> beenthere;
int res=doResolve(qname, qtype, ret, 0, beenthere);
if(!res && s_doAdditionalProcessing)
addCruft(qname, ret);
return res;
}
//! This is the 'out of band resolver', in other words, the authoritative server
bool SyncRes::doOOBResolve(const string &qname, const QType &qtype, vector<DNSResourceRecord>&ret, int depth, int& res)
{
string prefix;
if(doLog()) {
prefix=d_prefix;
prefix.append(depth, ' ');
}
LOG(prefix<<qname<<": checking auth storage for '"<<qname<<"|"<<qtype.getName()<<"'"<<endl);
string authdomain(qname);
domainmap_t::const_iterator iter=getBestAuthZone(&authdomain);
if(iter==t_sstorage->domainmap->end()) {
LOG(prefix<<qname<<": auth storage has no zone for this query!"<<endl);
return false;
}
LOG(prefix<<qname<<": auth storage has data, zone='"<<authdomain<<"'"<<endl);
pair<AuthDomain::records_t::const_iterator, AuthDomain::records_t::const_iterator> range;
range=iter->second.d_records.equal_range(tie(qname)); // partial lookup
ret.clear();
AuthDomain::records_t::const_iterator ziter;
bool somedata=false;
for(ziter=range.first; ziter!=range.second; ++ziter) {
somedata=true;
if(qtype.getCode()==QType::ANY || ziter->qtype==qtype || ziter->qtype.getCode()==QType::CNAME) // let rest of nameserver do the legwork on this one
ret.push_back(*ziter);
}
if(!ret.empty()) {
LOG(prefix<<qname<<": exact match in zone '"<<authdomain<<"'"<<endl);
res=0;
return true;
}
if(somedata) {
LOG(prefix<<qname<<": found record in '"<<authdomain<<"', but nothing of the right type, sending SOA"<<endl);
ziter=iter->second.d_records.find(make_tuple(authdomain, QType(QType::SOA)));
if(ziter!=iter->second.d_records.end()) {
DNSResourceRecord rr=*ziter;
rr.d_place=DNSResourceRecord::AUTHORITY;
ret.push_back(rr);
}
else
LOG(prefix<<qname<<": can't find SOA record '"<<authdomain<<"' in our zone!"<<endl);
res=RCode::NoError;
return true;
}
LOG(prefix<<qname<<": nothing found so far in '"<<authdomain<<"', trying wildcards"<<endl);
string wcarddomain(qname);
while(!pdns_iequals(wcarddomain, iter->first) && chopOffDotted(wcarddomain)) {
LOG(prefix<<qname<<": trying '*."+wcarddomain+"' in "<<authdomain<<endl);
range=iter->second.d_records.equal_range(make_tuple("*."+wcarddomain));
if(range.first==range.second)
continue;
for(ziter=range.first; ziter!=range.second; ++ziter) {
DNSResourceRecord rr=*ziter;
if(rr.qtype == qtype || qtype.getCode() == QType::ANY) {
rr.qname = qname;
rr.d_place=DNSResourceRecord::ANSWER;
ret.push_back(rr);
}
}
LOG(prefix<<qname<<": in '"<<authdomain<<"', had wildcard match on '*."+wcarddomain+"'"<<endl);
res=RCode::NoError;
return true;
}
string nsdomain(qname);
while(chopOffDotted(nsdomain) && !pdns_iequals(nsdomain, iter->first)) {
range=iter->second.d_records.equal_range(make_tuple(nsdomain,QType(QType::NS)));
if(range.first==range.second)
continue;
for(ziter=range.first; ziter!=range.second; ++ziter) {
DNSResourceRecord rr=*ziter;
rr.d_place=DNSResourceRecord::AUTHORITY;
ret.push_back(rr);
}
}
if(ret.empty()) {
LOG(prefix<<qname<<": no NS match in zone '"<<authdomain<<"' either, handing out SOA"<<endl);
ziter=iter->second.d_records.find(make_tuple(authdomain, QType(QType::SOA)));
if(ziter!=iter->second.d_records.end()) {
DNSResourceRecord rr=*ziter;
rr.d_place=DNSResourceRecord::AUTHORITY;
ret.push_back(rr);
}
else
LOG(prefix<<qname<<": can't find SOA record '"<<authdomain<<"' in our zone!"<<endl);
res=RCode::NXDomain;
}
else
res=0;
return true;
}
void SyncRes::doEDNSDumpAndClose(int fd)
{
FILE* fp=fdopen(fd, "w");
fprintf(fp,"IP Address\tMode\tMode last updated at\n");
for(ednsstatus_t::const_iterator iter = t_sstorage->ednsstatus.begin(); iter != t_sstorage->ednsstatus.end(); ++iter) {
fprintf(fp, "%s\t%d\t%s", iter->first.toString().c_str(), (int)iter->second.mode, ctime(&iter->second.modeSetAt));
}
fclose(fp);
}
int SyncRes::asyncresolveWrapper(const ComboAddress& ip, const string& domain, int type, bool doTCP, bool sendRDQuery, struct timeval* now, LWResult* res)
{
/* what is your QUEST?
the goal is to get as many remotes as possible on the highest level of hipness: EDNS PING responders.
The levels are:
-1) CONFIRMEDPINGER: Confirmed pinger!
0) UNKNOWN Unknown state
1) EDNSNOPING: Honors EDNS0 if no PING is included
2) EDNSPINGOK: Ignores EDNS0+PING, but does generate EDNS0 response
3) EDNSIGNORANT: Ignores EDNS0+PING, gives replies without EDNS0 nor PING
4) NOEDNS: Generates FORMERR on EDNS queries
Everybody starts out assumed to be '0'.
If '-1', send out EDNS0+Ping
If we get a FormErr, ignore
If we get a incorrect PING, ignore
If we get no PING, ignore
If '0', send out EDNS0+Ping
If we get a pure EDNS response, you are downgraded to '2'.
If you FORMERR us, go to '1',
If no EDNS in response, go to '3' - 3 and 0 are really identical, except confirmed
If with correct PING, upgrade to -1
If '1', send out EDNS0, no PING
If FORMERR, downgrade to 4
If '2', keep on including EDNS0+PING, just don't expect PING to be correct
If PING correct, move to '0', and cheer in the log file!
If '3', keep on including EDNS0+PING, see what happens
Same behaviour as 0
If '4', send bare queries
*/
if(s_noEDNS) {
g_stats.noEdnsOutQueries++;
return asyncresolve(ip, domain, type, doTCP, sendRDQuery, 0, now, res);
}
SyncRes::EDNSStatus* ednsstatus;
ednsstatus = &t_sstorage->ednsstatus[ip];
if(ednsstatus->modeSetAt && ednsstatus->modeSetAt + 3600 < d_now.tv_sec) {
*ednsstatus=SyncRes::EDNSStatus();
// cerr<<"Resetting EDNS Status for "<<ip.toString()<<endl);
}
if(s_noEDNSPing && ednsstatus->mode == EDNSStatus::UNKNOWN)
ednsstatus->mode = EDNSStatus::EDNSNOPING;
SyncRes::EDNSStatus::EDNSMode& mode=ednsstatus->mode;
SyncRes::EDNSStatus::EDNSMode oldmode = mode;
int EDNSLevel=0;
int ret;
for(int tries = 0; tries < 3; ++tries) {
// cerr<<"Remote '"<<ip.toString()<<"' currently in mode "<<mode<<endl);
if(mode==EDNSStatus::CONFIRMEDPINGER || mode==EDNSStatus::UNKNOWN || mode==EDNSStatus::EDNSPINGOK || mode==EDNSStatus::EDNSIGNORANT)
EDNSLevel = 2;
else if(mode==EDNSStatus::EDNSNOPING) {
EDNSLevel = 1;
g_stats.noPingOutQueries++;
}
else if(mode==EDNSStatus::NOEDNS) {
g_stats.noEdnsOutQueries++;
EDNSLevel = 0;
}
ret=asyncresolve(ip, domain, type, doTCP, sendRDQuery, EDNSLevel, now, res);
if(ret == 0 || ret < 0) {
// cerr<<"Transport error or timeout (ret="<<ret<<"), no change in mode"<<endl);
return ret;
}
if(mode== EDNSStatus::CONFIRMEDPINGER) { // confirmed pinger!
if(!res->d_pingCorrect) {
L<<Logger::Error<<"Confirmed EDNS-PING enabled host "<<ip.toString()<<" did not send back correct ping"<<endl;
// perhaps lower some kind of count here, don't want to punnish a downgrader too long!
ret = 0;
res->d_rcode = RCode::ServFail;
g_stats.ednsPingMismatches++;
}
else {
g_stats.ednsPingMatches++;
ednsstatus->modeSetAt=d_now.tv_sec; // only the very best mode self-perpetuates
}
}
else if(mode==EDNSStatus::UNKNOWN || mode==EDNSStatus::EDNSPINGOK || mode == EDNSStatus::EDNSIGNORANT ) {
if(res->d_rcode == RCode::FormErr) {
// cerr<<"Downgrading to EDNSNOPING because of FORMERR!"<<endl);
mode = EDNSStatus::EDNSNOPING;
continue;
}
else if(mode==EDNSStatus::UNKNOWN && (res->d_rcode == RCode::Refused || res->d_rcode == RCode::NotImp) ) { // this "fixes" F5
// cerr<<"Downgrading an unknown status to EDNSNOPING because of RCODE="<<res->d_rcode<<endl;
mode = EDNSStatus::EDNSNOPING;
continue;
}
else if(!res->d_pingCorrect && res->d_haveEDNS)
mode = EDNSStatus::EDNSPINGOK;
else if(res->d_pingCorrect) {
L<<Logger::Warning<<"We welcome "<<ip.toString()<<" to the land of EDNS-PING!"<<endl;
mode = EDNSStatus::CONFIRMEDPINGER;
g_stats.ednsPingMatches++;
}
else if(!res->d_haveEDNS) {
if(mode != EDNSStatus::EDNSIGNORANT) {
mode = EDNSStatus::EDNSIGNORANT;
// cerr<<"We find that "<<ip.toString()<<" is an EDNS-ignorer, moving to mode 3"<<endl);
}
}
}
else if(mode==EDNSStatus::EDNSNOPING) {
if(res->d_rcode == RCode::FormErr) {
// cerr<<"Downgrading to mode 4, FORMERR!"<<endl);
mode = EDNSStatus::NOEDNS;
continue;
}
}
else if(mode==EDNSStatus::EDNSPINGOK) {
if(res->d_pingCorrect) {
// an upgrade!
L<<Logger::Warning<<"We welcome "<<ip.toString()<<" to the land of EDNS-PING!"<<endl;
mode = EDNSStatus::CONFIRMEDPINGER;
}
}
if(oldmode != mode)
ednsstatus->modeSetAt=d_now.tv_sec;
// cerr<<"Result: ret="<<ret<<", EDNS-level: "<<EDNSLevel<<", haveEDNS: "<<res->d_haveEDNS<<", EDNS-PING correct: "<<res->d_pingCorrect<<", new mode: "<<mode<<endl);
return ret;
}
return ret;
}
int SyncRes::doResolve(const string &qname, const QType &qtype, vector<DNSResourceRecord>&ret, int depth, set<GetBestNSAnswer>& beenthere)
{
string prefix;
if(doLog()) {
prefix=d_prefix;
prefix.append(depth, ' ');
}
int res=0;
if(!(d_nocache && qtype.getCode()==QType::NS && qname==".")) {
if(d_cacheonly) { // very limited OOB support
LWResult lwr;
LOG(prefix<<qname<<": Recursion not requested for '"<<qname<<"|"<<qtype.getName()<<"', peeking at auth/forward zones"<<endl);
string authname(qname);
domainmap_t::const_iterator iter=getBestAuthZone(&authname);
if(iter != t_sstorage->domainmap->end()) {
const vector<ComboAddress>& servers = iter->second.d_servers;
if(servers.empty()) {
ret.clear();
doOOBResolve(qname, qtype, ret, depth, res);
return res;
}
else {
const ComboAddress remoteIP = servers.front();
LOG(prefix<<qname<<": forwarding query to hardcoded nameserver '"<< remoteIP.toStringWithPort()<<"' for zone '"<<authname<<"'"<<endl);
res=asyncresolveWrapper(remoteIP, qname, qtype.getCode(), false, false, &d_now, &lwr);
// filter out the good stuff from lwr.result()
for(LWResult::res_t::const_iterator i=lwr.d_result.begin();i!=lwr.d_result.end();++i) {
if(i->d_place == DNSResourceRecord::ANSWER)
ret.push_back(*i);
}
return res;
}
}
}
if(doCNAMECacheCheck(qname,qtype,ret,depth,res)) // will reroute us if needed
return res;
if(doCacheCheck(qname,qtype,ret,depth,res)) // we done
return res;
}
if(d_cacheonly)
return 0;
LOG(prefix<<qname<<": No cache hit for '"<<qname<<"|"<<qtype.getName()<<"', trying to find an appropriate NS record"<<endl);
string subdomain(qname);
set<string, CIStringCompare> nsset;
bool flawedNSSet=false;
// the two retries allow getBestNSNamesFromCache&co to reprime the root
// hints, in case they ever go missing
for(int tries=0;tries<2 && nsset.empty();++tries) {
subdomain=getBestNSNamesFromCache(subdomain, nsset, &flawedNSSet, depth, beenthere); // pass beenthere to both occasions
}
if(!(res=doResolveAt(nsset, subdomain, flawedNSSet, qname, qtype, ret, depth, beenthere)))
return 0;
LOG(prefix<<qname<<": failed (res="<<res<<")"<<endl);
return res<0 ? RCode::ServFail : res;
}
#if 0
// for testing purposes
static bool ipv6First(const ComboAddress& a, const ComboAddress& b)
{
return !(a.sin4.sin_family < a.sin4.sin_family);
}
#endif
/** This function explicitly goes out for A or AAAA addresses
*/
vector<ComboAddress> SyncRes::getAddrs(const string &qname, int depth, set<GetBestNSAnswer>& beenthere)
{
typedef vector<DNSResourceRecord> res_t;
res_t res;
typedef vector<ComboAddress> ret_t;
ret_t ret;
QType type;
for(int j=1-s_doIPv6; j<2+s_doIPv6; j++)
{
bool done=false;
// j=0: ANY
// j=1: A
// j=2: AAAA
switch(j) {
case 0:
type = QType::ANY;
break;
case 1:
type = QType::A;
break;
case 2:
type = QType::AAAA;
break;
}
if(!doResolve(qname, type, res,depth+1,beenthere) && !res.empty()) { // this consults cache, OR goes out
for(res_t::const_iterator i=res.begin(); i!= res.end(); ++i) {
if(i->qtype.getCode()==QType::A || i->qtype.getCode()==QType::AAAA) {
ret.push_back(ComboAddress(i->content, 53));
if(!j) done=true;
}
}
}
if(done) break;
}
if(ret.size() > 1) {
random_shuffle(ret.begin(), ret.end(), dns_random);
// move 'best' address for this nameserver name up front
nsspeeds_t::iterator best = t_sstorage->nsSpeeds.find(qname);
if(best != t_sstorage->nsSpeeds.end())
for(ret_t::iterator i=ret.begin(); i != ret.end(); ++i) {
if(*i==best->second.d_best) { // got the fastest one
if(i!=ret.begin()) {
*i=*ret.begin();
*ret.begin()=best->second.d_best;
}
break;
}
}
}
return ret;
}
void SyncRes::getBestNSFromCache(const string &qname, set<DNSResourceRecord>&bestns, bool* flawedNSSet, int depth, set<GetBestNSAnswer>& beenthere)
{
string prefix, subdomain(qname);
if(doLog()) {
prefix=d_prefix;
prefix.append(depth, ' ');
}
bestns.clear();
do {
LOG(prefix<<qname<<": Checking if we have NS in cache for '"<<subdomain<<"'"<<endl);
set<DNSResourceRecord> ns;
*flawedNSSet = false;
if(t_RC->get(d_now.tv_sec, subdomain, QType(QType::NS), &ns) > 0) {
for(set<DNSResourceRecord>::const_iterator k=ns.begin();k!=ns.end();++k) {
if(k->ttl > (unsigned int)d_now.tv_sec ) {
set<DNSResourceRecord> aset;
DNSResourceRecord rr=*k;
rr.content=k->content;
if(!dottedEndsOn(rr.content, subdomain) || t_RC->get(d_now.tv_sec, rr.content, s_doIPv6 ? QType(QType::ADDR) : QType(QType::A),
doLog() ? &aset : 0) > 5) {
bestns.insert(rr);
LOG(prefix<<qname<<": NS (with ip, or non-glue) in cache for '"<<subdomain<<"' -> '"<<rr.content<<"'"<<endl);
LOG(prefix<<qname<<": within bailiwick: "<<dottedEndsOn(rr.content, subdomain));
if(!aset.empty()) {
LOG(", in cache, ttl="<<(unsigned int)(((time_t)aset.begin()->ttl- d_now.tv_sec ))<<endl);
}
else {
LOG(", not in cache / did not look at cache"<<endl);
}
}
else {
*flawedNSSet=true;
LOG(prefix<<qname<<": NS in cache for '"<<subdomain<<"', but needs glue ("<<k->content<<") which we miss or is expired"<<endl);
}
}
}
if(!bestns.empty()) {
GetBestNSAnswer answer;
answer.qname=qname; answer.bestns=bestns;
if(beenthere.count(answer)) {
LOG(prefix<<qname<<": We have NS in cache for '"<<subdomain<<"' but part of LOOP (already seen "<<answer.qname<<")! Trying less specific NS"<<endl);
if(doLog())
for( set<GetBestNSAnswer>::const_iterator j=beenthere.begin();j!=beenthere.end();++j) {
LOG(prefix<<qname<<": beenthere: "<<j->qname<<" ("<<(unsigned int)j->bestns.size()<<")"<<endl);
}
bestns.clear();
}
else {
beenthere.insert(answer);
LOG(prefix<<qname<<": We have NS in cache for '"<<subdomain<<"' (flawedNSSet="<<*flawedNSSet<<")"<<endl);
return;
}
}
}
LOG(prefix<<qname<<": no valid/useful NS in cache for '"<<subdomain<<"'"<<endl);
if(subdomain==".") { primeHints(); }
}while(chopOffDotted(subdomain));
}
SyncRes::domainmap_t::const_iterator SyncRes::getBestAuthZone(string* qname)
{
SyncRes::domainmap_t::const_iterator ret;
do {
ret=t_sstorage->domainmap->find(*qname);
if(ret!=t_sstorage->domainmap->end())
break;
}while(chopOffDotted(*qname));
return ret;
}
/** doesn't actually do the work, leaves that to getBestNSFromCache */
string SyncRes::getBestNSNamesFromCache(const string &qname, set<string, CIStringCompare>& nsset, bool* flawedNSSet, int depth, set<GetBestNSAnswer>&beenthere)
{
string subdomain(qname);
string authdomain(qname);
domainmap_t::const_iterator iter=getBestAuthZone(&authdomain);
if(iter!=t_sstorage->domainmap->end()) {
if( iter->second.d_servers.empty() )
nsset.insert(string()); // this gets picked up in doResolveAt, if empty it means "we are auth", otherwise it denotes a forward
else {
for(vector<ComboAddress>::const_iterator server=iter->second.d_servers.begin(); server != iter->second.d_servers.end(); ++server)
nsset.insert((iter->second.d_rdForward ? "+" : "-") + server->toStringWithPort()); // add a '+' if the rd bit should be set
}
return authdomain;
}
set<DNSResourceRecord> bestns;
getBestNSFromCache(subdomain, bestns, flawedNSSet, depth, beenthere);
for(set<DNSResourceRecord>::const_iterator k=bestns.begin();k!=bestns.end();++k) {
nsset.insert(k->content);
if(k==bestns.begin())
subdomain=k->qname;
}
return subdomain;
}
bool SyncRes::doCNAMECacheCheck(const string &qname, const QType &qtype, vector<DNSResourceRecord>&ret, int depth, int &res)
{
string prefix;
if(doLog()) {
prefix=d_prefix;
prefix.append(depth, ' ');
}
if((depth>9 && d_outqueries>10 && d_throttledqueries>5) || depth > 15) {
LOG(prefix<<qname<<": recursing (CNAME or other indirection) too deep, depth="<<depth<<endl);
res=RCode::ServFail;
return true;
}
LOG(prefix<<qname<<": Looking for CNAME cache hit of '"<<(qname+"|CNAME")<<"'"<<endl);
set<DNSResourceRecord> cset;
if(t_RC->get(d_now.tv_sec, qname,QType(QType::CNAME),&cset) > 0) {
for(set<DNSResourceRecord>::const_iterator j=cset.begin();j!=cset.end();++j) {
if(j->ttl>(unsigned int) d_now.tv_sec) {
LOG(prefix<<qname<<": Found cache CNAME hit for '"<< (qname+"|CNAME") <<"' to '"<<j->content<<"'"<<endl);
DNSResourceRecord rr=*j;
rr.ttl-=d_now.tv_sec;
ret.push_back(rr);
if(!(qtype==QType(QType::CNAME))) { // perhaps they really wanted a CNAME!
set<GetBestNSAnswer>beenthere;
res=doResolve(j->content, qtype, ret, depth+1, beenthere);
}
else
res=0;
return true;
}
}
}
LOG(prefix<<qname<<": No CNAME cache hit of '"<< (qname+"|CNAME") <<"' found"<<endl);
return false;
}
bool SyncRes::doCacheCheck(const string &qname, const QType &qtype, vector<DNSResourceRecord>&ret, int depth, int &res)
{
bool giveNegative=false;
string prefix;
if(doLog()) {
prefix=d_prefix;
prefix.append(depth, ' ');
}
string sqname(qname);
QType sqt(qtype);
uint32_t sttl=0;
// cout<<"Lookup for '"<<qname<<"|"<<qtype.getName()<<"'\n";
pair<negcache_t::const_iterator, negcache_t::const_iterator> range=t_sstorage->negcache.equal_range(tie(qname));
negcache_t::iterator ni;
for(ni=range.first; ni != range.second; ni++) {
// we have something
if(ni->d_qtype.getCode() == 0 || ni->d_qtype == qtype) {
res=0;
if((uint32_t)d_now.tv_sec < ni->d_ttd) {
sttl=ni->d_ttd - d_now.tv_sec;
if(ni->d_qtype.getCode()) {
LOG(prefix<<qname<<": "<<qtype.getName()<<" is negatively cached via '"<<ni->d_qname<<"' for another "<<sttl<<" seconds"<<endl);
res = RCode::NoError;
}
else {
LOG(prefix<<qname<<": Entire record '"<<qname<<"', is negatively cached via '"<<ni->d_qname<<"' for another "<<sttl<<" seconds"<<endl);
res= RCode::NXDomain;
}
giveNegative=true;
sqname=ni->d_qname;
sqt=QType::SOA;
moveCacheItemToBack(t_sstorage->negcache, ni);
break;
}
else {
LOG(prefix<<qname<<": Entire record '"<<qname<<"' or type was negatively cached, but entry expired"<<endl);
moveCacheItemToFront(t_sstorage->negcache, ni);
}
}
}
set<DNSResourceRecord> cset;
bool found=false, expired=false;
if(t_RC->get(d_now.tv_sec, sqname, sqt, &cset) > 0) {
LOG(prefix<<sqname<<": Found cache hit for "<<sqt.getName()<<": ");
for(set<DNSResourceRecord>::const_iterator j=cset.begin();j!=cset.end();++j) {
LOG(j->content);
if(j->ttl>(unsigned int) d_now.tv_sec) {
DNSResourceRecord rr=*j;
rr.ttl-=d_now.tv_sec;
if(giveNegative) {
rr.d_place=DNSResourceRecord::AUTHORITY;
rr.ttl=sttl;
}
ret.push_back(rr);
LOG("[ttl="<<rr.ttl<<"] ");
found=true;
}
else {
LOG("[expired] ");
expired=true;
}
}
LOG(endl);
if(found && !expired) {
if(!giveNegative)
res=0;
return true;
}
else
LOG(prefix<<qname<<": cache had only stale entries"<<endl);
}
return false;
}
bool SyncRes::moreSpecificThan(const string& a, const string &b)
{
static string dot(".");
int counta=(a!=dot), countb=(b!=dot);
for(string::size_type n=0;n<a.size();++n)
if(a[n]=='.')
counta++;
for(string::size_type n=0;n<b.size();++n)
if(b[n]=='.')
countb++;
return counta>countb;
}
struct speedOrder
{
speedOrder(map<string,double> &speeds) : d_speeds(speeds) {}
bool operator()(const string &a, const string &b) const
{
return d_speeds[a] < d_speeds[b];
}
map<string, double>& d_speeds;
};
inline vector<string> SyncRes::shuffleInSpeedOrder(set<string, CIStringCompare> &tnameservers, const string &prefix)
{
vector<string> rnameservers;
rnameservers.reserve(tnameservers.size());
BOOST_FOREACH(const string& str, tnameservers) {
rnameservers.push_back(str);
}
map<string, double> speeds;
BOOST_FOREACH(const string& val, rnameservers) {
double speed;
speed=t_sstorage->nsSpeeds[val].get(&d_now);
speeds[val]=speed;
}
random_shuffle(rnameservers.begin(),rnameservers.end(), dns_random);
speedOrder so(speeds);
stable_sort(rnameservers.begin(),rnameservers.end(), so);
if(doLog()) {
LOG(prefix<<"Nameservers: ");
for(vector<string>::const_iterator i=rnameservers.begin();i!=rnameservers.end();++i) {
if(i!=rnameservers.begin()) {
LOG(", ");
if(!((i-rnameservers.begin())%3)) {
LOG(endl<<prefix<<" ");
}
}
LOG(*i<<"(" << (boost::format("%0.2f") % (speeds[*i]/1000.0)).str() <<"ms)");
}
LOG(endl);
}
return rnameservers;
}
struct TCacheComp
{
bool operator()(const pair<string, QType>& a, const pair<string, QType>& b) const
{
if(pdns_ilexicographical_compare(a.first, b.first))
return true;
if(pdns_ilexicographical_compare(b.first, a.first))
return false;
return a.second < b.second;
}
};
static bool magicAddrMatch(const QType& query, const QType& answer)
{
if(query.getCode() != QType::ADDR)
return false;
return answer.getCode() == QType::A || answer.getCode() == QType::AAAA;
}
/** returns -1 in case of no results, rcode otherwise */
int SyncRes::doResolveAt(set<string, CIStringCompare> nameservers, string auth, bool flawedNSSet, const string &qname, const QType &qtype,
vector<DNSResourceRecord>&ret,
int depth, set<GetBestNSAnswer>&beenthere)
{
string prefix;
if(doLog()) {
prefix=d_prefix;
prefix.append(depth, ' ');
}
LOG(prefix<<qname<<": Cache consultations done, have "<<(unsigned int)nameservers.size()<<" NS to contact"<<endl);
for(;;) { // we may get more specific nameservers
vector<string > rnameservers = shuffleInSpeedOrder(nameservers, doLog() ? (prefix+qname+": ") : string() );
for(vector<string >::const_iterator tns=rnameservers.begin();;++tns) {
if(tns==rnameservers.end()) {
LOG(prefix<<qname<<": Failed to resolve via any of the "<<(unsigned int)rnameservers.size()<<" offered NS at level '"<<auth<<"'"<<endl);
if(auth!="." && flawedNSSet) {
LOG(prefix<<qname<<": Ageing nameservers for level '"<<auth<<"', next query might succeed"<<endl);
if(t_RC->doAgeCache(d_now.tv_sec, auth, QType::NS, 10))
g_stats.nsSetInvalidations++;
}
return -1;
}
// this line needs to identify the 'self-resolving' behaviour, but we get it wrong now
if(pdns_iequals(qname, *tns) && qtype.getCode()==QType::A && rnameservers.size() > (unsigned)(1+1*s_doIPv6)) {
LOG(prefix<<qname<<": Not using NS to resolve itself!"<<endl);
continue;
}
typedef vector<ComboAddress> remoteIPs_t;
remoteIPs_t remoteIPs;
remoteIPs_t::const_iterator remoteIP;
bool doTCP=false;
int resolveret;
bool pierceDontQuery=false;
bool sendRDQuery=false;
LWResult lwr;
if(tns->empty()) {
LOG(prefix<<qname<<": Domain is out-of-band"<<endl);
doOOBResolve(qname, qtype, lwr.d_result, depth, lwr.d_rcode);
lwr.d_tcbit=false;
lwr.d_aabit=true;
}
else {
LOG(prefix<<qname<<": Trying to resolve NS '"<<*tns<< "' ("<<1+tns-rnameservers.begin()<<"/"<<(unsigned int)rnameservers.size()<<")"<<endl);
if(!isCanonical(*tns)) {
LOG(prefix<<qname<<": Domain has hardcoded nameserver(s)"<<endl);
string txtAddr = *tns;
if(!tns->empty()) {
sendRDQuery = txtAddr[0] == '+';
txtAddr=txtAddr.c_str()+1;
}
ComboAddress addr=parseIPAndPort(txtAddr, 53);
remoteIPs.push_back(addr);
pierceDontQuery=true;
}
else {
remoteIPs=getAddrs(*tns, depth+2, beenthere);
pierceDontQuery=false;
}
if(remoteIPs.empty()) {
LOG(prefix<<qname<<": Failed to get IP for NS "<<*tns<<", trying next if available"<<endl);
flawedNSSet=true;
continue;
}
else {
LOG(prefix<<qname<<": Resolved '"+auth+"' NS "<<*tns<<" to: ");
for(remoteIP = remoteIPs.begin(); remoteIP != remoteIPs.end(); ++remoteIP) {
if(remoteIP != remoteIPs.begin()) {
LOG(", ");
}
LOG(remoteIP->toString());
}
LOG(endl);
}
for(remoteIP = remoteIPs.begin(); remoteIP != remoteIPs.end(); ++remoteIP) {
LOG(prefix<<qname<<": Trying IP "<< remoteIP->toStringWithPort() <<", asking '"<<qname<<"|"<<qtype.getName()<<"'"<<endl);
extern NetmaskGroup* g_dontQuery;
if(t_sstorage->throttle.shouldThrottle(d_now.tv_sec, make_tuple(*remoteIP, "", 0))) {
LOG(prefix<<qname<<": server throttled "<<endl);
s_throttledqueries++; d_throttledqueries++;
continue;
}
else if(t_sstorage->throttle.shouldThrottle(d_now.tv_sec, make_tuple(*remoteIP, qname, qtype.getCode()))) {
LOG(prefix<<qname<<": query throttled "<<endl);
s_throttledqueries++; d_throttledqueries++;
continue;
}
else if(!pierceDontQuery && g_dontQuery && g_dontQuery->match(&*remoteIP)) {
LOG(prefix<<qname<<": not sending query to " << remoteIP->toString() << ", blocked by 'dont-query' setting" << endl);
s_dontqueries++;
continue;
}
else {
s_outqueries++; d_outqueries++;
TryTCP:
if(doTCP) {
LOG(prefix<<qname<<": using TCP with "<< remoteIP->toStringWithPort() <<endl);
s_tcpoutqueries++; d_tcpoutqueries++;
}
resolveret=asyncresolveWrapper(*remoteIP, qname, qtype.getCode(),
doTCP, sendRDQuery, &d_now, &lwr); // <- we go out on the wire!
if(resolveret != 1) {
if(resolveret==0) {
LOG(prefix<<qname<<": timeout resolving "<< (doTCP ? "over TCP" : "")<<endl);
d_timeouts++;
s_outgoingtimeouts++;
}
else if(resolveret==-2) {
LOG(prefix<<qname<<": hit a local resource limit resolving"<< (doTCP ? " over TCP" : "")<<", probable error: "<<stringerror()<<endl);
g_stats.resourceLimits++;
}
else {
s_unreachables++; d_unreachables++;
LOG(prefix<<qname<<": error resolving"<< (doTCP ? " over TCP" : "") <<", possible error: "<<strerror(errno)<< endl);
}
if(resolveret!=-2) { // don't account for resource limits, they are our own fault
{
t_sstorage->nsSpeeds[*tns].submit(*remoteIP, 1000000, &d_now); // 1 sec
}
if (s_serverdownmaxfails > 0 && t_sstorage->fails.incr(*remoteIP) >= s_serverdownmaxfails) {
LOG(prefix<<qname<<": Max fails reached resolving on "<< remoteIP->toString() <<". Going full throttle for 1 minute" <<endl);
t_sstorage->throttle.throttle(d_now.tv_sec, make_tuple(*remoteIP, "", 0), s_serverdownthrottletime, 10000); // mark server as down
} else if(resolveret==-1)
t_sstorage->throttle.throttle(d_now.tv_sec, make_tuple(*remoteIP, qname, qtype.getCode()), 60, 100); // unreachable, 1 minute or 100 queries
else
t_sstorage->throttle.throttle(d_now.tv_sec, make_tuple(*remoteIP, qname, qtype.getCode()), 10, 5); // timeout
}
continue;
}
if(lwr.d_rcode==RCode::ServFail || lwr.d_rcode==RCode::Refused) {
LOG(prefix<<qname<<": "<<*tns<<" returned a "<< (lwr.d_rcode==RCode::ServFail ? "ServFail" : "Refused") << ", trying sibling IP or NS"<<endl);
t_sstorage->throttle.throttle(d_now.tv_sec,make_tuple(*remoteIP, qname, qtype.getCode()),60,3); // servfail or refused
continue;
}
if(s_serverdownmaxfails > 0)
t_sstorage->fails.clear(*remoteIP);
break; // this IP address worked!
wasLame:; // well, it didn't
LOG(prefix<<qname<<": status=NS "<<*tns<<" ("<< remoteIP->toString() <<") is lame for '"<<auth<<"', trying sibling IP or NS"<<endl);
t_sstorage->throttle.throttle(d_now.tv_sec, make_tuple(*remoteIP, qname, qtype.getCode()), 60, 100); // lame
}
}
if(remoteIP == remoteIPs.end()) // we tried all IP addresses, none worked
continue;
if(lwr.d_tcbit) {
if(!doTCP) {
doTCP=true;
LOG(prefix<<qname<<": truncated bit set, retrying via TCP"<<endl);
goto TryTCP;
}
LOG(prefix<<qname<<": truncated bit set, over TCP?"<<endl);
return RCode::ServFail;
}
LOG(prefix<<qname<<": Got "<<(unsigned int)lwr.d_result.size()<<" answers from "<<*tns<<" ("<< remoteIP->toString() <<"), rcode="<<lwr.d_rcode<<" ("<<RCode::to_s(lwr.d_rcode)<<"), aa="<<lwr.d_aabit<<", in "<<lwr.d_usec/1000<<"ms"<<endl);
/* // for you IPv6 fanatics :-)