blob: 4d131265fbf1e2c5bfd3108c8a245502182afb65 [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 Innocentif89b3512018-08-30 07:34:37 +090029#include <pthread.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090030#include <resolv.h>
31#include <stdarg.h>
32#include <stdio.h>
33#include <stdlib.h>
34#include <string.h>
35#include <time.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090036
Bernie Innocenti55864192018-08-30 04:05:20 +090037#include <arpa/nameser.h>
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090038#include <errno.h>
39#include <linux/if.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090040#include <net/if.h>
41#include <netdb.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090042
43#include <arpa/inet.h>
Bernie Innocentif89b3512018-08-30 07:34:37 +090044
Bernie Innocenti55864192018-08-30 04:05:20 +090045#include "res_private.h"
Bernie Innocentif89b3512018-08-30 07:34:37 +090046#include "resolv_cache.h"
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090047#include "resolv_netid.h"
48#include "resolv_private.h"
Bernie Innocenti55864192018-08-30 04:05:20 +090049
50#include <async_safe/log.h>
51
52/* This code implements a small and *simple* DNS resolver cache.
53 *
54 * It is only used to cache DNS answers for a time defined by the smallest TTL
55 * among the answer records in order to reduce DNS traffic. It is not supposed
56 * to be a full DNS cache, since we plan to implement that in the future in a
57 * dedicated process running on the system.
58 *
59 * Note that its design is kept simple very intentionally, i.e.:
60 *
61 * - it takes raw DNS query packet data as input, and returns raw DNS
62 * answer packet data as output
63 *
64 * (this means that two similar queries that encode the DNS name
65 * differently will be treated distinctly).
66 *
67 * the smallest TTL value among the answer records are used as the time
68 * to keep an answer in the cache.
69 *
70 * this is bad, but we absolutely want to avoid parsing the answer packets
71 * (and should be solved by the later full DNS cache process).
72 *
73 * - the implementation is just a (query-data) => (answer-data) hash table
74 * with a trivial least-recently-used expiration policy.
75 *
76 * Doing this keeps the code simple and avoids to deal with a lot of things
77 * that a full DNS cache is expected to do.
78 *
79 * The API is also very simple:
80 *
81 * - the client calls _resolv_cache_get() to obtain a handle to the cache.
82 * this will initialize the cache on first usage. the result can be NULL
83 * if the cache is disabled.
84 *
85 * - the client calls _resolv_cache_lookup() before performing a query
86 *
87 * if the function returns RESOLV_CACHE_FOUND, a copy of the answer data
88 * has been copied into the client-provided answer buffer.
89 *
90 * if the function returns RESOLV_CACHE_NOTFOUND, the client should perform
91 * a request normally, *then* call _resolv_cache_add() to add the received
92 * answer to the cache.
93 *
94 * if the function returns RESOLV_CACHE_UNSUPPORTED, the client should
95 * perform a request normally, and *not* call _resolv_cache_add()
96 *
97 * note that RESOLV_CACHE_UNSUPPORTED is also returned if the answer buffer
98 * is too short to accomodate the cached result.
99 */
100
101/* default number of entries kept in the cache. This value has been
102 * determined by browsing through various sites and counting the number
103 * of corresponding requests. Keep in mind that our framework is currently
104 * performing two requests per name lookup (one for IPv4, the other for IPv6)
105 *
106 * www.google.com 4
107 * www.ysearch.com 6
108 * www.amazon.com 8
109 * www.nytimes.com 22
110 * www.espn.com 28
111 * www.msn.com 28
112 * www.lemonde.fr 35
113 *
114 * (determined in 2009-2-17 from Paris, France, results may vary depending
115 * on location)
116 *
117 * most high-level websites use lots of media/ad servers with different names
118 * but these are generally reused when browsing through the site.
119 *
120 * As such, a value of 64 should be relatively comfortable at the moment.
121 *
122 * ******************************************
123 * * NOTE - this has changed.
124 * * 1) we've added IPv6 support so each dns query results in 2 responses
125 * * 2) we've made this a system-wide cache, so the cost is less (it's not
126 * * duplicated in each process) and the need is greater (more processes
127 * * making different requests).
128 * * Upping by 2x for IPv6
129 * * Upping by another 5x for the centralized nature
130 * *****************************************
131 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900132#define CONFIG_MAX_ENTRIES 64 * 2 * 5
Bernie Innocenti55864192018-08-30 04:05:20 +0900133
Bernie Innocenti55864192018-08-30 04:05:20 +0900134/* set to 1 to debug cache operations */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900135#define DEBUG 0
Bernie Innocenti55864192018-08-30 04:05:20 +0900136
137/* set to 1 to debug query data */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900138#define DEBUG_DATA 0
Bernie Innocenti55864192018-08-30 04:05:20 +0900139
Bernie Innocenti55864192018-08-30 04:05:20 +0900140#undef XLOG
141
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900142#define XLOG(...) \
143 ({ \
144 if (DEBUG) { \
145 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", __VA_ARGS__); \
146 } else { \
147 ((void) 0); \
148 } \
149 })
Bernie Innocenti55864192018-08-30 04:05:20 +0900150
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900151/** BOUNDED BUFFER FORMATTING **/
Bernie Innocenti55864192018-08-30 04:05:20 +0900152
153/* technical note:
154 *
155 * the following debugging routines are used to append data to a bounded
156 * buffer they take two parameters that are:
157 *
158 * - p : a pointer to the current cursor position in the buffer
159 * this value is initially set to the buffer's address.
160 *
161 * - end : the address of the buffer's limit, i.e. of the first byte
162 * after the buffer. this address should never be touched.
163 *
164 * IMPORTANT: it is assumed that end > buffer_address, i.e.
165 * that the buffer is at least one byte.
166 *
167 * the _bprint_() functions return the new value of 'p' after the data
168 * has been appended, and also ensure the following:
169 *
170 * - the returned value will never be strictly greater than 'end'
171 *
172 * - a return value equal to 'end' means that truncation occured
173 * (in which case, end[-1] will be set to 0)
174 *
175 * - after returning from a _bprint_() function, the content of the buffer
176 * is always 0-terminated, even in the event of truncation.
177 *
178 * these conventions allow you to call _bprint_ functions multiple times and
179 * only check for truncation at the end of the sequence, as in:
180 *
181 * char buff[1000], *p = buff, *end = p + sizeof(buff);
182 *
183 * p = _bprint_c(p, end, '"');
184 * p = _bprint_s(p, end, my_string);
185 * p = _bprint_c(p, end, '"');
186 *
187 * if (p >= end) {
188 * // buffer was too small
189 * }
190 *
191 * printf( "%s", buff );
192 */
193
194/* add a char to a bounded buffer */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900195static char* _bprint_c(char* p, char* end, int c) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900196 if (p < end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900197 if (p + 1 == end)
Bernie Innocenti55864192018-08-30 04:05:20 +0900198 *p++ = 0;
199 else {
200 *p++ = (char) c;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900201 *p = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900202 }
203 }
204 return p;
205}
206
207/* add a sequence of bytes to a bounded buffer */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900208static char* _bprint_b(char* p, char* end, const char* buf, int len) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900209 int avail = end - p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900210
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900211 if (avail <= 0 || len <= 0) return p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900212
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900213 if (avail > len) avail = len;
Bernie Innocenti55864192018-08-30 04:05:20 +0900214
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900215 memcpy(p, buf, avail);
Bernie Innocenti55864192018-08-30 04:05:20 +0900216 p += avail;
217
218 if (p < end)
219 p[0] = 0;
220 else
221 end[-1] = 0;
222
223 return p;
224}
225
226/* add a string to a bounded buffer */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900227static char* _bprint_s(char* p, char* end, const char* str) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900228 return _bprint_b(p, end, str, strlen(str));
229}
230
231/* add a formatted string to a bounded buffer */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900232[[maybe_unused]] static char* _bprint(char* p, char* end, const char* format, ...) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900233 int avail, n;
234 va_list args;
Bernie Innocenti55864192018-08-30 04:05:20 +0900235
236 avail = end - p;
237
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900238 if (avail <= 0) return p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900239
240 va_start(args, format);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900241 n = vsnprintf(p, avail, format, args);
Bernie Innocenti55864192018-08-30 04:05:20 +0900242 va_end(args);
243
244 /* certain C libraries return -1 in case of truncation */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900245 if (n < 0 || n > avail) n = avail;
Bernie Innocenti55864192018-08-30 04:05:20 +0900246
247 p += n;
248 /* certain C libraries do not zero-terminate in case of truncation */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900249 if (p == end) p[-1] = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900250
251 return p;
252}
253
254/* add a hex value to a bounded buffer, up to 8 digits */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900255static char* _bprint_hex(char* p, char* end, unsigned value, int numDigits) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900256 char text[sizeof(unsigned) * 2];
257 int nn = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900258
259 while (numDigits-- > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900260 text[nn++] = "0123456789abcdef"[(value >> (numDigits * 4)) & 15];
Bernie Innocenti55864192018-08-30 04:05:20 +0900261 }
262 return _bprint_b(p, end, text, nn);
263}
264
265/* add the hexadecimal dump of some memory area to a bounded buffer */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900266static char* _bprint_hexdump(char* p, char* end, const uint8_t* data, int datalen) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900267 int lineSize = 16;
Bernie Innocenti55864192018-08-30 04:05:20 +0900268
269 while (datalen > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900270 int avail = datalen;
271 int nn;
Bernie Innocenti55864192018-08-30 04:05:20 +0900272
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900273 if (avail > lineSize) avail = lineSize;
Bernie Innocenti55864192018-08-30 04:05:20 +0900274
275 for (nn = 0; nn < avail; nn++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900276 if (nn > 0) p = _bprint_c(p, end, ' ');
Bernie Innocenti55864192018-08-30 04:05:20 +0900277 p = _bprint_hex(p, end, data[nn], 2);
278 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900279 for (; nn < lineSize; nn++) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900280 p = _bprint_s(p, end, " ");
281 }
282 p = _bprint_s(p, end, " ");
283
284 for (nn = 0; nn < avail; nn++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900285 int c = data[nn];
Bernie Innocenti55864192018-08-30 04:05:20 +0900286
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900287 if (c < 32 || c > 127) c = '.';
Bernie Innocenti55864192018-08-30 04:05:20 +0900288
289 p = _bprint_c(p, end, c);
290 }
291 p = _bprint_c(p, end, '\n');
292
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900293 data += avail;
Bernie Innocenti55864192018-08-30 04:05:20 +0900294 datalen -= avail;
295 }
296 return p;
297}
298
299/* dump the content of a query of packet to the log */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900300[[maybe_unused]] static void XLOG_BYTES(const uint8_t* base, int len) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900301 if (DEBUG_DATA) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900302 char buff[1024];
303 char *p = buff, *end = p + sizeof(buff);
Bernie Innocenti55864192018-08-30 04:05:20 +0900304
305 p = _bprint_hexdump(p, end, base, len);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900306 XLOG("%s", buff);
Bernie Innocenti55864192018-08-30 04:05:20 +0900307 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900308}
Bernie Innocenti55864192018-08-30 04:05:20 +0900309
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900310static time_t _time_now(void) {
311 struct timeval tv;
Bernie Innocenti55864192018-08-30 04:05:20 +0900312
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900313 gettimeofday(&tv, NULL);
Bernie Innocenti55864192018-08-30 04:05:20 +0900314 return tv.tv_sec;
315}
316
317/* reminder: the general format of a DNS packet is the following:
318 *
319 * HEADER (12 bytes)
320 * QUESTION (variable)
321 * ANSWER (variable)
322 * AUTHORITY (variable)
323 * ADDITIONNAL (variable)
324 *
325 * the HEADER is made of:
326 *
327 * ID : 16 : 16-bit unique query identification field
328 *
329 * QR : 1 : set to 0 for queries, and 1 for responses
330 * Opcode : 4 : set to 0 for queries
331 * AA : 1 : set to 0 for queries
332 * TC : 1 : truncation flag, will be set to 0 in queries
333 * RD : 1 : recursion desired
334 *
335 * RA : 1 : recursion available (0 in queries)
336 * Z : 3 : three reserved zero bits
337 * RCODE : 4 : response code (always 0=NOERROR in queries)
338 *
339 * QDCount: 16 : question count
340 * ANCount: 16 : Answer count (0 in queries)
341 * NSCount: 16: Authority Record count (0 in queries)
342 * ARCount: 16: Additionnal Record count (0 in queries)
343 *
344 * the QUESTION is made of QDCount Question Record (QRs)
345 * the ANSWER is made of ANCount RRs
346 * the AUTHORITY is made of NSCount RRs
347 * the ADDITIONNAL is made of ARCount RRs
348 *
349 * Each Question Record (QR) is made of:
350 *
351 * QNAME : variable : Query DNS NAME
352 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
353 * CLASS : 16 : class of query (IN=1)
354 *
355 * Each Resource Record (RR) is made of:
356 *
357 * NAME : variable : DNS NAME
358 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
359 * CLASS : 16 : class of query (IN=1)
360 * TTL : 32 : seconds to cache this RR (0=none)
361 * RDLENGTH: 16 : size of RDDATA in bytes
362 * RDDATA : variable : RR data (depends on TYPE)
363 *
364 * Each QNAME contains a domain name encoded as a sequence of 'labels'
365 * terminated by a zero. Each label has the following format:
366 *
367 * LEN : 8 : lenght of label (MUST be < 64)
368 * NAME : 8*LEN : label length (must exclude dots)
369 *
370 * A value of 0 in the encoding is interpreted as the 'root' domain and
371 * terminates the encoding. So 'www.android.com' will be encoded as:
372 *
373 * <3>www<7>android<3>com<0>
374 *
375 * Where <n> represents the byte with value 'n'
376 *
377 * Each NAME reflects the QNAME of the question, but has a slightly more
378 * complex encoding in order to provide message compression. This is achieved
379 * by using a 2-byte pointer, with format:
380 *
381 * TYPE : 2 : 0b11 to indicate a pointer, 0b01 and 0b10 are reserved
382 * OFFSET : 14 : offset to another part of the DNS packet
383 *
384 * The offset is relative to the start of the DNS packet and must point
385 * A pointer terminates the encoding.
386 *
387 * The NAME can be encoded in one of the following formats:
388 *
389 * - a sequence of simple labels terminated by 0 (like QNAMEs)
390 * - a single pointer
391 * - a sequence of simple labels terminated by a pointer
392 *
393 * A pointer shall always point to either a pointer of a sequence of
394 * labels (which can themselves be terminated by either a 0 or a pointer)
395 *
396 * The expanded length of a given domain name should not exceed 255 bytes.
397 *
398 * NOTE: we don't parse the answer packets, so don't need to deal with NAME
399 * records, only QNAMEs.
400 */
401
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900402#define DNS_HEADER_SIZE 12
Bernie Innocenti55864192018-08-30 04:05:20 +0900403
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900404#define DNS_TYPE_A "\00\01" /* big-endian decimal 1 */
405#define DNS_TYPE_PTR "\00\014" /* big-endian decimal 12 */
406#define DNS_TYPE_MX "\00\017" /* big-endian decimal 15 */
407#define DNS_TYPE_AAAA "\00\034" /* big-endian decimal 28 */
408#define DNS_TYPE_ALL "\00\0377" /* big-endian decimal 255 */
Bernie Innocenti55864192018-08-30 04:05:20 +0900409
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900410#define DNS_CLASS_IN "\00\01" /* big-endian decimal 1 */
Bernie Innocenti55864192018-08-30 04:05:20 +0900411
412typedef struct {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900413 const uint8_t* base;
414 const uint8_t* end;
415 const uint8_t* cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900416} DnsPacket;
417
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900418static void _dnsPacket_init(DnsPacket* packet, const uint8_t* buff, int bufflen) {
419 packet->base = buff;
420 packet->end = buff + bufflen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900421 packet->cursor = buff;
422}
423
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900424static void _dnsPacket_rewind(DnsPacket* packet) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900425 packet->cursor = packet->base;
426}
427
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900428static void _dnsPacket_skip(DnsPacket* packet, int count) {
429 const uint8_t* p = packet->cursor + count;
Bernie Innocenti55864192018-08-30 04:05:20 +0900430
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900431 if (p > packet->end) p = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900432
433 packet->cursor = p;
434}
435
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900436static int _dnsPacket_readInt16(DnsPacket* packet) {
437 const uint8_t* p = packet->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900438
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900439 if (p + 2 > packet->end) return -1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900440
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900441 packet->cursor = p + 2;
442 return (p[0] << 8) | p[1];
Bernie Innocenti55864192018-08-30 04:05:20 +0900443}
444
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900445/** QUERY CHECKING **/
Bernie Innocenti55864192018-08-30 04:05:20 +0900446
447/* check bytes in a dns packet. returns 1 on success, 0 on failure.
448 * the cursor is only advanced in the case of success
449 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900450static int _dnsPacket_checkBytes(DnsPacket* packet, int numBytes, const void* bytes) {
451 const uint8_t* p = packet->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900452
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900453 if (p + numBytes > packet->end) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900454
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900455 if (memcmp(p, bytes, numBytes) != 0) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900456
457 packet->cursor = p + numBytes;
458 return 1;
459}
460
461/* parse and skip a given QNAME stored in a query packet,
462 * from the current cursor position. returns 1 on success,
463 * or 0 for malformed data.
464 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900465static int _dnsPacket_checkQName(DnsPacket* packet) {
466 const uint8_t* p = packet->cursor;
467 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900468
469 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900470 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900471
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900472 if (p >= end) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900473
474 c = *p++;
475
476 if (c == 0) {
477 packet->cursor = p;
478 return 1;
479 }
480
481 /* we don't expect label compression in QNAMEs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900482 if (c >= 64) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900483
484 p += c;
485 /* we rely on the bound check at the start
486 * of the loop here */
487 }
488 /* malformed data */
489 XLOG("malformed QNAME");
490 return 0;
491}
492
493/* parse and skip a given QR stored in a packet.
494 * returns 1 on success, and 0 on failure
495 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900496static int _dnsPacket_checkQR(DnsPacket* packet) {
497 if (!_dnsPacket_checkQName(packet)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900498
499 /* TYPE must be one of the things we support */
500 if (!_dnsPacket_checkBytes(packet, 2, DNS_TYPE_A) &&
501 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_PTR) &&
502 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_MX) &&
503 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_AAAA) &&
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900504 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_ALL)) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900505 XLOG("unsupported TYPE");
506 return 0;
507 }
508 /* CLASS must be IN */
509 if (!_dnsPacket_checkBytes(packet, 2, DNS_CLASS_IN)) {
510 XLOG("unsupported CLASS");
511 return 0;
512 }
513
514 return 1;
515}
516
517/* check the header of a DNS Query packet, return 1 if it is one
518 * type of query we can cache, or 0 otherwise
519 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900520static int _dnsPacket_checkQuery(DnsPacket* packet) {
521 const uint8_t* p = packet->base;
522 int qdCount, anCount, dnCount, arCount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900523
524 if (p + DNS_HEADER_SIZE > packet->end) {
525 XLOG("query packet too small");
526 return 0;
527 }
528
529 /* QR must be set to 0, opcode must be 0 and AA must be 0 */
530 /* RA, Z, and RCODE must be 0 */
531 if ((p[2] & 0xFC) != 0 || (p[3] & 0xCF) != 0) {
532 XLOG("query packet flags unsupported");
533 return 0;
534 }
535
536 /* Note that we ignore the TC, RD, CD, and AD bits here for the
537 * following reasons:
538 *
539 * - there is no point for a query packet sent to a server
540 * to have the TC bit set, but the implementation might
541 * set the bit in the query buffer for its own needs
542 * between a _resolv_cache_lookup and a
543 * _resolv_cache_add. We should not freak out if this
544 * is the case.
545 *
546 * - we consider that the result from a query might depend on
547 * the RD, AD, and CD bits, so these bits
548 * should be used to differentiate cached result.
549 *
550 * this implies that these bits are checked when hashing or
551 * comparing query packets, but not TC
552 */
553
554 /* ANCOUNT, DNCOUNT and ARCOUNT must be 0 */
555 qdCount = (p[4] << 8) | p[5];
556 anCount = (p[6] << 8) | p[7];
557 dnCount = (p[8] << 8) | p[9];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900558 arCount = (p[10] << 8) | p[11];
Bernie Innocenti55864192018-08-30 04:05:20 +0900559
560 if (anCount != 0 || dnCount != 0 || arCount > 1) {
561 XLOG("query packet contains non-query records");
562 return 0;
563 }
564
565 if (qdCount == 0) {
566 XLOG("query packet doesn't contain query record");
567 return 0;
568 }
569
570 /* Check QDCOUNT QRs */
571 packet->cursor = p + DNS_HEADER_SIZE;
572
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900573 for (; qdCount > 0; qdCount--)
574 if (!_dnsPacket_checkQR(packet)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900575
576 return 1;
577}
578
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900579/** QUERY DEBUGGING **/
Bernie Innocenti55864192018-08-30 04:05:20 +0900580#if DEBUG
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900581static char* _dnsPacket_bprintQName(DnsPacket* packet, char* bp, char* bend) {
582 const uint8_t* p = packet->cursor;
583 const uint8_t* end = packet->end;
584 int first = 1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900585
586 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900587 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900588
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900589 if (p >= end) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900590
591 c = *p++;
592
593 if (c == 0) {
594 packet->cursor = p;
595 return bp;
596 }
597
598 /* we don't expect label compression in QNAMEs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900599 if (c >= 64) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900600
601 if (first)
602 first = 0;
603 else
604 bp = _bprint_c(bp, bend, '.');
605
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900606 bp = _bprint_b(bp, bend, (const char*) p, c);
Bernie Innocenti55864192018-08-30 04:05:20 +0900607
608 p += c;
609 /* we rely on the bound check at the start
610 * of the loop here */
611 }
612 /* malformed data */
613 bp = _bprint_s(bp, bend, "<MALFORMED>");
614 return bp;
615}
616
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900617static char* _dnsPacket_bprintQR(DnsPacket* packet, char* p, char* end) {
618#define QQ(x) \
619 { DNS_TYPE_##x, #x }
Bernie Innocenti55864192018-08-30 04:05:20 +0900620 static const struct {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900621 const char* typeBytes;
622 const char* typeString;
623 } qTypes[] = {QQ(A), QQ(PTR), QQ(MX), QQ(AAAA), QQ(ALL), {NULL, NULL}};
624 int nn;
625 const char* typeString = NULL;
Bernie Innocenti55864192018-08-30 04:05:20 +0900626
627 /* dump QNAME */
628 p = _dnsPacket_bprintQName(packet, p, end);
629
630 /* dump TYPE */
631 p = _bprint_s(p, end, " (");
632
633 for (nn = 0; qTypes[nn].typeBytes != NULL; nn++) {
634 if (_dnsPacket_checkBytes(packet, 2, qTypes[nn].typeBytes)) {
635 typeString = qTypes[nn].typeString;
636 break;
637 }
638 }
639
640 if (typeString != NULL)
641 p = _bprint_s(p, end, typeString);
642 else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900643 int typeCode = _dnsPacket_readInt16(packet);
Bernie Innocenti55864192018-08-30 04:05:20 +0900644 p = _bprint(p, end, "UNKNOWN-%d", typeCode);
645 }
646
647 p = _bprint_c(p, end, ')');
648
649 /* skip CLASS */
650 _dnsPacket_skip(packet, 2);
651 return p;
652}
653
654/* this function assumes the packet has already been checked */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900655static char* _dnsPacket_bprintQuery(DnsPacket* packet, char* p, char* end) {
656 int qdCount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900657
658 if (packet->base[2] & 0x1) {
659 p = _bprint_s(p, end, "RECURSIVE ");
660 }
661
662 _dnsPacket_skip(packet, 4);
663 qdCount = _dnsPacket_readInt16(packet);
664 _dnsPacket_skip(packet, 6);
665
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900666 for (; qdCount > 0; qdCount--) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900667 p = _dnsPacket_bprintQR(packet, p, end);
668 }
669 return p;
670}
671#endif
672
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 Innocenti55864192018-08-30 04:05:20 +0900702 XLOG("%s: INTERNAL_ERROR: read-overflow !!\n", __FUNCTION__);
703 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) {
711 XLOG("%s: INTERNAL_ERROR: malformed domain !!\n", __FUNCTION__);
712 break;
713 }
714 if (p + c >= end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900715 XLOG("%s: INTERNAL_ERROR: simple label read-overflow !!\n", __FUNCTION__);
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
786 ** BEEN SUCCESFULLY CHECKED.
787 **/
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) {
799 XLOG("%s: INTERNAL_ERROR: read-overflow !!\n", __FUNCTION__);
800 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) {
812 XLOG("%s: INTERNAL_ERROR: malformed domain !!\n", __FUNCTION__);
813 break;
814 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900815 if ((p1 + c1 > end1) || (p2 + c1 > end2)) {
816 XLOG("%s: INTERNAL_ERROR: simple label read-overflow !!\n", __FUNCTION__);
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 */
825 XLOG("different DN");
826 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)) {
873 XLOG("different RD");
874 return 0;
875 }
876
877 if (pack1->base[3] != pack2->base[3]) {
878 XLOG("different CD or AD");
879 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) {
890 XLOG("different QDCOUNT");
891 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) {
902 XLOG("different ARCOUNT");
903 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)) {
909 XLOG("different QR");
910 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)) {
917 XLOG("different additional RR");
918 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 {
1024 XLOG("ns_parserr failed ancount no = %d. errno = %s\n", n, strerror(errno));
1025 }
1026 }
1027 }
1028 } else {
1029 XLOG("ns_parserr failed. %s\n", strerror(errno));
1030 }
1031
1032 XLOG("TTL = %lu\n", result);
1033
1034 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 Innocentif12d5bb2018-08-31 14:09:46 +09001044static __inline__ 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 Innocentif12d5bb2018-08-31 14:09:46 +09001049static __inline__ void entry_mru_add(Entry* e, Entry* list) {
1050 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
1119/****************************************************************************/
1120/****************************************************************************/
1121/***** *****/
1122/***** *****/
1123/***** *****/
1124/****************************************************************************/
1125/****************************************************************************/
1126
1127/* We use a simple hash table with external collision lists
1128 * for simplicity, the hash-table fields 'hash' and 'hlink' are
1129 * inlined in the Entry structure.
1130 */
1131
1132/* Maximum time for a thread to wait for an pending request */
1133#define PENDING_REQUEST_TIMEOUT 20;
1134
1135typedef struct pending_req_info {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001136 unsigned int hash;
1137 pthread_cond_t cond;
1138 struct pending_req_info* next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001139} PendingReqInfo;
1140
1141typedef struct resolv_cache {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001142 int max_entries;
1143 int num_entries;
1144 Entry mru_list;
1145 int last_id;
1146 Entry* entries;
1147 PendingReqInfo pending_requests;
Bernie Innocenti55864192018-08-30 04:05:20 +09001148} Cache;
1149
1150struct resolv_cache_info {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001151 unsigned netid;
1152 Cache* cache;
1153 struct resolv_cache_info* next;
1154 int nscount;
1155 char* nameservers[MAXNS];
1156 struct addrinfo* nsaddrinfo[MAXNS];
1157 int revision_id; // # times the nameservers have been replaced
1158 struct __res_params params;
1159 struct __res_stats nsstats[MAXNS];
1160 char defdname[MAXDNSRCHPATH];
1161 int dnsrch_offset[MAXDNSRCH + 1]; // offsets into defdname
Bernie Innocenti55864192018-08-30 04:05:20 +09001162};
1163
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001164#define HTABLE_VALID(x) ((x) != NULL && (x) != HTABLE_DELETED)
Bernie Innocenti55864192018-08-30 04:05:20 +09001165
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001166static pthread_once_t _res_cache_once = PTHREAD_ONCE_INIT;
Bernie Innocenti55864192018-08-30 04:05:20 +09001167static void _res_cache_init(void);
1168
1169// lock protecting everything in the _resolve_cache_info structs (next ptr, etc)
1170static pthread_mutex_t _res_cache_list_lock;
1171
1172/* gets cache associated with a network, or NULL if none exists */
1173static struct resolv_cache* _find_named_cache_locked(unsigned netid);
1174
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001175static void _cache_flush_pending_requests_locked(struct resolv_cache* cache) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001176 struct pending_req_info *ri, *tmp;
1177 if (cache) {
1178 ri = cache->pending_requests.next;
1179
1180 while (ri) {
1181 tmp = ri;
1182 ri = ri->next;
1183 pthread_cond_broadcast(&tmp->cond);
1184
1185 pthread_cond_destroy(&tmp->cond);
1186 free(tmp);
1187 }
1188
1189 cache->pending_requests.next = NULL;
1190 }
1191}
1192
1193/* Return 0 if no pending request is found matching the key.
1194 * If a matching request is found the calling thread will wait until
1195 * the matching request completes, then update *cache and return 1. */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001196static int _cache_check_pending_request_locked(struct resolv_cache** cache, Entry* key,
1197 unsigned netid) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001198 struct pending_req_info *ri, *prev;
1199 int exist = 0;
1200
1201 if (*cache && key) {
1202 ri = (*cache)->pending_requests.next;
1203 prev = &(*cache)->pending_requests;
1204 while (ri) {
1205 if (ri->hash == key->hash) {
1206 exist = 1;
1207 break;
1208 }
1209 prev = ri;
1210 ri = ri->next;
1211 }
1212
1213 if (!exist) {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001214 ri = (struct pending_req_info*) calloc(1, sizeof(struct pending_req_info));
Bernie Innocenti55864192018-08-30 04:05:20 +09001215 if (ri) {
1216 ri->hash = key->hash;
1217 pthread_cond_init(&ri->cond, NULL);
1218 prev->next = ri;
1219 }
1220 } else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001221 struct timespec ts = {0, 0};
Bernie Innocenti55864192018-08-30 04:05:20 +09001222 XLOG("Waiting for previous request");
1223 ts.tv_sec = _time_now() + PENDING_REQUEST_TIMEOUT;
1224 pthread_cond_timedwait(&ri->cond, &_res_cache_list_lock, &ts);
1225 /* Must update *cache as it could have been deleted. */
1226 *cache = _find_named_cache_locked(netid);
1227 }
1228 }
1229
1230 return exist;
1231}
1232
1233/* notify any waiting thread that waiting on a request
1234 * matching the key has been added to the cache */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001235static void _cache_notify_waiting_tid_locked(struct resolv_cache* cache, Entry* key) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001236 struct pending_req_info *ri, *prev;
1237
1238 if (cache && key) {
1239 ri = cache->pending_requests.next;
1240 prev = &cache->pending_requests;
1241 while (ri) {
1242 if (ri->hash == key->hash) {
1243 pthread_cond_broadcast(&ri->cond);
1244 break;
1245 }
1246 prev = ri;
1247 ri = ri->next;
1248 }
1249
1250 // remove item from list and destroy
1251 if (ri) {
1252 prev->next = ri->next;
1253 pthread_cond_destroy(&ri->cond);
1254 free(ri);
1255 }
1256 }
1257}
1258
1259/* notify the cache that the query failed */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001260void _resolv_cache_query_failed(unsigned netid, const void* query, int querylen) {
1261 Entry key[1];
1262 Cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001263
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001264 if (!entry_init_key(key, query, querylen)) return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001265
1266 pthread_mutex_lock(&_res_cache_list_lock);
1267
1268 cache = _find_named_cache_locked(netid);
1269
1270 if (cache) {
1271 _cache_notify_waiting_tid_locked(cache, key);
1272 }
1273
1274 pthread_mutex_unlock(&_res_cache_list_lock);
1275}
1276
1277static struct resolv_cache_info* _find_cache_info_locked(unsigned netid);
1278
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001279static void _cache_flush_locked(Cache* cache) {
1280 int nn;
Bernie Innocenti55864192018-08-30 04:05:20 +09001281
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001282 for (nn = 0; nn < cache->max_entries; nn++) {
1283 Entry** pnode = (Entry**) &cache->entries[nn];
Bernie Innocenti55864192018-08-30 04:05:20 +09001284
1285 while (*pnode != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001286 Entry* node = *pnode;
Bernie Innocenti55864192018-08-30 04:05:20 +09001287 *pnode = node->hlink;
1288 entry_free(node);
1289 }
1290 }
1291
1292 // flush pending request
1293 _cache_flush_pending_requests_locked(cache);
1294
1295 cache->mru_list.mru_next = cache->mru_list.mru_prev = &cache->mru_list;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001296 cache->num_entries = 0;
1297 cache->last_id = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +09001298
1299 XLOG("*************************\n"
1300 "*** DNS CACHE FLUSHED ***\n"
1301 "*************************");
1302}
1303
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001304static int _res_cache_get_max_entries(void) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001305 int cache_size = CONFIG_MAX_ENTRIES;
1306
1307 const char* cache_mode = getenv("ANDROID_DNS_MODE");
1308 if (cache_mode == NULL || strcmp(cache_mode, "local") != 0) {
1309 // Don't use the cache in local mode. This is used by the proxy itself.
1310 cache_size = 0;
1311 }
1312
1313 XLOG("cache size: %d", cache_size);
1314 return cache_size;
1315}
1316
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001317static struct resolv_cache* _resolv_cache_create(void) {
1318 struct resolv_cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001319
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001320 cache = (struct resolv_cache*) calloc(sizeof(*cache), 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001321 if (cache) {
1322 cache->max_entries = _res_cache_get_max_entries();
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001323 cache->entries = (Entry*) calloc(sizeof(*cache->entries), cache->max_entries);
Bernie Innocenti55864192018-08-30 04:05:20 +09001324 if (cache->entries) {
1325 cache->mru_list.mru_prev = cache->mru_list.mru_next = &cache->mru_list;
1326 XLOG("%s: cache created\n", __FUNCTION__);
1327 } else {
1328 free(cache);
1329 cache = NULL;
1330 }
1331 }
1332 return cache;
1333}
1334
Bernie Innocenti55864192018-08-30 04:05:20 +09001335#if DEBUG
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001336static void _dump_query(const uint8_t* query, int querylen) {
1337 char temp[256], *p = temp, *end = p + sizeof(temp);
1338 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001339
1340 _dnsPacket_init(pack, query, querylen);
1341 p = _dnsPacket_bprintQuery(pack, p, end);
1342 XLOG("QUERY: %s", temp);
1343}
1344
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001345static void _cache_dump_mru(Cache* cache) {
1346 char temp[512], *p = temp, *end = p + sizeof(temp);
1347 Entry* e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001348
1349 p = _bprint(temp, end, "MRU LIST (%2d): ", cache->num_entries);
1350 for (e = cache->mru_list.mru_next; e != &cache->mru_list; e = e->mru_next)
1351 p = _bprint(p, end, " %d", e->id);
1352
1353 XLOG("%s", temp);
1354}
1355
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001356static void _dump_answer(const void* answer, int answerlen) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001357 res_state statep;
1358 FILE* fp;
1359 char* buf;
1360 int fileLen;
1361
1362 fp = fopen("/data/reslog.txt", "w+e");
1363 if (fp != NULL) {
1364 statep = __res_get_state();
1365
1366 res_pquery(statep, answer, answerlen, fp);
1367
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001368 // Get file length
Bernie Innocenti55864192018-08-30 04:05:20 +09001369 fseek(fp, 0, SEEK_END);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001370 fileLen = ftell(fp);
Bernie Innocenti55864192018-08-30 04:05:20 +09001371 fseek(fp, 0, SEEK_SET);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001372 buf = (char*) malloc(fileLen + 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001373 if (buf != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001374 // Read file contents into buffer
Bernie Innocenti55864192018-08-30 04:05:20 +09001375 fread(buf, fileLen, 1, fp);
1376 XLOG("%s\n", buf);
1377 free(buf);
1378 }
1379 fclose(fp);
1380 remove("/data/reslog.txt");
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001381 } else {
1382 errno = 0; // else debug is introducing error signals
Bernie Innocenti55864192018-08-30 04:05:20 +09001383 XLOG("%s: can't open file\n", __FUNCTION__);
1384 }
1385}
1386#endif
1387
1388#if DEBUG
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001389#define XLOG_QUERY(q, len) _dump_query((q), (len))
1390#define XLOG_ANSWER(a, len) _dump_answer((a), (len))
Bernie Innocenti55864192018-08-30 04:05:20 +09001391#else
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001392#define XLOG_QUERY(q, len) ((void) 0)
1393#define XLOG_ANSWER(a, len) ((void) 0)
Bernie Innocenti55864192018-08-30 04:05:20 +09001394#endif
1395
1396/* This function tries to find a key within the hash table
1397 * In case of success, it will return a *pointer* to the hashed key.
1398 * In case of failure, it will return a *pointer* to NULL
1399 *
1400 * So, the caller must check '*result' to check for success/failure.
1401 *
1402 * The main idea is that the result can later be used directly in
1403 * calls to _resolv_cache_add or _resolv_cache_remove as the 'lookup'
1404 * parameter. This makes the code simpler and avoids re-searching
1405 * for the key position in the htable.
1406 *
1407 * The result of a lookup_p is only valid until you alter the hash
1408 * table.
1409 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001410static Entry** _cache_lookup_p(Cache* cache, Entry* key) {
1411 int index = key->hash % cache->max_entries;
1412 Entry** pnode = (Entry**) &cache->entries[index];
Bernie Innocenti55864192018-08-30 04:05:20 +09001413
1414 while (*pnode != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001415 Entry* node = *pnode;
Bernie Innocenti55864192018-08-30 04:05:20 +09001416
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001417 if (node == NULL) break;
Bernie Innocenti55864192018-08-30 04:05:20 +09001418
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001419 if (node->hash == key->hash && entry_equals(node, key)) break;
Bernie Innocenti55864192018-08-30 04:05:20 +09001420
1421 pnode = &node->hlink;
1422 }
1423 return pnode;
1424}
1425
1426/* Add a new entry to the hash table. 'lookup' must be the
1427 * result of an immediate previous failed _lookup_p() call
1428 * (i.e. with *lookup == NULL), and 'e' is the pointer to the
1429 * newly created entry
1430 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001431static void _cache_add_p(Cache* cache, Entry** lookup, Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001432 *lookup = e;
1433 e->id = ++cache->last_id;
1434 entry_mru_add(e, &cache->mru_list);
1435 cache->num_entries += 1;
1436
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001437 XLOG("%s: entry %d added (count=%d)", __FUNCTION__, e->id, cache->num_entries);
Bernie Innocenti55864192018-08-30 04:05:20 +09001438}
1439
1440/* Remove an existing entry from the hash table,
1441 * 'lookup' must be the result of an immediate previous
1442 * and succesful _lookup_p() call.
1443 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001444static void _cache_remove_p(Cache* cache, Entry** lookup) {
1445 Entry* e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001446
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001447 XLOG("%s: entry %d removed (count=%d)", __FUNCTION__, e->id, cache->num_entries - 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001448
1449 entry_mru_remove(e);
1450 *lookup = e->hlink;
1451 entry_free(e);
1452 cache->num_entries -= 1;
1453}
1454
1455/* Remove the oldest entry from the hash table.
1456 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001457static void _cache_remove_oldest(Cache* cache) {
1458 Entry* oldest = cache->mru_list.mru_prev;
1459 Entry** lookup = _cache_lookup_p(cache, oldest);
Bernie Innocenti55864192018-08-30 04:05:20 +09001460
1461 if (*lookup == NULL) { /* should not happen */
1462 XLOG("%s: OLDEST NOT IN HTABLE ?", __FUNCTION__);
1463 return;
1464 }
1465 if (DEBUG) {
1466 XLOG("Cache full - removing oldest");
1467 XLOG_QUERY(oldest->query, oldest->querylen);
1468 }
1469 _cache_remove_p(cache, lookup);
1470}
1471
1472/* Remove all expired entries from the hash table.
1473 */
1474static void _cache_remove_expired(Cache* cache) {
1475 Entry* e;
1476 time_t now = _time_now();
1477
1478 for (e = cache->mru_list.mru_next; e != &cache->mru_list;) {
1479 // Entry is old, remove
1480 if (now >= e->expires) {
1481 Entry** lookup = _cache_lookup_p(cache, e);
1482 if (*lookup == NULL) { /* should not happen */
1483 XLOG("%s: ENTRY NOT IN HTABLE ?", __FUNCTION__);
1484 return;
1485 }
1486 e = e->mru_next;
1487 _cache_remove_p(cache, lookup);
1488 } else {
1489 e = e->mru_next;
1490 }
1491 }
1492}
1493
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001494ResolvCacheStatus _resolv_cache_lookup(unsigned netid, const void* query, int querylen,
1495 void* answer, int answersize, int* answerlen) {
1496 Entry key[1];
1497 Entry** lookup;
1498 Entry* e;
1499 time_t now;
1500 Cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001501
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001502 ResolvCacheStatus result = RESOLV_CACHE_NOTFOUND;
Bernie Innocenti55864192018-08-30 04:05:20 +09001503
1504 XLOG("%s: lookup", __FUNCTION__);
1505 XLOG_QUERY(query, querylen);
1506
1507 /* we don't cache malformed queries */
1508 if (!entry_init_key(key, query, querylen)) {
1509 XLOG("%s: unsupported query", __FUNCTION__);
1510 return RESOLV_CACHE_UNSUPPORTED;
1511 }
1512 /* lookup cache */
1513 pthread_once(&_res_cache_once, _res_cache_init);
1514 pthread_mutex_lock(&_res_cache_list_lock);
1515
1516 cache = _find_named_cache_locked(netid);
1517 if (cache == NULL) {
1518 result = RESOLV_CACHE_UNSUPPORTED;
1519 goto Exit;
1520 }
1521
1522 /* see the description of _lookup_p to understand this.
1523 * the function always return a non-NULL pointer.
1524 */
1525 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001526 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001527
1528 if (e == NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001529 XLOG("NOT IN CACHE");
Bernie Innocenti55864192018-08-30 04:05:20 +09001530 // calling thread will wait if an outstanding request is found
1531 // that matching this query
1532 if (!_cache_check_pending_request_locked(&cache, key, netid) || cache == NULL) {
1533 goto Exit;
1534 } else {
1535 lookup = _cache_lookup_p(cache, key);
1536 e = *lookup;
1537 if (e == NULL) {
1538 goto Exit;
1539 }
1540 }
1541 }
1542
1543 now = _time_now();
1544
1545 /* remove stale entries here */
1546 if (now >= e->expires) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001547 XLOG(" NOT IN CACHE (STALE ENTRY %p DISCARDED)", *lookup);
Bernie Innocenti55864192018-08-30 04:05:20 +09001548 XLOG_QUERY(e->query, e->querylen);
1549 _cache_remove_p(cache, lookup);
1550 goto Exit;
1551 }
1552
1553 *answerlen = e->answerlen;
1554 if (e->answerlen > answersize) {
1555 /* NOTE: we return UNSUPPORTED if the answer buffer is too short */
1556 result = RESOLV_CACHE_UNSUPPORTED;
1557 XLOG(" ANSWER TOO LONG");
1558 goto Exit;
1559 }
1560
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001561 memcpy(answer, e->answer, e->answerlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001562
1563 /* bump up this entry to the top of the MRU list */
1564 if (e != cache->mru_list.mru_next) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001565 entry_mru_remove(e);
1566 entry_mru_add(e, &cache->mru_list);
Bernie Innocenti55864192018-08-30 04:05:20 +09001567 }
1568
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001569 XLOG("FOUND IN CACHE entry=%p", e);
Bernie Innocenti55864192018-08-30 04:05:20 +09001570 result = RESOLV_CACHE_FOUND;
1571
1572Exit:
1573 pthread_mutex_unlock(&_res_cache_list_lock);
1574 return result;
1575}
1576
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001577void _resolv_cache_add(unsigned netid, const void* query, int querylen, const void* answer,
1578 int answerlen) {
1579 Entry key[1];
1580 Entry* e;
1581 Entry** lookup;
1582 u_long ttl;
1583 Cache* cache = NULL;
Bernie Innocenti55864192018-08-30 04:05:20 +09001584
1585 /* don't assume that the query has already been cached
1586 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001587 if (!entry_init_key(key, query, querylen)) {
1588 XLOG("%s: passed invalid query ?", __FUNCTION__);
Bernie Innocenti55864192018-08-30 04:05:20 +09001589 return;
1590 }
1591
1592 pthread_mutex_lock(&_res_cache_list_lock);
1593
1594 cache = _find_named_cache_locked(netid);
1595 if (cache == NULL) {
1596 goto Exit;
1597 }
1598
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001599 XLOG("%s: query:", __FUNCTION__);
1600 XLOG_QUERY(query, querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001601 XLOG_ANSWER(answer, answerlen);
1602#if DEBUG_DATA
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001603 XLOG("answer:");
1604 XLOG_BYTES(answer, answerlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001605#endif
1606
1607 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001608 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001609
1610 if (e != NULL) { /* should not happen */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001611 XLOG("%s: ALREADY IN CACHE (%p) ? IGNORING ADD", __FUNCTION__, e);
Bernie Innocenti55864192018-08-30 04:05:20 +09001612 goto Exit;
1613 }
1614
1615 if (cache->num_entries >= cache->max_entries) {
1616 _cache_remove_expired(cache);
1617 if (cache->num_entries >= cache->max_entries) {
1618 _cache_remove_oldest(cache);
1619 }
1620 /* need to lookup again */
1621 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001622 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001623 if (e != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001624 XLOG("%s: ALREADY IN CACHE (%p) ? IGNORING ADD", __FUNCTION__, e);
Bernie Innocenti55864192018-08-30 04:05:20 +09001625 goto Exit;
1626 }
1627 }
1628
1629 ttl = answer_getTTL(answer, answerlen);
1630 if (ttl > 0) {
1631 e = entry_alloc(key, answer, answerlen);
1632 if (e != NULL) {
1633 e->expires = ttl + _time_now();
1634 _cache_add_p(cache, lookup, e);
1635 }
1636 }
1637#if DEBUG
1638 _cache_dump_mru(cache);
1639#endif
1640Exit:
1641 if (cache != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001642 _cache_notify_waiting_tid_locked(cache, key);
Bernie Innocenti55864192018-08-30 04:05:20 +09001643 }
1644 pthread_mutex_unlock(&_res_cache_list_lock);
1645}
1646
Bernie Innocenti55864192018-08-30 04:05:20 +09001647// Head of the list of caches. Protected by _res_cache_list_lock.
1648static struct resolv_cache_info _res_cache_list;
1649
1650/* insert resolv_cache_info into the list of resolv_cache_infos */
1651static void _insert_cache_info_locked(struct resolv_cache_info* cache_info);
1652/* creates a resolv_cache_info */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001653static struct resolv_cache_info* _create_cache_info(void);
Bernie Innocenti55864192018-08-30 04:05:20 +09001654/* gets a resolv_cache_info associated with a network, or NULL if not found */
1655static struct resolv_cache_info* _find_cache_info_locked(unsigned netid);
1656/* look up the named cache, and creates one if needed */
1657static struct resolv_cache* _get_res_cache_for_net_locked(unsigned netid);
1658/* empty the named cache */
1659static void _flush_cache_for_net_locked(unsigned netid);
1660/* empty the nameservers set for the named cache */
1661static void _free_nameservers_locked(struct resolv_cache_info* cache_info);
1662/* return 1 if the provided list of name servers differs from the list of name servers
1663 * currently attached to the provided cache_info */
1664static int _resolv_is_nameservers_equal_locked(struct resolv_cache_info* cache_info,
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001665 const char** servers, int numservers);
Bernie Innocenti55864192018-08-30 04:05:20 +09001666/* clears the stats samples contained withing the given cache_info */
1667static void _res_cache_clear_stats_locked(struct resolv_cache_info* cache_info);
1668
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001669static void _res_cache_init(void) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001670 memset(&_res_cache_list, 0, sizeof(_res_cache_list));
1671 pthread_mutex_init(&_res_cache_list_lock, NULL);
1672}
1673
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001674static struct resolv_cache* _get_res_cache_for_net_locked(unsigned netid) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001675 struct resolv_cache* cache = _find_named_cache_locked(netid);
1676 if (!cache) {
1677 struct resolv_cache_info* cache_info = _create_cache_info();
1678 if (cache_info) {
1679 cache = _resolv_cache_create();
1680 if (cache) {
1681 cache_info->cache = cache;
1682 cache_info->netid = netid;
1683 _insert_cache_info_locked(cache_info);
1684 } else {
1685 free(cache_info);
1686 }
1687 }
1688 }
1689 return cache;
1690}
1691
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001692void _resolv_flush_cache_for_net(unsigned netid) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001693 pthread_once(&_res_cache_once, _res_cache_init);
1694 pthread_mutex_lock(&_res_cache_list_lock);
1695
1696 _flush_cache_for_net_locked(netid);
1697
1698 pthread_mutex_unlock(&_res_cache_list_lock);
1699}
1700
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001701static void _flush_cache_for_net_locked(unsigned netid) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001702 struct resolv_cache* cache = _find_named_cache_locked(netid);
1703 if (cache) {
1704 _cache_flush_locked(cache);
1705 }
1706
1707 // Also clear the NS statistics.
1708 struct resolv_cache_info* cache_info = _find_cache_info_locked(netid);
1709 _res_cache_clear_stats_locked(cache_info);
1710}
1711
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001712void _resolv_delete_cache_for_net(unsigned netid) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001713 pthread_once(&_res_cache_once, _res_cache_init);
1714 pthread_mutex_lock(&_res_cache_list_lock);
1715
1716 struct resolv_cache_info* prev_cache_info = &_res_cache_list;
1717
1718 while (prev_cache_info->next) {
1719 struct resolv_cache_info* cache_info = prev_cache_info->next;
1720
1721 if (cache_info->netid == netid) {
1722 prev_cache_info->next = cache_info->next;
1723 _cache_flush_locked(cache_info->cache);
1724 free(cache_info->cache->entries);
1725 free(cache_info->cache);
1726 _free_nameservers_locked(cache_info);
1727 free(cache_info);
1728 break;
1729 }
1730
1731 prev_cache_info = prev_cache_info->next;
1732 }
1733
1734 pthread_mutex_unlock(&_res_cache_list_lock);
1735}
1736
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001737static struct resolv_cache_info* _create_cache_info(void) {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001738 return (struct resolv_cache_info*) calloc(sizeof(struct resolv_cache_info), 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001739}
1740
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001741static void _insert_cache_info_locked(struct resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001742 struct resolv_cache_info* last;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001743 for (last = &_res_cache_list; last->next; last = last->next) {}
Bernie Innocenti55864192018-08-30 04:05:20 +09001744 last->next = cache_info;
Bernie Innocenti55864192018-08-30 04:05:20 +09001745}
1746
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001747static struct resolv_cache* _find_named_cache_locked(unsigned netid) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001748 struct resolv_cache_info* info = _find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001749 if (info != NULL) return info->cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001750 return NULL;
1751}
1752
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001753static struct resolv_cache_info* _find_cache_info_locked(unsigned netid) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001754 struct resolv_cache_info* cache_info = _res_cache_list.next;
1755
1756 while (cache_info) {
1757 if (cache_info->netid == netid) {
1758 break;
1759 }
1760
1761 cache_info = cache_info->next;
1762 }
1763 return cache_info;
1764}
1765
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001766void _resolv_set_default_params(struct __res_params* params) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001767 params->sample_validity = NSSAMPLE_VALIDITY;
1768 params->success_threshold = SUCCESS_THRESHOLD;
1769 params->min_samples = 0;
1770 params->max_samples = 0;
1771 params->base_timeout_msec = 0; // 0 = legacy algorithm
1772}
1773
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001774int _resolv_set_nameservers_for_net(unsigned netid, const char** servers, unsigned numservers,
1775 const char* domains, const struct __res_params* params) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001776 char sbuf[NI_MAXSERV];
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001777 char* cp;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001778 int* offset;
Bernie Innocenti55864192018-08-30 04:05:20 +09001779 struct addrinfo* nsaddrinfo[MAXNS];
1780
1781 if (numservers > MAXNS) {
1782 XLOG("%s: numservers=%u, MAXNS=%u", __FUNCTION__, numservers, MAXNS);
1783 return E2BIG;
1784 }
1785
1786 // Parse the addresses before actually locking or changing any state, in case there is an error.
1787 // As a side effect this also reduces the time the lock is kept.
1788 struct addrinfo hints = {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001789 .ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM, .ai_flags = AI_NUMERICHOST};
Bernie Innocenti55864192018-08-30 04:05:20 +09001790 snprintf(sbuf, sizeof(sbuf), "%u", NAMESERVER_PORT);
1791 for (unsigned i = 0; i < numservers; i++) {
1792 // The addrinfo structures allocated here are freed in _free_nameservers_locked().
1793 int rt = getaddrinfo(servers[i], sbuf, &hints, &nsaddrinfo[i]);
1794 if (rt != 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001795 for (unsigned j = 0; j < i; j++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001796 freeaddrinfo(nsaddrinfo[j]);
1797 nsaddrinfo[j] = NULL;
1798 }
1799 XLOG("%s: getaddrinfo(%s)=%s", __FUNCTION__, servers[i], gai_strerror(rt));
1800 return EINVAL;
1801 }
1802 }
1803
1804 pthread_once(&_res_cache_once, _res_cache_init);
1805 pthread_mutex_lock(&_res_cache_list_lock);
1806
1807 // creates the cache if not created
1808 _get_res_cache_for_net_locked(netid);
1809
1810 struct resolv_cache_info* cache_info = _find_cache_info_locked(netid);
1811
1812 if (cache_info != NULL) {
1813 uint8_t old_max_samples = cache_info->params.max_samples;
1814 if (params != NULL) {
1815 cache_info->params = *params;
1816 } else {
1817 _resolv_set_default_params(&cache_info->params);
1818 }
1819
1820 if (!_resolv_is_nameservers_equal_locked(cache_info, servers, numservers)) {
1821 // free current before adding new
1822 _free_nameservers_locked(cache_info);
1823 unsigned i;
1824 for (i = 0; i < numservers; i++) {
1825 cache_info->nsaddrinfo[i] = nsaddrinfo[i];
1826 cache_info->nameservers[i] = strdup(servers[i]);
1827 XLOG("%s: netid = %u, addr = %s\n", __FUNCTION__, netid, servers[i]);
1828 }
1829 cache_info->nscount = numservers;
1830
1831 // Clear the NS statistics because the mapping to nameservers might have changed.
1832 _res_cache_clear_stats_locked(cache_info);
1833
1834 // increment the revision id to ensure that sample state is not written back if the
1835 // servers change; in theory it would suffice to do so only if the servers or
1836 // max_samples actually change, in practice the overhead of checking is higher than the
1837 // cost, and overflows are unlikely
1838 ++cache_info->revision_id;
1839 } else if (cache_info->params.max_samples != old_max_samples) {
1840 // If the maximum number of samples changes, the overhead of keeping the most recent
1841 // samples around is not considered worth the effort, so they are cleared instead. All
1842 // other parameters do not affect shared state: Changing these parameters does not
1843 // invalidate the samples, as they only affect aggregation and the conditions under
1844 // which servers are considered usable.
1845 _res_cache_clear_stats_locked(cache_info);
1846 ++cache_info->revision_id;
1847 }
1848
1849 // Always update the search paths, since determining whether they actually changed is
1850 // complex due to the zero-padding, and probably not worth the effort. Cache-flushing
1851 // however is not // necessary, since the stored cache entries do contain the domain, not
1852 // just the host name.
1853 // code moved from res_init.c, load_domain_search_list
1854 strlcpy(cache_info->defdname, domains, sizeof(cache_info->defdname));
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001855 if ((cp = strchr(cache_info->defdname, '\n')) != NULL) *cp = '\0';
Bernie Innocenti55864192018-08-30 04:05:20 +09001856
1857 cp = cache_info->defdname;
1858 offset = cache_info->dnsrch_offset;
1859 while (offset < cache_info->dnsrch_offset + MAXDNSRCH) {
1860 while (*cp == ' ' || *cp == '\t') /* skip leading white space */
1861 cp++;
1862 if (*cp == '\0') /* stop if nothing more to do */
1863 break;
1864 *offset++ = cp - cache_info->defdname; /* record this search domain */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001865 while (*cp) { /* zero-terminate it */
1866 if (*cp == ' ' || *cp == '\t') {
Bernie Innocenti55864192018-08-30 04:05:20 +09001867 *cp++ = '\0';
1868 break;
1869 }
1870 cp++;
1871 }
1872 }
1873 *offset = -1; /* cache_info->dnsrch_offset has MAXDNSRCH+1 items */
1874 }
1875
1876 pthread_mutex_unlock(&_res_cache_list_lock);
1877 return 0;
1878}
1879
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001880static int _resolv_is_nameservers_equal_locked(struct resolv_cache_info* cache_info,
1881 const char** servers, int numservers) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001882 if (cache_info->nscount != numservers) {
1883 return 0;
1884 }
1885
1886 // Compare each name server against current name servers.
1887 // TODO: this is incorrect if the list of current or previous nameservers
1888 // contains duplicates. This does not really matter because the framework
1889 // filters out duplicates, but we should probably fix it. It's also
1890 // insensitive to the order of the nameservers; we should probably fix that
1891 // too.
1892 for (int i = 0; i < numservers; i++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001893 for (int j = 0;; j++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001894 if (j >= numservers) {
1895 return 0;
1896 }
1897 if (strcmp(cache_info->nameservers[i], servers[j]) == 0) {
1898 break;
1899 }
1900 }
1901 }
1902
1903 return 1;
1904}
1905
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001906static void _free_nameservers_locked(struct resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001907 int i;
1908 for (i = 0; i < cache_info->nscount; i++) {
1909 free(cache_info->nameservers[i]);
1910 cache_info->nameservers[i] = NULL;
1911 if (cache_info->nsaddrinfo[i] != NULL) {
1912 freeaddrinfo(cache_info->nsaddrinfo[i]);
1913 cache_info->nsaddrinfo[i] = NULL;
1914 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001915 cache_info->nsstats[i].sample_count = cache_info->nsstats[i].sample_next = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +09001916 }
1917 cache_info->nscount = 0;
1918 _res_cache_clear_stats_locked(cache_info);
1919 ++cache_info->revision_id;
1920}
1921
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001922void _resolv_populate_res_for_net(res_state statp) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001923 if (statp == NULL) {
1924 return;
1925 }
1926
1927 pthread_once(&_res_cache_once, _res_cache_init);
1928 pthread_mutex_lock(&_res_cache_list_lock);
1929
1930 struct resolv_cache_info* info = _find_cache_info_locked(statp->netid);
1931 if (info != NULL) {
1932 int nserv;
1933 struct addrinfo* ai;
1934 XLOG("%s: %u\n", __FUNCTION__, statp->netid);
1935 for (nserv = 0; nserv < MAXNS; nserv++) {
1936 ai = info->nsaddrinfo[nserv];
1937 if (ai == NULL) {
1938 break;
1939 }
1940
1941 if ((size_t) ai->ai_addrlen <= sizeof(statp->_u._ext.ext->nsaddrs[0])) {
1942 if (statp->_u._ext.ext != NULL) {
1943 memcpy(&statp->_u._ext.ext->nsaddrs[nserv], ai->ai_addr, ai->ai_addrlen);
1944 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
1945 } else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001946 if ((size_t) ai->ai_addrlen <= sizeof(statp->nsaddr_list[0])) {
1947 memcpy(&statp->nsaddr_list[nserv], ai->ai_addr, ai->ai_addrlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001948 } else {
1949 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
1950 }
1951 }
1952 } else {
1953 XLOG("%s: found too long addrlen", __FUNCTION__);
1954 }
1955 }
1956 statp->nscount = nserv;
1957 // now do search domains. Note that we cache the offsets as this code runs alot
1958 // but the setting/offset-computer only runs when set/changed
1959 // WARNING: Don't use str*cpy() here, this string contains zeroes.
1960 memcpy(statp->defdname, info->defdname, sizeof(statp->defdname));
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001961 char** pp = statp->dnsrch;
1962 int* p = info->dnsrch_offset;
Bernie Innocenti55864192018-08-30 04:05:20 +09001963 while (pp < statp->dnsrch + MAXDNSRCH && *p != -1) {
1964 *pp++ = &statp->defdname[0] + *p++;
1965 }
1966 }
1967 pthread_mutex_unlock(&_res_cache_list_lock);
1968}
1969
1970/* Resolver reachability statistics. */
1971
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001972static void _res_cache_add_stats_sample_locked(struct __res_stats* stats,
1973 const struct __res_sample* sample, int max_samples) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001974 // Note: This function expects max_samples > 0, otherwise a (harmless) modification of the
1975 // allocated but supposedly unused memory for samples[0] will happen
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001976 XLOG("%s: adding sample to stats, next = %d, count = %d", __FUNCTION__, stats->sample_next,
1977 stats->sample_count);
Bernie Innocenti55864192018-08-30 04:05:20 +09001978 stats->samples[stats->sample_next] = *sample;
1979 if (stats->sample_count < max_samples) {
1980 ++stats->sample_count;
1981 }
1982 if (++stats->sample_next >= max_samples) {
1983 stats->sample_next = 0;
1984 }
1985}
1986
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001987static void _res_cache_clear_stats_locked(struct resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001988 if (cache_info) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001989 for (int i = 0; i < MAXNS; ++i) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001990 cache_info->nsstats->sample_count = cache_info->nsstats->sample_next = 0;
1991 }
1992 }
1993}
1994
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001995int android_net_res_stats_get_info_for_net(unsigned netid, int* nscount,
1996 struct sockaddr_storage servers[MAXNS], int* dcount,
1997 char domains[MAXDNSRCH][MAXDNSRCHPATH],
1998 struct __res_params* params,
1999 struct __res_stats stats[MAXNS]) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002000 int revision_id = -1;
2001 pthread_mutex_lock(&_res_cache_list_lock);
2002
2003 struct resolv_cache_info* info = _find_cache_info_locked(netid);
2004 if (info) {
2005 if (info->nscount > MAXNS) {
2006 pthread_mutex_unlock(&_res_cache_list_lock);
2007 XLOG("%s: nscount %d > MAXNS %d", __FUNCTION__, info->nscount, MAXNS);
2008 errno = EFAULT;
2009 return -1;
2010 }
2011 int i;
2012 for (i = 0; i < info->nscount; i++) {
2013 // Verify that the following assumptions are held, failure indicates corruption:
2014 // - getaddrinfo() may never return a sockaddr > sockaddr_storage
2015 // - all addresses are valid
2016 // - there is only one address per addrinfo thanks to numeric resolution
2017 int addrlen = info->nsaddrinfo[i]->ai_addrlen;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002018 if (addrlen < (int) sizeof(struct sockaddr) || addrlen > (int) sizeof(servers[0])) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002019 pthread_mutex_unlock(&_res_cache_list_lock);
2020 XLOG("%s: nsaddrinfo[%d].ai_addrlen == %d", __FUNCTION__, i, addrlen);
2021 errno = EMSGSIZE;
2022 return -1;
2023 }
2024 if (info->nsaddrinfo[i]->ai_addr == NULL) {
2025 pthread_mutex_unlock(&_res_cache_list_lock);
2026 XLOG("%s: nsaddrinfo[%d].ai_addr == NULL", __FUNCTION__, i);
2027 errno = ENOENT;
2028 return -1;
2029 }
2030 if (info->nsaddrinfo[i]->ai_next != NULL) {
2031 pthread_mutex_unlock(&_res_cache_list_lock);
2032 XLOG("%s: nsaddrinfo[%d].ai_next != NULL", __FUNCTION__, i);
2033 errno = ENOTUNIQ;
2034 return -1;
2035 }
2036 }
2037 *nscount = info->nscount;
2038 for (i = 0; i < info->nscount; i++) {
2039 memcpy(&servers[i], info->nsaddrinfo[i]->ai_addr, info->nsaddrinfo[i]->ai_addrlen);
2040 stats[i] = info->nsstats[i];
2041 }
2042 for (i = 0; i < MAXDNSRCH; i++) {
2043 const char* cur_domain = info->defdname + info->dnsrch_offset[i];
2044 // dnsrch_offset[i] can either be -1 or point to an empty string to indicate the end
2045 // of the search offsets. Checking for < 0 is not strictly necessary, but safer.
2046 // TODO: Pass in a search domain array instead of a string to
2047 // _resolv_set_nameservers_for_net() and make this double check unnecessary.
2048 if (info->dnsrch_offset[i] < 0 ||
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002049 ((size_t) info->dnsrch_offset[i]) >= sizeof(info->defdname) || !cur_domain[0]) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002050 break;
2051 }
2052 strlcpy(domains[i], cur_domain, MAXDNSRCHPATH);
2053 }
2054 *dcount = i;
2055 *params = info->params;
2056 revision_id = info->revision_id;
2057 }
2058
2059 pthread_mutex_unlock(&_res_cache_list_lock);
2060 return revision_id;
2061}
2062
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002063int _resolv_cache_get_resolver_stats(unsigned netid, struct __res_params* params,
2064 struct __res_stats stats[MAXNS]) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002065 int revision_id = -1;
2066 pthread_mutex_lock(&_res_cache_list_lock);
2067
2068 struct resolv_cache_info* info = _find_cache_info_locked(netid);
2069 if (info) {
2070 memcpy(stats, info->nsstats, sizeof(info->nsstats));
2071 *params = info->params;
2072 revision_id = info->revision_id;
2073 }
2074
2075 pthread_mutex_unlock(&_res_cache_list_lock);
2076 return revision_id;
2077}
2078
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002079void _resolv_cache_add_resolver_stats_sample(unsigned netid, int revision_id, int ns,
2080 const struct __res_sample* sample, int max_samples) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002081 if (max_samples <= 0) return;
2082
2083 pthread_mutex_lock(&_res_cache_list_lock);
2084
2085 struct resolv_cache_info* info = _find_cache_info_locked(netid);
2086
2087 if (info && info->revision_id == revision_id) {
2088 _res_cache_add_stats_sample_locked(&info->nsstats[ns], sample, max_samples);
2089 }
2090
2091 pthread_mutex_unlock(&_res_cache_list_lock);
2092}