blob: b3c437016745323c5c3c887bc69f6a4b082925b9 [file] [log] [blame]
Bernie Innocenti55864192018-08-30 04:05:20 +09001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090029// NOTE: verbose logging MUST NOT be left enabled in production binaries.
30// It floods logs at high rate, and can leak privacy-sensitive information.
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090031constexpr bool kDumpData = false;
32#define LOG_TAG "res_cache"
33
Bernie Innocenti34de3ba2019-02-19 18:08:36 +090034#include "resolv_cache.h"
35
Bernie Innocenti55864192018-08-30 04:05:20 +090036#include <resolv.h>
37#include <stdarg.h>
38#include <stdio.h>
39#include <stdlib.h>
40#include <string.h>
41#include <time.h>
Ken Chen2a429352018-12-22 21:46:55 +080042#include <mutex>
Bernie Innocenti55864192018-08-30 04:05:20 +090043
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090044#include <arpa/inet.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090045#include <arpa/nameser.h>
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090046#include <errno.h>
47#include <linux/if.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090048#include <net/if.h>
49#include <netdb.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090050
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090051#include <android-base/logging.h>
Ken Chen2a429352018-12-22 21:46:55 +080052#include <android-base/thread_annotations.h>
Bernie Innocenti34de3ba2019-02-19 18:08:36 +090053#include <android/multinetwork.h> // ResNsendFlags
Bernie Innocentif89b3512018-08-30 07:34:37 +090054
Bernie Innocenti189eb502018-10-01 23:10:18 +090055#include "res_state_ext.h"
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090056#include "resolv_private.h"
Bernie Innocenti55864192018-08-30 04:05:20 +090057
Bernie Innocenti55864192018-08-30 04:05:20 +090058/* This code implements a small and *simple* DNS resolver cache.
59 *
60 * It is only used to cache DNS answers for a time defined by the smallest TTL
61 * among the answer records in order to reduce DNS traffic. It is not supposed
62 * to be a full DNS cache, since we plan to implement that in the future in a
63 * dedicated process running on the system.
64 *
65 * Note that its design is kept simple very intentionally, i.e.:
66 *
67 * - it takes raw DNS query packet data as input, and returns raw DNS
68 * answer packet data as output
69 *
70 * (this means that two similar queries that encode the DNS name
71 * differently will be treated distinctly).
72 *
73 * the smallest TTL value among the answer records are used as the time
74 * to keep an answer in the cache.
75 *
76 * this is bad, but we absolutely want to avoid parsing the answer packets
77 * (and should be solved by the later full DNS cache process).
78 *
79 * - the implementation is just a (query-data) => (answer-data) hash table
80 * with a trivial least-recently-used expiration policy.
81 *
82 * Doing this keeps the code simple and avoids to deal with a lot of things
83 * that a full DNS cache is expected to do.
84 *
85 * The API is also very simple:
86 *
87 * - the client calls _resolv_cache_get() to obtain a handle to the cache.
88 * this will initialize the cache on first usage. the result can be NULL
89 * if the cache is disabled.
90 *
91 * - the client calls _resolv_cache_lookup() before performing a query
92 *
93 * if the function returns RESOLV_CACHE_FOUND, a copy of the answer data
94 * has been copied into the client-provided answer buffer.
95 *
96 * if the function returns RESOLV_CACHE_NOTFOUND, the client should perform
97 * a request normally, *then* call _resolv_cache_add() to add the received
98 * answer to the cache.
99 *
100 * if the function returns RESOLV_CACHE_UNSUPPORTED, the client should
101 * perform a request normally, and *not* call _resolv_cache_add()
102 *
103 * note that RESOLV_CACHE_UNSUPPORTED is also returned if the answer buffer
104 * is too short to accomodate the cached result.
105 */
106
107/* default number of entries kept in the cache. This value has been
108 * determined by browsing through various sites and counting the number
109 * of corresponding requests. Keep in mind that our framework is currently
110 * performing two requests per name lookup (one for IPv4, the other for IPv6)
111 *
112 * www.google.com 4
113 * www.ysearch.com 6
114 * www.amazon.com 8
115 * www.nytimes.com 22
116 * www.espn.com 28
117 * www.msn.com 28
118 * www.lemonde.fr 35
119 *
120 * (determined in 2009-2-17 from Paris, France, results may vary depending
121 * on location)
122 *
123 * most high-level websites use lots of media/ad servers with different names
124 * but these are generally reused when browsing through the site.
125 *
126 * As such, a value of 64 should be relatively comfortable at the moment.
127 *
128 * ******************************************
129 * * NOTE - this has changed.
130 * * 1) we've added IPv6 support so each dns query results in 2 responses
131 * * 2) we've made this a system-wide cache, so the cost is less (it's not
132 * * duplicated in each process) and the need is greater (more processes
133 * * making different requests).
134 * * Upping by 2x for IPv6
135 * * Upping by another 5x for the centralized nature
136 * *****************************************
137 */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900138#define CONFIG_MAX_ENTRIES (64 * 2 * 5)
Bernie Innocenti55864192018-08-30 04:05:20 +0900139
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900140/** BOUNDED BUFFER FORMATTING **/
Bernie Innocenti55864192018-08-30 04:05:20 +0900141
142/* technical note:
143 *
144 * the following debugging routines are used to append data to a bounded
145 * buffer they take two parameters that are:
146 *
147 * - p : a pointer to the current cursor position in the buffer
148 * this value is initially set to the buffer's address.
149 *
150 * - end : the address of the buffer's limit, i.e. of the first byte
151 * after the buffer. this address should never be touched.
152 *
153 * IMPORTANT: it is assumed that end > buffer_address, i.e.
154 * that the buffer is at least one byte.
155 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900156 * the bprint_x() functions return the new value of 'p' after the data
Bernie Innocenti55864192018-08-30 04:05:20 +0900157 * has been appended, and also ensure the following:
158 *
159 * - the returned value will never be strictly greater than 'end'
160 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900161 * - a return value equal to 'end' means that truncation occurred
Bernie Innocenti55864192018-08-30 04:05:20 +0900162 * (in which case, end[-1] will be set to 0)
163 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900164 * - after returning from a bprint_x() function, the content of the buffer
Bernie Innocenti55864192018-08-30 04:05:20 +0900165 * is always 0-terminated, even in the event of truncation.
166 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900167 * these conventions allow you to call bprint_x() functions multiple times and
Bernie Innocenti55864192018-08-30 04:05:20 +0900168 * only check for truncation at the end of the sequence, as in:
169 *
170 * char buff[1000], *p = buff, *end = p + sizeof(buff);
171 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900172 * p = bprint_c(p, end, '"');
173 * p = bprint_s(p, end, my_string);
174 * p = bprint_c(p, end, '"');
Bernie Innocenti55864192018-08-30 04:05:20 +0900175 *
176 * if (p >= end) {
177 * // buffer was too small
178 * }
179 *
180 * printf( "%s", buff );
181 */
182
Bernie Innocenti34de3ba2019-02-19 18:08:36 +0900183/* Defaults used for initializing res_params */
Bernie Innocenti1fbca5c2018-10-01 20:46:20 +0900184
185// If successes * 100 / total_samples is less than this value, the server is considered failing
186#define SUCCESS_THRESHOLD 75
187// Sample validity in seconds. Set to -1 to disable skipping failing servers.
188#define NSSAMPLE_VALIDITY 1800
189
Bernie Innocenti55864192018-08-30 04:05:20 +0900190/* add a char to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900191static char* bprint_c(char* p, char* end, int c) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900192 if (p < end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900193 if (p + 1 == end)
Bernie Innocenti55864192018-08-30 04:05:20 +0900194 *p++ = 0;
195 else {
196 *p++ = (char) c;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900197 *p = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900198 }
199 }
200 return p;
201}
202
203/* add a sequence of bytes to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900204static char* bprint_b(char* p, char* end, const char* buf, int len) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900205 int avail = end - p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900206
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900207 if (avail <= 0 || len <= 0) return p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900208
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900209 if (avail > len) avail = len;
Bernie Innocenti55864192018-08-30 04:05:20 +0900210
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900211 memcpy(p, buf, avail);
Bernie Innocenti55864192018-08-30 04:05:20 +0900212 p += avail;
213
214 if (p < end)
215 p[0] = 0;
216 else
217 end[-1] = 0;
218
219 return p;
220}
221
222/* add a string to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900223static char* bprint_s(char* p, char* end, const char* str) {
224 return bprint_b(p, end, str, strlen(str));
Bernie Innocenti55864192018-08-30 04:05:20 +0900225}
226
227/* add a formatted string to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900228static char* bprint(char* p, char* end, const char* format, ...) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900229 int avail, n;
230 va_list args;
Bernie Innocenti55864192018-08-30 04:05:20 +0900231
232 avail = end - p;
233
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900234 if (avail <= 0) return p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900235
236 va_start(args, format);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900237 n = vsnprintf(p, avail, format, args);
Bernie Innocenti55864192018-08-30 04:05:20 +0900238 va_end(args);
239
240 /* certain C libraries return -1 in case of truncation */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900241 if (n < 0 || n > avail) n = avail;
Bernie Innocenti55864192018-08-30 04:05:20 +0900242
243 p += n;
244 /* certain C libraries do not zero-terminate in case of truncation */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900245 if (p == end) p[-1] = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900246
247 return p;
248}
249
250/* add a hex value to a bounded buffer, up to 8 digits */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900251static char* bprint_hex(char* p, char* end, unsigned value, int numDigits) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900252 char text[sizeof(unsigned) * 2];
253 int nn = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900254
255 while (numDigits-- > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900256 text[nn++] = "0123456789abcdef"[(value >> (numDigits * 4)) & 15];
Bernie Innocenti55864192018-08-30 04:05:20 +0900257 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900258 return bprint_b(p, end, text, nn);
Bernie Innocenti55864192018-08-30 04:05:20 +0900259}
260
261/* add the hexadecimal dump of some memory area to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900262static char* bprint_hexdump(char* p, char* end, const uint8_t* data, int datalen) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900263 int lineSize = 16;
Bernie Innocenti55864192018-08-30 04:05:20 +0900264
265 while (datalen > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900266 int avail = datalen;
267 int nn;
Bernie Innocenti55864192018-08-30 04:05:20 +0900268
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900269 if (avail > lineSize) avail = lineSize;
Bernie Innocenti55864192018-08-30 04:05:20 +0900270
271 for (nn = 0; nn < avail; nn++) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900272 if (nn > 0) p = bprint_c(p, end, ' ');
273 p = bprint_hex(p, end, data[nn], 2);
Bernie Innocenti55864192018-08-30 04:05:20 +0900274 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900275 for (; nn < lineSize; nn++) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900276 p = bprint_s(p, end, " ");
Bernie Innocenti55864192018-08-30 04:05:20 +0900277 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900278 p = bprint_s(p, end, " ");
Bernie Innocenti55864192018-08-30 04:05:20 +0900279
280 for (nn = 0; nn < avail; nn++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900281 int c = data[nn];
Bernie Innocenti55864192018-08-30 04:05:20 +0900282
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900283 if (c < 32 || c > 127) c = '.';
Bernie Innocenti55864192018-08-30 04:05:20 +0900284
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900285 p = bprint_c(p, end, c);
Bernie Innocenti55864192018-08-30 04:05:20 +0900286 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900287 p = bprint_c(p, end, '\n');
Bernie Innocenti55864192018-08-30 04:05:20 +0900288
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900289 data += avail;
Bernie Innocenti55864192018-08-30 04:05:20 +0900290 datalen -= avail;
291 }
292 return p;
293}
294
295/* dump the content of a query of packet to the log */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900296static void dump_bytes(const uint8_t* base, int len) {
297 if (!kDumpData) return;
Bernie Innocenti55864192018-08-30 04:05:20 +0900298
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900299 char buff[1024];
300 char *p = buff, *end = p + sizeof(buff);
301
302 p = bprint_hexdump(p, end, base, len);
chenbruce16adee42019-02-20 19:45:50 +0800303 LOG(INFO) << buff;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900304}
Bernie Innocenti55864192018-08-30 04:05:20 +0900305
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900306static time_t _time_now(void) {
307 struct timeval tv;
Bernie Innocenti55864192018-08-30 04:05:20 +0900308
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900309 gettimeofday(&tv, NULL);
Bernie Innocenti55864192018-08-30 04:05:20 +0900310 return tv.tv_sec;
311}
312
313/* reminder: the general format of a DNS packet is the following:
314 *
315 * HEADER (12 bytes)
316 * QUESTION (variable)
317 * ANSWER (variable)
318 * AUTHORITY (variable)
319 * ADDITIONNAL (variable)
320 *
321 * the HEADER is made of:
322 *
323 * ID : 16 : 16-bit unique query identification field
324 *
325 * QR : 1 : set to 0 for queries, and 1 for responses
326 * Opcode : 4 : set to 0 for queries
327 * AA : 1 : set to 0 for queries
328 * TC : 1 : truncation flag, will be set to 0 in queries
329 * RD : 1 : recursion desired
330 *
331 * RA : 1 : recursion available (0 in queries)
332 * Z : 3 : three reserved zero bits
333 * RCODE : 4 : response code (always 0=NOERROR in queries)
334 *
335 * QDCount: 16 : question count
336 * ANCount: 16 : Answer count (0 in queries)
337 * NSCount: 16: Authority Record count (0 in queries)
338 * ARCount: 16: Additionnal Record count (0 in queries)
339 *
340 * the QUESTION is made of QDCount Question Record (QRs)
341 * the ANSWER is made of ANCount RRs
342 * the AUTHORITY is made of NSCount RRs
343 * the ADDITIONNAL is made of ARCount RRs
344 *
345 * Each Question Record (QR) is made of:
346 *
347 * QNAME : variable : Query DNS NAME
348 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
349 * CLASS : 16 : class of query (IN=1)
350 *
351 * Each Resource Record (RR) is made of:
352 *
353 * NAME : variable : DNS NAME
354 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
355 * CLASS : 16 : class of query (IN=1)
356 * TTL : 32 : seconds to cache this RR (0=none)
357 * RDLENGTH: 16 : size of RDDATA in bytes
358 * RDDATA : variable : RR data (depends on TYPE)
359 *
360 * Each QNAME contains a domain name encoded as a sequence of 'labels'
361 * terminated by a zero. Each label has the following format:
362 *
363 * LEN : 8 : lenght of label (MUST be < 64)
364 * NAME : 8*LEN : label length (must exclude dots)
365 *
366 * A value of 0 in the encoding is interpreted as the 'root' domain and
367 * terminates the encoding. So 'www.android.com' will be encoded as:
368 *
369 * <3>www<7>android<3>com<0>
370 *
371 * Where <n> represents the byte with value 'n'
372 *
373 * Each NAME reflects the QNAME of the question, but has a slightly more
374 * complex encoding in order to provide message compression. This is achieved
375 * by using a 2-byte pointer, with format:
376 *
377 * TYPE : 2 : 0b11 to indicate a pointer, 0b01 and 0b10 are reserved
378 * OFFSET : 14 : offset to another part of the DNS packet
379 *
380 * The offset is relative to the start of the DNS packet and must point
381 * A pointer terminates the encoding.
382 *
383 * The NAME can be encoded in one of the following formats:
384 *
385 * - a sequence of simple labels terminated by 0 (like QNAMEs)
386 * - a single pointer
387 * - a sequence of simple labels terminated by a pointer
388 *
389 * A pointer shall always point to either a pointer of a sequence of
390 * labels (which can themselves be terminated by either a 0 or a pointer)
391 *
392 * The expanded length of a given domain name should not exceed 255 bytes.
393 *
394 * NOTE: we don't parse the answer packets, so don't need to deal with NAME
395 * records, only QNAMEs.
396 */
397
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900398#define DNS_HEADER_SIZE 12
Bernie Innocenti55864192018-08-30 04:05:20 +0900399
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900400#define DNS_TYPE_A "\00\01" /* big-endian decimal 1 */
401#define DNS_TYPE_PTR "\00\014" /* big-endian decimal 12 */
402#define DNS_TYPE_MX "\00\017" /* big-endian decimal 15 */
403#define DNS_TYPE_AAAA "\00\034" /* big-endian decimal 28 */
404#define DNS_TYPE_ALL "\00\0377" /* big-endian decimal 255 */
Bernie Innocenti55864192018-08-30 04:05:20 +0900405
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900406#define DNS_CLASS_IN "\00\01" /* big-endian decimal 1 */
Bernie Innocenti55864192018-08-30 04:05:20 +0900407
408typedef struct {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900409 const uint8_t* base;
410 const uint8_t* end;
411 const uint8_t* cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900412} DnsPacket;
413
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900414static void _dnsPacket_init(DnsPacket* packet, const uint8_t* buff, int bufflen) {
415 packet->base = buff;
416 packet->end = buff + bufflen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900417 packet->cursor = buff;
418}
419
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900420static void _dnsPacket_rewind(DnsPacket* packet) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900421 packet->cursor = packet->base;
422}
423
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900424static void _dnsPacket_skip(DnsPacket* packet, int count) {
425 const uint8_t* p = packet->cursor + count;
Bernie Innocenti55864192018-08-30 04:05:20 +0900426
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900427 if (p > packet->end) p = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900428
429 packet->cursor = p;
430}
431
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900432static int _dnsPacket_readInt16(DnsPacket* packet) {
433 const uint8_t* p = packet->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900434
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900435 if (p + 2 > packet->end) return -1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900436
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900437 packet->cursor = p + 2;
438 return (p[0] << 8) | p[1];
Bernie Innocenti55864192018-08-30 04:05:20 +0900439}
440
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900441/** QUERY CHECKING **/
Bernie Innocenti55864192018-08-30 04:05:20 +0900442
443/* check bytes in a dns packet. returns 1 on success, 0 on failure.
444 * the cursor is only advanced in the case of success
445 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900446static int _dnsPacket_checkBytes(DnsPacket* packet, int numBytes, const void* bytes) {
447 const uint8_t* p = packet->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900448
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900449 if (p + numBytes > packet->end) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900450
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900451 if (memcmp(p, bytes, numBytes) != 0) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900452
453 packet->cursor = p + numBytes;
454 return 1;
455}
456
457/* parse and skip a given QNAME stored in a query packet,
458 * from the current cursor position. returns 1 on success,
459 * or 0 for malformed data.
460 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900461static int _dnsPacket_checkQName(DnsPacket* packet) {
462 const uint8_t* p = packet->cursor;
463 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900464
465 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900466 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900467
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900468 if (p >= end) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900469
470 c = *p++;
471
472 if (c == 0) {
473 packet->cursor = p;
474 return 1;
475 }
476
477 /* we don't expect label compression in QNAMEs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900478 if (c >= 64) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900479
480 p += c;
481 /* we rely on the bound check at the start
482 * of the loop here */
483 }
484 /* malformed data */
chenbruce16adee42019-02-20 19:45:50 +0800485 LOG(INFO) << "malformed QNAME";
Bernie Innocenti55864192018-08-30 04:05:20 +0900486 return 0;
487}
488
489/* parse and skip a given QR stored in a packet.
490 * returns 1 on success, and 0 on failure
491 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900492static int _dnsPacket_checkQR(DnsPacket* packet) {
493 if (!_dnsPacket_checkQName(packet)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900494
495 /* TYPE must be one of the things we support */
496 if (!_dnsPacket_checkBytes(packet, 2, DNS_TYPE_A) &&
497 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_PTR) &&
498 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_MX) &&
499 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_AAAA) &&
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900500 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_ALL)) {
chenbruce16adee42019-02-20 19:45:50 +0800501 LOG(INFO) << "unsupported TYPE";
Bernie Innocenti55864192018-08-30 04:05:20 +0900502 return 0;
503 }
504 /* CLASS must be IN */
505 if (!_dnsPacket_checkBytes(packet, 2, DNS_CLASS_IN)) {
chenbruce16adee42019-02-20 19:45:50 +0800506 LOG(INFO) << "unsupported CLASS";
Bernie Innocenti55864192018-08-30 04:05:20 +0900507 return 0;
508 }
509
510 return 1;
511}
512
513/* check the header of a DNS Query packet, return 1 if it is one
514 * type of query we can cache, or 0 otherwise
515 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900516static int _dnsPacket_checkQuery(DnsPacket* packet) {
517 const uint8_t* p = packet->base;
518 int qdCount, anCount, dnCount, arCount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900519
520 if (p + DNS_HEADER_SIZE > packet->end) {
chenbruce16adee42019-02-20 19:45:50 +0800521 LOG(INFO) << "query packet too small";
Bernie Innocenti55864192018-08-30 04:05:20 +0900522 return 0;
523 }
524
525 /* QR must be set to 0, opcode must be 0 and AA must be 0 */
526 /* RA, Z, and RCODE must be 0 */
527 if ((p[2] & 0xFC) != 0 || (p[3] & 0xCF) != 0) {
chenbruce16adee42019-02-20 19:45:50 +0800528 LOG(INFO) << "query packet flags unsupported";
Bernie Innocenti55864192018-08-30 04:05:20 +0900529 return 0;
530 }
531
532 /* Note that we ignore the TC, RD, CD, and AD bits here for the
533 * following reasons:
534 *
535 * - there is no point for a query packet sent to a server
536 * to have the TC bit set, but the implementation might
537 * set the bit in the query buffer for its own needs
538 * between a _resolv_cache_lookup and a
539 * _resolv_cache_add. We should not freak out if this
540 * is the case.
541 *
542 * - we consider that the result from a query might depend on
543 * the RD, AD, and CD bits, so these bits
544 * should be used to differentiate cached result.
545 *
546 * this implies that these bits are checked when hashing or
547 * comparing query packets, but not TC
548 */
549
550 /* ANCOUNT, DNCOUNT and ARCOUNT must be 0 */
551 qdCount = (p[4] << 8) | p[5];
552 anCount = (p[6] << 8) | p[7];
553 dnCount = (p[8] << 8) | p[9];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900554 arCount = (p[10] << 8) | p[11];
Bernie Innocenti55864192018-08-30 04:05:20 +0900555
556 if (anCount != 0 || dnCount != 0 || arCount > 1) {
chenbruce16adee42019-02-20 19:45:50 +0800557 LOG(INFO) << "query packet contains non-query records";
Bernie Innocenti55864192018-08-30 04:05:20 +0900558 return 0;
559 }
560
561 if (qdCount == 0) {
chenbruce16adee42019-02-20 19:45:50 +0800562 LOG(INFO) << "query packet doesn't contain query record";
Bernie Innocenti55864192018-08-30 04:05:20 +0900563 return 0;
564 }
565
566 /* Check QDCOUNT QRs */
567 packet->cursor = p + DNS_HEADER_SIZE;
568
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900569 for (; qdCount > 0; qdCount--)
570 if (!_dnsPacket_checkQR(packet)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900571
572 return 1;
573}
574
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900575/** QUERY DEBUGGING **/
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900576static char* dnsPacket_bprintQName(DnsPacket* packet, char* bp, char* bend) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900577 const uint8_t* p = packet->cursor;
578 const uint8_t* end = packet->end;
579 int first = 1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900580
581 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900582 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900583
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900584 if (p >= end) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900585
586 c = *p++;
587
588 if (c == 0) {
589 packet->cursor = p;
590 return bp;
591 }
592
593 /* we don't expect label compression in QNAMEs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900594 if (c >= 64) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900595
596 if (first)
597 first = 0;
598 else
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900599 bp = bprint_c(bp, bend, '.');
Bernie Innocenti55864192018-08-30 04:05:20 +0900600
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900601 bp = bprint_b(bp, bend, (const char*) p, c);
Bernie Innocenti55864192018-08-30 04:05:20 +0900602
603 p += c;
604 /* we rely on the bound check at the start
605 * of the loop here */
606 }
607 /* malformed data */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900608 bp = bprint_s(bp, bend, "<MALFORMED>");
Bernie Innocenti55864192018-08-30 04:05:20 +0900609 return bp;
610}
611
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900612static char* dnsPacket_bprintQR(DnsPacket* packet, char* p, char* end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900613#define QQ(x) \
614 { DNS_TYPE_##x, #x }
Bernie Innocenti55864192018-08-30 04:05:20 +0900615 static const struct {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900616 const char* typeBytes;
617 const char* typeString;
618 } qTypes[] = {QQ(A), QQ(PTR), QQ(MX), QQ(AAAA), QQ(ALL), {NULL, NULL}};
619 int nn;
620 const char* typeString = NULL;
Bernie Innocenti55864192018-08-30 04:05:20 +0900621
622 /* dump QNAME */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900623 p = dnsPacket_bprintQName(packet, p, end);
Bernie Innocenti55864192018-08-30 04:05:20 +0900624
625 /* dump TYPE */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900626 p = bprint_s(p, end, " (");
Bernie Innocenti55864192018-08-30 04:05:20 +0900627
628 for (nn = 0; qTypes[nn].typeBytes != NULL; nn++) {
629 if (_dnsPacket_checkBytes(packet, 2, qTypes[nn].typeBytes)) {
630 typeString = qTypes[nn].typeString;
631 break;
632 }
633 }
634
635 if (typeString != NULL)
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900636 p = bprint_s(p, end, typeString);
Bernie Innocenti55864192018-08-30 04:05:20 +0900637 else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900638 int typeCode = _dnsPacket_readInt16(packet);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900639 p = bprint(p, end, "UNKNOWN-%d", typeCode);
Bernie Innocenti55864192018-08-30 04:05:20 +0900640 }
641
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900642 p = bprint_c(p, end, ')');
Bernie Innocenti55864192018-08-30 04:05:20 +0900643
644 /* skip CLASS */
645 _dnsPacket_skip(packet, 2);
646 return p;
647}
648
649/* this function assumes the packet has already been checked */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900650static char* dnsPacket_bprintQuery(DnsPacket* packet, char* p, char* end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900651 int qdCount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900652
653 if (packet->base[2] & 0x1) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900654 p = bprint_s(p, end, "RECURSIVE ");
Bernie Innocenti55864192018-08-30 04:05:20 +0900655 }
656
657 _dnsPacket_skip(packet, 4);
658 qdCount = _dnsPacket_readInt16(packet);
659 _dnsPacket_skip(packet, 6);
660
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900661 for (; qdCount > 0; qdCount--) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900662 p = dnsPacket_bprintQR(packet, p, end);
Bernie Innocenti55864192018-08-30 04:05:20 +0900663 }
664 return p;
665}
Bernie Innocenti55864192018-08-30 04:05:20 +0900666
Bernie Innocenti55864192018-08-30 04:05:20 +0900667/** QUERY HASHING SUPPORT
668 **
669 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKET HAS ALREADY
670 ** BEEN SUCCESFULLY CHECKED.
671 **/
672
673/* use 32-bit FNV hash function */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900674#define FNV_MULT 16777619U
675#define FNV_BASIS 2166136261U
Bernie Innocenti55864192018-08-30 04:05:20 +0900676
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900677static unsigned _dnsPacket_hashBytes(DnsPacket* packet, int numBytes, unsigned hash) {
678 const uint8_t* p = packet->cursor;
679 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900680
681 while (numBytes > 0 && p < end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900682 hash = hash * FNV_MULT ^ *p++;
Bernie Innocenti55864192018-08-30 04:05:20 +0900683 }
684 packet->cursor = p;
685 return hash;
686}
687
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900688static unsigned _dnsPacket_hashQName(DnsPacket* packet, unsigned hash) {
689 const uint8_t* p = packet->cursor;
690 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900691
692 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900693 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900694
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900695 if (p >= end) { /* should not happen */
chenbruce16adee42019-02-20 19:45:50 +0800696 LOG(INFO) << __func__ << ": INTERNAL_ERROR: read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900697 break;
698 }
699
700 c = *p++;
701
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900702 if (c == 0) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900703
704 if (c >= 64) {
chenbruce16adee42019-02-20 19:45:50 +0800705 LOG(INFO) << __func__ << ": INTERNAL_ERROR: malformed domain";
Bernie Innocenti55864192018-08-30 04:05:20 +0900706 break;
707 }
708 if (p + c >= end) {
chenbruce16adee42019-02-20 19:45:50 +0800709 LOG(INFO) << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900710 break;
711 }
712 while (c > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900713 hash = hash * FNV_MULT ^ *p++;
714 c -= 1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900715 }
716 }
717 packet->cursor = p;
718 return hash;
719}
720
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900721static unsigned _dnsPacket_hashQR(DnsPacket* packet, unsigned hash) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900722 hash = _dnsPacket_hashQName(packet, hash);
723 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TYPE and CLASS */
724 return hash;
725}
726
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900727static unsigned _dnsPacket_hashRR(DnsPacket* packet, unsigned hash) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900728 int rdlength;
729 hash = _dnsPacket_hashQR(packet, hash);
730 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TTL */
731 rdlength = _dnsPacket_readInt16(packet);
732 hash = _dnsPacket_hashBytes(packet, rdlength, hash); /* RDATA */
733 return hash;
734}
735
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900736static unsigned _dnsPacket_hashQuery(DnsPacket* packet) {
737 unsigned hash = FNV_BASIS;
738 int count, arcount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900739 _dnsPacket_rewind(packet);
740
741 /* ignore the ID */
742 _dnsPacket_skip(packet, 2);
743
744 /* we ignore the TC bit for reasons explained in
745 * _dnsPacket_checkQuery().
746 *
747 * however we hash the RD bit to differentiate
748 * between answers for recursive and non-recursive
749 * queries.
750 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900751 hash = hash * FNV_MULT ^ (packet->base[2] & 1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900752
753 /* mark the first header byte as processed */
754 _dnsPacket_skip(packet, 1);
755
756 /* process the second header byte */
757 hash = _dnsPacket_hashBytes(packet, 1, hash);
758
759 /* read QDCOUNT */
760 count = _dnsPacket_readInt16(packet);
761
762 /* assume: ANcount and NScount are 0 */
763 _dnsPacket_skip(packet, 4);
764
765 /* read ARCOUNT */
766 arcount = _dnsPacket_readInt16(packet);
767
768 /* hash QDCOUNT QRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900769 for (; count > 0; count--) hash = _dnsPacket_hashQR(packet, hash);
Bernie Innocenti55864192018-08-30 04:05:20 +0900770
771 /* hash ARCOUNT RRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900772 for (; arcount > 0; arcount--) hash = _dnsPacket_hashRR(packet, hash);
Bernie Innocenti55864192018-08-30 04:05:20 +0900773
774 return hash;
775}
776
Bernie Innocenti55864192018-08-30 04:05:20 +0900777/** QUERY COMPARISON
778 **
779 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKETS HAVE ALREADY
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900780 ** BEEN SUCCESSFULLY CHECKED.
Bernie Innocenti55864192018-08-30 04:05:20 +0900781 **/
782
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900783static int _dnsPacket_isEqualDomainName(DnsPacket* pack1, DnsPacket* pack2) {
784 const uint8_t* p1 = pack1->cursor;
785 const uint8_t* end1 = pack1->end;
786 const uint8_t* p2 = pack2->cursor;
787 const uint8_t* end2 = pack2->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900788
789 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900790 int c1, c2;
Bernie Innocenti55864192018-08-30 04:05:20 +0900791
792 if (p1 >= end1 || p2 >= end2) {
chenbruce16adee42019-02-20 19:45:50 +0800793 LOG(INFO) << __func__ << ": INTERNAL_ERROR: read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900794 break;
795 }
796 c1 = *p1++;
797 c2 = *p2++;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900798 if (c1 != c2) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900799
800 if (c1 == 0) {
801 pack1->cursor = p1;
802 pack2->cursor = p2;
803 return 1;
804 }
805 if (c1 >= 64) {
chenbruce16adee42019-02-20 19:45:50 +0800806 LOG(INFO) << __func__ << ": INTERNAL_ERROR: malformed domain";
Bernie Innocenti55864192018-08-30 04:05:20 +0900807 break;
808 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900809 if ((p1 + c1 > end1) || (p2 + c1 > end2)) {
chenbruce16adee42019-02-20 19:45:50 +0800810 LOG(INFO) << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900811 break;
812 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900813 if (memcmp(p1, p2, c1) != 0) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900814 p1 += c1;
815 p2 += c1;
816 /* we rely on the bound checks at the start of the loop */
817 }
818 /* not the same, or one is malformed */
chenbruce16adee42019-02-20 19:45:50 +0800819 LOG(INFO) << "different DN";
Bernie Innocenti55864192018-08-30 04:05:20 +0900820 return 0;
821}
822
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900823static int _dnsPacket_isEqualBytes(DnsPacket* pack1, DnsPacket* pack2, int numBytes) {
824 const uint8_t* p1 = pack1->cursor;
825 const uint8_t* p2 = pack2->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900826
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900827 if (p1 + numBytes > pack1->end || p2 + numBytes > pack2->end) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900828
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900829 if (memcmp(p1, p2, numBytes) != 0) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900830
831 pack1->cursor += numBytes;
832 pack2->cursor += numBytes;
833 return 1;
834}
835
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900836static int _dnsPacket_isEqualQR(DnsPacket* pack1, DnsPacket* pack2) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900837 /* compare domain name encoding + TYPE + CLASS */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900838 if (!_dnsPacket_isEqualDomainName(pack1, pack2) ||
839 !_dnsPacket_isEqualBytes(pack1, pack2, 2 + 2))
Bernie Innocenti55864192018-08-30 04:05:20 +0900840 return 0;
841
842 return 1;
843}
844
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900845static int _dnsPacket_isEqualRR(DnsPacket* pack1, DnsPacket* pack2) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900846 int rdlength1, rdlength2;
847 /* compare query + TTL */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900848 if (!_dnsPacket_isEqualQR(pack1, pack2) || !_dnsPacket_isEqualBytes(pack1, pack2, 4)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900849
850 /* compare RDATA */
851 rdlength1 = _dnsPacket_readInt16(pack1);
852 rdlength2 = _dnsPacket_readInt16(pack2);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900853 if (rdlength1 != rdlength2 || !_dnsPacket_isEqualBytes(pack1, pack2, rdlength1)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900854
855 return 1;
856}
857
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900858static int _dnsPacket_isEqualQuery(DnsPacket* pack1, DnsPacket* pack2) {
859 int count1, count2, arcount1, arcount2;
Bernie Innocenti55864192018-08-30 04:05:20 +0900860
861 /* compare the headers, ignore most fields */
862 _dnsPacket_rewind(pack1);
863 _dnsPacket_rewind(pack2);
864
865 /* compare RD, ignore TC, see comment in _dnsPacket_checkQuery */
866 if ((pack1->base[2] & 1) != (pack2->base[2] & 1)) {
chenbruce16adee42019-02-20 19:45:50 +0800867 LOG(INFO) << "different RD";
Bernie Innocenti55864192018-08-30 04:05:20 +0900868 return 0;
869 }
870
871 if (pack1->base[3] != pack2->base[3]) {
chenbruce16adee42019-02-20 19:45:50 +0800872 LOG(INFO) << "different CD or AD";
Bernie Innocenti55864192018-08-30 04:05:20 +0900873 return 0;
874 }
875
876 /* mark ID and header bytes as compared */
877 _dnsPacket_skip(pack1, 4);
878 _dnsPacket_skip(pack2, 4);
879
880 /* compare QDCOUNT */
881 count1 = _dnsPacket_readInt16(pack1);
882 count2 = _dnsPacket_readInt16(pack2);
883 if (count1 != count2 || count1 < 0) {
chenbruce16adee42019-02-20 19:45:50 +0800884 LOG(INFO) << "different QDCOUNT";
Bernie Innocenti55864192018-08-30 04:05:20 +0900885 return 0;
886 }
887
888 /* assume: ANcount and NScount are 0 */
889 _dnsPacket_skip(pack1, 4);
890 _dnsPacket_skip(pack2, 4);
891
892 /* compare ARCOUNT */
893 arcount1 = _dnsPacket_readInt16(pack1);
894 arcount2 = _dnsPacket_readInt16(pack2);
895 if (arcount1 != arcount2 || arcount1 < 0) {
chenbruce16adee42019-02-20 19:45:50 +0800896 LOG(INFO) << "different ARCOUNT";
Bernie Innocenti55864192018-08-30 04:05:20 +0900897 return 0;
898 }
899
900 /* compare the QDCOUNT QRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900901 for (; count1 > 0; count1--) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900902 if (!_dnsPacket_isEqualQR(pack1, pack2)) {
chenbruce16adee42019-02-20 19:45:50 +0800903 LOG(INFO) << "different QR";
Bernie Innocenti55864192018-08-30 04:05:20 +0900904 return 0;
905 }
906 }
907
908 /* compare the ARCOUNT RRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900909 for (; arcount1 > 0; arcount1--) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900910 if (!_dnsPacket_isEqualRR(pack1, pack2)) {
chenbruce16adee42019-02-20 19:45:50 +0800911 LOG(INFO) << "different additional RR";
Bernie Innocenti55864192018-08-30 04:05:20 +0900912 return 0;
913 }
914 }
915 return 1;
916}
917
Bernie Innocenti55864192018-08-30 04:05:20 +0900918/* cache entry. for simplicity, 'hash' and 'hlink' are inlined in this
919 * structure though they are conceptually part of the hash table.
920 *
921 * similarly, mru_next and mru_prev are part of the global MRU list
922 */
923typedef struct Entry {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900924 unsigned int hash; /* hash value */
925 struct Entry* hlink; /* next in collision chain */
926 struct Entry* mru_prev;
927 struct Entry* mru_next;
Bernie Innocenti55864192018-08-30 04:05:20 +0900928
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900929 const uint8_t* query;
930 int querylen;
931 const uint8_t* answer;
932 int answerlen;
933 time_t expires; /* time_t when the entry isn't valid any more */
934 int id; /* for debugging purpose */
Bernie Innocenti55864192018-08-30 04:05:20 +0900935} Entry;
936
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900937/*
Bernie Innocenti55864192018-08-30 04:05:20 +0900938 * Find the TTL for a negative DNS result. This is defined as the minimum
939 * of the SOA records TTL and the MINIMUM-TTL field (RFC-2308).
940 *
941 * Return 0 if not found.
942 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900943static u_long answer_getNegativeTTL(ns_msg handle) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900944 int n, nscount;
945 u_long result = 0;
946 ns_rr rr;
947
948 nscount = ns_msg_count(handle, ns_s_ns);
949 for (n = 0; n < nscount; n++) {
950 if ((ns_parserr(&handle, ns_s_ns, n, &rr) == 0) && (ns_rr_type(rr) == ns_t_soa)) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900951 const u_char* rdata = ns_rr_rdata(rr); // find the data
952 const u_char* edata = rdata + ns_rr_rdlen(rr); // add the len to find the end
Bernie Innocenti55864192018-08-30 04:05:20 +0900953 int len;
954 u_long ttl, rec_result = ns_rr_ttl(rr);
955
956 // find the MINIMUM-TTL field from the blob of binary data for this record
957 // skip the server name
958 len = dn_skipname(rdata, edata);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900959 if (len == -1) continue; // error skipping
Bernie Innocenti55864192018-08-30 04:05:20 +0900960 rdata += len;
961
962 // skip the admin name
963 len = dn_skipname(rdata, edata);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900964 if (len == -1) continue; // error skipping
Bernie Innocenti55864192018-08-30 04:05:20 +0900965 rdata += len;
966
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900967 if (edata - rdata != 5 * NS_INT32SZ) continue;
Bernie Innocenti55864192018-08-30 04:05:20 +0900968 // skip: serial number + refresh interval + retry interval + expiry
969 rdata += NS_INT32SZ * 4;
970 // finally read the MINIMUM TTL
971 ttl = ns_get32(rdata);
972 if (ttl < rec_result) {
973 rec_result = ttl;
974 }
975 // Now that the record is read successfully, apply the new min TTL
976 if (n == 0 || rec_result < result) {
977 result = rec_result;
978 }
979 }
980 }
981 return result;
982}
983
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900984/*
Bernie Innocenti55864192018-08-30 04:05:20 +0900985 * Parse the answer records and find the appropriate
986 * smallest TTL among the records. This might be from
987 * the answer records if found or from the SOA record
988 * if it's a negative result.
989 *
990 * The returned TTL is the number of seconds to
991 * keep the answer in the cache.
992 *
993 * In case of parse error zero (0) is returned which
994 * indicates that the answer shall not be cached.
995 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900996static u_long answer_getTTL(const void* answer, int answerlen) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900997 ns_msg handle;
998 int ancount, n;
999 u_long result, ttl;
1000 ns_rr rr;
1001
1002 result = 0;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001003 if (ns_initparse((const uint8_t*) answer, answerlen, &handle) >= 0) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001004 // get number of answer records
1005 ancount = ns_msg_count(handle, ns_s_an);
1006
1007 if (ancount == 0) {
1008 // a response with no answers? Cache this negative result.
1009 result = answer_getNegativeTTL(handle);
1010 } else {
1011 for (n = 0; n < ancount; n++) {
1012 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
1013 ttl = ns_rr_ttl(rr);
1014 if (n == 0 || ttl < result) {
1015 result = ttl;
1016 }
1017 } else {
chenbruce16adee42019-02-20 19:45:50 +08001018 LOG(INFO) << "ns_parserr failed ancount no = " << n
1019 << ". errno = " << strerror(errno);
Bernie Innocenti55864192018-08-30 04:05:20 +09001020 }
1021 }
1022 }
1023 } else {
chenbruce16adee42019-02-20 19:45:50 +08001024 LOG(INFO) << "ns_initparse failed: " << strerror(errno);
Bernie Innocenti55864192018-08-30 04:05:20 +09001025 }
1026
chenbruce16adee42019-02-20 19:45:50 +08001027 LOG(INFO) << "TTL = " << result;
Bernie Innocenti55864192018-08-30 04:05:20 +09001028 return result;
1029}
1030
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001031static void entry_free(Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001032 /* everything is allocated in a single memory block */
1033 if (e) {
1034 free(e);
1035 }
1036}
1037
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001038static void entry_mru_remove(Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001039 e->mru_prev->mru_next = e->mru_next;
1040 e->mru_next->mru_prev = e->mru_prev;
1041}
1042
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001043static void entry_mru_add(Entry* e, Entry* list) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001044 Entry* first = list->mru_next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001045
1046 e->mru_next = first;
1047 e->mru_prev = list;
1048
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001049 list->mru_next = e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001050 first->mru_prev = e;
1051}
1052
1053/* compute the hash of a given entry, this is a hash of most
1054 * data in the query (key) */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001055static unsigned entry_hash(const Entry* e) {
1056 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001057
1058 _dnsPacket_init(pack, e->query, e->querylen);
1059 return _dnsPacket_hashQuery(pack);
1060}
1061
1062/* initialize an Entry as a search key, this also checks the input query packet
1063 * returns 1 on success, or 0 in case of unsupported/malformed data */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001064static int entry_init_key(Entry* e, const void* query, int querylen) {
1065 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001066
1067 memset(e, 0, sizeof(*e));
1068
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001069 e->query = (const uint8_t*) query;
Bernie Innocenti55864192018-08-30 04:05:20 +09001070 e->querylen = querylen;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001071 e->hash = entry_hash(e);
Bernie Innocenti55864192018-08-30 04:05:20 +09001072
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001073 _dnsPacket_init(pack, e->query, e->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001074
1075 return _dnsPacket_checkQuery(pack);
1076}
1077
1078/* allocate a new entry as a cache node */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001079static Entry* entry_alloc(const Entry* init, const void* answer, int answerlen) {
1080 Entry* e;
1081 int size;
Bernie Innocenti55864192018-08-30 04:05:20 +09001082
1083 size = sizeof(*e) + init->querylen + answerlen;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001084 e = (Entry*) calloc(size, 1);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001085 if (e == NULL) return e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001086
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001087 e->hash = init->hash;
1088 e->query = (const uint8_t*) (e + 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001089 e->querylen = init->querylen;
1090
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001091 memcpy((char*) e->query, init->query, e->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001092
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001093 e->answer = e->query + e->querylen;
Bernie Innocenti55864192018-08-30 04:05:20 +09001094 e->answerlen = answerlen;
1095
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001096 memcpy((char*) e->answer, answer, e->answerlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001097
1098 return e;
1099}
1100
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001101static int entry_equals(const Entry* e1, const Entry* e2) {
1102 DnsPacket pack1[1], pack2[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001103
1104 if (e1->querylen != e2->querylen) {
1105 return 0;
1106 }
1107 _dnsPacket_init(pack1, e1->query, e1->querylen);
1108 _dnsPacket_init(pack2, e2->query, e2->querylen);
1109
1110 return _dnsPacket_isEqualQuery(pack1, pack2);
1111}
1112
Bernie Innocenti55864192018-08-30 04:05:20 +09001113/* We use a simple hash table with external collision lists
1114 * for simplicity, the hash-table fields 'hash' and 'hlink' are
1115 * inlined in the Entry structure.
1116 */
1117
1118/* Maximum time for a thread to wait for an pending request */
Ken Chen2a429352018-12-22 21:46:55 +08001119constexpr int PENDING_REQUEST_TIMEOUT = 20;
Bernie Innocenti55864192018-08-30 04:05:20 +09001120
1121typedef struct resolv_cache {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001122 int max_entries;
1123 int num_entries;
1124 Entry mru_list;
1125 int last_id;
1126 Entry* entries;
Ken Chen2a429352018-12-22 21:46:55 +08001127 struct pending_req_info {
1128 unsigned int hash;
1129 struct pending_req_info* next;
1130 } pending_requests;
Bernie Innocenti55864192018-08-30 04:05:20 +09001131} Cache;
1132
1133struct resolv_cache_info {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001134 unsigned netid;
1135 Cache* cache;
1136 struct resolv_cache_info* next;
1137 int nscount;
1138 char* nameservers[MAXNS];
1139 struct addrinfo* nsaddrinfo[MAXNS];
1140 int revision_id; // # times the nameservers have been replaced
Bernie Innocenti34de3ba2019-02-19 18:08:36 +09001141 res_params params;
Bernie Innocenti189eb502018-10-01 23:10:18 +09001142 struct res_stats nsstats[MAXNS];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001143 char defdname[MAXDNSRCHPATH];
1144 int dnsrch_offset[MAXDNSRCH + 1]; // offsets into defdname
Ken Chen2a429352018-12-22 21:46:55 +08001145 int wait_for_pending_req_timeout_count;
Bernie Innocenti55864192018-08-30 04:05:20 +09001146};
1147
Ken Chen2a429352018-12-22 21:46:55 +08001148// A helper class for the Clang Thread Safety Analysis to deal with
1149// std::unique_lock.
1150class SCOPED_CAPABILITY ScopedAssumeLocked {
1151 public:
1152 ScopedAssumeLocked(std::mutex& mutex) ACQUIRE(mutex) {}
1153 ~ScopedAssumeLocked() RELEASE() {}
1154};
Bernie Innocenti55864192018-08-30 04:05:20 +09001155
Ken Chen2a429352018-12-22 21:46:55 +08001156// lock protecting everything in the resolve_cache_info structs (next ptr, etc)
1157static std::mutex cache_mutex;
1158static std::condition_variable cv;
Bernie Innocenti55864192018-08-30 04:05:20 +09001159
1160/* gets cache associated with a network, or NULL if none exists */
Ken Chen2a429352018-12-22 21:46:55 +08001161static struct resolv_cache* find_named_cache_locked(unsigned netid) REQUIRES(cache_mutex);
1162static resolv_cache* get_res_cache_for_net_locked(unsigned netid) REQUIRES(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001163
Ken Chen2a429352018-12-22 21:46:55 +08001164static void cache_flush_pending_requests_locked(struct resolv_cache* cache) {
1165 resolv_cache::pending_req_info *ri, *tmp;
1166 if (!cache) return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001167
Ken Chen2a429352018-12-22 21:46:55 +08001168 ri = cache->pending_requests.next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001169
Ken Chen2a429352018-12-22 21:46:55 +08001170 while (ri) {
1171 tmp = ri;
1172 ri = ri->next;
1173 free(tmp);
Bernie Innocenti55864192018-08-30 04:05:20 +09001174 }
1175
Ken Chen2a429352018-12-22 21:46:55 +08001176 cache->pending_requests.next = NULL;
1177 cv.notify_all();
Bernie Innocenti55864192018-08-30 04:05:20 +09001178}
1179
Ken Chen2a429352018-12-22 21:46:55 +08001180// Return true - if there is a pending request in |cache| matching |key|.
1181// Return false - if no pending request is found matching the key. Optionally
1182// link a new one if parameter append_if_not_found is true.
1183static bool cache_has_pending_request_locked(resolv_cache* cache, const Entry* key,
1184 bool append_if_not_found) {
1185 if (!cache || !key) return false;
Bernie Innocenti55864192018-08-30 04:05:20 +09001186
Ken Chen2a429352018-12-22 21:46:55 +08001187 resolv_cache::pending_req_info* ri = cache->pending_requests.next;
1188 resolv_cache::pending_req_info* prev = &cache->pending_requests;
1189 while (ri) {
1190 if (ri->hash == key->hash) {
1191 return true;
Bernie Innocenti55864192018-08-30 04:05:20 +09001192 }
Ken Chen2a429352018-12-22 21:46:55 +08001193 prev = ri;
1194 ri = ri->next;
1195 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001196
Ken Chen2a429352018-12-22 21:46:55 +08001197 if (append_if_not_found) {
1198 ri = (resolv_cache::pending_req_info*)calloc(1, sizeof(resolv_cache::pending_req_info));
Bernie Innocenti55864192018-08-30 04:05:20 +09001199 if (ri) {
Ken Chen2a429352018-12-22 21:46:55 +08001200 ri->hash = key->hash;
1201 prev->next = ri;
Bernie Innocenti55864192018-08-30 04:05:20 +09001202 }
1203 }
Ken Chen2a429352018-12-22 21:46:55 +08001204 return false;
1205}
1206
1207// Notify all threads that the cache entry |key| has become available
1208static void _cache_notify_waiting_tid_locked(struct resolv_cache* cache, const Entry* key) {
1209 if (!cache || !key) return;
1210
1211 resolv_cache::pending_req_info* ri = cache->pending_requests.next;
1212 resolv_cache::pending_req_info* prev = &cache->pending_requests;
1213 while (ri) {
1214 if (ri->hash == key->hash) {
1215 // remove item from list and destroy
1216 prev->next = ri->next;
1217 free(ri);
1218 cv.notify_all();
1219 return;
1220 }
1221 prev = ri;
1222 ri = ri->next;
1223 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001224}
1225
Luke Huang952d0942018-12-26 16:53:03 +08001226void _resolv_cache_query_failed(unsigned netid, const void* query, int querylen, uint32_t flags) {
1227 // We should not notify with these flags.
1228 if (flags & (ANDROID_RESOLV_NO_CACHE_STORE | ANDROID_RESOLV_NO_CACHE_LOOKUP)) {
1229 return;
1230 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001231 Entry key[1];
1232 Cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001233
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001234 if (!entry_init_key(key, query, querylen)) return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001235
Ken Chen2a429352018-12-22 21:46:55 +08001236 std::lock_guard guard(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001237
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001238 cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001239
1240 if (cache) {
1241 _cache_notify_waiting_tid_locked(cache, key);
1242 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001243}
1244
Bernie Innocentid2b27032018-12-18 19:53:42 +09001245static void cache_flush_locked(Cache* cache) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001246 int nn;
Bernie Innocenti55864192018-08-30 04:05:20 +09001247
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001248 for (nn = 0; nn < cache->max_entries; nn++) {
1249 Entry** pnode = (Entry**) &cache->entries[nn];
Bernie Innocenti55864192018-08-30 04:05:20 +09001250
1251 while (*pnode != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001252 Entry* node = *pnode;
Bernie Innocenti55864192018-08-30 04:05:20 +09001253 *pnode = node->hlink;
1254 entry_free(node);
1255 }
1256 }
1257
1258 // flush pending request
Ken Chen2a429352018-12-22 21:46:55 +08001259 cache_flush_pending_requests_locked(cache);
Bernie Innocenti55864192018-08-30 04:05:20 +09001260
1261 cache->mru_list.mru_next = cache->mru_list.mru_prev = &cache->mru_list;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001262 cache->num_entries = 0;
1263 cache->last_id = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +09001264
chenbruce16adee42019-02-20 19:45:50 +08001265 LOG(INFO) << "*** DNS CACHE FLUSHED ***";
Bernie Innocenti55864192018-08-30 04:05:20 +09001266}
1267
Ken Chen2a429352018-12-22 21:46:55 +08001268static resolv_cache* resolv_cache_create() {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001269 struct resolv_cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001270
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001271 cache = (struct resolv_cache*) calloc(sizeof(*cache), 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001272 if (cache) {
nuccachen989d2232018-11-29 17:41:12 +08001273 cache->max_entries = CONFIG_MAX_ENTRIES;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001274 cache->entries = (Entry*) calloc(sizeof(*cache->entries), cache->max_entries);
Bernie Innocenti55864192018-08-30 04:05:20 +09001275 if (cache->entries) {
1276 cache->mru_list.mru_prev = cache->mru_list.mru_next = &cache->mru_list;
chenbruce16adee42019-02-20 19:45:50 +08001277 LOG(INFO) << __func__ << ": cache created";
Bernie Innocenti55864192018-08-30 04:05:20 +09001278 } else {
1279 free(cache);
1280 cache = NULL;
1281 }
1282 }
1283 return cache;
1284}
1285
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001286static void dump_query(const uint8_t* query, int querylen) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001287 char temp[256], *p = temp, *end = p + sizeof(temp);
1288 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001289
1290 _dnsPacket_init(pack, query, querylen);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001291 p = dnsPacket_bprintQuery(pack, p, end);
chenbruce16adee42019-02-20 19:45:50 +08001292 LOG(INFO) << temp;
Bernie Innocenti55864192018-08-30 04:05:20 +09001293}
1294
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001295static void cache_dump_mru(Cache* cache) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001296 char temp[512], *p = temp, *end = p + sizeof(temp);
1297 Entry* e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001298
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001299 p = bprint(temp, end, "MRU LIST (%2d): ", cache->num_entries);
Bernie Innocenti55864192018-08-30 04:05:20 +09001300 for (e = cache->mru_list.mru_next; e != &cache->mru_list; e = e->mru_next)
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001301 p = bprint(p, end, " %d", e->id);
Bernie Innocenti55864192018-08-30 04:05:20 +09001302
chenbruce16adee42019-02-20 19:45:50 +08001303 LOG(INFO) << temp;
Bernie Innocenti55864192018-08-30 04:05:20 +09001304}
1305
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001306// TODO: Rewrite to avoid creating a file in /data as temporary buffer (WAT).
1307static void dump_answer(const u_char* answer, int answerlen) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001308 res_state statep;
Bernie Innocenti55864192018-08-30 04:05:20 +09001309
chenbruce16adee42019-02-20 19:45:50 +08001310 statep = res_get_state();
1311 res_pquery(statep, answer, answerlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001312}
Bernie Innocenti55864192018-08-30 04:05:20 +09001313
1314/* This function tries to find a key within the hash table
1315 * In case of success, it will return a *pointer* to the hashed key.
1316 * In case of failure, it will return a *pointer* to NULL
1317 *
1318 * So, the caller must check '*result' to check for success/failure.
1319 *
1320 * The main idea is that the result can later be used directly in
1321 * calls to _resolv_cache_add or _resolv_cache_remove as the 'lookup'
1322 * parameter. This makes the code simpler and avoids re-searching
1323 * for the key position in the htable.
1324 *
1325 * The result of a lookup_p is only valid until you alter the hash
1326 * table.
1327 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001328static Entry** _cache_lookup_p(Cache* cache, Entry* key) {
1329 int index = key->hash % cache->max_entries;
1330 Entry** pnode = (Entry**) &cache->entries[index];
Bernie Innocenti55864192018-08-30 04:05:20 +09001331
1332 while (*pnode != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001333 Entry* node = *pnode;
Bernie Innocenti55864192018-08-30 04:05:20 +09001334
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001335 if (node == NULL) break;
Bernie Innocenti55864192018-08-30 04:05:20 +09001336
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001337 if (node->hash == key->hash && entry_equals(node, key)) break;
Bernie Innocenti55864192018-08-30 04:05:20 +09001338
1339 pnode = &node->hlink;
1340 }
1341 return pnode;
1342}
1343
1344/* Add a new entry to the hash table. 'lookup' must be the
1345 * result of an immediate previous failed _lookup_p() call
1346 * (i.e. with *lookup == NULL), and 'e' is the pointer to the
1347 * newly created entry
1348 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001349static void _cache_add_p(Cache* cache, Entry** lookup, Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001350 *lookup = e;
1351 e->id = ++cache->last_id;
1352 entry_mru_add(e, &cache->mru_list);
1353 cache->num_entries += 1;
1354
chenbruce16adee42019-02-20 19:45:50 +08001355 LOG(INFO) << __func__ << ": entry " << e->id << " added (count=" << cache->num_entries << ")";
Bernie Innocenti55864192018-08-30 04:05:20 +09001356}
1357
1358/* Remove an existing entry from the hash table,
1359 * 'lookup' must be the result of an immediate previous
1360 * and succesful _lookup_p() call.
1361 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001362static void _cache_remove_p(Cache* cache, Entry** lookup) {
1363 Entry* e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001364
chenbruce16adee42019-02-20 19:45:50 +08001365 LOG(INFO) << __func__ << ": entry " << e->id << " removed (count=" << cache->num_entries - 1
1366 << ")";
Bernie Innocenti55864192018-08-30 04:05:20 +09001367
1368 entry_mru_remove(e);
1369 *lookup = e->hlink;
1370 entry_free(e);
1371 cache->num_entries -= 1;
1372}
1373
1374/* Remove the oldest entry from the hash table.
1375 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001376static void _cache_remove_oldest(Cache* cache) {
1377 Entry* oldest = cache->mru_list.mru_prev;
1378 Entry** lookup = _cache_lookup_p(cache, oldest);
Bernie Innocenti55864192018-08-30 04:05:20 +09001379
1380 if (*lookup == NULL) { /* should not happen */
chenbruce16adee42019-02-20 19:45:50 +08001381 LOG(INFO) << __func__ << ": OLDEST NOT IN HTABLE ?";
Bernie Innocenti55864192018-08-30 04:05:20 +09001382 return;
1383 }
chenbruce16adee42019-02-20 19:45:50 +08001384 LOG(INFO) << "Cache full - removing oldest";
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001385 dump_query(oldest->query, oldest->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001386 _cache_remove_p(cache, lookup);
1387}
1388
1389/* Remove all expired entries from the hash table.
1390 */
1391static void _cache_remove_expired(Cache* cache) {
1392 Entry* e;
1393 time_t now = _time_now();
1394
1395 for (e = cache->mru_list.mru_next; e != &cache->mru_list;) {
1396 // Entry is old, remove
1397 if (now >= e->expires) {
1398 Entry** lookup = _cache_lookup_p(cache, e);
1399 if (*lookup == NULL) { /* should not happen */
chenbruce16adee42019-02-20 19:45:50 +08001400 LOG(INFO) << __func__ << ": ENTRY NOT IN HTABLE ?";
Bernie Innocenti55864192018-08-30 04:05:20 +09001401 return;
1402 }
1403 e = e->mru_next;
1404 _cache_remove_p(cache, lookup);
1405 } else {
1406 e = e->mru_next;
1407 }
1408 }
1409}
1410
Ken Chen2a429352018-12-22 21:46:55 +08001411// gets a resolv_cache_info associated with a network, or NULL if not found
1412static resolv_cache_info* find_cache_info_locked(unsigned netid) REQUIRES(cache_mutex);
1413
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001414ResolvCacheStatus _resolv_cache_lookup(unsigned netid, const void* query, int querylen,
Luke Huang952d0942018-12-26 16:53:03 +08001415 void* answer, int answersize, int* answerlen,
1416 uint32_t flags) {
1417 if (flags & ANDROID_RESOLV_NO_CACHE_LOOKUP) {
1418 return RESOLV_CACHE_SKIP;
1419 }
Ken Chen2a429352018-12-22 21:46:55 +08001420 Entry key;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001421 Entry** lookup;
1422 Entry* e;
1423 time_t now;
1424 Cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001425
chenbruce16adee42019-02-20 19:45:50 +08001426 LOG(INFO) << __func__ << ": lookup";
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001427 dump_query((u_char*) query, querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001428
1429 /* we don't cache malformed queries */
Ken Chen2a429352018-12-22 21:46:55 +08001430 if (!entry_init_key(&key, query, querylen)) {
chenbruce16adee42019-02-20 19:45:50 +08001431 LOG(INFO) << __func__ << ": unsupported query";
Bernie Innocenti55864192018-08-30 04:05:20 +09001432 return RESOLV_CACHE_UNSUPPORTED;
1433 }
1434 /* lookup cache */
Ken Chen2a429352018-12-22 21:46:55 +08001435 std::unique_lock lock(cache_mutex);
1436 ScopedAssumeLocked assume_lock(cache_mutex);
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001437 cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001438 if (cache == NULL) {
Ken Chen2a429352018-12-22 21:46:55 +08001439 return RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti55864192018-08-30 04:05:20 +09001440 }
1441
1442 /* see the description of _lookup_p to understand this.
1443 * the function always return a non-NULL pointer.
1444 */
Ken Chen2a429352018-12-22 21:46:55 +08001445 lookup = _cache_lookup_p(cache, &key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001446 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001447
1448 if (e == NULL) {
chenbruce16adee42019-02-20 19:45:50 +08001449 LOG(INFO) << "NOT IN CACHE";
Luke Huang952d0942018-12-26 16:53:03 +08001450 // If it is no-cache-store mode, we won't wait for possible query.
1451 if (flags & ANDROID_RESOLV_NO_CACHE_STORE) {
Ken Chen2a429352018-12-22 21:46:55 +08001452 return RESOLV_CACHE_SKIP;
Luke Huang952d0942018-12-26 16:53:03 +08001453 }
Ken Chen2a429352018-12-22 21:46:55 +08001454
1455 if (!cache_has_pending_request_locked(cache, &key, true)) {
1456 return RESOLV_CACHE_NOTFOUND;
1457
Bernie Innocenti55864192018-08-30 04:05:20 +09001458 } else {
chenbruce16adee42019-02-20 19:45:50 +08001459 LOG(INFO) << "Waiting for previous request";
Ken Chen2a429352018-12-22 21:46:55 +08001460 // wait until (1) timeout OR
1461 // (2) cv is notified AND no pending request matching the |key|
1462 // (cv notifier should delete pending request before sending notification.)
1463 bool ret = cv.wait_for(lock, std::chrono::seconds(PENDING_REQUEST_TIMEOUT),
1464 [netid, &cache, &key]() REQUIRES(cache_mutex) {
1465 // Must update cache as it could have been deleted
1466 cache = find_named_cache_locked(netid);
1467 return !cache_has_pending_request_locked(cache, &key, false);
1468 });
Ken Chen111c1ba2019-02-21 03:50:11 +08001469 if (!cache) {
1470 return RESOLV_CACHE_NOTFOUND;
1471 }
Ken Chen2a429352018-12-22 21:46:55 +08001472 if (ret == false) {
1473 resolv_cache_info* info = find_cache_info_locked(netid);
1474 if (info != NULL) {
1475 info->wait_for_pending_req_timeout_count++;
1476 }
1477 }
1478 lookup = _cache_lookup_p(cache, &key);
Bernie Innocenti55864192018-08-30 04:05:20 +09001479 e = *lookup;
1480 if (e == NULL) {
Ken Chen2a429352018-12-22 21:46:55 +08001481 return RESOLV_CACHE_NOTFOUND;
Bernie Innocenti55864192018-08-30 04:05:20 +09001482 }
1483 }
1484 }
1485
1486 now = _time_now();
1487
1488 /* remove stale entries here */
1489 if (now >= e->expires) {
chenbruce16adee42019-02-20 19:45:50 +08001490 LOG(INFO) << " NOT IN CACHE (STALE ENTRY " << *lookup << "DISCARDED)";
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001491 dump_query(e->query, e->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001492 _cache_remove_p(cache, lookup);
Ken Chen2a429352018-12-22 21:46:55 +08001493 return RESOLV_CACHE_NOTFOUND;
Bernie Innocenti55864192018-08-30 04:05:20 +09001494 }
1495
1496 *answerlen = e->answerlen;
1497 if (e->answerlen > answersize) {
1498 /* NOTE: we return UNSUPPORTED if the answer buffer is too short */
chenbruce16adee42019-02-20 19:45:50 +08001499 LOG(INFO) << " ANSWER TOO LONG";
Ken Chen2a429352018-12-22 21:46:55 +08001500 return RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti55864192018-08-30 04:05:20 +09001501 }
1502
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001503 memcpy(answer, e->answer, e->answerlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001504
1505 /* bump up this entry to the top of the MRU list */
1506 if (e != cache->mru_list.mru_next) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001507 entry_mru_remove(e);
1508 entry_mru_add(e, &cache->mru_list);
Bernie Innocenti55864192018-08-30 04:05:20 +09001509 }
1510
chenbruce16adee42019-02-20 19:45:50 +08001511 LOG(INFO) << " FOUND IN CACHE entry=" << e;
Ken Chen2a429352018-12-22 21:46:55 +08001512 return RESOLV_CACHE_FOUND;
Bernie Innocenti55864192018-08-30 04:05:20 +09001513}
1514
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001515void _resolv_cache_add(unsigned netid, const void* query, int querylen, const void* answer,
1516 int answerlen) {
1517 Entry key[1];
1518 Entry* e;
1519 Entry** lookup;
1520 u_long ttl;
1521 Cache* cache = NULL;
Bernie Innocenti55864192018-08-30 04:05:20 +09001522
1523 /* don't assume that the query has already been cached
1524 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001525 if (!entry_init_key(key, query, querylen)) {
chenbruce16adee42019-02-20 19:45:50 +08001526 LOG(INFO) << __func__ << ": passed invalid query?";
Bernie Innocenti55864192018-08-30 04:05:20 +09001527 return;
1528 }
1529
Ken Chen2a429352018-12-22 21:46:55 +08001530 std::lock_guard guard(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001531
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001532 cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001533 if (cache == NULL) {
Ken Chen2a429352018-12-22 21:46:55 +08001534 return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001535 }
1536
chenbruce16adee42019-02-20 19:45:50 +08001537 LOG(INFO) << __func__ << ": query:";
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001538 dump_query((u_char*) query, querylen);
1539 dump_answer((u_char*) answer, answerlen);
1540 if (kDumpData) {
chenbruce16adee42019-02-20 19:45:50 +08001541 LOG(INFO) << "answer:";
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001542 dump_bytes((u_char*) answer, answerlen);
1543 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001544
1545 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001546 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001547
1548 if (e != NULL) { /* should not happen */
chenbruce16adee42019-02-20 19:45:50 +08001549 LOG(INFO) << __func__ << ": ALREADY IN CACHE (" << e << ") ? IGNORING ADD";
Ken Chen2a429352018-12-22 21:46:55 +08001550 _cache_notify_waiting_tid_locked(cache, key);
1551 return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001552 }
1553
1554 if (cache->num_entries >= cache->max_entries) {
1555 _cache_remove_expired(cache);
1556 if (cache->num_entries >= cache->max_entries) {
1557 _cache_remove_oldest(cache);
1558 }
1559 /* need to lookup again */
1560 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001561 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001562 if (e != NULL) {
chenbruce16adee42019-02-20 19:45:50 +08001563 LOG(INFO) << __func__ << ": ALREADY IN CACHE (" << e << ") ? IGNORING ADD";
Ken Chen2a429352018-12-22 21:46:55 +08001564 _cache_notify_waiting_tid_locked(cache, key);
1565 return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001566 }
1567 }
1568
1569 ttl = answer_getTTL(answer, answerlen);
1570 if (ttl > 0) {
1571 e = entry_alloc(key, answer, answerlen);
1572 if (e != NULL) {
1573 e->expires = ttl + _time_now();
1574 _cache_add_p(cache, lookup, e);
1575 }
1576 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001577
Ken Chen2a429352018-12-22 21:46:55 +08001578 cache_dump_mru(cache);
1579 _cache_notify_waiting_tid_locked(cache, key);
Bernie Innocenti55864192018-08-30 04:05:20 +09001580}
1581
Ken Chen2a429352018-12-22 21:46:55 +08001582// Head of the list of caches.
1583static struct resolv_cache_info res_cache_list GUARDED_BY(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001584
ckenb1a69a42018-12-01 17:45:18 +09001585// insert resolv_cache_info into the list of resolv_cache_infos
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001586static void insert_cache_info_locked(resolv_cache_info* cache_info);
ckenb1a69a42018-12-01 17:45:18 +09001587// creates a resolv_cache_info
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001588static resolv_cache_info* create_cache_info();
ckenb1a69a42018-12-01 17:45:18 +09001589// empty the nameservers set for the named cache
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001590static void free_nameservers_locked(resolv_cache_info* cache_info);
1591// return 1 if the provided list of name servers differs from the list of name servers
1592// currently attached to the provided cache_info
1593static int resolv_is_nameservers_equal_locked(resolv_cache_info* cache_info, const char** servers,
1594 int numservers);
ckenb1a69a42018-12-01 17:45:18 +09001595// clears the stats samples contained withing the given cache_info
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001596static void res_cache_clear_stats_locked(resolv_cache_info* cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001597
ckenb1a69a42018-12-01 17:45:18 +09001598// public API for netd to query if name server is set on specific netid
1599bool resolv_has_nameservers(unsigned netid) {
Ken Chen2a429352018-12-22 21:46:55 +08001600 std::lock_guard guard(cache_mutex);
ckenb1a69a42018-12-01 17:45:18 +09001601 resolv_cache_info* info = find_cache_info_locked(netid);
Ken Chen2a429352018-12-22 21:46:55 +08001602 return (info != nullptr) && (info->nscount > 0);
ckenb1a69a42018-12-01 17:45:18 +09001603}
1604
1605// look up the named cache, and creates one if needed
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001606static resolv_cache* get_res_cache_for_net_locked(unsigned netid) {
1607 resolv_cache* cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001608 if (!cache) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001609 resolv_cache_info* cache_info = create_cache_info();
Bernie Innocenti55864192018-08-30 04:05:20 +09001610 if (cache_info) {
Ken Chen2a429352018-12-22 21:46:55 +08001611 cache = resolv_cache_create();
Bernie Innocenti55864192018-08-30 04:05:20 +09001612 if (cache) {
1613 cache_info->cache = cache;
1614 cache_info->netid = netid;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001615 insert_cache_info_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001616 } else {
1617 free(cache_info);
1618 }
1619 }
1620 }
1621 return cache;
1622}
1623
Bernie Innocenti189eb502018-10-01 23:10:18 +09001624void resolv_delete_cache_for_net(unsigned netid) {
Ken Chen2a429352018-12-22 21:46:55 +08001625 std::lock_guard guard(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001626
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001627 struct resolv_cache_info* prev_cache_info = &res_cache_list;
Bernie Innocenti55864192018-08-30 04:05:20 +09001628
1629 while (prev_cache_info->next) {
1630 struct resolv_cache_info* cache_info = prev_cache_info->next;
1631
1632 if (cache_info->netid == netid) {
1633 prev_cache_info->next = cache_info->next;
Bernie Innocentid2b27032018-12-18 19:53:42 +09001634 cache_flush_locked(cache_info->cache);
Bernie Innocenti55864192018-08-30 04:05:20 +09001635 free(cache_info->cache->entries);
1636 free(cache_info->cache);
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001637 free_nameservers_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001638 free(cache_info);
1639 break;
1640 }
1641
1642 prev_cache_info = prev_cache_info->next;
1643 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001644}
1645
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001646static resolv_cache_info* create_cache_info() {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001647 return (struct resolv_cache_info*) calloc(sizeof(struct resolv_cache_info), 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001648}
1649
Ken Chen2a429352018-12-22 21:46:55 +08001650// TODO: convert this to a simple and efficient C++ container.
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001651static void insert_cache_info_locked(struct resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001652 struct resolv_cache_info* last;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001653 for (last = &res_cache_list; last->next; last = last->next) {}
Bernie Innocenti55864192018-08-30 04:05:20 +09001654 last->next = cache_info;
Bernie Innocenti55864192018-08-30 04:05:20 +09001655}
1656
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001657static resolv_cache* find_named_cache_locked(unsigned netid) {
ckenb1a69a42018-12-01 17:45:18 +09001658 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001659 if (info != NULL) return info->cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001660 return NULL;
1661}
1662
ckenb1a69a42018-12-01 17:45:18 +09001663static resolv_cache_info* find_cache_info_locked(unsigned netid) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001664 struct resolv_cache_info* cache_info = res_cache_list.next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001665
1666 while (cache_info) {
1667 if (cache_info->netid == netid) {
1668 break;
1669 }
1670
1671 cache_info = cache_info->next;
1672 }
1673 return cache_info;
1674}
1675
Bernie Innocenti34de3ba2019-02-19 18:08:36 +09001676static void resolv_set_default_params(res_params* params) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001677 params->sample_validity = NSSAMPLE_VALIDITY;
1678 params->success_threshold = SUCCESS_THRESHOLD;
1679 params->min_samples = 0;
1680 params->max_samples = 0;
1681 params->base_timeout_msec = 0; // 0 = legacy algorithm
waynemad193e4d2019-02-18 17:47:59 +08001682 params->retry_count = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +09001683}
1684
Bernie Innocenti45238a12018-12-04 14:57:48 +09001685int resolv_set_nameservers_for_net(unsigned netid, const char** servers, const int numservers,
Bernie Innocenti34de3ba2019-02-19 18:08:36 +09001686 const char* domains, const res_params* params) {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001687 char* cp;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001688 int* offset;
Bernie Innocenti55864192018-08-30 04:05:20 +09001689 struct addrinfo* nsaddrinfo[MAXNS];
1690
1691 if (numservers > MAXNS) {
chenbruce16adee42019-02-20 19:45:50 +08001692 LOG(INFO) << __func__ << ": numservers=" << numservers << ", MAXNS=" << MAXNS;
Bernie Innocenti55864192018-08-30 04:05:20 +09001693 return E2BIG;
1694 }
1695
1696 // Parse the addresses before actually locking or changing any state, in case there is an error.
1697 // As a side effect this also reduces the time the lock is kept.
Bernie Innocentic165ce82018-10-16 23:35:28 +09001698 char sbuf[NI_MAXSERV];
Bernie Innocenti55864192018-08-30 04:05:20 +09001699 snprintf(sbuf, sizeof(sbuf), "%u", NAMESERVER_PORT);
Bernie Innocenti45238a12018-12-04 14:57:48 +09001700 for (int i = 0; i < numservers; i++) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001701 // The addrinfo structures allocated here are freed in free_nameservers_locked().
Bernie Innocentic165ce82018-10-16 23:35:28 +09001702 const addrinfo hints = {
1703 .ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM, .ai_flags = AI_NUMERICHOST};
1704 int rt = getaddrinfo_numeric(servers[i], sbuf, hints, &nsaddrinfo[i]);
Bernie Innocenti55864192018-08-30 04:05:20 +09001705 if (rt != 0) {
Bernie Innocenti45238a12018-12-04 14:57:48 +09001706 for (int j = 0; j < i; j++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001707 freeaddrinfo(nsaddrinfo[j]);
Bernie Innocenti55864192018-08-30 04:05:20 +09001708 }
chenbruce16adee42019-02-20 19:45:50 +08001709 LOG(INFO) << __func__ << ": getaddrinfo_numeric(" << servers[i]
1710 << ") = " << gai_strerror(rt);
Bernie Innocenti55864192018-08-30 04:05:20 +09001711 return EINVAL;
1712 }
1713 }
1714
Ken Chen2a429352018-12-22 21:46:55 +08001715 std::lock_guard guard(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001716 // creates the cache if not created
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001717 get_res_cache_for_net_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001718
ckenb1a69a42018-12-01 17:45:18 +09001719 resolv_cache_info* cache_info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001720
1721 if (cache_info != NULL) {
1722 uint8_t old_max_samples = cache_info->params.max_samples;
1723 if (params != NULL) {
1724 cache_info->params = *params;
1725 } else {
Bernie Innocenti1fbca5c2018-10-01 20:46:20 +09001726 resolv_set_default_params(&cache_info->params);
Bernie Innocenti55864192018-08-30 04:05:20 +09001727 }
1728
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001729 if (!resolv_is_nameservers_equal_locked(cache_info, servers, numservers)) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001730 // free current before adding new
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001731 free_nameservers_locked(cache_info);
Bernie Innocenti45238a12018-12-04 14:57:48 +09001732 for (int i = 0; i < numservers; i++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001733 cache_info->nsaddrinfo[i] = nsaddrinfo[i];
1734 cache_info->nameservers[i] = strdup(servers[i]);
chenbruce16adee42019-02-20 19:45:50 +08001735 LOG(INFO) << __func__ << ": netid = " << netid << ", addr = " << servers[i];
Bernie Innocenti55864192018-08-30 04:05:20 +09001736 }
1737 cache_info->nscount = numservers;
1738
1739 // Clear the NS statistics because the mapping to nameservers might have changed.
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001740 res_cache_clear_stats_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001741
1742 // increment the revision id to ensure that sample state is not written back if the
1743 // servers change; in theory it would suffice to do so only if the servers or
1744 // max_samples actually change, in practice the overhead of checking is higher than the
1745 // cost, and overflows are unlikely
1746 ++cache_info->revision_id;
Ken Chen26f01e42018-11-02 13:18:40 +08001747 } else {
1748 if (cache_info->params.max_samples != old_max_samples) {
1749 // If the maximum number of samples changes, the overhead of keeping the most recent
1750 // samples around is not considered worth the effort, so they are cleared instead.
1751 // All other parameters do not affect shared state: Changing these parameters does
1752 // not invalidate the samples, as they only affect aggregation and the conditions
1753 // under which servers are considered usable.
1754 res_cache_clear_stats_locked(cache_info);
1755 ++cache_info->revision_id;
1756 }
Bernie Innocenti45238a12018-12-04 14:57:48 +09001757 for (int j = 0; j < numservers; j++) {
Ken Chen26f01e42018-11-02 13:18:40 +08001758 freeaddrinfo(nsaddrinfo[j]);
1759 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001760 }
1761
1762 // Always update the search paths, since determining whether they actually changed is
1763 // complex due to the zero-padding, and probably not worth the effort. Cache-flushing
1764 // however is not // necessary, since the stored cache entries do contain the domain, not
1765 // just the host name.
1766 // code moved from res_init.c, load_domain_search_list
1767 strlcpy(cache_info->defdname, domains, sizeof(cache_info->defdname));
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001768 if ((cp = strchr(cache_info->defdname, '\n')) != NULL) *cp = '\0';
Bernie Innocenti55864192018-08-30 04:05:20 +09001769
1770 cp = cache_info->defdname;
1771 offset = cache_info->dnsrch_offset;
1772 while (offset < cache_info->dnsrch_offset + MAXDNSRCH) {
1773 while (*cp == ' ' || *cp == '\t') /* skip leading white space */
1774 cp++;
1775 if (*cp == '\0') /* stop if nothing more to do */
1776 break;
1777 *offset++ = cp - cache_info->defdname; /* record this search domain */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001778 while (*cp) { /* zero-terminate it */
1779 if (*cp == ' ' || *cp == '\t') {
Bernie Innocenti55864192018-08-30 04:05:20 +09001780 *cp++ = '\0';
1781 break;
1782 }
1783 cp++;
1784 }
1785 }
1786 *offset = -1; /* cache_info->dnsrch_offset has MAXDNSRCH+1 items */
1787 }
1788
Bernie Innocenti55864192018-08-30 04:05:20 +09001789 return 0;
1790}
1791
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001792static int resolv_is_nameservers_equal_locked(resolv_cache_info* cache_info, const char** servers,
1793 int numservers) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001794 if (cache_info->nscount != numservers) {
1795 return 0;
1796 }
1797
1798 // Compare each name server against current name servers.
1799 // TODO: this is incorrect if the list of current or previous nameservers
1800 // contains duplicates. This does not really matter because the framework
1801 // filters out duplicates, but we should probably fix it. It's also
1802 // insensitive to the order of the nameservers; we should probably fix that
1803 // too.
1804 for (int i = 0; i < numservers; i++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001805 for (int j = 0;; j++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001806 if (j >= numservers) {
1807 return 0;
1808 }
1809 if (strcmp(cache_info->nameservers[i], servers[j]) == 0) {
1810 break;
1811 }
1812 }
1813 }
1814
1815 return 1;
1816}
1817
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001818static void free_nameservers_locked(resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001819 int i;
1820 for (i = 0; i < cache_info->nscount; i++) {
1821 free(cache_info->nameservers[i]);
1822 cache_info->nameservers[i] = NULL;
1823 if (cache_info->nsaddrinfo[i] != NULL) {
1824 freeaddrinfo(cache_info->nsaddrinfo[i]);
1825 cache_info->nsaddrinfo[i] = NULL;
1826 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001827 cache_info->nsstats[i].sample_count = cache_info->nsstats[i].sample_next = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +09001828 }
1829 cache_info->nscount = 0;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001830 res_cache_clear_stats_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001831 ++cache_info->revision_id;
1832}
1833
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001834void _resolv_populate_res_for_net(res_state statp) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001835 if (statp == NULL) {
1836 return;
1837 }
1838
Ken Chen2a429352018-12-22 21:46:55 +08001839 std::lock_guard guard(cache_mutex);
ckenb1a69a42018-12-01 17:45:18 +09001840 resolv_cache_info* info = find_cache_info_locked(statp->netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001841 if (info != NULL) {
1842 int nserv;
1843 struct addrinfo* ai;
chenbruce16adee42019-02-20 19:45:50 +08001844 LOG(INFO) << __func__ << ": " << statp->netid;
Bernie Innocenti55864192018-08-30 04:05:20 +09001845 for (nserv = 0; nserv < MAXNS; nserv++) {
1846 ai = info->nsaddrinfo[nserv];
1847 if (ai == NULL) {
1848 break;
1849 }
1850
1851 if ((size_t) ai->ai_addrlen <= sizeof(statp->_u._ext.ext->nsaddrs[0])) {
1852 if (statp->_u._ext.ext != NULL) {
1853 memcpy(&statp->_u._ext.ext->nsaddrs[nserv], ai->ai_addr, ai->ai_addrlen);
1854 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
1855 } else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001856 if ((size_t) ai->ai_addrlen <= sizeof(statp->nsaddr_list[0])) {
1857 memcpy(&statp->nsaddr_list[nserv], ai->ai_addr, ai->ai_addrlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001858 } else {
1859 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
1860 }
1861 }
1862 } else {
chenbruce16adee42019-02-20 19:45:50 +08001863 LOG(INFO) << __func__ << ": found too long addrlen";
Bernie Innocenti55864192018-08-30 04:05:20 +09001864 }
1865 }
1866 statp->nscount = nserv;
1867 // now do search domains. Note that we cache the offsets as this code runs alot
1868 // but the setting/offset-computer only runs when set/changed
1869 // WARNING: Don't use str*cpy() here, this string contains zeroes.
1870 memcpy(statp->defdname, info->defdname, sizeof(statp->defdname));
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001871 char** pp = statp->dnsrch;
1872 int* p = info->dnsrch_offset;
Bernie Innocenti55864192018-08-30 04:05:20 +09001873 while (pp < statp->dnsrch + MAXDNSRCH && *p != -1) {
1874 *pp++ = &statp->defdname[0] + *p++;
1875 }
1876 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001877}
1878
1879/* Resolver reachability statistics. */
1880
Bernie Innocenti189eb502018-10-01 23:10:18 +09001881static void _res_cache_add_stats_sample_locked(res_stats* stats, const res_sample* sample,
1882 int max_samples) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001883 // Note: This function expects max_samples > 0, otherwise a (harmless) modification of the
1884 // allocated but supposedly unused memory for samples[0] will happen
chenbruce16adee42019-02-20 19:45:50 +08001885 LOG(INFO) << __func__ << ": adding sample to stats, next = " << stats->sample_next
1886 << ", count = " << stats->sample_count;
Bernie Innocenti55864192018-08-30 04:05:20 +09001887 stats->samples[stats->sample_next] = *sample;
1888 if (stats->sample_count < max_samples) {
1889 ++stats->sample_count;
1890 }
1891 if (++stats->sample_next >= max_samples) {
1892 stats->sample_next = 0;
1893 }
1894}
1895
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001896static void res_cache_clear_stats_locked(resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001897 if (cache_info) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001898 for (int i = 0; i < MAXNS; ++i) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001899 cache_info->nsstats->sample_count = cache_info->nsstats->sample_next = 0;
1900 }
1901 }
1902}
1903
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001904int android_net_res_stats_get_info_for_net(unsigned netid, int* nscount,
1905 struct sockaddr_storage servers[MAXNS], int* dcount,
1906 char domains[MAXDNSRCH][MAXDNSRCHPATH],
Bernie Innocenti34de3ba2019-02-19 18:08:36 +09001907 res_params* params, struct res_stats stats[MAXNS],
Ken Chen2a429352018-12-22 21:46:55 +08001908 int* wait_for_pending_req_timeout_count) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001909 int revision_id = -1;
Ken Chen2a429352018-12-22 21:46:55 +08001910 std::lock_guard guard(cache_mutex);
Bernie Innocenti55864192018-08-30 04:05:20 +09001911
ckenb1a69a42018-12-01 17:45:18 +09001912 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001913 if (info) {
1914 if (info->nscount > MAXNS) {
chenbruce16adee42019-02-20 19:45:50 +08001915 LOG(INFO) << __func__ << ": nscount " << info->nscount << " > MAXNS " << MAXNS;
Bernie Innocenti55864192018-08-30 04:05:20 +09001916 errno = EFAULT;
1917 return -1;
1918 }
1919 int i;
1920 for (i = 0; i < info->nscount; i++) {
1921 // Verify that the following assumptions are held, failure indicates corruption:
1922 // - getaddrinfo() may never return a sockaddr > sockaddr_storage
1923 // - all addresses are valid
1924 // - there is only one address per addrinfo thanks to numeric resolution
1925 int addrlen = info->nsaddrinfo[i]->ai_addrlen;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001926 if (addrlen < (int) sizeof(struct sockaddr) || addrlen > (int) sizeof(servers[0])) {
chenbruce16adee42019-02-20 19:45:50 +08001927 LOG(INFO) << __func__ << ": nsaddrinfo[" << i << "].ai_addrlen == " << addrlen;
Bernie Innocenti55864192018-08-30 04:05:20 +09001928 errno = EMSGSIZE;
1929 return -1;
1930 }
1931 if (info->nsaddrinfo[i]->ai_addr == NULL) {
chenbruce16adee42019-02-20 19:45:50 +08001932 LOG(INFO) << __func__ << ": nsaddrinfo[" << i << "].ai_addr == NULL";
Bernie Innocenti55864192018-08-30 04:05:20 +09001933 errno = ENOENT;
1934 return -1;
1935 }
1936 if (info->nsaddrinfo[i]->ai_next != NULL) {
chenbruce16adee42019-02-20 19:45:50 +08001937 LOG(INFO) << __func__ << ": nsaddrinfo[" << i << "].ai_next != NULL";
Bernie Innocenti55864192018-08-30 04:05:20 +09001938 errno = ENOTUNIQ;
1939 return -1;
1940 }
1941 }
1942 *nscount = info->nscount;
1943 for (i = 0; i < info->nscount; i++) {
1944 memcpy(&servers[i], info->nsaddrinfo[i]->ai_addr, info->nsaddrinfo[i]->ai_addrlen);
1945 stats[i] = info->nsstats[i];
1946 }
1947 for (i = 0; i < MAXDNSRCH; i++) {
1948 const char* cur_domain = info->defdname + info->dnsrch_offset[i];
1949 // dnsrch_offset[i] can either be -1 or point to an empty string to indicate the end
1950 // of the search offsets. Checking for < 0 is not strictly necessary, but safer.
1951 // TODO: Pass in a search domain array instead of a string to
Bernie Innocenti189eb502018-10-01 23:10:18 +09001952 // resolv_set_nameservers_for_net() and make this double check unnecessary.
Bernie Innocenti55864192018-08-30 04:05:20 +09001953 if (info->dnsrch_offset[i] < 0 ||
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001954 ((size_t) info->dnsrch_offset[i]) >= sizeof(info->defdname) || !cur_domain[0]) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001955 break;
1956 }
1957 strlcpy(domains[i], cur_domain, MAXDNSRCHPATH);
1958 }
1959 *dcount = i;
1960 *params = info->params;
1961 revision_id = info->revision_id;
Ken Chen2a429352018-12-22 21:46:55 +08001962 *wait_for_pending_req_timeout_count = info->wait_for_pending_req_timeout_count;
Bernie Innocenti55864192018-08-30 04:05:20 +09001963 }
1964
Bernie Innocenti55864192018-08-30 04:05:20 +09001965 return revision_id;
1966}
1967
Bernie Innocenti34de3ba2019-02-19 18:08:36 +09001968int resolv_cache_get_resolver_stats(unsigned netid, res_params* params, res_stats stats[MAXNS]) {
Ken Chen2a429352018-12-22 21:46:55 +08001969 std::lock_guard guard(cache_mutex);
ckenb1a69a42018-12-01 17:45:18 +09001970 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001971 if (info) {
1972 memcpy(stats, info->nsstats, sizeof(info->nsstats));
1973 *params = info->params;
Ken Chen2a429352018-12-22 21:46:55 +08001974 return info->revision_id;
Bernie Innocenti55864192018-08-30 04:05:20 +09001975 }
1976
Ken Chen2a429352018-12-22 21:46:55 +08001977 return -1;
Bernie Innocenti55864192018-08-30 04:05:20 +09001978}
1979
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001980void _resolv_cache_add_resolver_stats_sample(unsigned netid, int revision_id, int ns,
Bernie Innocenti189eb502018-10-01 23:10:18 +09001981 const res_sample* sample, int max_samples) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001982 if (max_samples <= 0) return;
1983
Ken Chen2a429352018-12-22 21:46:55 +08001984 std::lock_guard guard(cache_mutex);
ckenb1a69a42018-12-01 17:45:18 +09001985 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001986
1987 if (info && info->revision_id == revision_id) {
1988 _res_cache_add_stats_sample_locked(&info->nsstats[ns], sample, max_samples);
1989 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001990}