blob: 98e6909b4d34fc7b0c5ebdeb582ed890aaadde7a [file] [log] [blame]
Bernie Innocenti55864192018-08-30 04:05:20 +09001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090029// 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 Innocenti34de3ba2019-02-19 18:08:36 +090035#include "resolv_cache.h"
36
Bernie Innocenti55864192018-08-30 04:05:20 +090037#include <resolv.h>
38#include <stdarg.h>
39#include <stdio.h>
40#include <stdlib.h>
41#include <string.h>
42#include <time.h>
Ken Chen2a429352018-12-22 21:46:55 +080043#include <mutex>
Bernie Innocenti55864192018-08-30 04:05:20 +090044
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090045#include <arpa/inet.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090046#include <arpa/nameser.h>
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090047#include <errno.h>
48#include <linux/if.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090049#include <net/if.h>
50#include <netdb.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090051
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090052#include <android-base/logging.h>
Ken Chen2a429352018-12-22 21:46:55 +080053#include <android-base/thread_annotations.h>
Bernie Innocenti34de3ba2019-02-19 18:08:36 +090054#include <android/multinetwork.h> // ResNsendFlags
Bernie Innocentif89b3512018-08-30 07:34:37 +090055
Bernie Innocenti189eb502018-10-01 23:10:18 +090056#include "res_state_ext.h"
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090057#include "resolv_private.h"
Bernie Innocenti55864192018-08-30 04:05:20 +090058
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090059#define VLOG if (!kVerboseLogging) {} else LOG(INFO)
60
61#ifndef RESOLV_ALLOW_VERBOSE_LOGGING
62static_assert(kVerboseLogging == false && kDumpData == false,
63 "Verbose logging floods logs at high-rate and exposes privacy-sensitive information. "
64 "Do not enable in release builds.");
65#endif
Bernie Innocenti55864192018-08-30 04:05:20 +090066
67/* This code implements a small and *simple* DNS resolver cache.
68 *
69 * It is only used to cache DNS answers for a time defined by the smallest TTL
70 * among the answer records in order to reduce DNS traffic. It is not supposed
71 * to be a full DNS cache, since we plan to implement that in the future in a
72 * dedicated process running on the system.
73 *
74 * Note that its design is kept simple very intentionally, i.e.:
75 *
76 * - it takes raw DNS query packet data as input, and returns raw DNS
77 * answer packet data as output
78 *
79 * (this means that two similar queries that encode the DNS name
80 * differently will be treated distinctly).
81 *
82 * the smallest TTL value among the answer records are used as the time
83 * to keep an answer in the cache.
84 *
85 * this is bad, but we absolutely want to avoid parsing the answer packets
86 * (and should be solved by the later full DNS cache process).
87 *
88 * - the implementation is just a (query-data) => (answer-data) hash table
89 * with a trivial least-recently-used expiration policy.
90 *
91 * Doing this keeps the code simple and avoids to deal with a lot of things
92 * that a full DNS cache is expected to do.
93 *
94 * The API is also very simple:
95 *
96 * - the client calls _resolv_cache_get() to obtain a handle to the cache.
97 * this will initialize the cache on first usage. the result can be NULL
98 * if the cache is disabled.
99 *
100 * - the client calls _resolv_cache_lookup() before performing a query
101 *
102 * if the function returns RESOLV_CACHE_FOUND, a copy of the answer data
103 * has been copied into the client-provided answer buffer.
104 *
105 * if the function returns RESOLV_CACHE_NOTFOUND, the client should perform
106 * a request normally, *then* call _resolv_cache_add() to add the received
107 * answer to the cache.
108 *
109 * if the function returns RESOLV_CACHE_UNSUPPORTED, the client should
110 * perform a request normally, and *not* call _resolv_cache_add()
111 *
112 * note that RESOLV_CACHE_UNSUPPORTED is also returned if the answer buffer
113 * is too short to accomodate the cached result.
114 */
115
116/* default number of entries kept in the cache. This value has been
117 * determined by browsing through various sites and counting the number
118 * of corresponding requests. Keep in mind that our framework is currently
119 * performing two requests per name lookup (one for IPv4, the other for IPv6)
120 *
121 * www.google.com 4
122 * www.ysearch.com 6
123 * www.amazon.com 8
124 * www.nytimes.com 22
125 * www.espn.com 28
126 * www.msn.com 28
127 * www.lemonde.fr 35
128 *
129 * (determined in 2009-2-17 from Paris, France, results may vary depending
130 * on location)
131 *
132 * most high-level websites use lots of media/ad servers with different names
133 * but these are generally reused when browsing through the site.
134 *
135 * As such, a value of 64 should be relatively comfortable at the moment.
136 *
137 * ******************************************
138 * * NOTE - this has changed.
139 * * 1) we've added IPv6 support so each dns query results in 2 responses
140 * * 2) we've made this a system-wide cache, so the cost is less (it's not
141 * * duplicated in each process) and the need is greater (more processes
142 * * making different requests).
143 * * Upping by 2x for IPv6
144 * * Upping by another 5x for the centralized nature
145 * *****************************************
146 */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900147#define CONFIG_MAX_ENTRIES (64 * 2 * 5)
Bernie Innocenti55864192018-08-30 04:05:20 +0900148
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900149/** BOUNDED BUFFER FORMATTING **/
Bernie Innocenti55864192018-08-30 04:05:20 +0900150
151/* technical note:
152 *
153 * the following debugging routines are used to append data to a bounded
154 * buffer they take two parameters that are:
155 *
156 * - p : a pointer to the current cursor position in the buffer
157 * this value is initially set to the buffer's address.
158 *
159 * - end : the address of the buffer's limit, i.e. of the first byte
160 * after the buffer. this address should never be touched.
161 *
162 * IMPORTANT: it is assumed that end > buffer_address, i.e.
163 * that the buffer is at least one byte.
164 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900165 * the bprint_x() functions return the new value of 'p' after the data
Bernie Innocenti55864192018-08-30 04:05:20 +0900166 * has been appended, and also ensure the following:
167 *
168 * - the returned value will never be strictly greater than 'end'
169 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900170 * - a return value equal to 'end' means that truncation occurred
Bernie Innocenti55864192018-08-30 04:05:20 +0900171 * (in which case, end[-1] will be set to 0)
172 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900173 * - after returning from a bprint_x() function, the content of the buffer
Bernie Innocenti55864192018-08-30 04:05:20 +0900174 * is always 0-terminated, even in the event of truncation.
175 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900176 * these conventions allow you to call bprint_x() functions multiple times and
Bernie Innocenti55864192018-08-30 04:05:20 +0900177 * only check for truncation at the end of the sequence, as in:
178 *
179 * char buff[1000], *p = buff, *end = p + sizeof(buff);
180 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900181 * p = bprint_c(p, end, '"');
182 * p = bprint_s(p, end, my_string);
183 * p = bprint_c(p, end, '"');
Bernie Innocenti55864192018-08-30 04:05:20 +0900184 *
185 * if (p >= end) {
186 * // buffer was too small
187 * }
188 *
189 * printf( "%s", buff );
190 */
191
Bernie Innocenti34de3ba2019-02-19 18:08:36 +0900192/* Defaults used for initializing res_params */
Bernie Innocenti1fbca5c2018-10-01 20:46:20 +0900193
194// If successes * 100 / total_samples is less than this value, the server is considered failing
195#define SUCCESS_THRESHOLD 75
196// Sample validity in seconds. Set to -1 to disable skipping failing servers.
197#define NSSAMPLE_VALIDITY 1800
198
Bernie Innocenti55864192018-08-30 04:05:20 +0900199/* add a char to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900200static char* bprint_c(char* p, char* end, int c) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900201 if (p < end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900202 if (p + 1 == end)
Bernie Innocenti55864192018-08-30 04:05:20 +0900203 *p++ = 0;
204 else {
205 *p++ = (char) c;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900206 *p = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900207 }
208 }
209 return p;
210}
211
212/* add a sequence of bytes to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900213static char* bprint_b(char* p, char* end, const char* buf, int len) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900214 int avail = end - p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900215
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900216 if (avail <= 0 || len <= 0) return p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900217
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900218 if (avail > len) avail = len;
Bernie Innocenti55864192018-08-30 04:05:20 +0900219
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900220 memcpy(p, buf, avail);
Bernie Innocenti55864192018-08-30 04:05:20 +0900221 p += avail;
222
223 if (p < end)
224 p[0] = 0;
225 else
226 end[-1] = 0;
227
228 return p;
229}
230
231/* add a string to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900232static char* bprint_s(char* p, char* end, const char* str) {
233 return bprint_b(p, end, str, strlen(str));
Bernie Innocenti55864192018-08-30 04:05:20 +0900234}
235
236/* add a formatted string to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900237static char* bprint(char* p, char* end, const char* format, ...) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900238 int avail, n;
239 va_list args;
Bernie Innocenti55864192018-08-30 04:05:20 +0900240
241 avail = end - p;
242
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900243 if (avail <= 0) return p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900244
245 va_start(args, format);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900246 n = vsnprintf(p, avail, format, args);
Bernie Innocenti55864192018-08-30 04:05:20 +0900247 va_end(args);
248
249 /* certain C libraries return -1 in case of truncation */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900250 if (n < 0 || n > avail) n = avail;
Bernie Innocenti55864192018-08-30 04:05:20 +0900251
252 p += n;
253 /* certain C libraries do not zero-terminate in case of truncation */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900254 if (p == end) p[-1] = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900255
256 return p;
257}
258
259/* add a hex value to a bounded buffer, up to 8 digits */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900260static char* bprint_hex(char* p, char* end, unsigned value, int numDigits) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900261 char text[sizeof(unsigned) * 2];
262 int nn = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900263
264 while (numDigits-- > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900265 text[nn++] = "0123456789abcdef"[(value >> (numDigits * 4)) & 15];
Bernie Innocenti55864192018-08-30 04:05:20 +0900266 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900267 return bprint_b(p, end, text, nn);
Bernie Innocenti55864192018-08-30 04:05:20 +0900268}
269
270/* add the hexadecimal dump of some memory area to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900271static char* bprint_hexdump(char* p, char* end, const uint8_t* data, int datalen) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900272 int lineSize = 16;
Bernie Innocenti55864192018-08-30 04:05:20 +0900273
274 while (datalen > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900275 int avail = datalen;
276 int nn;
Bernie Innocenti55864192018-08-30 04:05:20 +0900277
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900278 if (avail > lineSize) avail = lineSize;
Bernie Innocenti55864192018-08-30 04:05:20 +0900279
280 for (nn = 0; nn < avail; nn++) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900281 if (nn > 0) p = bprint_c(p, end, ' ');
282 p = bprint_hex(p, end, data[nn], 2);
Bernie Innocenti55864192018-08-30 04:05:20 +0900283 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900284 for (; nn < lineSize; nn++) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900285 p = bprint_s(p, end, " ");
Bernie Innocenti55864192018-08-30 04:05:20 +0900286 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900287 p = bprint_s(p, end, " ");
Bernie Innocenti55864192018-08-30 04:05:20 +0900288
289 for (nn = 0; nn < avail; nn++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900290 int c = data[nn];
Bernie Innocenti55864192018-08-30 04:05:20 +0900291
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900292 if (c < 32 || c > 127) c = '.';
Bernie Innocenti55864192018-08-30 04:05:20 +0900293
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900294 p = bprint_c(p, end, c);
Bernie Innocenti55864192018-08-30 04:05:20 +0900295 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900296 p = bprint_c(p, end, '\n');
Bernie Innocenti55864192018-08-30 04:05:20 +0900297
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900298 data += avail;
Bernie Innocenti55864192018-08-30 04:05:20 +0900299 datalen -= avail;
300 }
301 return p;
302}
303
304/* dump the content of a query of packet to the log */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900305static void dump_bytes(const uint8_t* base, int len) {
306 if (!kDumpData) return;
Bernie Innocenti55864192018-08-30 04:05:20 +0900307
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900308 char buff[1024];
309 char *p = buff, *end = p + sizeof(buff);
310
311 p = bprint_hexdump(p, end, base, len);
312 VLOG << buff;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900313}
Bernie Innocenti55864192018-08-30 04:05:20 +0900314
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900315static time_t _time_now(void) {
316 struct timeval tv;
Bernie Innocenti55864192018-08-30 04:05:20 +0900317
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900318 gettimeofday(&tv, NULL);
Bernie Innocenti55864192018-08-30 04:05:20 +0900319 return tv.tv_sec;
320}
321
322/* reminder: the general format of a DNS packet is the following:
323 *
324 * HEADER (12 bytes)
325 * QUESTION (variable)
326 * ANSWER (variable)
327 * AUTHORITY (variable)
328 * ADDITIONNAL (variable)
329 *
330 * the HEADER is made of:
331 *
332 * ID : 16 : 16-bit unique query identification field
333 *
334 * QR : 1 : set to 0 for queries, and 1 for responses
335 * Opcode : 4 : set to 0 for queries
336 * AA : 1 : set to 0 for queries
337 * TC : 1 : truncation flag, will be set to 0 in queries
338 * RD : 1 : recursion desired
339 *
340 * RA : 1 : recursion available (0 in queries)
341 * Z : 3 : three reserved zero bits
342 * RCODE : 4 : response code (always 0=NOERROR in queries)
343 *
344 * QDCount: 16 : question count
345 * ANCount: 16 : Answer count (0 in queries)
346 * NSCount: 16: Authority Record count (0 in queries)
347 * ARCount: 16: Additionnal Record count (0 in queries)
348 *
349 * the QUESTION is made of QDCount Question Record (QRs)
350 * the ANSWER is made of ANCount RRs
351 * the AUTHORITY is made of NSCount RRs
352 * the ADDITIONNAL is made of ARCount RRs
353 *
354 * Each Question Record (QR) is made of:
355 *
356 * QNAME : variable : Query DNS NAME
357 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
358 * CLASS : 16 : class of query (IN=1)
359 *
360 * Each Resource Record (RR) is made of:
361 *
362 * NAME : variable : DNS NAME
363 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
364 * CLASS : 16 : class of query (IN=1)
365 * TTL : 32 : seconds to cache this RR (0=none)
366 * RDLENGTH: 16 : size of RDDATA in bytes
367 * RDDATA : variable : RR data (depends on TYPE)
368 *
369 * Each QNAME contains a domain name encoded as a sequence of 'labels'
370 * terminated by a zero. Each label has the following format:
371 *
372 * LEN : 8 : lenght of label (MUST be < 64)
373 * NAME : 8*LEN : label length (must exclude dots)
374 *
375 * A value of 0 in the encoding is interpreted as the 'root' domain and
376 * terminates the encoding. So 'www.android.com' will be encoded as:
377 *
378 * <3>www<7>android<3>com<0>
379 *
380 * Where <n> represents the byte with value 'n'
381 *
382 * Each NAME reflects the QNAME of the question, but has a slightly more
383 * complex encoding in order to provide message compression. This is achieved
384 * by using a 2-byte pointer, with format:
385 *
386 * TYPE : 2 : 0b11 to indicate a pointer, 0b01 and 0b10 are reserved
387 * OFFSET : 14 : offset to another part of the DNS packet
388 *
389 * The offset is relative to the start of the DNS packet and must point
390 * A pointer terminates the encoding.
391 *
392 * The NAME can be encoded in one of the following formats:
393 *
394 * - a sequence of simple labels terminated by 0 (like QNAMEs)
395 * - a single pointer
396 * - a sequence of simple labels terminated by a pointer
397 *
398 * A pointer shall always point to either a pointer of a sequence of
399 * labels (which can themselves be terminated by either a 0 or a pointer)
400 *
401 * The expanded length of a given domain name should not exceed 255 bytes.
402 *
403 * NOTE: we don't parse the answer packets, so don't need to deal with NAME
404 * records, only QNAMEs.
405 */
406
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900407#define DNS_HEADER_SIZE 12
Bernie Innocenti55864192018-08-30 04:05:20 +0900408
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900409#define DNS_TYPE_A "\00\01" /* big-endian decimal 1 */
410#define DNS_TYPE_PTR "\00\014" /* big-endian decimal 12 */
411#define DNS_TYPE_MX "\00\017" /* big-endian decimal 15 */
412#define DNS_TYPE_AAAA "\00\034" /* big-endian decimal 28 */
413#define DNS_TYPE_ALL "\00\0377" /* big-endian decimal 255 */
Bernie Innocenti55864192018-08-30 04:05:20 +0900414
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900415#define DNS_CLASS_IN "\00\01" /* big-endian decimal 1 */
Bernie Innocenti55864192018-08-30 04:05:20 +0900416
417typedef struct {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900418 const uint8_t* base;
419 const uint8_t* end;
420 const uint8_t* cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900421} DnsPacket;
422
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900423static void _dnsPacket_init(DnsPacket* packet, const uint8_t* buff, int bufflen) {
424 packet->base = buff;
425 packet->end = buff + bufflen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900426 packet->cursor = buff;
427}
428
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900429static void _dnsPacket_rewind(DnsPacket* packet) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900430 packet->cursor = packet->base;
431}
432
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900433static void _dnsPacket_skip(DnsPacket* packet, int count) {
434 const uint8_t* p = packet->cursor + count;
Bernie Innocenti55864192018-08-30 04:05:20 +0900435
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900436 if (p > packet->end) p = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900437
438 packet->cursor = p;
439}
440
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900441static int _dnsPacket_readInt16(DnsPacket* packet) {
442 const uint8_t* p = packet->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900443
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900444 if (p + 2 > packet->end) return -1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900445
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900446 packet->cursor = p + 2;
447 return (p[0] << 8) | p[1];
Bernie Innocenti55864192018-08-30 04:05:20 +0900448}
449
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900450/** QUERY CHECKING **/
Bernie Innocenti55864192018-08-30 04:05:20 +0900451
452/* check bytes in a dns packet. returns 1 on success, 0 on failure.
453 * the cursor is only advanced in the case of success
454 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900455static int _dnsPacket_checkBytes(DnsPacket* packet, int numBytes, const void* bytes) {
456 const uint8_t* p = packet->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900457
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900458 if (p + numBytes > packet->end) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900459
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900460 if (memcmp(p, bytes, numBytes) != 0) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900461
462 packet->cursor = p + numBytes;
463 return 1;
464}
465
466/* parse and skip a given QNAME stored in a query packet,
467 * from the current cursor position. returns 1 on success,
468 * or 0 for malformed data.
469 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900470static int _dnsPacket_checkQName(DnsPacket* packet) {
471 const uint8_t* p = packet->cursor;
472 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900473
474 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900475 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900476
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900477 if (p >= end) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900478
479 c = *p++;
480
481 if (c == 0) {
482 packet->cursor = p;
483 return 1;
484 }
485
486 /* we don't expect label compression in QNAMEs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900487 if (c >= 64) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900488
489 p += c;
490 /* we rely on the bound check at the start
491 * of the loop here */
492 }
493 /* malformed data */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900494 VLOG << "malformed QNAME";
Bernie Innocenti55864192018-08-30 04:05:20 +0900495 return 0;
496}
497
498/* parse and skip a given QR stored in a packet.
499 * returns 1 on success, and 0 on failure
500 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900501static int _dnsPacket_checkQR(DnsPacket* packet) {
502 if (!_dnsPacket_checkQName(packet)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900503
504 /* TYPE must be one of the things we support */
505 if (!_dnsPacket_checkBytes(packet, 2, DNS_TYPE_A) &&
506 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_PTR) &&
507 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_MX) &&
508 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_AAAA) &&
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900509 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_ALL)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900510 VLOG << "unsupported TYPE";
Bernie Innocenti55864192018-08-30 04:05:20 +0900511 return 0;
512 }
513 /* CLASS must be IN */
514 if (!_dnsPacket_checkBytes(packet, 2, DNS_CLASS_IN)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900515 VLOG << "unsupported CLASS";
Bernie Innocenti55864192018-08-30 04:05:20 +0900516 return 0;
517 }
518
519 return 1;
520}
521
522/* check the header of a DNS Query packet, return 1 if it is one
523 * type of query we can cache, or 0 otherwise
524 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900525static int _dnsPacket_checkQuery(DnsPacket* packet) {
526 const uint8_t* p = packet->base;
527 int qdCount, anCount, dnCount, arCount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900528
529 if (p + DNS_HEADER_SIZE > packet->end) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900530 VLOG << "query packet too small";
Bernie Innocenti55864192018-08-30 04:05:20 +0900531 return 0;
532 }
533
534 /* QR must be set to 0, opcode must be 0 and AA must be 0 */
535 /* RA, Z, and RCODE must be 0 */
536 if ((p[2] & 0xFC) != 0 || (p[3] & 0xCF) != 0) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900537 VLOG << "query packet flags unsupported";
Bernie Innocenti55864192018-08-30 04:05:20 +0900538 return 0;
539 }
540
541 /* Note that we ignore the TC, RD, CD, and AD bits here for the
542 * following reasons:
543 *
544 * - there is no point for a query packet sent to a server
545 * to have the TC bit set, but the implementation might
546 * set the bit in the query buffer for its own needs
547 * between a _resolv_cache_lookup and a
548 * _resolv_cache_add. We should not freak out if this
549 * is the case.
550 *
551 * - we consider that the result from a query might depend on
552 * the RD, AD, and CD bits, so these bits
553 * should be used to differentiate cached result.
554 *
555 * this implies that these bits are checked when hashing or
556 * comparing query packets, but not TC
557 */
558
559 /* ANCOUNT, DNCOUNT and ARCOUNT must be 0 */
560 qdCount = (p[4] << 8) | p[5];
561 anCount = (p[6] << 8) | p[7];
562 dnCount = (p[8] << 8) | p[9];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900563 arCount = (p[10] << 8) | p[11];
Bernie Innocenti55864192018-08-30 04:05:20 +0900564
565 if (anCount != 0 || dnCount != 0 || arCount > 1) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900566 VLOG << "query packet contains non-query records";
Bernie Innocenti55864192018-08-30 04:05:20 +0900567 return 0;
568 }
569
570 if (qdCount == 0) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900571 VLOG << "query packet doesn't contain query record";
Bernie Innocenti55864192018-08-30 04:05:20 +0900572 return 0;
573 }
574
575 /* Check QDCOUNT QRs */
576 packet->cursor = p + DNS_HEADER_SIZE;
577
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900578 for (; qdCount > 0; qdCount--)
579 if (!_dnsPacket_checkQR(packet)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900580
581 return 1;
582}
583
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900584/** QUERY DEBUGGING **/
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900585static char* dnsPacket_bprintQName(DnsPacket* packet, char* bp, char* bend) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900586 const uint8_t* p = packet->cursor;
587 const uint8_t* end = packet->end;
588 int first = 1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900589
590 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900591 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900592
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900593 if (p >= end) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900594
595 c = *p++;
596
597 if (c == 0) {
598 packet->cursor = p;
599 return bp;
600 }
601
602 /* we don't expect label compression in QNAMEs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900603 if (c >= 64) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900604
605 if (first)
606 first = 0;
607 else
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900608 bp = bprint_c(bp, bend, '.');
Bernie Innocenti55864192018-08-30 04:05:20 +0900609
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900610 bp = bprint_b(bp, bend, (const char*) p, c);
Bernie Innocenti55864192018-08-30 04:05:20 +0900611
612 p += c;
613 /* we rely on the bound check at the start
614 * of the loop here */
615 }
616 /* malformed data */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900617 bp = bprint_s(bp, bend, "<MALFORMED>");
Bernie Innocenti55864192018-08-30 04:05:20 +0900618 return bp;
619}
620
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900621static char* dnsPacket_bprintQR(DnsPacket* packet, char* p, char* end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900622#define QQ(x) \
623 { DNS_TYPE_##x, #x }
Bernie Innocenti55864192018-08-30 04:05:20 +0900624 static const struct {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900625 const char* typeBytes;
626 const char* typeString;
627 } qTypes[] = {QQ(A), QQ(PTR), QQ(MX), QQ(AAAA), QQ(ALL), {NULL, NULL}};
628 int nn;
629 const char* typeString = NULL;
Bernie Innocenti55864192018-08-30 04:05:20 +0900630
631 /* dump QNAME */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900632 p = dnsPacket_bprintQName(packet, p, end);
Bernie Innocenti55864192018-08-30 04:05:20 +0900633
634 /* dump TYPE */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900635 p = bprint_s(p, end, " (");
Bernie Innocenti55864192018-08-30 04:05:20 +0900636
637 for (nn = 0; qTypes[nn].typeBytes != NULL; nn++) {
638 if (_dnsPacket_checkBytes(packet, 2, qTypes[nn].typeBytes)) {
639 typeString = qTypes[nn].typeString;
640 break;
641 }
642 }
643
644 if (typeString != NULL)
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900645 p = bprint_s(p, end, typeString);
Bernie Innocenti55864192018-08-30 04:05:20 +0900646 else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900647 int typeCode = _dnsPacket_readInt16(packet);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900648 p = bprint(p, end, "UNKNOWN-%d", typeCode);
Bernie Innocenti55864192018-08-30 04:05:20 +0900649 }
650
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900651 p = bprint_c(p, end, ')');
Bernie Innocenti55864192018-08-30 04:05:20 +0900652
653 /* skip CLASS */
654 _dnsPacket_skip(packet, 2);
655 return p;
656}
657
658/* this function assumes the packet has already been checked */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900659static char* dnsPacket_bprintQuery(DnsPacket* packet, char* p, char* end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900660 int qdCount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900661
662 if (packet->base[2] & 0x1) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900663 p = bprint_s(p, end, "RECURSIVE ");
Bernie Innocenti55864192018-08-30 04:05:20 +0900664 }
665
666 _dnsPacket_skip(packet, 4);
667 qdCount = _dnsPacket_readInt16(packet);
668 _dnsPacket_skip(packet, 6);
669
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900670 for (; qdCount > 0; qdCount--) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900671 p = dnsPacket_bprintQR(packet, p, end);
Bernie Innocenti55864192018-08-30 04:05:20 +0900672 }
673 return p;
674}
Bernie Innocenti55864192018-08-30 04:05:20 +0900675
Bernie Innocenti55864192018-08-30 04:05:20 +0900676/** QUERY HASHING SUPPORT
677 **
678 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKET HAS ALREADY
679 ** BEEN SUCCESFULLY CHECKED.
680 **/
681
682/* use 32-bit FNV hash function */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900683#define FNV_MULT 16777619U
684#define FNV_BASIS 2166136261U
Bernie Innocenti55864192018-08-30 04:05:20 +0900685
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900686static unsigned _dnsPacket_hashBytes(DnsPacket* packet, int numBytes, unsigned hash) {
687 const uint8_t* p = packet->cursor;
688 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900689
690 while (numBytes > 0 && p < end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900691 hash = hash * FNV_MULT ^ *p++;
Bernie Innocenti55864192018-08-30 04:05:20 +0900692 }
693 packet->cursor = p;
694 return hash;
695}
696
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900697static unsigned _dnsPacket_hashQName(DnsPacket* packet, unsigned hash) {
698 const uint8_t* p = packet->cursor;
699 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900700
701 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900702 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900703
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900704 if (p >= end) { /* should not happen */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900705 VLOG << __func__ << ": INTERNAL_ERROR: read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900706 break;
707 }
708
709 c = *p++;
710
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900711 if (c == 0) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900712
713 if (c >= 64) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900714 VLOG << __func__ << ": INTERNAL_ERROR: malformed domain";
Bernie Innocenti55864192018-08-30 04:05:20 +0900715 break;
716 }
717 if (p + c >= end) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900718 VLOG << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900719 break;
720 }
721 while (c > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900722 hash = hash * FNV_MULT ^ *p++;
723 c -= 1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900724 }
725 }
726 packet->cursor = p;
727 return hash;
728}
729
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900730static unsigned _dnsPacket_hashQR(DnsPacket* packet, unsigned hash) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900731 hash = _dnsPacket_hashQName(packet, hash);
732 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TYPE and CLASS */
733 return hash;
734}
735
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900736static unsigned _dnsPacket_hashRR(DnsPacket* packet, unsigned hash) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900737 int rdlength;
738 hash = _dnsPacket_hashQR(packet, hash);
739 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TTL */
740 rdlength = _dnsPacket_readInt16(packet);
741 hash = _dnsPacket_hashBytes(packet, rdlength, hash); /* RDATA */
742 return hash;
743}
744
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900745static unsigned _dnsPacket_hashQuery(DnsPacket* packet) {
746 unsigned hash = FNV_BASIS;
747 int count, arcount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900748 _dnsPacket_rewind(packet);
749
750 /* ignore the ID */
751 _dnsPacket_skip(packet, 2);
752
753 /* we ignore the TC bit for reasons explained in
754 * _dnsPacket_checkQuery().
755 *
756 * however we hash the RD bit to differentiate
757 * between answers for recursive and non-recursive
758 * queries.
759 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900760 hash = hash * FNV_MULT ^ (packet->base[2] & 1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900761
762 /* mark the first header byte as processed */
763 _dnsPacket_skip(packet, 1);
764
765 /* process the second header byte */
766 hash = _dnsPacket_hashBytes(packet, 1, hash);
767
768 /* read QDCOUNT */
769 count = _dnsPacket_readInt16(packet);
770
771 /* assume: ANcount and NScount are 0 */
772 _dnsPacket_skip(packet, 4);
773
774 /* read ARCOUNT */
775 arcount = _dnsPacket_readInt16(packet);
776
777 /* hash QDCOUNT QRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900778 for (; count > 0; count--) hash = _dnsPacket_hashQR(packet, hash);
Bernie Innocenti55864192018-08-30 04:05:20 +0900779
780 /* hash ARCOUNT RRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900781 for (; arcount > 0; arcount--) hash = _dnsPacket_hashRR(packet, hash);
Bernie Innocenti55864192018-08-30 04:05:20 +0900782
783 return hash;
784}
785
Bernie Innocenti55864192018-08-30 04:05:20 +0900786/** QUERY COMPARISON
787 **
788 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKETS HAVE ALREADY
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900789 ** BEEN SUCCESSFULLY CHECKED.
Bernie Innocenti55864192018-08-30 04:05:20 +0900790 **/
791
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900792static int _dnsPacket_isEqualDomainName(DnsPacket* pack1, DnsPacket* pack2) {
793 const uint8_t* p1 = pack1->cursor;
794 const uint8_t* end1 = pack1->end;
795 const uint8_t* p2 = pack2->cursor;
796 const uint8_t* end2 = pack2->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900797
798 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900799 int c1, c2;
Bernie Innocenti55864192018-08-30 04:05:20 +0900800
801 if (p1 >= end1 || p2 >= end2) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900802 VLOG << __func__ << ": INTERNAL_ERROR: read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900803 break;
804 }
805 c1 = *p1++;
806 c2 = *p2++;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900807 if (c1 != c2) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900808
809 if (c1 == 0) {
810 pack1->cursor = p1;
811 pack2->cursor = p2;
812 return 1;
813 }
814 if (c1 >= 64) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900815 VLOG << __func__ << ": INTERNAL_ERROR: malformed domain";
Bernie Innocenti55864192018-08-30 04:05:20 +0900816 break;
817 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900818 if ((p1 + c1 > end1) || (p2 + c1 > end2)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900819 VLOG << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900820 break;
821 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900822 if (memcmp(p1, p2, c1) != 0) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900823 p1 += c1;
824 p2 += c1;
825 /* we rely on the bound checks at the start of the loop */
826 }
827 /* not the same, or one is malformed */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900828 VLOG << "different DN";
Bernie Innocenti55864192018-08-30 04:05:20 +0900829 return 0;
830}
831
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900832static int _dnsPacket_isEqualBytes(DnsPacket* pack1, DnsPacket* pack2, int numBytes) {
833 const uint8_t* p1 = pack1->cursor;
834 const uint8_t* p2 = pack2->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900835
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900836 if (p1 + numBytes > pack1->end || p2 + numBytes > pack2->end) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900837
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900838 if (memcmp(p1, p2, numBytes) != 0) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900839
840 pack1->cursor += numBytes;
841 pack2->cursor += numBytes;
842 return 1;
843}
844
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900845static int _dnsPacket_isEqualQR(DnsPacket* pack1, DnsPacket* pack2) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900846 /* compare domain name encoding + TYPE + CLASS */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900847 if (!_dnsPacket_isEqualDomainName(pack1, pack2) ||
848 !_dnsPacket_isEqualBytes(pack1, pack2, 2 + 2))
Bernie Innocenti55864192018-08-30 04:05:20 +0900849 return 0;
850
851 return 1;
852}
853
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900854static int _dnsPacket_isEqualRR(DnsPacket* pack1, DnsPacket* pack2) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900855 int rdlength1, rdlength2;
856 /* compare query + TTL */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900857 if (!_dnsPacket_isEqualQR(pack1, pack2) || !_dnsPacket_isEqualBytes(pack1, pack2, 4)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900858
859 /* compare RDATA */
860 rdlength1 = _dnsPacket_readInt16(pack1);
861 rdlength2 = _dnsPacket_readInt16(pack2);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900862 if (rdlength1 != rdlength2 || !_dnsPacket_isEqualBytes(pack1, pack2, rdlength1)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900863
864 return 1;
865}
866
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900867static int _dnsPacket_isEqualQuery(DnsPacket* pack1, DnsPacket* pack2) {
868 int count1, count2, arcount1, arcount2;
Bernie Innocenti55864192018-08-30 04:05:20 +0900869
870 /* compare the headers, ignore most fields */
871 _dnsPacket_rewind(pack1);
872 _dnsPacket_rewind(pack2);
873
874 /* compare RD, ignore TC, see comment in _dnsPacket_checkQuery */
875 if ((pack1->base[2] & 1) != (pack2->base[2] & 1)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900876 VLOG << "different RD";
Bernie Innocenti55864192018-08-30 04:05:20 +0900877 return 0;
878 }
879
880 if (pack1->base[3] != pack2->base[3]) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900881 VLOG << "different CD or AD";
Bernie Innocenti55864192018-08-30 04:05:20 +0900882 return 0;
883 }
884
885 /* mark ID and header bytes as compared */
886 _dnsPacket_skip(pack1, 4);
887 _dnsPacket_skip(pack2, 4);
888
889 /* compare QDCOUNT */
890 count1 = _dnsPacket_readInt16(pack1);
891 count2 = _dnsPacket_readInt16(pack2);
892 if (count1 != count2 || count1 < 0) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900893 VLOG << "different QDCOUNT";
Bernie Innocenti55864192018-08-30 04:05:20 +0900894 return 0;
895 }
896
897 /* assume: ANcount and NScount are 0 */
898 _dnsPacket_skip(pack1, 4);
899 _dnsPacket_skip(pack2, 4);
900
901 /* compare ARCOUNT */
902 arcount1 = _dnsPacket_readInt16(pack1);
903 arcount2 = _dnsPacket_readInt16(pack2);
904 if (arcount1 != arcount2 || arcount1 < 0) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900905 VLOG << "different ARCOUNT";
Bernie Innocenti55864192018-08-30 04:05:20 +0900906 return 0;
907 }
908
909 /* compare the QDCOUNT QRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900910 for (; count1 > 0; count1--) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900911 if (!_dnsPacket_isEqualQR(pack1, pack2)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900912 VLOG << "different QR";
Bernie Innocenti55864192018-08-30 04:05:20 +0900913 return 0;
914 }
915 }
916
917 /* compare the ARCOUNT RRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900918 for (; arcount1 > 0; arcount1--) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900919 if (!_dnsPacket_isEqualRR(pack1, pack2)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900920 VLOG << "different additional RR";
Bernie Innocenti55864192018-08-30 04:05:20 +0900921 return 0;
922 }
923 }
924 return 1;
925}
926
Bernie Innocenti55864192018-08-30 04:05:20 +0900927/* cache entry. for simplicity, 'hash' and 'hlink' are inlined in this
928 * structure though they are conceptually part of the hash table.
929 *
930 * similarly, mru_next and mru_prev are part of the global MRU list
931 */
932typedef struct Entry {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900933 unsigned int hash; /* hash value */
934 struct Entry* hlink; /* next in collision chain */
935 struct Entry* mru_prev;
936 struct Entry* mru_next;
Bernie Innocenti55864192018-08-30 04:05:20 +0900937
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900938 const uint8_t* query;
939 int querylen;
940 const uint8_t* answer;
941 int answerlen;
942 time_t expires; /* time_t when the entry isn't valid any more */
943 int id; /* for debugging purpose */
Bernie Innocenti55864192018-08-30 04:05:20 +0900944} Entry;
945
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900946/*
Bernie Innocenti55864192018-08-30 04:05:20 +0900947 * Find the TTL for a negative DNS result. This is defined as the minimum
948 * of the SOA records TTL and the MINIMUM-TTL field (RFC-2308).
949 *
950 * Return 0 if not found.
951 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900952static u_long answer_getNegativeTTL(ns_msg handle) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900953 int n, nscount;
954 u_long result = 0;
955 ns_rr rr;
956
957 nscount = ns_msg_count(handle, ns_s_ns);
958 for (n = 0; n < nscount; n++) {
959 if ((ns_parserr(&handle, ns_s_ns, n, &rr) == 0) && (ns_rr_type(rr) == ns_t_soa)) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900960 const u_char* rdata = ns_rr_rdata(rr); // find the data
961 const u_char* edata = rdata + ns_rr_rdlen(rr); // add the len to find the end
Bernie Innocenti55864192018-08-30 04:05:20 +0900962 int len;
963 u_long ttl, rec_result = ns_rr_ttl(rr);
964
965 // find the MINIMUM-TTL field from the blob of binary data for this record
966 // skip the server name
967 len = dn_skipname(rdata, edata);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900968 if (len == -1) continue; // error skipping
Bernie Innocenti55864192018-08-30 04:05:20 +0900969 rdata += len;
970
971 // skip the admin name
972 len = dn_skipname(rdata, edata);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900973 if (len == -1) continue; // error skipping
Bernie Innocenti55864192018-08-30 04:05:20 +0900974 rdata += len;
975
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900976 if (edata - rdata != 5 * NS_INT32SZ) continue;
Bernie Innocenti55864192018-08-30 04:05:20 +0900977 // skip: serial number + refresh interval + retry interval + expiry
978 rdata += NS_INT32SZ * 4;
979 // finally read the MINIMUM TTL
980 ttl = ns_get32(rdata);
981 if (ttl < rec_result) {
982 rec_result = ttl;
983 }
984 // Now that the record is read successfully, apply the new min TTL
985 if (n == 0 || rec_result < result) {
986 result = rec_result;
987 }
988 }
989 }
990 return result;
991}
992
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900993/*
Bernie Innocenti55864192018-08-30 04:05:20 +0900994 * Parse the answer records and find the appropriate
995 * smallest TTL among the records. This might be from
996 * the answer records if found or from the SOA record
997 * if it's a negative result.
998 *
999 * The returned TTL is the number of seconds to
1000 * keep the answer in the cache.
1001 *
1002 * In case of parse error zero (0) is returned which
1003 * indicates that the answer shall not be cached.
1004 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001005static u_long answer_getTTL(const void* answer, int answerlen) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001006 ns_msg handle;
1007 int ancount, n;
1008 u_long result, ttl;
1009 ns_rr rr;
1010
1011 result = 0;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001012 if (ns_initparse((const uint8_t*) answer, answerlen, &handle) >= 0) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001013 // get number of answer records
1014 ancount = ns_msg_count(handle, ns_s_an);
1015
1016 if (ancount == 0) {
1017 // a response with no answers? Cache this negative result.
1018 result = answer_getNegativeTTL(handle);
1019 } else {
1020 for (n = 0; n < ancount; n++) {
1021 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
1022 ttl = ns_rr_ttl(rr);
1023 if (n == 0 || ttl < result) {
1024 result = ttl;
1025 }
1026 } else {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001027 VLOG << "ns_parserr failed ancount no = "
1028 << n << ". errno = " << strerror(errno);
Bernie Innocenti55864192018-08-30 04:05:20 +09001029 }
1030 }
1031 }
1032 } else {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001033 VLOG << "ns_initparse failed: " << strerror(errno);
Bernie Innocenti55864192018-08-30 04:05:20 +09001034 }
1035
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001036 VLOG << "TTL = " << result;
Bernie Innocenti55864192018-08-30 04:05:20 +09001037 return result;
1038}
1039
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001040static void entry_free(Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001041 /* everything is allocated in a single memory block */
1042 if (e) {
1043 free(e);
1044 }
1045}
1046
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001047static void entry_mru_remove(Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001048 e->mru_prev->mru_next = e->mru_next;
1049 e->mru_next->mru_prev = e->mru_prev;
1050}
1051
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001052static void entry_mru_add(Entry* e, Entry* list) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001053 Entry* first = list->mru_next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001054
1055 e->mru_next = first;
1056 e->mru_prev = list;
1057
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001058 list->mru_next = e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001059 first->mru_prev = e;
1060}
1061
1062/* compute the hash of a given entry, this is a hash of most
1063 * data in the query (key) */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001064static unsigned entry_hash(const Entry* e) {
1065 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001066
1067 _dnsPacket_init(pack, e->query, e->querylen);
1068 return _dnsPacket_hashQuery(pack);
1069}
1070
1071/* initialize an Entry as a search key, this also checks the input query packet
1072 * returns 1 on success, or 0 in case of unsupported/malformed data */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001073static int entry_init_key(Entry* e, const void* query, int querylen) {
1074 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001075
1076 memset(e, 0, sizeof(*e));
1077
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001078 e->query = (const uint8_t*) query;
Bernie Innocenti55864192018-08-30 04:05:20 +09001079 e->querylen = querylen;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001080 e->hash = entry_hash(e);
Bernie Innocenti55864192018-08-30 04:05:20 +09001081
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001082 _dnsPacket_init(pack, e->query, e->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001083
1084 return _dnsPacket_checkQuery(pack);
1085}
1086
1087/* allocate a new entry as a cache node */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001088static Entry* entry_alloc(const Entry* init, const void* answer, int answerlen) {
1089 Entry* e;
1090 int size;
Bernie Innocenti55864192018-08-30 04:05:20 +09001091
1092 size = sizeof(*e) + init->querylen + answerlen;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001093 e = (Entry*) calloc(size, 1);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001094 if (e == NULL) return e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001095
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001096 e->hash = init->hash;
1097 e->query = (const uint8_t*) (e + 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001098 e->querylen = init->querylen;
1099
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001100 memcpy((char*) e->query, init->query, e->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001101
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001102 e->answer = e->query + e->querylen;
Bernie Innocenti55864192018-08-30 04:05:20 +09001103 e->answerlen = answerlen;
1104
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001105 memcpy((char*) e->answer, answer, e->answerlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001106
1107 return e;
1108}
1109
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001110static int entry_equals(const Entry* e1, const Entry* e2) {
1111 DnsPacket pack1[1], pack2[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001112
1113 if (e1->querylen != e2->querylen) {
1114 return 0;
1115 }
1116 _dnsPacket_init(pack1, e1->query, e1->querylen);
1117 _dnsPacket_init(pack2, e2->query, e2->querylen);
1118
1119 return _dnsPacket_isEqualQuery(pack1, pack2);
1120}
1121
Bernie Innocenti55864192018-08-30 04:05:20 +09001122/* We use a simple hash table with external collision lists
1123 * for simplicity, the hash-table fields 'hash' and 'hlink' are
1124 * inlined in the Entry structure.
1125 */
1126
1127/* Maximum time for a thread to wait for an pending request */
Ken Chen2a429352018-12-22 21:46:55 +08001128constexpr int PENDING_REQUEST_TIMEOUT = 20;
Bernie Innocenti55864192018-08-30 04:05:20 +09001129
1130typedef struct resolv_cache {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001131 int max_entries;
1132 int num_entries;
1133 Entry mru_list;
1134 int last_id;
1135 Entry* entries;
Ken Chen2a429352018-12-22 21:46:55 +08001136 struct pending_req_info {
1137 unsigned int hash;
1138 struct pending_req_info* next;
1139 } pending_requests;
Bernie Innocenti55864192018-08-30 04:05:20 +09001140} Cache;
1141
1142struct resolv_cache_info {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001143 unsigned netid;
1144 Cache* cache;
1145 struct resolv_cache_info* next;
1146 int nscount;
1147 char* nameservers[MAXNS];
1148 struct addrinfo* nsaddrinfo[MAXNS];
1149 int revision_id; // # times the nameservers have been replaced
Bernie Innocenti34de3ba2019-02-19 18:08:36 +09001150 res_params params;
Bernie Innocenti189eb502018-10-01 23:10:18 +09001151 struct res_stats nsstats[MAXNS];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001152 char defdname[MAXDNSRCHPATH];
1153 int dnsrch_offset[MAXDNSRCH + 1]; // offsets into defdname
Ken Chen2a429352018-12-22 21:46:55 +08001154 int wait_for_pending_req_timeout_count;
Bernie Innocenti55864192018-08-30 04:05:20 +09001155};
1156
Ken Chen2a429352018-12-22 21:46:55 +08001157// A helper class for the Clang Thread Safety Analysis to deal with
1158// std::unique_lock.
1159class SCOPED_CAPABILITY ScopedAssumeLocked {
1160 public:
1161 ScopedAssumeLocked(std::mutex& mutex) ACQUIRE(mutex) {}
1162 ~ScopedAssumeLocked() RELEASE() {}
1163};
Bernie Innocenti55864192018-08-30 04:05:20 +09001164
Ken Chen2a429352018-12-22 21:46:55 +08001165// lock protecting everything in the resolve_cache_info structs (next ptr, etc)
1166static std::mutex cache_mutex;
1167static std::condition_variable cv;
Bernie Innocenti55864192018-08-30 04:05:20 +09001168
1169/* gets cache associated with a network, or NULL if none exists */
Ken Chen2a429352018-12-22 21:46:55 +08001170static struct resolv_cache* find_named_cache_locked(unsigned netid) REQUIRES(cache_mutex);
1171static resolv_cache* get_res_cache_for_net_locked(unsigned netid) REQUIRES(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001172
Ken Chen2a429352018-12-22 21:46:55 +08001173static void cache_flush_pending_requests_locked(struct resolv_cache* cache) {
1174 resolv_cache::pending_req_info *ri, *tmp;
1175 if (!cache) return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001176
Ken Chen2a429352018-12-22 21:46:55 +08001177 ri = cache->pending_requests.next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001178
Ken Chen2a429352018-12-22 21:46:55 +08001179 while (ri) {
1180 tmp = ri;
1181 ri = ri->next;
1182 free(tmp);
Bernie Innocenti55864192018-08-30 04:05:20 +09001183 }
1184
Ken Chen2a429352018-12-22 21:46:55 +08001185 cache->pending_requests.next = NULL;
1186 cv.notify_all();
Bernie Innocenti55864192018-08-30 04:05:20 +09001187}
1188
Ken Chen2a429352018-12-22 21:46:55 +08001189// Return true - if there is a pending request in |cache| matching |key|.
1190// Return false - if no pending request is found matching the key. Optionally
1191// link a new one if parameter append_if_not_found is true.
1192static bool cache_has_pending_request_locked(resolv_cache* cache, const Entry* key,
1193 bool append_if_not_found) {
1194 if (!cache || !key) return false;
Bernie Innocenti55864192018-08-30 04:05:20 +09001195
Ken Chen2a429352018-12-22 21:46:55 +08001196 resolv_cache::pending_req_info* ri = cache->pending_requests.next;
1197 resolv_cache::pending_req_info* prev = &cache->pending_requests;
1198 while (ri) {
1199 if (ri->hash == key->hash) {
1200 return true;
Bernie Innocenti55864192018-08-30 04:05:20 +09001201 }
Ken Chen2a429352018-12-22 21:46:55 +08001202 prev = ri;
1203 ri = ri->next;
1204 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001205
Ken Chen2a429352018-12-22 21:46:55 +08001206 if (append_if_not_found) {
1207 ri = (resolv_cache::pending_req_info*)calloc(1, sizeof(resolv_cache::pending_req_info));
Bernie Innocenti55864192018-08-30 04:05:20 +09001208 if (ri) {
Ken Chen2a429352018-12-22 21:46:55 +08001209 ri->hash = key->hash;
1210 prev->next = ri;
Bernie Innocenti55864192018-08-30 04:05:20 +09001211 }
1212 }
Ken Chen2a429352018-12-22 21:46:55 +08001213 return false;
1214}
1215
1216// Notify all threads that the cache entry |key| has become available
1217static void _cache_notify_waiting_tid_locked(struct resolv_cache* cache, const Entry* key) {
1218 if (!cache || !key) return;
1219
1220 resolv_cache::pending_req_info* ri = cache->pending_requests.next;
1221 resolv_cache::pending_req_info* prev = &cache->pending_requests;
1222 while (ri) {
1223 if (ri->hash == key->hash) {
1224 // remove item from list and destroy
1225 prev->next = ri->next;
1226 free(ri);
1227 cv.notify_all();
1228 return;
1229 }
1230 prev = ri;
1231 ri = ri->next;
1232 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001233}
1234
Luke Huang952d0942018-12-26 16:53:03 +08001235void _resolv_cache_query_failed(unsigned netid, const void* query, int querylen, uint32_t flags) {
1236 // We should not notify with these flags.
1237 if (flags & (ANDROID_RESOLV_NO_CACHE_STORE | ANDROID_RESOLV_NO_CACHE_LOOKUP)) {
1238 return;
1239 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001240 Entry key[1];
1241 Cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001242
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001243 if (!entry_init_key(key, query, querylen)) return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001244
Ken Chen2a429352018-12-22 21:46:55 +08001245 std::lock_guard guard(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001246
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001247 cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001248
1249 if (cache) {
1250 _cache_notify_waiting_tid_locked(cache, key);
1251 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001252}
1253
Bernie Innocentid2b27032018-12-18 19:53:42 +09001254static void cache_flush_locked(Cache* cache) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001255 int nn;
Bernie Innocenti55864192018-08-30 04:05:20 +09001256
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001257 for (nn = 0; nn < cache->max_entries; nn++) {
1258 Entry** pnode = (Entry**) &cache->entries[nn];
Bernie Innocenti55864192018-08-30 04:05:20 +09001259
1260 while (*pnode != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001261 Entry* node = *pnode;
Bernie Innocenti55864192018-08-30 04:05:20 +09001262 *pnode = node->hlink;
1263 entry_free(node);
1264 }
1265 }
1266
1267 // flush pending request
Ken Chen2a429352018-12-22 21:46:55 +08001268 cache_flush_pending_requests_locked(cache);
Bernie Innocenti55864192018-08-30 04:05:20 +09001269
1270 cache->mru_list.mru_next = cache->mru_list.mru_prev = &cache->mru_list;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001271 cache->num_entries = 0;
1272 cache->last_id = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +09001273
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001274 VLOG << "*** DNS CACHE FLUSHED ***";
Bernie Innocenti55864192018-08-30 04:05:20 +09001275}
1276
Ken Chen2a429352018-12-22 21:46:55 +08001277static resolv_cache* resolv_cache_create() {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001278 struct resolv_cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001279
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001280 cache = (struct resolv_cache*) calloc(sizeof(*cache), 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001281 if (cache) {
nuccachen989d2232018-11-29 17:41:12 +08001282 cache->max_entries = CONFIG_MAX_ENTRIES;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001283 cache->entries = (Entry*) calloc(sizeof(*cache->entries), cache->max_entries);
Bernie Innocenti55864192018-08-30 04:05:20 +09001284 if (cache->entries) {
1285 cache->mru_list.mru_prev = cache->mru_list.mru_next = &cache->mru_list;
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001286 VLOG << __func__ << ": cache created";
Bernie Innocenti55864192018-08-30 04:05:20 +09001287 } else {
1288 free(cache);
1289 cache = NULL;
1290 }
1291 }
1292 return cache;
1293}
1294
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001295static void dump_query(const uint8_t* query, int querylen) {
1296 if (!kVerboseLogging) return;
1297
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001298 char temp[256], *p = temp, *end = p + sizeof(temp);
1299 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001300
1301 _dnsPacket_init(pack, query, querylen);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001302 p = dnsPacket_bprintQuery(pack, p, end);
1303 VLOG << temp;
Bernie Innocenti55864192018-08-30 04:05:20 +09001304}
1305
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001306static void cache_dump_mru(Cache* cache) {
1307 if (!kVerboseLogging) return;
1308
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001309 char temp[512], *p = temp, *end = p + sizeof(temp);
1310 Entry* e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001311
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001312 p = bprint(temp, end, "MRU LIST (%2d): ", cache->num_entries);
Bernie Innocenti55864192018-08-30 04:05:20 +09001313 for (e = cache->mru_list.mru_next; e != &cache->mru_list; e = e->mru_next)
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001314 p = bprint(p, end, " %d", e->id);
Bernie Innocenti55864192018-08-30 04:05:20 +09001315
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001316 VLOG << temp;
Bernie Innocenti55864192018-08-30 04:05:20 +09001317}
1318
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001319// TODO: Rewrite to avoid creating a file in /data as temporary buffer (WAT).
1320static void dump_answer(const u_char* answer, int answerlen) {
1321 if (!kVerboseLogging) return;
1322
Bernie Innocenti55864192018-08-30 04:05:20 +09001323 res_state statep;
1324 FILE* fp;
1325 char* buf;
1326 int fileLen;
1327
1328 fp = fopen("/data/reslog.txt", "w+e");
1329 if (fp != NULL) {
Bernie Innocenti4acba1a2018-09-26 11:52:04 +09001330 statep = res_get_state();
Bernie Innocenti55864192018-08-30 04:05:20 +09001331
1332 res_pquery(statep, answer, answerlen, fp);
1333
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001334 // Get file length
Bernie Innocenti55864192018-08-30 04:05:20 +09001335 fseek(fp, 0, SEEK_END);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001336 fileLen = ftell(fp);
Bernie Innocenti55864192018-08-30 04:05:20 +09001337 fseek(fp, 0, SEEK_SET);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001338 buf = (char*) malloc(fileLen + 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001339 if (buf != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001340 // Read file contents into buffer
Bernie Innocenti55864192018-08-30 04:05:20 +09001341 fread(buf, fileLen, 1, fp);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001342 VLOG << buf;
Bernie Innocenti55864192018-08-30 04:05:20 +09001343 free(buf);
1344 }
1345 fclose(fp);
1346 remove("/data/reslog.txt");
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001347 } else {
1348 errno = 0; // else debug is introducing error signals
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001349 VLOG << __func__ << ": can't open file";
Bernie Innocenti55864192018-08-30 04:05:20 +09001350 }
1351}
Bernie Innocenti55864192018-08-30 04:05:20 +09001352
1353/* This function tries to find a key within the hash table
1354 * In case of success, it will return a *pointer* to the hashed key.
1355 * In case of failure, it will return a *pointer* to NULL
1356 *
1357 * So, the caller must check '*result' to check for success/failure.
1358 *
1359 * The main idea is that the result can later be used directly in
1360 * calls to _resolv_cache_add or _resolv_cache_remove as the 'lookup'
1361 * parameter. This makes the code simpler and avoids re-searching
1362 * for the key position in the htable.
1363 *
1364 * The result of a lookup_p is only valid until you alter the hash
1365 * table.
1366 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001367static Entry** _cache_lookup_p(Cache* cache, Entry* key) {
1368 int index = key->hash % cache->max_entries;
1369 Entry** pnode = (Entry**) &cache->entries[index];
Bernie Innocenti55864192018-08-30 04:05:20 +09001370
1371 while (*pnode != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001372 Entry* node = *pnode;
Bernie Innocenti55864192018-08-30 04:05:20 +09001373
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001374 if (node == NULL) break;
Bernie Innocenti55864192018-08-30 04:05:20 +09001375
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001376 if (node->hash == key->hash && entry_equals(node, key)) break;
Bernie Innocenti55864192018-08-30 04:05:20 +09001377
1378 pnode = &node->hlink;
1379 }
1380 return pnode;
1381}
1382
1383/* Add a new entry to the hash table. 'lookup' must be the
1384 * result of an immediate previous failed _lookup_p() call
1385 * (i.e. with *lookup == NULL), and 'e' is the pointer to the
1386 * newly created entry
1387 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001388static void _cache_add_p(Cache* cache, Entry** lookup, Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001389 *lookup = e;
1390 e->id = ++cache->last_id;
1391 entry_mru_add(e, &cache->mru_list);
1392 cache->num_entries += 1;
1393
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001394 VLOG << __func__ << ": entry " << e->id << " added (count=" << cache->num_entries << ")";
Bernie Innocenti55864192018-08-30 04:05:20 +09001395}
1396
1397/* Remove an existing entry from the hash table,
1398 * 'lookup' must be the result of an immediate previous
1399 * and succesful _lookup_p() call.
1400 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001401static void _cache_remove_p(Cache* cache, Entry** lookup) {
1402 Entry* e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001403
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001404 VLOG << __func__ << ": entry " << e->id << " removed (count=" << cache->num_entries - 1 << ")";
Bernie Innocenti55864192018-08-30 04:05:20 +09001405
1406 entry_mru_remove(e);
1407 *lookup = e->hlink;
1408 entry_free(e);
1409 cache->num_entries -= 1;
1410}
1411
1412/* Remove the oldest entry from the hash table.
1413 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001414static void _cache_remove_oldest(Cache* cache) {
1415 Entry* oldest = cache->mru_list.mru_prev;
1416 Entry** lookup = _cache_lookup_p(cache, oldest);
Bernie Innocenti55864192018-08-30 04:05:20 +09001417
1418 if (*lookup == NULL) { /* should not happen */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001419 VLOG << __func__ << ": OLDEST NOT IN HTABLE ?";
Bernie Innocenti55864192018-08-30 04:05:20 +09001420 return;
1421 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001422 VLOG << "Cache full - removing oldest";
1423 dump_query(oldest->query, oldest->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001424 _cache_remove_p(cache, lookup);
1425}
1426
1427/* Remove all expired entries from the hash table.
1428 */
1429static void _cache_remove_expired(Cache* cache) {
1430 Entry* e;
1431 time_t now = _time_now();
1432
1433 for (e = cache->mru_list.mru_next; e != &cache->mru_list;) {
1434 // Entry is old, remove
1435 if (now >= e->expires) {
1436 Entry** lookup = _cache_lookup_p(cache, e);
1437 if (*lookup == NULL) { /* should not happen */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001438 VLOG << __func__ << ": ENTRY NOT IN HTABLE ?";
Bernie Innocenti55864192018-08-30 04:05:20 +09001439 return;
1440 }
1441 e = e->mru_next;
1442 _cache_remove_p(cache, lookup);
1443 } else {
1444 e = e->mru_next;
1445 }
1446 }
1447}
1448
Ken Chen2a429352018-12-22 21:46:55 +08001449// gets a resolv_cache_info associated with a network, or NULL if not found
1450static resolv_cache_info* find_cache_info_locked(unsigned netid) REQUIRES(cache_mutex);
1451
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001452ResolvCacheStatus _resolv_cache_lookup(unsigned netid, const void* query, int querylen,
Luke Huang952d0942018-12-26 16:53:03 +08001453 void* answer, int answersize, int* answerlen,
1454 uint32_t flags) {
1455 if (flags & ANDROID_RESOLV_NO_CACHE_LOOKUP) {
1456 return RESOLV_CACHE_SKIP;
1457 }
Ken Chen2a429352018-12-22 21:46:55 +08001458 Entry key;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001459 Entry** lookup;
1460 Entry* e;
1461 time_t now;
1462 Cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001463
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001464 VLOG << __func__ << ": lookup";
1465 dump_query((u_char*) query, querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001466
1467 /* we don't cache malformed queries */
Ken Chen2a429352018-12-22 21:46:55 +08001468 if (!entry_init_key(&key, query, querylen)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001469 VLOG << __func__ << ": unsupported query";
Bernie Innocenti55864192018-08-30 04:05:20 +09001470 return RESOLV_CACHE_UNSUPPORTED;
1471 }
1472 /* lookup cache */
Ken Chen2a429352018-12-22 21:46:55 +08001473 std::unique_lock lock(cache_mutex);
1474 ScopedAssumeLocked assume_lock(cache_mutex);
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001475 cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001476 if (cache == NULL) {
Ken Chen2a429352018-12-22 21:46:55 +08001477 return RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti55864192018-08-30 04:05:20 +09001478 }
1479
1480 /* see the description of _lookup_p to understand this.
1481 * the function always return a non-NULL pointer.
1482 */
Ken Chen2a429352018-12-22 21:46:55 +08001483 lookup = _cache_lookup_p(cache, &key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001484 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001485
1486 if (e == NULL) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001487 VLOG << "NOT IN CACHE";
Luke Huang952d0942018-12-26 16:53:03 +08001488 // If it is no-cache-store mode, we won't wait for possible query.
1489 if (flags & ANDROID_RESOLV_NO_CACHE_STORE) {
Ken Chen2a429352018-12-22 21:46:55 +08001490 return RESOLV_CACHE_SKIP;
Luke Huang952d0942018-12-26 16:53:03 +08001491 }
Ken Chen2a429352018-12-22 21:46:55 +08001492
1493 if (!cache_has_pending_request_locked(cache, &key, true)) {
1494 return RESOLV_CACHE_NOTFOUND;
1495
Bernie Innocenti55864192018-08-30 04:05:20 +09001496 } else {
Ken Chen2a429352018-12-22 21:46:55 +08001497 VLOG << "Waiting for previous request";
1498 // wait until (1) timeout OR
1499 // (2) cv is notified AND no pending request matching the |key|
1500 // (cv notifier should delete pending request before sending notification.)
1501 bool ret = cv.wait_for(lock, std::chrono::seconds(PENDING_REQUEST_TIMEOUT),
1502 [netid, &cache, &key]() REQUIRES(cache_mutex) {
1503 // Must update cache as it could have been deleted
1504 cache = find_named_cache_locked(netid);
1505 return !cache_has_pending_request_locked(cache, &key, false);
1506 });
Ken Chen111c1ba2019-02-21 03:50:11 +08001507 if (!cache) {
1508 return RESOLV_CACHE_NOTFOUND;
1509 }
Ken Chen2a429352018-12-22 21:46:55 +08001510 if (ret == false) {
1511 resolv_cache_info* info = find_cache_info_locked(netid);
1512 if (info != NULL) {
1513 info->wait_for_pending_req_timeout_count++;
1514 }
1515 }
1516 lookup = _cache_lookup_p(cache, &key);
Bernie Innocenti55864192018-08-30 04:05:20 +09001517 e = *lookup;
1518 if (e == NULL) {
Ken Chen2a429352018-12-22 21:46:55 +08001519 return RESOLV_CACHE_NOTFOUND;
Bernie Innocenti55864192018-08-30 04:05:20 +09001520 }
1521 }
1522 }
1523
1524 now = _time_now();
1525
1526 /* remove stale entries here */
1527 if (now >= e->expires) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001528 VLOG << " NOT IN CACHE (STALE ENTRY " << *lookup << "DISCARDED)";
1529 dump_query(e->query, e->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001530 _cache_remove_p(cache, lookup);
Ken Chen2a429352018-12-22 21:46:55 +08001531 return RESOLV_CACHE_NOTFOUND;
Bernie Innocenti55864192018-08-30 04:05:20 +09001532 }
1533
1534 *answerlen = e->answerlen;
1535 if (e->answerlen > answersize) {
1536 /* NOTE: we return UNSUPPORTED if the answer buffer is too short */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001537 VLOG << " ANSWER TOO LONG";
Ken Chen2a429352018-12-22 21:46:55 +08001538 return RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti55864192018-08-30 04:05:20 +09001539 }
1540
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001541 memcpy(answer, e->answer, e->answerlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001542
1543 /* bump up this entry to the top of the MRU list */
1544 if (e != cache->mru_list.mru_next) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001545 entry_mru_remove(e);
1546 entry_mru_add(e, &cache->mru_list);
Bernie Innocenti55864192018-08-30 04:05:20 +09001547 }
1548
Ken Chen2a429352018-12-22 21:46:55 +08001549 VLOG << " FOUND IN CACHE entry=" << e;
1550 return RESOLV_CACHE_FOUND;
Bernie Innocenti55864192018-08-30 04:05:20 +09001551}
1552
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001553void _resolv_cache_add(unsigned netid, const void* query, int querylen, const void* answer,
1554 int answerlen) {
1555 Entry key[1];
1556 Entry* e;
1557 Entry** lookup;
1558 u_long ttl;
1559 Cache* cache = NULL;
Bernie Innocenti55864192018-08-30 04:05:20 +09001560
1561 /* don't assume that the query has already been cached
1562 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001563 if (!entry_init_key(key, query, querylen)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001564 VLOG << __func__ << ": passed invalid query?";
Bernie Innocenti55864192018-08-30 04:05:20 +09001565 return;
1566 }
1567
Ken Chen2a429352018-12-22 21:46:55 +08001568 std::lock_guard guard(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001569
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001570 cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001571 if (cache == NULL) {
Ken Chen2a429352018-12-22 21:46:55 +08001572 return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001573 }
1574
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001575 VLOG << __func__ << ": query:";
1576 dump_query((u_char*) query, querylen);
1577 dump_answer((u_char*) answer, answerlen);
1578 if (kDumpData) {
1579 VLOG << "answer:";
1580 dump_bytes((u_char*) answer, answerlen);
1581 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001582
1583 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001584 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001585
1586 if (e != NULL) { /* should not happen */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001587 VLOG << __func__ << ": ALREADY IN CACHE (" << e << ") ? IGNORING ADD";
Ken Chen2a429352018-12-22 21:46:55 +08001588 _cache_notify_waiting_tid_locked(cache, key);
1589 return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001590 }
1591
1592 if (cache->num_entries >= cache->max_entries) {
1593 _cache_remove_expired(cache);
1594 if (cache->num_entries >= cache->max_entries) {
1595 _cache_remove_oldest(cache);
1596 }
1597 /* need to lookup again */
1598 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001599 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001600 if (e != NULL) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001601 VLOG << __func__ << ": ALREADY IN CACHE (" << e << ") ? IGNORING ADD";
Ken Chen2a429352018-12-22 21:46:55 +08001602 _cache_notify_waiting_tid_locked(cache, key);
1603 return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001604 }
1605 }
1606
1607 ttl = answer_getTTL(answer, answerlen);
1608 if (ttl > 0) {
1609 e = entry_alloc(key, answer, answerlen);
1610 if (e != NULL) {
1611 e->expires = ttl + _time_now();
1612 _cache_add_p(cache, lookup, e);
1613 }
1614 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001615
Ken Chen2a429352018-12-22 21:46:55 +08001616 cache_dump_mru(cache);
1617 _cache_notify_waiting_tid_locked(cache, key);
Bernie Innocenti55864192018-08-30 04:05:20 +09001618}
1619
Ken Chen2a429352018-12-22 21:46:55 +08001620// Head of the list of caches.
1621static struct resolv_cache_info res_cache_list GUARDED_BY(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001622
ckenb1a69a42018-12-01 17:45:18 +09001623// insert resolv_cache_info into the list of resolv_cache_infos
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001624static void insert_cache_info_locked(resolv_cache_info* cache_info);
ckenb1a69a42018-12-01 17:45:18 +09001625// creates a resolv_cache_info
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001626static resolv_cache_info* create_cache_info();
ckenb1a69a42018-12-01 17:45:18 +09001627// empty the nameservers set for the named cache
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001628static void free_nameservers_locked(resolv_cache_info* cache_info);
1629// return 1 if the provided list of name servers differs from the list of name servers
1630// currently attached to the provided cache_info
1631static int resolv_is_nameservers_equal_locked(resolv_cache_info* cache_info, const char** servers,
1632 int numservers);
ckenb1a69a42018-12-01 17:45:18 +09001633// clears the stats samples contained withing the given cache_info
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001634static void res_cache_clear_stats_locked(resolv_cache_info* cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001635
ckenb1a69a42018-12-01 17:45:18 +09001636// public API for netd to query if name server is set on specific netid
1637bool resolv_has_nameservers(unsigned netid) {
Ken Chen2a429352018-12-22 21:46:55 +08001638 std::lock_guard guard(cache_mutex);
ckenb1a69a42018-12-01 17:45:18 +09001639 resolv_cache_info* info = find_cache_info_locked(netid);
Ken Chen2a429352018-12-22 21:46:55 +08001640 return (info != nullptr) && (info->nscount > 0);
ckenb1a69a42018-12-01 17:45:18 +09001641}
1642
1643// look up the named cache, and creates one if needed
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001644static resolv_cache* get_res_cache_for_net_locked(unsigned netid) {
1645 resolv_cache* cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001646 if (!cache) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001647 resolv_cache_info* cache_info = create_cache_info();
Bernie Innocenti55864192018-08-30 04:05:20 +09001648 if (cache_info) {
Ken Chen2a429352018-12-22 21:46:55 +08001649 cache = resolv_cache_create();
Bernie Innocenti55864192018-08-30 04:05:20 +09001650 if (cache) {
1651 cache_info->cache = cache;
1652 cache_info->netid = netid;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001653 insert_cache_info_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001654 } else {
1655 free(cache_info);
1656 }
1657 }
1658 }
1659 return cache;
1660}
1661
Bernie Innocenti189eb502018-10-01 23:10:18 +09001662void resolv_delete_cache_for_net(unsigned netid) {
Ken Chen2a429352018-12-22 21:46:55 +08001663 std::lock_guard guard(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001664
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001665 struct resolv_cache_info* prev_cache_info = &res_cache_list;
Bernie Innocenti55864192018-08-30 04:05:20 +09001666
1667 while (prev_cache_info->next) {
1668 struct resolv_cache_info* cache_info = prev_cache_info->next;
1669
1670 if (cache_info->netid == netid) {
1671 prev_cache_info->next = cache_info->next;
Bernie Innocentid2b27032018-12-18 19:53:42 +09001672 cache_flush_locked(cache_info->cache);
Bernie Innocenti55864192018-08-30 04:05:20 +09001673 free(cache_info->cache->entries);
1674 free(cache_info->cache);
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001675 free_nameservers_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001676 free(cache_info);
1677 break;
1678 }
1679
1680 prev_cache_info = prev_cache_info->next;
1681 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001682}
1683
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001684static resolv_cache_info* create_cache_info() {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001685 return (struct resolv_cache_info*) calloc(sizeof(struct resolv_cache_info), 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001686}
1687
Ken Chen2a429352018-12-22 21:46:55 +08001688// TODO: convert this to a simple and efficient C++ container.
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001689static void insert_cache_info_locked(struct resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001690 struct resolv_cache_info* last;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001691 for (last = &res_cache_list; last->next; last = last->next) {}
Bernie Innocenti55864192018-08-30 04:05:20 +09001692 last->next = cache_info;
Bernie Innocenti55864192018-08-30 04:05:20 +09001693}
1694
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001695static resolv_cache* find_named_cache_locked(unsigned netid) {
ckenb1a69a42018-12-01 17:45:18 +09001696 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001697 if (info != NULL) return info->cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001698 return NULL;
1699}
1700
ckenb1a69a42018-12-01 17:45:18 +09001701static resolv_cache_info* find_cache_info_locked(unsigned netid) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001702 struct resolv_cache_info* cache_info = res_cache_list.next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001703
1704 while (cache_info) {
1705 if (cache_info->netid == netid) {
1706 break;
1707 }
1708
1709 cache_info = cache_info->next;
1710 }
1711 return cache_info;
1712}
1713
Bernie Innocenti34de3ba2019-02-19 18:08:36 +09001714static void resolv_set_default_params(res_params* params) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001715 params->sample_validity = NSSAMPLE_VALIDITY;
1716 params->success_threshold = SUCCESS_THRESHOLD;
1717 params->min_samples = 0;
1718 params->max_samples = 0;
1719 params->base_timeout_msec = 0; // 0 = legacy algorithm
waynemad193e4d2019-02-18 17:47:59 +08001720 params->retry_count = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +09001721}
1722
Bernie Innocenti45238a12018-12-04 14:57:48 +09001723int resolv_set_nameservers_for_net(unsigned netid, const char** servers, const int numservers,
Bernie Innocenti34de3ba2019-02-19 18:08:36 +09001724 const char* domains, const res_params* params) {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001725 char* cp;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001726 int* offset;
Bernie Innocenti55864192018-08-30 04:05:20 +09001727 struct addrinfo* nsaddrinfo[MAXNS];
1728
1729 if (numservers > MAXNS) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001730 VLOG << __func__ << ": numservers=" << numservers << ", MAXNS=" << MAXNS;
Bernie Innocenti55864192018-08-30 04:05:20 +09001731 return E2BIG;
1732 }
1733
1734 // Parse the addresses before actually locking or changing any state, in case there is an error.
1735 // As a side effect this also reduces the time the lock is kept.
Bernie Innocentic165ce82018-10-16 23:35:28 +09001736 char sbuf[NI_MAXSERV];
Bernie Innocenti55864192018-08-30 04:05:20 +09001737 snprintf(sbuf, sizeof(sbuf), "%u", NAMESERVER_PORT);
Bernie Innocenti45238a12018-12-04 14:57:48 +09001738 for (int i = 0; i < numservers; i++) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001739 // The addrinfo structures allocated here are freed in free_nameservers_locked().
Bernie Innocentic165ce82018-10-16 23:35:28 +09001740 const addrinfo hints = {
1741 .ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM, .ai_flags = AI_NUMERICHOST};
1742 int rt = getaddrinfo_numeric(servers[i], sbuf, hints, &nsaddrinfo[i]);
Bernie Innocenti55864192018-08-30 04:05:20 +09001743 if (rt != 0) {
Bernie Innocenti45238a12018-12-04 14:57:48 +09001744 for (int j = 0; j < i; j++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001745 freeaddrinfo(nsaddrinfo[j]);
Bernie Innocenti55864192018-08-30 04:05:20 +09001746 }
Bernie Innocentic165ce82018-10-16 23:35:28 +09001747 VLOG << __func__ << ": getaddrinfo_numeric(" << servers[i]
1748 << ") = " << gai_strerror(rt);
Bernie Innocenti55864192018-08-30 04:05:20 +09001749 return EINVAL;
1750 }
1751 }
1752
Ken Chen2a429352018-12-22 21:46:55 +08001753 std::lock_guard guard(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001754 // creates the cache if not created
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001755 get_res_cache_for_net_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001756
ckenb1a69a42018-12-01 17:45:18 +09001757 resolv_cache_info* cache_info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001758
1759 if (cache_info != NULL) {
1760 uint8_t old_max_samples = cache_info->params.max_samples;
1761 if (params != NULL) {
1762 cache_info->params = *params;
1763 } else {
Bernie Innocenti1fbca5c2018-10-01 20:46:20 +09001764 resolv_set_default_params(&cache_info->params);
Bernie Innocenti55864192018-08-30 04:05:20 +09001765 }
1766
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001767 if (!resolv_is_nameservers_equal_locked(cache_info, servers, numservers)) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001768 // free current before adding new
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001769 free_nameservers_locked(cache_info);
Bernie Innocenti45238a12018-12-04 14:57:48 +09001770 for (int i = 0; i < numservers; i++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001771 cache_info->nsaddrinfo[i] = nsaddrinfo[i];
1772 cache_info->nameservers[i] = strdup(servers[i]);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001773 VLOG << __func__ << ": netid = " << netid << ", addr = " << servers[i];
Bernie Innocenti55864192018-08-30 04:05:20 +09001774 }
1775 cache_info->nscount = numservers;
1776
1777 // Clear the NS statistics because the mapping to nameservers might have changed.
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001778 res_cache_clear_stats_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001779
1780 // increment the revision id to ensure that sample state is not written back if the
1781 // servers change; in theory it would suffice to do so only if the servers or
1782 // max_samples actually change, in practice the overhead of checking is higher than the
1783 // cost, and overflows are unlikely
1784 ++cache_info->revision_id;
Ken Chen26f01e42018-11-02 13:18:40 +08001785 } else {
1786 if (cache_info->params.max_samples != old_max_samples) {
1787 // If the maximum number of samples changes, the overhead of keeping the most recent
1788 // samples around is not considered worth the effort, so they are cleared instead.
1789 // All other parameters do not affect shared state: Changing these parameters does
1790 // not invalidate the samples, as they only affect aggregation and the conditions
1791 // under which servers are considered usable.
1792 res_cache_clear_stats_locked(cache_info);
1793 ++cache_info->revision_id;
1794 }
Bernie Innocenti45238a12018-12-04 14:57:48 +09001795 for (int j = 0; j < numservers; j++) {
Ken Chen26f01e42018-11-02 13:18:40 +08001796 freeaddrinfo(nsaddrinfo[j]);
1797 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001798 }
1799
1800 // Always update the search paths, since determining whether they actually changed is
1801 // complex due to the zero-padding, and probably not worth the effort. Cache-flushing
1802 // however is not // necessary, since the stored cache entries do contain the domain, not
1803 // just the host name.
1804 // code moved from res_init.c, load_domain_search_list
1805 strlcpy(cache_info->defdname, domains, sizeof(cache_info->defdname));
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001806 if ((cp = strchr(cache_info->defdname, '\n')) != NULL) *cp = '\0';
Bernie Innocenti55864192018-08-30 04:05:20 +09001807
1808 cp = cache_info->defdname;
1809 offset = cache_info->dnsrch_offset;
1810 while (offset < cache_info->dnsrch_offset + MAXDNSRCH) {
1811 while (*cp == ' ' || *cp == '\t') /* skip leading white space */
1812 cp++;
1813 if (*cp == '\0') /* stop if nothing more to do */
1814 break;
1815 *offset++ = cp - cache_info->defdname; /* record this search domain */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001816 while (*cp) { /* zero-terminate it */
1817 if (*cp == ' ' || *cp == '\t') {
Bernie Innocenti55864192018-08-30 04:05:20 +09001818 *cp++ = '\0';
1819 break;
1820 }
1821 cp++;
1822 }
1823 }
1824 *offset = -1; /* cache_info->dnsrch_offset has MAXDNSRCH+1 items */
1825 }
1826
Bernie Innocenti55864192018-08-30 04:05:20 +09001827 return 0;
1828}
1829
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001830static int resolv_is_nameservers_equal_locked(resolv_cache_info* cache_info, const char** servers,
1831 int numservers) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001832 if (cache_info->nscount != numservers) {
1833 return 0;
1834 }
1835
1836 // Compare each name server against current name servers.
1837 // TODO: this is incorrect if the list of current or previous nameservers
1838 // contains duplicates. This does not really matter because the framework
1839 // filters out duplicates, but we should probably fix it. It's also
1840 // insensitive to the order of the nameservers; we should probably fix that
1841 // too.
1842 for (int i = 0; i < numservers; i++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001843 for (int j = 0;; j++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001844 if (j >= numservers) {
1845 return 0;
1846 }
1847 if (strcmp(cache_info->nameservers[i], servers[j]) == 0) {
1848 break;
1849 }
1850 }
1851 }
1852
1853 return 1;
1854}
1855
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001856static void free_nameservers_locked(resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001857 int i;
1858 for (i = 0; i < cache_info->nscount; i++) {
1859 free(cache_info->nameservers[i]);
1860 cache_info->nameservers[i] = NULL;
1861 if (cache_info->nsaddrinfo[i] != NULL) {
1862 freeaddrinfo(cache_info->nsaddrinfo[i]);
1863 cache_info->nsaddrinfo[i] = NULL;
1864 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001865 cache_info->nsstats[i].sample_count = cache_info->nsstats[i].sample_next = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +09001866 }
1867 cache_info->nscount = 0;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001868 res_cache_clear_stats_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001869 ++cache_info->revision_id;
1870}
1871
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001872void _resolv_populate_res_for_net(res_state statp) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001873 if (statp == NULL) {
1874 return;
1875 }
1876
Ken Chen2a429352018-12-22 21:46:55 +08001877 std::lock_guard guard(cache_mutex);
ckenb1a69a42018-12-01 17:45:18 +09001878 resolv_cache_info* info = find_cache_info_locked(statp->netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001879 if (info != NULL) {
1880 int nserv;
1881 struct addrinfo* ai;
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001882 VLOG << __func__ << ": " << statp->netid;
Bernie Innocenti55864192018-08-30 04:05:20 +09001883 for (nserv = 0; nserv < MAXNS; nserv++) {
1884 ai = info->nsaddrinfo[nserv];
1885 if (ai == NULL) {
1886 break;
1887 }
1888
1889 if ((size_t) ai->ai_addrlen <= sizeof(statp->_u._ext.ext->nsaddrs[0])) {
1890 if (statp->_u._ext.ext != NULL) {
1891 memcpy(&statp->_u._ext.ext->nsaddrs[nserv], ai->ai_addr, ai->ai_addrlen);
1892 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
1893 } else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001894 if ((size_t) ai->ai_addrlen <= sizeof(statp->nsaddr_list[0])) {
1895 memcpy(&statp->nsaddr_list[nserv], ai->ai_addr, ai->ai_addrlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001896 } else {
1897 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
1898 }
1899 }
1900 } else {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001901 VLOG << __func__ << ": found too long addrlen";
Bernie Innocenti55864192018-08-30 04:05:20 +09001902 }
1903 }
1904 statp->nscount = nserv;
1905 // now do search domains. Note that we cache the offsets as this code runs alot
1906 // but the setting/offset-computer only runs when set/changed
1907 // WARNING: Don't use str*cpy() here, this string contains zeroes.
1908 memcpy(statp->defdname, info->defdname, sizeof(statp->defdname));
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001909 char** pp = statp->dnsrch;
1910 int* p = info->dnsrch_offset;
Bernie Innocenti55864192018-08-30 04:05:20 +09001911 while (pp < statp->dnsrch + MAXDNSRCH && *p != -1) {
1912 *pp++ = &statp->defdname[0] + *p++;
1913 }
1914 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001915}
1916
1917/* Resolver reachability statistics. */
1918
Bernie Innocenti189eb502018-10-01 23:10:18 +09001919static void _res_cache_add_stats_sample_locked(res_stats* stats, const res_sample* sample,
1920 int max_samples) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001921 // Note: This function expects max_samples > 0, otherwise a (harmless) modification of the
1922 // allocated but supposedly unused memory for samples[0] will happen
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001923 VLOG << __func__ << ": adding sample to stats, next = " << stats->sample_next
1924 << ", count = " << stats->sample_count;
Bernie Innocenti55864192018-08-30 04:05:20 +09001925 stats->samples[stats->sample_next] = *sample;
1926 if (stats->sample_count < max_samples) {
1927 ++stats->sample_count;
1928 }
1929 if (++stats->sample_next >= max_samples) {
1930 stats->sample_next = 0;
1931 }
1932}
1933
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001934static void res_cache_clear_stats_locked(resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001935 if (cache_info) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001936 for (int i = 0; i < MAXNS; ++i) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001937 cache_info->nsstats->sample_count = cache_info->nsstats->sample_next = 0;
1938 }
1939 }
1940}
1941
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001942int android_net_res_stats_get_info_for_net(unsigned netid, int* nscount,
1943 struct sockaddr_storage servers[MAXNS], int* dcount,
1944 char domains[MAXDNSRCH][MAXDNSRCHPATH],
Bernie Innocenti34de3ba2019-02-19 18:08:36 +09001945 res_params* params, struct res_stats stats[MAXNS],
Ken Chen2a429352018-12-22 21:46:55 +08001946 int* wait_for_pending_req_timeout_count) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001947 int revision_id = -1;
Ken Chen2a429352018-12-22 21:46:55 +08001948 std::lock_guard guard(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001949
ckenb1a69a42018-12-01 17:45:18 +09001950 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001951 if (info) {
1952 if (info->nscount > MAXNS) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001953 VLOG << __func__ << ": nscount " << info->nscount << " > MAXNS " << MAXNS;
Bernie Innocenti55864192018-08-30 04:05:20 +09001954 errno = EFAULT;
1955 return -1;
1956 }
1957 int i;
1958 for (i = 0; i < info->nscount; i++) {
1959 // Verify that the following assumptions are held, failure indicates corruption:
1960 // - getaddrinfo() may never return a sockaddr > sockaddr_storage
1961 // - all addresses are valid
1962 // - there is only one address per addrinfo thanks to numeric resolution
1963 int addrlen = info->nsaddrinfo[i]->ai_addrlen;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001964 if (addrlen < (int) sizeof(struct sockaddr) || addrlen > (int) sizeof(servers[0])) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001965 VLOG << __func__ << ": nsaddrinfo[" << i << "].ai_addrlen == " << addrlen;
Bernie Innocenti55864192018-08-30 04:05:20 +09001966 errno = EMSGSIZE;
1967 return -1;
1968 }
1969 if (info->nsaddrinfo[i]->ai_addr == NULL) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001970 VLOG << __func__ << ": nsaddrinfo[" << i << "].ai_addr == NULL";
Bernie Innocenti55864192018-08-30 04:05:20 +09001971 errno = ENOENT;
1972 return -1;
1973 }
1974 if (info->nsaddrinfo[i]->ai_next != NULL) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001975 VLOG << __func__ << ": nsaddrinfo[" << i << "].ai_next != NULL";
Bernie Innocenti55864192018-08-30 04:05:20 +09001976 errno = ENOTUNIQ;
1977 return -1;
1978 }
1979 }
1980 *nscount = info->nscount;
1981 for (i = 0; i < info->nscount; i++) {
1982 memcpy(&servers[i], info->nsaddrinfo[i]->ai_addr, info->nsaddrinfo[i]->ai_addrlen);
1983 stats[i] = info->nsstats[i];
1984 }
1985 for (i = 0; i < MAXDNSRCH; i++) {
1986 const char* cur_domain = info->defdname + info->dnsrch_offset[i];
1987 // dnsrch_offset[i] can either be -1 or point to an empty string to indicate the end
1988 // of the search offsets. Checking for < 0 is not strictly necessary, but safer.
1989 // TODO: Pass in a search domain array instead of a string to
Bernie Innocenti189eb502018-10-01 23:10:18 +09001990 // resolv_set_nameservers_for_net() and make this double check unnecessary.
Bernie Innocenti55864192018-08-30 04:05:20 +09001991 if (info->dnsrch_offset[i] < 0 ||
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001992 ((size_t) info->dnsrch_offset[i]) >= sizeof(info->defdname) || !cur_domain[0]) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001993 break;
1994 }
1995 strlcpy(domains[i], cur_domain, MAXDNSRCHPATH);
1996 }
1997 *dcount = i;
1998 *params = info->params;
1999 revision_id = info->revision_id;
Ken Chen2a429352018-12-22 21:46:55 +08002000 *wait_for_pending_req_timeout_count = info->wait_for_pending_req_timeout_count;
Bernie Innocenti55864192018-08-30 04:05:20 +09002001 }
2002
Bernie Innocenti55864192018-08-30 04:05:20 +09002003 return revision_id;
2004}
2005
Bernie Innocenti34de3ba2019-02-19 18:08:36 +09002006int resolv_cache_get_resolver_stats(unsigned netid, res_params* params, res_stats stats[MAXNS]) {
Ken Chen2a429352018-12-22 21:46:55 +08002007 std::lock_guard guard(cache_mutex);
ckenb1a69a42018-12-01 17:45:18 +09002008 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09002009 if (info) {
2010 memcpy(stats, info->nsstats, sizeof(info->nsstats));
2011 *params = info->params;
Ken Chen2a429352018-12-22 21:46:55 +08002012 return info->revision_id;
Bernie Innocenti55864192018-08-30 04:05:20 +09002013 }
2014
Ken Chen2a429352018-12-22 21:46:55 +08002015 return -1;
Bernie Innocenti55864192018-08-30 04:05:20 +09002016}
2017
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002018void _resolv_cache_add_resolver_stats_sample(unsigned netid, int revision_id, int ns,
Bernie Innocenti189eb502018-10-01 23:10:18 +09002019 const res_sample* sample, int max_samples) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002020 if (max_samples <= 0) return;
2021
Ken Chen2a429352018-12-22 21:46:55 +08002022 std::lock_guard guard(cache_mutex);
ckenb1a69a42018-12-01 17:45:18 +09002023 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09002024
2025 if (info && info->revision_id == revision_id) {
2026 _res_cache_add_stats_sample_locked(&info->nsstats[ns], sample, max_samples);
2027 }
Bernie Innocenti55864192018-08-30 04:05:20 +09002028}