• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *  * Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  *  * Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in
12  *    the documentation and/or other materials provided with the
13  *    distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #define LOG_TAG "resolv"
30 
31 #include "resolv_cache.h"
32 
33 #include <resolv.h>
34 #include <stdarg.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <time.h>
38 #include <algorithm>
39 #include <mutex>
40 #include <set>
41 #include <string>
42 #include <unordered_map>
43 #include <vector>
44 
45 #include <arpa/inet.h>
46 #include <arpa/nameser.h>
47 #include <errno.h>
48 #include <linux/if.h>
49 #include <net/if.h>
50 #include <netdb.h>
51 
52 #include <aidl/android/net/IDnsResolver.h>
53 #include <android-base/logging.h>
54 #include <android-base/parseint.h>
55 #include <android-base/stringprintf.h>
56 #include <android-base/strings.h>
57 #include <android-base/thread_annotations.h>
58 #include <android/multinetwork.h>  // ResNsendFlags
59 
60 #include <server_configurable_flags/get_flags.h>
61 
62 #include "DnsStats.h"
63 #include "Experiments.h"
64 #include "res_comp.h"
65 #include "res_debug.h"
66 #include "resolv_private.h"
67 #include "util.h"
68 
69 using aidl::android::net::IDnsResolver;
70 using aidl::android::net::ResolverOptionsParcel;
71 using android::base::StringAppendF;
72 using android::net::DnsQueryEvent;
73 using android::net::DnsStats;
74 using android::net::Experiments;
75 using android::net::PROTO_DOT;
76 using android::net::PROTO_TCP;
77 using android::net::PROTO_UDP;
78 using android::netdutils::DumpWriter;
79 using android::netdutils::IPSockAddr;
80 
81 /* This code implements a small and *simple* DNS resolver cache.
82  *
83  * It is only used to cache DNS answers for a time defined by the smallest TTL
84  * among the answer records in order to reduce DNS traffic. It is not supposed
85  * to be a full DNS cache, since we plan to implement that in the future in a
86  * dedicated process running on the system.
87  *
88  * Note that its design is kept simple very intentionally, i.e.:
89  *
90  *  - it takes raw DNS query packet data as input, and returns raw DNS
91  *    answer packet data as output
92  *
93  *    (this means that two similar queries that encode the DNS name
94  *     differently will be treated distinctly).
95  *
96  *    the smallest TTL value among the answer records are used as the time
97  *    to keep an answer in the cache.
98  *
99  *    this is bad, but we absolutely want to avoid parsing the answer packets
100  *    (and should be solved by the later full DNS cache process).
101  *
102  *  - the implementation is just a (query-data) => (answer-data) hash table
103  *    with a trivial least-recently-used expiration policy.
104  *
105  * Doing this keeps the code simple and avoids to deal with a lot of things
106  * that a full DNS cache is expected to do.
107  *
108  * The API is also very simple:
109  *
110  *   - the client calls resolv_cache_lookup() before performing a query
111  *
112  *     If the function returns RESOLV_CACHE_FOUND, a copy of the answer data
113  *     has been copied into the client-provided answer buffer.
114  *
115  *     If the function returns RESOLV_CACHE_NOTFOUND, the client should perform
116  *     a request normally, *then* call resolv_cache_add() to add the received
117  *     answer to the cache.
118  *
119  *     If the function returns RESOLV_CACHE_UNSUPPORTED, the client should
120  *     perform a request normally, and *not* call resolv_cache_add()
121  *
122  *     Note that RESOLV_CACHE_UNSUPPORTED is also returned if the answer buffer
123  *     is too short to accomodate the cached result.
124  */
125 
126 /* Default number of entries kept in the cache. This value has been
127  * determined by browsing through various sites and counting the number
128  * of corresponding requests. Keep in mind that our framework is currently
129  * performing two requests per name lookup (one for IPv4, the other for IPv6)
130  *
131  *    www.google.com      4
132  *    www.ysearch.com     6
133  *    www.amazon.com      8
134  *    www.nytimes.com     22
135  *    www.espn.com        28
136  *    www.msn.com         28
137  *    www.lemonde.fr      35
138  *
139  * (determined in 2009-2-17 from Paris, France, results may vary depending
140  *  on location)
141  *
142  * most high-level websites use lots of media/ad servers with different names
143  * but these are generally reused when browsing through the site.
144  *
145  * As such, a value of 64 should be relatively comfortable at the moment.
146  *
147  * ******************************************
148  * * NOTE - this has changed.
149  * * 1) we've added IPv6 support so each dns query results in 2 responses
150  * * 2) we've made this a system-wide cache, so the cost is less (it's not
151  * *    duplicated in each process) and the need is greater (more processes
152  * *    making different requests).
153  * * Upping by 2x for IPv6
154  * * Upping by another 5x for the centralized nature
155  * *****************************************
156  */
157 const int CONFIG_MAX_ENTRIES = 64 * 2 * 5;
158 constexpr int DNSEVENT_SUBSAMPLING_MAP_DEFAULT_KEY = -1;
159 
_time_now(void)160 static time_t _time_now(void) {
161     struct timeval tv;
162 
163     gettimeofday(&tv, NULL);
164     return tv.tv_sec;
165 }
166 
167 /* reminder: the general format of a DNS packet is the following:
168  *
169  *    HEADER  (12 bytes)
170  *    QUESTION  (variable)
171  *    ANSWER (variable)
172  *    AUTHORITY (variable)
173  *    ADDITIONNAL (variable)
174  *
175  * the HEADER is made of:
176  *
177  *   ID     : 16 : 16-bit unique query identification field
178  *
179  *   QR     :  1 : set to 0 for queries, and 1 for responses
180  *   Opcode :  4 : set to 0 for queries
181  *   AA     :  1 : set to 0 for queries
182  *   TC     :  1 : truncation flag, will be set to 0 in queries
183  *   RD     :  1 : recursion desired
184  *
185  *   RA     :  1 : recursion available (0 in queries)
186  *   Z      :  3 : three reserved zero bits
187  *   RCODE  :  4 : response code (always 0=NOERROR in queries)
188  *
189  *   QDCount: 16 : question count
190  *   ANCount: 16 : Answer count (0 in queries)
191  *   NSCount: 16: Authority Record count (0 in queries)
192  *   ARCount: 16: Additionnal Record count (0 in queries)
193  *
194  * the QUESTION is made of QDCount Question Record (QRs)
195  * the ANSWER is made of ANCount RRs
196  * the AUTHORITY is made of NSCount RRs
197  * the ADDITIONNAL is made of ARCount RRs
198  *
199  * Each Question Record (QR) is made of:
200  *
201  *   QNAME   : variable : Query DNS NAME
202  *   TYPE    : 16       : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
203  *   CLASS   : 16       : class of query (IN=1)
204  *
205  * Each Resource Record (RR) is made of:
206  *
207  *   NAME    : variable : DNS NAME
208  *   TYPE    : 16       : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
209  *   CLASS   : 16       : class of query (IN=1)
210  *   TTL     : 32       : seconds to cache this RR (0=none)
211  *   RDLENGTH: 16       : size of RDDATA in bytes
212  *   RDDATA  : variable : RR data (depends on TYPE)
213  *
214  * Each QNAME contains a domain name encoded as a sequence of 'labels'
215  * terminated by a zero. Each label has the following format:
216  *
217  *    LEN  : 8     : lenght of label (MUST be < 64)
218  *    NAME : 8*LEN : label length (must exclude dots)
219  *
220  * A value of 0 in the encoding is interpreted as the 'root' domain and
221  * terminates the encoding. So 'www.android.com' will be encoded as:
222  *
223  *   <3>www<7>android<3>com<0>
224  *
225  * Where <n> represents the byte with value 'n'
226  *
227  * Each NAME reflects the QNAME of the question, but has a slightly more
228  * complex encoding in order to provide message compression. This is achieved
229  * by using a 2-byte pointer, with format:
230  *
231  *    TYPE   : 2  : 0b11 to indicate a pointer, 0b01 and 0b10 are reserved
232  *    OFFSET : 14 : offset to another part of the DNS packet
233  *
234  * The offset is relative to the start of the DNS packet and must point
235  * A pointer terminates the encoding.
236  *
237  * The NAME can be encoded in one of the following formats:
238  *
239  *   - a sequence of simple labels terminated by 0 (like QNAMEs)
240  *   - a single pointer
241  *   - a sequence of simple labels terminated by a pointer
242  *
243  * A pointer shall always point to either a pointer of a sequence of
244  * labels (which can themselves be terminated by either a 0 or a pointer)
245  *
246  * The expanded length of a given domain name should not exceed 255 bytes.
247  *
248  * NOTE: we don't parse the answer packets, so don't need to deal with NAME
249  *       records, only QNAMEs.
250  */
251 
252 #define DNS_HEADER_SIZE 12
253 
254 #define DNS_TYPE_A "\00\01"     /* big-endian decimal 1 */
255 #define DNS_TYPE_PTR "\00\014"  /* big-endian decimal 12 */
256 #define DNS_TYPE_MX "\00\017"   /* big-endian decimal 15 */
257 #define DNS_TYPE_AAAA "\00\034" /* big-endian decimal 28 */
258 #define DNS_TYPE_ALL "\00\0377" /* big-endian decimal 255 */
259 
260 #define DNS_CLASS_IN "\00\01" /* big-endian decimal 1 */
261 
262 struct DnsPacket {
263     const uint8_t* base;
264     const uint8_t* end;
265     const uint8_t* cursor;
266 };
267 
res_tolower(uint8_t c)268 static uint8_t res_tolower(uint8_t c) {
269     return (c >= 'A' && c <= 'Z') ? (c | 0x20) : c;
270 }
271 
res_memcasecmp(const unsigned char * s1,const unsigned char * s2,size_t len)272 static int res_memcasecmp(const unsigned char *s1, const unsigned char *s2, size_t len) {
273     for (size_t i = 0; i < len; i++) {
274         int ch1 = *s1++;
275         int ch2 = *s2++;
276         int d = res_tolower(ch1) - res_tolower(ch2);
277         if (d != 0) {
278             return d;
279         }
280     }
281     return 0;
282 }
283 
_dnsPacket_init(DnsPacket * packet,const uint8_t * buff,int bufflen)284 static void _dnsPacket_init(DnsPacket* packet, const uint8_t* buff, int bufflen) {
285     packet->base = buff;
286     packet->end = buff + bufflen;
287     packet->cursor = buff;
288 }
289 
_dnsPacket_rewind(DnsPacket * packet)290 static void _dnsPacket_rewind(DnsPacket* packet) {
291     packet->cursor = packet->base;
292 }
293 
_dnsPacket_skip(DnsPacket * packet,int count)294 static void _dnsPacket_skip(DnsPacket* packet, int count) {
295     const uint8_t* p = packet->cursor + count;
296 
297     if (p > packet->end) p = packet->end;
298 
299     packet->cursor = p;
300 }
301 
_dnsPacket_readInt16(DnsPacket * packet)302 static int _dnsPacket_readInt16(DnsPacket* packet) {
303     const uint8_t* p = packet->cursor;
304 
305     if (p + 2 > packet->end) return -1;
306 
307     packet->cursor = p + 2;
308     return (p[0] << 8) | p[1];
309 }
310 
311 /** QUERY CHECKING **/
312 
313 /* check bytes in a dns packet. returns 1 on success, 0 on failure.
314  * the cursor is only advanced in the case of success
315  */
_dnsPacket_checkBytes(DnsPacket * packet,int numBytes,const void * bytes)316 static int _dnsPacket_checkBytes(DnsPacket* packet, int numBytes, const void* bytes) {
317     const uint8_t* p = packet->cursor;
318 
319     if (p + numBytes > packet->end) return 0;
320 
321     if (memcmp(p, bytes, numBytes) != 0) return 0;
322 
323     packet->cursor = p + numBytes;
324     return 1;
325 }
326 
327 /* parse and skip a given QNAME stored in a query packet,
328  * from the current cursor position. returns 1 on success,
329  * or 0 for malformed data.
330  */
_dnsPacket_checkQName(DnsPacket * packet)331 static int _dnsPacket_checkQName(DnsPacket* packet) {
332     const uint8_t* p = packet->cursor;
333     const uint8_t* end = packet->end;
334 
335     for (;;) {
336         int c;
337 
338         if (p >= end) break;
339 
340         c = *p++;
341 
342         if (c == 0) {
343             packet->cursor = p;
344             return 1;
345         }
346 
347         /* we don't expect label compression in QNAMEs */
348         if (c >= 64) break;
349 
350         p += c;
351         /* we rely on the bound check at the start
352          * of the loop here */
353     }
354     /* malformed data */
355     LOG(INFO) << __func__ << ": malformed QNAME";
356     return 0;
357 }
358 
359 /* parse and skip a given QR stored in a packet.
360  * returns 1 on success, and 0 on failure
361  */
_dnsPacket_checkQR(DnsPacket * packet)362 static int _dnsPacket_checkQR(DnsPacket* packet) {
363     if (!_dnsPacket_checkQName(packet)) return 0;
364 
365     /* TYPE must be one of the things we support */
366     if (!_dnsPacket_checkBytes(packet, 2, DNS_TYPE_A) &&
367         !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_PTR) &&
368         !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_MX) &&
369         !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_AAAA) &&
370         !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_ALL)) {
371         LOG(INFO) << __func__ << ": unsupported TYPE";
372         return 0;
373     }
374     /* CLASS must be IN */
375     if (!_dnsPacket_checkBytes(packet, 2, DNS_CLASS_IN)) {
376         LOG(INFO) << __func__ << ": unsupported CLASS";
377         return 0;
378     }
379 
380     return 1;
381 }
382 
383 /* check the header of a DNS Query packet, return 1 if it is one
384  * type of query we can cache, or 0 otherwise
385  */
_dnsPacket_checkQuery(DnsPacket * packet)386 static int _dnsPacket_checkQuery(DnsPacket* packet) {
387     const uint8_t* p = packet->base;
388     int qdCount, anCount, dnCount, arCount;
389 
390     if (p + DNS_HEADER_SIZE > packet->end) {
391         LOG(INFO) << __func__ << ": query packet too small";
392         return 0;
393     }
394 
395     /* QR must be set to 0, opcode must be 0 and AA must be 0 */
396     /* RA, Z, and RCODE must be 0 */
397     if ((p[2] & 0xFC) != 0 || (p[3] & 0xCF) != 0) {
398         LOG(INFO) << __func__ << ": query packet flags unsupported";
399         return 0;
400     }
401 
402     /* Note that we ignore the TC, RD, CD, and AD bits here for the
403      * following reasons:
404      *
405      * - there is no point for a query packet sent to a server
406      *   to have the TC bit set, but the implementation might
407      *   set the bit in the query buffer for its own needs
408      *   between a resolv_cache_lookup and a resolv_cache_add.
409      *   We should not freak out if this is the case.
410      *
411      * - we consider that the result from a query might depend on
412      *   the RD, AD, and CD bits, so these bits
413      *   should be used to differentiate cached result.
414      *
415      *   this implies that these bits are checked when hashing or
416      *   comparing query packets, but not TC
417      */
418 
419     /* ANCOUNT, DNCOUNT and ARCOUNT must be 0 */
420     qdCount = (p[4] << 8) | p[5];
421     anCount = (p[6] << 8) | p[7];
422     dnCount = (p[8] << 8) | p[9];
423     arCount = (p[10] << 8) | p[11];
424 
425     if (anCount != 0 || dnCount != 0 || arCount > 1) {
426         LOG(INFO) << __func__ << ": query packet contains non-query records";
427         return 0;
428     }
429 
430     if (qdCount == 0) {
431         LOG(INFO) << __func__ << ": query packet doesn't contain query record";
432         return 0;
433     }
434 
435     /* Check QDCOUNT QRs */
436     packet->cursor = p + DNS_HEADER_SIZE;
437 
438     for (; qdCount > 0; qdCount--)
439         if (!_dnsPacket_checkQR(packet)) return 0;
440 
441     return 1;
442 }
443 
444 /** QUERY HASHING SUPPORT
445  **
446  ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKET HAS ALREADY
447  ** BEEN SUCCESFULLY CHECKED.
448  **/
449 
450 /* use 32-bit FNV hash function */
451 #define FNV_MULT 16777619U
452 #define FNV_BASIS 2166136261U
453 
_dnsPacket_hashBytes(DnsPacket * packet,int numBytes,unsigned hash)454 static unsigned _dnsPacket_hashBytes(DnsPacket* packet, int numBytes, unsigned hash) {
455     const uint8_t* p = packet->cursor;
456     const uint8_t* end = packet->end;
457 
458     while (numBytes > 0 && p < end) {
459         hash = hash * FNV_MULT ^ *p++;
460         numBytes--;
461     }
462     packet->cursor = p;
463     return hash;
464 }
465 
_dnsPacket_hashQName(DnsPacket * packet,unsigned hash)466 static unsigned _dnsPacket_hashQName(DnsPacket* packet, unsigned hash) {
467     const uint8_t* p = packet->cursor;
468     const uint8_t* end = packet->end;
469 
470     for (;;) {
471         if (p >= end) { /* should not happen */
472             LOG(INFO) << __func__ << ": INTERNAL_ERROR: read-overflow";
473             break;
474         }
475 
476         int c = *p++;
477 
478         if (c == 0) break;
479 
480         if (c >= 64) {
481             LOG(INFO) << __func__ << ": INTERNAL_ERROR: malformed domain";
482             break;
483         }
484         if (p + c >= end) {
485             LOG(INFO) << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
486             break;
487         }
488 
489         while (c > 0) {
490             uint8_t ch = *p++;
491             ch = res_tolower(ch);
492             hash = hash * FNV_MULT ^ ch;
493             c--;
494         }
495     }
496     packet->cursor = p;
497     return hash;
498 }
499 
_dnsPacket_hashQR(DnsPacket * packet,unsigned hash)500 static unsigned _dnsPacket_hashQR(DnsPacket* packet, unsigned hash) {
501     hash = _dnsPacket_hashQName(packet, hash);
502     hash = _dnsPacket_hashBytes(packet, 4, hash); /* TYPE and CLASS */
503     return hash;
504 }
505 
_dnsPacket_hashRR(DnsPacket * packet,unsigned hash)506 static unsigned _dnsPacket_hashRR(DnsPacket* packet, unsigned hash) {
507     int rdlength;
508     hash = _dnsPacket_hashQR(packet, hash);
509     hash = _dnsPacket_hashBytes(packet, 4, hash); /* TTL */
510     rdlength = _dnsPacket_readInt16(packet);
511     hash = _dnsPacket_hashBytes(packet, rdlength, hash); /* RDATA */
512     return hash;
513 }
514 
_dnsPacket_hashQuery(DnsPacket * packet)515 static unsigned _dnsPacket_hashQuery(DnsPacket* packet) {
516     unsigned hash = FNV_BASIS;
517     int count, arcount;
518     _dnsPacket_rewind(packet);
519 
520     /* ignore the ID */
521     _dnsPacket_skip(packet, 2);
522 
523     /* we ignore the TC bit for reasons explained in
524      * _dnsPacket_checkQuery().
525      *
526      * however we hash the RD bit to differentiate
527      * between answers for recursive and non-recursive
528      * queries.
529      */
530     hash = hash * FNV_MULT ^ (packet->base[2] & 1);
531 
532     /* mark the first header byte as processed */
533     _dnsPacket_skip(packet, 1);
534 
535     /* process the second header byte */
536     hash = _dnsPacket_hashBytes(packet, 1, hash);
537 
538     /* read QDCOUNT */
539     count = _dnsPacket_readInt16(packet);
540 
541     /* assume: ANcount and NScount are 0 */
542     _dnsPacket_skip(packet, 4);
543 
544     /* read ARCOUNT */
545     arcount = _dnsPacket_readInt16(packet);
546 
547     /* hash QDCOUNT QRs */
548     for (; count > 0; count--) hash = _dnsPacket_hashQR(packet, hash);
549 
550     /* hash ARCOUNT RRs */
551     for (; arcount > 0; arcount--) hash = _dnsPacket_hashRR(packet, hash);
552 
553     return hash;
554 }
555 
556 /** QUERY COMPARISON
557  **
558  ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKETS HAVE ALREADY
559  ** BEEN SUCCESSFULLY CHECKED.
560  **/
561 
_dnsPacket_isEqualDomainName(DnsPacket * pack1,DnsPacket * pack2)562 static int _dnsPacket_isEqualDomainName(DnsPacket* pack1, DnsPacket* pack2) {
563     const uint8_t* p1 = pack1->cursor;
564     const uint8_t* end1 = pack1->end;
565     const uint8_t* p2 = pack2->cursor;
566     const uint8_t* end2 = pack2->end;
567 
568     for (;;) {
569         if (p1 >= end1 || p2 >= end2) {
570             LOG(INFO) << __func__ << ": INTERNAL_ERROR: read-overflow";
571             break;
572         }
573         int c1 = *p1++;
574         int c2 = *p2++;
575         if (c1 != c2) break;
576 
577         if (c1 == 0) {
578             pack1->cursor = p1;
579             pack2->cursor = p2;
580             return 1;
581         }
582         if (c1 >= 64) {
583             LOG(INFO) << __func__ << ": INTERNAL_ERROR: malformed domain";
584             break;
585         }
586         if ((p1 + c1 > end1) || (p2 + c1 > end2)) {
587             LOG(INFO) << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
588             break;
589         }
590         if (res_memcasecmp(p1, p2, c1) != 0) break;
591         p1 += c1;
592         p2 += c1;
593         /* we rely on the bound checks at the start of the loop */
594     }
595     /* not the same, or one is malformed */
596     LOG(INFO) << __func__ << ": different DN";
597     return 0;
598 }
599 
_dnsPacket_isEqualBytes(DnsPacket * pack1,DnsPacket * pack2,int numBytes)600 static int _dnsPacket_isEqualBytes(DnsPacket* pack1, DnsPacket* pack2, int numBytes) {
601     const uint8_t* p1 = pack1->cursor;
602     const uint8_t* p2 = pack2->cursor;
603 
604     if (p1 + numBytes > pack1->end || p2 + numBytes > pack2->end) return 0;
605 
606     if (memcmp(p1, p2, numBytes) != 0) return 0;
607 
608     pack1->cursor += numBytes;
609     pack2->cursor += numBytes;
610     return 1;
611 }
612 
_dnsPacket_isEqualQR(DnsPacket * pack1,DnsPacket * pack2)613 static int _dnsPacket_isEqualQR(DnsPacket* pack1, DnsPacket* pack2) {
614     /* compare domain name encoding + TYPE + CLASS */
615     if (!_dnsPacket_isEqualDomainName(pack1, pack2) ||
616         !_dnsPacket_isEqualBytes(pack1, pack2, 2 + 2))
617         return 0;
618 
619     return 1;
620 }
621 
_dnsPacket_isEqualRR(DnsPacket * pack1,DnsPacket * pack2)622 static int _dnsPacket_isEqualRR(DnsPacket* pack1, DnsPacket* pack2) {
623     int rdlength1, rdlength2;
624     /* compare query + TTL */
625     if (!_dnsPacket_isEqualQR(pack1, pack2) || !_dnsPacket_isEqualBytes(pack1, pack2, 4)) return 0;
626 
627     /* compare RDATA */
628     rdlength1 = _dnsPacket_readInt16(pack1);
629     rdlength2 = _dnsPacket_readInt16(pack2);
630     if (rdlength1 != rdlength2 || !_dnsPacket_isEqualBytes(pack1, pack2, rdlength1)) return 0;
631 
632     return 1;
633 }
634 
_dnsPacket_isEqualQuery(DnsPacket * pack1,DnsPacket * pack2)635 static int _dnsPacket_isEqualQuery(DnsPacket* pack1, DnsPacket* pack2) {
636     int count1, count2, arcount1, arcount2;
637 
638     /* compare the headers, ignore most fields */
639     _dnsPacket_rewind(pack1);
640     _dnsPacket_rewind(pack2);
641 
642     /* compare RD, ignore TC, see comment in _dnsPacket_checkQuery */
643     if ((pack1->base[2] & 1) != (pack2->base[2] & 1)) {
644         LOG(INFO) << __func__ << ": different RD";
645         return 0;
646     }
647 
648     if (pack1->base[3] != pack2->base[3]) {
649         LOG(INFO) << __func__ << ": different CD or AD";
650         return 0;
651     }
652 
653     /* mark ID and header bytes as compared */
654     _dnsPacket_skip(pack1, 4);
655     _dnsPacket_skip(pack2, 4);
656 
657     /* compare QDCOUNT */
658     count1 = _dnsPacket_readInt16(pack1);
659     count2 = _dnsPacket_readInt16(pack2);
660     if (count1 != count2 || count1 < 0) {
661         LOG(INFO) << __func__ << ": different QDCOUNT";
662         return 0;
663     }
664 
665     /* assume: ANcount and NScount are 0 */
666     _dnsPacket_skip(pack1, 4);
667     _dnsPacket_skip(pack2, 4);
668 
669     /* compare ARCOUNT */
670     arcount1 = _dnsPacket_readInt16(pack1);
671     arcount2 = _dnsPacket_readInt16(pack2);
672     if (arcount1 != arcount2 || arcount1 < 0) {
673         LOG(INFO) << __func__ << ": different ARCOUNT";
674         return 0;
675     }
676 
677     /* compare the QDCOUNT QRs */
678     for (; count1 > 0; count1--) {
679         if (!_dnsPacket_isEqualQR(pack1, pack2)) {
680             LOG(INFO) << __func__ << ": different QR";
681             return 0;
682         }
683     }
684 
685     /* compare the ARCOUNT RRs */
686     for (; arcount1 > 0; arcount1--) {
687         if (!_dnsPacket_isEqualRR(pack1, pack2)) {
688             LOG(INFO) << __func__ << ": different additional RR";
689             return 0;
690         }
691     }
692     return 1;
693 }
694 
695 /* cache entry. for simplicity, 'hash' and 'hlink' are inlined in this
696  * structure though they are conceptually part of the hash table.
697  *
698  * similarly, mru_next and mru_prev are part of the global MRU list
699  */
700 struct Entry {
701     unsigned int hash;   /* hash value */
702     struct Entry* hlink; /* next in collision chain */
703     struct Entry* mru_prev;
704     struct Entry* mru_next;
705 
706     const uint8_t* query;
707     int querylen;
708     const uint8_t* answer;
709     int answerlen;
710     time_t expires; /* time_t when the entry isn't valid any more */
711     int id;         /* for debugging purpose */
712 };
713 
714 /*
715  * Find the TTL for a negative DNS result.  This is defined as the minimum
716  * of the SOA records TTL and the MINIMUM-TTL field (RFC-2308).
717  *
718  * Return 0 if not found.
719  */
answer_getNegativeTTL(ns_msg handle)720 static uint32_t answer_getNegativeTTL(ns_msg handle) {
721     int n, nscount;
722     uint32_t result = 0;
723     ns_rr rr;
724 
725     nscount = ns_msg_count(handle, ns_s_ns);
726     for (n = 0; n < nscount; n++) {
727         if ((ns_parserr(&handle, ns_s_ns, n, &rr) == 0) && (ns_rr_type(rr) == ns_t_soa)) {
728             const uint8_t* rdata = ns_rr_rdata(rr);          // find the data
729             const uint8_t* edata = rdata + ns_rr_rdlen(rr);  // add the len to find the end
730             int len;
731             uint32_t ttl, rec_result = rr.ttl;
732 
733             // find the MINIMUM-TTL field from the blob of binary data for this record
734             // skip the server name
735             len = dn_skipname(rdata, edata);
736             if (len == -1) continue;  // error skipping
737             rdata += len;
738 
739             // skip the admin name
740             len = dn_skipname(rdata, edata);
741             if (len == -1) continue;  // error skipping
742             rdata += len;
743 
744             if (edata - rdata != 5 * NS_INT32SZ) continue;
745             // skip: serial number + refresh interval + retry interval + expiry
746             rdata += NS_INT32SZ * 4;
747             // finally read the MINIMUM TTL
748             ttl = ntohl(*reinterpret_cast<const uint32_t*>(rdata));
749             if (ttl < rec_result) {
750                 rec_result = ttl;
751             }
752             // Now that the record is read successfully, apply the new min TTL
753             if (n == 0 || rec_result < result) {
754                 result = rec_result;
755             }
756         }
757     }
758     return result;
759 }
760 
761 /*
762  * Parse the answer records and find the appropriate
763  * smallest TTL among the records.  This might be from
764  * the answer records if found or from the SOA record
765  * if it's a negative result.
766  *
767  * The returned TTL is the number of seconds to
768  * keep the answer in the cache.
769  *
770  * In case of parse error zero (0) is returned which
771  * indicates that the answer shall not be cached.
772  */
answer_getTTL(const void * answer,int answerlen)773 static uint32_t answer_getTTL(const void* answer, int answerlen) {
774     ns_msg handle;
775     int ancount, n;
776     uint32_t result, ttl;
777     ns_rr rr;
778 
779     result = 0;
780     if (ns_initparse((const uint8_t*) answer, answerlen, &handle) >= 0) {
781         // get number of answer records
782         ancount = ns_msg_count(handle, ns_s_an);
783 
784         if (ancount == 0) {
785             // a response with no answers?  Cache this negative result.
786             result = answer_getNegativeTTL(handle);
787         } else {
788             for (n = 0; n < ancount; n++) {
789                 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
790                     ttl = rr.ttl;
791                     if (n == 0 || ttl < result) {
792                         result = ttl;
793                     }
794                 } else {
795                     PLOG(INFO) << __func__ << ": ns_parserr failed ancount no = " << n;
796                 }
797             }
798         }
799     } else {
800         PLOG(INFO) << __func__ << ": ns_initparse failed";
801     }
802 
803     LOG(INFO) << __func__ << ": TTL = " << result;
804     return result;
805 }
806 
entry_free(Entry * e)807 static void entry_free(Entry* e) {
808     /* everything is allocated in a single memory block */
809     if (e) {
810         free(e);
811     }
812 }
813 
entry_mru_remove(Entry * e)814 static void entry_mru_remove(Entry* e) {
815     e->mru_prev->mru_next = e->mru_next;
816     e->mru_next->mru_prev = e->mru_prev;
817 }
818 
entry_mru_add(Entry * e,Entry * list)819 static void entry_mru_add(Entry* e, Entry* list) {
820     Entry* first = list->mru_next;
821 
822     e->mru_next = first;
823     e->mru_prev = list;
824 
825     list->mru_next = e;
826     first->mru_prev = e;
827 }
828 
829 /* compute the hash of a given entry, this is a hash of most
830  * data in the query (key) */
entry_hash(const Entry * e)831 static unsigned entry_hash(const Entry* e) {
832     DnsPacket pack[1];
833 
834     _dnsPacket_init(pack, e->query, e->querylen);
835     return _dnsPacket_hashQuery(pack);
836 }
837 
838 /* initialize an Entry as a search key, this also checks the input query packet
839  * returns 1 on success, or 0 in case of unsupported/malformed data */
entry_init_key(Entry * e,const void * query,int querylen)840 static int entry_init_key(Entry* e, const void* query, int querylen) {
841     DnsPacket pack[1];
842 
843     memset(e, 0, sizeof(*e));
844 
845     e->query = (const uint8_t*) query;
846     e->querylen = querylen;
847     e->hash = entry_hash(e);
848 
849     _dnsPacket_init(pack, e->query, e->querylen);
850 
851     return _dnsPacket_checkQuery(pack);
852 }
853 
854 /* allocate a new entry as a cache node */
entry_alloc(const Entry * init,const void * answer,int answerlen)855 static Entry* entry_alloc(const Entry* init, const void* answer, int answerlen) {
856     Entry* e;
857     int size;
858 
859     size = sizeof(*e) + init->querylen + answerlen;
860     e = (Entry*) calloc(size, 1);
861     if (e == NULL) return e;
862 
863     e->hash = init->hash;
864     e->query = (const uint8_t*) (e + 1);
865     e->querylen = init->querylen;
866 
867     memcpy((char*) e->query, init->query, e->querylen);
868 
869     e->answer = e->query + e->querylen;
870     e->answerlen = answerlen;
871 
872     memcpy((char*) e->answer, answer, e->answerlen);
873 
874     return e;
875 }
876 
entry_equals(const Entry * e1,const Entry * e2)877 static int entry_equals(const Entry* e1, const Entry* e2) {
878     DnsPacket pack1[1], pack2[1];
879 
880     if (e1->querylen != e2->querylen) {
881         return 0;
882     }
883     _dnsPacket_init(pack1, e1->query, e1->querylen);
884     _dnsPacket_init(pack2, e2->query, e2->querylen);
885 
886     return _dnsPacket_isEqualQuery(pack1, pack2);
887 }
888 
889 /* We use a simple hash table with external collision lists
890  * for simplicity, the hash-table fields 'hash' and 'hlink' are
891  * inlined in the Entry structure.
892  */
893 
894 /* Maximum time for a thread to wait for an pending request */
895 constexpr int PENDING_REQUEST_TIMEOUT = 20;
896 
897 // lock protecting everything in NetConfig.
898 static std::mutex cache_mutex;
899 static std::condition_variable cv;
900 
901 namespace {
902 
903 // Map format: ReturnCode:rate_denom
904 // if the ReturnCode is not associated with any rate_denom, use default
905 // Sampling rate varies by return code; events to log are chosen randomly, with a
906 // probability proportional to the sampling rate.
907 constexpr const char DEFAULT_SUBSAMPLING_MAP[] = "default:8 0:400 2:110 7:110";
908 
resolv_get_dns_event_subsampling_map()909 std::unordered_map<int, uint32_t> resolv_get_dns_event_subsampling_map() {
910     using android::base::ParseInt;
911     using android::base::ParseUint;
912     using android::base::Split;
913     using server_configurable_flags::GetServerConfigurableFlag;
914     std::unordered_map<int, uint32_t> sampling_rate_map{};
915     std::vector<std::string> subsampling_vector =
916             Split(GetServerConfigurableFlag("netd_native", "dns_event_subsample_map",
917                                             DEFAULT_SUBSAMPLING_MAP),
918                   " ");
919     for (const auto& pair : subsampling_vector) {
920         std::vector<std::string> rate_denom = Split(pair, ":");
921         int return_code;
922         uint32_t denom;
923         if (rate_denom.size() != 2) {
924             LOG(ERROR) << __func__ << ": invalid subsampling_pair = " << pair;
925             continue;
926         }
927         if (rate_denom[0] == "default") {
928             return_code = DNSEVENT_SUBSAMPLING_MAP_DEFAULT_KEY;
929         } else if (!ParseInt(rate_denom[0], &return_code)) {
930             LOG(ERROR) << __func__ << ": parse subsampling_pair failed = " << pair;
931             continue;
932         }
933         if (!ParseUint(rate_denom[1], &denom)) {
934             LOG(ERROR) << __func__ << ": parse subsampling_pair failed = " << pair;
935             continue;
936         }
937         sampling_rate_map[return_code] = denom;
938     }
939     return sampling_rate_map;
940 }
941 
942 }  // namespace
943 
944 // Note that Cache is not thread-safe per se, access to its members must be protected
945 // by an external mutex.
946 //
947 // TODO: move all cache manipulation code here and make data members private.
948 struct Cache {
CacheCache949     Cache() {
950         entries.resize(CONFIG_MAX_ENTRIES);
951         mru_list.mru_prev = mru_list.mru_next = &mru_list;
952     }
~CacheCache953     ~Cache() { flush(); }
954 
flushCache955     void flush() {
956         for (int nn = 0; nn < CONFIG_MAX_ENTRIES; nn++) {
957             Entry** pnode = (Entry**)&entries[nn];
958 
959             while (*pnode) {
960                 Entry* node = *pnode;
961                 *pnode = node->hlink;
962                 entry_free(node);
963             }
964         }
965 
966         flushPendingRequests();
967 
968         mru_list.mru_next = mru_list.mru_prev = &mru_list;
969         num_entries = 0;
970         last_id = 0;
971 
972         LOG(INFO) << "DNS cache flushed";
973     }
974 
flushPendingRequestsCache975     void flushPendingRequests() {
976         pending_req_info* ri = pending_requests.next;
977         while (ri) {
978             pending_req_info* tmp = ri;
979             ri = ri->next;
980             free(tmp);
981         }
982 
983         pending_requests.next = nullptr;
984         cv.notify_all();
985     }
986 
987     int num_entries = 0;
988 
989     // TODO: convert to std::list
990     Entry mru_list;
991     int last_id = 0;
992     std::vector<Entry> entries;
993 
994     // TODO: convert to std::vector
995     struct pending_req_info {
996         unsigned int hash;
997         struct pending_req_info* next;
998     } pending_requests{};
999 };
1000 
1001 struct NetConfig {
NetConfigNetConfig1002     explicit NetConfig(unsigned netId) : netid(netId) {
1003         cache = std::make_unique<Cache>();
1004         dns_event_subsampling_map = resolv_get_dns_event_subsampling_map();
1005     }
nameserverCountNetConfig1006     int nameserverCount() { return nameserverSockAddrs.size(); }
setOptionsNetConfig1007     int setOptions(const ResolverOptionsParcel& resolverOptions) {
1008         customizedTable.clear();
1009         for (const auto& host : resolverOptions.hosts) {
1010             if (!host.hostName.empty() && !host.ipAddr.empty())
1011                 customizedTable.emplace(host.hostName, host.ipAddr);
1012         }
1013 
1014         if (resolverOptions.tcMode < aidl::android::net::IDnsResolver::TC_MODE_DEFAULT ||
1015             resolverOptions.tcMode > aidl::android::net::IDnsResolver::TC_MODE_UDP_TCP) {
1016             LOG(WARNING) << __func__ << ": netid = " << netid
1017                          << ", invalid TC mode: " << resolverOptions.tcMode;
1018             return -EINVAL;
1019         }
1020         tc_mode = resolverOptions.tcMode;
1021         enforceDnsUid = resolverOptions.enforceDnsUid;
1022         return 0;
1023     }
1024     const unsigned netid;
1025     std::unique_ptr<Cache> cache;
1026     std::vector<std::string> nameservers;
1027     std::vector<IPSockAddr> nameserverSockAddrs;
1028     int revision_id = 0;  // # times the nameservers have been replaced
1029     res_params params{};
1030     res_stats nsstats[MAXNS]{};
1031     std::vector<std::string> search_domains;
1032     int wait_for_pending_req_timeout_count = 0;
1033     // Map format: ReturnCode:rate_denom
1034     std::unordered_map<int, uint32_t> dns_event_subsampling_map;
1035     DnsStats dnsStats;
1036 
1037     // Customized hostname/address table will be stored in customizedTable.
1038     // If resolverParams.hosts is empty, the existing customized table will be erased.
1039     typedef std::multimap<std::string /* hostname */, std::string /* IPv4/IPv6 address */>
1040             HostMapping;
1041     HostMapping customizedTable = {};
1042 
1043     int tc_mode = aidl::android::net::IDnsResolver::TC_MODE_DEFAULT;
1044     bool enforceDnsUid = false;
1045     std::vector<int32_t> transportTypes;
1046 };
1047 
1048 /* gets cache associated with a network, or NULL if none exists */
1049 static Cache* find_named_cache_locked(unsigned netid) REQUIRES(cache_mutex);
1050 
1051 // Return true - if there is a pending request in |cache| matching |key|.
1052 // Return false - if no pending request is found matching the key. Optionally
1053 //                link a new one if parameter append_if_not_found is true.
cache_has_pending_request_locked(Cache * cache,const Entry * key,bool append_if_not_found)1054 static bool cache_has_pending_request_locked(Cache* cache, const Entry* key,
1055                                              bool append_if_not_found) {
1056     if (!cache || !key) return false;
1057 
1058     Cache::pending_req_info* ri = cache->pending_requests.next;
1059     Cache::pending_req_info* prev = &cache->pending_requests;
1060     while (ri) {
1061         if (ri->hash == key->hash) {
1062             return true;
1063         }
1064         prev = ri;
1065         ri = ri->next;
1066     }
1067 
1068     if (append_if_not_found) {
1069         ri = (Cache::pending_req_info*)calloc(1, sizeof(Cache::pending_req_info));
1070         if (ri) {
1071             ri->hash = key->hash;
1072             prev->next = ri;
1073         }
1074     }
1075     return false;
1076 }
1077 
1078 // Notify all threads that the cache entry |key| has become available
cache_notify_waiting_tid_locked(struct Cache * cache,const Entry * key)1079 static void cache_notify_waiting_tid_locked(struct Cache* cache, const Entry* key) {
1080     if (!cache || !key) return;
1081 
1082     Cache::pending_req_info* ri = cache->pending_requests.next;
1083     Cache::pending_req_info* prev = &cache->pending_requests;
1084     while (ri) {
1085         if (ri->hash == key->hash) {
1086             // remove item from list and destroy
1087             prev->next = ri->next;
1088             free(ri);
1089             cv.notify_all();
1090             return;
1091         }
1092         prev = ri;
1093         ri = ri->next;
1094     }
1095 }
1096 
_resolv_cache_query_failed(unsigned netid,const void * query,int querylen,uint32_t flags)1097 void _resolv_cache_query_failed(unsigned netid, const void* query, int querylen, uint32_t flags) {
1098     // We should not notify with these flags.
1099     if (flags & (ANDROID_RESOLV_NO_CACHE_STORE | ANDROID_RESOLV_NO_CACHE_LOOKUP)) {
1100         return;
1101     }
1102     Entry key[1];
1103 
1104     if (!entry_init_key(key, query, querylen)) return;
1105 
1106     std::lock_guard guard(cache_mutex);
1107 
1108     Cache* cache = find_named_cache_locked(netid);
1109 
1110     if (cache) {
1111         cache_notify_waiting_tid_locked(cache, key);
1112     }
1113 }
1114 
cache_dump_mru_locked(Cache * cache)1115 static void cache_dump_mru_locked(Cache* cache) {
1116     std::string buf;
1117 
1118     StringAppendF(&buf, "MRU LIST (%2d): ", cache->num_entries);
1119     for (Entry* e = cache->mru_list.mru_next; e != &cache->mru_list; e = e->mru_next) {
1120         StringAppendF(&buf, " %d", e->id);
1121     }
1122 
1123     LOG(INFO) << __func__ << ": " << buf;
1124 }
1125 
1126 /* This function tries to find a key within the hash table
1127  * In case of success, it will return a *pointer* to the hashed key.
1128  * In case of failure, it will return a *pointer* to NULL
1129  *
1130  * So, the caller must check '*result' to check for success/failure.
1131  *
1132  * The main idea is that the result can later be used directly in
1133  * calls to resolv_cache_add or _resolv_cache_remove as the 'lookup'
1134  * parameter. This makes the code simpler and avoids re-searching
1135  * for the key position in the htable.
1136  *
1137  * The result of a lookup_p is only valid until you alter the hash
1138  * table.
1139  */
_cache_lookup_p(Cache * cache,Entry * key)1140 static Entry** _cache_lookup_p(Cache* cache, Entry* key) {
1141     int index = key->hash % CONFIG_MAX_ENTRIES;
1142     Entry** pnode = (Entry**) &cache->entries[index];
1143 
1144     while (*pnode != NULL) {
1145         Entry* node = *pnode;
1146 
1147         if (node == NULL) break;
1148 
1149         if (node->hash == key->hash && entry_equals(node, key)) break;
1150 
1151         pnode = &node->hlink;
1152     }
1153     return pnode;
1154 }
1155 
1156 /* Add a new entry to the hash table. 'lookup' must be the
1157  * result of an immediate previous failed _lookup_p() call
1158  * (i.e. with *lookup == NULL), and 'e' is the pointer to the
1159  * newly created entry
1160  */
_cache_add_p(Cache * cache,Entry ** lookup,Entry * e)1161 static void _cache_add_p(Cache* cache, Entry** lookup, Entry* e) {
1162     *lookup = e;
1163     e->id = ++cache->last_id;
1164     entry_mru_add(e, &cache->mru_list);
1165     cache->num_entries += 1;
1166 
1167     LOG(INFO) << __func__ << ": entry " << e->id << " added (count=" << cache->num_entries << ")";
1168 }
1169 
1170 /* Remove an existing entry from the hash table,
1171  * 'lookup' must be the result of an immediate previous
1172  * and succesful _lookup_p() call.
1173  */
_cache_remove_p(Cache * cache,Entry ** lookup)1174 static void _cache_remove_p(Cache* cache, Entry** lookup) {
1175     Entry* e = *lookup;
1176 
1177     LOG(INFO) << __func__ << ": entry " << e->id << " removed (count=" << cache->num_entries - 1
1178               << ")";
1179 
1180     entry_mru_remove(e);
1181     *lookup = e->hlink;
1182     entry_free(e);
1183     cache->num_entries -= 1;
1184 }
1185 
1186 /* Remove the oldest entry from the hash table.
1187  */
_cache_remove_oldest(Cache * cache)1188 static void _cache_remove_oldest(Cache* cache) {
1189     Entry* oldest = cache->mru_list.mru_prev;
1190     Entry** lookup = _cache_lookup_p(cache, oldest);
1191 
1192     if (*lookup == NULL) { /* should not happen */
1193         LOG(INFO) << __func__ << ": OLDEST NOT IN HTABLE ?";
1194         return;
1195     }
1196     LOG(INFO) << __func__ << ": Cache full - removing oldest";
1197     res_pquery(oldest->query, oldest->querylen);
1198     _cache_remove_p(cache, lookup);
1199 }
1200 
1201 /* Remove all expired entries from the hash table.
1202  */
_cache_remove_expired(Cache * cache)1203 static void _cache_remove_expired(Cache* cache) {
1204     Entry* e;
1205     time_t now = _time_now();
1206 
1207     for (e = cache->mru_list.mru_next; e != &cache->mru_list;) {
1208         // Entry is old, remove
1209         if (now >= e->expires) {
1210             Entry** lookup = _cache_lookup_p(cache, e);
1211             if (*lookup == NULL) { /* should not happen */
1212                 LOG(INFO) << __func__ << ": ENTRY NOT IN HTABLE ?";
1213                 return;
1214             }
1215             e = e->mru_next;
1216             _cache_remove_p(cache, lookup);
1217         } else {
1218             e = e->mru_next;
1219         }
1220     }
1221 }
1222 
1223 // Get a NetConfig associated with a network, or nullptr if not found.
1224 static NetConfig* find_netconfig_locked(unsigned netid) REQUIRES(cache_mutex);
1225 
resolv_cache_lookup(unsigned netid,const void * query,int querylen,void * answer,int answersize,int * answerlen,uint32_t flags)1226 ResolvCacheStatus resolv_cache_lookup(unsigned netid, const void* query, int querylen, void* answer,
1227                                       int answersize, int* answerlen, uint32_t flags) {
1228     // Skip cache lookup, return RESOLV_CACHE_NOTFOUND directly so that it is
1229     // possible to cache the answer of this query.
1230     // If ANDROID_RESOLV_NO_CACHE_STORE is set, return RESOLV_CACHE_SKIP to skip possible cache
1231     // storing.
1232     // (b/150371903): ANDROID_RESOLV_NO_CACHE_STORE should imply ANDROID_RESOLV_NO_CACHE_LOOKUP
1233     // to avoid side channel attack.
1234     if (flags & (ANDROID_RESOLV_NO_CACHE_LOOKUP | ANDROID_RESOLV_NO_CACHE_STORE)) {
1235         return flags & ANDROID_RESOLV_NO_CACHE_STORE ? RESOLV_CACHE_SKIP : RESOLV_CACHE_NOTFOUND;
1236     }
1237     Entry key;
1238     Entry** lookup;
1239     Entry* e;
1240     time_t now;
1241 
1242     LOG(INFO) << __func__ << ": lookup";
1243 
1244     /* we don't cache malformed queries */
1245     if (!entry_init_key(&key, query, querylen)) {
1246         LOG(INFO) << __func__ << ": unsupported query";
1247         return RESOLV_CACHE_UNSUPPORTED;
1248     }
1249     /* lookup cache */
1250     std::unique_lock lock(cache_mutex);
1251     android::base::ScopedLockAssertion assume_lock(cache_mutex);
1252     Cache* cache = find_named_cache_locked(netid);
1253     if (cache == nullptr) {
1254         return RESOLV_CACHE_UNSUPPORTED;
1255     }
1256 
1257     /* see the description of _lookup_p to understand this.
1258      * the function always return a non-NULL pointer.
1259      */
1260     lookup = _cache_lookup_p(cache, &key);
1261     e = *lookup;
1262 
1263     if (e == NULL) {
1264         LOG(INFO) << __func__ << ": NOT IN CACHE";
1265 
1266         if (!cache_has_pending_request_locked(cache, &key, true)) {
1267             return RESOLV_CACHE_NOTFOUND;
1268 
1269         } else {
1270             LOG(INFO) << __func__ << ": Waiting for previous request";
1271             // wait until (1) timeout OR
1272             //            (2) cv is notified AND no pending request matching the |key|
1273             // (cv notifier should delete pending request before sending notification.)
1274             bool ret = cv.wait_for(lock, std::chrono::seconds(PENDING_REQUEST_TIMEOUT),
1275                                    [netid, &cache, &key]() REQUIRES(cache_mutex) {
1276                                        // Must update cache as it could have been deleted
1277                                        cache = find_named_cache_locked(netid);
1278                                        return !cache_has_pending_request_locked(cache, &key, false);
1279                                    });
1280             if (!cache) {
1281                 return RESOLV_CACHE_NOTFOUND;
1282             }
1283             if (ret == false) {
1284                 NetConfig* info = find_netconfig_locked(netid);
1285                 if (info != NULL) {
1286                     info->wait_for_pending_req_timeout_count++;
1287                 }
1288             }
1289             lookup = _cache_lookup_p(cache, &key);
1290             e = *lookup;
1291             if (e == NULL) {
1292                 return RESOLV_CACHE_NOTFOUND;
1293             }
1294         }
1295     }
1296 
1297     now = _time_now();
1298 
1299     /* remove stale entries here */
1300     if (now >= e->expires) {
1301         LOG(INFO) << __func__ << ": NOT IN CACHE (STALE ENTRY " << *lookup << "DISCARDED)";
1302         res_pquery(e->query, e->querylen);
1303         _cache_remove_p(cache, lookup);
1304         return RESOLV_CACHE_NOTFOUND;
1305     }
1306 
1307     *answerlen = e->answerlen;
1308     if (e->answerlen > answersize) {
1309         /* NOTE: we return UNSUPPORTED if the answer buffer is too short */
1310         LOG(INFO) << __func__ << ": ANSWER TOO LONG";
1311         return RESOLV_CACHE_UNSUPPORTED;
1312     }
1313 
1314     memcpy(answer, e->answer, e->answerlen);
1315 
1316     /* bump up this entry to the top of the MRU list */
1317     if (e != cache->mru_list.mru_next) {
1318         entry_mru_remove(e);
1319         entry_mru_add(e, &cache->mru_list);
1320     }
1321 
1322     LOG(INFO) << __func__ << ": FOUND IN CACHE entry=" << e;
1323     return RESOLV_CACHE_FOUND;
1324 }
1325 
resolv_cache_add(unsigned netid,const void * query,int querylen,const void * answer,int answerlen)1326 int resolv_cache_add(unsigned netid, const void* query, int querylen, const void* answer,
1327                      int answerlen) {
1328     Entry key[1];
1329     Entry* e;
1330     Entry** lookup;
1331     uint32_t ttl;
1332     Cache* cache = NULL;
1333 
1334     /* don't assume that the query has already been cached
1335      */
1336     if (!entry_init_key(key, query, querylen)) {
1337         LOG(INFO) << __func__ << ": passed invalid query?";
1338         return -EINVAL;
1339     }
1340 
1341     std::lock_guard guard(cache_mutex);
1342 
1343     cache = find_named_cache_locked(netid);
1344     if (cache == nullptr) {
1345         return -ENONET;
1346     }
1347 
1348     lookup = _cache_lookup_p(cache, key);
1349     e = *lookup;
1350 
1351     // Should only happen on ANDROID_RESOLV_NO_CACHE_LOOKUP
1352     if (e != NULL) {
1353         LOG(INFO) << __func__ << ": ALREADY IN CACHE (" << e << ") ? IGNORING ADD";
1354         cache_notify_waiting_tid_locked(cache, key);
1355         return -EEXIST;
1356     }
1357 
1358     if (cache->num_entries >= CONFIG_MAX_ENTRIES) {
1359         _cache_remove_expired(cache);
1360         if (cache->num_entries >= CONFIG_MAX_ENTRIES) {
1361             _cache_remove_oldest(cache);
1362         }
1363         // TODO: It looks useless, remove below code after having test to prove it.
1364         lookup = _cache_lookup_p(cache, key);
1365         e = *lookup;
1366         if (e != NULL) {
1367             LOG(INFO) << __func__ << ": ALREADY IN CACHE (" << e << ") ? IGNORING ADD";
1368             cache_notify_waiting_tid_locked(cache, key);
1369             return -EEXIST;
1370         }
1371     }
1372 
1373     ttl = answer_getTTL(answer, answerlen);
1374     if (ttl > 0) {
1375         e = entry_alloc(key, answer, answerlen);
1376         if (e != NULL) {
1377             e->expires = ttl + _time_now();
1378             _cache_add_p(cache, lookup, e);
1379         }
1380     }
1381 
1382     cache_dump_mru_locked(cache);
1383     cache_notify_waiting_tid_locked(cache, key);
1384 
1385     return 0;
1386 }
1387 
resolv_gethostbyaddr_from_cache(unsigned netid,char domain_name[],size_t domain_name_size,const char * ip_address,int af)1388 bool resolv_gethostbyaddr_from_cache(unsigned netid, char domain_name[], size_t domain_name_size,
1389                                      const char* ip_address, int af) {
1390     if (domain_name_size > NS_MAXDNAME) {
1391         LOG(WARNING) << __func__ << ": invalid domain_name_size " << domain_name_size;
1392         return false;
1393     } else if (ip_address == nullptr || ip_address[0] == '\0') {
1394         LOG(WARNING) << __func__ << ": invalid ip_address";
1395         return false;
1396     } else if (af != AF_INET && af != AF_INET6) {
1397         LOG(WARNING) << __func__ << ": unsupported AF";
1398         return false;
1399     }
1400 
1401     Cache* cache = nullptr;
1402     Entry* node = nullptr;
1403 
1404     ns_rr rr;
1405     ns_msg handle;
1406     ns_rr rr_query;
1407 
1408     struct sockaddr_in sa;
1409     struct sockaddr_in6 sa6;
1410     char* addr_buf = nullptr;
1411 
1412     std::lock_guard guard(cache_mutex);
1413 
1414     cache = find_named_cache_locked(netid);
1415     if (cache == nullptr) {
1416         return false;
1417     }
1418 
1419     for (node = cache->mru_list.mru_next; node != nullptr && node != &cache->mru_list;
1420          node = node->mru_next) {
1421         if (node->answer == nullptr) {
1422             continue;
1423         }
1424 
1425         memset(&handle, 0, sizeof(handle));
1426 
1427         if (ns_initparse(node->answer, node->answerlen, &handle) < 0) {
1428             continue;
1429         }
1430 
1431         for (int n = 0; n < ns_msg_count(handle, ns_s_an); n++) {
1432             memset(&rr, 0, sizeof(rr));
1433 
1434             if (ns_parserr(&handle, ns_s_an, n, &rr)) {
1435                 continue;
1436             }
1437 
1438             if (ns_rr_type(rr) == ns_t_a && af == AF_INET) {
1439                 addr_buf = (char*)&(sa.sin_addr);
1440             } else if (ns_rr_type(rr) == ns_t_aaaa && af == AF_INET6) {
1441                 addr_buf = (char*)&(sa6.sin6_addr);
1442             } else {
1443                 continue;
1444             }
1445 
1446             if (inet_pton(af, ip_address, addr_buf) != 1) {
1447                 LOG(WARNING) << __func__ << ": inet_pton() fail";
1448                 return false;
1449             }
1450 
1451             if (memcmp(ns_rr_rdata(rr), addr_buf, ns_rr_rdlen(rr)) == 0) {
1452                 int query_count = ns_msg_count(handle, ns_s_qd);
1453                 for (int i = 0; i < query_count; i++) {
1454                     memset(&rr_query, 0, sizeof(rr_query));
1455                     if (ns_parserr(&handle, ns_s_qd, i, &rr_query)) {
1456                         continue;
1457                     }
1458                     strlcpy(domain_name, ns_rr_name(rr_query), domain_name_size);
1459                     if (domain_name[0] != '\0') {
1460                         return true;
1461                     }
1462                 }
1463             }
1464         }
1465     }
1466 
1467     return false;
1468 }
1469 
1470 static std::unordered_map<unsigned, std::unique_ptr<NetConfig>> sNetConfigMap
1471         GUARDED_BY(cache_mutex);
1472 
1473 // Clears nameservers set for |netconfig| and clears the stats
1474 static void free_nameservers_locked(NetConfig* netconfig);
1475 // Order-insensitive comparison for the two set of servers.
1476 static bool resolv_is_nameservers_equal(const std::vector<std::string>& oldServers,
1477                                         const std::vector<std::string>& newServers);
1478 // clears the stats samples contained withing the given netconfig.
1479 static void res_cache_clear_stats_locked(NetConfig* netconfig);
1480 
1481 // public API for netd to query if name server is set on specific netid
resolv_has_nameservers(unsigned netid)1482 bool resolv_has_nameservers(unsigned netid) {
1483     std::lock_guard guard(cache_mutex);
1484     NetConfig* info = find_netconfig_locked(netid);
1485     return (info != nullptr) && (info->nameserverCount() > 0);
1486 }
1487 
resolv_create_cache_for_net(unsigned netid)1488 int resolv_create_cache_for_net(unsigned netid) {
1489     std::lock_guard guard(cache_mutex);
1490     if (sNetConfigMap.find(netid) != sNetConfigMap.end()) {
1491         LOG(ERROR) << __func__ << ": Cache is already created, netId: " << netid;
1492         return -EEXIST;
1493     }
1494 
1495     sNetConfigMap[netid] = std::make_unique<NetConfig>(netid);
1496     return 0;
1497 }
1498 
resolv_delete_cache_for_net(unsigned netid)1499 void resolv_delete_cache_for_net(unsigned netid) {
1500     std::lock_guard guard(cache_mutex);
1501     sNetConfigMap.erase(netid);
1502 }
1503 
resolv_flush_cache_for_net(unsigned netid)1504 int resolv_flush_cache_for_net(unsigned netid) {
1505     std::lock_guard guard(cache_mutex);
1506 
1507     NetConfig* netconfig = find_netconfig_locked(netid);
1508     if (netconfig == nullptr) {
1509         return -ENONET;
1510     }
1511     netconfig->cache->flush();
1512 
1513     // Also clear the NS statistics.
1514     res_cache_clear_stats_locked(netconfig);
1515     return 0;
1516 }
1517 
resolv_list_caches()1518 std::vector<unsigned> resolv_list_caches() {
1519     std::lock_guard guard(cache_mutex);
1520     std::vector<unsigned> result;
1521     result.reserve(sNetConfigMap.size());
1522     for (const auto& [netId, _] : sNetConfigMap) {
1523         result.push_back(netId);
1524     }
1525     return result;
1526 }
1527 
find_named_cache_locked(unsigned netid)1528 static Cache* find_named_cache_locked(unsigned netid) {
1529     NetConfig* info = find_netconfig_locked(netid);
1530     if (info != nullptr) return info->cache.get();
1531     return nullptr;
1532 }
1533 
find_netconfig_locked(unsigned netid)1534 static NetConfig* find_netconfig_locked(unsigned netid) {
1535     if (auto it = sNetConfigMap.find(netid); it != sNetConfigMap.end()) {
1536         return it->second.get();
1537     }
1538     return nullptr;
1539 }
1540 
resolv_set_experiment_params(res_params * params)1541 static void resolv_set_experiment_params(res_params* params) {
1542     if (params->retry_count == 0) {
1543         params->retry_count = getExperimentFlagInt("retry_count", RES_DFLRETRY);
1544     }
1545 
1546     if (params->base_timeout_msec == 0) {
1547         params->base_timeout_msec =
1548                 getExperimentFlagInt("retransmission_time_interval", RES_TIMEOUT);
1549     }
1550 }
1551 
resolv_get_network_types_for_net(unsigned netid)1552 android::net::NetworkType resolv_get_network_types_for_net(unsigned netid) {
1553     std::lock_guard guard(cache_mutex);
1554     NetConfig* netconfig = find_netconfig_locked(netid);
1555     if (netconfig == nullptr) return android::net::NT_UNKNOWN;
1556     return convert_network_type(netconfig->transportTypes);
1557 }
1558 
1559 namespace {
1560 
1561 // Returns valid domains without duplicates which are limited to max size |MAXDNSRCH|.
filter_domains(const std::vector<std::string> & domains)1562 std::vector<std::string> filter_domains(const std::vector<std::string>& domains) {
1563     std::set<std::string> tmp_set;
1564     std::vector<std::string> res;
1565 
1566     std::copy_if(domains.begin(), domains.end(), std::back_inserter(res),
1567                  [&tmp_set](const std::string& str) {
1568                      return !(str.size() > MAXDNSRCHPATH - 1) && (tmp_set.insert(str).second);
1569                  });
1570     if (res.size() > MAXDNSRCH) {
1571         LOG(WARNING) << __func__ << ": valid domains=" << res.size()
1572                      << ", but MAXDNSRCH=" << MAXDNSRCH;
1573         res.resize(MAXDNSRCH);
1574     }
1575     return res;
1576 }
1577 
filter_nameservers(const std::vector<std::string> & servers)1578 std::vector<std::string> filter_nameservers(const std::vector<std::string>& servers) {
1579     std::vector<std::string> res = servers;
1580     if (res.size() > MAXNS) {
1581         LOG(WARNING) << __func__ << ": too many servers: " << res.size();
1582         res.resize(MAXNS);
1583     }
1584     return res;
1585 }
1586 
isValidServer(const std::string & server)1587 bool isValidServer(const std::string& server) {
1588     const addrinfo hints = {
1589             .ai_family = AF_UNSPEC,
1590             .ai_socktype = SOCK_DGRAM,
1591     };
1592     addrinfo* result = nullptr;
1593     if (int err = getaddrinfo_numeric(server.c_str(), "53", hints, &result); err != 0) {
1594         LOG(WARNING) << __func__ << ": getaddrinfo_numeric(" << server
1595                      << ") = " << gai_strerror(err);
1596         return false;
1597     }
1598     freeaddrinfo(result);
1599     return true;
1600 }
1601 
1602 }  // namespace
1603 
getCustomizedTableByName(const size_t netid,const char * hostname)1604 std::vector<std::string> getCustomizedTableByName(const size_t netid, const char* hostname) {
1605     std::lock_guard guard(cache_mutex);
1606     NetConfig* netconfig = find_netconfig_locked(netid);
1607 
1608     std::vector<std::string> result;
1609     if (netconfig != nullptr) {
1610         const auto& hosts = netconfig->customizedTable.equal_range(hostname);
1611         for (auto i = hosts.first; i != hosts.second; ++i) {
1612             result.push_back(i->second);
1613         }
1614     }
1615     return result;
1616 }
1617 
resolv_set_nameservers(unsigned netid,const std::vector<std::string> & servers,const std::vector<std::string> & domains,const res_params & params,const std::optional<ResolverOptionsParcel> optionalResolverOptions,const std::vector<int32_t> & transportTypes)1618 int resolv_set_nameservers(unsigned netid, const std::vector<std::string>& servers,
1619                            const std::vector<std::string>& domains, const res_params& params,
1620                            const std::optional<ResolverOptionsParcel> optionalResolverOptions,
1621                            const std::vector<int32_t>& transportTypes) {
1622     std::vector<std::string> nameservers = filter_nameservers(servers);
1623     const int numservers = static_cast<int>(nameservers.size());
1624 
1625     LOG(INFO) << __func__ << ": netId = " << netid << ", numservers = " << numservers;
1626 
1627     // Parse the addresses before actually locking or changing any state, in case there is an error.
1628     // As a side effect this also reduces the time the lock is kept.
1629     std::vector<IPSockAddr> ipSockAddrs;
1630     ipSockAddrs.reserve(nameservers.size());
1631     for (const auto& server : nameservers) {
1632         if (!isValidServer(server)) return -EINVAL;
1633         ipSockAddrs.push_back(IPSockAddr::toIPSockAddr(server, 53));
1634     }
1635 
1636     std::lock_guard guard(cache_mutex);
1637     NetConfig* netconfig = find_netconfig_locked(netid);
1638 
1639     if (netconfig == nullptr) return -ENONET;
1640 
1641     uint8_t old_max_samples = netconfig->params.max_samples;
1642     netconfig->params = params;
1643     resolv_set_experiment_params(&netconfig->params);
1644     if (!resolv_is_nameservers_equal(netconfig->nameservers, nameservers)) {
1645         // free current before adding new
1646         free_nameservers_locked(netconfig);
1647         netconfig->nameservers = std::move(nameservers);
1648         for (int i = 0; i < numservers; i++) {
1649             LOG(INFO) << __func__ << ": netid = " << netid
1650                       << ", addr = " << netconfig->nameservers[i];
1651         }
1652         netconfig->nameserverSockAddrs = std::move(ipSockAddrs);
1653     } else {
1654         if (netconfig->params.max_samples != old_max_samples) {
1655             // If the maximum number of samples changes, the overhead of keeping the most recent
1656             // samples around is not considered worth the effort, so they are cleared instead.
1657             // All other parameters do not affect shared state: Changing these parameters does
1658             // not invalidate the samples, as they only affect aggregation and the conditions
1659             // under which servers are considered usable.
1660             res_cache_clear_stats_locked(netconfig);
1661         }
1662     }
1663 
1664     // Always update the search paths. Cache-flushing however is not necessary,
1665     // since the stored cache entries do contain the domain, not just the host name.
1666     netconfig->search_domains = filter_domains(domains);
1667 
1668     // Setup stats for cleartext dns servers.
1669     if (!netconfig->dnsStats.setServers(netconfig->nameserverSockAddrs, PROTO_TCP) ||
1670         !netconfig->dnsStats.setServers(netconfig->nameserverSockAddrs, PROTO_UDP)) {
1671         LOG(WARNING) << __func__ << ": netid = " << netid << ", failed to set dns stats";
1672         return -EINVAL;
1673     }
1674     netconfig->transportTypes = transportTypes;
1675     if (optionalResolverOptions.has_value()) {
1676         const ResolverOptionsParcel& resolverOptions = optionalResolverOptions.value();
1677         return netconfig->setOptions(resolverOptions);
1678     }
1679     return 0;
1680 }
1681 
resolv_set_options(unsigned netid,const ResolverOptionsParcel & options)1682 int resolv_set_options(unsigned netid, const ResolverOptionsParcel& options) {
1683     std::lock_guard guard(cache_mutex);
1684     NetConfig* netconfig = find_netconfig_locked(netid);
1685 
1686     if (netconfig == nullptr) return -ENONET;
1687     return netconfig->setOptions(options);
1688 }
1689 
resolv_is_nameservers_equal(const std::vector<std::string> & oldServers,const std::vector<std::string> & newServers)1690 static bool resolv_is_nameservers_equal(const std::vector<std::string>& oldServers,
1691                                         const std::vector<std::string>& newServers) {
1692     const std::set<std::string> olds(oldServers.begin(), oldServers.end());
1693     const std::set<std::string> news(newServers.begin(), newServers.end());
1694 
1695     // TODO: this is incorrect if the list of current or previous nameservers
1696     // contains duplicates. This does not really matter because the framework
1697     // filters out duplicates, but we should probably fix it. It's also
1698     // insensitive to the order of the nameservers; we should probably fix that
1699     // too.
1700     return olds == news;
1701 }
1702 
free_nameservers_locked(NetConfig * netconfig)1703 static void free_nameservers_locked(NetConfig* netconfig) {
1704     netconfig->nameservers.clear();
1705     netconfig->nameserverSockAddrs.clear();
1706     res_cache_clear_stats_locked(netconfig);
1707 }
1708 
resolv_populate_res_for_net(ResState * statp)1709 void resolv_populate_res_for_net(ResState* statp) {
1710     if (statp == nullptr) {
1711         return;
1712     }
1713     LOG(INFO) << __func__ << ": netid=" << statp->netid;
1714 
1715     std::lock_guard guard(cache_mutex);
1716     NetConfig* info = find_netconfig_locked(statp->netid);
1717     if (info == nullptr) return;
1718 
1719     const bool sortNameservers = Experiments::getInstance()->getFlag("sort_nameservers", 0);
1720     statp->sort_nameservers = sortNameservers;
1721     statp->nsaddrs = sortNameservers ? info->dnsStats.getSortedServers(PROTO_UDP)
1722                                      : info->nameserverSockAddrs;
1723     statp->search_domains = info->search_domains;
1724     statp->tc_mode = info->tc_mode;
1725     statp->enforce_dns_uid = info->enforceDnsUid;
1726 }
1727 
1728 /* Resolver reachability statistics. */
1729 
res_cache_add_stats_sample_locked(res_stats * stats,const res_sample & sample,int max_samples)1730 static void res_cache_add_stats_sample_locked(res_stats* stats, const res_sample& sample,
1731                                               int max_samples) {
1732     // Note: This function expects max_samples > 0, otherwise a (harmless) modification of the
1733     // allocated but supposedly unused memory for samples[0] will happen
1734     LOG(INFO) << __func__ << ": adding sample to stats, next = " << unsigned(stats->sample_next)
1735               << ", count = " << unsigned(stats->sample_count);
1736     stats->samples[stats->sample_next] = sample;
1737     if (stats->sample_count < max_samples) {
1738         ++stats->sample_count;
1739     }
1740     if (++stats->sample_next >= max_samples) {
1741         stats->sample_next = 0;
1742     }
1743 }
1744 
res_cache_clear_stats_locked(NetConfig * netconfig)1745 static void res_cache_clear_stats_locked(NetConfig* netconfig) {
1746     for (int i = 0; i < MAXNS; ++i) {
1747         netconfig->nsstats[i].sample_count = 0;
1748         netconfig->nsstats[i].sample_next = 0;
1749     }
1750 
1751     // Increment the revision id to ensure that sample state is not written back if the
1752     // servers change; in theory it would suffice to do so only if the servers or
1753     // max_samples actually change, in practice the overhead of checking is higher than the
1754     // cost, and overflows are unlikely.
1755     ++netconfig->revision_id;
1756 }
1757 
android_net_res_stats_get_info_for_net(unsigned netid,int * nscount,struct sockaddr_storage servers[MAXNS],int * dcount,char domains[MAXDNSRCH][MAXDNSRCHPATH],res_params * params,struct res_stats stats[MAXNS],int * wait_for_pending_req_timeout_count)1758 int android_net_res_stats_get_info_for_net(unsigned netid, int* nscount,
1759                                            struct sockaddr_storage servers[MAXNS], int* dcount,
1760                                            char domains[MAXDNSRCH][MAXDNSRCHPATH],
1761                                            res_params* params, struct res_stats stats[MAXNS],
1762                                            int* wait_for_pending_req_timeout_count) {
1763     std::lock_guard guard(cache_mutex);
1764     NetConfig* info = find_netconfig_locked(netid);
1765     if (!info) return -1;
1766 
1767     const int num = info->nameserverCount();
1768     if (num > MAXNS) {
1769         LOG(INFO) << __func__ << ": nscount " << num << " > MAXNS " << MAXNS;
1770         errno = EFAULT;
1771         return -1;
1772     }
1773 
1774     for (int i = 0; i < num; i++) {
1775         servers[i] = info->nameserverSockAddrs[i];
1776         stats[i] = info->nsstats[i];
1777     }
1778 
1779     for (size_t i = 0; i < info->search_domains.size(); i++) {
1780         strlcpy(domains[i], info->search_domains[i].c_str(), MAXDNSRCHPATH);
1781     }
1782 
1783     *nscount = num;
1784     *dcount = static_cast<int>(info->search_domains.size());
1785     *params = info->params;
1786     *wait_for_pending_req_timeout_count = info->wait_for_pending_req_timeout_count;
1787 
1788     return info->revision_id;
1789 }
1790 
resolv_cache_dump_subsampling_map(unsigned netid)1791 std::vector<std::string> resolv_cache_dump_subsampling_map(unsigned netid) {
1792     using android::base::StringPrintf;
1793     std::lock_guard guard(cache_mutex);
1794     NetConfig* netconfig = find_netconfig_locked(netid);
1795     if (netconfig == nullptr) return {};
1796     std::vector<std::string> result;
1797     for (const auto& pair : netconfig->dns_event_subsampling_map) {
1798         result.push_back(StringPrintf("%s:%d",
1799                                       (pair.first == DNSEVENT_SUBSAMPLING_MAP_DEFAULT_KEY)
1800                                               ? "default"
1801                                               : std::to_string(pair.first).c_str(),
1802                                       pair.second));
1803     }
1804     return result;
1805 }
1806 
1807 // Decides whether an event should be sampled using a random number generator and
1808 // a sampling factor derived from the netid and the return code.
1809 //
1810 // Returns the subsampling rate if the event should be sampled, or 0 if it should be discarded.
resolv_cache_get_subsampling_denom(unsigned netid,int return_code)1811 uint32_t resolv_cache_get_subsampling_denom(unsigned netid, int return_code) {
1812     std::lock_guard guard(cache_mutex);
1813     NetConfig* netconfig = find_netconfig_locked(netid);
1814     if (netconfig == nullptr) return 0;  // Don't log anything at all.
1815     const auto& subsampling_map = netconfig->dns_event_subsampling_map;
1816     auto search_returnCode = subsampling_map.find(return_code);
1817     uint32_t denom;
1818     if (search_returnCode != subsampling_map.end()) {
1819         denom = search_returnCode->second;
1820     } else {
1821         auto search_default = subsampling_map.find(DNSEVENT_SUBSAMPLING_MAP_DEFAULT_KEY);
1822         denom = (search_default == subsampling_map.end()) ? 0 : search_default->second;
1823     }
1824     return denom;
1825 }
1826 
resolv_cache_get_resolver_stats(unsigned netid,res_params * params,res_stats stats[MAXNS],const std::vector<IPSockAddr> & serverSockAddrs)1827 int resolv_cache_get_resolver_stats(unsigned netid, res_params* params, res_stats stats[MAXNS],
1828                                     const std::vector<IPSockAddr>& serverSockAddrs) {
1829     std::lock_guard guard(cache_mutex);
1830     NetConfig* info = find_netconfig_locked(netid);
1831     if (!info) return -1;
1832 
1833     for (size_t i = 0; i < serverSockAddrs.size(); i++) {
1834         for (size_t j = 0; j < info->nameserverSockAddrs.size(); j++) {
1835             // Should never happen. Just in case because of the fix-sized array |stats|.
1836             if (j >= MAXNS) {
1837                 LOG(WARNING) << __func__ << ": unexpected size " << j;
1838                 return -1;
1839             }
1840 
1841             // It's possible that the server is not found, e.g. when a new list of nameservers
1842             // is updated to the NetConfig just after this look up thread being populated.
1843             // Keep the server valid as-is (by means of keeping stats[i] unset), but we should
1844             // think about if there's a better way.
1845             if (info->nameserverSockAddrs[j] == serverSockAddrs[i]) {
1846                 stats[i] = info->nsstats[j];
1847                 break;
1848             }
1849         }
1850     }
1851 
1852     *params = info->params;
1853     return info->revision_id;
1854 }
1855 
resolv_cache_add_resolver_stats_sample(unsigned netid,int revision_id,const IPSockAddr & serverSockAddr,const res_sample & sample,int max_samples)1856 void resolv_cache_add_resolver_stats_sample(unsigned netid, int revision_id,
1857                                             const IPSockAddr& serverSockAddr,
1858                                             const res_sample& sample, int max_samples) {
1859     if (max_samples <= 0) return;
1860 
1861     std::lock_guard guard(cache_mutex);
1862     NetConfig* info = find_netconfig_locked(netid);
1863 
1864     if (info && info->revision_id == revision_id) {
1865         const int serverNum = std::min(MAXNS, static_cast<int>(info->nameserverSockAddrs.size()));
1866         for (int ns = 0; ns < serverNum; ns++) {
1867             if (serverSockAddr == info->nameserverSockAddrs[ns]) {
1868                 res_cache_add_stats_sample_locked(&info->nsstats[ns], sample, max_samples);
1869                 return;
1870             }
1871         }
1872     }
1873 }
1874 
has_named_cache(unsigned netid)1875 bool has_named_cache(unsigned netid) {
1876     std::lock_guard guard(cache_mutex);
1877     return find_named_cache_locked(netid) != nullptr;
1878 }
1879 
resolv_cache_get_expiration(unsigned netid,const std::vector<char> & query,time_t * expiration)1880 int resolv_cache_get_expiration(unsigned netid, const std::vector<char>& query,
1881                                 time_t* expiration) {
1882     Entry key;
1883     *expiration = -1;
1884 
1885     // A malformed query is not allowed.
1886     if (!entry_init_key(&key, query.data(), query.size())) {
1887         LOG(WARNING) << __func__ << ": unsupported query";
1888         return -EINVAL;
1889     }
1890 
1891     // lookup cache.
1892     Cache* cache;
1893     std::lock_guard guard(cache_mutex);
1894     if (cache = find_named_cache_locked(netid); cache == nullptr) {
1895         LOG(WARNING) << __func__ << ": cache not created in the network " << netid;
1896         return -ENONET;
1897     }
1898     Entry** lookup = _cache_lookup_p(cache, &key);
1899     Entry* e = *lookup;
1900     if (e == NULL) {
1901         LOG(WARNING) << __func__ << ": not in cache";
1902         return -ENODATA;
1903     }
1904 
1905     if (_time_now() >= e->expires) {
1906         LOG(WARNING) << __func__ << ": entry expired";
1907         return -ENODATA;
1908     }
1909 
1910     *expiration = e->expires;
1911     return 0;
1912 }
1913 
resolv_stats_set_servers_for_dot(unsigned netid,const std::vector<std::string> & servers)1914 int resolv_stats_set_servers_for_dot(unsigned netid, const std::vector<std::string>& servers) {
1915     std::lock_guard guard(cache_mutex);
1916     const auto info = find_netconfig_locked(netid);
1917 
1918     if (info == nullptr) return -ENONET;
1919 
1920     std::vector<IPSockAddr> serverSockAddrs;
1921     serverSockAddrs.reserve(servers.size());
1922     for (const auto& server : servers) {
1923         serverSockAddrs.push_back(IPSockAddr::toIPSockAddr(server, 853));
1924     }
1925 
1926     if (!info->dnsStats.setServers(serverSockAddrs, android::net::PROTO_DOT)) {
1927         LOG(WARNING) << __func__ << ": netid = " << netid << ", failed to set dns stats";
1928         return -EINVAL;
1929     }
1930 
1931     return 0;
1932 }
1933 
resolv_stats_add(unsigned netid,const android::netdutils::IPSockAddr & server,const DnsQueryEvent * record)1934 bool resolv_stats_add(unsigned netid, const android::netdutils::IPSockAddr& server,
1935                       const DnsQueryEvent* record) {
1936     if (record == nullptr) return false;
1937 
1938     std::lock_guard guard(cache_mutex);
1939     if (const auto info = find_netconfig_locked(netid); info != nullptr) {
1940         return info->dnsStats.addStats(server, *record);
1941     }
1942     return false;
1943 }
1944 
tc_mode_to_str(const int mode)1945 static const char* tc_mode_to_str(const int mode) {
1946     switch (mode) {
1947         case aidl::android::net::IDnsResolver::TC_MODE_DEFAULT:
1948             return "default";
1949         case aidl::android::net::IDnsResolver::TC_MODE_UDP_TCP:
1950             return "UDP_TCP";
1951         default:
1952             return "unknown";
1953     }
1954 }
1955 
to_stats_network_type(int32_t mainType,bool withVpn)1956 static android::net::NetworkType to_stats_network_type(int32_t mainType, bool withVpn) {
1957     switch (mainType) {
1958         case IDnsResolver::TRANSPORT_CELLULAR:
1959             return withVpn ? android::net::NT_CELLULAR_VPN : android::net::NT_CELLULAR;
1960         case IDnsResolver::TRANSPORT_WIFI:
1961             return withVpn ? android::net::NT_WIFI_VPN : android::net::NT_WIFI;
1962         case IDnsResolver::TRANSPORT_BLUETOOTH:
1963             return withVpn ? android::net::NT_BLUETOOTH_VPN : android::net::NT_BLUETOOTH;
1964         case IDnsResolver::TRANSPORT_ETHERNET:
1965             return withVpn ? android::net::NT_ETHERNET_VPN : android::net::NT_ETHERNET;
1966         case IDnsResolver::TRANSPORT_VPN:
1967             return withVpn ? android::net::NT_UNKNOWN : android::net::NT_VPN;
1968         case IDnsResolver::TRANSPORT_WIFI_AWARE:
1969             return withVpn ? android::net::NT_UNKNOWN : android::net::NT_WIFI_AWARE;
1970         case IDnsResolver::TRANSPORT_LOWPAN:
1971             return withVpn ? android::net::NT_UNKNOWN : android::net::NT_LOWPAN;
1972         default:
1973             return android::net::NT_UNKNOWN;
1974     }
1975 }
1976 
convert_network_type(const std::vector<int32_t> & transportTypes)1977 android::net::NetworkType convert_network_type(const std::vector<int32_t>& transportTypes) {
1978     // The valid transportTypes size is 1 to 3.
1979     if (transportTypes.size() > 3 || transportTypes.size() == 0) return android::net::NT_UNKNOWN;
1980     // TransportTypes size == 1, map the type to stats network type directly.
1981     if (transportTypes.size() == 1) return to_stats_network_type(transportTypes[0], false);
1982     // TransportTypes size == 3, only cellular + wifi + vpn is valid.
1983     if (transportTypes.size() == 3) {
1984         std::vector<int32_t> sortedTransTypes = transportTypes;
1985         std::sort(sortedTransTypes.begin(), sortedTransTypes.end());
1986         if (sortedTransTypes != std::vector<int32_t>{IDnsResolver::TRANSPORT_CELLULAR,
1987                                                      IDnsResolver::TRANSPORT_WIFI,
1988                                                      IDnsResolver::TRANSPORT_VPN}) {
1989             return android::net::NT_UNKNOWN;
1990         }
1991         return android::net::NT_WIFI_CELLULAR_VPN;
1992     }
1993     // TransportTypes size == 2, it shoud be 1 main type + vpn type.
1994     // Otherwise, consider it as UNKNOWN.
1995     bool hasVpn = false;
1996     int32_t mainType = IDnsResolver::TRANSPORT_UNKNOWN;
1997     for (const auto& transportType : transportTypes) {
1998         if (transportType == IDnsResolver::TRANSPORT_VPN) {
1999             hasVpn = true;
2000             continue;
2001         }
2002         mainType = transportType;
2003     }
2004     return hasVpn ? to_stats_network_type(mainType, true) : android::net::NT_UNKNOWN;
2005 }
2006 
transport_type_to_str(const std::vector<int32_t> & transportTypes)2007 static const char* transport_type_to_str(const std::vector<int32_t>& transportTypes) {
2008     switch (convert_network_type(transportTypes)) {
2009         case android::net::NT_CELLULAR:
2010             return "CELLULAR";
2011         case android::net::NT_WIFI:
2012             return "WIFI";
2013         case android::net::NT_BLUETOOTH:
2014             return "BLUETOOTH";
2015         case android::net::NT_ETHERNET:
2016             return "ETHERNET";
2017         case android::net::NT_VPN:
2018             return "VPN";
2019         case android::net::NT_WIFI_AWARE:
2020             return "WIFI_AWARE";
2021         case android::net::NT_LOWPAN:
2022             return "LOWPAN";
2023         case android::net::NT_CELLULAR_VPN:
2024             return "CELLULAR_VPN";
2025         case android::net::NT_WIFI_VPN:
2026             return "WIFI_VPN";
2027         case android::net::NT_BLUETOOTH_VPN:
2028             return "BLUETOOTH_VPN";
2029         case android::net::NT_ETHERNET_VPN:
2030             return "ETHERNET_VPN";
2031         case android::net::NT_WIFI_CELLULAR_VPN:
2032             return "WIFI_CELLULAR_VPN";
2033         default:
2034             return "UNKNOWN";
2035     }
2036 }
2037 
resolv_netconfig_dump(DumpWriter & dw,unsigned netid)2038 void resolv_netconfig_dump(DumpWriter& dw, unsigned netid) {
2039     std::lock_guard guard(cache_mutex);
2040     if (const auto info = find_netconfig_locked(netid); info != nullptr) {
2041         info->dnsStats.dump(dw);
2042         // TODO: dump info->hosts
2043         dw.println("TC mode: %s", tc_mode_to_str(info->tc_mode));
2044         dw.println("TransportType: %s", transport_type_to_str(info->transportTypes));
2045     }
2046 }
2047