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