blob: a38fc4cc899d78d3d287c6d74ce432a7e1782032 [file] [log] [blame]
Bernie Innocenti55864192018-08-30 04:05:20 +09001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090029#define LOG_TAG "res_cache"
30
Bernie Innocenti34de3ba2019-02-19 18:08:36 +090031#include "resolv_cache.h"
32
Bernie Innocenti55864192018-08-30 04:05:20 +090033#include <resolv.h>
34#include <stdarg.h>
35#include <stdio.h>
36#include <stdlib.h>
37#include <string.h>
38#include <time.h>
Ken Chen2a429352018-12-22 21:46:55 +080039#include <mutex>
Bernie Innocenti55864192018-08-30 04:05:20 +090040
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090041#include <arpa/inet.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090042#include <arpa/nameser.h>
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090043#include <errno.h>
44#include <linux/if.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090045#include <net/if.h>
46#include <netdb.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090047
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090048#include <android-base/logging.h>
Ken Chen2a429352018-12-22 21:46:55 +080049#include <android-base/thread_annotations.h>
Bernie Innocenti34de3ba2019-02-19 18:08:36 +090050#include <android/multinetwork.h> // ResNsendFlags
Bernie Innocentif89b3512018-08-30 07:34:37 +090051
Bernie Innocenti189eb502018-10-01 23:10:18 +090052#include "res_state_ext.h"
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090053#include "resolv_private.h"
Bernie Innocenti55864192018-08-30 04:05:20 +090054
Bernie Innocentid017e972019-03-03 19:39:53 +090055// NOTE: verbose logging MUST NOT be left enabled in production binaries.
56// It floods logs at high rate, and can leak privacy-sensitive information.
57constexpr bool kDumpData = false;
58
Bernie Innocenti55864192018-08-30 04:05:20 +090059/* This code implements a small and *simple* DNS resolver cache.
60 *
61 * It is only used to cache DNS answers for a time defined by the smallest TTL
62 * among the answer records in order to reduce DNS traffic. It is not supposed
63 * to be a full DNS cache, since we plan to implement that in the future in a
64 * dedicated process running on the system.
65 *
66 * Note that its design is kept simple very intentionally, i.e.:
67 *
68 * - it takes raw DNS query packet data as input, and returns raw DNS
69 * answer packet data as output
70 *
71 * (this means that two similar queries that encode the DNS name
72 * differently will be treated distinctly).
73 *
74 * the smallest TTL value among the answer records are used as the time
75 * to keep an answer in the cache.
76 *
77 * this is bad, but we absolutely want to avoid parsing the answer packets
78 * (and should be solved by the later full DNS cache process).
79 *
80 * - the implementation is just a (query-data) => (answer-data) hash table
81 * with a trivial least-recently-used expiration policy.
82 *
83 * Doing this keeps the code simple and avoids to deal with a lot of things
84 * that a full DNS cache is expected to do.
85 *
86 * The API is also very simple:
87 *
88 * - the client calls _resolv_cache_get() to obtain a handle to the cache.
89 * this will initialize the cache on first usage. the result can be NULL
90 * if the cache is disabled.
91 *
92 * - the client calls _resolv_cache_lookup() before performing a query
93 *
94 * if the function returns RESOLV_CACHE_FOUND, a copy of the answer data
95 * has been copied into the client-provided answer buffer.
96 *
97 * if the function returns RESOLV_CACHE_NOTFOUND, the client should perform
98 * a request normally, *then* call _resolv_cache_add() to add the received
99 * answer to the cache.
100 *
101 * if the function returns RESOLV_CACHE_UNSUPPORTED, the client should
102 * perform a request normally, and *not* call _resolv_cache_add()
103 *
104 * note that RESOLV_CACHE_UNSUPPORTED is also returned if the answer buffer
105 * is too short to accomodate the cached result.
106 */
107
108/* default number of entries kept in the cache. This value has been
109 * determined by browsing through various sites and counting the number
110 * of corresponding requests. Keep in mind that our framework is currently
111 * performing two requests per name lookup (one for IPv4, the other for IPv6)
112 *
113 * www.google.com 4
114 * www.ysearch.com 6
115 * www.amazon.com 8
116 * www.nytimes.com 22
117 * www.espn.com 28
118 * www.msn.com 28
119 * www.lemonde.fr 35
120 *
121 * (determined in 2009-2-17 from Paris, France, results may vary depending
122 * on location)
123 *
124 * most high-level websites use lots of media/ad servers with different names
125 * but these are generally reused when browsing through the site.
126 *
127 * As such, a value of 64 should be relatively comfortable at the moment.
128 *
129 * ******************************************
130 * * NOTE - this has changed.
131 * * 1) we've added IPv6 support so each dns query results in 2 responses
132 * * 2) we've made this a system-wide cache, so the cost is less (it's not
133 * * duplicated in each process) and the need is greater (more processes
134 * * making different requests).
135 * * Upping by 2x for IPv6
136 * * Upping by another 5x for the centralized nature
137 * *****************************************
138 */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900139#define CONFIG_MAX_ENTRIES (64 * 2 * 5)
Bernie Innocenti55864192018-08-30 04:05:20 +0900140
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900141/** BOUNDED BUFFER FORMATTING **/
Bernie Innocenti55864192018-08-30 04:05:20 +0900142
143/* technical note:
144 *
145 * the following debugging routines are used to append data to a bounded
146 * buffer they take two parameters that are:
147 *
148 * - p : a pointer to the current cursor position in the buffer
149 * this value is initially set to the buffer's address.
150 *
151 * - end : the address of the buffer's limit, i.e. of the first byte
152 * after the buffer. this address should never be touched.
153 *
154 * IMPORTANT: it is assumed that end > buffer_address, i.e.
155 * that the buffer is at least one byte.
156 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900157 * the bprint_x() functions return the new value of 'p' after the data
Bernie Innocenti55864192018-08-30 04:05:20 +0900158 * has been appended, and also ensure the following:
159 *
160 * - the returned value will never be strictly greater than 'end'
161 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900162 * - a return value equal to 'end' means that truncation occurred
Bernie Innocenti55864192018-08-30 04:05:20 +0900163 * (in which case, end[-1] will be set to 0)
164 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900165 * - after returning from a bprint_x() function, the content of the buffer
Bernie Innocenti55864192018-08-30 04:05:20 +0900166 * is always 0-terminated, even in the event of truncation.
167 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900168 * these conventions allow you to call bprint_x() functions multiple times and
Bernie Innocenti55864192018-08-30 04:05:20 +0900169 * only check for truncation at the end of the sequence, as in:
170 *
171 * char buff[1000], *p = buff, *end = p + sizeof(buff);
172 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900173 * p = bprint_c(p, end, '"');
174 * p = bprint_s(p, end, my_string);
175 * p = bprint_c(p, end, '"');
Bernie Innocenti55864192018-08-30 04:05:20 +0900176 *
177 * if (p >= end) {
178 * // buffer was too small
179 * }
180 *
181 * printf( "%s", buff );
182 */
183
Bernie Innocenti34de3ba2019-02-19 18:08:36 +0900184/* Defaults used for initializing res_params */
Bernie Innocenti1fbca5c2018-10-01 20:46:20 +0900185
186// If successes * 100 / total_samples is less than this value, the server is considered failing
187#define SUCCESS_THRESHOLD 75
188// Sample validity in seconds. Set to -1 to disable skipping failing servers.
189#define NSSAMPLE_VALIDITY 1800
190
Bernie Innocenti55864192018-08-30 04:05:20 +0900191/* add a char to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900192static char* bprint_c(char* p, char* end, int c) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900193 if (p < end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900194 if (p + 1 == end)
Bernie Innocenti55864192018-08-30 04:05:20 +0900195 *p++ = 0;
196 else {
197 *p++ = (char) c;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900198 *p = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900199 }
200 }
201 return p;
202}
203
204/* add a sequence of bytes to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900205static char* bprint_b(char* p, char* end, const char* buf, int len) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900206 int avail = end - p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900207
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900208 if (avail <= 0 || len <= 0) return p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900209
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900210 if (avail > len) avail = len;
Bernie Innocenti55864192018-08-30 04:05:20 +0900211
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900212 memcpy(p, buf, avail);
Bernie Innocenti55864192018-08-30 04:05:20 +0900213 p += avail;
214
215 if (p < end)
216 p[0] = 0;
217 else
218 end[-1] = 0;
219
220 return p;
221}
222
223/* add a string to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900224static char* bprint_s(char* p, char* end, const char* str) {
225 return bprint_b(p, end, str, strlen(str));
Bernie Innocenti55864192018-08-30 04:05:20 +0900226}
227
228/* add a formatted string to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900229static char* bprint(char* p, char* end, const char* format, ...) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900230 int avail, n;
231 va_list args;
Bernie Innocenti55864192018-08-30 04:05:20 +0900232
233 avail = end - p;
234
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900235 if (avail <= 0) return p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900236
237 va_start(args, format);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900238 n = vsnprintf(p, avail, format, args);
Bernie Innocenti55864192018-08-30 04:05:20 +0900239 va_end(args);
240
241 /* certain C libraries return -1 in case of truncation */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900242 if (n < 0 || n > avail) n = avail;
Bernie Innocenti55864192018-08-30 04:05:20 +0900243
244 p += n;
245 /* certain C libraries do not zero-terminate in case of truncation */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900246 if (p == end) p[-1] = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900247
248 return p;
249}
250
251/* add a hex value to a bounded buffer, up to 8 digits */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900252static char* bprint_hex(char* p, char* end, unsigned value, int numDigits) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900253 char text[sizeof(unsigned) * 2];
254 int nn = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900255
256 while (numDigits-- > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900257 text[nn++] = "0123456789abcdef"[(value >> (numDigits * 4)) & 15];
Bernie Innocenti55864192018-08-30 04:05:20 +0900258 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900259 return bprint_b(p, end, text, nn);
Bernie Innocenti55864192018-08-30 04:05:20 +0900260}
261
262/* add the hexadecimal dump of some memory area to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900263static char* bprint_hexdump(char* p, char* end, const uint8_t* data, int datalen) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900264 int lineSize = 16;
Bernie Innocenti55864192018-08-30 04:05:20 +0900265
266 while (datalen > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900267 int avail = datalen;
268 int nn;
Bernie Innocenti55864192018-08-30 04:05:20 +0900269
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900270 if (avail > lineSize) avail = lineSize;
Bernie Innocenti55864192018-08-30 04:05:20 +0900271
272 for (nn = 0; nn < avail; nn++) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900273 if (nn > 0) p = bprint_c(p, end, ' ');
274 p = bprint_hex(p, end, data[nn], 2);
Bernie Innocenti55864192018-08-30 04:05:20 +0900275 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900276 for (; nn < lineSize; nn++) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900277 p = bprint_s(p, end, " ");
Bernie Innocenti55864192018-08-30 04:05:20 +0900278 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900279 p = bprint_s(p, end, " ");
Bernie Innocenti55864192018-08-30 04:05:20 +0900280
281 for (nn = 0; nn < avail; nn++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900282 int c = data[nn];
Bernie Innocenti55864192018-08-30 04:05:20 +0900283
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900284 if (c < 32 || c > 127) c = '.';
Bernie Innocenti55864192018-08-30 04:05:20 +0900285
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900286 p = bprint_c(p, end, c);
Bernie Innocenti55864192018-08-30 04:05:20 +0900287 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900288 p = bprint_c(p, end, '\n');
Bernie Innocenti55864192018-08-30 04:05:20 +0900289
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900290 data += avail;
Bernie Innocenti55864192018-08-30 04:05:20 +0900291 datalen -= avail;
292 }
293 return p;
294}
295
296/* dump the content of a query of packet to the log */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900297static void dump_bytes(const uint8_t* base, int len) {
298 if (!kDumpData) return;
Bernie Innocenti55864192018-08-30 04:05:20 +0900299
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900300 char buff[1024];
301 char *p = buff, *end = p + sizeof(buff);
302
303 p = bprint_hexdump(p, end, base, len);
chenbruce16adee42019-02-20 19:45:50 +0800304 LOG(INFO) << buff;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900305}
Bernie Innocenti55864192018-08-30 04:05:20 +0900306
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900307static time_t _time_now(void) {
308 struct timeval tv;
Bernie Innocenti55864192018-08-30 04:05:20 +0900309
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900310 gettimeofday(&tv, NULL);
Bernie Innocenti55864192018-08-30 04:05:20 +0900311 return tv.tv_sec;
312}
313
314/* reminder: the general format of a DNS packet is the following:
315 *
316 * HEADER (12 bytes)
317 * QUESTION (variable)
318 * ANSWER (variable)
319 * AUTHORITY (variable)
320 * ADDITIONNAL (variable)
321 *
322 * the HEADER is made of:
323 *
324 * ID : 16 : 16-bit unique query identification field
325 *
326 * QR : 1 : set to 0 for queries, and 1 for responses
327 * Opcode : 4 : set to 0 for queries
328 * AA : 1 : set to 0 for queries
329 * TC : 1 : truncation flag, will be set to 0 in queries
330 * RD : 1 : recursion desired
331 *
332 * RA : 1 : recursion available (0 in queries)
333 * Z : 3 : three reserved zero bits
334 * RCODE : 4 : response code (always 0=NOERROR in queries)
335 *
336 * QDCount: 16 : question count
337 * ANCount: 16 : Answer count (0 in queries)
338 * NSCount: 16: Authority Record count (0 in queries)
339 * ARCount: 16: Additionnal Record count (0 in queries)
340 *
341 * the QUESTION is made of QDCount Question Record (QRs)
342 * the ANSWER is made of ANCount RRs
343 * the AUTHORITY is made of NSCount RRs
344 * the ADDITIONNAL is made of ARCount RRs
345 *
346 * Each Question Record (QR) is made of:
347 *
348 * QNAME : variable : Query DNS NAME
349 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
350 * CLASS : 16 : class of query (IN=1)
351 *
352 * Each Resource Record (RR) is made of:
353 *
354 * NAME : variable : DNS NAME
355 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
356 * CLASS : 16 : class of query (IN=1)
357 * TTL : 32 : seconds to cache this RR (0=none)
358 * RDLENGTH: 16 : size of RDDATA in bytes
359 * RDDATA : variable : RR data (depends on TYPE)
360 *
361 * Each QNAME contains a domain name encoded as a sequence of 'labels'
362 * terminated by a zero. Each label has the following format:
363 *
364 * LEN : 8 : lenght of label (MUST be < 64)
365 * NAME : 8*LEN : label length (must exclude dots)
366 *
367 * A value of 0 in the encoding is interpreted as the 'root' domain and
368 * terminates the encoding. So 'www.android.com' will be encoded as:
369 *
370 * <3>www<7>android<3>com<0>
371 *
372 * Where <n> represents the byte with value 'n'
373 *
374 * Each NAME reflects the QNAME of the question, but has a slightly more
375 * complex encoding in order to provide message compression. This is achieved
376 * by using a 2-byte pointer, with format:
377 *
378 * TYPE : 2 : 0b11 to indicate a pointer, 0b01 and 0b10 are reserved
379 * OFFSET : 14 : offset to another part of the DNS packet
380 *
381 * The offset is relative to the start of the DNS packet and must point
382 * A pointer terminates the encoding.
383 *
384 * The NAME can be encoded in one of the following formats:
385 *
386 * - a sequence of simple labels terminated by 0 (like QNAMEs)
387 * - a single pointer
388 * - a sequence of simple labels terminated by a pointer
389 *
390 * A pointer shall always point to either a pointer of a sequence of
391 * labels (which can themselves be terminated by either a 0 or a pointer)
392 *
393 * The expanded length of a given domain name should not exceed 255 bytes.
394 *
395 * NOTE: we don't parse the answer packets, so don't need to deal with NAME
396 * records, only QNAMEs.
397 */
398
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900399#define DNS_HEADER_SIZE 12
Bernie Innocenti55864192018-08-30 04:05:20 +0900400
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900401#define DNS_TYPE_A "\00\01" /* big-endian decimal 1 */
402#define DNS_TYPE_PTR "\00\014" /* big-endian decimal 12 */
403#define DNS_TYPE_MX "\00\017" /* big-endian decimal 15 */
404#define DNS_TYPE_AAAA "\00\034" /* big-endian decimal 28 */
405#define DNS_TYPE_ALL "\00\0377" /* big-endian decimal 255 */
Bernie Innocenti55864192018-08-30 04:05:20 +0900406
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900407#define DNS_CLASS_IN "\00\01" /* big-endian decimal 1 */
Bernie Innocenti55864192018-08-30 04:05:20 +0900408
409typedef struct {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900410 const uint8_t* base;
411 const uint8_t* end;
412 const uint8_t* cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900413} DnsPacket;
414
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900415static void _dnsPacket_init(DnsPacket* packet, const uint8_t* buff, int bufflen) {
416 packet->base = buff;
417 packet->end = buff + bufflen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900418 packet->cursor = buff;
419}
420
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900421static void _dnsPacket_rewind(DnsPacket* packet) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900422 packet->cursor = packet->base;
423}
424
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900425static void _dnsPacket_skip(DnsPacket* packet, int count) {
426 const uint8_t* p = packet->cursor + count;
Bernie Innocenti55864192018-08-30 04:05:20 +0900427
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900428 if (p > packet->end) p = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900429
430 packet->cursor = p;
431}
432
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900433static int _dnsPacket_readInt16(DnsPacket* packet) {
434 const uint8_t* p = packet->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900435
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900436 if (p + 2 > packet->end) return -1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900437
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900438 packet->cursor = p + 2;
439 return (p[0] << 8) | p[1];
Bernie Innocenti55864192018-08-30 04:05:20 +0900440}
441
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900442/** QUERY CHECKING **/
Bernie Innocenti55864192018-08-30 04:05:20 +0900443
444/* check bytes in a dns packet. returns 1 on success, 0 on failure.
445 * the cursor is only advanced in the case of success
446 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900447static int _dnsPacket_checkBytes(DnsPacket* packet, int numBytes, const void* bytes) {
448 const uint8_t* p = packet->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900449
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900450 if (p + numBytes > packet->end) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900451
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900452 if (memcmp(p, bytes, numBytes) != 0) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900453
454 packet->cursor = p + numBytes;
455 return 1;
456}
457
458/* parse and skip a given QNAME stored in a query packet,
459 * from the current cursor position. returns 1 on success,
460 * or 0 for malformed data.
461 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900462static int _dnsPacket_checkQName(DnsPacket* packet) {
463 const uint8_t* p = packet->cursor;
464 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900465
466 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900467 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900468
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900469 if (p >= end) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900470
471 c = *p++;
472
473 if (c == 0) {
474 packet->cursor = p;
475 return 1;
476 }
477
478 /* we don't expect label compression in QNAMEs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900479 if (c >= 64) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900480
481 p += c;
482 /* we rely on the bound check at the start
483 * of the loop here */
484 }
485 /* malformed data */
chenbruce16adee42019-02-20 19:45:50 +0800486 LOG(INFO) << "malformed QNAME";
Bernie Innocenti55864192018-08-30 04:05:20 +0900487 return 0;
488}
489
490/* parse and skip a given QR stored in a packet.
491 * returns 1 on success, and 0 on failure
492 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900493static int _dnsPacket_checkQR(DnsPacket* packet) {
494 if (!_dnsPacket_checkQName(packet)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900495
496 /* TYPE must be one of the things we support */
497 if (!_dnsPacket_checkBytes(packet, 2, DNS_TYPE_A) &&
498 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_PTR) &&
499 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_MX) &&
500 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_AAAA) &&
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900501 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_ALL)) {
chenbruce16adee42019-02-20 19:45:50 +0800502 LOG(INFO) << "unsupported TYPE";
Bernie Innocenti55864192018-08-30 04:05:20 +0900503 return 0;
504 }
505 /* CLASS must be IN */
506 if (!_dnsPacket_checkBytes(packet, 2, DNS_CLASS_IN)) {
chenbruce16adee42019-02-20 19:45:50 +0800507 LOG(INFO) << "unsupported CLASS";
Bernie Innocenti55864192018-08-30 04:05:20 +0900508 return 0;
509 }
510
511 return 1;
512}
513
514/* check the header of a DNS Query packet, return 1 if it is one
515 * type of query we can cache, or 0 otherwise
516 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900517static int _dnsPacket_checkQuery(DnsPacket* packet) {
518 const uint8_t* p = packet->base;
519 int qdCount, anCount, dnCount, arCount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900520
521 if (p + DNS_HEADER_SIZE > packet->end) {
chenbruce16adee42019-02-20 19:45:50 +0800522 LOG(INFO) << "query packet too small";
Bernie Innocenti55864192018-08-30 04:05:20 +0900523 return 0;
524 }
525
526 /* QR must be set to 0, opcode must be 0 and AA must be 0 */
527 /* RA, Z, and RCODE must be 0 */
528 if ((p[2] & 0xFC) != 0 || (p[3] & 0xCF) != 0) {
chenbruce16adee42019-02-20 19:45:50 +0800529 LOG(INFO) << "query packet flags unsupported";
Bernie Innocenti55864192018-08-30 04:05:20 +0900530 return 0;
531 }
532
533 /* Note that we ignore the TC, RD, CD, and AD bits here for the
534 * following reasons:
535 *
536 * - there is no point for a query packet sent to a server
537 * to have the TC bit set, but the implementation might
538 * set the bit in the query buffer for its own needs
539 * between a _resolv_cache_lookup and a
540 * _resolv_cache_add. We should not freak out if this
541 * is the case.
542 *
543 * - we consider that the result from a query might depend on
544 * the RD, AD, and CD bits, so these bits
545 * should be used to differentiate cached result.
546 *
547 * this implies that these bits are checked when hashing or
548 * comparing query packets, but not TC
549 */
550
551 /* ANCOUNT, DNCOUNT and ARCOUNT must be 0 */
552 qdCount = (p[4] << 8) | p[5];
553 anCount = (p[6] << 8) | p[7];
554 dnCount = (p[8] << 8) | p[9];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900555 arCount = (p[10] << 8) | p[11];
Bernie Innocenti55864192018-08-30 04:05:20 +0900556
557 if (anCount != 0 || dnCount != 0 || arCount > 1) {
chenbruce16adee42019-02-20 19:45:50 +0800558 LOG(INFO) << "query packet contains non-query records";
Bernie Innocenti55864192018-08-30 04:05:20 +0900559 return 0;
560 }
561
562 if (qdCount == 0) {
chenbruce16adee42019-02-20 19:45:50 +0800563 LOG(INFO) << "query packet doesn't contain query record";
Bernie Innocenti55864192018-08-30 04:05:20 +0900564 return 0;
565 }
566
567 /* Check QDCOUNT QRs */
568 packet->cursor = p + DNS_HEADER_SIZE;
569
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900570 for (; qdCount > 0; qdCount--)
571 if (!_dnsPacket_checkQR(packet)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900572
573 return 1;
574}
575
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900576/** QUERY DEBUGGING **/
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900577static char* dnsPacket_bprintQName(DnsPacket* packet, char* bp, char* bend) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900578 const uint8_t* p = packet->cursor;
579 const uint8_t* end = packet->end;
580 int first = 1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900581
582 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900583 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900584
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900585 if (p >= end) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900586
587 c = *p++;
588
589 if (c == 0) {
590 packet->cursor = p;
591 return bp;
592 }
593
594 /* we don't expect label compression in QNAMEs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900595 if (c >= 64) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900596
597 if (first)
598 first = 0;
599 else
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900600 bp = bprint_c(bp, bend, '.');
Bernie Innocenti55864192018-08-30 04:05:20 +0900601
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900602 bp = bprint_b(bp, bend, (const char*) p, c);
Bernie Innocenti55864192018-08-30 04:05:20 +0900603
604 p += c;
605 /* we rely on the bound check at the start
606 * of the loop here */
607 }
608 /* malformed data */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900609 bp = bprint_s(bp, bend, "<MALFORMED>");
Bernie Innocenti55864192018-08-30 04:05:20 +0900610 return bp;
611}
612
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900613static char* dnsPacket_bprintQR(DnsPacket* packet, char* p, char* end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900614#define QQ(x) \
615 { DNS_TYPE_##x, #x }
Bernie Innocenti55864192018-08-30 04:05:20 +0900616 static const struct {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900617 const char* typeBytes;
618 const char* typeString;
619 } qTypes[] = {QQ(A), QQ(PTR), QQ(MX), QQ(AAAA), QQ(ALL), {NULL, NULL}};
620 int nn;
621 const char* typeString = NULL;
Bernie Innocenti55864192018-08-30 04:05:20 +0900622
623 /* dump QNAME */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900624 p = dnsPacket_bprintQName(packet, p, end);
Bernie Innocenti55864192018-08-30 04:05:20 +0900625
626 /* dump TYPE */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900627 p = bprint_s(p, end, " (");
Bernie Innocenti55864192018-08-30 04:05:20 +0900628
629 for (nn = 0; qTypes[nn].typeBytes != NULL; nn++) {
630 if (_dnsPacket_checkBytes(packet, 2, qTypes[nn].typeBytes)) {
631 typeString = qTypes[nn].typeString;
632 break;
633 }
634 }
635
636 if (typeString != NULL)
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900637 p = bprint_s(p, end, typeString);
Bernie Innocenti55864192018-08-30 04:05:20 +0900638 else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900639 int typeCode = _dnsPacket_readInt16(packet);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900640 p = bprint(p, end, "UNKNOWN-%d", typeCode);
Bernie Innocenti55864192018-08-30 04:05:20 +0900641 }
642
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900643 p = bprint_c(p, end, ')');
Bernie Innocenti55864192018-08-30 04:05:20 +0900644
645 /* skip CLASS */
646 _dnsPacket_skip(packet, 2);
647 return p;
648}
649
650/* this function assumes the packet has already been checked */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900651static char* dnsPacket_bprintQuery(DnsPacket* packet, char* p, char* end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900652 int qdCount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900653
654 if (packet->base[2] & 0x1) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900655 p = bprint_s(p, end, "RECURSIVE ");
Bernie Innocenti55864192018-08-30 04:05:20 +0900656 }
657
658 _dnsPacket_skip(packet, 4);
659 qdCount = _dnsPacket_readInt16(packet);
660 _dnsPacket_skip(packet, 6);
661
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900662 for (; qdCount > 0; qdCount--) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900663 p = dnsPacket_bprintQR(packet, p, end);
Bernie Innocenti55864192018-08-30 04:05:20 +0900664 }
665 return p;
666}
Bernie Innocenti55864192018-08-30 04:05:20 +0900667
Bernie Innocenti55864192018-08-30 04:05:20 +0900668/** QUERY HASHING SUPPORT
669 **
670 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKET HAS ALREADY
671 ** BEEN SUCCESFULLY CHECKED.
672 **/
673
674/* use 32-bit FNV hash function */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900675#define FNV_MULT 16777619U
676#define FNV_BASIS 2166136261U
Bernie Innocenti55864192018-08-30 04:05:20 +0900677
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900678static unsigned _dnsPacket_hashBytes(DnsPacket* packet, int numBytes, unsigned hash) {
679 const uint8_t* p = packet->cursor;
680 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900681
682 while (numBytes > 0 && p < end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900683 hash = hash * FNV_MULT ^ *p++;
Bernie Innocenti55864192018-08-30 04:05:20 +0900684 }
685 packet->cursor = p;
686 return hash;
687}
688
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900689static unsigned _dnsPacket_hashQName(DnsPacket* packet, unsigned hash) {
690 const uint8_t* p = packet->cursor;
691 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900692
693 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900694 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900695
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900696 if (p >= end) { /* should not happen */
chenbruce16adee42019-02-20 19:45:50 +0800697 LOG(INFO) << __func__ << ": INTERNAL_ERROR: read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900698 break;
699 }
700
701 c = *p++;
702
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900703 if (c == 0) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900704
705 if (c >= 64) {
chenbruce16adee42019-02-20 19:45:50 +0800706 LOG(INFO) << __func__ << ": INTERNAL_ERROR: malformed domain";
Bernie Innocenti55864192018-08-30 04:05:20 +0900707 break;
708 }
709 if (p + c >= end) {
chenbruce16adee42019-02-20 19:45:50 +0800710 LOG(INFO) << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900711 break;
712 }
713 while (c > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900714 hash = hash * FNV_MULT ^ *p++;
715 c -= 1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900716 }
717 }
718 packet->cursor = p;
719 return hash;
720}
721
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900722static unsigned _dnsPacket_hashQR(DnsPacket* packet, unsigned hash) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900723 hash = _dnsPacket_hashQName(packet, hash);
724 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TYPE and CLASS */
725 return hash;
726}
727
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900728static unsigned _dnsPacket_hashRR(DnsPacket* packet, unsigned hash) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900729 int rdlength;
730 hash = _dnsPacket_hashQR(packet, hash);
731 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TTL */
732 rdlength = _dnsPacket_readInt16(packet);
733 hash = _dnsPacket_hashBytes(packet, rdlength, hash); /* RDATA */
734 return hash;
735}
736
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900737static unsigned _dnsPacket_hashQuery(DnsPacket* packet) {
738 unsigned hash = FNV_BASIS;
739 int count, arcount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900740 _dnsPacket_rewind(packet);
741
742 /* ignore the ID */
743 _dnsPacket_skip(packet, 2);
744
745 /* we ignore the TC bit for reasons explained in
746 * _dnsPacket_checkQuery().
747 *
748 * however we hash the RD bit to differentiate
749 * between answers for recursive and non-recursive
750 * queries.
751 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900752 hash = hash * FNV_MULT ^ (packet->base[2] & 1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900753
754 /* mark the first header byte as processed */
755 _dnsPacket_skip(packet, 1);
756
757 /* process the second header byte */
758 hash = _dnsPacket_hashBytes(packet, 1, hash);
759
760 /* read QDCOUNT */
761 count = _dnsPacket_readInt16(packet);
762
763 /* assume: ANcount and NScount are 0 */
764 _dnsPacket_skip(packet, 4);
765
766 /* read ARCOUNT */
767 arcount = _dnsPacket_readInt16(packet);
768
769 /* hash QDCOUNT QRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900770 for (; count > 0; count--) hash = _dnsPacket_hashQR(packet, hash);
Bernie Innocenti55864192018-08-30 04:05:20 +0900771
772 /* hash ARCOUNT RRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900773 for (; arcount > 0; arcount--) hash = _dnsPacket_hashRR(packet, hash);
Bernie Innocenti55864192018-08-30 04:05:20 +0900774
775 return hash;
776}
777
Bernie Innocenti55864192018-08-30 04:05:20 +0900778/** QUERY COMPARISON
779 **
780 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKETS HAVE ALREADY
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900781 ** BEEN SUCCESSFULLY CHECKED.
Bernie Innocenti55864192018-08-30 04:05:20 +0900782 **/
783
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900784static int _dnsPacket_isEqualDomainName(DnsPacket* pack1, DnsPacket* pack2) {
785 const uint8_t* p1 = pack1->cursor;
786 const uint8_t* end1 = pack1->end;
787 const uint8_t* p2 = pack2->cursor;
788 const uint8_t* end2 = pack2->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900789
790 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900791 int c1, c2;
Bernie Innocenti55864192018-08-30 04:05:20 +0900792
793 if (p1 >= end1 || p2 >= end2) {
chenbruce16adee42019-02-20 19:45:50 +0800794 LOG(INFO) << __func__ << ": INTERNAL_ERROR: read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900795 break;
796 }
797 c1 = *p1++;
798 c2 = *p2++;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900799 if (c1 != c2) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900800
801 if (c1 == 0) {
802 pack1->cursor = p1;
803 pack2->cursor = p2;
804 return 1;
805 }
806 if (c1 >= 64) {
chenbruce16adee42019-02-20 19:45:50 +0800807 LOG(INFO) << __func__ << ": INTERNAL_ERROR: malformed domain";
Bernie Innocenti55864192018-08-30 04:05:20 +0900808 break;
809 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900810 if ((p1 + c1 > end1) || (p2 + c1 > end2)) {
chenbruce16adee42019-02-20 19:45:50 +0800811 LOG(INFO) << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900812 break;
813 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900814 if (memcmp(p1, p2, c1) != 0) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900815 p1 += c1;
816 p2 += c1;
817 /* we rely on the bound checks at the start of the loop */
818 }
819 /* not the same, or one is malformed */
chenbruce16adee42019-02-20 19:45:50 +0800820 LOG(INFO) << "different DN";
Bernie Innocenti55864192018-08-30 04:05:20 +0900821 return 0;
822}
823
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900824static int _dnsPacket_isEqualBytes(DnsPacket* pack1, DnsPacket* pack2, int numBytes) {
825 const uint8_t* p1 = pack1->cursor;
826 const uint8_t* p2 = pack2->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900827
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900828 if (p1 + numBytes > pack1->end || p2 + numBytes > pack2->end) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900829
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900830 if (memcmp(p1, p2, numBytes) != 0) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900831
832 pack1->cursor += numBytes;
833 pack2->cursor += numBytes;
834 return 1;
835}
836
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900837static int _dnsPacket_isEqualQR(DnsPacket* pack1, DnsPacket* pack2) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900838 /* compare domain name encoding + TYPE + CLASS */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900839 if (!_dnsPacket_isEqualDomainName(pack1, pack2) ||
840 !_dnsPacket_isEqualBytes(pack1, pack2, 2 + 2))
Bernie Innocenti55864192018-08-30 04:05:20 +0900841 return 0;
842
843 return 1;
844}
845
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900846static int _dnsPacket_isEqualRR(DnsPacket* pack1, DnsPacket* pack2) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900847 int rdlength1, rdlength2;
848 /* compare query + TTL */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900849 if (!_dnsPacket_isEqualQR(pack1, pack2) || !_dnsPacket_isEqualBytes(pack1, pack2, 4)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900850
851 /* compare RDATA */
852 rdlength1 = _dnsPacket_readInt16(pack1);
853 rdlength2 = _dnsPacket_readInt16(pack2);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900854 if (rdlength1 != rdlength2 || !_dnsPacket_isEqualBytes(pack1, pack2, rdlength1)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900855
856 return 1;
857}
858
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900859static int _dnsPacket_isEqualQuery(DnsPacket* pack1, DnsPacket* pack2) {
860 int count1, count2, arcount1, arcount2;
Bernie Innocenti55864192018-08-30 04:05:20 +0900861
862 /* compare the headers, ignore most fields */
863 _dnsPacket_rewind(pack1);
864 _dnsPacket_rewind(pack2);
865
866 /* compare RD, ignore TC, see comment in _dnsPacket_checkQuery */
867 if ((pack1->base[2] & 1) != (pack2->base[2] & 1)) {
chenbruce16adee42019-02-20 19:45:50 +0800868 LOG(INFO) << "different RD";
Bernie Innocenti55864192018-08-30 04:05:20 +0900869 return 0;
870 }
871
872 if (pack1->base[3] != pack2->base[3]) {
chenbruce16adee42019-02-20 19:45:50 +0800873 LOG(INFO) << "different CD or AD";
Bernie Innocenti55864192018-08-30 04:05:20 +0900874 return 0;
875 }
876
877 /* mark ID and header bytes as compared */
878 _dnsPacket_skip(pack1, 4);
879 _dnsPacket_skip(pack2, 4);
880
881 /* compare QDCOUNT */
882 count1 = _dnsPacket_readInt16(pack1);
883 count2 = _dnsPacket_readInt16(pack2);
884 if (count1 != count2 || count1 < 0) {
chenbruce16adee42019-02-20 19:45:50 +0800885 LOG(INFO) << "different QDCOUNT";
Bernie Innocenti55864192018-08-30 04:05:20 +0900886 return 0;
887 }
888
889 /* assume: ANcount and NScount are 0 */
890 _dnsPacket_skip(pack1, 4);
891 _dnsPacket_skip(pack2, 4);
892
893 /* compare ARCOUNT */
894 arcount1 = _dnsPacket_readInt16(pack1);
895 arcount2 = _dnsPacket_readInt16(pack2);
896 if (arcount1 != arcount2 || arcount1 < 0) {
chenbruce16adee42019-02-20 19:45:50 +0800897 LOG(INFO) << "different ARCOUNT";
Bernie Innocenti55864192018-08-30 04:05:20 +0900898 return 0;
899 }
900
901 /* compare the QDCOUNT QRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900902 for (; count1 > 0; count1--) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900903 if (!_dnsPacket_isEqualQR(pack1, pack2)) {
chenbruce16adee42019-02-20 19:45:50 +0800904 LOG(INFO) << "different QR";
Bernie Innocenti55864192018-08-30 04:05:20 +0900905 return 0;
906 }
907 }
908
909 /* compare the ARCOUNT RRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900910 for (; arcount1 > 0; arcount1--) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900911 if (!_dnsPacket_isEqualRR(pack1, pack2)) {
chenbruce16adee42019-02-20 19:45:50 +0800912 LOG(INFO) << "different additional RR";
Bernie Innocenti55864192018-08-30 04:05:20 +0900913 return 0;
914 }
915 }
916 return 1;
917}
918
Bernie Innocenti55864192018-08-30 04:05:20 +0900919/* cache entry. for simplicity, 'hash' and 'hlink' are inlined in this
920 * structure though they are conceptually part of the hash table.
921 *
922 * similarly, mru_next and mru_prev are part of the global MRU list
923 */
924typedef struct Entry {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900925 unsigned int hash; /* hash value */
926 struct Entry* hlink; /* next in collision chain */
927 struct Entry* mru_prev;
928 struct Entry* mru_next;
Bernie Innocenti55864192018-08-30 04:05:20 +0900929
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900930 const uint8_t* query;
931 int querylen;
932 const uint8_t* answer;
933 int answerlen;
934 time_t expires; /* time_t when the entry isn't valid any more */
935 int id; /* for debugging purpose */
Bernie Innocenti55864192018-08-30 04:05:20 +0900936} Entry;
937
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900938/*
Bernie Innocenti55864192018-08-30 04:05:20 +0900939 * Find the TTL for a negative DNS result. This is defined as the minimum
940 * of the SOA records TTL and the MINIMUM-TTL field (RFC-2308).
941 *
942 * Return 0 if not found.
943 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900944static u_long answer_getNegativeTTL(ns_msg handle) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900945 int n, nscount;
946 u_long result = 0;
947 ns_rr rr;
948
949 nscount = ns_msg_count(handle, ns_s_ns);
950 for (n = 0; n < nscount; n++) {
951 if ((ns_parserr(&handle, ns_s_ns, n, &rr) == 0) && (ns_rr_type(rr) == ns_t_soa)) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900952 const u_char* rdata = ns_rr_rdata(rr); // find the data
953 const u_char* edata = rdata + ns_rr_rdlen(rr); // add the len to find the end
Bernie Innocenti55864192018-08-30 04:05:20 +0900954 int len;
955 u_long ttl, rec_result = ns_rr_ttl(rr);
956
957 // find the MINIMUM-TTL field from the blob of binary data for this record
958 // skip the server name
959 len = dn_skipname(rdata, edata);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900960 if (len == -1) continue; // error skipping
Bernie Innocenti55864192018-08-30 04:05:20 +0900961 rdata += len;
962
963 // skip the admin name
964 len = dn_skipname(rdata, edata);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900965 if (len == -1) continue; // error skipping
Bernie Innocenti55864192018-08-30 04:05:20 +0900966 rdata += len;
967
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900968 if (edata - rdata != 5 * NS_INT32SZ) continue;
Bernie Innocenti55864192018-08-30 04:05:20 +0900969 // skip: serial number + refresh interval + retry interval + expiry
970 rdata += NS_INT32SZ * 4;
971 // finally read the MINIMUM TTL
972 ttl = ns_get32(rdata);
973 if (ttl < rec_result) {
974 rec_result = ttl;
975 }
976 // Now that the record is read successfully, apply the new min TTL
977 if (n == 0 || rec_result < result) {
978 result = rec_result;
979 }
980 }
981 }
982 return result;
983}
984
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900985/*
Bernie Innocenti55864192018-08-30 04:05:20 +0900986 * Parse the answer records and find the appropriate
987 * smallest TTL among the records. This might be from
988 * the answer records if found or from the SOA record
989 * if it's a negative result.
990 *
991 * The returned TTL is the number of seconds to
992 * keep the answer in the cache.
993 *
994 * In case of parse error zero (0) is returned which
995 * indicates that the answer shall not be cached.
996 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900997static u_long answer_getTTL(const void* answer, int answerlen) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900998 ns_msg handle;
999 int ancount, n;
1000 u_long result, ttl;
1001 ns_rr rr;
1002
1003 result = 0;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001004 if (ns_initparse((const uint8_t*) answer, answerlen, &handle) >= 0) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001005 // get number of answer records
1006 ancount = ns_msg_count(handle, ns_s_an);
1007
1008 if (ancount == 0) {
1009 // a response with no answers? Cache this negative result.
1010 result = answer_getNegativeTTL(handle);
1011 } else {
1012 for (n = 0; n < ancount; n++) {
1013 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
1014 ttl = ns_rr_ttl(rr);
1015 if (n == 0 || ttl < result) {
1016 result = ttl;
1017 }
1018 } else {
chenbruce16adee42019-02-20 19:45:50 +08001019 LOG(INFO) << "ns_parserr failed ancount no = " << n
1020 << ". errno = " << strerror(errno);
Bernie Innocenti55864192018-08-30 04:05:20 +09001021 }
1022 }
1023 }
1024 } else {
chenbruce16adee42019-02-20 19:45:50 +08001025 LOG(INFO) << "ns_initparse failed: " << strerror(errno);
Bernie Innocenti55864192018-08-30 04:05:20 +09001026 }
1027
chenbruce16adee42019-02-20 19:45:50 +08001028 LOG(INFO) << "TTL = " << result;
Bernie Innocenti55864192018-08-30 04:05:20 +09001029 return result;
1030}
1031
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001032static void entry_free(Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001033 /* everything is allocated in a single memory block */
1034 if (e) {
1035 free(e);
1036 }
1037}
1038
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001039static void entry_mru_remove(Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001040 e->mru_prev->mru_next = e->mru_next;
1041 e->mru_next->mru_prev = e->mru_prev;
1042}
1043
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001044static void entry_mru_add(Entry* e, Entry* list) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001045 Entry* first = list->mru_next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001046
1047 e->mru_next = first;
1048 e->mru_prev = list;
1049
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001050 list->mru_next = e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001051 first->mru_prev = e;
1052}
1053
1054/* compute the hash of a given entry, this is a hash of most
1055 * data in the query (key) */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001056static unsigned entry_hash(const Entry* e) {
1057 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001058
1059 _dnsPacket_init(pack, e->query, e->querylen);
1060 return _dnsPacket_hashQuery(pack);
1061}
1062
1063/* initialize an Entry as a search key, this also checks the input query packet
1064 * returns 1 on success, or 0 in case of unsupported/malformed data */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001065static int entry_init_key(Entry* e, const void* query, int querylen) {
1066 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001067
1068 memset(e, 0, sizeof(*e));
1069
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001070 e->query = (const uint8_t*) query;
Bernie Innocenti55864192018-08-30 04:05:20 +09001071 e->querylen = querylen;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001072 e->hash = entry_hash(e);
Bernie Innocenti55864192018-08-30 04:05:20 +09001073
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001074 _dnsPacket_init(pack, e->query, e->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001075
1076 return _dnsPacket_checkQuery(pack);
1077}
1078
1079/* allocate a new entry as a cache node */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001080static Entry* entry_alloc(const Entry* init, const void* answer, int answerlen) {
1081 Entry* e;
1082 int size;
Bernie Innocenti55864192018-08-30 04:05:20 +09001083
1084 size = sizeof(*e) + init->querylen + answerlen;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001085 e = (Entry*) calloc(size, 1);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001086 if (e == NULL) return e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001087
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001088 e->hash = init->hash;
1089 e->query = (const uint8_t*) (e + 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001090 e->querylen = init->querylen;
1091
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001092 memcpy((char*) e->query, init->query, e->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001093
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001094 e->answer = e->query + e->querylen;
Bernie Innocenti55864192018-08-30 04:05:20 +09001095 e->answerlen = answerlen;
1096
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001097 memcpy((char*) e->answer, answer, e->answerlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001098
1099 return e;
1100}
1101
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001102static int entry_equals(const Entry* e1, const Entry* e2) {
1103 DnsPacket pack1[1], pack2[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001104
1105 if (e1->querylen != e2->querylen) {
1106 return 0;
1107 }
1108 _dnsPacket_init(pack1, e1->query, e1->querylen);
1109 _dnsPacket_init(pack2, e2->query, e2->querylen);
1110
1111 return _dnsPacket_isEqualQuery(pack1, pack2);
1112}
1113
Bernie Innocenti55864192018-08-30 04:05:20 +09001114/* We use a simple hash table with external collision lists
1115 * for simplicity, the hash-table fields 'hash' and 'hlink' are
1116 * inlined in the Entry structure.
1117 */
1118
1119/* Maximum time for a thread to wait for an pending request */
Ken Chen2a429352018-12-22 21:46:55 +08001120constexpr int PENDING_REQUEST_TIMEOUT = 20;
Bernie Innocenti55864192018-08-30 04:05:20 +09001121
1122typedef struct resolv_cache {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001123 int max_entries;
1124 int num_entries;
1125 Entry mru_list;
1126 int last_id;
1127 Entry* entries;
Ken Chen2a429352018-12-22 21:46:55 +08001128 struct pending_req_info {
1129 unsigned int hash;
1130 struct pending_req_info* next;
1131 } pending_requests;
Bernie Innocenti55864192018-08-30 04:05:20 +09001132} Cache;
1133
1134struct resolv_cache_info {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001135 unsigned netid;
1136 Cache* cache;
1137 struct resolv_cache_info* next;
1138 int nscount;
1139 char* nameservers[MAXNS];
1140 struct addrinfo* nsaddrinfo[MAXNS];
1141 int revision_id; // # times the nameservers have been replaced
Bernie Innocenti34de3ba2019-02-19 18:08:36 +09001142 res_params params;
Bernie Innocenti189eb502018-10-01 23:10:18 +09001143 struct res_stats nsstats[MAXNS];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001144 char defdname[MAXDNSRCHPATH];
1145 int dnsrch_offset[MAXDNSRCH + 1]; // offsets into defdname
Ken Chen2a429352018-12-22 21:46:55 +08001146 int wait_for_pending_req_timeout_count;
Bernie Innocenti55864192018-08-30 04:05:20 +09001147};
1148
Ken Chen2a429352018-12-22 21:46:55 +08001149// A helper class for the Clang Thread Safety Analysis to deal with
1150// std::unique_lock.
1151class SCOPED_CAPABILITY ScopedAssumeLocked {
1152 public:
1153 ScopedAssumeLocked(std::mutex& mutex) ACQUIRE(mutex) {}
1154 ~ScopedAssumeLocked() RELEASE() {}
1155};
Bernie Innocenti55864192018-08-30 04:05:20 +09001156
Ken Chen2a429352018-12-22 21:46:55 +08001157// lock protecting everything in the resolve_cache_info structs (next ptr, etc)
1158static std::mutex cache_mutex;
1159static std::condition_variable cv;
Bernie Innocenti55864192018-08-30 04:05:20 +09001160
1161/* gets cache associated with a network, or NULL if none exists */
Ken Chen2a429352018-12-22 21:46:55 +08001162static struct resolv_cache* find_named_cache_locked(unsigned netid) REQUIRES(cache_mutex);
1163static resolv_cache* get_res_cache_for_net_locked(unsigned netid) REQUIRES(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001164
Ken Chen2a429352018-12-22 21:46:55 +08001165static void cache_flush_pending_requests_locked(struct resolv_cache* cache) {
1166 resolv_cache::pending_req_info *ri, *tmp;
1167 if (!cache) return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001168
Ken Chen2a429352018-12-22 21:46:55 +08001169 ri = cache->pending_requests.next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001170
Ken Chen2a429352018-12-22 21:46:55 +08001171 while (ri) {
1172 tmp = ri;
1173 ri = ri->next;
1174 free(tmp);
Bernie Innocenti55864192018-08-30 04:05:20 +09001175 }
1176
Ken Chen2a429352018-12-22 21:46:55 +08001177 cache->pending_requests.next = NULL;
1178 cv.notify_all();
Bernie Innocenti55864192018-08-30 04:05:20 +09001179}
1180
Ken Chen2a429352018-12-22 21:46:55 +08001181// Return true - if there is a pending request in |cache| matching |key|.
1182// Return false - if no pending request is found matching the key. Optionally
1183// link a new one if parameter append_if_not_found is true.
1184static bool cache_has_pending_request_locked(resolv_cache* cache, const Entry* key,
1185 bool append_if_not_found) {
1186 if (!cache || !key) return false;
Bernie Innocenti55864192018-08-30 04:05:20 +09001187
Ken Chen2a429352018-12-22 21:46:55 +08001188 resolv_cache::pending_req_info* ri = cache->pending_requests.next;
1189 resolv_cache::pending_req_info* prev = &cache->pending_requests;
1190 while (ri) {
1191 if (ri->hash == key->hash) {
1192 return true;
Bernie Innocenti55864192018-08-30 04:05:20 +09001193 }
Ken Chen2a429352018-12-22 21:46:55 +08001194 prev = ri;
1195 ri = ri->next;
1196 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001197
Ken Chen2a429352018-12-22 21:46:55 +08001198 if (append_if_not_found) {
1199 ri = (resolv_cache::pending_req_info*)calloc(1, sizeof(resolv_cache::pending_req_info));
Bernie Innocenti55864192018-08-30 04:05:20 +09001200 if (ri) {
Ken Chen2a429352018-12-22 21:46:55 +08001201 ri->hash = key->hash;
1202 prev->next = ri;
Bernie Innocenti55864192018-08-30 04:05:20 +09001203 }
1204 }
Ken Chen2a429352018-12-22 21:46:55 +08001205 return false;
1206}
1207
1208// Notify all threads that the cache entry |key| has become available
1209static void _cache_notify_waiting_tid_locked(struct resolv_cache* cache, const Entry* key) {
1210 if (!cache || !key) return;
1211
1212 resolv_cache::pending_req_info* ri = cache->pending_requests.next;
1213 resolv_cache::pending_req_info* prev = &cache->pending_requests;
1214 while (ri) {
1215 if (ri->hash == key->hash) {
1216 // remove item from list and destroy
1217 prev->next = ri->next;
1218 free(ri);
1219 cv.notify_all();
1220 return;
1221 }
1222 prev = ri;
1223 ri = ri->next;
1224 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001225}
1226
Luke Huang952d0942018-12-26 16:53:03 +08001227void _resolv_cache_query_failed(unsigned netid, const void* query, int querylen, uint32_t flags) {
1228 // We should not notify with these flags.
1229 if (flags & (ANDROID_RESOLV_NO_CACHE_STORE | ANDROID_RESOLV_NO_CACHE_LOOKUP)) {
1230 return;
1231 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001232 Entry key[1];
1233 Cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001234
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001235 if (!entry_init_key(key, query, querylen)) return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001236
Ken Chen2a429352018-12-22 21:46:55 +08001237 std::lock_guard guard(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001238
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001239 cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001240
1241 if (cache) {
1242 _cache_notify_waiting_tid_locked(cache, key);
1243 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001244}
1245
Bernie Innocentid2b27032018-12-18 19:53:42 +09001246static void cache_flush_locked(Cache* cache) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001247 int nn;
Bernie Innocenti55864192018-08-30 04:05:20 +09001248
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001249 for (nn = 0; nn < cache->max_entries; nn++) {
1250 Entry** pnode = (Entry**) &cache->entries[nn];
Bernie Innocenti55864192018-08-30 04:05:20 +09001251
1252 while (*pnode != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001253 Entry* node = *pnode;
Bernie Innocenti55864192018-08-30 04:05:20 +09001254 *pnode = node->hlink;
1255 entry_free(node);
1256 }
1257 }
1258
1259 // flush pending request
Ken Chen2a429352018-12-22 21:46:55 +08001260 cache_flush_pending_requests_locked(cache);
Bernie Innocenti55864192018-08-30 04:05:20 +09001261
1262 cache->mru_list.mru_next = cache->mru_list.mru_prev = &cache->mru_list;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001263 cache->num_entries = 0;
1264 cache->last_id = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +09001265
chenbruce16adee42019-02-20 19:45:50 +08001266 LOG(INFO) << "*** DNS CACHE FLUSHED ***";
Bernie Innocenti55864192018-08-30 04:05:20 +09001267}
1268
Ken Chen2a429352018-12-22 21:46:55 +08001269static resolv_cache* resolv_cache_create() {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001270 struct resolv_cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001271
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001272 cache = (struct resolv_cache*) calloc(sizeof(*cache), 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001273 if (cache) {
nuccachen989d2232018-11-29 17:41:12 +08001274 cache->max_entries = CONFIG_MAX_ENTRIES;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001275 cache->entries = (Entry*) calloc(sizeof(*cache->entries), cache->max_entries);
Bernie Innocenti55864192018-08-30 04:05:20 +09001276 if (cache->entries) {
1277 cache->mru_list.mru_prev = cache->mru_list.mru_next = &cache->mru_list;
chenbruce16adee42019-02-20 19:45:50 +08001278 LOG(INFO) << __func__ << ": cache created";
Bernie Innocenti55864192018-08-30 04:05:20 +09001279 } else {
1280 free(cache);
1281 cache = NULL;
1282 }
1283 }
1284 return cache;
1285}
1286
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001287static void dump_query(const uint8_t* query, int querylen) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001288 char temp[256], *p = temp, *end = p + sizeof(temp);
1289 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001290
1291 _dnsPacket_init(pack, query, querylen);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001292 p = dnsPacket_bprintQuery(pack, p, end);
chenbruce16adee42019-02-20 19:45:50 +08001293 LOG(INFO) << temp;
Bernie Innocenti55864192018-08-30 04:05:20 +09001294}
1295
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001296static void cache_dump_mru(Cache* cache) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001297 char temp[512], *p = temp, *end = p + sizeof(temp);
1298 Entry* e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001299
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001300 p = bprint(temp, end, "MRU LIST (%2d): ", cache->num_entries);
Bernie Innocenti55864192018-08-30 04:05:20 +09001301 for (e = cache->mru_list.mru_next; e != &cache->mru_list; e = e->mru_next)
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001302 p = bprint(p, end, " %d", e->id);
Bernie Innocenti55864192018-08-30 04:05:20 +09001303
chenbruce16adee42019-02-20 19:45:50 +08001304 LOG(INFO) << temp;
Bernie Innocenti55864192018-08-30 04:05:20 +09001305}
1306
Bernie Innocenti55864192018-08-30 04:05:20 +09001307/* This function tries to find a key within the hash table
1308 * In case of success, it will return a *pointer* to the hashed key.
1309 * In case of failure, it will return a *pointer* to NULL
1310 *
1311 * So, the caller must check '*result' to check for success/failure.
1312 *
1313 * The main idea is that the result can later be used directly in
1314 * calls to _resolv_cache_add or _resolv_cache_remove as the 'lookup'
1315 * parameter. This makes the code simpler and avoids re-searching
1316 * for the key position in the htable.
1317 *
1318 * The result of a lookup_p is only valid until you alter the hash
1319 * table.
1320 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001321static Entry** _cache_lookup_p(Cache* cache, Entry* key) {
1322 int index = key->hash % cache->max_entries;
1323 Entry** pnode = (Entry**) &cache->entries[index];
Bernie Innocenti55864192018-08-30 04:05:20 +09001324
1325 while (*pnode != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001326 Entry* node = *pnode;
Bernie Innocenti55864192018-08-30 04:05:20 +09001327
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001328 if (node == NULL) break;
Bernie Innocenti55864192018-08-30 04:05:20 +09001329
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001330 if (node->hash == key->hash && entry_equals(node, key)) break;
Bernie Innocenti55864192018-08-30 04:05:20 +09001331
1332 pnode = &node->hlink;
1333 }
1334 return pnode;
1335}
1336
1337/* Add a new entry to the hash table. 'lookup' must be the
1338 * result of an immediate previous failed _lookup_p() call
1339 * (i.e. with *lookup == NULL), and 'e' is the pointer to the
1340 * newly created entry
1341 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001342static void _cache_add_p(Cache* cache, Entry** lookup, Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001343 *lookup = e;
1344 e->id = ++cache->last_id;
1345 entry_mru_add(e, &cache->mru_list);
1346 cache->num_entries += 1;
1347
chenbruce16adee42019-02-20 19:45:50 +08001348 LOG(INFO) << __func__ << ": entry " << e->id << " added (count=" << cache->num_entries << ")";
Bernie Innocenti55864192018-08-30 04:05:20 +09001349}
1350
1351/* Remove an existing entry from the hash table,
1352 * 'lookup' must be the result of an immediate previous
1353 * and succesful _lookup_p() call.
1354 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001355static void _cache_remove_p(Cache* cache, Entry** lookup) {
1356 Entry* e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001357
chenbruce16adee42019-02-20 19:45:50 +08001358 LOG(INFO) << __func__ << ": entry " << e->id << " removed (count=" << cache->num_entries - 1
1359 << ")";
Bernie Innocenti55864192018-08-30 04:05:20 +09001360
1361 entry_mru_remove(e);
1362 *lookup = e->hlink;
1363 entry_free(e);
1364 cache->num_entries -= 1;
1365}
1366
1367/* Remove the oldest entry from the hash table.
1368 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001369static void _cache_remove_oldest(Cache* cache) {
1370 Entry* oldest = cache->mru_list.mru_prev;
1371 Entry** lookup = _cache_lookup_p(cache, oldest);
Bernie Innocenti55864192018-08-30 04:05:20 +09001372
1373 if (*lookup == NULL) { /* should not happen */
chenbruce16adee42019-02-20 19:45:50 +08001374 LOG(INFO) << __func__ << ": OLDEST NOT IN HTABLE ?";
Bernie Innocenti55864192018-08-30 04:05:20 +09001375 return;
1376 }
chenbruce16adee42019-02-20 19:45:50 +08001377 LOG(INFO) << "Cache full - removing oldest";
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001378 dump_query(oldest->query, oldest->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001379 _cache_remove_p(cache, lookup);
1380}
1381
1382/* Remove all expired entries from the hash table.
1383 */
1384static void _cache_remove_expired(Cache* cache) {
1385 Entry* e;
1386 time_t now = _time_now();
1387
1388 for (e = cache->mru_list.mru_next; e != &cache->mru_list;) {
1389 // Entry is old, remove
1390 if (now >= e->expires) {
1391 Entry** lookup = _cache_lookup_p(cache, e);
1392 if (*lookup == NULL) { /* should not happen */
chenbruce16adee42019-02-20 19:45:50 +08001393 LOG(INFO) << __func__ << ": ENTRY NOT IN HTABLE ?";
Bernie Innocenti55864192018-08-30 04:05:20 +09001394 return;
1395 }
1396 e = e->mru_next;
1397 _cache_remove_p(cache, lookup);
1398 } else {
1399 e = e->mru_next;
1400 }
1401 }
1402}
1403
Ken Chen2a429352018-12-22 21:46:55 +08001404// gets a resolv_cache_info associated with a network, or NULL if not found
1405static resolv_cache_info* find_cache_info_locked(unsigned netid) REQUIRES(cache_mutex);
1406
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001407ResolvCacheStatus _resolv_cache_lookup(unsigned netid, const void* query, int querylen,
Luke Huang952d0942018-12-26 16:53:03 +08001408 void* answer, int answersize, int* answerlen,
1409 uint32_t flags) {
1410 if (flags & ANDROID_RESOLV_NO_CACHE_LOOKUP) {
1411 return RESOLV_CACHE_SKIP;
1412 }
Ken Chen2a429352018-12-22 21:46:55 +08001413 Entry key;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001414 Entry** lookup;
1415 Entry* e;
1416 time_t now;
1417 Cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001418
chenbruce16adee42019-02-20 19:45:50 +08001419 LOG(INFO) << __func__ << ": lookup";
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001420 dump_query((u_char*) query, querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001421
1422 /* we don't cache malformed queries */
Ken Chen2a429352018-12-22 21:46:55 +08001423 if (!entry_init_key(&key, query, querylen)) {
chenbruce16adee42019-02-20 19:45:50 +08001424 LOG(INFO) << __func__ << ": unsupported query";
Bernie Innocenti55864192018-08-30 04:05:20 +09001425 return RESOLV_CACHE_UNSUPPORTED;
1426 }
1427 /* lookup cache */
Ken Chen2a429352018-12-22 21:46:55 +08001428 std::unique_lock lock(cache_mutex);
1429 ScopedAssumeLocked assume_lock(cache_mutex);
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001430 cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001431 if (cache == NULL) {
Ken Chen2a429352018-12-22 21:46:55 +08001432 return RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti55864192018-08-30 04:05:20 +09001433 }
1434
1435 /* see the description of _lookup_p to understand this.
1436 * the function always return a non-NULL pointer.
1437 */
Ken Chen2a429352018-12-22 21:46:55 +08001438 lookup = _cache_lookup_p(cache, &key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001439 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001440
1441 if (e == NULL) {
chenbruce16adee42019-02-20 19:45:50 +08001442 LOG(INFO) << "NOT IN CACHE";
Luke Huang952d0942018-12-26 16:53:03 +08001443 // If it is no-cache-store mode, we won't wait for possible query.
1444 if (flags & ANDROID_RESOLV_NO_CACHE_STORE) {
Ken Chen2a429352018-12-22 21:46:55 +08001445 return RESOLV_CACHE_SKIP;
Luke Huang952d0942018-12-26 16:53:03 +08001446 }
Ken Chen2a429352018-12-22 21:46:55 +08001447
1448 if (!cache_has_pending_request_locked(cache, &key, true)) {
1449 return RESOLV_CACHE_NOTFOUND;
1450
Bernie Innocenti55864192018-08-30 04:05:20 +09001451 } else {
chenbruce16adee42019-02-20 19:45:50 +08001452 LOG(INFO) << "Waiting for previous request";
Ken Chen2a429352018-12-22 21:46:55 +08001453 // wait until (1) timeout OR
1454 // (2) cv is notified AND no pending request matching the |key|
1455 // (cv notifier should delete pending request before sending notification.)
1456 bool ret = cv.wait_for(lock, std::chrono::seconds(PENDING_REQUEST_TIMEOUT),
1457 [netid, &cache, &key]() REQUIRES(cache_mutex) {
1458 // Must update cache as it could have been deleted
1459 cache = find_named_cache_locked(netid);
1460 return !cache_has_pending_request_locked(cache, &key, false);
1461 });
Ken Chen111c1ba2019-02-21 03:50:11 +08001462 if (!cache) {
1463 return RESOLV_CACHE_NOTFOUND;
1464 }
Ken Chen2a429352018-12-22 21:46:55 +08001465 if (ret == false) {
1466 resolv_cache_info* info = find_cache_info_locked(netid);
1467 if (info != NULL) {
1468 info->wait_for_pending_req_timeout_count++;
1469 }
1470 }
1471 lookup = _cache_lookup_p(cache, &key);
Bernie Innocenti55864192018-08-30 04:05:20 +09001472 e = *lookup;
1473 if (e == NULL) {
Ken Chen2a429352018-12-22 21:46:55 +08001474 return RESOLV_CACHE_NOTFOUND;
Bernie Innocenti55864192018-08-30 04:05:20 +09001475 }
1476 }
1477 }
1478
1479 now = _time_now();
1480
1481 /* remove stale entries here */
1482 if (now >= e->expires) {
chenbruce16adee42019-02-20 19:45:50 +08001483 LOG(INFO) << " NOT IN CACHE (STALE ENTRY " << *lookup << "DISCARDED)";
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001484 dump_query(e->query, e->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001485 _cache_remove_p(cache, lookup);
Ken Chen2a429352018-12-22 21:46:55 +08001486 return RESOLV_CACHE_NOTFOUND;
Bernie Innocenti55864192018-08-30 04:05:20 +09001487 }
1488
1489 *answerlen = e->answerlen;
1490 if (e->answerlen > answersize) {
1491 /* NOTE: we return UNSUPPORTED if the answer buffer is too short */
chenbruce16adee42019-02-20 19:45:50 +08001492 LOG(INFO) << " ANSWER TOO LONG";
Ken Chen2a429352018-12-22 21:46:55 +08001493 return RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti55864192018-08-30 04:05:20 +09001494 }
1495
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001496 memcpy(answer, e->answer, e->answerlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001497
1498 /* bump up this entry to the top of the MRU list */
1499 if (e != cache->mru_list.mru_next) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001500 entry_mru_remove(e);
1501 entry_mru_add(e, &cache->mru_list);
Bernie Innocenti55864192018-08-30 04:05:20 +09001502 }
1503
chenbruce16adee42019-02-20 19:45:50 +08001504 LOG(INFO) << " FOUND IN CACHE entry=" << e;
Ken Chen2a429352018-12-22 21:46:55 +08001505 return RESOLV_CACHE_FOUND;
Bernie Innocenti55864192018-08-30 04:05:20 +09001506}
1507
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001508void _resolv_cache_add(unsigned netid, const void* query, int querylen, const void* answer,
1509 int answerlen) {
1510 Entry key[1];
1511 Entry* e;
1512 Entry** lookup;
1513 u_long ttl;
1514 Cache* cache = NULL;
Bernie Innocenti55864192018-08-30 04:05:20 +09001515
1516 /* don't assume that the query has already been cached
1517 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001518 if (!entry_init_key(key, query, querylen)) {
chenbruce16adee42019-02-20 19:45:50 +08001519 LOG(INFO) << __func__ << ": passed invalid query?";
Bernie Innocenti55864192018-08-30 04:05:20 +09001520 return;
1521 }
1522
Ken Chen2a429352018-12-22 21:46:55 +08001523 std::lock_guard guard(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001524
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001525 cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001526 if (cache == NULL) {
Ken Chen2a429352018-12-22 21:46:55 +08001527 return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001528 }
1529
chenbruce16adee42019-02-20 19:45:50 +08001530 LOG(INFO) << __func__ << ": query:";
chenbrucee8911f92019-03-06 13:52:43 +08001531 dump_query((u_char*)query, querylen);
1532 res_pquery((u_char*)answer, answerlen);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001533 if (kDumpData) {
chenbruce16adee42019-02-20 19:45:50 +08001534 LOG(INFO) << "answer:";
chenbrucee8911f92019-03-06 13:52:43 +08001535 dump_bytes((u_char*)answer, answerlen);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001536 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001537
1538 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001539 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001540
1541 if (e != NULL) { /* should not happen */
chenbruce16adee42019-02-20 19:45:50 +08001542 LOG(INFO) << __func__ << ": ALREADY IN CACHE (" << e << ") ? IGNORING ADD";
Ken Chen2a429352018-12-22 21:46:55 +08001543 _cache_notify_waiting_tid_locked(cache, key);
1544 return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001545 }
1546
1547 if (cache->num_entries >= cache->max_entries) {
1548 _cache_remove_expired(cache);
1549 if (cache->num_entries >= cache->max_entries) {
1550 _cache_remove_oldest(cache);
1551 }
1552 /* need to lookup again */
1553 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001554 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001555 if (e != NULL) {
chenbruce16adee42019-02-20 19:45:50 +08001556 LOG(INFO) << __func__ << ": ALREADY IN CACHE (" << e << ") ? IGNORING ADD";
Ken Chen2a429352018-12-22 21:46:55 +08001557 _cache_notify_waiting_tid_locked(cache, key);
1558 return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001559 }
1560 }
1561
1562 ttl = answer_getTTL(answer, answerlen);
1563 if (ttl > 0) {
1564 e = entry_alloc(key, answer, answerlen);
1565 if (e != NULL) {
1566 e->expires = ttl + _time_now();
1567 _cache_add_p(cache, lookup, e);
1568 }
1569 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001570
Ken Chen2a429352018-12-22 21:46:55 +08001571 cache_dump_mru(cache);
1572 _cache_notify_waiting_tid_locked(cache, key);
Bernie Innocenti55864192018-08-30 04:05:20 +09001573}
1574
Ken Chen2a429352018-12-22 21:46:55 +08001575// Head of the list of caches.
1576static struct resolv_cache_info res_cache_list GUARDED_BY(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001577
ckenb1a69a42018-12-01 17:45:18 +09001578// insert resolv_cache_info into the list of resolv_cache_infos
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001579static void insert_cache_info_locked(resolv_cache_info* cache_info);
ckenb1a69a42018-12-01 17:45:18 +09001580// creates a resolv_cache_info
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001581static resolv_cache_info* create_cache_info();
ckenb1a69a42018-12-01 17:45:18 +09001582// empty the nameservers set for the named cache
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001583static void free_nameservers_locked(resolv_cache_info* cache_info);
1584// return 1 if the provided list of name servers differs from the list of name servers
1585// currently attached to the provided cache_info
1586static int resolv_is_nameservers_equal_locked(resolv_cache_info* cache_info, const char** servers,
1587 int numservers);
ckenb1a69a42018-12-01 17:45:18 +09001588// clears the stats samples contained withing the given cache_info
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001589static void res_cache_clear_stats_locked(resolv_cache_info* cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001590
ckenb1a69a42018-12-01 17:45:18 +09001591// public API for netd to query if name server is set on specific netid
1592bool resolv_has_nameservers(unsigned netid) {
Ken Chen2a429352018-12-22 21:46:55 +08001593 std::lock_guard guard(cache_mutex);
ckenb1a69a42018-12-01 17:45:18 +09001594 resolv_cache_info* info = find_cache_info_locked(netid);
Ken Chen2a429352018-12-22 21:46:55 +08001595 return (info != nullptr) && (info->nscount > 0);
ckenb1a69a42018-12-01 17:45:18 +09001596}
1597
1598// look up the named cache, and creates one if needed
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001599static resolv_cache* get_res_cache_for_net_locked(unsigned netid) {
1600 resolv_cache* cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001601 if (!cache) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001602 resolv_cache_info* cache_info = create_cache_info();
Bernie Innocenti55864192018-08-30 04:05:20 +09001603 if (cache_info) {
Ken Chen2a429352018-12-22 21:46:55 +08001604 cache = resolv_cache_create();
Bernie Innocenti55864192018-08-30 04:05:20 +09001605 if (cache) {
1606 cache_info->cache = cache;
1607 cache_info->netid = netid;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001608 insert_cache_info_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001609 } else {
1610 free(cache_info);
1611 }
1612 }
1613 }
1614 return cache;
1615}
1616
Bernie Innocenti189eb502018-10-01 23:10:18 +09001617void resolv_delete_cache_for_net(unsigned netid) {
Ken Chen2a429352018-12-22 21:46:55 +08001618 std::lock_guard guard(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001619
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001620 struct resolv_cache_info* prev_cache_info = &res_cache_list;
Bernie Innocenti55864192018-08-30 04:05:20 +09001621
1622 while (prev_cache_info->next) {
1623 struct resolv_cache_info* cache_info = prev_cache_info->next;
1624
1625 if (cache_info->netid == netid) {
1626 prev_cache_info->next = cache_info->next;
Bernie Innocentid2b27032018-12-18 19:53:42 +09001627 cache_flush_locked(cache_info->cache);
Bernie Innocenti55864192018-08-30 04:05:20 +09001628 free(cache_info->cache->entries);
1629 free(cache_info->cache);
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001630 free_nameservers_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001631 free(cache_info);
1632 break;
1633 }
1634
1635 prev_cache_info = prev_cache_info->next;
1636 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001637}
1638
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001639static resolv_cache_info* create_cache_info() {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001640 return (struct resolv_cache_info*) calloc(sizeof(struct resolv_cache_info), 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001641}
1642
Ken Chen2a429352018-12-22 21:46:55 +08001643// TODO: convert this to a simple and efficient C++ container.
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001644static void insert_cache_info_locked(struct resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001645 struct resolv_cache_info* last;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001646 for (last = &res_cache_list; last->next; last = last->next) {}
Bernie Innocenti55864192018-08-30 04:05:20 +09001647 last->next = cache_info;
Bernie Innocenti55864192018-08-30 04:05:20 +09001648}
1649
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001650static resolv_cache* find_named_cache_locked(unsigned netid) {
ckenb1a69a42018-12-01 17:45:18 +09001651 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001652 if (info != NULL) return info->cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001653 return NULL;
1654}
1655
ckenb1a69a42018-12-01 17:45:18 +09001656static resolv_cache_info* find_cache_info_locked(unsigned netid) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001657 struct resolv_cache_info* cache_info = res_cache_list.next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001658
1659 while (cache_info) {
1660 if (cache_info->netid == netid) {
1661 break;
1662 }
1663
1664 cache_info = cache_info->next;
1665 }
1666 return cache_info;
1667}
1668
Bernie Innocenti34de3ba2019-02-19 18:08:36 +09001669static void resolv_set_default_params(res_params* params) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001670 params->sample_validity = NSSAMPLE_VALIDITY;
1671 params->success_threshold = SUCCESS_THRESHOLD;
1672 params->min_samples = 0;
1673 params->max_samples = 0;
1674 params->base_timeout_msec = 0; // 0 = legacy algorithm
waynemad193e4d2019-02-18 17:47:59 +08001675 params->retry_count = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +09001676}
1677
Bernie Innocenti45238a12018-12-04 14:57:48 +09001678int resolv_set_nameservers_for_net(unsigned netid, const char** servers, const int numservers,
Bernie Innocenti34de3ba2019-02-19 18:08:36 +09001679 const char* domains, const res_params* params) {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001680 char* cp;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001681 int* offset;
Bernie Innocenti55864192018-08-30 04:05:20 +09001682 struct addrinfo* nsaddrinfo[MAXNS];
1683
1684 if (numservers > MAXNS) {
Bernie Innocentid017e972019-03-03 19:39:53 +09001685 LOG(ERROR) << __func__ << ": numservers=" << numservers << ", MAXNS=" << MAXNS;
Bernie Innocenti55864192018-08-30 04:05:20 +09001686 return E2BIG;
1687 }
1688
1689 // Parse the addresses before actually locking or changing any state, in case there is an error.
1690 // As a side effect this also reduces the time the lock is kept.
Bernie Innocentic165ce82018-10-16 23:35:28 +09001691 char sbuf[NI_MAXSERV];
Bernie Innocenti55864192018-08-30 04:05:20 +09001692 snprintf(sbuf, sizeof(sbuf), "%u", NAMESERVER_PORT);
Bernie Innocenti45238a12018-12-04 14:57:48 +09001693 for (int i = 0; i < numservers; i++) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001694 // The addrinfo structures allocated here are freed in free_nameservers_locked().
Bernie Innocentic165ce82018-10-16 23:35:28 +09001695 const addrinfo hints = {
1696 .ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM, .ai_flags = AI_NUMERICHOST};
1697 int rt = getaddrinfo_numeric(servers[i], sbuf, hints, &nsaddrinfo[i]);
Bernie Innocenti55864192018-08-30 04:05:20 +09001698 if (rt != 0) {
Bernie Innocenti45238a12018-12-04 14:57:48 +09001699 for (int j = 0; j < i; j++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001700 freeaddrinfo(nsaddrinfo[j]);
Bernie Innocenti55864192018-08-30 04:05:20 +09001701 }
chenbruce16adee42019-02-20 19:45:50 +08001702 LOG(INFO) << __func__ << ": getaddrinfo_numeric(" << servers[i]
1703 << ") = " << gai_strerror(rt);
Bernie Innocenti55864192018-08-30 04:05:20 +09001704 return EINVAL;
1705 }
1706 }
1707
Ken Chen2a429352018-12-22 21:46:55 +08001708 std::lock_guard guard(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001709 // creates the cache if not created
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001710 get_res_cache_for_net_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001711
ckenb1a69a42018-12-01 17:45:18 +09001712 resolv_cache_info* cache_info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001713
1714 if (cache_info != NULL) {
1715 uint8_t old_max_samples = cache_info->params.max_samples;
1716 if (params != NULL) {
1717 cache_info->params = *params;
1718 } else {
Bernie Innocenti1fbca5c2018-10-01 20:46:20 +09001719 resolv_set_default_params(&cache_info->params);
Bernie Innocenti55864192018-08-30 04:05:20 +09001720 }
1721
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001722 if (!resolv_is_nameservers_equal_locked(cache_info, servers, numservers)) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001723 // free current before adding new
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001724 free_nameservers_locked(cache_info);
Bernie Innocenti45238a12018-12-04 14:57:48 +09001725 for (int i = 0; i < numservers; i++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001726 cache_info->nsaddrinfo[i] = nsaddrinfo[i];
1727 cache_info->nameservers[i] = strdup(servers[i]);
chenbruce16adee42019-02-20 19:45:50 +08001728 LOG(INFO) << __func__ << ": netid = " << netid << ", addr = " << servers[i];
Bernie Innocenti55864192018-08-30 04:05:20 +09001729 }
1730 cache_info->nscount = numservers;
1731
1732 // Clear the NS statistics because the mapping to nameservers might have changed.
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001733 res_cache_clear_stats_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001734
1735 // increment the revision id to ensure that sample state is not written back if the
1736 // servers change; in theory it would suffice to do so only if the servers or
1737 // max_samples actually change, in practice the overhead of checking is higher than the
1738 // cost, and overflows are unlikely
1739 ++cache_info->revision_id;
Ken Chen26f01e42018-11-02 13:18:40 +08001740 } else {
1741 if (cache_info->params.max_samples != old_max_samples) {
1742 // If the maximum number of samples changes, the overhead of keeping the most recent
1743 // samples around is not considered worth the effort, so they are cleared instead.
1744 // All other parameters do not affect shared state: Changing these parameters does
1745 // not invalidate the samples, as they only affect aggregation and the conditions
1746 // under which servers are considered usable.
1747 res_cache_clear_stats_locked(cache_info);
1748 ++cache_info->revision_id;
1749 }
Bernie Innocenti45238a12018-12-04 14:57:48 +09001750 for (int j = 0; j < numservers; j++) {
Ken Chen26f01e42018-11-02 13:18:40 +08001751 freeaddrinfo(nsaddrinfo[j]);
1752 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001753 }
1754
1755 // Always update the search paths, since determining whether they actually changed is
1756 // complex due to the zero-padding, and probably not worth the effort. Cache-flushing
Bernie Innocentid017e972019-03-03 19:39:53 +09001757 // however is not necessary, since the stored cache entries do contain the domain, not
Bernie Innocenti55864192018-08-30 04:05:20 +09001758 // just the host name.
Bernie Innocenti55864192018-08-30 04:05:20 +09001759 strlcpy(cache_info->defdname, domains, sizeof(cache_info->defdname));
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001760 if ((cp = strchr(cache_info->defdname, '\n')) != NULL) *cp = '\0';
Bernie Innocentid017e972019-03-03 19:39:53 +09001761 LOG(INFO) << __func__ << ": domains=\"" << cache_info->defdname << "\"";
Bernie Innocenti55864192018-08-30 04:05:20 +09001762
1763 cp = cache_info->defdname;
1764 offset = cache_info->dnsrch_offset;
1765 while (offset < cache_info->dnsrch_offset + MAXDNSRCH) {
1766 while (*cp == ' ' || *cp == '\t') /* skip leading white space */
1767 cp++;
1768 if (*cp == '\0') /* stop if nothing more to do */
1769 break;
1770 *offset++ = cp - cache_info->defdname; /* record this search domain */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001771 while (*cp) { /* zero-terminate it */
1772 if (*cp == ' ' || *cp == '\t') {
Bernie Innocenti55864192018-08-30 04:05:20 +09001773 *cp++ = '\0';
1774 break;
1775 }
1776 cp++;
1777 }
1778 }
1779 *offset = -1; /* cache_info->dnsrch_offset has MAXDNSRCH+1 items */
1780 }
1781
Bernie Innocenti55864192018-08-30 04:05:20 +09001782 return 0;
1783}
1784
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001785static int resolv_is_nameservers_equal_locked(resolv_cache_info* cache_info, const char** servers,
1786 int numservers) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001787 if (cache_info->nscount != numservers) {
1788 return 0;
1789 }
1790
1791 // Compare each name server against current name servers.
1792 // TODO: this is incorrect if the list of current or previous nameservers
1793 // contains duplicates. This does not really matter because the framework
1794 // filters out duplicates, but we should probably fix it. It's also
1795 // insensitive to the order of the nameservers; we should probably fix that
1796 // too.
1797 for (int i = 0; i < numservers; i++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001798 for (int j = 0;; j++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001799 if (j >= numservers) {
1800 return 0;
1801 }
1802 if (strcmp(cache_info->nameservers[i], servers[j]) == 0) {
1803 break;
1804 }
1805 }
1806 }
1807
1808 return 1;
1809}
1810
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001811static void free_nameservers_locked(resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001812 int i;
1813 for (i = 0; i < cache_info->nscount; i++) {
1814 free(cache_info->nameservers[i]);
1815 cache_info->nameservers[i] = NULL;
1816 if (cache_info->nsaddrinfo[i] != NULL) {
1817 freeaddrinfo(cache_info->nsaddrinfo[i]);
1818 cache_info->nsaddrinfo[i] = NULL;
1819 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001820 cache_info->nsstats[i].sample_count = cache_info->nsstats[i].sample_next = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +09001821 }
1822 cache_info->nscount = 0;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001823 res_cache_clear_stats_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001824 ++cache_info->revision_id;
1825}
1826
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001827void _resolv_populate_res_for_net(res_state statp) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001828 if (statp == NULL) {
1829 return;
1830 }
Bernie Innocentid017e972019-03-03 19:39:53 +09001831 LOG(INFO) << __func__ << "(netid=" << statp->netid << ")";
Bernie Innocenti55864192018-08-30 04:05:20 +09001832
Ken Chen2a429352018-12-22 21:46:55 +08001833 std::lock_guard guard(cache_mutex);
ckenb1a69a42018-12-01 17:45:18 +09001834 resolv_cache_info* info = find_cache_info_locked(statp->netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001835 if (info != NULL) {
1836 int nserv;
1837 struct addrinfo* ai;
Bernie Innocenti55864192018-08-30 04:05:20 +09001838 for (nserv = 0; nserv < MAXNS; nserv++) {
1839 ai = info->nsaddrinfo[nserv];
1840 if (ai == NULL) {
1841 break;
1842 }
1843
1844 if ((size_t) ai->ai_addrlen <= sizeof(statp->_u._ext.ext->nsaddrs[0])) {
1845 if (statp->_u._ext.ext != NULL) {
1846 memcpy(&statp->_u._ext.ext->nsaddrs[nserv], ai->ai_addr, ai->ai_addrlen);
1847 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
1848 } else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001849 if ((size_t) ai->ai_addrlen <= sizeof(statp->nsaddr_list[0])) {
1850 memcpy(&statp->nsaddr_list[nserv], ai->ai_addr, ai->ai_addrlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001851 } else {
1852 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
1853 }
1854 }
1855 } else {
chenbruce16adee42019-02-20 19:45:50 +08001856 LOG(INFO) << __func__ << ": found too long addrlen";
Bernie Innocenti55864192018-08-30 04:05:20 +09001857 }
1858 }
1859 statp->nscount = nserv;
1860 // now do search domains. Note that we cache the offsets as this code runs alot
1861 // but the setting/offset-computer only runs when set/changed
1862 // WARNING: Don't use str*cpy() here, this string contains zeroes.
1863 memcpy(statp->defdname, info->defdname, sizeof(statp->defdname));
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001864 char** pp = statp->dnsrch;
1865 int* p = info->dnsrch_offset;
Bernie Innocenti55864192018-08-30 04:05:20 +09001866 while (pp < statp->dnsrch + MAXDNSRCH && *p != -1) {
1867 *pp++ = &statp->defdname[0] + *p++;
1868 }
1869 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001870}
1871
1872/* Resolver reachability statistics. */
1873
Bernie Innocenti189eb502018-10-01 23:10:18 +09001874static void _res_cache_add_stats_sample_locked(res_stats* stats, const res_sample* sample,
1875 int max_samples) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001876 // Note: This function expects max_samples > 0, otherwise a (harmless) modification of the
1877 // allocated but supposedly unused memory for samples[0] will happen
chenbruce16adee42019-02-20 19:45:50 +08001878 LOG(INFO) << __func__ << ": adding sample to stats, next = " << stats->sample_next
1879 << ", count = " << stats->sample_count;
Bernie Innocenti55864192018-08-30 04:05:20 +09001880 stats->samples[stats->sample_next] = *sample;
1881 if (stats->sample_count < max_samples) {
1882 ++stats->sample_count;
1883 }
1884 if (++stats->sample_next >= max_samples) {
1885 stats->sample_next = 0;
1886 }
1887}
1888
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001889static void res_cache_clear_stats_locked(resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001890 if (cache_info) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001891 for (int i = 0; i < MAXNS; ++i) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001892 cache_info->nsstats->sample_count = cache_info->nsstats->sample_next = 0;
1893 }
1894 }
1895}
1896
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001897int android_net_res_stats_get_info_for_net(unsigned netid, int* nscount,
1898 struct sockaddr_storage servers[MAXNS], int* dcount,
1899 char domains[MAXDNSRCH][MAXDNSRCHPATH],
Bernie Innocenti34de3ba2019-02-19 18:08:36 +09001900 res_params* params, struct res_stats stats[MAXNS],
Ken Chen2a429352018-12-22 21:46:55 +08001901 int* wait_for_pending_req_timeout_count) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001902 int revision_id = -1;
Ken Chen2a429352018-12-22 21:46:55 +08001903 std::lock_guard guard(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001904
ckenb1a69a42018-12-01 17:45:18 +09001905 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001906 if (info) {
1907 if (info->nscount > MAXNS) {
chenbruce16adee42019-02-20 19:45:50 +08001908 LOG(INFO) << __func__ << ": nscount " << info->nscount << " > MAXNS " << MAXNS;
Bernie Innocenti55864192018-08-30 04:05:20 +09001909 errno = EFAULT;
1910 return -1;
1911 }
1912 int i;
1913 for (i = 0; i < info->nscount; i++) {
1914 // Verify that the following assumptions are held, failure indicates corruption:
1915 // - getaddrinfo() may never return a sockaddr > sockaddr_storage
1916 // - all addresses are valid
1917 // - there is only one address per addrinfo thanks to numeric resolution
1918 int addrlen = info->nsaddrinfo[i]->ai_addrlen;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001919 if (addrlen < (int) sizeof(struct sockaddr) || addrlen > (int) sizeof(servers[0])) {
chenbruce16adee42019-02-20 19:45:50 +08001920 LOG(INFO) << __func__ << ": nsaddrinfo[" << i << "].ai_addrlen == " << addrlen;
Bernie Innocenti55864192018-08-30 04:05:20 +09001921 errno = EMSGSIZE;
1922 return -1;
1923 }
1924 if (info->nsaddrinfo[i]->ai_addr == NULL) {
chenbruce16adee42019-02-20 19:45:50 +08001925 LOG(INFO) << __func__ << ": nsaddrinfo[" << i << "].ai_addr == NULL";
Bernie Innocenti55864192018-08-30 04:05:20 +09001926 errno = ENOENT;
1927 return -1;
1928 }
1929 if (info->nsaddrinfo[i]->ai_next != NULL) {
chenbruce16adee42019-02-20 19:45:50 +08001930 LOG(INFO) << __func__ << ": nsaddrinfo[" << i << "].ai_next != NULL";
Bernie Innocenti55864192018-08-30 04:05:20 +09001931 errno = ENOTUNIQ;
1932 return -1;
1933 }
1934 }
1935 *nscount = info->nscount;
1936 for (i = 0; i < info->nscount; i++) {
1937 memcpy(&servers[i], info->nsaddrinfo[i]->ai_addr, info->nsaddrinfo[i]->ai_addrlen);
1938 stats[i] = info->nsstats[i];
1939 }
1940 for (i = 0; i < MAXDNSRCH; i++) {
1941 const char* cur_domain = info->defdname + info->dnsrch_offset[i];
1942 // dnsrch_offset[i] can either be -1 or point to an empty string to indicate the end
1943 // of the search offsets. Checking for < 0 is not strictly necessary, but safer.
1944 // TODO: Pass in a search domain array instead of a string to
Bernie Innocenti189eb502018-10-01 23:10:18 +09001945 // resolv_set_nameservers_for_net() and make this double check unnecessary.
Bernie Innocenti55864192018-08-30 04:05:20 +09001946 if (info->dnsrch_offset[i] < 0 ||
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001947 ((size_t) info->dnsrch_offset[i]) >= sizeof(info->defdname) || !cur_domain[0]) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001948 break;
1949 }
1950 strlcpy(domains[i], cur_domain, MAXDNSRCHPATH);
1951 }
1952 *dcount = i;
1953 *params = info->params;
1954 revision_id = info->revision_id;
Ken Chen2a429352018-12-22 21:46:55 +08001955 *wait_for_pending_req_timeout_count = info->wait_for_pending_req_timeout_count;
Bernie Innocenti55864192018-08-30 04:05:20 +09001956 }
1957
Bernie Innocenti55864192018-08-30 04:05:20 +09001958 return revision_id;
1959}
1960
Bernie Innocenti34de3ba2019-02-19 18:08:36 +09001961int resolv_cache_get_resolver_stats(unsigned netid, res_params* params, res_stats stats[MAXNS]) {
Ken Chen2a429352018-12-22 21:46:55 +08001962 std::lock_guard guard(cache_mutex);
ckenb1a69a42018-12-01 17:45:18 +09001963 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001964 if (info) {
1965 memcpy(stats, info->nsstats, sizeof(info->nsstats));
1966 *params = info->params;
Ken Chen2a429352018-12-22 21:46:55 +08001967 return info->revision_id;
Bernie Innocenti55864192018-08-30 04:05:20 +09001968 }
1969
Ken Chen2a429352018-12-22 21:46:55 +08001970 return -1;
Bernie Innocenti55864192018-08-30 04:05:20 +09001971}
1972
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001973void _resolv_cache_add_resolver_stats_sample(unsigned netid, int revision_id, int ns,
Bernie Innocenti189eb502018-10-01 23:10:18 +09001974 const res_sample* sample, int max_samples) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001975 if (max_samples <= 0) return;
1976
Ken Chen2a429352018-12-22 21:46:55 +08001977 std::lock_guard guard(cache_mutex);
ckenb1a69a42018-12-01 17:45:18 +09001978 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001979
1980 if (info && info->revision_id == revision_id) {
1981 _res_cache_add_stats_sample_locked(&info->nsstats[ns], sample, max_samples);
1982 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001983}