-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathres_cache.cpp
More file actions
2168 lines (1853 loc) · 72.8 KB
/
res_cache.cpp
File metadata and controls
2168 lines (1853 loc) · 72.8 KB
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) 2008 The Android Open Source Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#define LOG_TAG "resolv"
#include "resolv_cache.h"
#include <resolv.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <algorithm>
#include <mutex>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
#include <arpa/inet.h>
#include <arpa/nameser.h>
#include <errno.h>
#include <linux/if.h>
#include <net/if.h>
#include <netdb.h>
#include <aidl/android/net/IDnsResolver.h>
#include <android-base/logging.h>
#include <android-base/parseint.h>
#include <android-base/strings.h>
#include <android-base/thread_annotations.h>
#include <android/multinetwork.h> // ResNsendFlags
#include <server_configurable_flags/get_flags.h>
#include "DnsStats.h"
#include "Experiments.h"
#include "res_comp.h"
#include "res_debug.h"
#include "resolv_private.h"
#include "util.h"
using aidl::android::net::IDnsResolver;
using aidl::android::net::ResolverOptionsParcel;
using aidl::android::net::ResolverParamsParcel;
using android::net::DnsQueryEvent;
using android::net::DnsStats;
using android::net::Experiments;
using android::net::PROTO_TCP;
using android::net::PROTO_UDP;
using android::net::Protocol;
using android::netdutils::DumpWriter;
using android::netdutils::IPSockAddr;
using std::span;
/* This code implements a small and *simple* DNS resolver cache.
*
* It is only used to cache DNS answers for a time defined by the smallest TTL
* among the answer records in order to reduce DNS traffic. It is not supposed
* to be a full DNS cache, since we plan to implement that in the future in a
* dedicated process running on the system.
*
* Note that its design is kept simple very intentionally, i.e.:
*
* - it takes raw DNS query packet data as input, and returns raw DNS
* answer packet data as output
*
* (this means that two similar queries that encode the DNS name
* differently will be treated distinctly).
*
* the smallest TTL value among the answer records are used as the time
* to keep an answer in the cache.
*
* this is bad, but we absolutely want to avoid parsing the answer packets
* (and should be solved by the later full DNS cache process).
*
* - the implementation is just a (query-data) => (answer-data) hash table
* with a trivial least-recently-used expiration policy.
*
* Doing this keeps the code simple and avoids to deal with a lot of things
* that a full DNS cache is expected to do.
*
* The API is also very simple:
*
* - the client calls resolv_cache_lookup() before performing a query
*
* If the function returns RESOLV_CACHE_FOUND, a copy of the answer data
* has been copied into the client-provided answer buffer.
*
* If the function returns RESOLV_CACHE_NOTFOUND, the client should perform
* a request normally, *then* call resolv_cache_add() to add the received
* answer to the cache.
*
* If the function returns RESOLV_CACHE_UNSUPPORTED, the client should
* perform a request normally, and *not* call resolv_cache_add()
*
* Note that RESOLV_CACHE_UNSUPPORTED is also returned if the answer buffer
* is too short to accomodate the cached result.
*/
/* Default number of entries kept in the cache. This value has been
* determined by browsing through various sites and counting the number
* of corresponding requests. Keep in mind that our framework is currently
* performing two requests per name lookup (one for IPv4, the other for IPv6)
*
* www.google.com 4
* www.ysearch.com 6
* www.amazon.com 8
* www.nytimes.com 22
* www.espn.com 28
* www.msn.com 28
* www.lemonde.fr 35
*
* (determined in 2009-2-17 from Paris, France, results may vary depending
* on location)
*
* most high-level websites use lots of media/ad servers with different names
* but these are generally reused when browsing through the site.
*
* As such, a value of 64 should be relatively comfortable at the moment.
*
* ******************************************
* * NOTE - this has changed.
* * 1) we've added IPv6 support so each dns query results in 2 responses
* * 2) we've made this a system-wide cache, so the cost is less (it's not
* * duplicated in each process) and the need is greater (more processes
* * making different requests).
* * Upping by 2x for IPv6
* * Upping by another 5x for the centralized nature
* *****************************************
*/
const int MAX_ENTRIES_DEFAULT = 64 * 2 * 5;
const int MAX_ENTRIES_LOWER_BOUND = 1;
const int MAX_ENTRIES_UPPER_BOUND = 100 * 1000;
constexpr int DNSEVENT_SUBSAMPLING_MAP_DEFAULT_KEY = -1;
static time_t _time_now(void) {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec;
}
/* reminder: the general format of a DNS packet is the following:
*
* HEADER (12 bytes)
* QUESTION (variable)
* ANSWER (variable)
* AUTHORITY (variable)
* ADDITIONNAL (variable)
*
* the HEADER is made of:
*
* ID : 16 : 16-bit unique query identification field
*
* QR : 1 : set to 0 for queries, and 1 for responses
* Opcode : 4 : set to 0 for queries
* AA : 1 : set to 0 for queries
* TC : 1 : truncation flag, will be set to 0 in queries
* RD : 1 : recursion desired
*
* RA : 1 : recursion available (0 in queries)
* Z : 3 : three reserved zero bits
* RCODE : 4 : response code (always 0=NOERROR in queries)
*
* QDCount: 16 : question count
* ANCount: 16 : Answer count (0 in queries)
* NSCount: 16: Authority Record count (0 in queries)
* ARCount: 16: Additionnal Record count (0 in queries)
*
* the QUESTION is made of QDCount Question Record (QRs)
* the ANSWER is made of ANCount RRs
* the AUTHORITY is made of NSCount RRs
* the ADDITIONNAL is made of ARCount RRs
*
* Each Question Record (QR) is made of:
*
* QNAME : variable : Query DNS NAME
* TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
* CLASS : 16 : class of query (IN=1)
*
* Each Resource Record (RR) is made of:
*
* NAME : variable : DNS NAME
* TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
* CLASS : 16 : class of query (IN=1)
* TTL : 32 : seconds to cache this RR (0=none)
* RDLENGTH: 16 : size of RDDATA in bytes
* RDDATA : variable : RR data (depends on TYPE)
*
* Each QNAME contains a domain name encoded as a sequence of 'labels'
* terminated by a zero. Each label has the following format:
*
* LEN : 8 : lenght of label (MUST be < 64)
* NAME : 8*LEN : label length (must exclude dots)
*
* A value of 0 in the encoding is interpreted as the 'root' domain and
* terminates the encoding. So 'www.android.com' will be encoded as:
*
* <3>www<7>android<3>com<0>
*
* Where <n> represents the byte with value 'n'
*
* Each NAME reflects the QNAME of the question, but has a slightly more
* complex encoding in order to provide message compression. This is achieved
* by using a 2-byte pointer, with format:
*
* TYPE : 2 : 0b11 to indicate a pointer, 0b01 and 0b10 are reserved
* OFFSET : 14 : offset to another part of the DNS packet
*
* The offset is relative to the start of the DNS packet and must point
* A pointer terminates the encoding.
*
* The NAME can be encoded in one of the following formats:
*
* - a sequence of simple labels terminated by 0 (like QNAMEs)
* - a single pointer
* - a sequence of simple labels terminated by a pointer
*
* A pointer shall always point to either a pointer of a sequence of
* labels (which can themselves be terminated by either a 0 or a pointer)
*
* The expanded length of a given domain name should not exceed 255 bytes.
*
* NOTE: we don't parse the answer packets, so don't need to deal with NAME
* records, only QNAMEs.
*/
#define DNS_HEADER_SIZE 12
struct DnsPacket {
const uint8_t* base;
const uint8_t* end;
const uint8_t* cursor;
};
static uint8_t res_tolower(uint8_t c) {
return (c >= 'A' && c <= 'Z') ? (c | 0x20) : c;
}
static int res_memcasecmp(const unsigned char *s1, const unsigned char *s2, size_t len) {
for (size_t i = 0; i < len; i++) {
int ch1 = *s1++;
int ch2 = *s2++;
int d = res_tolower(ch1) - res_tolower(ch2);
if (d != 0) {
return d;
}
}
return 0;
}
static void _dnsPacket_init(DnsPacket* packet, const uint8_t* buff, int bufflen) {
packet->base = buff;
packet->end = buff + bufflen;
packet->cursor = buff;
}
static void _dnsPacket_rewind(DnsPacket* packet) {
packet->cursor = packet->base;
}
static void _dnsPacket_skip(DnsPacket* packet, int count) {
const uint8_t* p = packet->cursor + count;
if (p > packet->end) p = packet->end;
packet->cursor = p;
}
static int _dnsPacket_readInt16(DnsPacket* packet) {
const uint8_t* p = packet->cursor;
if (p + 2 > packet->end) return -1;
packet->cursor = p + 2;
return (p[0] << 8) | p[1];
}
/** QUERY CHECKING **/
/* check bytes in a dns packet. returns 1 on success, 0 on failure.
* the cursor is only advanced in the case of success
*/
static int _dnsPacket_checkBytes(DnsPacket* packet, int numBytes, const void* bytes) {
const uint8_t* p = packet->cursor;
if (p + numBytes > packet->end) return 0;
if (memcmp(p, bytes, numBytes) != 0) return 0;
packet->cursor = p + numBytes;
return 1;
}
static int _dnsPacket_checkBE16(DnsPacket* packet, uint16_t v) {
uint16_t be16 = htons(v);
return _dnsPacket_checkBytes(packet, sizeof(be16), &be16);
}
/* parse and skip a given QNAME stored in a query packet,
* from the current cursor position. returns 1 on success,
* or 0 for malformed data.
*/
static int _dnsPacket_checkQName(DnsPacket* packet) {
const uint8_t* p = packet->cursor;
const uint8_t* end = packet->end;
for (;;) {
int c;
if (p >= end) break;
c = *p++;
if (c == 0) {
packet->cursor = p;
return 1;
}
/* we don't expect label compression in QNAMEs */
if (c >= 64) break;
p += c;
/* we rely on the bound check at the start
* of the loop here */
}
/* malformed data */
LOG(INFO) << __func__ << ": malformed QNAME";
return 0;
}
/* parse and skip a given QR stored in a packet.
* returns 1 on success, and 0 on failure
*/
static int _dnsPacket_checkQR(DnsPacket* packet) {
if (!_dnsPacket_checkQName(packet)) return 0;
/* TYPE must be one of the things we support */
if (!_dnsPacket_checkBE16(packet, ns_type::ns_t_a) &&
!_dnsPacket_checkBE16(packet, ns_type::ns_t_ptr) &&
!_dnsPacket_checkBE16(packet, ns_type::ns_t_mx) &&
!_dnsPacket_checkBE16(packet, ns_type::ns_t_aaaa) &&
!_dnsPacket_checkBE16(packet, ns_type::ns_t_any /*all*/)) {
LOG(INFO) << __func__ << ": unsupported TYPE";
return 0;
}
/* CLASS must be IN */
if (!_dnsPacket_checkBE16(packet, ns_class::ns_c_in)) {
LOG(INFO) << __func__ << ": unsupported CLASS";
return 0;
}
return 1;
}
/* check the header of a DNS Query packet, return 1 if it is one
* type of query we can cache, or 0 otherwise
*/
static int _dnsPacket_checkQuery(DnsPacket* packet) {
const uint8_t* p = packet->base;
int qdCount, anCount, dnCount, arCount;
if (p + DNS_HEADER_SIZE > packet->end) {
LOG(INFO) << __func__ << ": query packet too small";
return 0;
}
/* QR must be set to 0, opcode must be 0 and AA must be 0 */
/* RA, Z, and RCODE must be 0 */
if ((p[2] & 0xFC) != 0 || (p[3] & 0xCF) != 0) {
LOG(INFO) << __func__ << ": query packet flags unsupported";
return 0;
}
/* Note that we ignore the TC, RD, CD, and AD bits here for the
* following reasons:
*
* - there is no point for a query packet sent to a server
* to have the TC bit set, but the implementation might
* set the bit in the query buffer for its own needs
* between a resolv_cache_lookup and a resolv_cache_add.
* We should not freak out if this is the case.
*
* - we consider that the result from a query might depend on
* the RD, AD, and CD bits, so these bits
* should be used to differentiate cached result.
*
* this implies that these bits are checked when hashing or
* comparing query packets, but not TC
*/
/* ANCOUNT, DNCOUNT and ARCOUNT must be 0 */
qdCount = (p[4] << 8) | p[5];
anCount = (p[6] << 8) | p[7];
dnCount = (p[8] << 8) | p[9];
arCount = (p[10] << 8) | p[11];
if (anCount != 0 || dnCount != 0 || arCount > 1) {
LOG(INFO) << __func__ << ": query packet contains non-query records";
return 0;
}
if (qdCount == 0) {
LOG(INFO) << __func__ << ": query packet doesn't contain query record";
return 0;
}
/* Check QDCOUNT QRs */
packet->cursor = p + DNS_HEADER_SIZE;
for (; qdCount > 0; qdCount--)
if (!_dnsPacket_checkQR(packet)) return 0;
return 1;
}
/** QUERY HASHING SUPPORT
**
** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKET HAS ALREADY
** BEEN SUCCESFULLY CHECKED.
**/
/* use 32-bit FNV hash function */
#define FNV_MULT 16777619U
#define FNV_BASIS 2166136261U
static unsigned _dnsPacket_hashBytes(DnsPacket* packet, int numBytes, unsigned hash) {
const uint8_t* p = packet->cursor;
const uint8_t* end = packet->end;
while (numBytes > 0 && p < end) {
hash = hash * FNV_MULT ^ *p++;
numBytes--;
}
packet->cursor = p;
return hash;
}
static unsigned _dnsPacket_hashQName(DnsPacket* packet, unsigned hash) {
const uint8_t* p = packet->cursor;
const uint8_t* end = packet->end;
for (;;) {
if (p >= end) { /* should not happen */
LOG(INFO) << __func__ << ": INTERNAL_ERROR: read-overflow";
break;
}
int c = *p++;
if (c == 0) break;
if (c >= 64) {
LOG(INFO) << __func__ << ": INTERNAL_ERROR: malformed domain";
break;
}
if (p + c >= end) {
LOG(INFO) << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
break;
}
while (c > 0) {
uint8_t ch = *p++;
ch = res_tolower(ch);
hash = hash * FNV_MULT ^ ch;
c--;
}
}
packet->cursor = p;
return hash;
}
static unsigned _dnsPacket_hashQR(DnsPacket* packet, unsigned hash) {
hash = _dnsPacket_hashQName(packet, hash);
hash = _dnsPacket_hashBytes(packet, 4, hash); /* TYPE and CLASS */
return hash;
}
static unsigned _dnsPacket_hashRR(DnsPacket* packet, unsigned hash) {
int rdlength;
hash = _dnsPacket_hashQR(packet, hash);
hash = _dnsPacket_hashBytes(packet, 4, hash); /* TTL */
rdlength = _dnsPacket_readInt16(packet);
hash = _dnsPacket_hashBytes(packet, rdlength, hash); /* RDATA */
return hash;
}
static unsigned _dnsPacket_hashQuery(DnsPacket* packet) {
unsigned hash = FNV_BASIS;
int count, arcount;
_dnsPacket_rewind(packet);
/* ignore the ID */
_dnsPacket_skip(packet, 2);
/* we ignore the TC bit for reasons explained in
* _dnsPacket_checkQuery().
*
* however we hash the RD bit to differentiate
* between answers for recursive and non-recursive
* queries.
*/
hash = hash * FNV_MULT ^ (packet->base[2] & 1);
/* mark the first header byte as processed */
_dnsPacket_skip(packet, 1);
/* process the second header byte */
hash = _dnsPacket_hashBytes(packet, 1, hash);
/* read QDCOUNT */
count = _dnsPacket_readInt16(packet);
/* assume: ANcount and NScount are 0 */
_dnsPacket_skip(packet, 4);
/* read ARCOUNT */
arcount = _dnsPacket_readInt16(packet);
/* hash QDCOUNT QRs */
for (; count > 0; count--) hash = _dnsPacket_hashQR(packet, hash);
/* hash ARCOUNT RRs */
for (; arcount > 0; arcount--) hash = _dnsPacket_hashRR(packet, hash);
return hash;
}
/** QUERY COMPARISON
**
** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKETS HAVE ALREADY
** BEEN SUCCESSFULLY CHECKED.
**/
static int _dnsPacket_isEqualDomainName(DnsPacket* pack1, DnsPacket* pack2) {
const uint8_t* p1 = pack1->cursor;
const uint8_t* end1 = pack1->end;
const uint8_t* p2 = pack2->cursor;
const uint8_t* end2 = pack2->end;
for (;;) {
if (p1 >= end1 || p2 >= end2) {
LOG(INFO) << __func__ << ": INTERNAL_ERROR: read-overflow";
break;
}
int c1 = *p1++;
int c2 = *p2++;
if (c1 != c2) break;
if (c1 == 0) {
pack1->cursor = p1;
pack2->cursor = p2;
return 1;
}
if (c1 >= 64) {
LOG(INFO) << __func__ << ": INTERNAL_ERROR: malformed domain";
break;
}
if ((p1 + c1 > end1) || (p2 + c1 > end2)) {
LOG(INFO) << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
break;
}
if (res_memcasecmp(p1, p2, c1) != 0) break;
p1 += c1;
p2 += c1;
/* we rely on the bound checks at the start of the loop */
}
/* not the same, or one is malformed */
LOG(INFO) << __func__ << ": different DN";
return 0;
}
static int _dnsPacket_isEqualBytes(DnsPacket* pack1, DnsPacket* pack2, int numBytes) {
const uint8_t* p1 = pack1->cursor;
const uint8_t* p2 = pack2->cursor;
if (p1 + numBytes > pack1->end || p2 + numBytes > pack2->end) return 0;
if (memcmp(p1, p2, numBytes) != 0) return 0;
pack1->cursor += numBytes;
pack2->cursor += numBytes;
return 1;
}
static int _dnsPacket_isEqualQR(DnsPacket* pack1, DnsPacket* pack2) {
/* compare domain name encoding + TYPE + CLASS */
if (!_dnsPacket_isEqualDomainName(pack1, pack2) ||
!_dnsPacket_isEqualBytes(pack1, pack2, 2 + 2))
return 0;
return 1;
}
static int _dnsPacket_isEqualRR(DnsPacket* pack1, DnsPacket* pack2) {
int rdlength1, rdlength2;
/* compare query + TTL */
if (!_dnsPacket_isEqualQR(pack1, pack2) || !_dnsPacket_isEqualBytes(pack1, pack2, 4)) return 0;
/* compare RDATA */
rdlength1 = _dnsPacket_readInt16(pack1);
rdlength2 = _dnsPacket_readInt16(pack2);
if (rdlength1 != rdlength2 || !_dnsPacket_isEqualBytes(pack1, pack2, rdlength1)) return 0;
return 1;
}
static int _dnsPacket_isEqualQuery(DnsPacket* pack1, DnsPacket* pack2) {
int count1, count2, arcount1, arcount2;
/* compare the headers, ignore most fields */
_dnsPacket_rewind(pack1);
_dnsPacket_rewind(pack2);
/* compare RD, ignore TC, see comment in _dnsPacket_checkQuery */
if ((pack1->base[2] & 1) != (pack2->base[2] & 1)) {
LOG(INFO) << __func__ << ": different RD";
return 0;
}
if (pack1->base[3] != pack2->base[3]) {
LOG(INFO) << __func__ << ": different CD or AD";
return 0;
}
/* mark ID and header bytes as compared */
_dnsPacket_skip(pack1, 4);
_dnsPacket_skip(pack2, 4);
/* compare QDCOUNT */
count1 = _dnsPacket_readInt16(pack1);
count2 = _dnsPacket_readInt16(pack2);
if (count1 != count2 || count1 < 0) {
LOG(INFO) << __func__ << ": different QDCOUNT";
return 0;
}
/* assume: ANcount and NScount are 0 */
_dnsPacket_skip(pack1, 4);
_dnsPacket_skip(pack2, 4);
/* compare ARCOUNT */
arcount1 = _dnsPacket_readInt16(pack1);
arcount2 = _dnsPacket_readInt16(pack2);
if (arcount1 != arcount2 || arcount1 < 0) {
LOG(INFO) << __func__ << ": different ARCOUNT";
return 0;
}
/* compare the QDCOUNT QRs */
for (; count1 > 0; count1--) {
if (!_dnsPacket_isEqualQR(pack1, pack2)) {
LOG(INFO) << __func__ << ": different QR";
return 0;
}
}
/* compare the ARCOUNT RRs */
for (; arcount1 > 0; arcount1--) {
if (!_dnsPacket_isEqualRR(pack1, pack2)) {
LOG(INFO) << __func__ << ": different additional RR";
return 0;
}
}
return 1;
}
/* cache entry. for simplicity, 'hash' and 'hlink' are inlined in this
* structure though they are conceptually part of the hash table.
*
* similarly, mru_next and mru_prev are part of the global MRU list
*/
struct Entry {
unsigned int hash; /* hash value */
struct Entry* hlink; /* next in collision chain */
struct Entry* mru_prev;
struct Entry* mru_next;
const uint8_t* query;
int querylen;
const uint8_t* answer;
int answerlen;
time_t expires; /* time_t when the entry isn't valid any more */
int id; /* for debugging purpose */
};
/*
* Find the TTL for a negative DNS result. This is defined as the minimum
* of the SOA records TTL and the MINIMUM-TTL field (RFC-2308).
*
* Return 0 if not found.
*/
static uint32_t answer_getNegativeTTL(ns_msg handle) {
int n, nscount;
uint32_t result = 0;
ns_rr rr;
nscount = ns_msg_count(handle, ns_s_ns);
for (n = 0; n < nscount; n++) {
if ((ns_parserr(&handle, ns_s_ns, n, &rr) == 0) && (ns_rr_type(rr) == ns_t_soa)) {
const uint8_t* rdata = ns_rr_rdata(rr); // find the data
const uint8_t* edata = rdata + ns_rr_rdlen(rr); // add the len to find the end
int len;
uint32_t ttl, rec_result = rr.ttl;
// find the MINIMUM-TTL field from the blob of binary data for this record
// skip the server name
len = dn_skipname(rdata, edata);
if (len == -1) continue; // error skipping
rdata += len;
// skip the admin name
len = dn_skipname(rdata, edata);
if (len == -1) continue; // error skipping
rdata += len;
if (edata - rdata != 5 * NS_INT32SZ) continue;
// skip: serial number + refresh interval + retry interval + expiry
rdata += NS_INT32SZ * 4;
// finally read the MINIMUM TTL
ttl = ntohl(*reinterpret_cast<const uint32_t*>(rdata));
if (ttl < rec_result) {
rec_result = ttl;
}
// Now that the record is read successfully, apply the new min TTL
if (n == 0 || rec_result < result) {
result = rec_result;
}
}
}
return result;
}
/*
* Parse the answer records and find the appropriate
* smallest TTL among the records. This might be from
* the answer records if found or from the SOA record
* if it's a negative result.
*
* The returned TTL is the number of seconds to
* keep the answer in the cache.
*
* In case of parse error zero (0) is returned which
* indicates that the answer shall not be cached.
*/
static uint32_t answer_getTTL(span<const uint8_t> answer) {
ns_msg handle;
int ancount, n;
uint32_t result, ttl;
ns_rr rr;
result = 0;
if (ns_initparse(answer.data(), answer.size(), &handle) >= 0) {
// get number of answer records
ancount = ns_msg_count(handle, ns_s_an);
if (ancount == 0) {
// a response with no answers? Cache this negative result.
result = answer_getNegativeTTL(handle);
} else {
for (n = 0; n < ancount; n++) {
if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
ttl = rr.ttl;
if (n == 0 || ttl < result) {
result = ttl;
}
} else {
PLOG(INFO) << __func__ << ": ns_parserr failed ancount no = " << n;
}
}
}
} else {
PLOG(INFO) << __func__ << ": ns_initparse failed";
}
LOG(DEBUG) << __func__ << ": TTL = " << result;
return result;
}
static void entry_free(Entry* e) {
/* everything is allocated in a single memory block */
if (e) {
free(e);
}
}
static void entry_mru_remove(Entry* e) {
e->mru_prev->mru_next = e->mru_next;
e->mru_next->mru_prev = e->mru_prev;
}
static void entry_mru_add(Entry* e, Entry* list) {
Entry* first = list->mru_next;
e->mru_next = first;
e->mru_prev = list;
list->mru_next = e;
first->mru_prev = e;
}
/* compute the hash of a given entry, this is a hash of most
* data in the query (key) */
static unsigned entry_hash(const Entry* e) {
DnsPacket pack[1];
_dnsPacket_init(pack, e->query, e->querylen);
return _dnsPacket_hashQuery(pack);
}
/* initialize an Entry as a search key, this also checks the input query packet
* returns 1 on success, or 0 in case of unsupported/malformed data */
static int entry_init_key(Entry* e, span<const uint8_t> query) {
DnsPacket pack[1];
memset(e, 0, sizeof(*e));
e->query = query.data();
e->querylen = query.size();
e->hash = entry_hash(e);
_dnsPacket_init(pack, e->query, e->querylen);
return _dnsPacket_checkQuery(pack);
}
/* allocate a new entry as a cache node */
static Entry* entry_alloc(const Entry* init, span<const uint8_t> answer) {
Entry* e;
int size;
size = sizeof(*e) + init->querylen + answer.size();
e = (Entry*) calloc(size, 1);
if (e == NULL) return e;
e->hash = init->hash;
e->query = (const uint8_t*) (e + 1);
e->querylen = init->querylen;
memcpy((char*) e->query, init->query, e->querylen);
e->answer = e->query + e->querylen;
e->answerlen = answer.size();
memcpy((char*)e->answer, answer.data(), e->answerlen);
return e;
}
static int entry_equals(const Entry* e1, const Entry* e2) {
DnsPacket pack1[1], pack2[1];
if (e1->querylen != e2->querylen) {
return 0;
}
_dnsPacket_init(pack1, e1->query, e1->querylen);
_dnsPacket_init(pack2, e2->query, e2->querylen);
return _dnsPacket_isEqualQuery(pack1, pack2);
}
/* We use a simple hash table with external collision lists
* for simplicity, the hash-table fields 'hash' and 'hlink' are
* inlined in the Entry structure.
*/
/* Maximum time for a thread to wait for an pending request */
constexpr int PENDING_REQUEST_TIMEOUT = 20;
// lock protecting everything in NetConfig.
static std::mutex cache_mutex;
static std::condition_variable cv;
namespace {
// Map format: ReturnCode:rate_denom
// if the ReturnCode is not associated with any rate_denom, use default
// Sampling rate varies by return code; events to log are chosen randomly, with a
// probability proportional to the sampling rate.
constexpr const char DEFAULT_SUBSAMPLING_MAP[] = "default:8 0:400 2:110 7:110";
constexpr const char DEFAULT_MDNS_SUBSAMPLING_MAP[] = "default:1";
std::unordered_map<int, uint32_t> resolv_get_dns_event_subsampling_map(bool isMdns) {
using android::base::ParseInt;
using android::base::ParseUint;
using android::base::Split;
using server_configurable_flags::GetServerConfigurableFlag;
std::unordered_map<int, uint32_t> sampling_rate_map{};
const char* flag = isMdns ? "mdns_event_subsample_map" : "dns_event_subsample_map";
const char* defaultMap = isMdns ? DEFAULT_MDNS_SUBSAMPLING_MAP : DEFAULT_SUBSAMPLING_MAP;
const std::vector<std::string> subsampling_vector =
Split(GetServerConfigurableFlag("netd_native", flag, defaultMap), " ");
for (const auto& pair : subsampling_vector) {
std::vector<std::string> rate_denom = Split(pair, ":");
int return_code;
uint32_t denom;
if (rate_denom.size() != 2) {
LOG(ERROR) << __func__ << ": invalid subsampling_pair = " << pair;
continue;
}
if (rate_denom[0] == "default") {
return_code = DNSEVENT_SUBSAMPLING_MAP_DEFAULT_KEY;
} else if (!ParseInt(rate_denom[0], &return_code)) {
LOG(ERROR) << __func__ << ": parse subsampling_pair failed = " << pair;
continue;
}
if (!ParseUint(rate_denom[1], &denom)) {
LOG(ERROR) << __func__ << ": parse subsampling_pair failed = " << pair;
continue;
}
sampling_rate_map[return_code] = denom;
}
return sampling_rate_map;
}
} // namespace
// Note that Cache is not thread-safe per se, access to its members must be protected
// by an external mutex.
//
// TODO: move all cache manipulation code here and make data members private.
struct Cache {
Cache() : max_cache_entries(get_max_cache_entries_from_flag()) {
entries.resize(max_cache_entries);
mru_list.mru_prev = mru_list.mru_next = &mru_list;
}
~Cache() { flush(); }
void flush() {
for (int nn = 0; nn < max_cache_entries; nn++) {
Entry** pnode = (Entry**)&entries[nn];
while (*pnode) {
Entry* node = *pnode;
*pnode = node->hlink;
entry_free(node);
}
}
flushPendingRequests();
mru_list.mru_next = mru_list.mru_prev = &mru_list;
num_entries = 0;
last_id = 0;
LOG(INFO) << "DNS cache flushed";
}
void flushPendingRequests() {
pending_req_info* ri = pending_requests.next;
while (ri) {
pending_req_info* tmp = ri;
ri = ri->next;
free(tmp);
}
pending_requests.next = nullptr;
cv.notify_all();
}
int get_max_cache_entries() { return max_cache_entries; }
int num_entries = 0;
// TODO: convert to std::list
Entry mru_list;
int last_id = 0;
std::vector<Entry> entries;
// TODO: convert to std::vector
struct pending_req_info {
unsigned int hash;