blob: d6f0cd80c4a0afe42e6fdd666416b33d65541daf [file] [log] [blame]
Bernie Innocenti55864192018-08-30 04:05:20 +09001/*
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
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090029#define LOG_TAG "res_cache"
30
Bernie Innocenti34de3ba2019-02-19 18:08:36 +090031#include "resolv_cache.h"
32
Bernie Innocenti55864192018-08-30 04:05:20 +090033#include <resolv.h>
34#include <stdarg.h>
35#include <stdio.h>
36#include <stdlib.h>
37#include <string.h>
38#include <time.h>
Luke Huang57b128d2019-07-23 16:04:12 -070039
Ken Chen2a429352018-12-22 21:46:55 +080040#include <mutex>
Luke Huang57b128d2019-07-23 16:04:12 -070041#include <string>
42#include <unordered_map>
43#include <vector>
Bernie Innocenti55864192018-08-30 04:05:20 +090044
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090045#include <arpa/inet.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090046#include <arpa/nameser.h>
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090047#include <errno.h>
48#include <linux/if.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090049#include <net/if.h>
50#include <netdb.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090051
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090052#include <android-base/logging.h>
waynema2371eab2019-01-18 14:02:31 +080053#include <android-base/parseint.h>
Luke Huang57b128d2019-07-23 16:04:12 -070054#include <android-base/stringprintf.h>
55#include <android-base/strings.h>
Ken Chen2a429352018-12-22 21:46:55 +080056#include <android-base/thread_annotations.h>
Bernie Innocenti34de3ba2019-02-19 18:08:36 +090057#include <android/multinetwork.h> // ResNsendFlags
Bernie Innocentif89b3512018-08-30 07:34:37 +090058
waynema2371eab2019-01-18 14:02:31 +080059#include <server_configurable_flags/get_flags.h>
60
Bernie Innocenti189eb502018-10-01 23:10:18 +090061#include "res_state_ext.h"
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090062#include "resolv_private.h"
Bernie Innocenti55864192018-08-30 04:05:20 +090063
Bernie Innocentid017e972019-03-03 19:39:53 +090064// NOTE: verbose logging MUST NOT be left enabled in production binaries.
65// It floods logs at high rate, and can leak privacy-sensitive information.
66constexpr bool kDumpData = false;
67
Bernie Innocenti55864192018-08-30 04:05:20 +090068/* This code implements a small and *simple* DNS resolver cache.
69 *
70 * It is only used to cache DNS answers for a time defined by the smallest TTL
71 * among the answer records in order to reduce DNS traffic. It is not supposed
72 * to be a full DNS cache, since we plan to implement that in the future in a
73 * dedicated process running on the system.
74 *
75 * Note that its design is kept simple very intentionally, i.e.:
76 *
77 * - it takes raw DNS query packet data as input, and returns raw DNS
78 * answer packet data as output
79 *
80 * (this means that two similar queries that encode the DNS name
81 * differently will be treated distinctly).
82 *
83 * the smallest TTL value among the answer records are used as the time
84 * to keep an answer in the cache.
85 *
86 * this is bad, but we absolutely want to avoid parsing the answer packets
87 * (and should be solved by the later full DNS cache process).
88 *
89 * - the implementation is just a (query-data) => (answer-data) hash table
90 * with a trivial least-recently-used expiration policy.
91 *
92 * Doing this keeps the code simple and avoids to deal with a lot of things
93 * that a full DNS cache is expected to do.
94 *
95 * The API is also very simple:
96 *
97 * - the client calls _resolv_cache_get() to obtain a handle to the cache.
98 * this will initialize the cache on first usage. the result can be NULL
99 * if the cache is disabled.
100 *
101 * - the client calls _resolv_cache_lookup() before performing a query
102 *
103 * if the function returns RESOLV_CACHE_FOUND, a copy of the answer data
104 * has been copied into the client-provided answer buffer.
105 *
106 * if the function returns RESOLV_CACHE_NOTFOUND, the client should perform
107 * a request normally, *then* call _resolv_cache_add() to add the received
108 * answer to the cache.
109 *
110 * if the function returns RESOLV_CACHE_UNSUPPORTED, the client should
111 * perform a request normally, and *not* call _resolv_cache_add()
112 *
113 * note that RESOLV_CACHE_UNSUPPORTED is also returned if the answer buffer
114 * is too short to accomodate the cached result.
115 */
116
117/* default number of entries kept in the cache. This value has been
118 * determined by browsing through various sites and counting the number
119 * of corresponding requests. Keep in mind that our framework is currently
120 * performing two requests per name lookup (one for IPv4, the other for IPv6)
121 *
122 * www.google.com 4
123 * www.ysearch.com 6
124 * www.amazon.com 8
125 * www.nytimes.com 22
126 * www.espn.com 28
127 * www.msn.com 28
128 * www.lemonde.fr 35
129 *
130 * (determined in 2009-2-17 from Paris, France, results may vary depending
131 * on location)
132 *
133 * most high-level websites use lots of media/ad servers with different names
134 * but these are generally reused when browsing through the site.
135 *
136 * As such, a value of 64 should be relatively comfortable at the moment.
137 *
138 * ******************************************
139 * * NOTE - this has changed.
140 * * 1) we've added IPv6 support so each dns query results in 2 responses
141 * * 2) we've made this a system-wide cache, so the cost is less (it's not
142 * * duplicated in each process) and the need is greater (more processes
143 * * making different requests).
144 * * Upping by 2x for IPv6
145 * * Upping by another 5x for the centralized nature
146 * *****************************************
147 */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900148#define CONFIG_MAX_ENTRIES (64 * 2 * 5)
Bernie Innocenti55864192018-08-30 04:05:20 +0900149
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900150/** BOUNDED BUFFER FORMATTING **/
Bernie Innocenti55864192018-08-30 04:05:20 +0900151
152/* technical note:
153 *
154 * the following debugging routines are used to append data to a bounded
155 * buffer they take two parameters that are:
156 *
157 * - p : a pointer to the current cursor position in the buffer
158 * this value is initially set to the buffer's address.
159 *
160 * - end : the address of the buffer's limit, i.e. of the first byte
161 * after the buffer. this address should never be touched.
162 *
163 * IMPORTANT: it is assumed that end > buffer_address, i.e.
164 * that the buffer is at least one byte.
165 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900166 * the bprint_x() functions return the new value of 'p' after the data
Bernie Innocenti55864192018-08-30 04:05:20 +0900167 * has been appended, and also ensure the following:
168 *
169 * - the returned value will never be strictly greater than 'end'
170 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900171 * - a return value equal to 'end' means that truncation occurred
Bernie Innocenti55864192018-08-30 04:05:20 +0900172 * (in which case, end[-1] will be set to 0)
173 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900174 * - after returning from a bprint_x() function, the content of the buffer
Bernie Innocenti55864192018-08-30 04:05:20 +0900175 * is always 0-terminated, even in the event of truncation.
176 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900177 * these conventions allow you to call bprint_x() functions multiple times and
Bernie Innocenti55864192018-08-30 04:05:20 +0900178 * only check for truncation at the end of the sequence, as in:
179 *
180 * char buff[1000], *p = buff, *end = p + sizeof(buff);
181 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900182 * p = bprint_c(p, end, '"');
183 * p = bprint_s(p, end, my_string);
184 * p = bprint_c(p, end, '"');
Bernie Innocenti55864192018-08-30 04:05:20 +0900185 *
186 * if (p >= end) {
187 * // buffer was too small
188 * }
189 *
190 * printf( "%s", buff );
191 */
192
Bernie Innocenti34de3ba2019-02-19 18:08:36 +0900193/* Defaults used for initializing res_params */
Bernie Innocenti1fbca5c2018-10-01 20:46:20 +0900194
195// If successes * 100 / total_samples is less than this value, the server is considered failing
196#define SUCCESS_THRESHOLD 75
197// Sample validity in seconds. Set to -1 to disable skipping failing servers.
198#define NSSAMPLE_VALIDITY 1800
199
Bernie Innocenti55864192018-08-30 04:05:20 +0900200/* add a char to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900201static char* bprint_c(char* p, char* end, int c) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900202 if (p < end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900203 if (p + 1 == end)
Bernie Innocenti55864192018-08-30 04:05:20 +0900204 *p++ = 0;
205 else {
206 *p++ = (char) c;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900207 *p = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900208 }
209 }
210 return p;
211}
212
213/* add a sequence of bytes to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900214static char* bprint_b(char* p, char* end, const char* buf, int len) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900215 int avail = end - p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900216
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900217 if (avail <= 0 || len <= 0) return p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900218
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900219 if (avail > len) avail = len;
Bernie Innocenti55864192018-08-30 04:05:20 +0900220
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900221 memcpy(p, buf, avail);
Bernie Innocenti55864192018-08-30 04:05:20 +0900222 p += avail;
223
224 if (p < end)
225 p[0] = 0;
226 else
227 end[-1] = 0;
228
229 return p;
230}
231
232/* add a string to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900233static char* bprint_s(char* p, char* end, const char* str) {
234 return bprint_b(p, end, str, strlen(str));
Bernie Innocenti55864192018-08-30 04:05:20 +0900235}
236
237/* add a formatted string to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900238static char* bprint(char* p, char* end, const char* format, ...) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900239 int avail, n;
240 va_list args;
Bernie Innocenti55864192018-08-30 04:05:20 +0900241
242 avail = end - p;
243
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900244 if (avail <= 0) return p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900245
246 va_start(args, format);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900247 n = vsnprintf(p, avail, format, args);
Bernie Innocenti55864192018-08-30 04:05:20 +0900248 va_end(args);
249
250 /* certain C libraries return -1 in case of truncation */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900251 if (n < 0 || n > avail) n = avail;
Bernie Innocenti55864192018-08-30 04:05:20 +0900252
253 p += n;
254 /* certain C libraries do not zero-terminate in case of truncation */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900255 if (p == end) p[-1] = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900256
257 return p;
258}
259
260/* add a hex value to a bounded buffer, up to 8 digits */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900261static char* bprint_hex(char* p, char* end, unsigned value, int numDigits) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900262 char text[sizeof(unsigned) * 2];
263 int nn = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900264
265 while (numDigits-- > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900266 text[nn++] = "0123456789abcdef"[(value >> (numDigits * 4)) & 15];
Bernie Innocenti55864192018-08-30 04:05:20 +0900267 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900268 return bprint_b(p, end, text, nn);
Bernie Innocenti55864192018-08-30 04:05:20 +0900269}
270
271/* add the hexadecimal dump of some memory area to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900272static char* bprint_hexdump(char* p, char* end, const uint8_t* data, int datalen) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900273 int lineSize = 16;
Bernie Innocenti55864192018-08-30 04:05:20 +0900274
275 while (datalen > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900276 int avail = datalen;
277 int nn;
Bernie Innocenti55864192018-08-30 04:05:20 +0900278
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900279 if (avail > lineSize) avail = lineSize;
Bernie Innocenti55864192018-08-30 04:05:20 +0900280
281 for (nn = 0; nn < avail; nn++) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900282 if (nn > 0) p = bprint_c(p, end, ' ');
283 p = bprint_hex(p, end, data[nn], 2);
Bernie Innocenti55864192018-08-30 04:05:20 +0900284 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900285 for (; nn < lineSize; nn++) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900286 p = bprint_s(p, end, " ");
Bernie Innocenti55864192018-08-30 04:05:20 +0900287 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900288 p = bprint_s(p, end, " ");
Bernie Innocenti55864192018-08-30 04:05:20 +0900289
290 for (nn = 0; nn < avail; nn++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900291 int c = data[nn];
Bernie Innocenti55864192018-08-30 04:05:20 +0900292
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900293 if (c < 32 || c > 127) c = '.';
Bernie Innocenti55864192018-08-30 04:05:20 +0900294
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900295 p = bprint_c(p, end, c);
Bernie Innocenti55864192018-08-30 04:05:20 +0900296 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900297 p = bprint_c(p, end, '\n');
Bernie Innocenti55864192018-08-30 04:05:20 +0900298
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900299 data += avail;
Bernie Innocenti55864192018-08-30 04:05:20 +0900300 datalen -= avail;
301 }
302 return p;
303}
304
305/* dump the content of a query of packet to the log */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900306static void dump_bytes(const uint8_t* base, int len) {
307 if (!kDumpData) return;
Bernie Innocenti55864192018-08-30 04:05:20 +0900308
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900309 char buff[1024];
310 char *p = buff, *end = p + sizeof(buff);
311
312 p = bprint_hexdump(p, end, base, len);
Ken Chenbab50142019-03-19 17:41:28 +0800313 LOG(INFO) << __func__ << ": " << buff;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900314}
Bernie Innocenti55864192018-08-30 04:05:20 +0900315
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900316static time_t _time_now(void) {
317 struct timeval tv;
Bernie Innocenti55864192018-08-30 04:05:20 +0900318
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900319 gettimeofday(&tv, NULL);
Bernie Innocenti55864192018-08-30 04:05:20 +0900320 return tv.tv_sec;
321}
322
323/* reminder: the general format of a DNS packet is the following:
324 *
325 * HEADER (12 bytes)
326 * QUESTION (variable)
327 * ANSWER (variable)
328 * AUTHORITY (variable)
329 * ADDITIONNAL (variable)
330 *
331 * the HEADER is made of:
332 *
333 * ID : 16 : 16-bit unique query identification field
334 *
335 * QR : 1 : set to 0 for queries, and 1 for responses
336 * Opcode : 4 : set to 0 for queries
337 * AA : 1 : set to 0 for queries
338 * TC : 1 : truncation flag, will be set to 0 in queries
339 * RD : 1 : recursion desired
340 *
341 * RA : 1 : recursion available (0 in queries)
342 * Z : 3 : three reserved zero bits
343 * RCODE : 4 : response code (always 0=NOERROR in queries)
344 *
345 * QDCount: 16 : question count
346 * ANCount: 16 : Answer count (0 in queries)
347 * NSCount: 16: Authority Record count (0 in queries)
348 * ARCount: 16: Additionnal Record count (0 in queries)
349 *
350 * the QUESTION is made of QDCount Question Record (QRs)
351 * the ANSWER is made of ANCount RRs
352 * the AUTHORITY is made of NSCount RRs
353 * the ADDITIONNAL is made of ARCount RRs
354 *
355 * Each Question Record (QR) is made of:
356 *
357 * QNAME : variable : Query DNS NAME
358 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
359 * CLASS : 16 : class of query (IN=1)
360 *
361 * Each Resource Record (RR) is made of:
362 *
363 * NAME : variable : DNS NAME
364 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
365 * CLASS : 16 : class of query (IN=1)
366 * TTL : 32 : seconds to cache this RR (0=none)
367 * RDLENGTH: 16 : size of RDDATA in bytes
368 * RDDATA : variable : RR data (depends on TYPE)
369 *
370 * Each QNAME contains a domain name encoded as a sequence of 'labels'
371 * terminated by a zero. Each label has the following format:
372 *
373 * LEN : 8 : lenght of label (MUST be < 64)
374 * NAME : 8*LEN : label length (must exclude dots)
375 *
376 * A value of 0 in the encoding is interpreted as the 'root' domain and
377 * terminates the encoding. So 'www.android.com' will be encoded as:
378 *
379 * <3>www<7>android<3>com<0>
380 *
381 * Where <n> represents the byte with value 'n'
382 *
383 * Each NAME reflects the QNAME of the question, but has a slightly more
384 * complex encoding in order to provide message compression. This is achieved
385 * by using a 2-byte pointer, with format:
386 *
387 * TYPE : 2 : 0b11 to indicate a pointer, 0b01 and 0b10 are reserved
388 * OFFSET : 14 : offset to another part of the DNS packet
389 *
390 * The offset is relative to the start of the DNS packet and must point
391 * A pointer terminates the encoding.
392 *
393 * The NAME can be encoded in one of the following formats:
394 *
395 * - a sequence of simple labels terminated by 0 (like QNAMEs)
396 * - a single pointer
397 * - a sequence of simple labels terminated by a pointer
398 *
399 * A pointer shall always point to either a pointer of a sequence of
400 * labels (which can themselves be terminated by either a 0 or a pointer)
401 *
402 * The expanded length of a given domain name should not exceed 255 bytes.
403 *
404 * NOTE: we don't parse the answer packets, so don't need to deal with NAME
405 * records, only QNAMEs.
406 */
407
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900408#define DNS_HEADER_SIZE 12
Bernie Innocenti55864192018-08-30 04:05:20 +0900409
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900410#define DNS_TYPE_A "\00\01" /* big-endian decimal 1 */
411#define DNS_TYPE_PTR "\00\014" /* big-endian decimal 12 */
412#define DNS_TYPE_MX "\00\017" /* big-endian decimal 15 */
413#define DNS_TYPE_AAAA "\00\034" /* big-endian decimal 28 */
414#define DNS_TYPE_ALL "\00\0377" /* big-endian decimal 255 */
Bernie Innocenti55864192018-08-30 04:05:20 +0900415
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900416#define DNS_CLASS_IN "\00\01" /* big-endian decimal 1 */
Bernie Innocenti55864192018-08-30 04:05:20 +0900417
418typedef struct {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900419 const uint8_t* base;
420 const uint8_t* end;
421 const uint8_t* cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900422} DnsPacket;
423
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900424static void _dnsPacket_init(DnsPacket* packet, const uint8_t* buff, int bufflen) {
425 packet->base = buff;
426 packet->end = buff + bufflen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900427 packet->cursor = buff;
428}
429
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900430static void _dnsPacket_rewind(DnsPacket* packet) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900431 packet->cursor = packet->base;
432}
433
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900434static void _dnsPacket_skip(DnsPacket* packet, int count) {
435 const uint8_t* p = packet->cursor + count;
Bernie Innocenti55864192018-08-30 04:05:20 +0900436
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900437 if (p > packet->end) p = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900438
439 packet->cursor = p;
440}
441
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900442static int _dnsPacket_readInt16(DnsPacket* packet) {
443 const uint8_t* p = packet->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900444
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900445 if (p + 2 > packet->end) return -1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900446
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900447 packet->cursor = p + 2;
448 return (p[0] << 8) | p[1];
Bernie Innocenti55864192018-08-30 04:05:20 +0900449}
450
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900451/** QUERY CHECKING **/
Bernie Innocenti55864192018-08-30 04:05:20 +0900452
453/* check bytes in a dns packet. returns 1 on success, 0 on failure.
454 * the cursor is only advanced in the case of success
455 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900456static int _dnsPacket_checkBytes(DnsPacket* packet, int numBytes, const void* bytes) {
457 const uint8_t* p = packet->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900458
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900459 if (p + numBytes > packet->end) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900460
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900461 if (memcmp(p, bytes, numBytes) != 0) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900462
463 packet->cursor = p + numBytes;
464 return 1;
465}
466
467/* parse and skip a given QNAME stored in a query packet,
468 * from the current cursor position. returns 1 on success,
469 * or 0 for malformed data.
470 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900471static int _dnsPacket_checkQName(DnsPacket* packet) {
472 const uint8_t* p = packet->cursor;
473 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900474
475 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900476 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900477
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900478 if (p >= end) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900479
480 c = *p++;
481
482 if (c == 0) {
483 packet->cursor = p;
484 return 1;
485 }
486
487 /* we don't expect label compression in QNAMEs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900488 if (c >= 64) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900489
490 p += c;
491 /* we rely on the bound check at the start
492 * of the loop here */
493 }
494 /* malformed data */
Ken Chenbab50142019-03-19 17:41:28 +0800495 LOG(INFO) << __func__ << ": malformed QNAME";
Bernie Innocenti55864192018-08-30 04:05:20 +0900496 return 0;
497}
498
499/* parse and skip a given QR stored in a packet.
500 * returns 1 on success, and 0 on failure
501 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900502static int _dnsPacket_checkQR(DnsPacket* packet) {
503 if (!_dnsPacket_checkQName(packet)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900504
505 /* TYPE must be one of the things we support */
506 if (!_dnsPacket_checkBytes(packet, 2, DNS_TYPE_A) &&
507 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_PTR) &&
508 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_MX) &&
509 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_AAAA) &&
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900510 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_ALL)) {
Ken Chenbab50142019-03-19 17:41:28 +0800511 LOG(INFO) << __func__ << ": unsupported TYPE";
Bernie Innocenti55864192018-08-30 04:05:20 +0900512 return 0;
513 }
514 /* CLASS must be IN */
515 if (!_dnsPacket_checkBytes(packet, 2, DNS_CLASS_IN)) {
Ken Chenbab50142019-03-19 17:41:28 +0800516 LOG(INFO) << __func__ << ": unsupported CLASS";
Bernie Innocenti55864192018-08-30 04:05:20 +0900517 return 0;
518 }
519
520 return 1;
521}
522
523/* check the header of a DNS Query packet, return 1 if it is one
524 * type of query we can cache, or 0 otherwise
525 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900526static int _dnsPacket_checkQuery(DnsPacket* packet) {
527 const uint8_t* p = packet->base;
528 int qdCount, anCount, dnCount, arCount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900529
530 if (p + DNS_HEADER_SIZE > packet->end) {
Ken Chenbab50142019-03-19 17:41:28 +0800531 LOG(INFO) << __func__ << ": query packet too small";
Bernie Innocenti55864192018-08-30 04:05:20 +0900532 return 0;
533 }
534
535 /* QR must be set to 0, opcode must be 0 and AA must be 0 */
536 /* RA, Z, and RCODE must be 0 */
537 if ((p[2] & 0xFC) != 0 || (p[3] & 0xCF) != 0) {
Ken Chenbab50142019-03-19 17:41:28 +0800538 LOG(INFO) << __func__ << ": query packet flags unsupported";
Bernie Innocenti55864192018-08-30 04:05:20 +0900539 return 0;
540 }
541
542 /* Note that we ignore the TC, RD, CD, and AD bits here for the
543 * following reasons:
544 *
545 * - there is no point for a query packet sent to a server
546 * to have the TC bit set, but the implementation might
547 * set the bit in the query buffer for its own needs
548 * between a _resolv_cache_lookup and a
549 * _resolv_cache_add. We should not freak out if this
550 * is the case.
551 *
552 * - we consider that the result from a query might depend on
553 * the RD, AD, and CD bits, so these bits
554 * should be used to differentiate cached result.
555 *
556 * this implies that these bits are checked when hashing or
557 * comparing query packets, but not TC
558 */
559
560 /* ANCOUNT, DNCOUNT and ARCOUNT must be 0 */
561 qdCount = (p[4] << 8) | p[5];
562 anCount = (p[6] << 8) | p[7];
563 dnCount = (p[8] << 8) | p[9];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900564 arCount = (p[10] << 8) | p[11];
Bernie Innocenti55864192018-08-30 04:05:20 +0900565
566 if (anCount != 0 || dnCount != 0 || arCount > 1) {
Ken Chenbab50142019-03-19 17:41:28 +0800567 LOG(INFO) << __func__ << ": query packet contains non-query records";
Bernie Innocenti55864192018-08-30 04:05:20 +0900568 return 0;
569 }
570
571 if (qdCount == 0) {
Ken Chenbab50142019-03-19 17:41:28 +0800572 LOG(INFO) << __func__ << ": query packet doesn't contain query record";
Bernie Innocenti55864192018-08-30 04:05:20 +0900573 return 0;
574 }
575
576 /* Check QDCOUNT QRs */
577 packet->cursor = p + DNS_HEADER_SIZE;
578
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900579 for (; qdCount > 0; qdCount--)
580 if (!_dnsPacket_checkQR(packet)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900581
582 return 1;
583}
584
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900585/** QUERY DEBUGGING **/
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900586static char* dnsPacket_bprintQName(DnsPacket* packet, char* bp, char* bend) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900587 const uint8_t* p = packet->cursor;
588 const uint8_t* end = packet->end;
589 int first = 1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900590
591 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900592 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900593
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900594 if (p >= end) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900595
596 c = *p++;
597
598 if (c == 0) {
599 packet->cursor = p;
600 return bp;
601 }
602
603 /* we don't expect label compression in QNAMEs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900604 if (c >= 64) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900605
606 if (first)
607 first = 0;
608 else
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900609 bp = bprint_c(bp, bend, '.');
Bernie Innocenti55864192018-08-30 04:05:20 +0900610
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900611 bp = bprint_b(bp, bend, (const char*) p, c);
Bernie Innocenti55864192018-08-30 04:05:20 +0900612
613 p += c;
614 /* we rely on the bound check at the start
615 * of the loop here */
616 }
617 /* malformed data */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900618 bp = bprint_s(bp, bend, "<MALFORMED>");
Bernie Innocenti55864192018-08-30 04:05:20 +0900619 return bp;
620}
621
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900622static char* dnsPacket_bprintQR(DnsPacket* packet, char* p, char* end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900623#define QQ(x) \
624 { DNS_TYPE_##x, #x }
Bernie Innocenti55864192018-08-30 04:05:20 +0900625 static const struct {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900626 const char* typeBytes;
627 const char* typeString;
628 } qTypes[] = {QQ(A), QQ(PTR), QQ(MX), QQ(AAAA), QQ(ALL), {NULL, NULL}};
629 int nn;
630 const char* typeString = NULL;
Bernie Innocenti55864192018-08-30 04:05:20 +0900631
632 /* dump QNAME */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900633 p = dnsPacket_bprintQName(packet, p, end);
Bernie Innocenti55864192018-08-30 04:05:20 +0900634
635 /* dump TYPE */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900636 p = bprint_s(p, end, " (");
Bernie Innocenti55864192018-08-30 04:05:20 +0900637
638 for (nn = 0; qTypes[nn].typeBytes != NULL; nn++) {
639 if (_dnsPacket_checkBytes(packet, 2, qTypes[nn].typeBytes)) {
640 typeString = qTypes[nn].typeString;
641 break;
642 }
643 }
644
645 if (typeString != NULL)
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900646 p = bprint_s(p, end, typeString);
Bernie Innocenti55864192018-08-30 04:05:20 +0900647 else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900648 int typeCode = _dnsPacket_readInt16(packet);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900649 p = bprint(p, end, "UNKNOWN-%d", typeCode);
Bernie Innocenti55864192018-08-30 04:05:20 +0900650 }
651
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900652 p = bprint_c(p, end, ')');
Bernie Innocenti55864192018-08-30 04:05:20 +0900653
654 /* skip CLASS */
655 _dnsPacket_skip(packet, 2);
656 return p;
657}
658
659/* this function assumes the packet has already been checked */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900660static char* dnsPacket_bprintQuery(DnsPacket* packet, char* p, char* end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900661 int qdCount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900662
663 if (packet->base[2] & 0x1) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900664 p = bprint_s(p, end, "RECURSIVE ");
Bernie Innocenti55864192018-08-30 04:05:20 +0900665 }
666
667 _dnsPacket_skip(packet, 4);
668 qdCount = _dnsPacket_readInt16(packet);
669 _dnsPacket_skip(packet, 6);
670
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900671 for (; qdCount > 0; qdCount--) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900672 p = dnsPacket_bprintQR(packet, p, end);
Bernie Innocenti55864192018-08-30 04:05:20 +0900673 }
674 return p;
675}
Bernie Innocenti55864192018-08-30 04:05:20 +0900676
Bernie Innocenti55864192018-08-30 04:05:20 +0900677/** QUERY HASHING SUPPORT
678 **
679 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKET HAS ALREADY
680 ** BEEN SUCCESFULLY CHECKED.
681 **/
682
683/* use 32-bit FNV hash function */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900684#define FNV_MULT 16777619U
685#define FNV_BASIS 2166136261U
Bernie Innocenti55864192018-08-30 04:05:20 +0900686
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900687static unsigned _dnsPacket_hashBytes(DnsPacket* packet, int numBytes, unsigned hash) {
688 const uint8_t* p = packet->cursor;
689 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900690
691 while (numBytes > 0 && p < end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900692 hash = hash * FNV_MULT ^ *p++;
Bernie Innocenti55864192018-08-30 04:05:20 +0900693 }
694 packet->cursor = p;
695 return hash;
696}
697
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900698static unsigned _dnsPacket_hashQName(DnsPacket* packet, unsigned hash) {
699 const uint8_t* p = packet->cursor;
700 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900701
702 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900703 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900704
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900705 if (p >= end) { /* should not happen */
chenbruce16adee42019-02-20 19:45:50 +0800706 LOG(INFO) << __func__ << ": INTERNAL_ERROR: read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900707 break;
708 }
709
710 c = *p++;
711
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900712 if (c == 0) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900713
714 if (c >= 64) {
chenbruce16adee42019-02-20 19:45:50 +0800715 LOG(INFO) << __func__ << ": INTERNAL_ERROR: malformed domain";
Bernie Innocenti55864192018-08-30 04:05:20 +0900716 break;
717 }
718 if (p + c >= end) {
chenbruce16adee42019-02-20 19:45:50 +0800719 LOG(INFO) << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900720 break;
721 }
722 while (c > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900723 hash = hash * FNV_MULT ^ *p++;
724 c -= 1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900725 }
726 }
727 packet->cursor = p;
728 return hash;
729}
730
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900731static unsigned _dnsPacket_hashQR(DnsPacket* packet, unsigned hash) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900732 hash = _dnsPacket_hashQName(packet, hash);
733 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TYPE and CLASS */
734 return hash;
735}
736
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900737static unsigned _dnsPacket_hashRR(DnsPacket* packet, unsigned hash) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900738 int rdlength;
739 hash = _dnsPacket_hashQR(packet, hash);
740 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TTL */
741 rdlength = _dnsPacket_readInt16(packet);
742 hash = _dnsPacket_hashBytes(packet, rdlength, hash); /* RDATA */
743 return hash;
744}
745
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900746static unsigned _dnsPacket_hashQuery(DnsPacket* packet) {
747 unsigned hash = FNV_BASIS;
748 int count, arcount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900749 _dnsPacket_rewind(packet);
750
751 /* ignore the ID */
752 _dnsPacket_skip(packet, 2);
753
754 /* we ignore the TC bit for reasons explained in
755 * _dnsPacket_checkQuery().
756 *
757 * however we hash the RD bit to differentiate
758 * between answers for recursive and non-recursive
759 * queries.
760 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900761 hash = hash * FNV_MULT ^ (packet->base[2] & 1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900762
763 /* mark the first header byte as processed */
764 _dnsPacket_skip(packet, 1);
765
766 /* process the second header byte */
767 hash = _dnsPacket_hashBytes(packet, 1, hash);
768
769 /* read QDCOUNT */
770 count = _dnsPacket_readInt16(packet);
771
772 /* assume: ANcount and NScount are 0 */
773 _dnsPacket_skip(packet, 4);
774
775 /* read ARCOUNT */
776 arcount = _dnsPacket_readInt16(packet);
777
778 /* hash QDCOUNT QRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900779 for (; count > 0; count--) hash = _dnsPacket_hashQR(packet, hash);
Bernie Innocenti55864192018-08-30 04:05:20 +0900780
781 /* hash ARCOUNT RRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900782 for (; arcount > 0; arcount--) hash = _dnsPacket_hashRR(packet, hash);
Bernie Innocenti55864192018-08-30 04:05:20 +0900783
784 return hash;
785}
786
Bernie Innocenti55864192018-08-30 04:05:20 +0900787/** QUERY COMPARISON
788 **
789 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKETS HAVE ALREADY
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900790 ** BEEN SUCCESSFULLY CHECKED.
Bernie Innocenti55864192018-08-30 04:05:20 +0900791 **/
792
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900793static int _dnsPacket_isEqualDomainName(DnsPacket* pack1, DnsPacket* pack2) {
794 const uint8_t* p1 = pack1->cursor;
795 const uint8_t* end1 = pack1->end;
796 const uint8_t* p2 = pack2->cursor;
797 const uint8_t* end2 = pack2->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900798
799 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900800 int c1, c2;
Bernie Innocenti55864192018-08-30 04:05:20 +0900801
802 if (p1 >= end1 || p2 >= end2) {
chenbruce16adee42019-02-20 19:45:50 +0800803 LOG(INFO) << __func__ << ": INTERNAL_ERROR: read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900804 break;
805 }
806 c1 = *p1++;
807 c2 = *p2++;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900808 if (c1 != c2) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900809
810 if (c1 == 0) {
811 pack1->cursor = p1;
812 pack2->cursor = p2;
813 return 1;
814 }
815 if (c1 >= 64) {
chenbruce16adee42019-02-20 19:45:50 +0800816 LOG(INFO) << __func__ << ": INTERNAL_ERROR: malformed domain";
Bernie Innocenti55864192018-08-30 04:05:20 +0900817 break;
818 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900819 if ((p1 + c1 > end1) || (p2 + c1 > end2)) {
chenbruce16adee42019-02-20 19:45:50 +0800820 LOG(INFO) << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900821 break;
822 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900823 if (memcmp(p1, p2, c1) != 0) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900824 p1 += c1;
825 p2 += c1;
826 /* we rely on the bound checks at the start of the loop */
827 }
828 /* not the same, or one is malformed */
Ken Chenbab50142019-03-19 17:41:28 +0800829 LOG(INFO) << __func__ << ": different DN";
Bernie Innocenti55864192018-08-30 04:05:20 +0900830 return 0;
831}
832
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900833static int _dnsPacket_isEqualBytes(DnsPacket* pack1, DnsPacket* pack2, int numBytes) {
834 const uint8_t* p1 = pack1->cursor;
835 const uint8_t* p2 = pack2->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900836
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900837 if (p1 + numBytes > pack1->end || p2 + numBytes > pack2->end) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900838
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900839 if (memcmp(p1, p2, numBytes) != 0) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900840
841 pack1->cursor += numBytes;
842 pack2->cursor += numBytes;
843 return 1;
844}
845
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900846static int _dnsPacket_isEqualQR(DnsPacket* pack1, DnsPacket* pack2) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900847 /* compare domain name encoding + TYPE + CLASS */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900848 if (!_dnsPacket_isEqualDomainName(pack1, pack2) ||
849 !_dnsPacket_isEqualBytes(pack1, pack2, 2 + 2))
Bernie Innocenti55864192018-08-30 04:05:20 +0900850 return 0;
851
852 return 1;
853}
854
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900855static int _dnsPacket_isEqualRR(DnsPacket* pack1, DnsPacket* pack2) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900856 int rdlength1, rdlength2;
857 /* compare query + TTL */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900858 if (!_dnsPacket_isEqualQR(pack1, pack2) || !_dnsPacket_isEqualBytes(pack1, pack2, 4)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900859
860 /* compare RDATA */
861 rdlength1 = _dnsPacket_readInt16(pack1);
862 rdlength2 = _dnsPacket_readInt16(pack2);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900863 if (rdlength1 != rdlength2 || !_dnsPacket_isEqualBytes(pack1, pack2, rdlength1)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900864
865 return 1;
866}
867
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900868static int _dnsPacket_isEqualQuery(DnsPacket* pack1, DnsPacket* pack2) {
869 int count1, count2, arcount1, arcount2;
Bernie Innocenti55864192018-08-30 04:05:20 +0900870
871 /* compare the headers, ignore most fields */
872 _dnsPacket_rewind(pack1);
873 _dnsPacket_rewind(pack2);
874
875 /* compare RD, ignore TC, see comment in _dnsPacket_checkQuery */
876 if ((pack1->base[2] & 1) != (pack2->base[2] & 1)) {
Ken Chenbab50142019-03-19 17:41:28 +0800877 LOG(INFO) << __func__ << ": different RD";
Bernie Innocenti55864192018-08-30 04:05:20 +0900878 return 0;
879 }
880
881 if (pack1->base[3] != pack2->base[3]) {
Ken Chenbab50142019-03-19 17:41:28 +0800882 LOG(INFO) << __func__ << ": different CD or AD";
Bernie Innocenti55864192018-08-30 04:05:20 +0900883 return 0;
884 }
885
886 /* mark ID and header bytes as compared */
887 _dnsPacket_skip(pack1, 4);
888 _dnsPacket_skip(pack2, 4);
889
890 /* compare QDCOUNT */
891 count1 = _dnsPacket_readInt16(pack1);
892 count2 = _dnsPacket_readInt16(pack2);
893 if (count1 != count2 || count1 < 0) {
Ken Chenbab50142019-03-19 17:41:28 +0800894 LOG(INFO) << __func__ << ": different QDCOUNT";
Bernie Innocenti55864192018-08-30 04:05:20 +0900895 return 0;
896 }
897
898 /* assume: ANcount and NScount are 0 */
899 _dnsPacket_skip(pack1, 4);
900 _dnsPacket_skip(pack2, 4);
901
902 /* compare ARCOUNT */
903 arcount1 = _dnsPacket_readInt16(pack1);
904 arcount2 = _dnsPacket_readInt16(pack2);
905 if (arcount1 != arcount2 || arcount1 < 0) {
Ken Chenbab50142019-03-19 17:41:28 +0800906 LOG(INFO) << __func__ << ": different ARCOUNT";
Bernie Innocenti55864192018-08-30 04:05:20 +0900907 return 0;
908 }
909
910 /* compare the QDCOUNT QRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900911 for (; count1 > 0; count1--) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900912 if (!_dnsPacket_isEqualQR(pack1, pack2)) {
Ken Chenbab50142019-03-19 17:41:28 +0800913 LOG(INFO) << __func__ << ": different QR";
Bernie Innocenti55864192018-08-30 04:05:20 +0900914 return 0;
915 }
916 }
917
918 /* compare the ARCOUNT RRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900919 for (; arcount1 > 0; arcount1--) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900920 if (!_dnsPacket_isEqualRR(pack1, pack2)) {
Ken Chenbab50142019-03-19 17:41:28 +0800921 LOG(INFO) << __func__ << ": different additional RR";
Bernie Innocenti55864192018-08-30 04:05:20 +0900922 return 0;
923 }
924 }
925 return 1;
926}
927
Bernie Innocenti55864192018-08-30 04:05:20 +0900928/* cache entry. for simplicity, 'hash' and 'hlink' are inlined in this
929 * structure though they are conceptually part of the hash table.
930 *
931 * similarly, mru_next and mru_prev are part of the global MRU list
932 */
933typedef struct Entry {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900934 unsigned int hash; /* hash value */
935 struct Entry* hlink; /* next in collision chain */
936 struct Entry* mru_prev;
937 struct Entry* mru_next;
Bernie Innocenti55864192018-08-30 04:05:20 +0900938
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900939 const uint8_t* query;
940 int querylen;
941 const uint8_t* answer;
942 int answerlen;
943 time_t expires; /* time_t when the entry isn't valid any more */
944 int id; /* for debugging purpose */
Bernie Innocenti55864192018-08-30 04:05:20 +0900945} Entry;
946
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900947/*
Bernie Innocenti55864192018-08-30 04:05:20 +0900948 * Find the TTL for a negative DNS result. This is defined as the minimum
949 * of the SOA records TTL and the MINIMUM-TTL field (RFC-2308).
950 *
951 * Return 0 if not found.
952 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900953static u_long answer_getNegativeTTL(ns_msg handle) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900954 int n, nscount;
955 u_long result = 0;
956 ns_rr rr;
957
958 nscount = ns_msg_count(handle, ns_s_ns);
959 for (n = 0; n < nscount; n++) {
960 if ((ns_parserr(&handle, ns_s_ns, n, &rr) == 0) && (ns_rr_type(rr) == ns_t_soa)) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900961 const u_char* rdata = ns_rr_rdata(rr); // find the data
962 const u_char* edata = rdata + ns_rr_rdlen(rr); // add the len to find the end
Bernie Innocenti55864192018-08-30 04:05:20 +0900963 int len;
964 u_long ttl, rec_result = ns_rr_ttl(rr);
965
966 // find the MINIMUM-TTL field from the blob of binary data for this record
967 // skip the server name
968 len = dn_skipname(rdata, edata);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900969 if (len == -1) continue; // error skipping
Bernie Innocenti55864192018-08-30 04:05:20 +0900970 rdata += len;
971
972 // skip the admin name
973 len = dn_skipname(rdata, edata);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900974 if (len == -1) continue; // error skipping
Bernie Innocenti55864192018-08-30 04:05:20 +0900975 rdata += len;
976
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900977 if (edata - rdata != 5 * NS_INT32SZ) continue;
Bernie Innocenti55864192018-08-30 04:05:20 +0900978 // skip: serial number + refresh interval + retry interval + expiry
979 rdata += NS_INT32SZ * 4;
980 // finally read the MINIMUM TTL
chenbruce86a50bb2019-03-28 18:44:37 +0800981 ttl = ntohl(*reinterpret_cast<const uint32_t*>(rdata));
Bernie Innocenti55864192018-08-30 04:05:20 +0900982 if (ttl < rec_result) {
983 rec_result = ttl;
984 }
985 // Now that the record is read successfully, apply the new min TTL
986 if (n == 0 || rec_result < result) {
987 result = rec_result;
988 }
989 }
990 }
991 return result;
992}
993
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900994/*
Bernie Innocenti55864192018-08-30 04:05:20 +0900995 * Parse the answer records and find the appropriate
996 * smallest TTL among the records. This might be from
997 * the answer records if found or from the SOA record
998 * if it's a negative result.
999 *
1000 * The returned TTL is the number of seconds to
1001 * keep the answer in the cache.
1002 *
1003 * In case of parse error zero (0) is returned which
1004 * indicates that the answer shall not be cached.
1005 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001006static u_long answer_getTTL(const void* answer, int answerlen) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001007 ns_msg handle;
1008 int ancount, n;
1009 u_long result, ttl;
1010 ns_rr rr;
1011
1012 result = 0;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001013 if (ns_initparse((const uint8_t*) answer, answerlen, &handle) >= 0) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001014 // get number of answer records
1015 ancount = ns_msg_count(handle, ns_s_an);
1016
1017 if (ancount == 0) {
1018 // a response with no answers? Cache this negative result.
1019 result = answer_getNegativeTTL(handle);
1020 } else {
1021 for (n = 0; n < ancount; n++) {
1022 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
1023 ttl = ns_rr_ttl(rr);
1024 if (n == 0 || ttl < result) {
1025 result = ttl;
1026 }
1027 } else {
Ken Chenbab50142019-03-19 17:41:28 +08001028 PLOG(INFO) << __func__ << ": ns_parserr failed ancount no = " << n;
Bernie Innocenti55864192018-08-30 04:05:20 +09001029 }
1030 }
1031 }
1032 } else {
Ken Chenbab50142019-03-19 17:41:28 +08001033 PLOG(INFO) << __func__ << ": ns_initparse failed";
Bernie Innocenti55864192018-08-30 04:05:20 +09001034 }
1035
Ken Chenbab50142019-03-19 17:41:28 +08001036 LOG(INFO) << __func__ << ": TTL = " << result;
Bernie Innocenti55864192018-08-30 04:05:20 +09001037 return result;
1038}
1039
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001040static void entry_free(Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001041 /* everything is allocated in a single memory block */
1042 if (e) {
1043 free(e);
1044 }
1045}
1046
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001047static void entry_mru_remove(Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001048 e->mru_prev->mru_next = e->mru_next;
1049 e->mru_next->mru_prev = e->mru_prev;
1050}
1051
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001052static void entry_mru_add(Entry* e, Entry* list) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001053 Entry* first = list->mru_next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001054
1055 e->mru_next = first;
1056 e->mru_prev = list;
1057
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001058 list->mru_next = e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001059 first->mru_prev = e;
1060}
1061
1062/* compute the hash of a given entry, this is a hash of most
1063 * data in the query (key) */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001064static unsigned entry_hash(const Entry* e) {
1065 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001066
1067 _dnsPacket_init(pack, e->query, e->querylen);
1068 return _dnsPacket_hashQuery(pack);
1069}
1070
1071/* initialize an Entry as a search key, this also checks the input query packet
1072 * returns 1 on success, or 0 in case of unsupported/malformed data */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001073static int entry_init_key(Entry* e, const void* query, int querylen) {
1074 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001075
1076 memset(e, 0, sizeof(*e));
1077
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001078 e->query = (const uint8_t*) query;
Bernie Innocenti55864192018-08-30 04:05:20 +09001079 e->querylen = querylen;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001080 e->hash = entry_hash(e);
Bernie Innocenti55864192018-08-30 04:05:20 +09001081
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001082 _dnsPacket_init(pack, e->query, e->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001083
1084 return _dnsPacket_checkQuery(pack);
1085}
1086
1087/* allocate a new entry as a cache node */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001088static Entry* entry_alloc(const Entry* init, const void* answer, int answerlen) {
1089 Entry* e;
1090 int size;
Bernie Innocenti55864192018-08-30 04:05:20 +09001091
1092 size = sizeof(*e) + init->querylen + answerlen;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001093 e = (Entry*) calloc(size, 1);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001094 if (e == NULL) return e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001095
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001096 e->hash = init->hash;
1097 e->query = (const uint8_t*) (e + 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001098 e->querylen = init->querylen;
1099
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001100 memcpy((char*) e->query, init->query, e->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001101
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001102 e->answer = e->query + e->querylen;
Bernie Innocenti55864192018-08-30 04:05:20 +09001103 e->answerlen = answerlen;
1104
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001105 memcpy((char*) e->answer, answer, e->answerlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001106
1107 return e;
1108}
1109
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001110static int entry_equals(const Entry* e1, const Entry* e2) {
1111 DnsPacket pack1[1], pack2[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001112
1113 if (e1->querylen != e2->querylen) {
1114 return 0;
1115 }
1116 _dnsPacket_init(pack1, e1->query, e1->querylen);
1117 _dnsPacket_init(pack2, e2->query, e2->querylen);
1118
1119 return _dnsPacket_isEqualQuery(pack1, pack2);
1120}
1121
Bernie Innocenti55864192018-08-30 04:05:20 +09001122/* We use a simple hash table with external collision lists
1123 * for simplicity, the hash-table fields 'hash' and 'hlink' are
1124 * inlined in the Entry structure.
1125 */
1126
1127/* Maximum time for a thread to wait for an pending request */
Ken Chen2a429352018-12-22 21:46:55 +08001128constexpr int PENDING_REQUEST_TIMEOUT = 20;
Bernie Innocenti55864192018-08-30 04:05:20 +09001129
1130typedef struct resolv_cache {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001131 int max_entries;
1132 int num_entries;
1133 Entry mru_list;
1134 int last_id;
1135 Entry* entries;
Ken Chen2a429352018-12-22 21:46:55 +08001136 struct pending_req_info {
1137 unsigned int hash;
1138 struct pending_req_info* next;
1139 } pending_requests;
Bernie Innocenti55864192018-08-30 04:05:20 +09001140} Cache;
1141
1142struct resolv_cache_info {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001143 unsigned netid;
1144 Cache* cache;
1145 struct resolv_cache_info* next;
1146 int nscount;
1147 char* nameservers[MAXNS];
1148 struct addrinfo* nsaddrinfo[MAXNS];
1149 int revision_id; // # times the nameservers have been replaced
Bernie Innocenti34de3ba2019-02-19 18:08:36 +09001150 res_params params;
Bernie Innocenti189eb502018-10-01 23:10:18 +09001151 struct res_stats nsstats[MAXNS];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001152 char defdname[MAXDNSRCHPATH];
1153 int dnsrch_offset[MAXDNSRCH + 1]; // offsets into defdname
Ken Chen2a429352018-12-22 21:46:55 +08001154 int wait_for_pending_req_timeout_count;
Luke Huang57b128d2019-07-23 16:04:12 -07001155 // Map format: ReturnCode:rate_denom
1156 std::unordered_map<int, uint32_t> dns_event_subsampling_map;
Bernie Innocenti55864192018-08-30 04:05:20 +09001157};
1158
Ken Chen2a429352018-12-22 21:46:55 +08001159// A helper class for the Clang Thread Safety Analysis to deal with
1160// std::unique_lock.
1161class SCOPED_CAPABILITY ScopedAssumeLocked {
1162 public:
1163 ScopedAssumeLocked(std::mutex& mutex) ACQUIRE(mutex) {}
1164 ~ScopedAssumeLocked() RELEASE() {}
1165};
Bernie Innocenti55864192018-08-30 04:05:20 +09001166
Ken Chen2a429352018-12-22 21:46:55 +08001167// lock protecting everything in the resolve_cache_info structs (next ptr, etc)
1168static std::mutex cache_mutex;
1169static std::condition_variable cv;
Bernie Innocenti55864192018-08-30 04:05:20 +09001170
1171/* gets cache associated with a network, or NULL if none exists */
Lorenzo Colittibb65ae22019-04-25 18:06:41 -07001172static resolv_cache* find_named_cache_locked(unsigned netid) REQUIRES(cache_mutex);
1173static int resolv_create_cache_for_net_locked(unsigned netid) REQUIRES(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001174
Ken Chen2a429352018-12-22 21:46:55 +08001175static void cache_flush_pending_requests_locked(struct resolv_cache* cache) {
1176 resolv_cache::pending_req_info *ri, *tmp;
1177 if (!cache) return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001178
Ken Chen2a429352018-12-22 21:46:55 +08001179 ri = cache->pending_requests.next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001180
Ken Chen2a429352018-12-22 21:46:55 +08001181 while (ri) {
1182 tmp = ri;
1183 ri = ri->next;
1184 free(tmp);
Bernie Innocenti55864192018-08-30 04:05:20 +09001185 }
1186
Ken Chen2a429352018-12-22 21:46:55 +08001187 cache->pending_requests.next = NULL;
1188 cv.notify_all();
Bernie Innocenti55864192018-08-30 04:05:20 +09001189}
1190
Ken Chen2a429352018-12-22 21:46:55 +08001191// Return true - if there is a pending request in |cache| matching |key|.
1192// Return false - if no pending request is found matching the key. Optionally
1193// link a new one if parameter append_if_not_found is true.
1194static bool cache_has_pending_request_locked(resolv_cache* cache, const Entry* key,
1195 bool append_if_not_found) {
1196 if (!cache || !key) return false;
Bernie Innocenti55864192018-08-30 04:05:20 +09001197
Ken Chen2a429352018-12-22 21:46:55 +08001198 resolv_cache::pending_req_info* ri = cache->pending_requests.next;
1199 resolv_cache::pending_req_info* prev = &cache->pending_requests;
1200 while (ri) {
1201 if (ri->hash == key->hash) {
1202 return true;
Bernie Innocenti55864192018-08-30 04:05:20 +09001203 }
Ken Chen2a429352018-12-22 21:46:55 +08001204 prev = ri;
1205 ri = ri->next;
1206 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001207
Ken Chen2a429352018-12-22 21:46:55 +08001208 if (append_if_not_found) {
1209 ri = (resolv_cache::pending_req_info*)calloc(1, sizeof(resolv_cache::pending_req_info));
Bernie Innocenti55864192018-08-30 04:05:20 +09001210 if (ri) {
Ken Chen2a429352018-12-22 21:46:55 +08001211 ri->hash = key->hash;
1212 prev->next = ri;
Bernie Innocenti55864192018-08-30 04:05:20 +09001213 }
1214 }
Ken Chen2a429352018-12-22 21:46:55 +08001215 return false;
1216}
1217
1218// Notify all threads that the cache entry |key| has become available
1219static void _cache_notify_waiting_tid_locked(struct resolv_cache* cache, const Entry* key) {
1220 if (!cache || !key) return;
1221
1222 resolv_cache::pending_req_info* ri = cache->pending_requests.next;
1223 resolv_cache::pending_req_info* prev = &cache->pending_requests;
1224 while (ri) {
1225 if (ri->hash == key->hash) {
1226 // remove item from list and destroy
1227 prev->next = ri->next;
1228 free(ri);
1229 cv.notify_all();
1230 return;
1231 }
1232 prev = ri;
1233 ri = ri->next;
1234 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001235}
1236
Luke Huang952d0942018-12-26 16:53:03 +08001237void _resolv_cache_query_failed(unsigned netid, const void* query, int querylen, uint32_t flags) {
1238 // We should not notify with these flags.
1239 if (flags & (ANDROID_RESOLV_NO_CACHE_STORE | ANDROID_RESOLV_NO_CACHE_LOOKUP)) {
1240 return;
1241 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001242 Entry key[1];
1243 Cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001244
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001245 if (!entry_init_key(key, query, querylen)) return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001246
Ken Chen2a429352018-12-22 21:46:55 +08001247 std::lock_guard guard(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001248
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001249 cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001250
1251 if (cache) {
1252 _cache_notify_waiting_tid_locked(cache, key);
1253 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001254}
1255
Bernie Innocentid2b27032018-12-18 19:53:42 +09001256static void cache_flush_locked(Cache* cache) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001257 int nn;
Bernie Innocenti55864192018-08-30 04:05:20 +09001258
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001259 for (nn = 0; nn < cache->max_entries; nn++) {
1260 Entry** pnode = (Entry**) &cache->entries[nn];
Bernie Innocenti55864192018-08-30 04:05:20 +09001261
1262 while (*pnode != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001263 Entry* node = *pnode;
Bernie Innocenti55864192018-08-30 04:05:20 +09001264 *pnode = node->hlink;
1265 entry_free(node);
1266 }
1267 }
1268
1269 // flush pending request
Ken Chen2a429352018-12-22 21:46:55 +08001270 cache_flush_pending_requests_locked(cache);
Bernie Innocenti55864192018-08-30 04:05:20 +09001271
1272 cache->mru_list.mru_next = cache->mru_list.mru_prev = &cache->mru_list;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001273 cache->num_entries = 0;
1274 cache->last_id = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +09001275
Ken Chenbab50142019-03-19 17:41:28 +08001276 LOG(INFO) << __func__ << ": *** DNS CACHE FLUSHED ***";
Bernie Innocenti55864192018-08-30 04:05:20 +09001277}
1278
Ken Chen2a429352018-12-22 21:46:55 +08001279static resolv_cache* resolv_cache_create() {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001280 struct resolv_cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001281
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001282 cache = (struct resolv_cache*) calloc(sizeof(*cache), 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001283 if (cache) {
nuccachen989d2232018-11-29 17:41:12 +08001284 cache->max_entries = CONFIG_MAX_ENTRIES;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001285 cache->entries = (Entry*) calloc(sizeof(*cache->entries), cache->max_entries);
Bernie Innocenti55864192018-08-30 04:05:20 +09001286 if (cache->entries) {
1287 cache->mru_list.mru_prev = cache->mru_list.mru_next = &cache->mru_list;
chenbruce16adee42019-02-20 19:45:50 +08001288 LOG(INFO) << __func__ << ": cache created";
Bernie Innocenti55864192018-08-30 04:05:20 +09001289 } else {
1290 free(cache);
1291 cache = NULL;
1292 }
1293 }
1294 return cache;
1295}
1296
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001297static void dump_query(const uint8_t* query, int querylen) {
Ken Chenbab50142019-03-19 17:41:28 +08001298 if (!WOULD_LOG(VERBOSE)) return;
1299
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001300 char temp[256], *p = temp, *end = p + sizeof(temp);
1301 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001302
1303 _dnsPacket_init(pack, query, querylen);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001304 p = dnsPacket_bprintQuery(pack, p, end);
Ken Chenbab50142019-03-19 17:41:28 +08001305 LOG(VERBOSE) << __func__ << ": " << temp;
Bernie Innocenti55864192018-08-30 04:05:20 +09001306}
1307
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001308static void cache_dump_mru(Cache* cache) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001309 char temp[512], *p = temp, *end = p + sizeof(temp);
1310 Entry* e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001311
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001312 p = bprint(temp, end, "MRU LIST (%2d): ", cache->num_entries);
Bernie Innocenti55864192018-08-30 04:05:20 +09001313 for (e = cache->mru_list.mru_next; e != &cache->mru_list; e = e->mru_next)
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001314 p = bprint(p, end, " %d", e->id);
Bernie Innocenti55864192018-08-30 04:05:20 +09001315
Ken Chenbab50142019-03-19 17:41:28 +08001316 LOG(INFO) << __func__ << ": " << temp;
Bernie Innocenti55864192018-08-30 04:05:20 +09001317}
1318
Bernie Innocenti55864192018-08-30 04:05:20 +09001319/* This function tries to find a key within the hash table
1320 * In case of success, it will return a *pointer* to the hashed key.
1321 * In case of failure, it will return a *pointer* to NULL
1322 *
1323 * So, the caller must check '*result' to check for success/failure.
1324 *
1325 * The main idea is that the result can later be used directly in
1326 * calls to _resolv_cache_add or _resolv_cache_remove as the 'lookup'
1327 * parameter. This makes the code simpler and avoids re-searching
1328 * for the key position in the htable.
1329 *
1330 * The result of a lookup_p is only valid until you alter the hash
1331 * table.
1332 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001333static Entry** _cache_lookup_p(Cache* cache, Entry* key) {
1334 int index = key->hash % cache->max_entries;
1335 Entry** pnode = (Entry**) &cache->entries[index];
Bernie Innocenti55864192018-08-30 04:05:20 +09001336
1337 while (*pnode != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001338 Entry* node = *pnode;
Bernie Innocenti55864192018-08-30 04:05:20 +09001339
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001340 if (node == NULL) break;
Bernie Innocenti55864192018-08-30 04:05:20 +09001341
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001342 if (node->hash == key->hash && entry_equals(node, key)) break;
Bernie Innocenti55864192018-08-30 04:05:20 +09001343
1344 pnode = &node->hlink;
1345 }
1346 return pnode;
1347}
1348
1349/* Add a new entry to the hash table. 'lookup' must be the
1350 * result of an immediate previous failed _lookup_p() call
1351 * (i.e. with *lookup == NULL), and 'e' is the pointer to the
1352 * newly created entry
1353 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001354static void _cache_add_p(Cache* cache, Entry** lookup, Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001355 *lookup = e;
1356 e->id = ++cache->last_id;
1357 entry_mru_add(e, &cache->mru_list);
1358 cache->num_entries += 1;
1359
chenbruce16adee42019-02-20 19:45:50 +08001360 LOG(INFO) << __func__ << ": entry " << e->id << " added (count=" << cache->num_entries << ")";
Bernie Innocenti55864192018-08-30 04:05:20 +09001361}
1362
1363/* Remove an existing entry from the hash table,
1364 * 'lookup' must be the result of an immediate previous
1365 * and succesful _lookup_p() call.
1366 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001367static void _cache_remove_p(Cache* cache, Entry** lookup) {
1368 Entry* e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001369
chenbruce16adee42019-02-20 19:45:50 +08001370 LOG(INFO) << __func__ << ": entry " << e->id << " removed (count=" << cache->num_entries - 1
1371 << ")";
Bernie Innocenti55864192018-08-30 04:05:20 +09001372
1373 entry_mru_remove(e);
1374 *lookup = e->hlink;
1375 entry_free(e);
1376 cache->num_entries -= 1;
1377}
1378
1379/* Remove the oldest entry from the hash table.
1380 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001381static void _cache_remove_oldest(Cache* cache) {
1382 Entry* oldest = cache->mru_list.mru_prev;
1383 Entry** lookup = _cache_lookup_p(cache, oldest);
Bernie Innocenti55864192018-08-30 04:05:20 +09001384
1385 if (*lookup == NULL) { /* should not happen */
chenbruce16adee42019-02-20 19:45:50 +08001386 LOG(INFO) << __func__ << ": OLDEST NOT IN HTABLE ?";
Bernie Innocenti55864192018-08-30 04:05:20 +09001387 return;
1388 }
Ken Chenbab50142019-03-19 17:41:28 +08001389 LOG(INFO) << __func__ << ": Cache full - removing oldest";
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001390 dump_query(oldest->query, oldest->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001391 _cache_remove_p(cache, lookup);
1392}
1393
1394/* Remove all expired entries from the hash table.
1395 */
1396static void _cache_remove_expired(Cache* cache) {
1397 Entry* e;
1398 time_t now = _time_now();
1399
1400 for (e = cache->mru_list.mru_next; e != &cache->mru_list;) {
1401 // Entry is old, remove
1402 if (now >= e->expires) {
1403 Entry** lookup = _cache_lookup_p(cache, e);
1404 if (*lookup == NULL) { /* should not happen */
chenbruce16adee42019-02-20 19:45:50 +08001405 LOG(INFO) << __func__ << ": ENTRY NOT IN HTABLE ?";
Bernie Innocenti55864192018-08-30 04:05:20 +09001406 return;
1407 }
1408 e = e->mru_next;
1409 _cache_remove_p(cache, lookup);
1410 } else {
1411 e = e->mru_next;
1412 }
1413 }
1414}
1415
Ken Chen2a429352018-12-22 21:46:55 +08001416// gets a resolv_cache_info associated with a network, or NULL if not found
1417static resolv_cache_info* find_cache_info_locked(unsigned netid) REQUIRES(cache_mutex);
1418
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001419ResolvCacheStatus _resolv_cache_lookup(unsigned netid, const void* query, int querylen,
Luke Huang952d0942018-12-26 16:53:03 +08001420 void* answer, int answersize, int* answerlen,
1421 uint32_t flags) {
Luke Huang95f33732019-03-19 17:30:36 +08001422 // Skip cache lookup, return RESOLV_CACHE_NOTFOUND directly so that it is
1423 // possible to cache the answer of this query.
Luke Huangee56e5b2019-05-09 21:33:13 -07001424 // If ANDROID_RESOLV_NO_CACHE_STORE is set, return RESOLV_CACHE_SKIP to skip possible cache
1425 // storing.
Luke Huang952d0942018-12-26 16:53:03 +08001426 if (flags & ANDROID_RESOLV_NO_CACHE_LOOKUP) {
Luke Huangee56e5b2019-05-09 21:33:13 -07001427 return flags & ANDROID_RESOLV_NO_CACHE_STORE ? RESOLV_CACHE_SKIP : RESOLV_CACHE_NOTFOUND;
Luke Huang952d0942018-12-26 16:53:03 +08001428 }
Ken Chen2a429352018-12-22 21:46:55 +08001429 Entry key;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001430 Entry** lookup;
1431 Entry* e;
1432 time_t now;
1433 Cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001434
chenbruce16adee42019-02-20 19:45:50 +08001435 LOG(INFO) << __func__ << ": lookup";
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001436 dump_query((u_char*) query, querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001437
1438 /* we don't cache malformed queries */
Ken Chen2a429352018-12-22 21:46:55 +08001439 if (!entry_init_key(&key, query, querylen)) {
chenbruce16adee42019-02-20 19:45:50 +08001440 LOG(INFO) << __func__ << ": unsupported query";
Bernie Innocenti55864192018-08-30 04:05:20 +09001441 return RESOLV_CACHE_UNSUPPORTED;
1442 }
1443 /* lookup cache */
Ken Chen2a429352018-12-22 21:46:55 +08001444 std::unique_lock lock(cache_mutex);
1445 ScopedAssumeLocked assume_lock(cache_mutex);
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001446 cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001447 if (cache == NULL) {
Ken Chen2a429352018-12-22 21:46:55 +08001448 return RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti55864192018-08-30 04:05:20 +09001449 }
1450
1451 /* see the description of _lookup_p to understand this.
1452 * the function always return a non-NULL pointer.
1453 */
Ken Chen2a429352018-12-22 21:46:55 +08001454 lookup = _cache_lookup_p(cache, &key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001455 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001456
1457 if (e == NULL) {
Ken Chenbab50142019-03-19 17:41:28 +08001458 LOG(INFO) << __func__ << ": NOT IN CACHE";
Luke Huang952d0942018-12-26 16:53:03 +08001459 // If it is no-cache-store mode, we won't wait for possible query.
1460 if (flags & ANDROID_RESOLV_NO_CACHE_STORE) {
Ken Chen2a429352018-12-22 21:46:55 +08001461 return RESOLV_CACHE_SKIP;
Luke Huang952d0942018-12-26 16:53:03 +08001462 }
Ken Chen2a429352018-12-22 21:46:55 +08001463
1464 if (!cache_has_pending_request_locked(cache, &key, true)) {
1465 return RESOLV_CACHE_NOTFOUND;
1466
Bernie Innocenti55864192018-08-30 04:05:20 +09001467 } else {
Ken Chenbab50142019-03-19 17:41:28 +08001468 LOG(INFO) << __func__ << ": Waiting for previous request";
Ken Chen2a429352018-12-22 21:46:55 +08001469 // wait until (1) timeout OR
1470 // (2) cv is notified AND no pending request matching the |key|
1471 // (cv notifier should delete pending request before sending notification.)
1472 bool ret = cv.wait_for(lock, std::chrono::seconds(PENDING_REQUEST_TIMEOUT),
1473 [netid, &cache, &key]() REQUIRES(cache_mutex) {
1474 // Must update cache as it could have been deleted
1475 cache = find_named_cache_locked(netid);
1476 return !cache_has_pending_request_locked(cache, &key, false);
1477 });
Ken Chen111c1ba2019-02-21 03:50:11 +08001478 if (!cache) {
1479 return RESOLV_CACHE_NOTFOUND;
1480 }
Ken Chen2a429352018-12-22 21:46:55 +08001481 if (ret == false) {
1482 resolv_cache_info* info = find_cache_info_locked(netid);
1483 if (info != NULL) {
1484 info->wait_for_pending_req_timeout_count++;
1485 }
1486 }
1487 lookup = _cache_lookup_p(cache, &key);
Bernie Innocenti55864192018-08-30 04:05:20 +09001488 e = *lookup;
1489 if (e == NULL) {
Ken Chen2a429352018-12-22 21:46:55 +08001490 return RESOLV_CACHE_NOTFOUND;
Bernie Innocenti55864192018-08-30 04:05:20 +09001491 }
1492 }
1493 }
1494
1495 now = _time_now();
1496
1497 /* remove stale entries here */
1498 if (now >= e->expires) {
Ken Chenbab50142019-03-19 17:41:28 +08001499 LOG(INFO) << __func__ << ": NOT IN CACHE (STALE ENTRY " << *lookup << "DISCARDED)";
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001500 dump_query(e->query, e->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001501 _cache_remove_p(cache, lookup);
Ken Chen2a429352018-12-22 21:46:55 +08001502 return RESOLV_CACHE_NOTFOUND;
Bernie Innocenti55864192018-08-30 04:05:20 +09001503 }
1504
1505 *answerlen = e->answerlen;
1506 if (e->answerlen > answersize) {
1507 /* NOTE: we return UNSUPPORTED if the answer buffer is too short */
Ken Chenbab50142019-03-19 17:41:28 +08001508 LOG(INFO) << __func__ << ": ANSWER TOO LONG";
Ken Chen2a429352018-12-22 21:46:55 +08001509 return RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti55864192018-08-30 04:05:20 +09001510 }
1511
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001512 memcpy(answer, e->answer, e->answerlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001513
1514 /* bump up this entry to the top of the MRU list */
1515 if (e != cache->mru_list.mru_next) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001516 entry_mru_remove(e);
1517 entry_mru_add(e, &cache->mru_list);
Bernie Innocenti55864192018-08-30 04:05:20 +09001518 }
1519
Ken Chenbab50142019-03-19 17:41:28 +08001520 LOG(INFO) << __func__ << ": FOUND IN CACHE entry=" << e;
Ken Chen2a429352018-12-22 21:46:55 +08001521 return RESOLV_CACHE_FOUND;
Bernie Innocenti55864192018-08-30 04:05:20 +09001522}
1523
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001524void _resolv_cache_add(unsigned netid, const void* query, int querylen, const void* answer,
1525 int answerlen) {
1526 Entry key[1];
1527 Entry* e;
1528 Entry** lookup;
1529 u_long ttl;
1530 Cache* cache = NULL;
Bernie Innocenti55864192018-08-30 04:05:20 +09001531
1532 /* don't assume that the query has already been cached
1533 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001534 if (!entry_init_key(key, query, querylen)) {
chenbruce16adee42019-02-20 19:45:50 +08001535 LOG(INFO) << __func__ << ": passed invalid query?";
Bernie Innocenti55864192018-08-30 04:05:20 +09001536 return;
1537 }
1538
Ken Chen2a429352018-12-22 21:46:55 +08001539 std::lock_guard guard(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001540
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001541 cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001542 if (cache == NULL) {
Ken Chen2a429352018-12-22 21:46:55 +08001543 return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001544 }
1545
chenbruce16adee42019-02-20 19:45:50 +08001546 LOG(INFO) << __func__ << ": query:";
chenbrucee8911f92019-03-06 13:52:43 +08001547 dump_query((u_char*)query, querylen);
1548 res_pquery((u_char*)answer, answerlen);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001549 if (kDumpData) {
Ken Chenbab50142019-03-19 17:41:28 +08001550 LOG(INFO) << __func__ << ": answer:";
chenbrucee8911f92019-03-06 13:52:43 +08001551 dump_bytes((u_char*)answer, answerlen);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001552 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001553
1554 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001555 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001556
Luke Huang95f33732019-03-19 17:30:36 +08001557 // Should only happen on ANDROID_RESOLV_NO_CACHE_LOOKUP
1558 if (e != NULL) {
chenbruce16adee42019-02-20 19:45:50 +08001559 LOG(INFO) << __func__ << ": ALREADY IN CACHE (" << e << ") ? IGNORING ADD";
Ken Chen2a429352018-12-22 21:46:55 +08001560 _cache_notify_waiting_tid_locked(cache, key);
1561 return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001562 }
1563
1564 if (cache->num_entries >= cache->max_entries) {
1565 _cache_remove_expired(cache);
1566 if (cache->num_entries >= cache->max_entries) {
1567 _cache_remove_oldest(cache);
1568 }
Luke Huang95f33732019-03-19 17:30:36 +08001569 // TODO: It looks useless, remove below code after having test to prove it.
Bernie Innocenti55864192018-08-30 04:05:20 +09001570 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001571 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001572 if (e != NULL) {
chenbruce16adee42019-02-20 19:45:50 +08001573 LOG(INFO) << __func__ << ": ALREADY IN CACHE (" << e << ") ? IGNORING ADD";
Ken Chen2a429352018-12-22 21:46:55 +08001574 _cache_notify_waiting_tid_locked(cache, key);
1575 return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001576 }
1577 }
1578
1579 ttl = answer_getTTL(answer, answerlen);
1580 if (ttl > 0) {
1581 e = entry_alloc(key, answer, answerlen);
1582 if (e != NULL) {
1583 e->expires = ttl + _time_now();
1584 _cache_add_p(cache, lookup, e);
1585 }
1586 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001587
Ken Chen2a429352018-12-22 21:46:55 +08001588 cache_dump_mru(cache);
1589 _cache_notify_waiting_tid_locked(cache, key);
Bernie Innocenti55864192018-08-30 04:05:20 +09001590}
1591
Ken Chen2a429352018-12-22 21:46:55 +08001592// Head of the list of caches.
1593static struct resolv_cache_info res_cache_list GUARDED_BY(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001594
ckenb1a69a42018-12-01 17:45:18 +09001595// insert resolv_cache_info into the list of resolv_cache_infos
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001596static void insert_cache_info_locked(resolv_cache_info* cache_info);
ckenb1a69a42018-12-01 17:45:18 +09001597// creates a resolv_cache_info
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001598static resolv_cache_info* create_cache_info();
ckenb1a69a42018-12-01 17:45:18 +09001599// empty the nameservers set for the named cache
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001600static void free_nameservers_locked(resolv_cache_info* cache_info);
1601// return 1 if the provided list of name servers differs from the list of name servers
1602// currently attached to the provided cache_info
1603static int resolv_is_nameservers_equal_locked(resolv_cache_info* cache_info, const char** servers,
1604 int numservers);
ckenb1a69a42018-12-01 17:45:18 +09001605// clears the stats samples contained withing the given cache_info
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001606static void res_cache_clear_stats_locked(resolv_cache_info* cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001607
ckenb1a69a42018-12-01 17:45:18 +09001608// public API for netd to query if name server is set on specific netid
1609bool resolv_has_nameservers(unsigned netid) {
Ken Chen2a429352018-12-22 21:46:55 +08001610 std::lock_guard guard(cache_mutex);
ckenb1a69a42018-12-01 17:45:18 +09001611 resolv_cache_info* info = find_cache_info_locked(netid);
Ken Chen2a429352018-12-22 21:46:55 +08001612 return (info != nullptr) && (info->nscount > 0);
ckenb1a69a42018-12-01 17:45:18 +09001613}
1614
Luke Huang57b128d2019-07-23 16:04:12 -07001615namespace {
1616
1617// Map format: ReturnCode:rate_denom
1618// if the ReturnCode is not associated with any rate_denom, use default
1619// Sampling rate varies by return code; events to log are chosen randomly, with a
1620// probability proportional to the sampling rate.
1621constexpr const char DEFAULT_SUBSAMPLING_MAP[] = "default:1 0:100 7:10";
1622
1623std::unordered_map<int, uint32_t> resolv_get_dns_event_subsampling_map() {
1624 using android::base::ParseInt;
1625 using android::base::ParseUint;
1626 using android::base::Split;
1627 using server_configurable_flags::GetServerConfigurableFlag;
1628 std::unordered_map<int, uint32_t> sampling_rate_map{};
1629 std::vector<std::string> subsampling_vector =
1630 Split(GetServerConfigurableFlag("netd_native", "dns_event_subsample_map",
1631 DEFAULT_SUBSAMPLING_MAP),
1632 " ");
1633 for (const auto& pair : subsampling_vector) {
1634 std::vector<std::string> rate_denom = Split(pair, ":");
1635 int return_code;
1636 uint32_t denom;
1637 if (rate_denom.size() != 2) {
1638 LOG(ERROR) << __func__ << ": invalid subsampling_pair = " << pair;
1639 continue;
1640 }
1641 if (rate_denom[0] == "default") {
1642 return_code = DNSEVENT_SUBSAMPLING_MAP_DEFAULT_KEY;
1643 } else if (!ParseInt(rate_denom[0], &return_code)) {
1644 LOG(ERROR) << __func__ << ": parse subsampling_pair failed = " << pair;
1645 continue;
1646 }
1647 if (!ParseUint(rate_denom[1], &denom)) {
1648 LOG(ERROR) << __func__ << ": parse subsampling_pair failed = " << pair;
1649 continue;
1650 }
1651 sampling_rate_map[return_code] = denom;
1652 }
1653 return sampling_rate_map;
1654}
1655
1656} // namespace
1657
Lorenzo Colittibb65ae22019-04-25 18:06:41 -07001658static int resolv_create_cache_for_net_locked(unsigned netid) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001659 resolv_cache* cache = find_named_cache_locked(netid);
Lorenzo Colittibb65ae22019-04-25 18:06:41 -07001660 // Should not happen
1661 if (cache) {
1662 LOG(ERROR) << __func__ << ": Cache is already created, netId: " << netid;
1663 return -EEXIST;
Bernie Innocenti55864192018-08-30 04:05:20 +09001664 }
Lorenzo Colittibb65ae22019-04-25 18:06:41 -07001665
1666 resolv_cache_info* cache_info = create_cache_info();
1667 if (!cache_info) return -ENOMEM;
1668 cache = resolv_cache_create();
1669 if (!cache) {
1670 free(cache_info);
1671 return -ENOMEM;
1672 }
1673 cache_info->cache = cache;
1674 cache_info->netid = netid;
Luke Huang57b128d2019-07-23 16:04:12 -07001675 cache_info->dns_event_subsampling_map = resolv_get_dns_event_subsampling_map();
Lorenzo Colittibb65ae22019-04-25 18:06:41 -07001676 insert_cache_info_locked(cache_info);
1677
1678 return 0;
1679}
1680
1681int resolv_create_cache_for_net(unsigned netid) {
1682 std::lock_guard guard(cache_mutex);
1683 return resolv_create_cache_for_net_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001684}
1685
Bernie Innocenti189eb502018-10-01 23:10:18 +09001686void resolv_delete_cache_for_net(unsigned netid) {
Ken Chen2a429352018-12-22 21:46:55 +08001687 std::lock_guard guard(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001688
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001689 struct resolv_cache_info* prev_cache_info = &res_cache_list;
Bernie Innocenti55864192018-08-30 04:05:20 +09001690
1691 while (prev_cache_info->next) {
1692 struct resolv_cache_info* cache_info = prev_cache_info->next;
1693
1694 if (cache_info->netid == netid) {
1695 prev_cache_info->next = cache_info->next;
Bernie Innocentid2b27032018-12-18 19:53:42 +09001696 cache_flush_locked(cache_info->cache);
Bernie Innocenti55864192018-08-30 04:05:20 +09001697 free(cache_info->cache->entries);
1698 free(cache_info->cache);
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001699 free_nameservers_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001700 free(cache_info);
1701 break;
1702 }
1703
1704 prev_cache_info = prev_cache_info->next;
1705 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001706}
1707
Bernie Innocentif5790f22019-03-28 19:25:11 +09001708std::vector<unsigned> resolv_list_caches() {
1709 std::lock_guard guard(cache_mutex);
1710 struct resolv_cache_info* cache_info = res_cache_list.next;
1711 std::vector<unsigned> result;
1712 while (cache_info) {
1713 result.push_back(cache_info->netid);
1714 cache_info = cache_info->next;
1715 }
1716 return result;
1717}
1718
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001719static resolv_cache_info* create_cache_info() {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001720 return (struct resolv_cache_info*) calloc(sizeof(struct resolv_cache_info), 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001721}
1722
Ken Chen2a429352018-12-22 21:46:55 +08001723// TODO: convert this to a simple and efficient C++ container.
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001724static void insert_cache_info_locked(struct resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001725 struct resolv_cache_info* last;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001726 for (last = &res_cache_list; last->next; last = last->next) {}
Bernie Innocenti55864192018-08-30 04:05:20 +09001727 last->next = cache_info;
Bernie Innocenti55864192018-08-30 04:05:20 +09001728}
1729
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001730static resolv_cache* find_named_cache_locked(unsigned netid) {
ckenb1a69a42018-12-01 17:45:18 +09001731 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001732 if (info != NULL) return info->cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001733 return NULL;
1734}
1735
ckenb1a69a42018-12-01 17:45:18 +09001736static resolv_cache_info* find_cache_info_locked(unsigned netid) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001737 struct resolv_cache_info* cache_info = res_cache_list.next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001738
1739 while (cache_info) {
1740 if (cache_info->netid == netid) {
1741 break;
1742 }
1743
1744 cache_info = cache_info->next;
1745 }
1746 return cache_info;
1747}
1748
Bernie Innocenti34de3ba2019-02-19 18:08:36 +09001749static void resolv_set_default_params(res_params* params) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001750 params->sample_validity = NSSAMPLE_VALIDITY;
1751 params->success_threshold = SUCCESS_THRESHOLD;
1752 params->min_samples = 0;
1753 params->max_samples = 0;
1754 params->base_timeout_msec = 0; // 0 = legacy algorithm
waynemad193e4d2019-02-18 17:47:59 +08001755 params->retry_count = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +09001756}
1757
waynema2371eab2019-01-18 14:02:31 +08001758static void resolv_set_experiment_params(res_params* params) {
1759 using android::base::ParseInt;
1760 using server_configurable_flags::GetServerConfigurableFlag;
1761
1762 if (params->retry_count == 0) {
1763 params->retry_count = RES_DFLRETRY;
1764 ParseInt(GetServerConfigurableFlag("netd_native", "retry_count", ""), &params->retry_count);
1765 }
1766
1767 if (params->base_timeout_msec == 0) {
1768 params->base_timeout_msec = RES_TIMEOUT;
1769 ParseInt(GetServerConfigurableFlag("netd_native", "retransmission_time_interval", ""),
1770 &params->base_timeout_msec);
1771 }
1772}
1773
Bernie Innocenti45238a12018-12-04 14:57:48 +09001774int resolv_set_nameservers_for_net(unsigned netid, const char** servers, const int numservers,
Bernie Innocenti34de3ba2019-02-19 18:08:36 +09001775 const char* domains, const res_params* params) {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001776 char* cp;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001777 int* offset;
Bernie Innocenti55864192018-08-30 04:05:20 +09001778 struct addrinfo* nsaddrinfo[MAXNS];
1779
1780 if (numservers > MAXNS) {
Bernie Innocentid017e972019-03-03 19:39:53 +09001781 LOG(ERROR) << __func__ << ": numservers=" << numservers << ", MAXNS=" << MAXNS;
Bernie Innocenti55864192018-08-30 04:05:20 +09001782 return E2BIG;
1783 }
1784
1785 // Parse the addresses before actually locking or changing any state, in case there is an error.
1786 // As a side effect this also reduces the time the lock is kept.
Bernie Innocentic165ce82018-10-16 23:35:28 +09001787 char sbuf[NI_MAXSERV];
Bernie Innocenti55864192018-08-30 04:05:20 +09001788 snprintf(sbuf, sizeof(sbuf), "%u", NAMESERVER_PORT);
Bernie Innocenti45238a12018-12-04 14:57:48 +09001789 for (int i = 0; i < numservers; i++) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001790 // The addrinfo structures allocated here are freed in free_nameservers_locked().
Bernie Innocentic165ce82018-10-16 23:35:28 +09001791 const addrinfo hints = {
1792 .ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM, .ai_flags = AI_NUMERICHOST};
1793 int rt = getaddrinfo_numeric(servers[i], sbuf, hints, &nsaddrinfo[i]);
Bernie Innocenti55864192018-08-30 04:05:20 +09001794 if (rt != 0) {
Bernie Innocenti45238a12018-12-04 14:57:48 +09001795 for (int j = 0; j < i; j++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001796 freeaddrinfo(nsaddrinfo[j]);
Bernie Innocenti55864192018-08-30 04:05:20 +09001797 }
chenbruce16adee42019-02-20 19:45:50 +08001798 LOG(INFO) << __func__ << ": getaddrinfo_numeric(" << servers[i]
1799 << ") = " << gai_strerror(rt);
Bernie Innocenti55864192018-08-30 04:05:20 +09001800 return EINVAL;
1801 }
1802 }
1803
Ken Chen2a429352018-12-22 21:46:55 +08001804 std::lock_guard guard(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001805
ckenb1a69a42018-12-01 17:45:18 +09001806 resolv_cache_info* cache_info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001807
Lorenzo Colittibb65ae22019-04-25 18:06:41 -07001808 if (cache_info == NULL) return ENONET;
Bernie Innocenti55864192018-08-30 04:05:20 +09001809
Lorenzo Colittibb65ae22019-04-25 18:06:41 -07001810 uint8_t old_max_samples = cache_info->params.max_samples;
1811 if (params != NULL) {
1812 cache_info->params = *params;
1813 } else {
1814 resolv_set_default_params(&cache_info->params);
Bernie Innocenti55864192018-08-30 04:05:20 +09001815 }
Lorenzo Colittibb65ae22019-04-25 18:06:41 -07001816 resolv_set_experiment_params(&cache_info->params);
1817 if (!resolv_is_nameservers_equal_locked(cache_info, servers, numservers)) {
1818 // free current before adding new
1819 free_nameservers_locked(cache_info);
1820 for (int i = 0; i < numservers; i++) {
1821 cache_info->nsaddrinfo[i] = nsaddrinfo[i];
1822 cache_info->nameservers[i] = strdup(servers[i]);
1823 LOG(INFO) << __func__ << ": netid = " << netid << ", addr = " << servers[i];
1824 }
1825 cache_info->nscount = numservers;
1826
1827 // Clear the NS statistics because the mapping to nameservers might have changed.
1828 res_cache_clear_stats_locked(cache_info);
1829
1830 // increment the revision id to ensure that sample state is not written back if the
1831 // servers change; in theory it would suffice to do so only if the servers or
1832 // max_samples actually change, in practice the overhead of checking is higher than the
1833 // cost, and overflows are unlikely
1834 ++cache_info->revision_id;
1835 } else {
1836 if (cache_info->params.max_samples != old_max_samples) {
1837 // If the maximum number of samples changes, the overhead of keeping the most recent
1838 // samples around is not considered worth the effort, so they are cleared instead.
1839 // All other parameters do not affect shared state: Changing these parameters does
1840 // not invalidate the samples, as they only affect aggregation and the conditions
1841 // under which servers are considered usable.
1842 res_cache_clear_stats_locked(cache_info);
1843 ++cache_info->revision_id;
1844 }
1845 for (int j = 0; j < numservers; j++) {
1846 freeaddrinfo(nsaddrinfo[j]);
1847 }
1848 }
1849
1850 // Always update the search paths, since determining whether they actually changed is
1851 // complex due to the zero-padding, and probably not worth the effort. Cache-flushing
1852 // however is not necessary, since the stored cache entries do contain the domain, not
1853 // just the host name.
1854 strlcpy(cache_info->defdname, domains, sizeof(cache_info->defdname));
1855 if ((cp = strchr(cache_info->defdname, '\n')) != NULL) *cp = '\0';
1856 LOG(INFO) << __func__ << ": domains=\"" << cache_info->defdname << "\"";
1857
1858 cp = cache_info->defdname;
1859 offset = cache_info->dnsrch_offset;
1860 while (offset < cache_info->dnsrch_offset + MAXDNSRCH) {
1861 while (*cp == ' ' || *cp == '\t') /* skip leading white space */
1862 cp++;
1863 if (*cp == '\0') /* stop if nothing more to do */
1864 break;
1865 *offset++ = cp - cache_info->defdname; /* record this search domain */
1866 while (*cp) { /* zero-terminate it */
1867 if (*cp == ' ' || *cp == '\t') {
1868 *cp++ = '\0';
1869 break;
1870 }
1871 cp++;
1872 }
1873 }
1874 *offset = -1; /* cache_info->dnsrch_offset has MAXDNSRCH+1 items */
Bernie Innocenti55864192018-08-30 04:05:20 +09001875
Bernie Innocenti55864192018-08-30 04:05:20 +09001876 return 0;
1877}
1878
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001879static int resolv_is_nameservers_equal_locked(resolv_cache_info* cache_info, const char** servers,
1880 int numservers) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001881 if (cache_info->nscount != numservers) {
1882 return 0;
1883 }
1884
1885 // Compare each name server against current name servers.
1886 // TODO: this is incorrect if the list of current or previous nameservers
1887 // contains duplicates. This does not really matter because the framework
1888 // filters out duplicates, but we should probably fix it. It's also
1889 // insensitive to the order of the nameservers; we should probably fix that
1890 // too.
1891 for (int i = 0; i < numservers; i++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001892 for (int j = 0;; j++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001893 if (j >= numservers) {
1894 return 0;
1895 }
1896 if (strcmp(cache_info->nameservers[i], servers[j]) == 0) {
1897 break;
1898 }
1899 }
1900 }
1901
1902 return 1;
1903}
1904
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001905static void free_nameservers_locked(resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001906 int i;
1907 for (i = 0; i < cache_info->nscount; i++) {
1908 free(cache_info->nameservers[i]);
1909 cache_info->nameservers[i] = NULL;
1910 if (cache_info->nsaddrinfo[i] != NULL) {
1911 freeaddrinfo(cache_info->nsaddrinfo[i]);
1912 cache_info->nsaddrinfo[i] = NULL;
1913 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001914 cache_info->nsstats[i].sample_count = cache_info->nsstats[i].sample_next = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +09001915 }
1916 cache_info->nscount = 0;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001917 res_cache_clear_stats_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001918 ++cache_info->revision_id;
1919}
1920
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001921void _resolv_populate_res_for_net(res_state statp) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001922 if (statp == NULL) {
1923 return;
1924 }
Ken Chenbab50142019-03-19 17:41:28 +08001925 LOG(INFO) << __func__ << ": netid=" << statp->netid;
Bernie Innocenti55864192018-08-30 04:05:20 +09001926
Ken Chen2a429352018-12-22 21:46:55 +08001927 std::lock_guard guard(cache_mutex);
ckenb1a69a42018-12-01 17:45:18 +09001928 resolv_cache_info* info = find_cache_info_locked(statp->netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001929 if (info != NULL) {
1930 int nserv;
1931 struct addrinfo* ai;
Bernie Innocenti55864192018-08-30 04:05:20 +09001932 for (nserv = 0; nserv < MAXNS; nserv++) {
1933 ai = info->nsaddrinfo[nserv];
1934 if (ai == NULL) {
1935 break;
1936 }
1937
1938 if ((size_t) ai->ai_addrlen <= sizeof(statp->_u._ext.ext->nsaddrs[0])) {
1939 if (statp->_u._ext.ext != NULL) {
1940 memcpy(&statp->_u._ext.ext->nsaddrs[nserv], ai->ai_addr, ai->ai_addrlen);
1941 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
1942 } else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001943 if ((size_t) ai->ai_addrlen <= sizeof(statp->nsaddr_list[0])) {
1944 memcpy(&statp->nsaddr_list[nserv], ai->ai_addr, ai->ai_addrlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001945 } else {
1946 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
1947 }
1948 }
1949 } else {
chenbruce16adee42019-02-20 19:45:50 +08001950 LOG(INFO) << __func__ << ": found too long addrlen";
Bernie Innocenti55864192018-08-30 04:05:20 +09001951 }
1952 }
1953 statp->nscount = nserv;
1954 // now do search domains. Note that we cache the offsets as this code runs alot
1955 // but the setting/offset-computer only runs when set/changed
1956 // WARNING: Don't use str*cpy() here, this string contains zeroes.
1957 memcpy(statp->defdname, info->defdname, sizeof(statp->defdname));
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001958 char** pp = statp->dnsrch;
1959 int* p = info->dnsrch_offset;
Bernie Innocenti55864192018-08-30 04:05:20 +09001960 while (pp < statp->dnsrch + MAXDNSRCH && *p != -1) {
1961 *pp++ = &statp->defdname[0] + *p++;
1962 }
1963 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001964}
1965
1966/* Resolver reachability statistics. */
1967
Bernie Innocenti189eb502018-10-01 23:10:18 +09001968static void _res_cache_add_stats_sample_locked(res_stats* stats, const res_sample* sample,
1969 int max_samples) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001970 // Note: This function expects max_samples > 0, otherwise a (harmless) modification of the
1971 // allocated but supposedly unused memory for samples[0] will happen
Ken Chenbab50142019-03-19 17:41:28 +08001972 LOG(INFO) << __func__ << ": adding sample to stats, next = " << unsigned(stats->sample_next)
1973 << ", count = " << unsigned(stats->sample_count);
Bernie Innocenti55864192018-08-30 04:05:20 +09001974 stats->samples[stats->sample_next] = *sample;
1975 if (stats->sample_count < max_samples) {
1976 ++stats->sample_count;
1977 }
1978 if (++stats->sample_next >= max_samples) {
1979 stats->sample_next = 0;
1980 }
1981}
1982
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001983static void res_cache_clear_stats_locked(resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001984 if (cache_info) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001985 for (int i = 0; i < MAXNS; ++i) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001986 cache_info->nsstats->sample_count = cache_info->nsstats->sample_next = 0;
1987 }
1988 }
1989}
1990
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001991int android_net_res_stats_get_info_for_net(unsigned netid, int* nscount,
1992 struct sockaddr_storage servers[MAXNS], int* dcount,
1993 char domains[MAXDNSRCH][MAXDNSRCHPATH],
Bernie Innocenti34de3ba2019-02-19 18:08:36 +09001994 res_params* params, struct res_stats stats[MAXNS],
Ken Chen2a429352018-12-22 21:46:55 +08001995 int* wait_for_pending_req_timeout_count) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001996 int revision_id = -1;
Ken Chen2a429352018-12-22 21:46:55 +08001997 std::lock_guard guard(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001998
ckenb1a69a42018-12-01 17:45:18 +09001999 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09002000 if (info) {
2001 if (info->nscount > MAXNS) {
chenbruce16adee42019-02-20 19:45:50 +08002002 LOG(INFO) << __func__ << ": nscount " << info->nscount << " > MAXNS " << MAXNS;
Bernie Innocenti55864192018-08-30 04:05:20 +09002003 errno = EFAULT;
2004 return -1;
2005 }
2006 int i;
2007 for (i = 0; i < info->nscount; i++) {
2008 // Verify that the following assumptions are held, failure indicates corruption:
2009 // - getaddrinfo() may never return a sockaddr > sockaddr_storage
2010 // - all addresses are valid
2011 // - there is only one address per addrinfo thanks to numeric resolution
2012 int addrlen = info->nsaddrinfo[i]->ai_addrlen;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002013 if (addrlen < (int) sizeof(struct sockaddr) || addrlen > (int) sizeof(servers[0])) {
chenbruce16adee42019-02-20 19:45:50 +08002014 LOG(INFO) << __func__ << ": nsaddrinfo[" << i << "].ai_addrlen == " << addrlen;
Bernie Innocenti55864192018-08-30 04:05:20 +09002015 errno = EMSGSIZE;
2016 return -1;
2017 }
2018 if (info->nsaddrinfo[i]->ai_addr == NULL) {
chenbruce16adee42019-02-20 19:45:50 +08002019 LOG(INFO) << __func__ << ": nsaddrinfo[" << i << "].ai_addr == NULL";
Bernie Innocenti55864192018-08-30 04:05:20 +09002020 errno = ENOENT;
2021 return -1;
2022 }
2023 if (info->nsaddrinfo[i]->ai_next != NULL) {
chenbruce16adee42019-02-20 19:45:50 +08002024 LOG(INFO) << __func__ << ": nsaddrinfo[" << i << "].ai_next != NULL";
Bernie Innocenti55864192018-08-30 04:05:20 +09002025 errno = ENOTUNIQ;
2026 return -1;
2027 }
2028 }
2029 *nscount = info->nscount;
2030 for (i = 0; i < info->nscount; i++) {
2031 memcpy(&servers[i], info->nsaddrinfo[i]->ai_addr, info->nsaddrinfo[i]->ai_addrlen);
2032 stats[i] = info->nsstats[i];
2033 }
2034 for (i = 0; i < MAXDNSRCH; i++) {
2035 const char* cur_domain = info->defdname + info->dnsrch_offset[i];
2036 // dnsrch_offset[i] can either be -1 or point to an empty string to indicate the end
2037 // of the search offsets. Checking for < 0 is not strictly necessary, but safer.
2038 // TODO: Pass in a search domain array instead of a string to
Bernie Innocenti189eb502018-10-01 23:10:18 +09002039 // resolv_set_nameservers_for_net() and make this double check unnecessary.
Bernie Innocenti55864192018-08-30 04:05:20 +09002040 if (info->dnsrch_offset[i] < 0 ||
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002041 ((size_t) info->dnsrch_offset[i]) >= sizeof(info->defdname) || !cur_domain[0]) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002042 break;
2043 }
2044 strlcpy(domains[i], cur_domain, MAXDNSRCHPATH);
2045 }
2046 *dcount = i;
2047 *params = info->params;
2048 revision_id = info->revision_id;
Ken Chen2a429352018-12-22 21:46:55 +08002049 *wait_for_pending_req_timeout_count = info->wait_for_pending_req_timeout_count;
Bernie Innocenti55864192018-08-30 04:05:20 +09002050 }
2051
Bernie Innocenti55864192018-08-30 04:05:20 +09002052 return revision_id;
2053}
2054
Luke Huang57b128d2019-07-23 16:04:12 -07002055std::vector<std::string> resolv_cache_dump_subsampling_map(unsigned netid) {
2056 using android::base::StringPrintf;
2057 std::lock_guard guard(cache_mutex);
2058 resolv_cache_info* cache_info = find_cache_info_locked(netid);
2059 if (cache_info == nullptr) return {};
2060 std::vector<std::string> result;
2061 for (const auto& pair : cache_info->dns_event_subsampling_map) {
2062 result.push_back(StringPrintf("%s:%d",
2063 (pair.first == DNSEVENT_SUBSAMPLING_MAP_DEFAULT_KEY)
2064 ? "default"
2065 : std::to_string(pair.first).c_str(),
2066 pair.second));
2067 }
2068 return result;
2069}
2070
2071// Decides whether an event should be sampled using a random number generator and
2072// a sampling factor derived from the netid and the return code.
2073//
2074// Returns the subsampling rate if the event should be sampled, or 0 if it should be discarded.
2075uint32_t resolv_cache_get_subsampling_denom(unsigned netid, int return_code) {
2076 std::lock_guard guard(cache_mutex);
2077 resolv_cache_info* cache_info = find_cache_info_locked(netid);
2078 if (cache_info == nullptr) return 0; // Don't log anything at all.
2079 const auto& subsampling_map = cache_info->dns_event_subsampling_map;
2080 auto search_returnCode = subsampling_map.find(return_code);
2081 uint32_t denom;
2082 if (search_returnCode != subsampling_map.end()) {
2083 denom = search_returnCode->second;
2084 } else {
2085 auto search_default = subsampling_map.find(DNSEVENT_SUBSAMPLING_MAP_DEFAULT_KEY);
2086 denom = (search_default == subsampling_map.end()) ? 0 : search_default->second;
2087 }
2088 return denom;
2089}
2090
Bernie Innocenti34de3ba2019-02-19 18:08:36 +09002091int resolv_cache_get_resolver_stats(unsigned netid, res_params* params, res_stats stats[MAXNS]) {
Ken Chen2a429352018-12-22 21:46:55 +08002092 std::lock_guard guard(cache_mutex);
ckenb1a69a42018-12-01 17:45:18 +09002093 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09002094 if (info) {
2095 memcpy(stats, info->nsstats, sizeof(info->nsstats));
2096 *params = info->params;
Ken Chen2a429352018-12-22 21:46:55 +08002097 return info->revision_id;
Bernie Innocenti55864192018-08-30 04:05:20 +09002098 }
2099
Ken Chen2a429352018-12-22 21:46:55 +08002100 return -1;
Bernie Innocenti55864192018-08-30 04:05:20 +09002101}
2102
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002103void _resolv_cache_add_resolver_stats_sample(unsigned netid, int revision_id, int ns,
Bernie Innocenti189eb502018-10-01 23:10:18 +09002104 const res_sample* sample, int max_samples) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002105 if (max_samples <= 0) return;
2106
Ken Chen2a429352018-12-22 21:46:55 +08002107 std::lock_guard guard(cache_mutex);
ckenb1a69a42018-12-01 17:45:18 +09002108 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09002109
2110 if (info && info->revision_id == revision_id) {
2111 _res_cache_add_stats_sample_locked(&info->nsstats[ns], sample, max_samples);
2112 }
Bernie Innocenti55864192018-08-30 04:05:20 +09002113}