-
Notifications
You must be signed in to change notification settings - Fork 495
/
dns_internal.cc
1896 lines (1534 loc) · 55.5 KB
/
dns_internal.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
/*
* Copyright (C) 1996-2022 The Squid Software Foundation and contributors
*
* Squid software is distributed under GPLv2+ license and includes
* contributions from numerous individuals and organizations.
* Please see the COPYING and CONTRIBUTORS files for details.
*/
/* DEBUG: section 78 DNS lookups; interacts with dns/rfc1035.cc */
#include "squid.h"
#include "base/CodeContext.h"
#include "base/InstanceId.h"
#include "base/Random.h"
#include "base/RunnersRegistry.h"
#include "comm.h"
#include "comm/Connection.h"
#include "comm/ConnOpener.h"
#include "comm/Loops.h"
#include "comm/Read.h"
#include "comm/Write.h"
#include "debug/Messages.h"
#include "dlink.h"
#include "dns/forward.h"
#include "dns/rfc3596.h"
#include "event.h"
#include "fd.h"
#include "fde.h"
#include "ip/tools.h"
#include "MemBuf.h"
#include "mgr/Registration.h"
#include "snmp_agent.h"
#include "SquidConfig.h"
#include "Store.h"
#include "tools.h"
#include "util.h"
#include "wordlist.h"
#if SQUID_SNMP
#include "snmp_core.h"
#endif
#if HAVE_ARPA_NAMESER_H
#include <arpa/nameser.h>
#endif
#include <cerrno>
#if HAVE_RESOLV_H
#include <resolv.h>
#endif
#if _SQUID_WINDOWS_
#define REG_TCPIP_PARA_INTERFACES "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces"
#define REG_TCPIP_PARA "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters"
#define REG_VXD_MSTCP "SYSTEM\\CurrentControlSet\\Services\\VxD\\MSTCP"
#endif
#ifndef _PATH_RESCONF
#define _PATH_RESCONF "/etc/resolv.conf"
#endif
#ifndef NS_DEFAULTPORT
#define NS_DEFAULTPORT 53
#endif
#ifndef NS_MAXDNAME
#define NS_MAXDNAME 1025
#endif
#ifndef MAXDNSRCH
#define MAXDNSRCH 6
#endif
/* The buffer size required to store the maximum allowed search path */
#ifndef RESOLV_BUFSZ
#define RESOLV_BUFSZ NS_MAXDNAME * MAXDNSRCH + sizeof("search ") + 1
#endif
#define IDNS_MAX_TRIES 20
#define MAX_RCODE 17
#define MAX_ATTEMPT 3
static int RcodeMatrix[MAX_RCODE][MAX_ATTEMPT];
// NP: see http://www.iana.org/assignments/dns-parameters
static const char *Rcodes[] = {
/* RFC 1035 */
"Success",
"Packet Format Error",
"DNS Server Failure",
"Non-Existent Domain",
"Not Implemented",
"Query Refused",
/* RFC 2136 */
"Name Exists when it should not",
"RR Set Exists when it should not",
"RR Set that should exist does not",
"Server Not Authoritative for zone",
"Name not contained in zone",
/* unassigned */
"","","","","",
/* RFC 2671 */
"Bad OPT Version or TSIG Signature Failure"
};
typedef struct _sp sp;
class idns_query
{
CBDATA_CLASS(idns_query);
public:
idns_query():
codeContext(CodeContext::Current())
{
callback = nullptr;
memset(&query, 0, sizeof(query));
*buf = 0;
*name = 0;
*orig = 0;
memset(&start_t, 0, sizeof(start_t));
memset(&sent_t, 0, sizeof(sent_t));
memset(&queue_t, 0, sizeof(queue_t));
}
~idns_query() {
if (message)
rfc1035MessageDestroy(&message);
delete queue;
delete slave;
// master is just a back-reference
cbdataReferenceDone(callback_data);
}
hash_link hash;
rfc1035_query query;
char buf[RESOLV_BUFSZ];
char name[NS_MAXDNAME + 1];
char orig[NS_MAXDNAME + 1];
ssize_t sz = 0;
unsigned short query_id = 0; ///< random query ID sent to server; changes with every query sent
InstanceId<idns_query> xact_id; ///< identifies our "transaction", stays constant when query is retried
int nsends = 0;
int need_vc = 0;
bool permit_mdns = false;
int pending = 0;
struct timeval start_t;
struct timeval sent_t;
struct timeval queue_t;
dlink_node lru;
IDNSCB *callback;
void *callback_data = nullptr;
CodeContext::Pointer codeContext; ///< requestor's context
int attempt = 0;
int rcode = 0;
idns_query *queue = nullptr;
idns_query *slave = nullptr; // single linked list
idns_query *master = nullptr; // single pointer to a shared master
unsigned short domain = 0;
unsigned short do_searchpath = 0;
rfc1035_message *message = nullptr;
int ancount = 0;
const char *error = nullptr;
};
InstanceIdDefinitions(idns_query, "dns");
CBDATA_CLASS_INIT(idns_query);
class nsvc
{
CBDATA_CLASS(nsvc);
public:
explicit nsvc(size_t nsv) : ns(nsv), msg(new MemBuf()), queue(new MemBuf()) {}
~nsvc();
size_t ns = 0;
Comm::ConnectionPointer conn;
unsigned short msglen = 0;
int read_msglen = 0;
MemBuf *msg = nullptr;
MemBuf *queue = nullptr;
bool busy = true;
};
CBDATA_CLASS_INIT(nsvc);
class ns
{
public:
Ip::Address S;
int nqueries = 0;
int nreplies = 0;
#if WHEN_EDNS_RESPONSES_ARE_PARSED
int last_seen_edns = 0;
#endif
bool mDNSResolver = false;
nsvc *vc = nullptr;
};
namespace Dns
{
/// manage DNS internal component
class ConfigRr : public RegisteredRunner
{
public:
/* RegisteredRunner API */
virtual void startReconfigure() override;
virtual void endingShutdown() override;
};
RunnerRegistrationEntry(ConfigRr);
} // namespace Dns
struct _sp {
char domain[NS_MAXDNAME];
int queries;
};
static std::vector<ns> nameservers;
static sp *searchpath = nullptr;
static int nns_mdns_count = 0;
static int npc = 0;
static int npc_alloc = 0;
static int ndots = 1;
static dlink_list lru_list;
static int event_queued = 0;
static hash_table *idns_lookup_hash = nullptr;
/*
* Notes on EDNS:
*
* IPv4:
* EDNS as specified may be sent as an additional record for any request.
* early testing has revealed that it works on common devices, but cannot
* be reliably used on any A or PTR requet done for IPv4 addresses.
*
* As such the IPv4 packets are still hard-coded not to contain EDNS (0)
*
* Squid design:
* Squid is optimized to generate one packet and re-send it to all NS
* due to this we cannot customize the EDNS size per NS.
*
* As such we take the configuration option value as fixed.
*
* FUTURE TODO:
* This may not be worth doing, but if/when additional-records are parsed
* we will be able to recover the OPT value specific to any one NS and
* cache it. Effectively automating the tuning of EDNS advertised to the
* size our active NS are capable.
* Default would need to start with 512 bytes RFC1035 says every NS must accept.
* Responses from the configured NS may cause this to be raised or turned off.
*/
#if WHEN_EDNS_RESPONSES_ARE_PARSED
static int max_shared_edns = RFC1035_DEFAULT_PACKET_SZ;
#endif
static OBJH idnsStats;
static void idnsAddNameserver(const char *buf);
static void idnsAddMDNSNameservers();
static void idnsAddPathComponent(const char *buf);
static void idnsFreeSearchpath(void);
static bool idnsParseNameservers(void);
static bool idnsParseResolvConf(void);
#if _SQUID_WINDOWS_
static bool idnsParseWIN32Registry(void);
static void idnsParseWIN32SearchList(const char *);
#endif
static void idnsStartQuery(idns_query * q, IDNSCB * callback, void *data);
static void idnsSendQuery(idns_query * q);
static IOCB idnsReadVCHeader;
static void idnsDoSendQueryVC(nsvc *vc);
static CNCB idnsInitVCConnected;
static IOCB idnsReadVC;
static IOCB idnsSentQueryVC;
static int idnsFromKnownNameserver(Ip::Address const &from);
static idns_query *idnsFindQuery(unsigned short id);
static void idnsGrokReply(const char *buf, size_t sz, int from_ns);
static PF idnsRead;
static EVH idnsCheckQueue;
static void idnsTickleQueue(void);
static void idnsRcodeCount(int, int);
static CLCB idnsVCClosed;
static unsigned short idnsQueryID(void);
static void idnsSendSlaveAAAAQuery(idns_query *q);
static void idnsCallbackOnEarlyError(IDNSCB *callback, void *cbdata, const char *error);
static void
idnsCheckMDNS(idns_query *q)
{
if (!Config.onoff.dns_mdns || q->permit_mdns)
return;
size_t slen = strlen(q->name);
if (slen > 6 && memcmp(q->name +(slen-6),".local", 6) == 0) {
q->permit_mdns = true;
}
}
static void
idnsAddMDNSNameservers()
{
nns_mdns_count=0;
// mDNS is disabled
if (!Config.onoff.dns_mdns)
return;
// mDNS resolver addresses are explicit multicast group IPs
if (Ip::EnableIpv6) {
idnsAddNameserver("FF02::FB");
nameservers.back().S.port(5353);
nameservers.back().mDNSResolver = true;
++nns_mdns_count;
}
idnsAddNameserver("224.0.0.251");
nameservers.back().S.port(5353);
nameservers.back().mDNSResolver = true;
++nns_mdns_count;
}
static void
idnsAddNameserver(const char *buf)
{
Ip::Address A;
if (!(A = buf)) {
debugs(78, DBG_CRITICAL, "WARNING: rejecting '" << buf << "' as a name server, because it is not a numeric IP address");
return;
}
if (A.isAnyAddr()) {
debugs(78, DBG_CRITICAL, "WARNING: Squid does not accept " << A << " in DNS server specifications.");
A.setLocalhost();
debugs(78, DBG_CRITICAL, "Will be using " << A << " instead, assuming you meant that DNS is running on the same machine");
}
if (!Ip::EnableIpv6 && !A.setIPv4()) {
debugs(78, DBG_IMPORTANT, "WARNING: IPv6 is disabled. Discarding " << A << " in DNS server specifications.");
return;
}
nameservers.emplace_back(ns());
A.port(NS_DEFAULTPORT);
nameservers.back().S = A;
#if WHEN_EDNS_RESPONSES_ARE_PARSED
nameservers.back().last_seen_edns = RFC1035_DEFAULT_PACKET_SZ;
// TODO generate a test packet to probe this NS from EDNS size and ability.
#endif
debugs(78, 3, "Added nameserver #" << nameservers.size()-1 << " (" << A << ")");
}
static void
idnsAddPathComponent(const char *buf)
{
if (npc == npc_alloc) {
int oldalloc = npc_alloc;
sp *oldptr = searchpath;
if (0 == npc_alloc)
npc_alloc = 2;
else
npc_alloc <<= 1;
searchpath = (sp *)xcalloc(npc_alloc, sizeof(*searchpath));
if (oldptr && oldalloc)
memcpy(searchpath, oldptr, oldalloc * sizeof(*searchpath));
if (oldptr)
safe_free(oldptr);
}
assert(npc < npc_alloc);
strncpy(searchpath[npc].domain, buf, sizeof(searchpath[npc].domain)-1);
searchpath[npc].domain[sizeof(searchpath[npc].domain)-1] = '\0';
Tolower(searchpath[npc].domain);
debugs(78, 3, "idnsAddPathComponent: Added domain #" << npc << ": " << searchpath[npc].domain);
++npc;
}
static void
idnsFreeSearchpath(void)
{
safe_free(searchpath);
npc = npc_alloc = 0;
}
static bool
idnsParseNameservers(void)
{
bool result = false;
for (auto &i : Config.dns.nameservers) {
debugs(78, Important(15), "Adding nameserver " << i << " from squid.conf");
idnsAddNameserver(i.c_str());
result = true;
}
return result;
}
static bool
idnsParseResolvConf(void)
{
bool result = false;
#if !_SQUID_WINDOWS_
FILE *fp = fopen(_PATH_RESCONF, "r");
if (!fp) {
int xerrno = errno;
debugs(78, DBG_IMPORTANT, "" << _PATH_RESCONF << ": " << xstrerr(xerrno));
return false;
}
char buf[RESOLV_BUFSZ];
const char *t = nullptr;
while (fgets(buf, RESOLV_BUFSZ, fp)) {
t = strtok(buf, w_space);
if (nullptr == t) {
continue;
} else if (strcmp(t, "nameserver") == 0) {
t = strtok(nullptr, w_space);
if (nullptr == t)
continue;
debugs(78, DBG_IMPORTANT, "Adding nameserver " << t << " from " << _PATH_RESCONF);
idnsAddNameserver(t);
result = true;
} else if (strcmp(t, "domain") == 0) {
idnsFreeSearchpath();
t = strtok(nullptr, w_space);
if (nullptr == t)
continue;
debugs(78, DBG_IMPORTANT, "Adding domain " << t << " from " << _PATH_RESCONF);
idnsAddPathComponent(t);
} else if (strcmp(t, "search") == 0) {
idnsFreeSearchpath();
while (nullptr != t) {
t = strtok(nullptr, w_space);
if (nullptr == t)
continue;
debugs(78, DBG_IMPORTANT, "Adding domain " << t << " from " << _PATH_RESCONF);
idnsAddPathComponent(t);
}
} else if (strcmp(t, "options") == 0) {
while (nullptr != t) {
t = strtok(nullptr, w_space);
if (nullptr == t)
continue;
if (strncmp(t, "ndots:", 6) == 0) {
ndots = atoi(t + 6);
if (ndots < 1)
ndots = 1;
debugs(78, DBG_IMPORTANT, "Adding ndots " << ndots << " from " << _PATH_RESCONF);
}
}
}
}
if (npc == 0 && (t = getMyHostname())) {
t = strchr(t, '.');
if (t)
idnsAddPathComponent(t+1);
}
fclose(fp);
#endif
return result;
}
#if _SQUID_WINDOWS_
static void
idnsParseWIN32SearchList(const char * Separator)
{
char *t;
char *token;
HKEY hndKey;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, REG_TCPIP_PARA, 0, KEY_QUERY_VALUE, &hndKey) == ERROR_SUCCESS) {
DWORD Type = 0;
DWORD Size = 0;
LONG Result;
Result = RegQueryValueEx(hndKey, "Domain", NULL, &Type, NULL, &Size);
if (Result == ERROR_SUCCESS && Size) {
t = (char *) xmalloc(Size);
RegQueryValueEx(hndKey, "Domain", NULL, &Type, (LPBYTE) t, &Size);
debugs(78, DBG_IMPORTANT, "Adding domain " << t << " from Registry");
idnsAddPathComponent(t);
xfree(t);
}
Result = RegQueryValueEx(hndKey, "SearchList", NULL, &Type, NULL, &Size);
if (Result == ERROR_SUCCESS && Size) {
t = (char *) xmalloc(Size);
RegQueryValueEx(hndKey, "SearchList", NULL, &Type, (LPBYTE) t, &Size);
token = strtok(t, Separator);
while (token) {
idnsAddPathComponent(token);
debugs(78, DBG_IMPORTANT, "Adding domain " << token << " from Registry");
token = strtok(NULL, Separator);
}
xfree(t);
}
RegCloseKey(hndKey);
}
if (npc == 0 && (t = (char *) getMyHostname())) {
t = strchr(t, '.');
if (t)
idnsAddPathComponent(t + 1);
}
}
static bool
idnsParseWIN32Registry(void)
{
char *t;
char *token;
HKEY hndKey, hndKey2;
bool result = false;
switch (WIN32_OS_version) {
case _WIN_OS_WINNT:
/* get nameservers from the Windows NT registry */
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, REG_TCPIP_PARA, 0, KEY_QUERY_VALUE, &hndKey) == ERROR_SUCCESS) {
DWORD Type = 0;
DWORD Size = 0;
LONG Result;
Result = RegQueryValueEx(hndKey, "DhcpNameServer", NULL, &Type, NULL, &Size);
if (Result == ERROR_SUCCESS && Size) {
t = (char *) xmalloc(Size);
RegQueryValueEx(hndKey, "DhcpNameServer", NULL, &Type, (LPBYTE) t, &Size);
token = strtok(t, ", ");
while (token) {
idnsAddNameserver(token);
result = true;
debugs(78, DBG_IMPORTANT, "Adding DHCP nameserver " << token << " from Registry");
token = strtok(NULL, ",");
}
xfree(t);
}
Result = RegQueryValueEx(hndKey, "NameServer", NULL, &Type, NULL, &Size);
if (Result == ERROR_SUCCESS && Size) {
t = (char *) xmalloc(Size);
RegQueryValueEx(hndKey, "NameServer", NULL, &Type, (LPBYTE) t, &Size);
token = strtok(t, ", ");
while (token) {
debugs(78, DBG_IMPORTANT, "Adding nameserver " << token << " from Registry");
idnsAddNameserver(token);
result = true;
token = strtok(NULL, ", ");
}
xfree(t);
}
RegCloseKey(hndKey);
}
idnsParseWIN32SearchList(" ");
break;
case _WIN_OS_WIN2K:
case _WIN_OS_WINXP:
case _WIN_OS_WINNET:
case _WIN_OS_WINLON:
case _WIN_OS_WIN7:
/* get nameservers from the Windows 2000 registry */
/* search all interfaces for DNS server addresses */
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, REG_TCPIP_PARA_INTERFACES, 0, KEY_READ, &hndKey) == ERROR_SUCCESS) {
int i;
DWORD MaxSubkeyLen, InterfacesCount;
char *keyname;
FILETIME ftLastWriteTime;
if (RegQueryInfoKey(hndKey, NULL, NULL, NULL, &InterfacesCount, &MaxSubkeyLen, NULL, NULL, NULL, NULL, NULL, NULL) == ERROR_SUCCESS) {
keyname = (char *) xmalloc(++MaxSubkeyLen);
for (i = 0; i < (int) InterfacesCount; ++i) {
DWORD j;
j = MaxSubkeyLen;
if (RegEnumKeyEx(hndKey, i, keyname, &j, NULL, NULL, NULL, &ftLastWriteTime) == ERROR_SUCCESS) {
char *newkeyname;
newkeyname = (char *) xmalloc(sizeof(REG_TCPIP_PARA_INTERFACES) + j + 2);
strcpy(newkeyname, REG_TCPIP_PARA_INTERFACES);
strcat(newkeyname, "\\");
strcat(newkeyname, keyname);
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, newkeyname, 0, KEY_QUERY_VALUE, &hndKey2) == ERROR_SUCCESS) {
DWORD Type = 0;
DWORD Size = 0;
LONG Result;
Result = RegQueryValueEx(hndKey2, "DhcpNameServer", NULL, &Type, NULL, &Size);
if (Result == ERROR_SUCCESS && Size) {
t = (char *) xmalloc(Size);
RegQueryValueEx(hndKey2, "DhcpNameServer", NULL, &Type, (LPBYTE)t, &Size);
token = strtok(t, ", ");
while (token) {
debugs(78, DBG_IMPORTANT, "Adding DHCP nameserver " << token << " from Registry");
idnsAddNameserver(token);
result = true;
token = strtok(NULL, ", ");
}
xfree(t);
}
Result = RegQueryValueEx(hndKey2, "NameServer", NULL, &Type, NULL, &Size);
if (Result == ERROR_SUCCESS && Size) {
t = (char *) xmalloc(Size);
RegQueryValueEx(hndKey2, "NameServer", NULL, &Type, (LPBYTE)t, &Size);
token = strtok(t, ", ");
while (token) {
debugs(78, DBG_IMPORTANT, "Adding nameserver " << token << " from Registry");
idnsAddNameserver(token);
result = true;
token = strtok(NULL, ", ");
}
xfree(t);
}
RegCloseKey(hndKey2);
}
xfree(newkeyname);
}
}
xfree(keyname);
}
RegCloseKey(hndKey);
}
idnsParseWIN32SearchList(", ");
break;
case _WIN_OS_WIN95:
case _WIN_OS_WIN98:
case _WIN_OS_WINME:
/* get nameservers from the Windows 9X registry */
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, REG_VXD_MSTCP, 0, KEY_QUERY_VALUE, &hndKey) == ERROR_SUCCESS) {
DWORD Type = 0;
DWORD Size = 0;
LONG Result;
Result = RegQueryValueEx(hndKey, "NameServer", NULL, &Type, NULL, &Size);
if (Result == ERROR_SUCCESS && Size) {
t = (char *) xmalloc(Size);
RegQueryValueEx(hndKey, "NameServer", NULL, &Type, (LPBYTE) t, &Size);
token = strtok(t, ", ");
while (token) {
debugs(78, DBG_IMPORTANT, "Adding nameserver " << token << " from Registry");
idnsAddNameserver(token);
result = true;
token = strtok(NULL, ", ");
}
xfree(t);
}
RegCloseKey(hndKey);
}
break;
default:
debugs(78, DBG_IMPORTANT, "ERROR: Failed to read nameserver from Registry: Unknown System Type.");
}
return result;
}
#endif
static void
idnsStats(StoreEntry * sentry)
{
dlink_node *n;
idns_query *q;
int i;
int j;
char buf[MAX_IPSTRLEN];
storeAppendPrintf(sentry, "Internal DNS Statistics:\n");
storeAppendPrintf(sentry, "\nThe Queue:\n");
storeAppendPrintf(sentry, " DELAY SINCE\n");
storeAppendPrintf(sentry, " ID SIZE SENDS FIRST SEND LAST SEND M FQDN\n");
storeAppendPrintf(sentry, "------ ---- ----- ---------- --------- - ----\n");
for (n = lru_list.head; n; n = n->next) {
q = (idns_query *)n->data;
storeAppendPrintf(sentry, "%#06x %4d %5d %10.3f %9.3f %c %s\n",
(int) q->query_id, (int) q->sz, q->nsends,
tvSubDsec(q->start_t, current_time),
tvSubDsec(q->sent_t, current_time),
(q->permit_mdns? 'M':' '),
q->name);
}
if (Config.dns.packet_max > 0)
storeAppendPrintf(sentry, "\nDNS jumbo-grams: %zd Bytes\n", Config.dns.packet_max);
else
storeAppendPrintf(sentry, "\nDNS jumbo-grams: not working\n");
storeAppendPrintf(sentry, "\nNameservers:\n");
storeAppendPrintf(sentry, "IP ADDRESS # QUERIES # REPLIES Type\n");
storeAppendPrintf(sentry, "---------------------------------------------- --------- --------- --------\n");
for (const auto &server : nameservers) {
storeAppendPrintf(sentry, "%-45s %9d %9d %s\n", /* Let's take the maximum: (15 IPv4/45 IPv6) */
server.S.toStr(buf,MAX_IPSTRLEN),
server.nqueries,
server.nreplies,
server.mDNSResolver?"multicast":"recurse");
}
storeAppendPrintf(sentry, "\nRcode Matrix:\n");
storeAppendPrintf(sentry, "RCODE");
for (i = 0; i < MAX_ATTEMPT; ++i)
storeAppendPrintf(sentry, " ATTEMPT%d", i + 1);
storeAppendPrintf(sentry, " PROBLEM\n");
for (j = 0; j < MAX_RCODE; ++j) {
if (j > 10 && j < 16)
continue; // unassigned by IANA.
storeAppendPrintf(sentry, "%5d", j);
for (i = 0; i < MAX_ATTEMPT; ++i)
storeAppendPrintf(sentry, " %8d", RcodeMatrix[j][i]);
storeAppendPrintf(sentry, " : %s\n",Rcodes[j]);
}
if (npc) {
storeAppendPrintf(sentry, "\nSearch list:\n");
for (i=0; i < npc; ++i)
storeAppendPrintf(sentry, "%s\n", searchpath[i].domain);
storeAppendPrintf(sentry, "\n");
}
}
static void
idnsTickleQueue(void)
{
if (event_queued)
return;
if (nullptr == lru_list.tail)
return;
const double when = min(Config.Timeout.idns_query, Config.Timeout.idns_retransmit)/1000.0;
eventAdd("idnsCheckQueue", idnsCheckQueue, nullptr, when, 1);
event_queued = 1;
}
static void
idnsSentQueryVC(const Comm::ConnectionPointer &conn, char *, size_t size, Comm::Flag flag, int, void *data)
{
nsvc * vc = (nsvc *)data;
if (flag == Comm::ERR_CLOSING)
return;
// XXX: irrelevant now that we have conn pointer?
if (!Comm::IsConnOpen(conn) || fd_table[conn->fd].closing())
return;
if (flag != Comm::OK || size <= 0) {
conn->close();
return;
}
vc->busy = 0;
idnsDoSendQueryVC(vc);
}
static void
idnsDoSendQueryVC(nsvc *vc)
{
if (vc->busy)
return;
if (vc->queue->contentSize() == 0)
return;
// if retrying after a TC UDP response, our close handler cb may be pending
if (fd_table[vc->conn->fd].closing())
return;
MemBuf *mb = vc->queue;
vc->queue = new MemBuf;
vc->busy = 1;
// Comm needs seconds but idnsCheckQueue() will check the exact timeout
const int timeout = (Config.Timeout.idns_query % 1000 ?
Config.Timeout.idns_query + 1000 : Config.Timeout.idns_query) / 1000;
AsyncCall::Pointer nil;
commSetConnTimeout(vc->conn, timeout, nil);
AsyncCall::Pointer call = commCbCall(78, 5, "idnsSentQueryVC",
CommIoCbPtrFun(&idnsSentQueryVC, vc));
Comm::Write(vc->conn, mb, call);
delete mb;
}
static void
idnsInitVCConnected(const Comm::ConnectionPointer &conn, Comm::Flag status, int, void *data)
{
nsvc * vc = (nsvc *)data;
if (status != Comm::OK || !conn) {
char buf[MAX_IPSTRLEN] = "";
if (vc->ns < nameservers.size())
nameservers[vc->ns].S.toStr(buf,MAX_IPSTRLEN);
debugs(78, DBG_IMPORTANT, "ERROR: Failed to connect to nameserver " << buf << " using TCP.");
return;
}
vc->conn = conn;
comm_add_close_handler(conn->fd, idnsVCClosed, vc);
AsyncCall::Pointer call = commCbCall(5,4, "idnsReadVCHeader",
CommIoCbPtrFun(idnsReadVCHeader, vc));
comm_read(conn, (char *)&vc->msglen, 2, call);
vc->busy = 0;
idnsDoSendQueryVC(vc);
}
static void
idnsVCClosed(const CommCloseCbParams ¶ms)
{
nsvc * vc = (nsvc *)params.data;
if (vc->conn) {
vc->conn->noteClosure();
vc->conn = nullptr;
}
delete vc;
}
nsvc::~nsvc()
{
delete queue;
delete msg;
if (ns < nameservers.size()) // XXX: idnsShutdownAndFreeState may have freed nameservers[]
nameservers[ns].vc = nullptr;
}
static void
idnsInitVC(size_t nsv)
{
assert(nsv < nameservers.size());
nsvc *vc = new nsvc(nsv);
assert(vc->conn == nullptr); // MUST be NULL from the construction process!
nameservers[nsv].vc = vc;
Comm::ConnectionPointer conn = new Comm::Connection();
if (!Config.Addrs.udp_outgoing.isNoAddr())
conn->setAddrs(Config.Addrs.udp_outgoing, nameservers[nsv].S);
else
conn->setAddrs(Config.Addrs.udp_incoming, nameservers[nsv].S);
if (conn->remote.isIPv4())
conn->local.setIPv4();
AsyncCall::Pointer call = commCbCall(78,3, "idnsInitVCConnected", CommConnectCbPtrFun(idnsInitVCConnected, vc));
Comm::ConnOpener *cs = new Comm::ConnOpener(conn, call, Config.Timeout.connect);
cs->setHost("DNS TCP Socket");
AsyncJob::Start(cs);
}
static void
idnsSendQueryVC(idns_query * q, size_t nsn)
{
assert(nsn < nameservers.size());
if (nameservers[nsn].vc == nullptr)
idnsInitVC(nsn);
nsvc *vc = nameservers[nsn].vc;
if (!vc) {
char buf[MAX_IPSTRLEN];
debugs(78, DBG_IMPORTANT, "ERROR: idnsSendQuery: Failed to initiate TCP connection to nameserver " << nameservers[nsn].S.toStr(buf,MAX_IPSTRLEN) << "!");
return;
}
vc->queue->reset();
short head = htons(q->sz);
vc->queue->append((char *)&head, 2);
vc->queue->append(q->buf, q->sz);
idnsDoSendQueryVC(vc);
}
static void
idnsSendQuery(idns_query * q)
{
// XXX: DNS sockets get closed during reconfigure produces a race between
// any already active connections (or ones received between closing DNS
// sockets and server listening sockets) and the reconfigure completing
// (Runner syncConfig() being run). Transactions which loose this race will
// produce DNS timeouts (or whatever the caller set) as their queries never
// get queued to be re-tried after the DNS socekts are re-opened.
if (DnsSocketA < 0 && DnsSocketB < 0) {
debugs(78, DBG_IMPORTANT, "WARNING: idnsSendQuery: Can't send query, no DNS socket!");
return;
}
if (nameservers.empty()) {
debugs(78, DBG_IMPORTANT, "WARNING: idnsSendQuery: Can't send query, no DNS nameservers known!");
return;
}
assert(q->lru.next == nullptr);
assert(q->lru.prev == nullptr);
int x = -1, y = -1;
size_t nsn;
const auto nsCount = nameservers.size();
do {
// only use mDNS resolvers for mDNS compatible queries
if (!q->permit_mdns)
nsn = nns_mdns_count + q->nsends % (nsCount - nns_mdns_count);
else
nsn = q->nsends % nsCount;
if (q->need_vc) {
idnsSendQueryVC(q, nsn);
x = y = 0;
} else {
if (DnsSocketB >= 0 && nameservers[nsn].S.isIPv6())
y = comm_udp_sendto(DnsSocketB, nameservers[nsn].S, q->buf, q->sz);
else if (DnsSocketA >= 0)
x = comm_udp_sendto(DnsSocketA, nameservers[nsn].S, q->buf, q->sz);
}
int xerrno = errno;
++ q->nsends;
q->sent_t = current_time;
if (y < 0 && nameservers[nsn].S.isIPv6())
debugs(50, DBG_IMPORTANT, MYNAME << "FD " << DnsSocketB << ": sendto: " << xstrerr(xerrno));
if (x < 0 && nameservers[nsn].S.isIPv4())
debugs(50, DBG_IMPORTANT, MYNAME << "FD " << DnsSocketA << ": sendto: " << xstrerr(xerrno));
} while ( (x<0 && y<0) && q->nsends % nsCount != 0);
if (y > 0) {