blob: e7a3b9b69e84eed67f7d25dc1f018da66e35e4c0 [file] [log] [blame]
Bernie Innocenti55864192018-08-30 04:05:20 +09001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090029// NOTE: verbose logging MUST NOT be left enabled in production binaries.
30// It floods logs at high rate, and can leak privacy-sensitive information.
31constexpr bool kVerboseLogging = false;
32constexpr bool kDumpData = false;
33#define LOG_TAG "res_cache"
34
Bernie Innocentif89b3512018-08-30 07:34:37 +090035#include <pthread.h>
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>
Bernie Innocenti55864192018-08-30 04:05:20 +090042
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090043#include <arpa/inet.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090044#include <arpa/nameser.h>
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090045#include <errno.h>
46#include <linux/if.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090047#include <net/if.h>
48#include <netdb.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090049
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090050#include <android-base/logging.h>
Bernie Innocentif89b3512018-08-30 07:34:37 +090051
Bernie Innocenti189eb502018-10-01 23:10:18 +090052#include "res_state_ext.h"
Bernie Innocentif89b3512018-08-30 07:34:37 +090053#include "resolv_cache.h"
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090054#include "resolv_private.h"
Bernie Innocenti55864192018-08-30 04:05:20 +090055
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090056#define VLOG if (!kVerboseLogging) {} else LOG(INFO)
57
58#ifndef RESOLV_ALLOW_VERBOSE_LOGGING
59static_assert(kVerboseLogging == false && kDumpData == false,
60 "Verbose logging floods logs at high-rate and exposes privacy-sensitive information. "
61 "Do not enable in release builds.");
62#endif
Bernie Innocenti55864192018-08-30 04:05:20 +090063
64/* This code implements a small and *simple* DNS resolver cache.
65 *
66 * It is only used to cache DNS answers for a time defined by the smallest TTL
67 * among the answer records in order to reduce DNS traffic. It is not supposed
68 * to be a full DNS cache, since we plan to implement that in the future in a
69 * dedicated process running on the system.
70 *
71 * Note that its design is kept simple very intentionally, i.e.:
72 *
73 * - it takes raw DNS query packet data as input, and returns raw DNS
74 * answer packet data as output
75 *
76 * (this means that two similar queries that encode the DNS name
77 * differently will be treated distinctly).
78 *
79 * the smallest TTL value among the answer records are used as the time
80 * to keep an answer in the cache.
81 *
82 * this is bad, but we absolutely want to avoid parsing the answer packets
83 * (and should be solved by the later full DNS cache process).
84 *
85 * - the implementation is just a (query-data) => (answer-data) hash table
86 * with a trivial least-recently-used expiration policy.
87 *
88 * Doing this keeps the code simple and avoids to deal with a lot of things
89 * that a full DNS cache is expected to do.
90 *
91 * The API is also very simple:
92 *
93 * - the client calls _resolv_cache_get() to obtain a handle to the cache.
94 * this will initialize the cache on first usage. the result can be NULL
95 * if the cache is disabled.
96 *
97 * - the client calls _resolv_cache_lookup() before performing a query
98 *
99 * if the function returns RESOLV_CACHE_FOUND, a copy of the answer data
100 * has been copied into the client-provided answer buffer.
101 *
102 * if the function returns RESOLV_CACHE_NOTFOUND, the client should perform
103 * a request normally, *then* call _resolv_cache_add() to add the received
104 * answer to the cache.
105 *
106 * if the function returns RESOLV_CACHE_UNSUPPORTED, the client should
107 * perform a request normally, and *not* call _resolv_cache_add()
108 *
109 * note that RESOLV_CACHE_UNSUPPORTED is also returned if the answer buffer
110 * is too short to accomodate the cached result.
111 */
112
113/* default number of entries kept in the cache. This value has been
114 * determined by browsing through various sites and counting the number
115 * of corresponding requests. Keep in mind that our framework is currently
116 * performing two requests per name lookup (one for IPv4, the other for IPv6)
117 *
118 * www.google.com 4
119 * www.ysearch.com 6
120 * www.amazon.com 8
121 * www.nytimes.com 22
122 * www.espn.com 28
123 * www.msn.com 28
124 * www.lemonde.fr 35
125 *
126 * (determined in 2009-2-17 from Paris, France, results may vary depending
127 * on location)
128 *
129 * most high-level websites use lots of media/ad servers with different names
130 * but these are generally reused when browsing through the site.
131 *
132 * As such, a value of 64 should be relatively comfortable at the moment.
133 *
134 * ******************************************
135 * * NOTE - this has changed.
136 * * 1) we've added IPv6 support so each dns query results in 2 responses
137 * * 2) we've made this a system-wide cache, so the cost is less (it's not
138 * * duplicated in each process) and the need is greater (more processes
139 * * making different requests).
140 * * Upping by 2x for IPv6
141 * * Upping by another 5x for the centralized nature
142 * *****************************************
143 */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900144#define CONFIG_MAX_ENTRIES (64 * 2 * 5)
Bernie Innocenti55864192018-08-30 04:05:20 +0900145
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900146/** BOUNDED BUFFER FORMATTING **/
Bernie Innocenti55864192018-08-30 04:05:20 +0900147
148/* technical note:
149 *
150 * the following debugging routines are used to append data to a bounded
151 * buffer they take two parameters that are:
152 *
153 * - p : a pointer to the current cursor position in the buffer
154 * this value is initially set to the buffer's address.
155 *
156 * - end : the address of the buffer's limit, i.e. of the first byte
157 * after the buffer. this address should never be touched.
158 *
159 * IMPORTANT: it is assumed that end > buffer_address, i.e.
160 * that the buffer is at least one byte.
161 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900162 * the bprint_x() functions return the new value of 'p' after the data
Bernie Innocenti55864192018-08-30 04:05:20 +0900163 * has been appended, and also ensure the following:
164 *
165 * - the returned value will never be strictly greater than 'end'
166 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900167 * - a return value equal to 'end' means that truncation occurred
Bernie Innocenti55864192018-08-30 04:05:20 +0900168 * (in which case, end[-1] will be set to 0)
169 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900170 * - after returning from a bprint_x() function, the content of the buffer
Bernie Innocenti55864192018-08-30 04:05:20 +0900171 * is always 0-terminated, even in the event of truncation.
172 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900173 * these conventions allow you to call bprint_x() functions multiple times and
Bernie Innocenti55864192018-08-30 04:05:20 +0900174 * only check for truncation at the end of the sequence, as in:
175 *
176 * char buff[1000], *p = buff, *end = p + sizeof(buff);
177 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900178 * p = bprint_c(p, end, '"');
179 * p = bprint_s(p, end, my_string);
180 * p = bprint_c(p, end, '"');
Bernie Innocenti55864192018-08-30 04:05:20 +0900181 *
182 * if (p >= end) {
183 * // buffer was too small
184 * }
185 *
186 * printf( "%s", buff );
187 */
188
Bernie Innocenti1fbca5c2018-10-01 20:46:20 +0900189/* Defaults used for initializing __res_params */
190
191// If successes * 100 / total_samples is less than this value, the server is considered failing
192#define SUCCESS_THRESHOLD 75
193// Sample validity in seconds. Set to -1 to disable skipping failing servers.
194#define NSSAMPLE_VALIDITY 1800
195
Bernie Innocenti55864192018-08-30 04:05:20 +0900196/* add a char to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900197static char* bprint_c(char* p, char* end, int c) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900198 if (p < end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900199 if (p + 1 == end)
Bernie Innocenti55864192018-08-30 04:05:20 +0900200 *p++ = 0;
201 else {
202 *p++ = (char) c;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900203 *p = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900204 }
205 }
206 return p;
207}
208
209/* add a sequence of bytes to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900210static char* bprint_b(char* p, char* end, const char* buf, int len) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900211 int avail = end - p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900212
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900213 if (avail <= 0 || len <= 0) return p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900214
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900215 if (avail > len) avail = len;
Bernie Innocenti55864192018-08-30 04:05:20 +0900216
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900217 memcpy(p, buf, avail);
Bernie Innocenti55864192018-08-30 04:05:20 +0900218 p += avail;
219
220 if (p < end)
221 p[0] = 0;
222 else
223 end[-1] = 0;
224
225 return p;
226}
227
228/* add a string to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900229static char* bprint_s(char* p, char* end, const char* str) {
230 return bprint_b(p, end, str, strlen(str));
Bernie Innocenti55864192018-08-30 04:05:20 +0900231}
232
233/* add a formatted string to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900234static char* bprint(char* p, char* end, const char* format, ...) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900235 int avail, n;
236 va_list args;
Bernie Innocenti55864192018-08-30 04:05:20 +0900237
238 avail = end - p;
239
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900240 if (avail <= 0) return p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900241
242 va_start(args, format);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900243 n = vsnprintf(p, avail, format, args);
Bernie Innocenti55864192018-08-30 04:05:20 +0900244 va_end(args);
245
246 /* certain C libraries return -1 in case of truncation */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900247 if (n < 0 || n > avail) n = avail;
Bernie Innocenti55864192018-08-30 04:05:20 +0900248
249 p += n;
250 /* certain C libraries do not zero-terminate in case of truncation */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900251 if (p == end) p[-1] = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900252
253 return p;
254}
255
256/* add a hex value to a bounded buffer, up to 8 digits */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900257static char* bprint_hex(char* p, char* end, unsigned value, int numDigits) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900258 char text[sizeof(unsigned) * 2];
259 int nn = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900260
261 while (numDigits-- > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900262 text[nn++] = "0123456789abcdef"[(value >> (numDigits * 4)) & 15];
Bernie Innocenti55864192018-08-30 04:05:20 +0900263 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900264 return bprint_b(p, end, text, nn);
Bernie Innocenti55864192018-08-30 04:05:20 +0900265}
266
267/* add the hexadecimal dump of some memory area to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900268static char* bprint_hexdump(char* p, char* end, const uint8_t* data, int datalen) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900269 int lineSize = 16;
Bernie Innocenti55864192018-08-30 04:05:20 +0900270
271 while (datalen > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900272 int avail = datalen;
273 int nn;
Bernie Innocenti55864192018-08-30 04:05:20 +0900274
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900275 if (avail > lineSize) avail = lineSize;
Bernie Innocenti55864192018-08-30 04:05:20 +0900276
277 for (nn = 0; nn < avail; nn++) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900278 if (nn > 0) p = bprint_c(p, end, ' ');
279 p = bprint_hex(p, end, data[nn], 2);
Bernie Innocenti55864192018-08-30 04:05:20 +0900280 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900281 for (; nn < lineSize; nn++) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900282 p = bprint_s(p, end, " ");
Bernie Innocenti55864192018-08-30 04:05:20 +0900283 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900284 p = bprint_s(p, end, " ");
Bernie Innocenti55864192018-08-30 04:05:20 +0900285
286 for (nn = 0; nn < avail; nn++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900287 int c = data[nn];
Bernie Innocenti55864192018-08-30 04:05:20 +0900288
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900289 if (c < 32 || c > 127) c = '.';
Bernie Innocenti55864192018-08-30 04:05:20 +0900290
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900291 p = bprint_c(p, end, c);
Bernie Innocenti55864192018-08-30 04:05:20 +0900292 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900293 p = bprint_c(p, end, '\n');
Bernie Innocenti55864192018-08-30 04:05:20 +0900294
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900295 data += avail;
Bernie Innocenti55864192018-08-30 04:05:20 +0900296 datalen -= avail;
297 }
298 return p;
299}
300
301/* dump the content of a query of packet to the log */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900302static void dump_bytes(const uint8_t* base, int len) {
303 if (!kDumpData) return;
Bernie Innocenti55864192018-08-30 04:05:20 +0900304
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900305 char buff[1024];
306 char *p = buff, *end = p + sizeof(buff);
307
308 p = bprint_hexdump(p, end, base, len);
309 VLOG << buff;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900310}
Bernie Innocenti55864192018-08-30 04:05:20 +0900311
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900312static time_t _time_now(void) {
313 struct timeval tv;
Bernie Innocenti55864192018-08-30 04:05:20 +0900314
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900315 gettimeofday(&tv, NULL);
Bernie Innocenti55864192018-08-30 04:05:20 +0900316 return tv.tv_sec;
317}
318
319/* reminder: the general format of a DNS packet is the following:
320 *
321 * HEADER (12 bytes)
322 * QUESTION (variable)
323 * ANSWER (variable)
324 * AUTHORITY (variable)
325 * ADDITIONNAL (variable)
326 *
327 * the HEADER is made of:
328 *
329 * ID : 16 : 16-bit unique query identification field
330 *
331 * QR : 1 : set to 0 for queries, and 1 for responses
332 * Opcode : 4 : set to 0 for queries
333 * AA : 1 : set to 0 for queries
334 * TC : 1 : truncation flag, will be set to 0 in queries
335 * RD : 1 : recursion desired
336 *
337 * RA : 1 : recursion available (0 in queries)
338 * Z : 3 : three reserved zero bits
339 * RCODE : 4 : response code (always 0=NOERROR in queries)
340 *
341 * QDCount: 16 : question count
342 * ANCount: 16 : Answer count (0 in queries)
343 * NSCount: 16: Authority Record count (0 in queries)
344 * ARCount: 16: Additionnal Record count (0 in queries)
345 *
346 * the QUESTION is made of QDCount Question Record (QRs)
347 * the ANSWER is made of ANCount RRs
348 * the AUTHORITY is made of NSCount RRs
349 * the ADDITIONNAL is made of ARCount RRs
350 *
351 * Each Question Record (QR) is made of:
352 *
353 * QNAME : variable : Query 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 *
357 * Each Resource Record (RR) is made of:
358 *
359 * NAME : variable : DNS NAME
360 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
361 * CLASS : 16 : class of query (IN=1)
362 * TTL : 32 : seconds to cache this RR (0=none)
363 * RDLENGTH: 16 : size of RDDATA in bytes
364 * RDDATA : variable : RR data (depends on TYPE)
365 *
366 * Each QNAME contains a domain name encoded as a sequence of 'labels'
367 * terminated by a zero. Each label has the following format:
368 *
369 * LEN : 8 : lenght of label (MUST be < 64)
370 * NAME : 8*LEN : label length (must exclude dots)
371 *
372 * A value of 0 in the encoding is interpreted as the 'root' domain and
373 * terminates the encoding. So 'www.android.com' will be encoded as:
374 *
375 * <3>www<7>android<3>com<0>
376 *
377 * Where <n> represents the byte with value 'n'
378 *
379 * Each NAME reflects the QNAME of the question, but has a slightly more
380 * complex encoding in order to provide message compression. This is achieved
381 * by using a 2-byte pointer, with format:
382 *
383 * TYPE : 2 : 0b11 to indicate a pointer, 0b01 and 0b10 are reserved
384 * OFFSET : 14 : offset to another part of the DNS packet
385 *
386 * The offset is relative to the start of the DNS packet and must point
387 * A pointer terminates the encoding.
388 *
389 * The NAME can be encoded in one of the following formats:
390 *
391 * - a sequence of simple labels terminated by 0 (like QNAMEs)
392 * - a single pointer
393 * - a sequence of simple labels terminated by a pointer
394 *
395 * A pointer shall always point to either a pointer of a sequence of
396 * labels (which can themselves be terminated by either a 0 or a pointer)
397 *
398 * The expanded length of a given domain name should not exceed 255 bytes.
399 *
400 * NOTE: we don't parse the answer packets, so don't need to deal with NAME
401 * records, only QNAMEs.
402 */
403
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900404#define DNS_HEADER_SIZE 12
Bernie Innocenti55864192018-08-30 04:05:20 +0900405
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900406#define DNS_TYPE_A "\00\01" /* big-endian decimal 1 */
407#define DNS_TYPE_PTR "\00\014" /* big-endian decimal 12 */
408#define DNS_TYPE_MX "\00\017" /* big-endian decimal 15 */
409#define DNS_TYPE_AAAA "\00\034" /* big-endian decimal 28 */
410#define DNS_TYPE_ALL "\00\0377" /* big-endian decimal 255 */
Bernie Innocenti55864192018-08-30 04:05:20 +0900411
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900412#define DNS_CLASS_IN "\00\01" /* big-endian decimal 1 */
Bernie Innocenti55864192018-08-30 04:05:20 +0900413
414typedef struct {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900415 const uint8_t* base;
416 const uint8_t* end;
417 const uint8_t* cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900418} DnsPacket;
419
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900420static void _dnsPacket_init(DnsPacket* packet, const uint8_t* buff, int bufflen) {
421 packet->base = buff;
422 packet->end = buff + bufflen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900423 packet->cursor = buff;
424}
425
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900426static void _dnsPacket_rewind(DnsPacket* packet) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900427 packet->cursor = packet->base;
428}
429
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900430static void _dnsPacket_skip(DnsPacket* packet, int count) {
431 const uint8_t* p = packet->cursor + count;
Bernie Innocenti55864192018-08-30 04:05:20 +0900432
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900433 if (p > packet->end) p = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900434
435 packet->cursor = p;
436}
437
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900438static int _dnsPacket_readInt16(DnsPacket* packet) {
439 const uint8_t* p = packet->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900440
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900441 if (p + 2 > packet->end) return -1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900442
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900443 packet->cursor = p + 2;
444 return (p[0] << 8) | p[1];
Bernie Innocenti55864192018-08-30 04:05:20 +0900445}
446
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900447/** QUERY CHECKING **/
Bernie Innocenti55864192018-08-30 04:05:20 +0900448
449/* check bytes in a dns packet. returns 1 on success, 0 on failure.
450 * the cursor is only advanced in the case of success
451 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900452static int _dnsPacket_checkBytes(DnsPacket* packet, int numBytes, const void* bytes) {
453 const uint8_t* p = packet->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900454
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900455 if (p + numBytes > packet->end) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900456
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900457 if (memcmp(p, bytes, numBytes) != 0) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900458
459 packet->cursor = p + numBytes;
460 return 1;
461}
462
463/* parse and skip a given QNAME stored in a query packet,
464 * from the current cursor position. returns 1 on success,
465 * or 0 for malformed data.
466 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900467static int _dnsPacket_checkQName(DnsPacket* packet) {
468 const uint8_t* p = packet->cursor;
469 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900470
471 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900472 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900473
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900474 if (p >= end) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900475
476 c = *p++;
477
478 if (c == 0) {
479 packet->cursor = p;
480 return 1;
481 }
482
483 /* we don't expect label compression in QNAMEs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900484 if (c >= 64) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900485
486 p += c;
487 /* we rely on the bound check at the start
488 * of the loop here */
489 }
490 /* malformed data */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900491 VLOG << "malformed QNAME";
Bernie Innocenti55864192018-08-30 04:05:20 +0900492 return 0;
493}
494
495/* parse and skip a given QR stored in a packet.
496 * returns 1 on success, and 0 on failure
497 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900498static int _dnsPacket_checkQR(DnsPacket* packet) {
499 if (!_dnsPacket_checkQName(packet)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900500
501 /* TYPE must be one of the things we support */
502 if (!_dnsPacket_checkBytes(packet, 2, DNS_TYPE_A) &&
503 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_PTR) &&
504 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_MX) &&
505 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_AAAA) &&
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900506 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_ALL)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900507 VLOG << "unsupported TYPE";
Bernie Innocenti55864192018-08-30 04:05:20 +0900508 return 0;
509 }
510 /* CLASS must be IN */
511 if (!_dnsPacket_checkBytes(packet, 2, DNS_CLASS_IN)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900512 VLOG << "unsupported CLASS";
Bernie Innocenti55864192018-08-30 04:05:20 +0900513 return 0;
514 }
515
516 return 1;
517}
518
519/* check the header of a DNS Query packet, return 1 if it is one
520 * type of query we can cache, or 0 otherwise
521 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900522static int _dnsPacket_checkQuery(DnsPacket* packet) {
523 const uint8_t* p = packet->base;
524 int qdCount, anCount, dnCount, arCount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900525
526 if (p + DNS_HEADER_SIZE > packet->end) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900527 VLOG << "query packet too small";
Bernie Innocenti55864192018-08-30 04:05:20 +0900528 return 0;
529 }
530
531 /* QR must be set to 0, opcode must be 0 and AA must be 0 */
532 /* RA, Z, and RCODE must be 0 */
533 if ((p[2] & 0xFC) != 0 || (p[3] & 0xCF) != 0) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900534 VLOG << "query packet flags unsupported";
Bernie Innocenti55864192018-08-30 04:05:20 +0900535 return 0;
536 }
537
538 /* Note that we ignore the TC, RD, CD, and AD bits here for the
539 * following reasons:
540 *
541 * - there is no point for a query packet sent to a server
542 * to have the TC bit set, but the implementation might
543 * set the bit in the query buffer for its own needs
544 * between a _resolv_cache_lookup and a
545 * _resolv_cache_add. We should not freak out if this
546 * is the case.
547 *
548 * - we consider that the result from a query might depend on
549 * the RD, AD, and CD bits, so these bits
550 * should be used to differentiate cached result.
551 *
552 * this implies that these bits are checked when hashing or
553 * comparing query packets, but not TC
554 */
555
556 /* ANCOUNT, DNCOUNT and ARCOUNT must be 0 */
557 qdCount = (p[4] << 8) | p[5];
558 anCount = (p[6] << 8) | p[7];
559 dnCount = (p[8] << 8) | p[9];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900560 arCount = (p[10] << 8) | p[11];
Bernie Innocenti55864192018-08-30 04:05:20 +0900561
562 if (anCount != 0 || dnCount != 0 || arCount > 1) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900563 VLOG << "query packet contains non-query records";
Bernie Innocenti55864192018-08-30 04:05:20 +0900564 return 0;
565 }
566
567 if (qdCount == 0) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900568 VLOG << "query packet doesn't contain query record";
Bernie Innocenti55864192018-08-30 04:05:20 +0900569 return 0;
570 }
571
572 /* Check QDCOUNT QRs */
573 packet->cursor = p + DNS_HEADER_SIZE;
574
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900575 for (; qdCount > 0; qdCount--)
576 if (!_dnsPacket_checkQR(packet)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900577
578 return 1;
579}
580
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900581/** QUERY DEBUGGING **/
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900582static char* dnsPacket_bprintQName(DnsPacket* packet, char* bp, char* bend) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900583 const uint8_t* p = packet->cursor;
584 const uint8_t* end = packet->end;
585 int first = 1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900586
587 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900588 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900589
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900590 if (p >= end) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900591
592 c = *p++;
593
594 if (c == 0) {
595 packet->cursor = p;
596 return bp;
597 }
598
599 /* we don't expect label compression in QNAMEs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900600 if (c >= 64) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900601
602 if (first)
603 first = 0;
604 else
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900605 bp = bprint_c(bp, bend, '.');
Bernie Innocenti55864192018-08-30 04:05:20 +0900606
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900607 bp = bprint_b(bp, bend, (const char*) p, c);
Bernie Innocenti55864192018-08-30 04:05:20 +0900608
609 p += c;
610 /* we rely on the bound check at the start
611 * of the loop here */
612 }
613 /* malformed data */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900614 bp = bprint_s(bp, bend, "<MALFORMED>");
Bernie Innocenti55864192018-08-30 04:05:20 +0900615 return bp;
616}
617
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900618static char* dnsPacket_bprintQR(DnsPacket* packet, char* p, char* end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900619#define QQ(x) \
620 { DNS_TYPE_##x, #x }
Bernie Innocenti55864192018-08-30 04:05:20 +0900621 static const struct {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900622 const char* typeBytes;
623 const char* typeString;
624 } qTypes[] = {QQ(A), QQ(PTR), QQ(MX), QQ(AAAA), QQ(ALL), {NULL, NULL}};
625 int nn;
626 const char* typeString = NULL;
Bernie Innocenti55864192018-08-30 04:05:20 +0900627
628 /* dump QNAME */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900629 p = dnsPacket_bprintQName(packet, p, end);
Bernie Innocenti55864192018-08-30 04:05:20 +0900630
631 /* dump TYPE */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900632 p = bprint_s(p, end, " (");
Bernie Innocenti55864192018-08-30 04:05:20 +0900633
634 for (nn = 0; qTypes[nn].typeBytes != NULL; nn++) {
635 if (_dnsPacket_checkBytes(packet, 2, qTypes[nn].typeBytes)) {
636 typeString = qTypes[nn].typeString;
637 break;
638 }
639 }
640
641 if (typeString != NULL)
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900642 p = bprint_s(p, end, typeString);
Bernie Innocenti55864192018-08-30 04:05:20 +0900643 else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900644 int typeCode = _dnsPacket_readInt16(packet);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900645 p = bprint(p, end, "UNKNOWN-%d", typeCode);
Bernie Innocenti55864192018-08-30 04:05:20 +0900646 }
647
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900648 p = bprint_c(p, end, ')');
Bernie Innocenti55864192018-08-30 04:05:20 +0900649
650 /* skip CLASS */
651 _dnsPacket_skip(packet, 2);
652 return p;
653}
654
655/* this function assumes the packet has already been checked */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900656static char* dnsPacket_bprintQuery(DnsPacket* packet, char* p, char* end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900657 int qdCount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900658
659 if (packet->base[2] & 0x1) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900660 p = bprint_s(p, end, "RECURSIVE ");
Bernie Innocenti55864192018-08-30 04:05:20 +0900661 }
662
663 _dnsPacket_skip(packet, 4);
664 qdCount = _dnsPacket_readInt16(packet);
665 _dnsPacket_skip(packet, 6);
666
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900667 for (; qdCount > 0; qdCount--) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900668 p = dnsPacket_bprintQR(packet, p, end);
Bernie Innocenti55864192018-08-30 04:05:20 +0900669 }
670 return p;
671}
Bernie Innocenti55864192018-08-30 04:05:20 +0900672
Bernie Innocenti55864192018-08-30 04:05:20 +0900673/** QUERY HASHING SUPPORT
674 **
675 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKET HAS ALREADY
676 ** BEEN SUCCESFULLY CHECKED.
677 **/
678
679/* use 32-bit FNV hash function */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900680#define FNV_MULT 16777619U
681#define FNV_BASIS 2166136261U
Bernie Innocenti55864192018-08-30 04:05:20 +0900682
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900683static unsigned _dnsPacket_hashBytes(DnsPacket* packet, int numBytes, unsigned hash) {
684 const uint8_t* p = packet->cursor;
685 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900686
687 while (numBytes > 0 && p < end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900688 hash = hash * FNV_MULT ^ *p++;
Bernie Innocenti55864192018-08-30 04:05:20 +0900689 }
690 packet->cursor = p;
691 return hash;
692}
693
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900694static unsigned _dnsPacket_hashQName(DnsPacket* packet, unsigned hash) {
695 const uint8_t* p = packet->cursor;
696 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900697
698 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900699 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900700
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900701 if (p >= end) { /* should not happen */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900702 VLOG << __func__ << ": INTERNAL_ERROR: read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900703 break;
704 }
705
706 c = *p++;
707
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900708 if (c == 0) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900709
710 if (c >= 64) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900711 VLOG << __func__ << ": INTERNAL_ERROR: malformed domain";
Bernie Innocenti55864192018-08-30 04:05:20 +0900712 break;
713 }
714 if (p + c >= end) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900715 VLOG << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900716 break;
717 }
718 while (c > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900719 hash = hash * FNV_MULT ^ *p++;
720 c -= 1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900721 }
722 }
723 packet->cursor = p;
724 return hash;
725}
726
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900727static unsigned _dnsPacket_hashQR(DnsPacket* packet, unsigned hash) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900728 hash = _dnsPacket_hashQName(packet, hash);
729 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TYPE and CLASS */
730 return hash;
731}
732
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900733static unsigned _dnsPacket_hashRR(DnsPacket* packet, unsigned hash) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900734 int rdlength;
735 hash = _dnsPacket_hashQR(packet, hash);
736 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TTL */
737 rdlength = _dnsPacket_readInt16(packet);
738 hash = _dnsPacket_hashBytes(packet, rdlength, hash); /* RDATA */
739 return hash;
740}
741
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900742static unsigned _dnsPacket_hashQuery(DnsPacket* packet) {
743 unsigned hash = FNV_BASIS;
744 int count, arcount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900745 _dnsPacket_rewind(packet);
746
747 /* ignore the ID */
748 _dnsPacket_skip(packet, 2);
749
750 /* we ignore the TC bit for reasons explained in
751 * _dnsPacket_checkQuery().
752 *
753 * however we hash the RD bit to differentiate
754 * between answers for recursive and non-recursive
755 * queries.
756 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900757 hash = hash * FNV_MULT ^ (packet->base[2] & 1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900758
759 /* mark the first header byte as processed */
760 _dnsPacket_skip(packet, 1);
761
762 /* process the second header byte */
763 hash = _dnsPacket_hashBytes(packet, 1, hash);
764
765 /* read QDCOUNT */
766 count = _dnsPacket_readInt16(packet);
767
768 /* assume: ANcount and NScount are 0 */
769 _dnsPacket_skip(packet, 4);
770
771 /* read ARCOUNT */
772 arcount = _dnsPacket_readInt16(packet);
773
774 /* hash QDCOUNT QRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900775 for (; count > 0; count--) hash = _dnsPacket_hashQR(packet, hash);
Bernie Innocenti55864192018-08-30 04:05:20 +0900776
777 /* hash ARCOUNT RRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900778 for (; arcount > 0; arcount--) hash = _dnsPacket_hashRR(packet, hash);
Bernie Innocenti55864192018-08-30 04:05:20 +0900779
780 return hash;
781}
782
Bernie Innocenti55864192018-08-30 04:05:20 +0900783/** QUERY COMPARISON
784 **
785 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKETS HAVE ALREADY
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900786 ** BEEN SUCCESSFULLY CHECKED.
Bernie Innocenti55864192018-08-30 04:05:20 +0900787 **/
788
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900789static int _dnsPacket_isEqualDomainName(DnsPacket* pack1, DnsPacket* pack2) {
790 const uint8_t* p1 = pack1->cursor;
791 const uint8_t* end1 = pack1->end;
792 const uint8_t* p2 = pack2->cursor;
793 const uint8_t* end2 = pack2->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900794
795 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900796 int c1, c2;
Bernie Innocenti55864192018-08-30 04:05:20 +0900797
798 if (p1 >= end1 || p2 >= end2) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900799 VLOG << __func__ << ": INTERNAL_ERROR: read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900800 break;
801 }
802 c1 = *p1++;
803 c2 = *p2++;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900804 if (c1 != c2) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900805
806 if (c1 == 0) {
807 pack1->cursor = p1;
808 pack2->cursor = p2;
809 return 1;
810 }
811 if (c1 >= 64) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900812 VLOG << __func__ << ": INTERNAL_ERROR: malformed domain";
Bernie Innocenti55864192018-08-30 04:05:20 +0900813 break;
814 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900815 if ((p1 + c1 > end1) || (p2 + c1 > end2)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900816 VLOG << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900817 break;
818 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900819 if (memcmp(p1, p2, c1) != 0) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900820 p1 += c1;
821 p2 += c1;
822 /* we rely on the bound checks at the start of the loop */
823 }
824 /* not the same, or one is malformed */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900825 VLOG << "different DN";
Bernie Innocenti55864192018-08-30 04:05:20 +0900826 return 0;
827}
828
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900829static int _dnsPacket_isEqualBytes(DnsPacket* pack1, DnsPacket* pack2, int numBytes) {
830 const uint8_t* p1 = pack1->cursor;
831 const uint8_t* p2 = pack2->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900832
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900833 if (p1 + numBytes > pack1->end || p2 + numBytes > pack2->end) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900834
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900835 if (memcmp(p1, p2, numBytes) != 0) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900836
837 pack1->cursor += numBytes;
838 pack2->cursor += numBytes;
839 return 1;
840}
841
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900842static int _dnsPacket_isEqualQR(DnsPacket* pack1, DnsPacket* pack2) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900843 /* compare domain name encoding + TYPE + CLASS */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900844 if (!_dnsPacket_isEqualDomainName(pack1, pack2) ||
845 !_dnsPacket_isEqualBytes(pack1, pack2, 2 + 2))
Bernie Innocenti55864192018-08-30 04:05:20 +0900846 return 0;
847
848 return 1;
849}
850
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900851static int _dnsPacket_isEqualRR(DnsPacket* pack1, DnsPacket* pack2) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900852 int rdlength1, rdlength2;
853 /* compare query + TTL */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900854 if (!_dnsPacket_isEqualQR(pack1, pack2) || !_dnsPacket_isEqualBytes(pack1, pack2, 4)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900855
856 /* compare RDATA */
857 rdlength1 = _dnsPacket_readInt16(pack1);
858 rdlength2 = _dnsPacket_readInt16(pack2);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900859 if (rdlength1 != rdlength2 || !_dnsPacket_isEqualBytes(pack1, pack2, rdlength1)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900860
861 return 1;
862}
863
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900864static int _dnsPacket_isEqualQuery(DnsPacket* pack1, DnsPacket* pack2) {
865 int count1, count2, arcount1, arcount2;
Bernie Innocenti55864192018-08-30 04:05:20 +0900866
867 /* compare the headers, ignore most fields */
868 _dnsPacket_rewind(pack1);
869 _dnsPacket_rewind(pack2);
870
871 /* compare RD, ignore TC, see comment in _dnsPacket_checkQuery */
872 if ((pack1->base[2] & 1) != (pack2->base[2] & 1)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900873 VLOG << "different RD";
Bernie Innocenti55864192018-08-30 04:05:20 +0900874 return 0;
875 }
876
877 if (pack1->base[3] != pack2->base[3]) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900878 VLOG << "different CD or AD";
Bernie Innocenti55864192018-08-30 04:05:20 +0900879 return 0;
880 }
881
882 /* mark ID and header bytes as compared */
883 _dnsPacket_skip(pack1, 4);
884 _dnsPacket_skip(pack2, 4);
885
886 /* compare QDCOUNT */
887 count1 = _dnsPacket_readInt16(pack1);
888 count2 = _dnsPacket_readInt16(pack2);
889 if (count1 != count2 || count1 < 0) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900890 VLOG << "different QDCOUNT";
Bernie Innocenti55864192018-08-30 04:05:20 +0900891 return 0;
892 }
893
894 /* assume: ANcount and NScount are 0 */
895 _dnsPacket_skip(pack1, 4);
896 _dnsPacket_skip(pack2, 4);
897
898 /* compare ARCOUNT */
899 arcount1 = _dnsPacket_readInt16(pack1);
900 arcount2 = _dnsPacket_readInt16(pack2);
901 if (arcount1 != arcount2 || arcount1 < 0) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900902 VLOG << "different ARCOUNT";
Bernie Innocenti55864192018-08-30 04:05:20 +0900903 return 0;
904 }
905
906 /* compare the QDCOUNT QRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900907 for (; count1 > 0; count1--) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900908 if (!_dnsPacket_isEqualQR(pack1, pack2)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900909 VLOG << "different QR";
Bernie Innocenti55864192018-08-30 04:05:20 +0900910 return 0;
911 }
912 }
913
914 /* compare the ARCOUNT RRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900915 for (; arcount1 > 0; arcount1--) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900916 if (!_dnsPacket_isEqualRR(pack1, pack2)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900917 VLOG << "different additional RR";
Bernie Innocenti55864192018-08-30 04:05:20 +0900918 return 0;
919 }
920 }
921 return 1;
922}
923
Bernie Innocenti55864192018-08-30 04:05:20 +0900924/* cache entry. for simplicity, 'hash' and 'hlink' are inlined in this
925 * structure though they are conceptually part of the hash table.
926 *
927 * similarly, mru_next and mru_prev are part of the global MRU list
928 */
929typedef struct Entry {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900930 unsigned int hash; /* hash value */
931 struct Entry* hlink; /* next in collision chain */
932 struct Entry* mru_prev;
933 struct Entry* mru_next;
Bernie Innocenti55864192018-08-30 04:05:20 +0900934
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900935 const uint8_t* query;
936 int querylen;
937 const uint8_t* answer;
938 int answerlen;
939 time_t expires; /* time_t when the entry isn't valid any more */
940 int id; /* for debugging purpose */
Bernie Innocenti55864192018-08-30 04:05:20 +0900941} Entry;
942
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900943/*
Bernie Innocenti55864192018-08-30 04:05:20 +0900944 * Find the TTL for a negative DNS result. This is defined as the minimum
945 * of the SOA records TTL and the MINIMUM-TTL field (RFC-2308).
946 *
947 * Return 0 if not found.
948 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900949static u_long answer_getNegativeTTL(ns_msg handle) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900950 int n, nscount;
951 u_long result = 0;
952 ns_rr rr;
953
954 nscount = ns_msg_count(handle, ns_s_ns);
955 for (n = 0; n < nscount; n++) {
956 if ((ns_parserr(&handle, ns_s_ns, n, &rr) == 0) && (ns_rr_type(rr) == ns_t_soa)) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900957 const u_char* rdata = ns_rr_rdata(rr); // find the data
958 const u_char* edata = rdata + ns_rr_rdlen(rr); // add the len to find the end
Bernie Innocenti55864192018-08-30 04:05:20 +0900959 int len;
960 u_long ttl, rec_result = ns_rr_ttl(rr);
961
962 // find the MINIMUM-TTL field from the blob of binary data for this record
963 // skip the server name
964 len = dn_skipname(rdata, edata);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900965 if (len == -1) continue; // error skipping
Bernie Innocenti55864192018-08-30 04:05:20 +0900966 rdata += len;
967
968 // skip the admin name
969 len = dn_skipname(rdata, edata);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900970 if (len == -1) continue; // error skipping
Bernie Innocenti55864192018-08-30 04:05:20 +0900971 rdata += len;
972
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900973 if (edata - rdata != 5 * NS_INT32SZ) continue;
Bernie Innocenti55864192018-08-30 04:05:20 +0900974 // skip: serial number + refresh interval + retry interval + expiry
975 rdata += NS_INT32SZ * 4;
976 // finally read the MINIMUM TTL
977 ttl = ns_get32(rdata);
978 if (ttl < rec_result) {
979 rec_result = ttl;
980 }
981 // Now that the record is read successfully, apply the new min TTL
982 if (n == 0 || rec_result < result) {
983 result = rec_result;
984 }
985 }
986 }
987 return result;
988}
989
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900990/*
Bernie Innocenti55864192018-08-30 04:05:20 +0900991 * Parse the answer records and find the appropriate
992 * smallest TTL among the records. This might be from
993 * the answer records if found or from the SOA record
994 * if it's a negative result.
995 *
996 * The returned TTL is the number of seconds to
997 * keep the answer in the cache.
998 *
999 * In case of parse error zero (0) is returned which
1000 * indicates that the answer shall not be cached.
1001 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001002static u_long answer_getTTL(const void* answer, int answerlen) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001003 ns_msg handle;
1004 int ancount, n;
1005 u_long result, ttl;
1006 ns_rr rr;
1007
1008 result = 0;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001009 if (ns_initparse((const uint8_t*) answer, answerlen, &handle) >= 0) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001010 // get number of answer records
1011 ancount = ns_msg_count(handle, ns_s_an);
1012
1013 if (ancount == 0) {
1014 // a response with no answers? Cache this negative result.
1015 result = answer_getNegativeTTL(handle);
1016 } else {
1017 for (n = 0; n < ancount; n++) {
1018 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
1019 ttl = ns_rr_ttl(rr);
1020 if (n == 0 || ttl < result) {
1021 result = ttl;
1022 }
1023 } else {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001024 VLOG << "ns_parserr failed ancount no = "
1025 << n << ". errno = " << strerror(errno);
Bernie Innocenti55864192018-08-30 04:05:20 +09001026 }
1027 }
1028 }
1029 } else {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001030 VLOG << "ns_initparse failed: " << strerror(errno);
Bernie Innocenti55864192018-08-30 04:05:20 +09001031 }
1032
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001033 VLOG << "TTL = " << result;
Bernie Innocenti55864192018-08-30 04:05:20 +09001034 return result;
1035}
1036
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001037static void entry_free(Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001038 /* everything is allocated in a single memory block */
1039 if (e) {
1040 free(e);
1041 }
1042}
1043
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001044static void entry_mru_remove(Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001045 e->mru_prev->mru_next = e->mru_next;
1046 e->mru_next->mru_prev = e->mru_prev;
1047}
1048
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001049static void entry_mru_add(Entry* e, Entry* list) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001050 Entry* first = list->mru_next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001051
1052 e->mru_next = first;
1053 e->mru_prev = list;
1054
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001055 list->mru_next = e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001056 first->mru_prev = e;
1057}
1058
1059/* compute the hash of a given entry, this is a hash of most
1060 * data in the query (key) */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001061static unsigned entry_hash(const Entry* e) {
1062 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001063
1064 _dnsPacket_init(pack, e->query, e->querylen);
1065 return _dnsPacket_hashQuery(pack);
1066}
1067
1068/* initialize an Entry as a search key, this also checks the input query packet
1069 * returns 1 on success, or 0 in case of unsupported/malformed data */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001070static int entry_init_key(Entry* e, const void* query, int querylen) {
1071 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001072
1073 memset(e, 0, sizeof(*e));
1074
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001075 e->query = (const uint8_t*) query;
Bernie Innocenti55864192018-08-30 04:05:20 +09001076 e->querylen = querylen;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001077 e->hash = entry_hash(e);
Bernie Innocenti55864192018-08-30 04:05:20 +09001078
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001079 _dnsPacket_init(pack, e->query, e->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001080
1081 return _dnsPacket_checkQuery(pack);
1082}
1083
1084/* allocate a new entry as a cache node */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001085static Entry* entry_alloc(const Entry* init, const void* answer, int answerlen) {
1086 Entry* e;
1087 int size;
Bernie Innocenti55864192018-08-30 04:05:20 +09001088
1089 size = sizeof(*e) + init->querylen + answerlen;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001090 e = (Entry*) calloc(size, 1);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001091 if (e == NULL) return e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001092
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001093 e->hash = init->hash;
1094 e->query = (const uint8_t*) (e + 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001095 e->querylen = init->querylen;
1096
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001097 memcpy((char*) e->query, init->query, e->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001098
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001099 e->answer = e->query + e->querylen;
Bernie Innocenti55864192018-08-30 04:05:20 +09001100 e->answerlen = answerlen;
1101
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001102 memcpy((char*) e->answer, answer, e->answerlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001103
1104 return e;
1105}
1106
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001107static int entry_equals(const Entry* e1, const Entry* e2) {
1108 DnsPacket pack1[1], pack2[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001109
1110 if (e1->querylen != e2->querylen) {
1111 return 0;
1112 }
1113 _dnsPacket_init(pack1, e1->query, e1->querylen);
1114 _dnsPacket_init(pack2, e2->query, e2->querylen);
1115
1116 return _dnsPacket_isEqualQuery(pack1, pack2);
1117}
1118
Bernie Innocenti55864192018-08-30 04:05:20 +09001119/* We use a simple hash table with external collision lists
1120 * for simplicity, the hash-table fields 'hash' and 'hlink' are
1121 * inlined in the Entry structure.
1122 */
1123
1124/* Maximum time for a thread to wait for an pending request */
1125#define PENDING_REQUEST_TIMEOUT 20;
1126
1127typedef struct pending_req_info {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001128 unsigned int hash;
1129 pthread_cond_t cond;
1130 struct pending_req_info* next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001131} PendingReqInfo;
1132
1133typedef struct resolv_cache {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001134 int max_entries;
1135 int num_entries;
1136 Entry mru_list;
1137 int last_id;
1138 Entry* entries;
1139 PendingReqInfo pending_requests;
Bernie Innocenti55864192018-08-30 04:05:20 +09001140} Cache;
1141
1142struct resolv_cache_info {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001143 unsigned netid;
1144 Cache* cache;
1145 struct resolv_cache_info* next;
1146 int nscount;
1147 char* nameservers[MAXNS];
1148 struct addrinfo* nsaddrinfo[MAXNS];
1149 int revision_id; // # times the nameservers have been replaced
1150 struct __res_params params;
Bernie Innocenti189eb502018-10-01 23:10:18 +09001151 struct res_stats nsstats[MAXNS];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001152 char defdname[MAXDNSRCHPATH];
1153 int dnsrch_offset[MAXDNSRCH + 1]; // offsets into defdname
Bernie Innocenti55864192018-08-30 04:05:20 +09001154};
1155
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001156static pthread_once_t _res_cache_once = PTHREAD_ONCE_INIT;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001157static void res_cache_init(void);
Bernie Innocenti55864192018-08-30 04:05:20 +09001158
1159// lock protecting everything in the _resolve_cache_info structs (next ptr, etc)
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001160static pthread_mutex_t res_cache_list_lock;
Bernie Innocenti55864192018-08-30 04:05:20 +09001161
1162/* gets cache associated with a network, or NULL if none exists */
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001163static struct resolv_cache* find_named_cache_locked(unsigned netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001164
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001165static void _cache_flush_pending_requests_locked(struct resolv_cache* cache) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001166 struct pending_req_info *ri, *tmp;
1167 if (cache) {
1168 ri = cache->pending_requests.next;
1169
1170 while (ri) {
1171 tmp = ri;
1172 ri = ri->next;
1173 pthread_cond_broadcast(&tmp->cond);
1174
1175 pthread_cond_destroy(&tmp->cond);
1176 free(tmp);
1177 }
1178
1179 cache->pending_requests.next = NULL;
1180 }
1181}
1182
1183/* Return 0 if no pending request is found matching the key.
1184 * If a matching request is found the calling thread will wait until
1185 * the matching request completes, then update *cache and return 1. */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001186static int _cache_check_pending_request_locked(struct resolv_cache** cache, Entry* key,
1187 unsigned netid) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001188 struct pending_req_info *ri, *prev;
1189 int exist = 0;
1190
1191 if (*cache && key) {
1192 ri = (*cache)->pending_requests.next;
1193 prev = &(*cache)->pending_requests;
1194 while (ri) {
1195 if (ri->hash == key->hash) {
1196 exist = 1;
1197 break;
1198 }
1199 prev = ri;
1200 ri = ri->next;
1201 }
1202
1203 if (!exist) {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001204 ri = (struct pending_req_info*) calloc(1, sizeof(struct pending_req_info));
Bernie Innocenti55864192018-08-30 04:05:20 +09001205 if (ri) {
1206 ri->hash = key->hash;
1207 pthread_cond_init(&ri->cond, NULL);
1208 prev->next = ri;
1209 }
1210 } else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001211 struct timespec ts = {0, 0};
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001212 VLOG << "Waiting for previous request";
Bernie Innocenti55864192018-08-30 04:05:20 +09001213 ts.tv_sec = _time_now() + PENDING_REQUEST_TIMEOUT;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001214 pthread_cond_timedwait(&ri->cond, &res_cache_list_lock, &ts);
Bernie Innocenti55864192018-08-30 04:05:20 +09001215 /* Must update *cache as it could have been deleted. */
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001216 *cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001217 }
1218 }
1219
1220 return exist;
1221}
1222
1223/* notify any waiting thread that waiting on a request
1224 * matching the key has been added to the cache */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001225static void _cache_notify_waiting_tid_locked(struct resolv_cache* cache, Entry* key) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001226 struct pending_req_info *ri, *prev;
1227
1228 if (cache && key) {
1229 ri = cache->pending_requests.next;
1230 prev = &cache->pending_requests;
1231 while (ri) {
1232 if (ri->hash == key->hash) {
1233 pthread_cond_broadcast(&ri->cond);
1234 break;
1235 }
1236 prev = ri;
1237 ri = ri->next;
1238 }
1239
1240 // remove item from list and destroy
1241 if (ri) {
1242 prev->next = ri->next;
1243 pthread_cond_destroy(&ri->cond);
1244 free(ri);
1245 }
1246 }
1247}
1248
1249/* notify the cache that the query failed */
Luke Huang952d0942018-12-26 16:53:03 +08001250void _resolv_cache_query_failed(unsigned netid, const void* query, int querylen, uint32_t flags) {
1251 // We should not notify with these flags.
1252 if (flags & (ANDROID_RESOLV_NO_CACHE_STORE | ANDROID_RESOLV_NO_CACHE_LOOKUP)) {
1253 return;
1254 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001255 Entry key[1];
1256 Cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001257
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001258 if (!entry_init_key(key, query, querylen)) return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001259
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001260 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001261
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001262 cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001263
1264 if (cache) {
1265 _cache_notify_waiting_tid_locked(cache, key);
1266 }
1267
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001268 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001269}
1270
ckenb1a69a42018-12-01 17:45:18 +09001271static resolv_cache_info* find_cache_info_locked(unsigned netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001272
Bernie Innocentid2b27032018-12-18 19:53:42 +09001273static void cache_flush_locked(Cache* cache) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001274 int nn;
Bernie Innocenti55864192018-08-30 04:05:20 +09001275
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001276 for (nn = 0; nn < cache->max_entries; nn++) {
1277 Entry** pnode = (Entry**) &cache->entries[nn];
Bernie Innocenti55864192018-08-30 04:05:20 +09001278
1279 while (*pnode != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001280 Entry* node = *pnode;
Bernie Innocenti55864192018-08-30 04:05:20 +09001281 *pnode = node->hlink;
1282 entry_free(node);
1283 }
1284 }
1285
1286 // flush pending request
1287 _cache_flush_pending_requests_locked(cache);
1288
1289 cache->mru_list.mru_next = cache->mru_list.mru_prev = &cache->mru_list;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001290 cache->num_entries = 0;
1291 cache->last_id = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +09001292
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001293 VLOG << "*** DNS CACHE FLUSHED ***";
Bernie Innocenti55864192018-08-30 04:05:20 +09001294}
1295
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001296static struct resolv_cache* _resolv_cache_create(void) {
1297 struct resolv_cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001298
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001299 cache = (struct resolv_cache*) calloc(sizeof(*cache), 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001300 if (cache) {
nuccachen989d2232018-11-29 17:41:12 +08001301 cache->max_entries = CONFIG_MAX_ENTRIES;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001302 cache->entries = (Entry*) calloc(sizeof(*cache->entries), cache->max_entries);
Bernie Innocenti55864192018-08-30 04:05:20 +09001303 if (cache->entries) {
1304 cache->mru_list.mru_prev = cache->mru_list.mru_next = &cache->mru_list;
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001305 VLOG << __func__ << ": cache created";
Bernie Innocenti55864192018-08-30 04:05:20 +09001306 } else {
1307 free(cache);
1308 cache = NULL;
1309 }
1310 }
1311 return cache;
1312}
1313
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001314static void dump_query(const uint8_t* query, int querylen) {
1315 if (!kVerboseLogging) return;
1316
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001317 char temp[256], *p = temp, *end = p + sizeof(temp);
1318 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001319
1320 _dnsPacket_init(pack, query, querylen);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001321 p = dnsPacket_bprintQuery(pack, p, end);
1322 VLOG << temp;
Bernie Innocenti55864192018-08-30 04:05:20 +09001323}
1324
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001325static void cache_dump_mru(Cache* cache) {
1326 if (!kVerboseLogging) return;
1327
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001328 char temp[512], *p = temp, *end = p + sizeof(temp);
1329 Entry* e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001330
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001331 p = bprint(temp, end, "MRU LIST (%2d): ", cache->num_entries);
Bernie Innocenti55864192018-08-30 04:05:20 +09001332 for (e = cache->mru_list.mru_next; e != &cache->mru_list; e = e->mru_next)
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001333 p = bprint(p, end, " %d", e->id);
Bernie Innocenti55864192018-08-30 04:05:20 +09001334
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001335 VLOG << temp;
Bernie Innocenti55864192018-08-30 04:05:20 +09001336}
1337
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001338// TODO: Rewrite to avoid creating a file in /data as temporary buffer (WAT).
1339static void dump_answer(const u_char* answer, int answerlen) {
1340 if (!kVerboseLogging) return;
1341
Bernie Innocenti55864192018-08-30 04:05:20 +09001342 res_state statep;
1343 FILE* fp;
1344 char* buf;
1345 int fileLen;
1346
1347 fp = fopen("/data/reslog.txt", "w+e");
1348 if (fp != NULL) {
Bernie Innocenti4acba1a2018-09-26 11:52:04 +09001349 statep = res_get_state();
Bernie Innocenti55864192018-08-30 04:05:20 +09001350
1351 res_pquery(statep, answer, answerlen, fp);
1352
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001353 // Get file length
Bernie Innocenti55864192018-08-30 04:05:20 +09001354 fseek(fp, 0, SEEK_END);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001355 fileLen = ftell(fp);
Bernie Innocenti55864192018-08-30 04:05:20 +09001356 fseek(fp, 0, SEEK_SET);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001357 buf = (char*) malloc(fileLen + 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001358 if (buf != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001359 // Read file contents into buffer
Bernie Innocenti55864192018-08-30 04:05:20 +09001360 fread(buf, fileLen, 1, fp);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001361 VLOG << buf;
Bernie Innocenti55864192018-08-30 04:05:20 +09001362 free(buf);
1363 }
1364 fclose(fp);
1365 remove("/data/reslog.txt");
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001366 } else {
1367 errno = 0; // else debug is introducing error signals
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001368 VLOG << __func__ << ": can't open file";
Bernie Innocenti55864192018-08-30 04:05:20 +09001369 }
1370}
Bernie Innocenti55864192018-08-30 04:05:20 +09001371
1372/* This function tries to find a key within the hash table
1373 * In case of success, it will return a *pointer* to the hashed key.
1374 * In case of failure, it will return a *pointer* to NULL
1375 *
1376 * So, the caller must check '*result' to check for success/failure.
1377 *
1378 * The main idea is that the result can later be used directly in
1379 * calls to _resolv_cache_add or _resolv_cache_remove as the 'lookup'
1380 * parameter. This makes the code simpler and avoids re-searching
1381 * for the key position in the htable.
1382 *
1383 * The result of a lookup_p is only valid until you alter the hash
1384 * table.
1385 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001386static Entry** _cache_lookup_p(Cache* cache, Entry* key) {
1387 int index = key->hash % cache->max_entries;
1388 Entry** pnode = (Entry**) &cache->entries[index];
Bernie Innocenti55864192018-08-30 04:05:20 +09001389
1390 while (*pnode != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001391 Entry* node = *pnode;
Bernie Innocenti55864192018-08-30 04:05:20 +09001392
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001393 if (node == NULL) break;
Bernie Innocenti55864192018-08-30 04:05:20 +09001394
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001395 if (node->hash == key->hash && entry_equals(node, key)) break;
Bernie Innocenti55864192018-08-30 04:05:20 +09001396
1397 pnode = &node->hlink;
1398 }
1399 return pnode;
1400}
1401
1402/* Add a new entry to the hash table. 'lookup' must be the
1403 * result of an immediate previous failed _lookup_p() call
1404 * (i.e. with *lookup == NULL), and 'e' is the pointer to the
1405 * newly created entry
1406 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001407static void _cache_add_p(Cache* cache, Entry** lookup, Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001408 *lookup = e;
1409 e->id = ++cache->last_id;
1410 entry_mru_add(e, &cache->mru_list);
1411 cache->num_entries += 1;
1412
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001413 VLOG << __func__ << ": entry " << e->id << " added (count=" << cache->num_entries << ")";
Bernie Innocenti55864192018-08-30 04:05:20 +09001414}
1415
1416/* Remove an existing entry from the hash table,
1417 * 'lookup' must be the result of an immediate previous
1418 * and succesful _lookup_p() call.
1419 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001420static void _cache_remove_p(Cache* cache, Entry** lookup) {
1421 Entry* e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001422
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001423 VLOG << __func__ << ": entry " << e->id << " removed (count=" << cache->num_entries - 1 << ")";
Bernie Innocenti55864192018-08-30 04:05:20 +09001424
1425 entry_mru_remove(e);
1426 *lookup = e->hlink;
1427 entry_free(e);
1428 cache->num_entries -= 1;
1429}
1430
1431/* Remove the oldest entry from the hash table.
1432 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001433static void _cache_remove_oldest(Cache* cache) {
1434 Entry* oldest = cache->mru_list.mru_prev;
1435 Entry** lookup = _cache_lookup_p(cache, oldest);
Bernie Innocenti55864192018-08-30 04:05:20 +09001436
1437 if (*lookup == NULL) { /* should not happen */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001438 VLOG << __func__ << ": OLDEST NOT IN HTABLE ?";
Bernie Innocenti55864192018-08-30 04:05:20 +09001439 return;
1440 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001441 VLOG << "Cache full - removing oldest";
1442 dump_query(oldest->query, oldest->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001443 _cache_remove_p(cache, lookup);
1444}
1445
1446/* Remove all expired entries from the hash table.
1447 */
1448static void _cache_remove_expired(Cache* cache) {
1449 Entry* e;
1450 time_t now = _time_now();
1451
1452 for (e = cache->mru_list.mru_next; e != &cache->mru_list;) {
1453 // Entry is old, remove
1454 if (now >= e->expires) {
1455 Entry** lookup = _cache_lookup_p(cache, e);
1456 if (*lookup == NULL) { /* should not happen */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001457 VLOG << __func__ << ": ENTRY NOT IN HTABLE ?";
Bernie Innocenti55864192018-08-30 04:05:20 +09001458 return;
1459 }
1460 e = e->mru_next;
1461 _cache_remove_p(cache, lookup);
1462 } else {
1463 e = e->mru_next;
1464 }
1465 }
1466}
1467
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001468ResolvCacheStatus _resolv_cache_lookup(unsigned netid, const void* query, int querylen,
Luke Huang952d0942018-12-26 16:53:03 +08001469 void* answer, int answersize, int* answerlen,
1470 uint32_t flags) {
1471 if (flags & ANDROID_RESOLV_NO_CACHE_LOOKUP) {
1472 return RESOLV_CACHE_SKIP;
1473 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001474 Entry key[1];
1475 Entry** lookup;
1476 Entry* e;
1477 time_t now;
1478 Cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001479
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001480 ResolvCacheStatus result = RESOLV_CACHE_NOTFOUND;
Bernie Innocenti55864192018-08-30 04:05:20 +09001481
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001482 VLOG << __func__ << ": lookup";
1483 dump_query((u_char*) query, querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001484
1485 /* we don't cache malformed queries */
1486 if (!entry_init_key(key, query, querylen)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001487 VLOG << __func__ << ": unsupported query";
Bernie Innocenti55864192018-08-30 04:05:20 +09001488 return RESOLV_CACHE_UNSUPPORTED;
1489 }
1490 /* lookup cache */
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001491 pthread_once(&_res_cache_once, res_cache_init);
1492 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001493
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001494 cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001495 if (cache == NULL) {
1496 result = RESOLV_CACHE_UNSUPPORTED;
1497 goto Exit;
1498 }
1499
1500 /* see the description of _lookup_p to understand this.
1501 * the function always return a non-NULL pointer.
1502 */
1503 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001504 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001505
1506 if (e == NULL) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001507 VLOG << "NOT IN CACHE";
Luke Huang952d0942018-12-26 16:53:03 +08001508 // If it is no-cache-store mode, we won't wait for possible query.
1509 if (flags & ANDROID_RESOLV_NO_CACHE_STORE) {
1510 result = RESOLV_CACHE_SKIP;
1511 goto Exit;
1512 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001513 // calling thread will wait if an outstanding request is found
1514 // that matching this query
1515 if (!_cache_check_pending_request_locked(&cache, key, netid) || cache == NULL) {
1516 goto Exit;
1517 } else {
1518 lookup = _cache_lookup_p(cache, key);
1519 e = *lookup;
1520 if (e == NULL) {
1521 goto Exit;
1522 }
1523 }
1524 }
1525
1526 now = _time_now();
1527
1528 /* remove stale entries here */
1529 if (now >= e->expires) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001530 VLOG << " NOT IN CACHE (STALE ENTRY " << *lookup << "DISCARDED)";
1531 dump_query(e->query, e->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001532 _cache_remove_p(cache, lookup);
1533 goto Exit;
1534 }
1535
1536 *answerlen = e->answerlen;
1537 if (e->answerlen > answersize) {
1538 /* NOTE: we return UNSUPPORTED if the answer buffer is too short */
1539 result = RESOLV_CACHE_UNSUPPORTED;
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001540 VLOG << " ANSWER TOO LONG";
Bernie Innocenti55864192018-08-30 04:05:20 +09001541 goto Exit;
1542 }
1543
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001544 memcpy(answer, e->answer, e->answerlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001545
1546 /* bump up this entry to the top of the MRU list */
1547 if (e != cache->mru_list.mru_next) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001548 entry_mru_remove(e);
1549 entry_mru_add(e, &cache->mru_list);
Bernie Innocenti55864192018-08-30 04:05:20 +09001550 }
1551
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001552 VLOG << "FOUND IN CACHE entry=" << e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001553 result = RESOLV_CACHE_FOUND;
1554
1555Exit:
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001556 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001557 return result;
1558}
1559
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001560void _resolv_cache_add(unsigned netid, const void* query, int querylen, const void* answer,
1561 int answerlen) {
1562 Entry key[1];
1563 Entry* e;
1564 Entry** lookup;
1565 u_long ttl;
1566 Cache* cache = NULL;
Bernie Innocenti55864192018-08-30 04:05:20 +09001567
1568 /* don't assume that the query has already been cached
1569 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001570 if (!entry_init_key(key, query, querylen)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001571 VLOG << __func__ << ": passed invalid query?";
Bernie Innocenti55864192018-08-30 04:05:20 +09001572 return;
1573 }
1574
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001575 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001576
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001577 cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001578 if (cache == NULL) {
1579 goto Exit;
1580 }
1581
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001582 VLOG << __func__ << ": query:";
1583 dump_query((u_char*) query, querylen);
1584 dump_answer((u_char*) answer, answerlen);
1585 if (kDumpData) {
1586 VLOG << "answer:";
1587 dump_bytes((u_char*) answer, answerlen);
1588 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001589
1590 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001591 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001592
1593 if (e != NULL) { /* should not happen */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001594 VLOG << __func__ << ": ALREADY IN CACHE (" << e << ") ? IGNORING ADD";
Bernie Innocenti55864192018-08-30 04:05:20 +09001595 goto Exit;
1596 }
1597
1598 if (cache->num_entries >= cache->max_entries) {
1599 _cache_remove_expired(cache);
1600 if (cache->num_entries >= cache->max_entries) {
1601 _cache_remove_oldest(cache);
1602 }
1603 /* need to lookup again */
1604 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001605 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001606 if (e != NULL) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001607 VLOG << __func__ << ": ALREADY IN CACHE (" << e << ") ? IGNORING ADD";
Bernie Innocenti55864192018-08-30 04:05:20 +09001608 goto Exit;
1609 }
1610 }
1611
1612 ttl = answer_getTTL(answer, answerlen);
1613 if (ttl > 0) {
1614 e = entry_alloc(key, answer, answerlen);
1615 if (e != NULL) {
1616 e->expires = ttl + _time_now();
1617 _cache_add_p(cache, lookup, e);
1618 }
1619 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001620 cache_dump_mru(cache);
1621
Bernie Innocenti55864192018-08-30 04:05:20 +09001622Exit:
1623 if (cache != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001624 _cache_notify_waiting_tid_locked(cache, key);
Bernie Innocenti55864192018-08-30 04:05:20 +09001625 }
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001626 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001627}
1628
Bernie Innocenti55864192018-08-30 04:05:20 +09001629// Head of the list of caches. Protected by _res_cache_list_lock.
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001630static struct resolv_cache_info res_cache_list;
Bernie Innocenti55864192018-08-30 04:05:20 +09001631
ckenb1a69a42018-12-01 17:45:18 +09001632// insert resolv_cache_info into the list of resolv_cache_infos
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001633static void insert_cache_info_locked(resolv_cache_info* cache_info);
ckenb1a69a42018-12-01 17:45:18 +09001634// creates a resolv_cache_info
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001635static resolv_cache_info* create_cache_info();
ckenb1a69a42018-12-01 17:45:18 +09001636// gets a resolv_cache_info associated with a network, or NULL if not found
1637static resolv_cache_info* find_cache_info_locked(unsigned netid);
ckenb1a69a42018-12-01 17:45:18 +09001638// empty the nameservers set for the named cache
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001639static void free_nameservers_locked(resolv_cache_info* cache_info);
1640// return 1 if the provided list of name servers differs from the list of name servers
1641// currently attached to the provided cache_info
1642static int resolv_is_nameservers_equal_locked(resolv_cache_info* cache_info, const char** servers,
1643 int numservers);
ckenb1a69a42018-12-01 17:45:18 +09001644// clears the stats samples contained withing the given cache_info
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001645static void res_cache_clear_stats_locked(resolv_cache_info* cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001646
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001647static void res_cache_init(void) {
1648 memset(&res_cache_list, 0, sizeof(res_cache_list));
1649 pthread_mutex_init(&res_cache_list_lock, NULL);
Bernie Innocenti55864192018-08-30 04:05:20 +09001650}
1651
ckenb1a69a42018-12-01 17:45:18 +09001652// public API for netd to query if name server is set on specific netid
1653bool resolv_has_nameservers(unsigned netid) {
1654 pthread_once(&_res_cache_once, res_cache_init);
1655 pthread_mutex_lock(&res_cache_list_lock);
1656 resolv_cache_info* info = find_cache_info_locked(netid);
1657 const bool ret = (info != nullptr) && (info->nscount > 0);
1658 pthread_mutex_unlock(&res_cache_list_lock);
1659
1660 return ret;
1661}
1662
1663// look up the named cache, and creates one if needed
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001664static resolv_cache* get_res_cache_for_net_locked(unsigned netid) {
1665 resolv_cache* cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001666 if (!cache) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001667 resolv_cache_info* cache_info = create_cache_info();
Bernie Innocenti55864192018-08-30 04:05:20 +09001668 if (cache_info) {
1669 cache = _resolv_cache_create();
1670 if (cache) {
1671 cache_info->cache = cache;
1672 cache_info->netid = netid;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001673 insert_cache_info_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001674 } else {
1675 free(cache_info);
1676 }
1677 }
1678 }
1679 return cache;
1680}
1681
Bernie Innocenti189eb502018-10-01 23:10:18 +09001682void resolv_delete_cache_for_net(unsigned netid) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001683 pthread_once(&_res_cache_once, res_cache_init);
1684 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001685
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001686 struct resolv_cache_info* prev_cache_info = &res_cache_list;
Bernie Innocenti55864192018-08-30 04:05:20 +09001687
1688 while (prev_cache_info->next) {
1689 struct resolv_cache_info* cache_info = prev_cache_info->next;
1690
1691 if (cache_info->netid == netid) {
1692 prev_cache_info->next = cache_info->next;
Bernie Innocentid2b27032018-12-18 19:53:42 +09001693 cache_flush_locked(cache_info->cache);
Bernie Innocenti55864192018-08-30 04:05:20 +09001694 free(cache_info->cache->entries);
1695 free(cache_info->cache);
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001696 free_nameservers_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001697 free(cache_info);
1698 break;
1699 }
1700
1701 prev_cache_info = prev_cache_info->next;
1702 }
1703
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001704 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001705}
1706
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001707static resolv_cache_info* create_cache_info() {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001708 return (struct resolv_cache_info*) calloc(sizeof(struct resolv_cache_info), 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001709}
1710
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001711static void insert_cache_info_locked(struct resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001712 struct resolv_cache_info* last;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001713 for (last = &res_cache_list; last->next; last = last->next) {}
Bernie Innocenti55864192018-08-30 04:05:20 +09001714 last->next = cache_info;
Bernie Innocenti55864192018-08-30 04:05:20 +09001715}
1716
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001717static resolv_cache* find_named_cache_locked(unsigned netid) {
ckenb1a69a42018-12-01 17:45:18 +09001718 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001719 if (info != NULL) return info->cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001720 return NULL;
1721}
1722
ckenb1a69a42018-12-01 17:45:18 +09001723static resolv_cache_info* find_cache_info_locked(unsigned netid) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001724 struct resolv_cache_info* cache_info = res_cache_list.next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001725
1726 while (cache_info) {
1727 if (cache_info->netid == netid) {
1728 break;
1729 }
1730
1731 cache_info = cache_info->next;
1732 }
1733 return cache_info;
1734}
1735
Bernie Innocenti1fbca5c2018-10-01 20:46:20 +09001736static void resolv_set_default_params(struct __res_params* params) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001737 params->sample_validity = NSSAMPLE_VALIDITY;
1738 params->success_threshold = SUCCESS_THRESHOLD;
1739 params->min_samples = 0;
1740 params->max_samples = 0;
1741 params->base_timeout_msec = 0; // 0 = legacy algorithm
1742}
1743
Bernie Innocenti45238a12018-12-04 14:57:48 +09001744int resolv_set_nameservers_for_net(unsigned netid, const char** servers, const int numservers,
Bernie Innocenti189eb502018-10-01 23:10:18 +09001745 const char* domains, const __res_params* params) {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001746 char* cp;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001747 int* offset;
Bernie Innocenti55864192018-08-30 04:05:20 +09001748 struct addrinfo* nsaddrinfo[MAXNS];
1749
1750 if (numservers > MAXNS) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001751 VLOG << __func__ << ": numservers=" << numservers << ", MAXNS=" << MAXNS;
Bernie Innocenti55864192018-08-30 04:05:20 +09001752 return E2BIG;
1753 }
1754
1755 // Parse the addresses before actually locking or changing any state, in case there is an error.
1756 // As a side effect this also reduces the time the lock is kept.
Bernie Innocentic165ce82018-10-16 23:35:28 +09001757 char sbuf[NI_MAXSERV];
Bernie Innocenti55864192018-08-30 04:05:20 +09001758 snprintf(sbuf, sizeof(sbuf), "%u", NAMESERVER_PORT);
Bernie Innocenti45238a12018-12-04 14:57:48 +09001759 for (int i = 0; i < numservers; i++) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001760 // The addrinfo structures allocated here are freed in free_nameservers_locked().
Bernie Innocentic165ce82018-10-16 23:35:28 +09001761 const addrinfo hints = {
1762 .ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM, .ai_flags = AI_NUMERICHOST};
1763 int rt = getaddrinfo_numeric(servers[i], sbuf, hints, &nsaddrinfo[i]);
Bernie Innocenti55864192018-08-30 04:05:20 +09001764 if (rt != 0) {
Bernie Innocenti45238a12018-12-04 14:57:48 +09001765 for (int j = 0; j < i; j++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001766 freeaddrinfo(nsaddrinfo[j]);
Bernie Innocenti55864192018-08-30 04:05:20 +09001767 }
Bernie Innocentic165ce82018-10-16 23:35:28 +09001768 VLOG << __func__ << ": getaddrinfo_numeric(" << servers[i]
1769 << ") = " << gai_strerror(rt);
Bernie Innocenti55864192018-08-30 04:05:20 +09001770 return EINVAL;
1771 }
1772 }
1773
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001774 pthread_once(&_res_cache_once, res_cache_init);
1775 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001776
1777 // creates the cache if not created
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001778 get_res_cache_for_net_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001779
ckenb1a69a42018-12-01 17:45:18 +09001780 resolv_cache_info* cache_info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001781
1782 if (cache_info != NULL) {
1783 uint8_t old_max_samples = cache_info->params.max_samples;
1784 if (params != NULL) {
1785 cache_info->params = *params;
1786 } else {
Bernie Innocenti1fbca5c2018-10-01 20:46:20 +09001787 resolv_set_default_params(&cache_info->params);
Bernie Innocenti55864192018-08-30 04:05:20 +09001788 }
1789
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001790 if (!resolv_is_nameservers_equal_locked(cache_info, servers, numservers)) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001791 // free current before adding new
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001792 free_nameservers_locked(cache_info);
Bernie Innocenti45238a12018-12-04 14:57:48 +09001793 for (int i = 0; i < numservers; i++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001794 cache_info->nsaddrinfo[i] = nsaddrinfo[i];
1795 cache_info->nameservers[i] = strdup(servers[i]);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001796 VLOG << __func__ << ": netid = " << netid << ", addr = " << servers[i];
Bernie Innocenti55864192018-08-30 04:05:20 +09001797 }
1798 cache_info->nscount = numservers;
1799
1800 // Clear the NS statistics because the mapping to nameservers might have changed.
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001801 res_cache_clear_stats_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001802
1803 // increment the revision id to ensure that sample state is not written back if the
1804 // servers change; in theory it would suffice to do so only if the servers or
1805 // max_samples actually change, in practice the overhead of checking is higher than the
1806 // cost, and overflows are unlikely
1807 ++cache_info->revision_id;
Ken Chen26f01e42018-11-02 13:18:40 +08001808 } else {
1809 if (cache_info->params.max_samples != old_max_samples) {
1810 // If the maximum number of samples changes, the overhead of keeping the most recent
1811 // samples around is not considered worth the effort, so they are cleared instead.
1812 // All other parameters do not affect shared state: Changing these parameters does
1813 // not invalidate the samples, as they only affect aggregation and the conditions
1814 // under which servers are considered usable.
1815 res_cache_clear_stats_locked(cache_info);
1816 ++cache_info->revision_id;
1817 }
Bernie Innocenti45238a12018-12-04 14:57:48 +09001818 for (int j = 0; j < numservers; j++) {
Ken Chen26f01e42018-11-02 13:18:40 +08001819 freeaddrinfo(nsaddrinfo[j]);
1820 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001821 }
1822
1823 // Always update the search paths, since determining whether they actually changed is
1824 // complex due to the zero-padding, and probably not worth the effort. Cache-flushing
1825 // however is not // necessary, since the stored cache entries do contain the domain, not
1826 // just the host name.
1827 // code moved from res_init.c, load_domain_search_list
1828 strlcpy(cache_info->defdname, domains, sizeof(cache_info->defdname));
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001829 if ((cp = strchr(cache_info->defdname, '\n')) != NULL) *cp = '\0';
Bernie Innocenti55864192018-08-30 04:05:20 +09001830
1831 cp = cache_info->defdname;
1832 offset = cache_info->dnsrch_offset;
1833 while (offset < cache_info->dnsrch_offset + MAXDNSRCH) {
1834 while (*cp == ' ' || *cp == '\t') /* skip leading white space */
1835 cp++;
1836 if (*cp == '\0') /* stop if nothing more to do */
1837 break;
1838 *offset++ = cp - cache_info->defdname; /* record this search domain */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001839 while (*cp) { /* zero-terminate it */
1840 if (*cp == ' ' || *cp == '\t') {
Bernie Innocenti55864192018-08-30 04:05:20 +09001841 *cp++ = '\0';
1842 break;
1843 }
1844 cp++;
1845 }
1846 }
1847 *offset = -1; /* cache_info->dnsrch_offset has MAXDNSRCH+1 items */
1848 }
1849
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001850 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001851 return 0;
1852}
1853
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001854static int resolv_is_nameservers_equal_locked(resolv_cache_info* cache_info, const char** servers,
1855 int numservers) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001856 if (cache_info->nscount != numservers) {
1857 return 0;
1858 }
1859
1860 // Compare each name server against current name servers.
1861 // TODO: this is incorrect if the list of current or previous nameservers
1862 // contains duplicates. This does not really matter because the framework
1863 // filters out duplicates, but we should probably fix it. It's also
1864 // insensitive to the order of the nameservers; we should probably fix that
1865 // too.
1866 for (int i = 0; i < numservers; i++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001867 for (int j = 0;; j++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001868 if (j >= numservers) {
1869 return 0;
1870 }
1871 if (strcmp(cache_info->nameservers[i], servers[j]) == 0) {
1872 break;
1873 }
1874 }
1875 }
1876
1877 return 1;
1878}
1879
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001880static void free_nameservers_locked(resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001881 int i;
1882 for (i = 0; i < cache_info->nscount; i++) {
1883 free(cache_info->nameservers[i]);
1884 cache_info->nameservers[i] = NULL;
1885 if (cache_info->nsaddrinfo[i] != NULL) {
1886 freeaddrinfo(cache_info->nsaddrinfo[i]);
1887 cache_info->nsaddrinfo[i] = NULL;
1888 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001889 cache_info->nsstats[i].sample_count = cache_info->nsstats[i].sample_next = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +09001890 }
1891 cache_info->nscount = 0;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001892 res_cache_clear_stats_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001893 ++cache_info->revision_id;
1894}
1895
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001896void _resolv_populate_res_for_net(res_state statp) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001897 if (statp == NULL) {
1898 return;
1899 }
1900
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001901 pthread_once(&_res_cache_once, res_cache_init);
1902 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001903
ckenb1a69a42018-12-01 17:45:18 +09001904 resolv_cache_info* info = find_cache_info_locked(statp->netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001905 if (info != NULL) {
1906 int nserv;
1907 struct addrinfo* ai;
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001908 VLOG << __func__ << ": " << statp->netid;
Bernie Innocenti55864192018-08-30 04:05:20 +09001909 for (nserv = 0; nserv < MAXNS; nserv++) {
1910 ai = info->nsaddrinfo[nserv];
1911 if (ai == NULL) {
1912 break;
1913 }
1914
1915 if ((size_t) ai->ai_addrlen <= sizeof(statp->_u._ext.ext->nsaddrs[0])) {
1916 if (statp->_u._ext.ext != NULL) {
1917 memcpy(&statp->_u._ext.ext->nsaddrs[nserv], ai->ai_addr, ai->ai_addrlen);
1918 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
1919 } else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001920 if ((size_t) ai->ai_addrlen <= sizeof(statp->nsaddr_list[0])) {
1921 memcpy(&statp->nsaddr_list[nserv], ai->ai_addr, ai->ai_addrlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001922 } else {
1923 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
1924 }
1925 }
1926 } else {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001927 VLOG << __func__ << ": found too long addrlen";
Bernie Innocenti55864192018-08-30 04:05:20 +09001928 }
1929 }
1930 statp->nscount = nserv;
1931 // now do search domains. Note that we cache the offsets as this code runs alot
1932 // but the setting/offset-computer only runs when set/changed
1933 // WARNING: Don't use str*cpy() here, this string contains zeroes.
1934 memcpy(statp->defdname, info->defdname, sizeof(statp->defdname));
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001935 char** pp = statp->dnsrch;
1936 int* p = info->dnsrch_offset;
Bernie Innocenti55864192018-08-30 04:05:20 +09001937 while (pp < statp->dnsrch + MAXDNSRCH && *p != -1) {
1938 *pp++ = &statp->defdname[0] + *p++;
1939 }
1940 }
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001941 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001942}
1943
1944/* Resolver reachability statistics. */
1945
Bernie Innocenti189eb502018-10-01 23:10:18 +09001946static void _res_cache_add_stats_sample_locked(res_stats* stats, const res_sample* sample,
1947 int max_samples) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001948 // Note: This function expects max_samples > 0, otherwise a (harmless) modification of the
1949 // allocated but supposedly unused memory for samples[0] will happen
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001950 VLOG << __func__ << ": adding sample to stats, next = " << stats->sample_next
1951 << ", count = " << stats->sample_count;
Bernie Innocenti55864192018-08-30 04:05:20 +09001952 stats->samples[stats->sample_next] = *sample;
1953 if (stats->sample_count < max_samples) {
1954 ++stats->sample_count;
1955 }
1956 if (++stats->sample_next >= max_samples) {
1957 stats->sample_next = 0;
1958 }
1959}
1960
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001961static void res_cache_clear_stats_locked(resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001962 if (cache_info) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001963 for (int i = 0; i < MAXNS; ++i) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001964 cache_info->nsstats->sample_count = cache_info->nsstats->sample_next = 0;
1965 }
1966 }
1967}
1968
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001969int android_net_res_stats_get_info_for_net(unsigned netid, int* nscount,
1970 struct sockaddr_storage servers[MAXNS], int* dcount,
1971 char domains[MAXDNSRCH][MAXDNSRCHPATH],
1972 struct __res_params* params,
Bernie Innocenti189eb502018-10-01 23:10:18 +09001973 struct res_stats stats[MAXNS]) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001974 int revision_id = -1;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001975 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001976
ckenb1a69a42018-12-01 17:45:18 +09001977 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001978 if (info) {
1979 if (info->nscount > MAXNS) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001980 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001981 VLOG << __func__ << ": nscount " << info->nscount << " > MAXNS " << MAXNS;
Bernie Innocenti55864192018-08-30 04:05:20 +09001982 errno = EFAULT;
1983 return -1;
1984 }
1985 int i;
1986 for (i = 0; i < info->nscount; i++) {
1987 // Verify that the following assumptions are held, failure indicates corruption:
1988 // - getaddrinfo() may never return a sockaddr > sockaddr_storage
1989 // - all addresses are valid
1990 // - there is only one address per addrinfo thanks to numeric resolution
1991 int addrlen = info->nsaddrinfo[i]->ai_addrlen;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001992 if (addrlen < (int) sizeof(struct sockaddr) || addrlen > (int) sizeof(servers[0])) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001993 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001994 VLOG << __func__ << ": nsaddrinfo[" << i << "].ai_addrlen == " << addrlen;
Bernie Innocenti55864192018-08-30 04:05:20 +09001995 errno = EMSGSIZE;
1996 return -1;
1997 }
1998 if (info->nsaddrinfo[i]->ai_addr == NULL) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001999 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09002000 VLOG << __func__ << ": nsaddrinfo[" << i << "].ai_addr == NULL";
Bernie Innocenti55864192018-08-30 04:05:20 +09002001 errno = ENOENT;
2002 return -1;
2003 }
2004 if (info->nsaddrinfo[i]->ai_next != NULL) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09002005 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09002006 VLOG << __func__ << ": nsaddrinfo[" << i << "].ai_next != NULL";
Bernie Innocenti55864192018-08-30 04:05:20 +09002007 errno = ENOTUNIQ;
2008 return -1;
2009 }
2010 }
2011 *nscount = info->nscount;
2012 for (i = 0; i < info->nscount; i++) {
2013 memcpy(&servers[i], info->nsaddrinfo[i]->ai_addr, info->nsaddrinfo[i]->ai_addrlen);
2014 stats[i] = info->nsstats[i];
2015 }
2016 for (i = 0; i < MAXDNSRCH; i++) {
2017 const char* cur_domain = info->defdname + info->dnsrch_offset[i];
2018 // dnsrch_offset[i] can either be -1 or point to an empty string to indicate the end
2019 // of the search offsets. Checking for < 0 is not strictly necessary, but safer.
2020 // TODO: Pass in a search domain array instead of a string to
Bernie Innocenti189eb502018-10-01 23:10:18 +09002021 // resolv_set_nameservers_for_net() and make this double check unnecessary.
Bernie Innocenti55864192018-08-30 04:05:20 +09002022 if (info->dnsrch_offset[i] < 0 ||
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002023 ((size_t) info->dnsrch_offset[i]) >= sizeof(info->defdname) || !cur_domain[0]) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002024 break;
2025 }
2026 strlcpy(domains[i], cur_domain, MAXDNSRCHPATH);
2027 }
2028 *dcount = i;
2029 *params = info->params;
2030 revision_id = info->revision_id;
2031 }
2032
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09002033 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09002034 return revision_id;
2035}
2036
Bernie Innocenti189eb502018-10-01 23:10:18 +09002037int resolv_cache_get_resolver_stats(unsigned netid, __res_params* params, res_stats stats[MAXNS]) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002038 int revision_id = -1;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09002039 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09002040
ckenb1a69a42018-12-01 17:45:18 +09002041 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09002042 if (info) {
2043 memcpy(stats, info->nsstats, sizeof(info->nsstats));
2044 *params = info->params;
2045 revision_id = info->revision_id;
2046 }
2047
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09002048 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09002049 return revision_id;
2050}
2051
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002052void _resolv_cache_add_resolver_stats_sample(unsigned netid, int revision_id, int ns,
Bernie Innocenti189eb502018-10-01 23:10:18 +09002053 const res_sample* sample, int max_samples) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002054 if (max_samples <= 0) return;
2055
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09002056 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09002057
ckenb1a69a42018-12-01 17:45:18 +09002058 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09002059
2060 if (info && info->revision_id == revision_id) {
2061 _res_cache_add_stats_sample_locked(&info->nsstats[ns], sample, max_samples);
2062 }
2063
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09002064 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09002065}