blob: 756844c105ae69b389386ecc2da572c5d91e3737 [file] [log] [blame]
Bernie Innocenti318ed2d2018-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 Innocenti9f05f5e2018-09-12 23:20:10 +090029// NOTE: verbose logging MUST NOT be left enabled in production binaries.
30// It floods logs at high rate, and can leak privacy-sensitive information.
31constexpr bool kVerboseLogging = false;
32constexpr bool kDumpData = false;
33#define LOG_TAG "res_cache"
34
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090035#include <resolv.h>
36#include <stdarg.h>
37#include <stdio.h>
38#include <stdlib.h>
39#include <string.h>
40#include <time.h>
Ken Chen92bed612018-12-22 21:46:55 +080041#include <mutex>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090042
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +090043#include <arpa/inet.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090044#include <arpa/nameser.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090045#include <errno.h>
46#include <linux/if.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090047#include <net/if.h>
48#include <netdb.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090049
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +090050#include <android-base/logging.h>
Ken Chen92bed612018-12-22 21:46:55 +080051#include <android-base/thread_annotations.h>
Bernie Innocentiafaacf72018-08-30 07:34:37 +090052
Bernie Innocentiac18b122018-10-01 23:10:18 +090053#include "res_state_ext.h"
Bernie Innocentiafaacf72018-08-30 07:34:37 +090054#include "resolv_cache.h"
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090055#include "resolv_private.h"
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090056
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +090057#define VLOG if (!kVerboseLogging) {} else LOG(INFO)
58
59#ifndef RESOLV_ALLOW_VERBOSE_LOGGING
60static_assert(kVerboseLogging == false && kDumpData == false,
61 "Verbose logging floods logs at high-rate and exposes privacy-sensitive information. "
62 "Do not enable in release builds.");
63#endif
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090064
65/* This code implements a small and *simple* DNS resolver cache.
66 *
67 * It is only used to cache DNS answers for a time defined by the smallest TTL
68 * among the answer records in order to reduce DNS traffic. It is not supposed
69 * to be a full DNS cache, since we plan to implement that in the future in a
70 * dedicated process running on the system.
71 *
72 * Note that its design is kept simple very intentionally, i.e.:
73 *
74 * - it takes raw DNS query packet data as input, and returns raw DNS
75 * answer packet data as output
76 *
77 * (this means that two similar queries that encode the DNS name
78 * differently will be treated distinctly).
79 *
80 * the smallest TTL value among the answer records are used as the time
81 * to keep an answer in the cache.
82 *
83 * this is bad, but we absolutely want to avoid parsing the answer packets
84 * (and should be solved by the later full DNS cache process).
85 *
86 * - the implementation is just a (query-data) => (answer-data) hash table
87 * with a trivial least-recently-used expiration policy.
88 *
89 * Doing this keeps the code simple and avoids to deal with a lot of things
90 * that a full DNS cache is expected to do.
91 *
92 * The API is also very simple:
93 *
94 * - the client calls _resolv_cache_get() to obtain a handle to the cache.
95 * this will initialize the cache on first usage. the result can be NULL
96 * if the cache is disabled.
97 *
98 * - the client calls _resolv_cache_lookup() before performing a query
99 *
100 * if the function returns RESOLV_CACHE_FOUND, a copy of the answer data
101 * has been copied into the client-provided answer buffer.
102 *
103 * if the function returns RESOLV_CACHE_NOTFOUND, the client should perform
104 * a request normally, *then* call _resolv_cache_add() to add the received
105 * answer to the cache.
106 *
107 * if the function returns RESOLV_CACHE_UNSUPPORTED, the client should
108 * perform a request normally, and *not* call _resolv_cache_add()
109 *
110 * note that RESOLV_CACHE_UNSUPPORTED is also returned if the answer buffer
111 * is too short to accomodate the cached result.
112 */
113
114/* default number of entries kept in the cache. This value has been
115 * determined by browsing through various sites and counting the number
116 * of corresponding requests. Keep in mind that our framework is currently
117 * performing two requests per name lookup (one for IPv4, the other for IPv6)
118 *
119 * www.google.com 4
120 * www.ysearch.com 6
121 * www.amazon.com 8
122 * www.nytimes.com 22
123 * www.espn.com 28
124 * www.msn.com 28
125 * www.lemonde.fr 35
126 *
127 * (determined in 2009-2-17 from Paris, France, results may vary depending
128 * on location)
129 *
130 * most high-level websites use lots of media/ad servers with different names
131 * but these are generally reused when browsing through the site.
132 *
133 * As such, a value of 64 should be relatively comfortable at the moment.
134 *
135 * ******************************************
136 * * NOTE - this has changed.
137 * * 1) we've added IPv6 support so each dns query results in 2 responses
138 * * 2) we've made this a system-wide cache, so the cost is less (it's not
139 * * duplicated in each process) and the need is greater (more processes
140 * * making different requests).
141 * * Upping by 2x for IPv6
142 * * Upping by another 5x for the centralized nature
143 * *****************************************
144 */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900145#define CONFIG_MAX_ENTRIES (64 * 2 * 5)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900146
Bernie Innocenti9c575932018-09-07 21:10:25 +0900147/** BOUNDED BUFFER FORMATTING **/
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900148
149/* technical note:
150 *
151 * the following debugging routines are used to append data to a bounded
152 * buffer they take two parameters that are:
153 *
154 * - p : a pointer to the current cursor position in the buffer
155 * this value is initially set to the buffer's address.
156 *
157 * - end : the address of the buffer's limit, i.e. of the first byte
158 * after the buffer. this address should never be touched.
159 *
160 * IMPORTANT: it is assumed that end > buffer_address, i.e.
161 * that the buffer is at least one byte.
162 *
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900163 * the bprint_x() functions return the new value of 'p' after the data
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900164 * has been appended, and also ensure the following:
165 *
166 * - the returned value will never be strictly greater than 'end'
167 *
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900168 * - a return value equal to 'end' means that truncation occurred
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900169 * (in which case, end[-1] will be set to 0)
170 *
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900171 * - after returning from a bprint_x() function, the content of the buffer
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900172 * is always 0-terminated, even in the event of truncation.
173 *
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900174 * these conventions allow you to call bprint_x() functions multiple times and
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900175 * only check for truncation at the end of the sequence, as in:
176 *
177 * char buff[1000], *p = buff, *end = p + sizeof(buff);
178 *
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900179 * p = bprint_c(p, end, '"');
180 * p = bprint_s(p, end, my_string);
181 * p = bprint_c(p, end, '"');
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900182 *
183 * if (p >= end) {
184 * // buffer was too small
185 * }
186 *
187 * printf( "%s", buff );
188 */
189
Bernie Innocenti136af7b2018-10-01 20:46:20 +0900190/* Defaults used for initializing __res_params */
191
192// If successes * 100 / total_samples is less than this value, the server is considered failing
193#define SUCCESS_THRESHOLD 75
194// Sample validity in seconds. Set to -1 to disable skipping failing servers.
195#define NSSAMPLE_VALIDITY 1800
196
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900197/* add a char to a bounded buffer */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900198static char* bprint_c(char* p, char* end, int c) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900199 if (p < end) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900200 if (p + 1 == end)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900201 *p++ = 0;
202 else {
203 *p++ = (char) c;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900204 *p = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900205 }
206 }
207 return p;
208}
209
210/* add a sequence of bytes to a bounded buffer */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900211static char* bprint_b(char* p, char* end, const char* buf, int len) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900212 int avail = end - p;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900213
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900214 if (avail <= 0 || len <= 0) return p;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900215
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900216 if (avail > len) avail = len;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900217
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900218 memcpy(p, buf, avail);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900219 p += avail;
220
221 if (p < end)
222 p[0] = 0;
223 else
224 end[-1] = 0;
225
226 return p;
227}
228
229/* add a string to a bounded buffer */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900230static char* bprint_s(char* p, char* end, const char* str) {
231 return bprint_b(p, end, str, strlen(str));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900232}
233
234/* add a formatted string to a bounded buffer */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900235static char* bprint(char* p, char* end, const char* format, ...) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900236 int avail, n;
237 va_list args;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900238
239 avail = end - p;
240
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900241 if (avail <= 0) return p;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900242
243 va_start(args, format);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900244 n = vsnprintf(p, avail, format, args);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900245 va_end(args);
246
247 /* certain C libraries return -1 in case of truncation */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900248 if (n < 0 || n > avail) n = avail;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900249
250 p += n;
251 /* certain C libraries do not zero-terminate in case of truncation */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900252 if (p == end) p[-1] = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900253
254 return p;
255}
256
257/* add a hex value to a bounded buffer, up to 8 digits */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900258static char* bprint_hex(char* p, char* end, unsigned value, int numDigits) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900259 char text[sizeof(unsigned) * 2];
260 int nn = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900261
262 while (numDigits-- > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900263 text[nn++] = "0123456789abcdef"[(value >> (numDigits * 4)) & 15];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900264 }
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900265 return bprint_b(p, end, text, nn);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900266}
267
268/* add the hexadecimal dump of some memory area to a bounded buffer */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900269static char* bprint_hexdump(char* p, char* end, const uint8_t* data, int datalen) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900270 int lineSize = 16;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900271
272 while (datalen > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900273 int avail = datalen;
274 int nn;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900275
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900276 if (avail > lineSize) avail = lineSize;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900277
278 for (nn = 0; nn < avail; nn++) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900279 if (nn > 0) p = bprint_c(p, end, ' ');
280 p = bprint_hex(p, end, data[nn], 2);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900281 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900282 for (; nn < lineSize; nn++) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900283 p = bprint_s(p, end, " ");
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900284 }
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900285 p = bprint_s(p, end, " ");
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900286
287 for (nn = 0; nn < avail; nn++) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900288 int c = data[nn];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900289
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900290 if (c < 32 || c > 127) c = '.';
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900291
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900292 p = bprint_c(p, end, c);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900293 }
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900294 p = bprint_c(p, end, '\n');
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900295
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900296 data += avail;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900297 datalen -= avail;
298 }
299 return p;
300}
301
302/* dump the content of a query of packet to the log */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900303static void dump_bytes(const uint8_t* base, int len) {
304 if (!kDumpData) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900305
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900306 char buff[1024];
307 char *p = buff, *end = p + sizeof(buff);
308
309 p = bprint_hexdump(p, end, base, len);
310 VLOG << buff;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900311}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900312
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900313static time_t _time_now(void) {
314 struct timeval tv;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900315
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900316 gettimeofday(&tv, NULL);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900317 return tv.tv_sec;
318}
319
320/* reminder: the general format of a DNS packet is the following:
321 *
322 * HEADER (12 bytes)
323 * QUESTION (variable)
324 * ANSWER (variable)
325 * AUTHORITY (variable)
326 * ADDITIONNAL (variable)
327 *
328 * the HEADER is made of:
329 *
330 * ID : 16 : 16-bit unique query identification field
331 *
332 * QR : 1 : set to 0 for queries, and 1 for responses
333 * Opcode : 4 : set to 0 for queries
334 * AA : 1 : set to 0 for queries
335 * TC : 1 : truncation flag, will be set to 0 in queries
336 * RD : 1 : recursion desired
337 *
338 * RA : 1 : recursion available (0 in queries)
339 * Z : 3 : three reserved zero bits
340 * RCODE : 4 : response code (always 0=NOERROR in queries)
341 *
342 * QDCount: 16 : question count
343 * ANCount: 16 : Answer count (0 in queries)
344 * NSCount: 16: Authority Record count (0 in queries)
345 * ARCount: 16: Additionnal Record count (0 in queries)
346 *
347 * the QUESTION is made of QDCount Question Record (QRs)
348 * the ANSWER is made of ANCount RRs
349 * the AUTHORITY is made of NSCount RRs
350 * the ADDITIONNAL is made of ARCount RRs
351 *
352 * Each Question Record (QR) is made of:
353 *
354 * QNAME : variable : Query DNS NAME
355 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
356 * CLASS : 16 : class of query (IN=1)
357 *
358 * Each Resource Record (RR) is made of:
359 *
360 * NAME : variable : DNS NAME
361 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
362 * CLASS : 16 : class of query (IN=1)
363 * TTL : 32 : seconds to cache this RR (0=none)
364 * RDLENGTH: 16 : size of RDDATA in bytes
365 * RDDATA : variable : RR data (depends on TYPE)
366 *
367 * Each QNAME contains a domain name encoded as a sequence of 'labels'
368 * terminated by a zero. Each label has the following format:
369 *
370 * LEN : 8 : lenght of label (MUST be < 64)
371 * NAME : 8*LEN : label length (must exclude dots)
372 *
373 * A value of 0 in the encoding is interpreted as the 'root' domain and
374 * terminates the encoding. So 'www.android.com' will be encoded as:
375 *
376 * <3>www<7>android<3>com<0>
377 *
378 * Where <n> represents the byte with value 'n'
379 *
380 * Each NAME reflects the QNAME of the question, but has a slightly more
381 * complex encoding in order to provide message compression. This is achieved
382 * by using a 2-byte pointer, with format:
383 *
384 * TYPE : 2 : 0b11 to indicate a pointer, 0b01 and 0b10 are reserved
385 * OFFSET : 14 : offset to another part of the DNS packet
386 *
387 * The offset is relative to the start of the DNS packet and must point
388 * A pointer terminates the encoding.
389 *
390 * The NAME can be encoded in one of the following formats:
391 *
392 * - a sequence of simple labels terminated by 0 (like QNAMEs)
393 * - a single pointer
394 * - a sequence of simple labels terminated by a pointer
395 *
396 * A pointer shall always point to either a pointer of a sequence of
397 * labels (which can themselves be terminated by either a 0 or a pointer)
398 *
399 * The expanded length of a given domain name should not exceed 255 bytes.
400 *
401 * NOTE: we don't parse the answer packets, so don't need to deal with NAME
402 * records, only QNAMEs.
403 */
404
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900405#define DNS_HEADER_SIZE 12
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900406
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900407#define DNS_TYPE_A "\00\01" /* big-endian decimal 1 */
408#define DNS_TYPE_PTR "\00\014" /* big-endian decimal 12 */
409#define DNS_TYPE_MX "\00\017" /* big-endian decimal 15 */
410#define DNS_TYPE_AAAA "\00\034" /* big-endian decimal 28 */
411#define DNS_TYPE_ALL "\00\0377" /* big-endian decimal 255 */
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900412
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900413#define DNS_CLASS_IN "\00\01" /* big-endian decimal 1 */
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900414
415typedef struct {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900416 const uint8_t* base;
417 const uint8_t* end;
418 const uint8_t* cursor;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900419} DnsPacket;
420
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900421static void _dnsPacket_init(DnsPacket* packet, const uint8_t* buff, int bufflen) {
422 packet->base = buff;
423 packet->end = buff + bufflen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900424 packet->cursor = buff;
425}
426
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900427static void _dnsPacket_rewind(DnsPacket* packet) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900428 packet->cursor = packet->base;
429}
430
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900431static void _dnsPacket_skip(DnsPacket* packet, int count) {
432 const uint8_t* p = packet->cursor + count;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900433
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900434 if (p > packet->end) p = packet->end;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900435
436 packet->cursor = p;
437}
438
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900439static int _dnsPacket_readInt16(DnsPacket* packet) {
440 const uint8_t* p = packet->cursor;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900441
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900442 if (p + 2 > packet->end) return -1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900443
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900444 packet->cursor = p + 2;
445 return (p[0] << 8) | p[1];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900446}
447
Bernie Innocenti9c575932018-09-07 21:10:25 +0900448/** QUERY CHECKING **/
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900449
450/* check bytes in a dns packet. returns 1 on success, 0 on failure.
451 * the cursor is only advanced in the case of success
452 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900453static int _dnsPacket_checkBytes(DnsPacket* packet, int numBytes, const void* bytes) {
454 const uint8_t* p = packet->cursor;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900455
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900456 if (p + numBytes > packet->end) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900457
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900458 if (memcmp(p, bytes, numBytes) != 0) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900459
460 packet->cursor = p + numBytes;
461 return 1;
462}
463
464/* parse and skip a given QNAME stored in a query packet,
465 * from the current cursor position. returns 1 on success,
466 * or 0 for malformed data.
467 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900468static int _dnsPacket_checkQName(DnsPacket* packet) {
469 const uint8_t* p = packet->cursor;
470 const uint8_t* end = packet->end;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900471
472 for (;;) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900473 int c;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900474
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900475 if (p >= end) break;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900476
477 c = *p++;
478
479 if (c == 0) {
480 packet->cursor = p;
481 return 1;
482 }
483
484 /* we don't expect label compression in QNAMEs */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900485 if (c >= 64) break;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900486
487 p += c;
488 /* we rely on the bound check at the start
489 * of the loop here */
490 }
491 /* malformed data */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900492 VLOG << "malformed QNAME";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900493 return 0;
494}
495
496/* parse and skip a given QR stored in a packet.
497 * returns 1 on success, and 0 on failure
498 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900499static int _dnsPacket_checkQR(DnsPacket* packet) {
500 if (!_dnsPacket_checkQName(packet)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900501
502 /* TYPE must be one of the things we support */
503 if (!_dnsPacket_checkBytes(packet, 2, DNS_TYPE_A) &&
504 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_PTR) &&
505 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_MX) &&
506 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_AAAA) &&
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900507 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_ALL)) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900508 VLOG << "unsupported TYPE";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900509 return 0;
510 }
511 /* CLASS must be IN */
512 if (!_dnsPacket_checkBytes(packet, 2, DNS_CLASS_IN)) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900513 VLOG << "unsupported CLASS";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900514 return 0;
515 }
516
517 return 1;
518}
519
520/* check the header of a DNS Query packet, return 1 if it is one
521 * type of query we can cache, or 0 otherwise
522 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900523static int _dnsPacket_checkQuery(DnsPacket* packet) {
524 const uint8_t* p = packet->base;
525 int qdCount, anCount, dnCount, arCount;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900526
527 if (p + DNS_HEADER_SIZE > packet->end) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900528 VLOG << "query packet too small";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900529 return 0;
530 }
531
532 /* QR must be set to 0, opcode must be 0 and AA must be 0 */
533 /* RA, Z, and RCODE must be 0 */
534 if ((p[2] & 0xFC) != 0 || (p[3] & 0xCF) != 0) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900535 VLOG << "query packet flags unsupported";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900536 return 0;
537 }
538
539 /* Note that we ignore the TC, RD, CD, and AD bits here for the
540 * following reasons:
541 *
542 * - there is no point for a query packet sent to a server
543 * to have the TC bit set, but the implementation might
544 * set the bit in the query buffer for its own needs
545 * between a _resolv_cache_lookup and a
546 * _resolv_cache_add. We should not freak out if this
547 * is the case.
548 *
549 * - we consider that the result from a query might depend on
550 * the RD, AD, and CD bits, so these bits
551 * should be used to differentiate cached result.
552 *
553 * this implies that these bits are checked when hashing or
554 * comparing query packets, but not TC
555 */
556
557 /* ANCOUNT, DNCOUNT and ARCOUNT must be 0 */
558 qdCount = (p[4] << 8) | p[5];
559 anCount = (p[6] << 8) | p[7];
560 dnCount = (p[8] << 8) | p[9];
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900561 arCount = (p[10] << 8) | p[11];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900562
563 if (anCount != 0 || dnCount != 0 || arCount > 1) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900564 VLOG << "query packet contains non-query records";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900565 return 0;
566 }
567
568 if (qdCount == 0) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900569 VLOG << "query packet doesn't contain query record";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900570 return 0;
571 }
572
573 /* Check QDCOUNT QRs */
574 packet->cursor = p + DNS_HEADER_SIZE;
575
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900576 for (; qdCount > 0; qdCount--)
577 if (!_dnsPacket_checkQR(packet)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900578
579 return 1;
580}
581
Bernie Innocenti9c575932018-09-07 21:10:25 +0900582/** QUERY DEBUGGING **/
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900583static char* dnsPacket_bprintQName(DnsPacket* packet, char* bp, char* bend) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900584 const uint8_t* p = packet->cursor;
585 const uint8_t* end = packet->end;
586 int first = 1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900587
588 for (;;) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900589 int c;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900590
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900591 if (p >= end) break;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900592
593 c = *p++;
594
595 if (c == 0) {
596 packet->cursor = p;
597 return bp;
598 }
599
600 /* we don't expect label compression in QNAMEs */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900601 if (c >= 64) break;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900602
603 if (first)
604 first = 0;
605 else
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900606 bp = bprint_c(bp, bend, '.');
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900607
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900608 bp = bprint_b(bp, bend, (const char*) p, c);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900609
610 p += c;
611 /* we rely on the bound check at the start
612 * of the loop here */
613 }
614 /* malformed data */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900615 bp = bprint_s(bp, bend, "<MALFORMED>");
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900616 return bp;
617}
618
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900619static char* dnsPacket_bprintQR(DnsPacket* packet, char* p, char* end) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900620#define QQ(x) \
621 { DNS_TYPE_##x, #x }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900622 static const struct {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900623 const char* typeBytes;
624 const char* typeString;
625 } qTypes[] = {QQ(A), QQ(PTR), QQ(MX), QQ(AAAA), QQ(ALL), {NULL, NULL}};
626 int nn;
627 const char* typeString = NULL;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900628
629 /* dump QNAME */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900630 p = dnsPacket_bprintQName(packet, p, end);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900631
632 /* dump TYPE */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900633 p = bprint_s(p, end, " (");
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900634
635 for (nn = 0; qTypes[nn].typeBytes != NULL; nn++) {
636 if (_dnsPacket_checkBytes(packet, 2, qTypes[nn].typeBytes)) {
637 typeString = qTypes[nn].typeString;
638 break;
639 }
640 }
641
642 if (typeString != NULL)
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900643 p = bprint_s(p, end, typeString);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900644 else {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900645 int typeCode = _dnsPacket_readInt16(packet);
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900646 p = bprint(p, end, "UNKNOWN-%d", typeCode);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900647 }
648
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900649 p = bprint_c(p, end, ')');
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900650
651 /* skip CLASS */
652 _dnsPacket_skip(packet, 2);
653 return p;
654}
655
656/* this function assumes the packet has already been checked */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900657static char* dnsPacket_bprintQuery(DnsPacket* packet, char* p, char* end) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900658 int qdCount;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900659
660 if (packet->base[2] & 0x1) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900661 p = bprint_s(p, end, "RECURSIVE ");
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900662 }
663
664 _dnsPacket_skip(packet, 4);
665 qdCount = _dnsPacket_readInt16(packet);
666 _dnsPacket_skip(packet, 6);
667
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900668 for (; qdCount > 0; qdCount--) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900669 p = dnsPacket_bprintQR(packet, p, end);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900670 }
671 return p;
672}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900673
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900674/** QUERY HASHING SUPPORT
675 **
676 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKET HAS ALREADY
677 ** BEEN SUCCESFULLY CHECKED.
678 **/
679
680/* use 32-bit FNV hash function */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900681#define FNV_MULT 16777619U
682#define FNV_BASIS 2166136261U
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900683
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900684static unsigned _dnsPacket_hashBytes(DnsPacket* packet, int numBytes, unsigned hash) {
685 const uint8_t* p = packet->cursor;
686 const uint8_t* end = packet->end;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900687
688 while (numBytes > 0 && p < end) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900689 hash = hash * FNV_MULT ^ *p++;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900690 }
691 packet->cursor = p;
692 return hash;
693}
694
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900695static unsigned _dnsPacket_hashQName(DnsPacket* packet, unsigned hash) {
696 const uint8_t* p = packet->cursor;
697 const uint8_t* end = packet->end;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900698
699 for (;;) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900700 int c;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900701
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900702 if (p >= end) { /* should not happen */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900703 VLOG << __func__ << ": INTERNAL_ERROR: read-overflow";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900704 break;
705 }
706
707 c = *p++;
708
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900709 if (c == 0) break;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900710
711 if (c >= 64) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900712 VLOG << __func__ << ": INTERNAL_ERROR: malformed domain";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900713 break;
714 }
715 if (p + c >= end) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900716 VLOG << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900717 break;
718 }
719 while (c > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900720 hash = hash * FNV_MULT ^ *p++;
721 c -= 1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900722 }
723 }
724 packet->cursor = p;
725 return hash;
726}
727
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900728static unsigned _dnsPacket_hashQR(DnsPacket* packet, unsigned hash) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900729 hash = _dnsPacket_hashQName(packet, hash);
730 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TYPE and CLASS */
731 return hash;
732}
733
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900734static unsigned _dnsPacket_hashRR(DnsPacket* packet, unsigned hash) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900735 int rdlength;
736 hash = _dnsPacket_hashQR(packet, hash);
737 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TTL */
738 rdlength = _dnsPacket_readInt16(packet);
739 hash = _dnsPacket_hashBytes(packet, rdlength, hash); /* RDATA */
740 return hash;
741}
742
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900743static unsigned _dnsPacket_hashQuery(DnsPacket* packet) {
744 unsigned hash = FNV_BASIS;
745 int count, arcount;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900746 _dnsPacket_rewind(packet);
747
748 /* ignore the ID */
749 _dnsPacket_skip(packet, 2);
750
751 /* we ignore the TC bit for reasons explained in
752 * _dnsPacket_checkQuery().
753 *
754 * however we hash the RD bit to differentiate
755 * between answers for recursive and non-recursive
756 * queries.
757 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900758 hash = hash * FNV_MULT ^ (packet->base[2] & 1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900759
760 /* mark the first header byte as processed */
761 _dnsPacket_skip(packet, 1);
762
763 /* process the second header byte */
764 hash = _dnsPacket_hashBytes(packet, 1, hash);
765
766 /* read QDCOUNT */
767 count = _dnsPacket_readInt16(packet);
768
769 /* assume: ANcount and NScount are 0 */
770 _dnsPacket_skip(packet, 4);
771
772 /* read ARCOUNT */
773 arcount = _dnsPacket_readInt16(packet);
774
775 /* hash QDCOUNT QRs */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900776 for (; count > 0; count--) hash = _dnsPacket_hashQR(packet, hash);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900777
778 /* hash ARCOUNT RRs */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900779 for (; arcount > 0; arcount--) hash = _dnsPacket_hashRR(packet, hash);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900780
781 return hash;
782}
783
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900784/** QUERY COMPARISON
785 **
786 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKETS HAVE ALREADY
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900787 ** BEEN SUCCESSFULLY CHECKED.
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900788 **/
789
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900790static int _dnsPacket_isEqualDomainName(DnsPacket* pack1, DnsPacket* pack2) {
791 const uint8_t* p1 = pack1->cursor;
792 const uint8_t* end1 = pack1->end;
793 const uint8_t* p2 = pack2->cursor;
794 const uint8_t* end2 = pack2->end;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900795
796 for (;;) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900797 int c1, c2;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900798
799 if (p1 >= end1 || p2 >= end2) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900800 VLOG << __func__ << ": INTERNAL_ERROR: read-overflow";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900801 break;
802 }
803 c1 = *p1++;
804 c2 = *p2++;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900805 if (c1 != c2) break;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900806
807 if (c1 == 0) {
808 pack1->cursor = p1;
809 pack2->cursor = p2;
810 return 1;
811 }
812 if (c1 >= 64) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900813 VLOG << __func__ << ": INTERNAL_ERROR: malformed domain";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900814 break;
815 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900816 if ((p1 + c1 > end1) || (p2 + c1 > end2)) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900817 VLOG << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900818 break;
819 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900820 if (memcmp(p1, p2, c1) != 0) break;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900821 p1 += c1;
822 p2 += c1;
823 /* we rely on the bound checks at the start of the loop */
824 }
825 /* not the same, or one is malformed */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900826 VLOG << "different DN";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900827 return 0;
828}
829
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900830static int _dnsPacket_isEqualBytes(DnsPacket* pack1, DnsPacket* pack2, int numBytes) {
831 const uint8_t* p1 = pack1->cursor;
832 const uint8_t* p2 = pack2->cursor;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900833
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900834 if (p1 + numBytes > pack1->end || p2 + numBytes > pack2->end) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900835
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900836 if (memcmp(p1, p2, numBytes) != 0) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900837
838 pack1->cursor += numBytes;
839 pack2->cursor += numBytes;
840 return 1;
841}
842
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900843static int _dnsPacket_isEqualQR(DnsPacket* pack1, DnsPacket* pack2) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900844 /* compare domain name encoding + TYPE + CLASS */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900845 if (!_dnsPacket_isEqualDomainName(pack1, pack2) ||
846 !_dnsPacket_isEqualBytes(pack1, pack2, 2 + 2))
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900847 return 0;
848
849 return 1;
850}
851
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900852static int _dnsPacket_isEqualRR(DnsPacket* pack1, DnsPacket* pack2) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900853 int rdlength1, rdlength2;
854 /* compare query + TTL */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900855 if (!_dnsPacket_isEqualQR(pack1, pack2) || !_dnsPacket_isEqualBytes(pack1, pack2, 4)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900856
857 /* compare RDATA */
858 rdlength1 = _dnsPacket_readInt16(pack1);
859 rdlength2 = _dnsPacket_readInt16(pack2);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900860 if (rdlength1 != rdlength2 || !_dnsPacket_isEqualBytes(pack1, pack2, rdlength1)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900861
862 return 1;
863}
864
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900865static int _dnsPacket_isEqualQuery(DnsPacket* pack1, DnsPacket* pack2) {
866 int count1, count2, arcount1, arcount2;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900867
868 /* compare the headers, ignore most fields */
869 _dnsPacket_rewind(pack1);
870 _dnsPacket_rewind(pack2);
871
872 /* compare RD, ignore TC, see comment in _dnsPacket_checkQuery */
873 if ((pack1->base[2] & 1) != (pack2->base[2] & 1)) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900874 VLOG << "different RD";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900875 return 0;
876 }
877
878 if (pack1->base[3] != pack2->base[3]) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900879 VLOG << "different CD or AD";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900880 return 0;
881 }
882
883 /* mark ID and header bytes as compared */
884 _dnsPacket_skip(pack1, 4);
885 _dnsPacket_skip(pack2, 4);
886
887 /* compare QDCOUNT */
888 count1 = _dnsPacket_readInt16(pack1);
889 count2 = _dnsPacket_readInt16(pack2);
890 if (count1 != count2 || count1 < 0) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900891 VLOG << "different QDCOUNT";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900892 return 0;
893 }
894
895 /* assume: ANcount and NScount are 0 */
896 _dnsPacket_skip(pack1, 4);
897 _dnsPacket_skip(pack2, 4);
898
899 /* compare ARCOUNT */
900 arcount1 = _dnsPacket_readInt16(pack1);
901 arcount2 = _dnsPacket_readInt16(pack2);
902 if (arcount1 != arcount2 || arcount1 < 0) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900903 VLOG << "different ARCOUNT";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900904 return 0;
905 }
906
907 /* compare the QDCOUNT QRs */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900908 for (; count1 > 0; count1--) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900909 if (!_dnsPacket_isEqualQR(pack1, pack2)) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900910 VLOG << "different QR";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900911 return 0;
912 }
913 }
914
915 /* compare the ARCOUNT RRs */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900916 for (; arcount1 > 0; arcount1--) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900917 if (!_dnsPacket_isEqualRR(pack1, pack2)) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900918 VLOG << "different additional RR";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900919 return 0;
920 }
921 }
922 return 1;
923}
924
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900925/* cache entry. for simplicity, 'hash' and 'hlink' are inlined in this
926 * structure though they are conceptually part of the hash table.
927 *
928 * similarly, mru_next and mru_prev are part of the global MRU list
929 */
930typedef struct Entry {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900931 unsigned int hash; /* hash value */
932 struct Entry* hlink; /* next in collision chain */
933 struct Entry* mru_prev;
934 struct Entry* mru_next;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900935
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900936 const uint8_t* query;
937 int querylen;
938 const uint8_t* answer;
939 int answerlen;
940 time_t expires; /* time_t when the entry isn't valid any more */
941 int id; /* for debugging purpose */
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900942} Entry;
943
Bernie Innocenti9c575932018-09-07 21:10:25 +0900944/*
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900945 * Find the TTL for a negative DNS result. This is defined as the minimum
946 * of the SOA records TTL and the MINIMUM-TTL field (RFC-2308).
947 *
948 * Return 0 if not found.
949 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900950static u_long answer_getNegativeTTL(ns_msg handle) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900951 int n, nscount;
952 u_long result = 0;
953 ns_rr rr;
954
955 nscount = ns_msg_count(handle, ns_s_ns);
956 for (n = 0; n < nscount; n++) {
957 if ((ns_parserr(&handle, ns_s_ns, n, &rr) == 0) && (ns_rr_type(rr) == ns_t_soa)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900958 const u_char* rdata = ns_rr_rdata(rr); // find the data
959 const u_char* edata = rdata + ns_rr_rdlen(rr); // add the len to find the end
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900960 int len;
961 u_long ttl, rec_result = ns_rr_ttl(rr);
962
963 // find the MINIMUM-TTL field from the blob of binary data for this record
964 // skip the server name
965 len = dn_skipname(rdata, edata);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900966 if (len == -1) continue; // error skipping
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900967 rdata += len;
968
969 // skip the admin name
970 len = dn_skipname(rdata, edata);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900971 if (len == -1) continue; // error skipping
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900972 rdata += len;
973
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900974 if (edata - rdata != 5 * NS_INT32SZ) continue;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900975 // skip: serial number + refresh interval + retry interval + expiry
976 rdata += NS_INT32SZ * 4;
977 // finally read the MINIMUM TTL
978 ttl = ns_get32(rdata);
979 if (ttl < rec_result) {
980 rec_result = ttl;
981 }
982 // Now that the record is read successfully, apply the new min TTL
983 if (n == 0 || rec_result < result) {
984 result = rec_result;
985 }
986 }
987 }
988 return result;
989}
990
Bernie Innocenti9c575932018-09-07 21:10:25 +0900991/*
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900992 * Parse the answer records and find the appropriate
993 * smallest TTL among the records. This might be from
994 * the answer records if found or from the SOA record
995 * if it's a negative result.
996 *
997 * The returned TTL is the number of seconds to
998 * keep the answer in the cache.
999 *
1000 * In case of parse error zero (0) is returned which
1001 * indicates that the answer shall not be cached.
1002 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001003static u_long answer_getTTL(const void* answer, int answerlen) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001004 ns_msg handle;
1005 int ancount, n;
1006 u_long result, ttl;
1007 ns_rr rr;
1008
1009 result = 0;
Bernie Innocenti9c575932018-09-07 21:10:25 +09001010 if (ns_initparse((const uint8_t*) answer, answerlen, &handle) >= 0) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001011 // get number of answer records
1012 ancount = ns_msg_count(handle, ns_s_an);
1013
1014 if (ancount == 0) {
1015 // a response with no answers? Cache this negative result.
1016 result = answer_getNegativeTTL(handle);
1017 } else {
1018 for (n = 0; n < ancount; n++) {
1019 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
1020 ttl = ns_rr_ttl(rr);
1021 if (n == 0 || ttl < result) {
1022 result = ttl;
1023 }
1024 } else {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001025 VLOG << "ns_parserr failed ancount no = "
1026 << n << ". errno = " << strerror(errno);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001027 }
1028 }
1029 }
1030 } else {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001031 VLOG << "ns_initparse failed: " << strerror(errno);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001032 }
1033
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001034 VLOG << "TTL = " << result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001035 return result;
1036}
1037
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001038static void entry_free(Entry* e) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001039 /* everything is allocated in a single memory block */
1040 if (e) {
1041 free(e);
1042 }
1043}
1044
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001045static void entry_mru_remove(Entry* e) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001046 e->mru_prev->mru_next = e->mru_next;
1047 e->mru_next->mru_prev = e->mru_prev;
1048}
1049
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001050static void entry_mru_add(Entry* e, Entry* list) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001051 Entry* first = list->mru_next;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001052
1053 e->mru_next = first;
1054 e->mru_prev = list;
1055
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001056 list->mru_next = e;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001057 first->mru_prev = e;
1058}
1059
1060/* compute the hash of a given entry, this is a hash of most
1061 * data in the query (key) */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001062static unsigned entry_hash(const Entry* e) {
1063 DnsPacket pack[1];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001064
1065 _dnsPacket_init(pack, e->query, e->querylen);
1066 return _dnsPacket_hashQuery(pack);
1067}
1068
1069/* initialize an Entry as a search key, this also checks the input query packet
1070 * returns 1 on success, or 0 in case of unsupported/malformed data */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001071static int entry_init_key(Entry* e, const void* query, int querylen) {
1072 DnsPacket pack[1];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001073
1074 memset(e, 0, sizeof(*e));
1075
Bernie Innocenti9c575932018-09-07 21:10:25 +09001076 e->query = (const uint8_t*) query;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001077 e->querylen = querylen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001078 e->hash = entry_hash(e);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001079
Bernie Innocenti9c575932018-09-07 21:10:25 +09001080 _dnsPacket_init(pack, e->query, e->querylen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001081
1082 return _dnsPacket_checkQuery(pack);
1083}
1084
1085/* allocate a new entry as a cache node */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001086static Entry* entry_alloc(const Entry* init, const void* answer, int answerlen) {
1087 Entry* e;
1088 int size;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001089
1090 size = sizeof(*e) + init->querylen + answerlen;
Bernie Innocenti9c575932018-09-07 21:10:25 +09001091 e = (Entry*) calloc(size, 1);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001092 if (e == NULL) return e;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001093
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001094 e->hash = init->hash;
1095 e->query = (const uint8_t*) (e + 1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001096 e->querylen = init->querylen;
1097
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001098 memcpy((char*) e->query, init->query, e->querylen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001099
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001100 e->answer = e->query + e->querylen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001101 e->answerlen = answerlen;
1102
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001103 memcpy((char*) e->answer, answer, e->answerlen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001104
1105 return e;
1106}
1107
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001108static int entry_equals(const Entry* e1, const Entry* e2) {
1109 DnsPacket pack1[1], pack2[1];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001110
1111 if (e1->querylen != e2->querylen) {
1112 return 0;
1113 }
1114 _dnsPacket_init(pack1, e1->query, e1->querylen);
1115 _dnsPacket_init(pack2, e2->query, e2->querylen);
1116
1117 return _dnsPacket_isEqualQuery(pack1, pack2);
1118}
1119
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001120/* We use a simple hash table with external collision lists
1121 * for simplicity, the hash-table fields 'hash' and 'hlink' are
1122 * inlined in the Entry structure.
1123 */
1124
1125/* Maximum time for a thread to wait for an pending request */
Ken Chen92bed612018-12-22 21:46:55 +08001126constexpr int PENDING_REQUEST_TIMEOUT = 20;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001127
1128typedef struct resolv_cache {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001129 int max_entries;
1130 int num_entries;
1131 Entry mru_list;
1132 int last_id;
1133 Entry* entries;
Ken Chen92bed612018-12-22 21:46:55 +08001134 struct pending_req_info {
1135 unsigned int hash;
1136 struct pending_req_info* next;
1137 } pending_requests;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001138} Cache;
1139
1140struct resolv_cache_info {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001141 unsigned netid;
1142 Cache* cache;
1143 struct resolv_cache_info* next;
1144 int nscount;
1145 char* nameservers[MAXNS];
1146 struct addrinfo* nsaddrinfo[MAXNS];
1147 int revision_id; // # times the nameservers have been replaced
1148 struct __res_params params;
Bernie Innocentiac18b122018-10-01 23:10:18 +09001149 struct res_stats nsstats[MAXNS];
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001150 char defdname[MAXDNSRCHPATH];
1151 int dnsrch_offset[MAXDNSRCH + 1]; // offsets into defdname
Ken Chen92bed612018-12-22 21:46:55 +08001152 int wait_for_pending_req_timeout_count;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001153};
1154
Ken Chen92bed612018-12-22 21:46:55 +08001155// A helper class for the Clang Thread Safety Analysis to deal with
1156// std::unique_lock.
1157class SCOPED_CAPABILITY ScopedAssumeLocked {
1158 public:
1159 ScopedAssumeLocked(std::mutex& mutex) ACQUIRE(mutex) {}
1160 ~ScopedAssumeLocked() RELEASE() {}
1161};
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001162
Ken Chen92bed612018-12-22 21:46:55 +08001163// lock protecting everything in the resolve_cache_info structs (next ptr, etc)
1164static std::mutex cache_mutex;
1165static std::condition_variable cv;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001166
1167/* gets cache associated with a network, or NULL if none exists */
Ken Chen92bed612018-12-22 21:46:55 +08001168static struct resolv_cache* find_named_cache_locked(unsigned netid) REQUIRES(cache_mutex);
1169static resolv_cache* get_res_cache_for_net_locked(unsigned netid) REQUIRES(cache_mutex);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001170
Ken Chen92bed612018-12-22 21:46:55 +08001171static void cache_flush_pending_requests_locked(struct resolv_cache* cache) {
1172 resolv_cache::pending_req_info *ri, *tmp;
1173 if (!cache) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001174
Ken Chen92bed612018-12-22 21:46:55 +08001175 ri = cache->pending_requests.next;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001176
Ken Chen92bed612018-12-22 21:46:55 +08001177 while (ri) {
1178 tmp = ri;
1179 ri = ri->next;
1180 free(tmp);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001181 }
1182
Ken Chen92bed612018-12-22 21:46:55 +08001183 cache->pending_requests.next = NULL;
1184 cv.notify_all();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001185}
1186
Ken Chen92bed612018-12-22 21:46:55 +08001187// Return true - if there is a pending request in |cache| matching |key|.
1188// Return false - if no pending request is found matching the key. Optionally
1189// link a new one if parameter append_if_not_found is true.
1190static bool cache_has_pending_request_locked(resolv_cache* cache, const Entry* key,
1191 bool append_if_not_found) {
1192 if (!cache || !key) return false;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001193
Ken Chen92bed612018-12-22 21:46:55 +08001194 resolv_cache::pending_req_info* ri = cache->pending_requests.next;
1195 resolv_cache::pending_req_info* prev = &cache->pending_requests;
1196 while (ri) {
1197 if (ri->hash == key->hash) {
1198 return true;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001199 }
Ken Chen92bed612018-12-22 21:46:55 +08001200 prev = ri;
1201 ri = ri->next;
1202 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001203
Ken Chen92bed612018-12-22 21:46:55 +08001204 if (append_if_not_found) {
1205 ri = (resolv_cache::pending_req_info*)calloc(1, sizeof(resolv_cache::pending_req_info));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001206 if (ri) {
Ken Chen92bed612018-12-22 21:46:55 +08001207 ri->hash = key->hash;
1208 prev->next = ri;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001209 }
1210 }
Ken Chen92bed612018-12-22 21:46:55 +08001211 return false;
1212}
1213
1214// Notify all threads that the cache entry |key| has become available
1215static void _cache_notify_waiting_tid_locked(struct resolv_cache* cache, const Entry* key) {
1216 if (!cache || !key) return;
1217
1218 resolv_cache::pending_req_info* ri = cache->pending_requests.next;
1219 resolv_cache::pending_req_info* prev = &cache->pending_requests;
1220 while (ri) {
1221 if (ri->hash == key->hash) {
1222 // remove item from list and destroy
1223 prev->next = ri->next;
1224 free(ri);
1225 cv.notify_all();
1226 return;
1227 }
1228 prev = ri;
1229 ri = ri->next;
1230 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001231}
1232
Luke Huangba7bef92018-12-26 16:53:03 +08001233void _resolv_cache_query_failed(unsigned netid, const void* query, int querylen, uint32_t flags) {
1234 // We should not notify with these flags.
1235 if (flags & (ANDROID_RESOLV_NO_CACHE_STORE | ANDROID_RESOLV_NO_CACHE_LOOKUP)) {
1236 return;
1237 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001238 Entry key[1];
1239 Cache* cache;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001240
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001241 if (!entry_init_key(key, query, querylen)) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001242
Ken Chen92bed612018-12-22 21:46:55 +08001243 std::lock_guard guard(cache_mutex);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001244
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001245 cache = find_named_cache_locked(netid);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001246
1247 if (cache) {
1248 _cache_notify_waiting_tid_locked(cache, key);
1249 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001250}
1251
Bernie Innocenti69906322018-12-18 19:53:42 +09001252static void cache_flush_locked(Cache* cache) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001253 int nn;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001254
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001255 for (nn = 0; nn < cache->max_entries; nn++) {
1256 Entry** pnode = (Entry**) &cache->entries[nn];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001257
1258 while (*pnode != NULL) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001259 Entry* node = *pnode;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001260 *pnode = node->hlink;
1261 entry_free(node);
1262 }
1263 }
1264
1265 // flush pending request
Ken Chen92bed612018-12-22 21:46:55 +08001266 cache_flush_pending_requests_locked(cache);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001267
1268 cache->mru_list.mru_next = cache->mru_list.mru_prev = &cache->mru_list;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001269 cache->num_entries = 0;
1270 cache->last_id = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001271
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001272 VLOG << "*** DNS CACHE FLUSHED ***";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001273}
1274
Ken Chen92bed612018-12-22 21:46:55 +08001275static resolv_cache* resolv_cache_create() {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001276 struct resolv_cache* cache;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001277
Bernie Innocenti9c575932018-09-07 21:10:25 +09001278 cache = (struct resolv_cache*) calloc(sizeof(*cache), 1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001279 if (cache) {
nuccachen159bfae2018-11-29 17:41:12 +08001280 cache->max_entries = CONFIG_MAX_ENTRIES;
Bernie Innocenti9c575932018-09-07 21:10:25 +09001281 cache->entries = (Entry*) calloc(sizeof(*cache->entries), cache->max_entries);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001282 if (cache->entries) {
1283 cache->mru_list.mru_prev = cache->mru_list.mru_next = &cache->mru_list;
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001284 VLOG << __func__ << ": cache created";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001285 } else {
1286 free(cache);
1287 cache = NULL;
1288 }
1289 }
1290 return cache;
1291}
1292
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001293static void dump_query(const uint8_t* query, int querylen) {
1294 if (!kVerboseLogging) return;
1295
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001296 char temp[256], *p = temp, *end = p + sizeof(temp);
1297 DnsPacket pack[1];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001298
1299 _dnsPacket_init(pack, query, querylen);
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001300 p = dnsPacket_bprintQuery(pack, p, end);
1301 VLOG << temp;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001302}
1303
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001304static void cache_dump_mru(Cache* cache) {
1305 if (!kVerboseLogging) return;
1306
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001307 char temp[512], *p = temp, *end = p + sizeof(temp);
1308 Entry* e;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001309
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001310 p = bprint(temp, end, "MRU LIST (%2d): ", cache->num_entries);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001311 for (e = cache->mru_list.mru_next; e != &cache->mru_list; e = e->mru_next)
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001312 p = bprint(p, end, " %d", e->id);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001313
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001314 VLOG << temp;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001315}
1316
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001317// TODO: Rewrite to avoid creating a file in /data as temporary buffer (WAT).
1318static void dump_answer(const u_char* answer, int answerlen) {
1319 if (!kVerboseLogging) return;
1320
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001321 res_state statep;
1322 FILE* fp;
1323 char* buf;
1324 int fileLen;
1325
1326 fp = fopen("/data/reslog.txt", "w+e");
1327 if (fp != NULL) {
Bernie Innocenti2e8540b2018-09-26 11:52:04 +09001328 statep = res_get_state();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001329
1330 res_pquery(statep, answer, answerlen, fp);
1331
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001332 // Get file length
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001333 fseek(fp, 0, SEEK_END);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001334 fileLen = ftell(fp);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001335 fseek(fp, 0, SEEK_SET);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001336 buf = (char*) malloc(fileLen + 1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001337 if (buf != NULL) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001338 // Read file contents into buffer
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001339 fread(buf, fileLen, 1, fp);
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001340 VLOG << buf;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001341 free(buf);
1342 }
1343 fclose(fp);
1344 remove("/data/reslog.txt");
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001345 } else {
1346 errno = 0; // else debug is introducing error signals
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001347 VLOG << __func__ << ": can't open file";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001348 }
1349}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001350
1351/* This function tries to find a key within the hash table
1352 * In case of success, it will return a *pointer* to the hashed key.
1353 * In case of failure, it will return a *pointer* to NULL
1354 *
1355 * So, the caller must check '*result' to check for success/failure.
1356 *
1357 * The main idea is that the result can later be used directly in
1358 * calls to _resolv_cache_add or _resolv_cache_remove as the 'lookup'
1359 * parameter. This makes the code simpler and avoids re-searching
1360 * for the key position in the htable.
1361 *
1362 * The result of a lookup_p is only valid until you alter the hash
1363 * table.
1364 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001365static Entry** _cache_lookup_p(Cache* cache, Entry* key) {
1366 int index = key->hash % cache->max_entries;
1367 Entry** pnode = (Entry**) &cache->entries[index];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001368
1369 while (*pnode != NULL) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001370 Entry* node = *pnode;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001371
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001372 if (node == NULL) break;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001373
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001374 if (node->hash == key->hash && entry_equals(node, key)) break;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001375
1376 pnode = &node->hlink;
1377 }
1378 return pnode;
1379}
1380
1381/* Add a new entry to the hash table. 'lookup' must be the
1382 * result of an immediate previous failed _lookup_p() call
1383 * (i.e. with *lookup == NULL), and 'e' is the pointer to the
1384 * newly created entry
1385 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001386static void _cache_add_p(Cache* cache, Entry** lookup, Entry* e) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001387 *lookup = e;
1388 e->id = ++cache->last_id;
1389 entry_mru_add(e, &cache->mru_list);
1390 cache->num_entries += 1;
1391
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001392 VLOG << __func__ << ": entry " << e->id << " added (count=" << cache->num_entries << ")";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001393}
1394
1395/* Remove an existing entry from the hash table,
1396 * 'lookup' must be the result of an immediate previous
1397 * and succesful _lookup_p() call.
1398 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001399static void _cache_remove_p(Cache* cache, Entry** lookup) {
1400 Entry* e = *lookup;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001401
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001402 VLOG << __func__ << ": entry " << e->id << " removed (count=" << cache->num_entries - 1 << ")";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001403
1404 entry_mru_remove(e);
1405 *lookup = e->hlink;
1406 entry_free(e);
1407 cache->num_entries -= 1;
1408}
1409
1410/* Remove the oldest entry from the hash table.
1411 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001412static void _cache_remove_oldest(Cache* cache) {
1413 Entry* oldest = cache->mru_list.mru_prev;
1414 Entry** lookup = _cache_lookup_p(cache, oldest);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001415
1416 if (*lookup == NULL) { /* should not happen */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001417 VLOG << __func__ << ": OLDEST NOT IN HTABLE ?";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001418 return;
1419 }
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001420 VLOG << "Cache full - removing oldest";
1421 dump_query(oldest->query, oldest->querylen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001422 _cache_remove_p(cache, lookup);
1423}
1424
1425/* Remove all expired entries from the hash table.
1426 */
1427static void _cache_remove_expired(Cache* cache) {
1428 Entry* e;
1429 time_t now = _time_now();
1430
1431 for (e = cache->mru_list.mru_next; e != &cache->mru_list;) {
1432 // Entry is old, remove
1433 if (now >= e->expires) {
1434 Entry** lookup = _cache_lookup_p(cache, e);
1435 if (*lookup == NULL) { /* should not happen */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001436 VLOG << __func__ << ": ENTRY NOT IN HTABLE ?";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001437 return;
1438 }
1439 e = e->mru_next;
1440 _cache_remove_p(cache, lookup);
1441 } else {
1442 e = e->mru_next;
1443 }
1444 }
1445}
1446
Ken Chen92bed612018-12-22 21:46:55 +08001447// gets a resolv_cache_info associated with a network, or NULL if not found
1448static resolv_cache_info* find_cache_info_locked(unsigned netid) REQUIRES(cache_mutex);
1449
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001450ResolvCacheStatus _resolv_cache_lookup(unsigned netid, const void* query, int querylen,
Luke Huangba7bef92018-12-26 16:53:03 +08001451 void* answer, int answersize, int* answerlen,
1452 uint32_t flags) {
1453 if (flags & ANDROID_RESOLV_NO_CACHE_LOOKUP) {
1454 return RESOLV_CACHE_SKIP;
1455 }
Ken Chen92bed612018-12-22 21:46:55 +08001456 Entry key;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001457 Entry** lookup;
1458 Entry* e;
1459 time_t now;
1460 Cache* cache;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001461
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001462 VLOG << __func__ << ": lookup";
1463 dump_query((u_char*) query, querylen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001464
1465 /* we don't cache malformed queries */
Ken Chen92bed612018-12-22 21:46:55 +08001466 if (!entry_init_key(&key, query, querylen)) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001467 VLOG << __func__ << ": unsupported query";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001468 return RESOLV_CACHE_UNSUPPORTED;
1469 }
1470 /* lookup cache */
Ken Chen92bed612018-12-22 21:46:55 +08001471 std::unique_lock lock(cache_mutex);
1472 ScopedAssumeLocked assume_lock(cache_mutex);
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001473 cache = find_named_cache_locked(netid);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001474 if (cache == NULL) {
Ken Chen92bed612018-12-22 21:46:55 +08001475 return RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001476 }
1477
1478 /* see the description of _lookup_p to understand this.
1479 * the function always return a non-NULL pointer.
1480 */
Ken Chen92bed612018-12-22 21:46:55 +08001481 lookup = _cache_lookup_p(cache, &key);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001482 e = *lookup;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001483
1484 if (e == NULL) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001485 VLOG << "NOT IN CACHE";
Luke Huangba7bef92018-12-26 16:53:03 +08001486 // If it is no-cache-store mode, we won't wait for possible query.
1487 if (flags & ANDROID_RESOLV_NO_CACHE_STORE) {
Ken Chen92bed612018-12-22 21:46:55 +08001488 return RESOLV_CACHE_SKIP;
Luke Huangba7bef92018-12-26 16:53:03 +08001489 }
Ken Chen92bed612018-12-22 21:46:55 +08001490
1491 if (!cache_has_pending_request_locked(cache, &key, true)) {
1492 return RESOLV_CACHE_NOTFOUND;
1493
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001494 } else {
Ken Chen92bed612018-12-22 21:46:55 +08001495 VLOG << "Waiting for previous request";
1496 // wait until (1) timeout OR
1497 // (2) cv is notified AND no pending request matching the |key|
1498 // (cv notifier should delete pending request before sending notification.)
1499 bool ret = cv.wait_for(lock, std::chrono::seconds(PENDING_REQUEST_TIMEOUT),
1500 [netid, &cache, &key]() REQUIRES(cache_mutex) {
1501 // Must update cache as it could have been deleted
1502 cache = find_named_cache_locked(netid);
1503 return !cache_has_pending_request_locked(cache, &key, false);
1504 });
1505 if (ret == false) {
1506 resolv_cache_info* info = find_cache_info_locked(netid);
1507 if (info != NULL) {
1508 info->wait_for_pending_req_timeout_count++;
1509 }
1510 }
1511 lookup = _cache_lookup_p(cache, &key);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001512 e = *lookup;
1513 if (e == NULL) {
Ken Chen92bed612018-12-22 21:46:55 +08001514 return RESOLV_CACHE_NOTFOUND;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001515 }
1516 }
1517 }
1518
1519 now = _time_now();
1520
1521 /* remove stale entries here */
1522 if (now >= e->expires) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001523 VLOG << " NOT IN CACHE (STALE ENTRY " << *lookup << "DISCARDED)";
1524 dump_query(e->query, e->querylen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001525 _cache_remove_p(cache, lookup);
Ken Chen92bed612018-12-22 21:46:55 +08001526 return RESOLV_CACHE_NOTFOUND;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001527 }
1528
1529 *answerlen = e->answerlen;
1530 if (e->answerlen > answersize) {
1531 /* NOTE: we return UNSUPPORTED if the answer buffer is too short */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001532 VLOG << " ANSWER TOO LONG";
Ken Chen92bed612018-12-22 21:46:55 +08001533 return RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001534 }
1535
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001536 memcpy(answer, e->answer, e->answerlen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001537
1538 /* bump up this entry to the top of the MRU list */
1539 if (e != cache->mru_list.mru_next) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001540 entry_mru_remove(e);
1541 entry_mru_add(e, &cache->mru_list);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001542 }
1543
Ken Chen92bed612018-12-22 21:46:55 +08001544 VLOG << " FOUND IN CACHE entry=" << e;
1545 return RESOLV_CACHE_FOUND;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001546}
1547
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001548void _resolv_cache_add(unsigned netid, const void* query, int querylen, const void* answer,
1549 int answerlen) {
1550 Entry key[1];
1551 Entry* e;
1552 Entry** lookup;
1553 u_long ttl;
1554 Cache* cache = NULL;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001555
1556 /* don't assume that the query has already been cached
1557 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001558 if (!entry_init_key(key, query, querylen)) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001559 VLOG << __func__ << ": passed invalid query?";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001560 return;
1561 }
1562
Ken Chen92bed612018-12-22 21:46:55 +08001563 std::lock_guard guard(cache_mutex);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001564
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001565 cache = find_named_cache_locked(netid);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001566 if (cache == NULL) {
Ken Chen92bed612018-12-22 21:46:55 +08001567 return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001568 }
1569
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001570 VLOG << __func__ << ": query:";
1571 dump_query((u_char*) query, querylen);
1572 dump_answer((u_char*) answer, answerlen);
1573 if (kDumpData) {
1574 VLOG << "answer:";
1575 dump_bytes((u_char*) answer, answerlen);
1576 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001577
1578 lookup = _cache_lookup_p(cache, key);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001579 e = *lookup;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001580
1581 if (e != NULL) { /* should not happen */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001582 VLOG << __func__ << ": ALREADY IN CACHE (" << e << ") ? IGNORING ADD";
Ken Chen92bed612018-12-22 21:46:55 +08001583 _cache_notify_waiting_tid_locked(cache, key);
1584 return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001585 }
1586
1587 if (cache->num_entries >= cache->max_entries) {
1588 _cache_remove_expired(cache);
1589 if (cache->num_entries >= cache->max_entries) {
1590 _cache_remove_oldest(cache);
1591 }
1592 /* need to lookup again */
1593 lookup = _cache_lookup_p(cache, key);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001594 e = *lookup;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001595 if (e != NULL) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001596 VLOG << __func__ << ": ALREADY IN CACHE (" << e << ") ? IGNORING ADD";
Ken Chen92bed612018-12-22 21:46:55 +08001597 _cache_notify_waiting_tid_locked(cache, key);
1598 return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001599 }
1600 }
1601
1602 ttl = answer_getTTL(answer, answerlen);
1603 if (ttl > 0) {
1604 e = entry_alloc(key, answer, answerlen);
1605 if (e != NULL) {
1606 e->expires = ttl + _time_now();
1607 _cache_add_p(cache, lookup, e);
1608 }
1609 }
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001610
Ken Chen92bed612018-12-22 21:46:55 +08001611 cache_dump_mru(cache);
1612 _cache_notify_waiting_tid_locked(cache, key);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001613}
1614
Ken Chen92bed612018-12-22 21:46:55 +08001615// Head of the list of caches.
1616static struct resolv_cache_info res_cache_list GUARDED_BY(cache_mutex);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001617
cken418cfb62018-12-01 17:45:18 +09001618// insert resolv_cache_info into the list of resolv_cache_infos
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001619static void insert_cache_info_locked(resolv_cache_info* cache_info);
cken418cfb62018-12-01 17:45:18 +09001620// creates a resolv_cache_info
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001621static resolv_cache_info* create_cache_info();
cken418cfb62018-12-01 17:45:18 +09001622// empty the nameservers set for the named cache
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001623static void free_nameservers_locked(resolv_cache_info* cache_info);
1624// return 1 if the provided list of name servers differs from the list of name servers
1625// currently attached to the provided cache_info
1626static int resolv_is_nameservers_equal_locked(resolv_cache_info* cache_info, const char** servers,
1627 int numservers);
cken418cfb62018-12-01 17:45:18 +09001628// clears the stats samples contained withing the given cache_info
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001629static void res_cache_clear_stats_locked(resolv_cache_info* cache_info);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001630
cken418cfb62018-12-01 17:45:18 +09001631// public API for netd to query if name server is set on specific netid
1632bool resolv_has_nameservers(unsigned netid) {
Ken Chen92bed612018-12-22 21:46:55 +08001633 std::lock_guard guard(cache_mutex);
cken418cfb62018-12-01 17:45:18 +09001634 resolv_cache_info* info = find_cache_info_locked(netid);
Ken Chen92bed612018-12-22 21:46:55 +08001635 return (info != nullptr) && (info->nscount > 0);
cken418cfb62018-12-01 17:45:18 +09001636}
1637
1638// look up the named cache, and creates one if needed
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001639static resolv_cache* get_res_cache_for_net_locked(unsigned netid) {
1640 resolv_cache* cache = find_named_cache_locked(netid);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001641 if (!cache) {
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001642 resolv_cache_info* cache_info = create_cache_info();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001643 if (cache_info) {
Ken Chen92bed612018-12-22 21:46:55 +08001644 cache = resolv_cache_create();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001645 if (cache) {
1646 cache_info->cache = cache;
1647 cache_info->netid = netid;
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001648 insert_cache_info_locked(cache_info);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001649 } else {
1650 free(cache_info);
1651 }
1652 }
1653 }
1654 return cache;
1655}
1656
Bernie Innocentiac18b122018-10-01 23:10:18 +09001657void resolv_delete_cache_for_net(unsigned netid) {
Ken Chen92bed612018-12-22 21:46:55 +08001658 std::lock_guard guard(cache_mutex);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001659
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001660 struct resolv_cache_info* prev_cache_info = &res_cache_list;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001661
1662 while (prev_cache_info->next) {
1663 struct resolv_cache_info* cache_info = prev_cache_info->next;
1664
1665 if (cache_info->netid == netid) {
1666 prev_cache_info->next = cache_info->next;
Bernie Innocenti69906322018-12-18 19:53:42 +09001667 cache_flush_locked(cache_info->cache);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001668 free(cache_info->cache->entries);
1669 free(cache_info->cache);
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001670 free_nameservers_locked(cache_info);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001671 free(cache_info);
1672 break;
1673 }
1674
1675 prev_cache_info = prev_cache_info->next;
1676 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001677}
1678
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001679static resolv_cache_info* create_cache_info() {
Bernie Innocenti9c575932018-09-07 21:10:25 +09001680 return (struct resolv_cache_info*) calloc(sizeof(struct resolv_cache_info), 1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001681}
1682
Ken Chen92bed612018-12-22 21:46:55 +08001683// TODO: convert this to a simple and efficient C++ container.
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001684static void insert_cache_info_locked(struct resolv_cache_info* cache_info) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001685 struct resolv_cache_info* last;
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001686 for (last = &res_cache_list; last->next; last = last->next) {}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001687 last->next = cache_info;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001688}
1689
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001690static resolv_cache* find_named_cache_locked(unsigned netid) {
cken418cfb62018-12-01 17:45:18 +09001691 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001692 if (info != NULL) return info->cache;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001693 return NULL;
1694}
1695
cken418cfb62018-12-01 17:45:18 +09001696static resolv_cache_info* find_cache_info_locked(unsigned netid) {
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001697 struct resolv_cache_info* cache_info = res_cache_list.next;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001698
1699 while (cache_info) {
1700 if (cache_info->netid == netid) {
1701 break;
1702 }
1703
1704 cache_info = cache_info->next;
1705 }
1706 return cache_info;
1707}
1708
Bernie Innocenti136af7b2018-10-01 20:46:20 +09001709static void resolv_set_default_params(struct __res_params* params) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001710 params->sample_validity = NSSAMPLE_VALIDITY;
1711 params->success_threshold = SUCCESS_THRESHOLD;
1712 params->min_samples = 0;
1713 params->max_samples = 0;
1714 params->base_timeout_msec = 0; // 0 = legacy algorithm
1715}
1716
Bernie Innocentib102dd22018-12-04 14:57:48 +09001717int resolv_set_nameservers_for_net(unsigned netid, const char** servers, const int numservers,
Bernie Innocentiac18b122018-10-01 23:10:18 +09001718 const char* domains, const __res_params* params) {
Bernie Innocenti9c575932018-09-07 21:10:25 +09001719 char* cp;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001720 int* offset;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001721 struct addrinfo* nsaddrinfo[MAXNS];
1722
1723 if (numservers > MAXNS) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001724 VLOG << __func__ << ": numservers=" << numservers << ", MAXNS=" << MAXNS;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001725 return E2BIG;
1726 }
1727
1728 // Parse the addresses before actually locking or changing any state, in case there is an error.
1729 // As a side effect this also reduces the time the lock is kept.
Bernie Innocentie2bc46f2018-10-16 23:35:28 +09001730 char sbuf[NI_MAXSERV];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001731 snprintf(sbuf, sizeof(sbuf), "%u", NAMESERVER_PORT);
Bernie Innocentib102dd22018-12-04 14:57:48 +09001732 for (int i = 0; i < numservers; i++) {
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001733 // The addrinfo structures allocated here are freed in free_nameservers_locked().
Bernie Innocentie2bc46f2018-10-16 23:35:28 +09001734 const addrinfo hints = {
1735 .ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM, .ai_flags = AI_NUMERICHOST};
1736 int rt = getaddrinfo_numeric(servers[i], sbuf, hints, &nsaddrinfo[i]);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001737 if (rt != 0) {
Bernie Innocentib102dd22018-12-04 14:57:48 +09001738 for (int j = 0; j < i; j++) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001739 freeaddrinfo(nsaddrinfo[j]);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001740 }
Bernie Innocentie2bc46f2018-10-16 23:35:28 +09001741 VLOG << __func__ << ": getaddrinfo_numeric(" << servers[i]
1742 << ") = " << gai_strerror(rt);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001743 return EINVAL;
1744 }
1745 }
1746
Ken Chen92bed612018-12-22 21:46:55 +08001747 std::lock_guard guard(cache_mutex);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001748 // creates the cache if not created
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001749 get_res_cache_for_net_locked(netid);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001750
cken418cfb62018-12-01 17:45:18 +09001751 resolv_cache_info* cache_info = find_cache_info_locked(netid);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001752
1753 if (cache_info != NULL) {
1754 uint8_t old_max_samples = cache_info->params.max_samples;
1755 if (params != NULL) {
1756 cache_info->params = *params;
1757 } else {
Bernie Innocenti136af7b2018-10-01 20:46:20 +09001758 resolv_set_default_params(&cache_info->params);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001759 }
1760
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001761 if (!resolv_is_nameservers_equal_locked(cache_info, servers, numservers)) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001762 // free current before adding new
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001763 free_nameservers_locked(cache_info);
Bernie Innocentib102dd22018-12-04 14:57:48 +09001764 for (int i = 0; i < numservers; i++) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001765 cache_info->nsaddrinfo[i] = nsaddrinfo[i];
1766 cache_info->nameservers[i] = strdup(servers[i]);
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001767 VLOG << __func__ << ": netid = " << netid << ", addr = " << servers[i];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001768 }
1769 cache_info->nscount = numservers;
1770
1771 // Clear the NS statistics because the mapping to nameservers might have changed.
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001772 res_cache_clear_stats_locked(cache_info);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001773
1774 // increment the revision id to ensure that sample state is not written back if the
1775 // servers change; in theory it would suffice to do so only if the servers or
1776 // max_samples actually change, in practice the overhead of checking is higher than the
1777 // cost, and overflows are unlikely
1778 ++cache_info->revision_id;
Ken Chen545b52c2018-11-02 13:18:40 +08001779 } else {
1780 if (cache_info->params.max_samples != old_max_samples) {
1781 // If the maximum number of samples changes, the overhead of keeping the most recent
1782 // samples around is not considered worth the effort, so they are cleared instead.
1783 // All other parameters do not affect shared state: Changing these parameters does
1784 // not invalidate the samples, as they only affect aggregation and the conditions
1785 // under which servers are considered usable.
1786 res_cache_clear_stats_locked(cache_info);
1787 ++cache_info->revision_id;
1788 }
Bernie Innocentib102dd22018-12-04 14:57:48 +09001789 for (int j = 0; j < numservers; j++) {
Ken Chen545b52c2018-11-02 13:18:40 +08001790 freeaddrinfo(nsaddrinfo[j]);
1791 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001792 }
1793
1794 // Always update the search paths, since determining whether they actually changed is
1795 // complex due to the zero-padding, and probably not worth the effort. Cache-flushing
1796 // however is not // necessary, since the stored cache entries do contain the domain, not
1797 // just the host name.
1798 // code moved from res_init.c, load_domain_search_list
1799 strlcpy(cache_info->defdname, domains, sizeof(cache_info->defdname));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001800 if ((cp = strchr(cache_info->defdname, '\n')) != NULL) *cp = '\0';
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001801
1802 cp = cache_info->defdname;
1803 offset = cache_info->dnsrch_offset;
1804 while (offset < cache_info->dnsrch_offset + MAXDNSRCH) {
1805 while (*cp == ' ' || *cp == '\t') /* skip leading white space */
1806 cp++;
1807 if (*cp == '\0') /* stop if nothing more to do */
1808 break;
1809 *offset++ = cp - cache_info->defdname; /* record this search domain */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001810 while (*cp) { /* zero-terminate it */
1811 if (*cp == ' ' || *cp == '\t') {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001812 *cp++ = '\0';
1813 break;
1814 }
1815 cp++;
1816 }
1817 }
1818 *offset = -1; /* cache_info->dnsrch_offset has MAXDNSRCH+1 items */
1819 }
1820
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001821 return 0;
1822}
1823
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001824static int resolv_is_nameservers_equal_locked(resolv_cache_info* cache_info, const char** servers,
1825 int numservers) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001826 if (cache_info->nscount != numservers) {
1827 return 0;
1828 }
1829
1830 // Compare each name server against current name servers.
1831 // TODO: this is incorrect if the list of current or previous nameservers
1832 // contains duplicates. This does not really matter because the framework
1833 // filters out duplicates, but we should probably fix it. It's also
1834 // insensitive to the order of the nameservers; we should probably fix that
1835 // too.
1836 for (int i = 0; i < numservers; i++) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001837 for (int j = 0;; j++) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001838 if (j >= numservers) {
1839 return 0;
1840 }
1841 if (strcmp(cache_info->nameservers[i], servers[j]) == 0) {
1842 break;
1843 }
1844 }
1845 }
1846
1847 return 1;
1848}
1849
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001850static void free_nameservers_locked(resolv_cache_info* cache_info) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001851 int i;
1852 for (i = 0; i < cache_info->nscount; i++) {
1853 free(cache_info->nameservers[i]);
1854 cache_info->nameservers[i] = NULL;
1855 if (cache_info->nsaddrinfo[i] != NULL) {
1856 freeaddrinfo(cache_info->nsaddrinfo[i]);
1857 cache_info->nsaddrinfo[i] = NULL;
1858 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001859 cache_info->nsstats[i].sample_count = cache_info->nsstats[i].sample_next = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001860 }
1861 cache_info->nscount = 0;
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001862 res_cache_clear_stats_locked(cache_info);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001863 ++cache_info->revision_id;
1864}
1865
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001866void _resolv_populate_res_for_net(res_state statp) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001867 if (statp == NULL) {
1868 return;
1869 }
1870
Ken Chen92bed612018-12-22 21:46:55 +08001871 std::lock_guard guard(cache_mutex);
cken418cfb62018-12-01 17:45:18 +09001872 resolv_cache_info* info = find_cache_info_locked(statp->netid);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001873 if (info != NULL) {
1874 int nserv;
1875 struct addrinfo* ai;
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001876 VLOG << __func__ << ": " << statp->netid;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001877 for (nserv = 0; nserv < MAXNS; nserv++) {
1878 ai = info->nsaddrinfo[nserv];
1879 if (ai == NULL) {
1880 break;
1881 }
1882
1883 if ((size_t) ai->ai_addrlen <= sizeof(statp->_u._ext.ext->nsaddrs[0])) {
1884 if (statp->_u._ext.ext != NULL) {
1885 memcpy(&statp->_u._ext.ext->nsaddrs[nserv], ai->ai_addr, ai->ai_addrlen);
1886 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
1887 } else {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001888 if ((size_t) ai->ai_addrlen <= sizeof(statp->nsaddr_list[0])) {
1889 memcpy(&statp->nsaddr_list[nserv], ai->ai_addr, ai->ai_addrlen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001890 } else {
1891 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
1892 }
1893 }
1894 } else {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001895 VLOG << __func__ << ": found too long addrlen";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001896 }
1897 }
1898 statp->nscount = nserv;
1899 // now do search domains. Note that we cache the offsets as this code runs alot
1900 // but the setting/offset-computer only runs when set/changed
1901 // WARNING: Don't use str*cpy() here, this string contains zeroes.
1902 memcpy(statp->defdname, info->defdname, sizeof(statp->defdname));
Bernie Innocenti9c575932018-09-07 21:10:25 +09001903 char** pp = statp->dnsrch;
1904 int* p = info->dnsrch_offset;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001905 while (pp < statp->dnsrch + MAXDNSRCH && *p != -1) {
1906 *pp++ = &statp->defdname[0] + *p++;
1907 }
1908 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001909}
1910
1911/* Resolver reachability statistics. */
1912
Bernie Innocentiac18b122018-10-01 23:10:18 +09001913static void _res_cache_add_stats_sample_locked(res_stats* stats, const res_sample* sample,
1914 int max_samples) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001915 // Note: This function expects max_samples > 0, otherwise a (harmless) modification of the
1916 // allocated but supposedly unused memory for samples[0] will happen
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001917 VLOG << __func__ << ": adding sample to stats, next = " << stats->sample_next
1918 << ", count = " << stats->sample_count;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001919 stats->samples[stats->sample_next] = *sample;
1920 if (stats->sample_count < max_samples) {
1921 ++stats->sample_count;
1922 }
1923 if (++stats->sample_next >= max_samples) {
1924 stats->sample_next = 0;
1925 }
1926}
1927
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001928static void res_cache_clear_stats_locked(resolv_cache_info* cache_info) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001929 if (cache_info) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001930 for (int i = 0; i < MAXNS; ++i) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001931 cache_info->nsstats->sample_count = cache_info->nsstats->sample_next = 0;
1932 }
1933 }
1934}
1935
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001936int android_net_res_stats_get_info_for_net(unsigned netid, int* nscount,
1937 struct sockaddr_storage servers[MAXNS], int* dcount,
1938 char domains[MAXDNSRCH][MAXDNSRCHPATH],
1939 struct __res_params* params,
Ken Chen92bed612018-12-22 21:46:55 +08001940 struct res_stats stats[MAXNS],
1941 int* wait_for_pending_req_timeout_count) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001942 int revision_id = -1;
Ken Chen92bed612018-12-22 21:46:55 +08001943 std::lock_guard guard(cache_mutex);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001944
cken418cfb62018-12-01 17:45:18 +09001945 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001946 if (info) {
1947 if (info->nscount > MAXNS) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001948 VLOG << __func__ << ": nscount " << info->nscount << " > MAXNS " << MAXNS;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001949 errno = EFAULT;
1950 return -1;
1951 }
1952 int i;
1953 for (i = 0; i < info->nscount; i++) {
1954 // Verify that the following assumptions are held, failure indicates corruption:
1955 // - getaddrinfo() may never return a sockaddr > sockaddr_storage
1956 // - all addresses are valid
1957 // - there is only one address per addrinfo thanks to numeric resolution
1958 int addrlen = info->nsaddrinfo[i]->ai_addrlen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001959 if (addrlen < (int) sizeof(struct sockaddr) || addrlen > (int) sizeof(servers[0])) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001960 VLOG << __func__ << ": nsaddrinfo[" << i << "].ai_addrlen == " << addrlen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001961 errno = EMSGSIZE;
1962 return -1;
1963 }
1964 if (info->nsaddrinfo[i]->ai_addr == NULL) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001965 VLOG << __func__ << ": nsaddrinfo[" << i << "].ai_addr == NULL";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001966 errno = ENOENT;
1967 return -1;
1968 }
1969 if (info->nsaddrinfo[i]->ai_next != NULL) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001970 VLOG << __func__ << ": nsaddrinfo[" << i << "].ai_next != NULL";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001971 errno = ENOTUNIQ;
1972 return -1;
1973 }
1974 }
1975 *nscount = info->nscount;
1976 for (i = 0; i < info->nscount; i++) {
1977 memcpy(&servers[i], info->nsaddrinfo[i]->ai_addr, info->nsaddrinfo[i]->ai_addrlen);
1978 stats[i] = info->nsstats[i];
1979 }
1980 for (i = 0; i < MAXDNSRCH; i++) {
1981 const char* cur_domain = info->defdname + info->dnsrch_offset[i];
1982 // dnsrch_offset[i] can either be -1 or point to an empty string to indicate the end
1983 // of the search offsets. Checking for < 0 is not strictly necessary, but safer.
1984 // TODO: Pass in a search domain array instead of a string to
Bernie Innocentiac18b122018-10-01 23:10:18 +09001985 // resolv_set_nameservers_for_net() and make this double check unnecessary.
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001986 if (info->dnsrch_offset[i] < 0 ||
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001987 ((size_t) info->dnsrch_offset[i]) >= sizeof(info->defdname) || !cur_domain[0]) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001988 break;
1989 }
1990 strlcpy(domains[i], cur_domain, MAXDNSRCHPATH);
1991 }
1992 *dcount = i;
1993 *params = info->params;
1994 revision_id = info->revision_id;
Ken Chen92bed612018-12-22 21:46:55 +08001995 *wait_for_pending_req_timeout_count = info->wait_for_pending_req_timeout_count;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001996 }
1997
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001998 return revision_id;
1999}
2000
Bernie Innocentiac18b122018-10-01 23:10:18 +09002001int resolv_cache_get_resolver_stats(unsigned netid, __res_params* params, res_stats stats[MAXNS]) {
Ken Chen92bed612018-12-22 21:46:55 +08002002 std::lock_guard guard(cache_mutex);
cken418cfb62018-12-01 17:45:18 +09002003 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09002004 if (info) {
2005 memcpy(stats, info->nsstats, sizeof(info->nsstats));
2006 *params = info->params;
Ken Chen92bed612018-12-22 21:46:55 +08002007 return info->revision_id;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09002008 }
2009
Ken Chen92bed612018-12-22 21:46:55 +08002010 return -1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09002011}
2012
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09002013void _resolv_cache_add_resolver_stats_sample(unsigned netid, int revision_id, int ns,
Bernie Innocentiac18b122018-10-01 23:10:18 +09002014 const res_sample* sample, int max_samples) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09002015 if (max_samples <= 0) return;
2016
Ken Chen92bed612018-12-22 21:46:55 +08002017 std::lock_guard guard(cache_mutex);
cken418cfb62018-12-01 17:45:18 +09002018 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09002019
2020 if (info && info->revision_id == revision_id) {
2021 _res_cache_add_stats_sample_locked(&info->nsstats[ns], sample, max_samples);
2022 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09002023}