-
Notifications
You must be signed in to change notification settings - Fork 780
/
DNS.cc
1709 lines (1537 loc) · 50.7 KB
/
DNS.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
/** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "P_DNS.h" /* MAGIC_EDITING_TAG */
#include <ts/ink_inet.h>
#ifdef SPLIT_DNS
#include "I_SplitDNS.h"
#endif
#define SRV_COST (RRFIXEDSZ + 0)
#define SRV_WEIGHT (RRFIXEDSZ + 2)
#define SRV_PORT (RRFIXEDSZ + 4)
#define SRV_SERVER (RRFIXEDSZ + 6)
#define SRV_FIXEDSZ (RRFIXEDSZ + 6)
EventType ET_DNS = ET_CALL;
//
// Config
//
int dns_timeout = DEFAULT_DNS_TIMEOUT;
int dns_retries = DEFAULT_DNS_RETRIES;
int dns_search = DEFAULT_DNS_SEARCH;
int dns_failover_number = DEFAULT_FAILOVER_NUMBER;
int dns_failover_period = DEFAULT_FAILOVER_PERIOD;
int dns_failover_try_period = DEFAULT_FAILOVER_TRY_PERIOD;
int dns_max_dns_in_flight = MAX_DNS_IN_FLIGHT;
int dns_validate_qname = 0;
unsigned int dns_handler_initialized = 0;
int dns_ns_rr = 0;
int dns_ns_rr_init_down = 1;
char *dns_ns_list = NULL;
char *dns_resolv_conf = NULL;
char *dns_local_ipv6 = NULL;
char *dns_local_ipv4 = NULL;
int dns_thread = 0;
int dns_prefer_ipv6 = 0;
namespace
{
// Currently only used for A and AAAA.
inline char const *
QtypeName(int qtype)
{
return T_AAAA == qtype ? "AAAA" : T_A == qtype ? "A" : "*";
}
inline bool
is_addr_query(int qtype)
{
return qtype == T_A || qtype == T_AAAA;
}
}
DNSProcessor dnsProcessor;
ClassAllocator<DNSEntry> dnsEntryAllocator("dnsEntryAllocator");
// Users are expected to free these entries in short order!
// We could page align this buffer to enable page flipping for recv...
ClassAllocator<HostEnt> dnsBufAllocator("dnsBufAllocator", 2);
//
// Function Prototypes
//
static bool dns_process(DNSHandler *h, HostEnt *ent, int len);
static DNSEntry *get_dns(DNSHandler *h, uint16_t id);
// returns true when e is done
static void dns_result(DNSHandler *h, DNSEntry *e, HostEnt *ent, bool retry);
static void write_dns(DNSHandler *h);
static bool write_dns_event(DNSHandler *h, DNSEntry *e);
// "reliable" name to try. need to build up first.
static int try_servers = 0;
static int local_num_entries = 1;
static int attempt_num_entries = 1;
char try_server_names[DEFAULT_NUM_TRY_SERVER][MAXDNAME];
static inline char *
strnchr(char *s, char c, int len)
{
while (*s && *s != c && len)
++s, --len;
return *s == c ? s : (char *)NULL;
}
static inline uint16_t
ink_get16(const uint8_t *src)
{
uint16_t dst;
NS_GET16(dst, src);
return dst;
}
void
HostEnt::free()
{
dnsBufAllocator.free(this);
}
void
make_ipv4_ptr(in_addr_t addr, char *buffer)
{
char *p = buffer;
uint8_t const *u = reinterpret_cast<uint8_t *>(&addr);
if (u[3] > 99)
*p++ = (u[3] / 100) + '0';
if (u[3] > 9)
*p++ = ((u[3] / 10) % 10) + '0';
*p++ = u[3] % 10 + '0';
*p++ = '.';
if (u[2] > 99)
*p++ = (u[2] / 100) + '0';
if (u[2] > 9)
*p++ = ((u[2] / 10) % 10) + '0';
*p++ = u[2] % 10 + '0';
*p++ = '.';
if (u[1] > 99)
*p++ = (u[1] / 100) + '0';
if (u[1] > 9)
*p++ = ((u[1] / 10) % 10) + '0';
*p++ = u[1] % 10 + '0';
*p++ = '.';
if (u[0] > 99)
*p++ = (u[0] / 100) + '0';
if (u[0] > 9)
*p++ = ((u[0] / 10) % 10) + '0';
*p++ = u[0] % 10 + '0';
*p++ = '.';
ink_strlcpy(p, "in-addr.arpa", MAXDNAME - (p - buffer + 1));
}
void
make_ipv6_ptr(in6_addr const *addr, char *buffer)
{
const char hex_digit[] = "0123456789abcdef";
char *p = buffer;
uint8_t const *src = addr->s6_addr;
int i;
for (i = TS_IP6_SIZE - 1; i >= 0; --i) {
*p++ = hex_digit[src[i] & 0x0f];
*p++ = '.';
*p++ = hex_digit[src[i] >> 4];
*p++ = '.';
}
ink_strlcpy(p, "ip6.arpa", MAXDNAME - (p - buffer + 1));
}
// Public functions
//
// See documentation is header files and Memos
//
int
DNSProcessor::start(int, size_t stacksize)
{
//
// Read configuration
//
REC_EstablishStaticConfigInt32(dns_retries, "proxy.config.dns.retries");
REC_EstablishStaticConfigInt32(dns_timeout, "proxy.config.dns.lookup_timeout");
REC_EstablishStaticConfigInt32(dns_search, "proxy.config.dns.search_default_domains");
REC_EstablishStaticConfigInt32(dns_failover_number, "proxy.config.dns.failover_number");
REC_EstablishStaticConfigInt32(dns_failover_period, "proxy.config.dns.failover_period");
REC_EstablishStaticConfigInt32(dns_max_dns_in_flight, "proxy.config.dns.max_dns_in_flight");
REC_EstablishStaticConfigInt32(dns_validate_qname, "proxy.config.dns.validate_query_name");
REC_EstablishStaticConfigInt32(dns_ns_rr, "proxy.config.dns.round_robin_nameservers");
REC_ReadConfigStringAlloc(dns_ns_list, "proxy.config.dns.nameservers");
REC_ReadConfigStringAlloc(dns_local_ipv4, "proxy.config.dns.local_ipv4");
REC_ReadConfigStringAlloc(dns_local_ipv6, "proxy.config.dns.local_ipv6");
REC_ReadConfigStringAlloc(dns_resolv_conf, "proxy.config.dns.resolv_conf");
REC_EstablishStaticConfigInt32(dns_thread, "proxy.config.dns.dedicated_thread");
if (dns_thread > 0) {
// TODO: Hmmm, should we just get a single thread some other way?
ET_DNS = eventProcessor.spawn_event_threads(1, "ET_DNS", stacksize);
initialize_thread_for_net(eventProcessor.eventthread[ET_DNS][0]);
} else {
// Initialize the first event thread for DNS.
ET_DNS = ET_CALL;
}
thread = eventProcessor.eventthread[ET_DNS][0];
dns_failover_try_period = dns_timeout + 1; // Modify the "default" accordingly
if (SplitDNSConfig::gsplit_dns_enabled) {
// reconfigure after threads start
SplitDNSConfig::reconfigure();
}
// Setup the default DNSHandler, it's used both by normal DNS, and SplitDNS (for PTR lookups etc.)
dns_init();
open();
return 0;
}
void
DNSProcessor::open(sockaddr const *target)
{
DNSHandler *h = new DNSHandler;
h->mutex = thread->mutex;
h->m_res = &l_res;
ats_ip_copy(&h->local_ipv4.sa, &local_ipv4.sa);
ats_ip_copy(&h->local_ipv6.sa, &local_ipv6.sa);
if (target)
ats_ip_copy(&h->ip, target);
else
ats_ip_invalidate(&h->ip); // marked to use default.
if (!dns_handler_initialized)
handler = h;
SET_CONTINUATION_HANDLER(h, &DNSHandler::startEvent);
thread->schedule_imm(h);
}
//
// Initialization
//
void
DNSProcessor::dns_init()
{
gethostname(try_server_names[0], 255);
Debug("dns", "localhost=%s", try_server_names[0]);
Debug("dns", "Round-robin nameservers = %d", dns_ns_rr);
IpEndpoint nameserver[MAX_NAMED];
size_t nserv = 0;
if (dns_ns_list) {
Debug("dns", "Nameserver list specified \"%s\"", dns_ns_list);
int i;
char *last;
char *ns_list = ats_strdup(dns_ns_list);
char *ns = (char *)strtok_r(ns_list, " ,;\t\r", &last);
for (i = 0, nserv = 0; (i < MAX_NAMED) && ns; ++i) {
Debug("dns", "Nameserver list - parsing \"%s\"", ns);
bool err = false;
int prt = DOMAIN_SERVICE_PORT;
char *colon = 0; // where the port colon is.
// Check for IPv6 notation.
if ('[' == *ns) {
char *ndx = strchr(ns + 1, ']');
if (ndx) {
if (':' == ndx[1])
colon = ndx + 1;
} else {
err = true;
Warning("Unmatched '[' in address for nameserver '%s', discarding.", ns);
}
} else
colon = strchr(ns, ':');
if (!err && colon) {
*colon = '\0';
// coverity[secure_coding]
if (sscanf(colon + 1, "%d%*s", &prt) != 1) {
Debug("dns", "Unable to parse port number '%s' for nameserver '%s', discardin.", colon + 1, ns);
Warning("Unable to parse port number '%s' for nameserver '%s', discarding.", colon + 1, ns);
err = true;
}
}
if (!err && 0 != ats_ip_pton(ns, &nameserver[nserv].sa)) {
Debug("dns", "Invalid IP address given for nameserver '%s', discarding", ns);
Warning("Invalid IP address given for nameserver '%s', discarding", ns);
err = true;
}
if (!err) {
ip_port_text_buffer buff;
ats_ip_port_cast(&nameserver[nserv].sa) = htons(prt);
Debug("dns", "Adding nameserver %s to nameserver list", ats_ip_nptop(&nameserver[nserv].sa, buff, sizeof(buff)));
++nserv;
}
ns = (char *)strtok_r(NULL, " ,;\t\r", &last);
}
ats_free(ns_list);
}
// The default domain (5th param) and search list (6th param) will
// come from /etc/resolv.conf.
if (ink_res_init(&l_res, nameserver, nserv, dns_search, NULL, NULL, dns_resolv_conf) < 0)
Warning("Failed to build DNS res records for the servers (%s). Using resolv.conf.", dns_ns_list);
// Check for local forced bindings.
if (dns_local_ipv6) {
if (0 != ats_ip_pton(dns_local_ipv6, &local_ipv6)) {
ats_ip_invalidate(&local_ipv6);
Warning("Invalid IP address '%s' for dns.local_ipv6 value, discarding.", dns_local_ipv6);
} else if (!ats_is_ip6(&local_ipv6.sa)) {
ats_ip_invalidate(&local_ipv6);
Warning("IP address '%s' for dns.local_ipv6 value was not IPv6, discarding.", dns_local_ipv6);
}
}
if (dns_local_ipv4) {
if (0 != ats_ip_pton(dns_local_ipv4, &local_ipv4)) {
ats_ip_invalidate(&local_ipv4);
Warning("Invalid IP address '%s' for dns.local_ipv4 value, discarding.", dns_local_ipv4);
} else if (!ats_is_ip4(&local_ipv4.sa)) {
ats_ip_invalidate(&local_ipv4);
Warning("IP address '%s' for dns.local_ipv4 value was not IPv4, discarding.", dns_local_ipv4);
}
}
}
/**
Inter-OS portability for dn_expand. dn_expand() expands the compressed
domain name comp_dn to a full domain name. Expanded names are converted
to upper case. msg is a pointer to the beginning of the message,
exp_dn is a pointer to a buffer of size length for the result. The
size of compressed name is returned or -1 if there was an error.
*/
inline int
ink_dn_expand(const u_char *msg, const u_char *eom, const u_char *comp_dn, u_char *exp_dn, int length)
{
return ::dn_expand((unsigned char *)msg, (unsigned char *)eom, (unsigned char *)comp_dn, (char *)exp_dn, length);
}
DNSProcessor::DNSProcessor() : thread(NULL), handler(NULL)
{
ink_zero(l_res);
ink_zero(local_ipv6);
ink_zero(local_ipv4);
}
void
DNSEntry::init(const char *x, int len, int qtype_arg, Continuation *acont, DNSProcessor::Options const &opt)
{
qtype = qtype_arg;
host_res_style = opt.host_res_style;
if (is_addr_query(qtype)) {
// adjust things based on family preference.
if (HOST_RES_IPV4 == host_res_style || HOST_RES_IPV4_ONLY == host_res_style) {
qtype = T_A;
} else if (HOST_RES_IPV6 == host_res_style || HOST_RES_IPV6_ONLY == host_res_style) {
qtype = T_AAAA;
}
}
submit_time = Thread::get_hrtime();
action = acont;
submit_thread = acont->mutex->thread_holding;
#ifdef SPLIT_DNS
if (SplitDNSConfig::gsplit_dns_enabled) {
dnsH = opt.handler ? opt.handler : dnsProcessor.handler;
} else {
dnsH = dnsProcessor.handler;
}
#else
dnsH = dnsProcessor.handler;
#endif // SPLIT_DNS
dnsH->txn_lookup_timeout = opt.timeout;
mutex = dnsH->mutex;
if (is_addr_query(qtype) || qtype == T_SRV) {
if (len) {
len = len > (MAXDNAME - 1) ? (MAXDNAME - 1) : len;
memcpy(qname, x, len);
qname[len] = 0;
orig_qname_len = qname_len = len;
} else {
qname_len = ink_strlcpy(qname, x, MAXDNAME);
orig_qname_len = qname_len;
}
} else { // T_PTR
IpAddr const *ip = reinterpret_cast<IpAddr const *>(x);
if (ip->isIp6())
make_ipv6_ptr(&ip->_addr._ip6, qname);
else if (ip->isIp4())
make_ipv4_ptr(ip->_addr._ip4, qname);
else
ink_assert(!"T_PTR query to DNS must be IP address.");
}
SET_HANDLER((DNSEntryHandler)&DNSEntry::mainEvent);
}
/**
Open (and close) connections as necessary and also assures that the
epoll fd struct is properly updated.
*/
void
DNSHandler::open_con(sockaddr const *target, bool failed, int icon)
{
ip_port_text_buffer ip_text;
PollDescriptor *pd = get_PollDescriptor(dnsProcessor.thread);
if (!icon && target) {
ats_ip_copy(&ip, target);
} else if (!target) {
target = &ip.sa;
}
Debug("dns", "open_con: opening connection %s", ats_ip_nptop(target, ip_text, sizeof ip_text));
if (con[icon].fd != NO_FD) { // Remove old FD from epoll fd
con[icon].eio.stop();
con[icon].close();
}
if (con[icon].connect(target, DNSConnection::Options()
.setNonBlockingConnect(true)
.setNonBlockingIo(true)
.setUseTcp(false)
.setBindRandomPort(true)
.setLocalIpv6(&local_ipv6.sa)
.setLocalIpv4(&local_ipv4.sa)) < 0) {
Debug("dns", "opening connection %s FAILED for %d", ip_text, icon);
if (!failed) {
if (dns_ns_rr)
rr_failure(icon);
else
failover();
}
return;
} else {
ns_down[icon] = 0;
if (con[icon].eio.start(pd, &con[icon], EVENTIO_READ) < 0) {
Error("[iocore_dns] open_con: Failed to add %d server to epoll list\n", icon);
} else {
con[icon].num = icon;
Debug("dns", "opening connection %s SUCCEEDED for %d", ip_text, icon);
}
}
}
void
DNSHandler::validate_ip()
{
if (!ip.isValid()) {
// Invalid, switch to default.
// seems that res_init always sets m_res.nscount to at least 1!
if (!m_res->nscount || !ats_ip_copy(&ip.sa, &m_res->nsaddr_list[0].sa)) {
Warning("bad nameserver config, fallback to loopback");
ip.setToLoopback(AF_INET);
}
}
}
/**
Initial state of the DNSHandler. Can reinitialize the running DNS
handler to a new nameserver.
*/
int
DNSHandler::startEvent(int /* event ATS_UNUSED */, Event *e)
{
//
// If this is for the default server, get it
Debug("dns", "DNSHandler::startEvent: on thread %d", e->ethread->id);
this->validate_ip();
if (!dns_handler_initialized) {
//
// If we are THE handler, open connection and configure for
// periodic execution.
//
dns_handler_initialized = 1;
SET_HANDLER(&DNSHandler::mainEvent);
if (dns_ns_rr) {
int max_nscount = m_res->nscount;
if (max_nscount > MAX_NAMED)
max_nscount = MAX_NAMED;
n_con = 0;
for (int i = 0; i < max_nscount; i++) {
ip_port_text_buffer buff;
sockaddr *sa = &m_res->nsaddr_list[i].sa;
if (ats_is_ip(sa)) {
open_con(sa, false, n_con);
++n_con;
Debug("dns_pas", "opened connection to %s, n_con = %d", ats_ip_nptop(sa, buff, sizeof(buff)), n_con);
}
}
dns_ns_rr_init_down = 0;
} else {
open_con(0); // use current target address.
n_con = 1;
}
e->ethread->schedule_every(this, DNS_PERIOD);
return EVENT_CONT;
} else {
ink_assert(false); // I.e. this should never really happen
return EVENT_DONE;
}
}
/**
Initial state of the DSNHandler. Can reinitialize the running DNS
hander to a new nameserver.
*/
int
DNSHandler::startEvent_sdns(int /* event ATS_UNUSED */, Event *e)
{
Debug("dns", "DNSHandler::startEvent_sdns: on thread %d", e->ethread->id);
this->validate_ip();
SET_HANDLER(&DNSHandler::mainEvent);
open_con(&ip.sa, false, n_con);
++n_con; // TODO should n_con be zeroed?
e->schedule_every(DNS_PERIOD);
return EVENT_CONT;
}
static inline int
_ink_res_mkquery(ink_res_state res, char *qname, int qtype, char *buffer)
{
int r = ink_res_mkquery(res, QUERY, qname, C_IN, qtype, NULL, 0, NULL, (unsigned char *)buffer, MAX_DNS_PACKET_LEN);
return r;
}
void
DNSHandler::recover()
{
ip_text_buffer buff;
Warning("connection to DNS server %s restored", ats_ip_ntop(&ip.sa, buff, sizeof(buff)));
name_server = 0;
switch_named(name_server);
}
void
DNSHandler::retry_named(int ndx, ink_hrtime t, bool reopen)
{
if (reopen && ((t - last_primary_reopen) > DNS_PRIMARY_REOPEN_PERIOD)) {
Debug("dns", "retry_named: reopening DNS connection for index %d", ndx);
last_primary_reopen = t;
con[ndx].close();
open_con(&m_res->nsaddr_list[ndx].sa, true, ndx);
}
char buffer[MAX_DNS_PACKET_LEN];
Debug("dns", "trying to resolve '%s' from DNS connection, ndx %d", try_server_names[try_servers], ndx);
int r = _ink_res_mkquery(m_res, try_server_names[try_servers], T_A, buffer);
try_servers = (try_servers + 1) % countof(try_server_names);
ink_assert(r >= 0);
if (r >= 0) { // looking for a bounce
int res = socketManager.send(con[ndx].fd, buffer, r, 0);
Debug("dns", "ping result = %d", res);
}
}
void
DNSHandler::try_primary_named(bool reopen)
{
ink_hrtime t = Thread::get_hrtime();
if (reopen && ((t - last_primary_reopen) > DNS_PRIMARY_REOPEN_PERIOD)) {
Debug("dns", "try_primary_named: reopening primary DNS connection");
last_primary_reopen = t;
open_con(&ip.sa, true, 0);
}
if ((t - last_primary_retry) > DNS_PRIMARY_RETRY_PERIOD) {
char buffer[MAX_DNS_PACKET_LEN];
last_primary_retry = t;
Debug("dns", "trying to resolve '%s' from primary DNS connection", try_server_names[try_servers]);
int r = _ink_res_mkquery(m_res, try_server_names[try_servers], T_A, buffer);
// if try_server_names[] is not full, round-robin within the
// filled entries.
if (local_num_entries < DEFAULT_NUM_TRY_SERVER)
try_servers = (try_servers + 1) % local_num_entries;
else
try_servers = (try_servers + 1) % countof(try_server_names);
ink_assert(r >= 0);
if (r >= 0) { // looking for a bounce
int res = socketManager.send(con[0].fd, buffer, r, 0);
Debug("dns", "ping result = %d", res);
}
}
}
void
DNSHandler::switch_named(int ndx)
{
for (DNSEntry *e = entries.head; e; e = (DNSEntry *)e->link.next) {
e->written_flag = 0;
if (e->retries < dns_retries)
++(e->retries); // give them another chance
}
in_flight = 0;
received_one(ndx); // reset failover counters
}
/** Fail over to another name server. */
void
DNSHandler::failover()
{
Debug("dns", "failover: initiating failover attempt, current name_server=%d", name_server);
// no hope, if we have only one server
if (m_res->nscount > 1) {
ip_text_buffer buff1, buff2;
int max_nscount = m_res->nscount;
if (max_nscount > MAX_NAMED)
max_nscount = MAX_NAMED;
sockaddr const *old_addr = &m_res->nsaddr_list[name_server].sa;
name_server = (name_server + 1) % max_nscount;
Debug("dns", "failover: failing over to name_server=%d", name_server);
IpEndpoint target;
ats_ip_copy(&target.sa, &m_res->nsaddr_list[name_server].sa);
Warning("failover: connection to DNS server %s lost, move to %s", ats_ip_ntop(old_addr, buff1, sizeof(buff1)),
ats_ip_ntop(&target.sa, buff2, sizeof(buff2)));
if (!target.isValid())
target.setToLoopback(AF_INET);
open_con(&target.sa, true, name_server);
if (n_con <= name_server)
n_con = name_server + 1;
switch_named(name_server);
} else {
ip_text_buffer buff;
Warning("failover: connection to DNS server %s lost, retrying", ats_ip_ntop(&ip.sa, buff, sizeof(buff)));
}
}
/** Mark one of the nameservers as down. */
void
DNSHandler::rr_failure(int ndx)
{
// no hope, if we have only one server
if (!ns_down[ndx]) {
ip_text_buffer buff;
// mark this nameserver as down
Debug("dns", "rr_failure: Marking nameserver %d as down", ndx);
ns_down[ndx] = 1;
Warning("connection to DNS server %s lost, marking as down", ats_ip_ntop(&m_res->nsaddr_list[ndx].sa, buff, sizeof(buff)));
}
int nscount = m_res->nscount;
if (nscount > MAX_NAMED)
nscount = MAX_NAMED;
// See if all nameservers are down
int all_down = 1;
for (int i = 0; i < nscount && all_down; i++) {
Debug("dns", "nsdown[%d]=%d", i, ns_down[i]);
if (!ns_down[i]) {
all_down = 0;
}
}
if (all_down && !dns_ns_rr_init_down) {
Warning("connection to all DNS servers lost, retrying");
// actual retries will be done in retry_named called from mainEvent
// mark any outstanding requests as not sent for later retry
for (DNSEntry *e = entries.head; e; e = (DNSEntry *)e->link.next) {
e->written_flag = 0;
if (e->retries < dns_retries)
++(e->retries); // give them another chance
--in_flight;
DNS_DECREMENT_DYN_STAT(dns_in_flight_stat);
}
} else {
// move outstanding requests that were sent to this nameserver to another
for (DNSEntry *e = entries.head; e; e = (DNSEntry *)e->link.next) {
if (e->which_ns == ndx) {
e->written_flag = 0;
if (e->retries < dns_retries)
++(e->retries); // give them another chance
--in_flight;
DNS_DECREMENT_DYN_STAT(dns_in_flight_stat);
}
}
}
}
static inline unsigned int
get_rcode(char *buff)
{
return reinterpret_cast<HEADER *>(buff)->rcode;
}
static inline unsigned int
get_rcode(HostEnt *ent)
{
return get_rcode(reinterpret_cast<char *>(ent));
}
static bool
good_rcode(char *buff)
{
unsigned int r = get_rcode(buff);
return NOERROR == r || NXDOMAIN == r;
}
void
DNSHandler::recv_dns(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
{
DNSConnection *dnsc = NULL;
ip_text_buffer ipbuff1, ipbuff2;
while ((dnsc = (DNSConnection *)triggered.dequeue())) {
while (1) {
IpEndpoint from_ip;
socklen_t from_length = sizeof(from_ip);
if (!hostent_cache)
hostent_cache = dnsBufAllocator.alloc();
HostEnt *buf = hostent_cache;
int res = socketManager.recvfrom(dnsc->fd, buf->buf, MAX_DNS_PACKET_LEN, 0, &from_ip.sa, &from_length);
if (res == -EAGAIN)
break;
if (res <= 0) {
Debug("dns", "named error: %d", res);
if (dns_ns_rr)
rr_failure(dnsc->num);
else if (dnsc->num == name_server)
failover();
break;
}
// verify that this response came from the correct server
if (!ats_ip_addr_eq(&dnsc->ip.sa, &from_ip.sa)) {
Warning("unexpected DNS response from %s (expected %s)", ats_ip_ntop(&from_ip.sa, ipbuff1, sizeof ipbuff1),
ats_ip_ntop(&dnsc->ip.sa, ipbuff2, sizeof ipbuff2));
continue;
}
hostent_cache = 0;
buf->packet_size = res;
Debug("dns", "received packet size = %d", res);
if (dns_ns_rr) {
Debug("dns", "round-robin: nameserver %d DNS response code = %d", dnsc->num, get_rcode(buf));
if (good_rcode(buf->buf)) {
received_one(dnsc->num);
if (ns_down[dnsc->num]) {
Warning("connection to DNS server %s restored",
ats_ip_ntop(&m_res->nsaddr_list[dnsc->num].sa, ipbuff1, sizeof ipbuff1));
ns_down[dnsc->num] = 0;
}
}
} else {
if (!dnsc->num) {
Debug("dns", "primary DNS response code = %d", get_rcode(buf));
if (good_rcode(buf->buf)) {
if (name_server)
recover();
else
received_one(name_server);
}
}
}
Ptr<HostEnt> protect_hostent = make_ptr(buf);
if (dns_process(this, buf, res)) {
if (dnsc->num == name_server)
received_one(name_server);
}
}
}
}
/** Main event for the DNSHandler. Attempt to read from and write to named. */
int
DNSHandler::mainEvent(int event, Event *e)
{
recv_dns(event, e);
if (dns_ns_rr) {
ink_hrtime t = Thread::get_hrtime();
if (t - last_primary_retry > DNS_PRIMARY_RETRY_PERIOD) {
for (int i = 0; i < n_con; i++) {
if (ns_down[i]) {
Debug("dns", "mainEvent: nameserver = %d is down", i);
retry_named(i, t, true);
}
}
last_primary_retry = t;
}
for (int i = 0; i < n_con; i++) {
if (!ns_down[i] && failover_soon(i)) {
Debug("dns", "mainEvent: nameserver = %d failover soon", name_server);
if (failover_now(i))
rr_failure(i);
else {
Debug("dns", "mainEvent: nameserver = %d no failover now - retrying", i);
retry_named(i, t, false);
++failover_soon_number[i];
}
}
}
} else {
if (failover_soon(name_server)) {
Debug("dns", "mainEvent: will failover soon");
if (failover_now(name_server)) {
Debug("dns", "mainEvent: failing over now to another nameserver");
failover();
} else {
try_primary_named(false);
++failover_soon_number[name_server];
}
} else if (name_server) // not on the primary named
try_primary_named(true);
}
if (entries.head)
write_dns(this);
return EVENT_CONT;
}
/** Find a DNSEntry by id. */
inline static DNSEntry *
get_dns(DNSHandler *h, uint16_t id)
{
for (DNSEntry *e = h->entries.head; e; e = (DNSEntry *)e->link.next) {
if (e->once_written_flag) {
for (int j = 0; j < MAX_DNS_RETRIES; j++) {
if (e->id[j] == id) {
return e;
} else if (e->id[j] < 0) {
goto Lnext;
}
}
}
Lnext:;
}
return NULL;
}
/** Find a DNSEntry by query name and type. */
inline static DNSEntry *
get_entry(DNSHandler *h, char *qname, int qtype)
{
for (DNSEntry *e = h->entries.head; e; e = (DNSEntry *)e->link.next) {
if (e->qtype == qtype) {
if (is_addr_query(qtype)) {
if (!strcmp(qname, e->qname))
return e;
} else if (0 == memcmp(qname, e->qname, e->qname_len))
return e;
}
}
return NULL;
}
/** Write up to dns_max_dns_in_flight entries. */
static void
write_dns(DNSHandler *h)
{
ProxyMutex *mutex = h->mutex.get();
DNS_INCREMENT_DYN_STAT(dns_total_lookups_stat);
int max_nscount = h->m_res->nscount;
if (max_nscount > MAX_NAMED)
max_nscount = MAX_NAMED;
if (max_nscount <= 0) {
Warning("There is no name server found in the resolv.conf");
if (h->entries.head) {
dns_result(h, h->entries.head, NULL, false);
}
return;
}
if (h->in_write_dns)
return;
h->in_write_dns = true;
// Debug("dns", "in_flight: %d, dns_max_dns_in_flight: %d", h->in_flight, dns_max_dns_in_flight);
if (h->in_flight < dns_max_dns_in_flight) {
DNSEntry *e = h->entries.head;
while (e) {
DNSEntry *n = (DNSEntry *)e->link.next;
if (!e->written_flag) {
if (dns_ns_rr) {
int ns_start = h->name_server;
do {
h->name_server = (h->name_server + 1) % max_nscount;
} while (h->ns_down[h->name_server] && h->name_server != ns_start);
}
if (!write_dns_event(h, e))
break;
}
if (h->in_flight >= dns_max_dns_in_flight)
break;
e = n;
}
}
h->in_write_dns = false;
}
uint16_t
DNSHandler::get_query_id()
{
uint16_t q1, q2;
q2 = q1 = (uint16_t)(generator.random() & 0xFFFF);
if (query_id_in_use(q2)) {
uint16_t i = q2 >> 6;
while (qid_in_flight[i] == UINT64_MAX) {
if (++i == sizeof(qid_in_flight) / sizeof(uint64_t)) {
i = 0;
}
if (i == q1 >> 6) {
Error("[iocore_dns] get_query_id: Exhausted all DNS query ids");
return q1;
}
}
i <<= 6;
q2 &= 0x3F;
while (query_id_in_use(i + q2)) {
++q2;
q2 &= 0x3F;
if (q2 == (q1 & 0x3F)) {
Error("[iocore_dns] get_query_id: Exhausted all DNS query ids");
return q1;
}
}
q2 += i;
}
set_query_id_in_use(q2);
return q2;
}
/**
Construct and Write the request for a single entry (using send(3N)).
@return true = keep going, false = give up for now.
*/
static bool
write_dns_event(DNSHandler *h, DNSEntry *e)
{
ProxyMutex *mutex = h->mutex.get();
union {
HEADER _h;
char _b[MAX_DNS_PACKET_LEN];
} blob;
int r = 0;
if ((r = _ink_res_mkquery(h->m_res, e->qname, e->qtype, blob._b)) <= 0) {
Debug("dns", "cannot build query: %s", e->qname);
dns_result(h, e, NULL, false);
return true;
}
uint16_t i = h->get_query_id();
blob._h.id = htons(i);
if (e->id[dns_retries - e->retries] >= 0) {
// clear previous id in case named was switched or domain was expanded
h->release_query_id(e->id[dns_retries - e->retries]);
}
e->id[dns_retries - e->retries] = i;
Debug("dns", "send query (qtype=%d) for %s to fd %d", e->qtype, e->qname, h->con[h->name_server].fd);
int s = socketManager.send(h->con[h->name_server].fd, blob._b, r, 0);
if (s != r) {
Debug("dns", "send() failed: qname = %s, %d != %d, nameserver= %d", e->qname, s, r, h->name_server);
// changed if condition from 'r < 0' to 's < 0' - 8/2001 pas
if (s < 0) {
if (dns_ns_rr)
h->rr_failure(h->name_server);
else
h->failover();
}
return false;
}
e->written_flag = true;
e->which_ns = h->name_server;
e->once_written_flag = true;
++h->in_flight;
DNS_INCREMENT_DYN_STAT(dns_in_flight_stat);
e->send_time = Thread::get_hrtime();