blob: 230ebef6aa73b4dd6ab1d28dc5e04527c3feb32f [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
134/****************************************************************************/
135/****************************************************************************/
136/***** *****/
137/***** *****/
138/***** *****/
139/****************************************************************************/
140/****************************************************************************/
141
142/* set to 1 to debug cache operations */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900143#define DEBUG 0
Bernie Innocenti55864192018-08-30 04:05:20 +0900144
145/* set to 1 to debug query data */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900146#define DEBUG_DATA 0
Bernie Innocenti55864192018-08-30 04:05:20 +0900147
148#if DEBUG
149#define __DEBUG__
150#else
151#define __DEBUG__ __attribute__((unused))
152#endif
153
154#undef XLOG
155
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900156#define XLOG(...) \
157 ({ \
158 if (DEBUG) { \
159 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", __VA_ARGS__); \
160 } else { \
161 ((void) 0); \
162 } \
163 })
Bernie Innocenti55864192018-08-30 04:05:20 +0900164
165/** BOUNDED BUFFER FORMATTING
166 **/
167
168/* technical note:
169 *
170 * the following debugging routines are used to append data to a bounded
171 * buffer they take two parameters that are:
172 *
173 * - p : a pointer to the current cursor position in the buffer
174 * this value is initially set to the buffer's address.
175 *
176 * - end : the address of the buffer's limit, i.e. of the first byte
177 * after the buffer. this address should never be touched.
178 *
179 * IMPORTANT: it is assumed that end > buffer_address, i.e.
180 * that the buffer is at least one byte.
181 *
182 * the _bprint_() functions return the new value of 'p' after the data
183 * has been appended, and also ensure the following:
184 *
185 * - the returned value will never be strictly greater than 'end'
186 *
187 * - a return value equal to 'end' means that truncation occured
188 * (in which case, end[-1] will be set to 0)
189 *
190 * - after returning from a _bprint_() function, the content of the buffer
191 * is always 0-terminated, even in the event of truncation.
192 *
193 * these conventions allow you to call _bprint_ functions multiple times and
194 * only check for truncation at the end of the sequence, as in:
195 *
196 * char buff[1000], *p = buff, *end = p + sizeof(buff);
197 *
198 * p = _bprint_c(p, end, '"');
199 * p = _bprint_s(p, end, my_string);
200 * p = _bprint_c(p, end, '"');
201 *
202 * if (p >= end) {
203 * // buffer was too small
204 * }
205 *
206 * printf( "%s", buff );
207 */
208
209/* add a char to a bounded buffer */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900210char* _bprint_c(char* p, char* end, int c) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900211 if (p < end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900212 if (p + 1 == end)
Bernie Innocenti55864192018-08-30 04:05:20 +0900213 *p++ = 0;
214 else {
215 *p++ = (char) c;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900216 *p = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900217 }
218 }
219 return p;
220}
221
222/* add a sequence of bytes to a bounded buffer */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900223char* _bprint_b(char* p, char* end, const char* buf, int len) {
224 int avail = end - p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900225
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900226 if (avail <= 0 || len <= 0) return p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900227
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900228 if (avail > len) avail = len;
Bernie Innocenti55864192018-08-30 04:05:20 +0900229
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900230 memcpy(p, buf, avail);
Bernie Innocenti55864192018-08-30 04:05:20 +0900231 p += avail;
232
233 if (p < end)
234 p[0] = 0;
235 else
236 end[-1] = 0;
237
238 return p;
239}
240
241/* add a string to a bounded buffer */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900242char* _bprint_s(char* p, char* end, const char* str) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900243 return _bprint_b(p, end, str, strlen(str));
244}
245
246/* add a formatted string to a bounded buffer */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900247char* _bprint(char* p, char* end, const char* format, ...) __DEBUG__;
248char* _bprint(char* p, char* end, const char* format, ...) {
249 int avail, n;
250 va_list args;
Bernie Innocenti55864192018-08-30 04:05:20 +0900251
252 avail = end - p;
253
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900254 if (avail <= 0) return p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900255
256 va_start(args, format);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900257 n = vsnprintf(p, avail, format, args);
Bernie Innocenti55864192018-08-30 04:05:20 +0900258 va_end(args);
259
260 /* certain C libraries return -1 in case of truncation */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900261 if (n < 0 || n > avail) n = avail;
Bernie Innocenti55864192018-08-30 04:05:20 +0900262
263 p += n;
264 /* certain C libraries do not zero-terminate in case of truncation */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900265 if (p == end) p[-1] = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900266
267 return p;
268}
269
270/* add a hex value to a bounded buffer, up to 8 digits */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900271char* _bprint_hex(char* p, char* end, unsigned value, int numDigits) {
272 char text[sizeof(unsigned) * 2];
273 int nn = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900274
275 while (numDigits-- > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900276 text[nn++] = "0123456789abcdef"[(value >> (numDigits * 4)) & 15];
Bernie Innocenti55864192018-08-30 04:05:20 +0900277 }
278 return _bprint_b(p, end, text, nn);
279}
280
281/* add the hexadecimal dump of some memory area to a bounded buffer */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900282char* _bprint_hexdump(char* p, char* end, const uint8_t* data, int datalen) {
283 int lineSize = 16;
Bernie Innocenti55864192018-08-30 04:05:20 +0900284
285 while (datalen > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900286 int avail = datalen;
287 int nn;
Bernie Innocenti55864192018-08-30 04:05:20 +0900288
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900289 if (avail > lineSize) avail = lineSize;
Bernie Innocenti55864192018-08-30 04:05:20 +0900290
291 for (nn = 0; nn < avail; nn++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900292 if (nn > 0) p = _bprint_c(p, end, ' ');
Bernie Innocenti55864192018-08-30 04:05:20 +0900293 p = _bprint_hex(p, end, data[nn], 2);
294 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900295 for (; nn < lineSize; nn++) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900296 p = _bprint_s(p, end, " ");
297 }
298 p = _bprint_s(p, end, " ");
299
300 for (nn = 0; nn < avail; nn++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900301 int c = data[nn];
Bernie Innocenti55864192018-08-30 04:05:20 +0900302
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900303 if (c < 32 || c > 127) c = '.';
Bernie Innocenti55864192018-08-30 04:05:20 +0900304
305 p = _bprint_c(p, end, c);
306 }
307 p = _bprint_c(p, end, '\n');
308
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900309 data += avail;
Bernie Innocenti55864192018-08-30 04:05:20 +0900310 datalen -= avail;
311 }
312 return p;
313}
314
315/* dump the content of a query of packet to the log */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900316void XLOG_BYTES(const void* base, int len) __DEBUG__;
317void XLOG_BYTES(const void* base, int len) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900318 if (DEBUG_DATA) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900319 char buff[1024];
320 char *p = buff, *end = p + sizeof(buff);
Bernie Innocenti55864192018-08-30 04:05:20 +0900321
322 p = _bprint_hexdump(p, end, base, len);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900323 XLOG("%s", buff);
Bernie Innocenti55864192018-08-30 04:05:20 +0900324 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900325}
326__DEBUG__
Bernie Innocenti55864192018-08-30 04:05:20 +0900327
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900328static time_t _time_now(void) {
329 struct timeval tv;
Bernie Innocenti55864192018-08-30 04:05:20 +0900330
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900331 gettimeofday(&tv, NULL);
Bernie Innocenti55864192018-08-30 04:05:20 +0900332 return tv.tv_sec;
333}
334
335/* reminder: the general format of a DNS packet is the following:
336 *
337 * HEADER (12 bytes)
338 * QUESTION (variable)
339 * ANSWER (variable)
340 * AUTHORITY (variable)
341 * ADDITIONNAL (variable)
342 *
343 * the HEADER is made of:
344 *
345 * ID : 16 : 16-bit unique query identification field
346 *
347 * QR : 1 : set to 0 for queries, and 1 for responses
348 * Opcode : 4 : set to 0 for queries
349 * AA : 1 : set to 0 for queries
350 * TC : 1 : truncation flag, will be set to 0 in queries
351 * RD : 1 : recursion desired
352 *
353 * RA : 1 : recursion available (0 in queries)
354 * Z : 3 : three reserved zero bits
355 * RCODE : 4 : response code (always 0=NOERROR in queries)
356 *
357 * QDCount: 16 : question count
358 * ANCount: 16 : Answer count (0 in queries)
359 * NSCount: 16: Authority Record count (0 in queries)
360 * ARCount: 16: Additionnal Record count (0 in queries)
361 *
362 * the QUESTION is made of QDCount Question Record (QRs)
363 * the ANSWER is made of ANCount RRs
364 * the AUTHORITY is made of NSCount RRs
365 * the ADDITIONNAL is made of ARCount RRs
366 *
367 * Each Question Record (QR) is made of:
368 *
369 * QNAME : variable : Query DNS NAME
370 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
371 * CLASS : 16 : class of query (IN=1)
372 *
373 * Each Resource Record (RR) is made of:
374 *
375 * NAME : variable : DNS NAME
376 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
377 * CLASS : 16 : class of query (IN=1)
378 * TTL : 32 : seconds to cache this RR (0=none)
379 * RDLENGTH: 16 : size of RDDATA in bytes
380 * RDDATA : variable : RR data (depends on TYPE)
381 *
382 * Each QNAME contains a domain name encoded as a sequence of 'labels'
383 * terminated by a zero. Each label has the following format:
384 *
385 * LEN : 8 : lenght of label (MUST be < 64)
386 * NAME : 8*LEN : label length (must exclude dots)
387 *
388 * A value of 0 in the encoding is interpreted as the 'root' domain and
389 * terminates the encoding. So 'www.android.com' will be encoded as:
390 *
391 * <3>www<7>android<3>com<0>
392 *
393 * Where <n> represents the byte with value 'n'
394 *
395 * Each NAME reflects the QNAME of the question, but has a slightly more
396 * complex encoding in order to provide message compression. This is achieved
397 * by using a 2-byte pointer, with format:
398 *
399 * TYPE : 2 : 0b11 to indicate a pointer, 0b01 and 0b10 are reserved
400 * OFFSET : 14 : offset to another part of the DNS packet
401 *
402 * The offset is relative to the start of the DNS packet and must point
403 * A pointer terminates the encoding.
404 *
405 * The NAME can be encoded in one of the following formats:
406 *
407 * - a sequence of simple labels terminated by 0 (like QNAMEs)
408 * - a single pointer
409 * - a sequence of simple labels terminated by a pointer
410 *
411 * A pointer shall always point to either a pointer of a sequence of
412 * labels (which can themselves be terminated by either a 0 or a pointer)
413 *
414 * The expanded length of a given domain name should not exceed 255 bytes.
415 *
416 * NOTE: we don't parse the answer packets, so don't need to deal with NAME
417 * records, only QNAMEs.
418 */
419
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900420#define DNS_HEADER_SIZE 12
Bernie Innocenti55864192018-08-30 04:05:20 +0900421
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900422#define DNS_TYPE_A "\00\01" /* big-endian decimal 1 */
423#define DNS_TYPE_PTR "\00\014" /* big-endian decimal 12 */
424#define DNS_TYPE_MX "\00\017" /* big-endian decimal 15 */
425#define DNS_TYPE_AAAA "\00\034" /* big-endian decimal 28 */
426#define DNS_TYPE_ALL "\00\0377" /* big-endian decimal 255 */
Bernie Innocenti55864192018-08-30 04:05:20 +0900427
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900428#define DNS_CLASS_IN "\00\01" /* big-endian decimal 1 */
Bernie Innocenti55864192018-08-30 04:05:20 +0900429
430typedef struct {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900431 const uint8_t* base;
432 const uint8_t* end;
433 const uint8_t* cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900434} DnsPacket;
435
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900436static void _dnsPacket_init(DnsPacket* packet, const uint8_t* buff, int bufflen) {
437 packet->base = buff;
438 packet->end = buff + bufflen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900439 packet->cursor = buff;
440}
441
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900442static void _dnsPacket_rewind(DnsPacket* packet) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900443 packet->cursor = packet->base;
444}
445
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900446static void _dnsPacket_skip(DnsPacket* packet, int count) {
447 const uint8_t* p = packet->cursor + count;
Bernie Innocenti55864192018-08-30 04:05:20 +0900448
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900449 if (p > packet->end) p = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900450
451 packet->cursor = p;
452}
453
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900454static int _dnsPacket_readInt16(DnsPacket* packet) {
455 const uint8_t* p = packet->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900456
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900457 if (p + 2 > packet->end) return -1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900458
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900459 packet->cursor = p + 2;
460 return (p[0] << 8) | p[1];
Bernie Innocenti55864192018-08-30 04:05:20 +0900461}
462
463/** QUERY CHECKING
464 **/
465
466/* check bytes in a dns packet. returns 1 on success, 0 on failure.
467 * the cursor is only advanced in the case of success
468 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900469static int _dnsPacket_checkBytes(DnsPacket* packet, int numBytes, const void* bytes) {
470 const uint8_t* p = packet->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900471
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900472 if (p + numBytes > packet->end) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900473
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900474 if (memcmp(p, bytes, numBytes) != 0) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900475
476 packet->cursor = p + numBytes;
477 return 1;
478}
479
480/* parse and skip a given QNAME stored in a query packet,
481 * from the current cursor position. returns 1 on success,
482 * or 0 for malformed data.
483 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900484static int _dnsPacket_checkQName(DnsPacket* packet) {
485 const uint8_t* p = packet->cursor;
486 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900487
488 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900489 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900490
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900491 if (p >= end) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900492
493 c = *p++;
494
495 if (c == 0) {
496 packet->cursor = p;
497 return 1;
498 }
499
500 /* we don't expect label compression in QNAMEs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900501 if (c >= 64) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900502
503 p += c;
504 /* we rely on the bound check at the start
505 * of the loop here */
506 }
507 /* malformed data */
508 XLOG("malformed QNAME");
509 return 0;
510}
511
512/* parse and skip a given QR stored in a packet.
513 * returns 1 on success, and 0 on failure
514 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900515static int _dnsPacket_checkQR(DnsPacket* packet) {
516 if (!_dnsPacket_checkQName(packet)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900517
518 /* TYPE must be one of the things we support */
519 if (!_dnsPacket_checkBytes(packet, 2, DNS_TYPE_A) &&
520 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_PTR) &&
521 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_MX) &&
522 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_AAAA) &&
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900523 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_ALL)) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900524 XLOG("unsupported TYPE");
525 return 0;
526 }
527 /* CLASS must be IN */
528 if (!_dnsPacket_checkBytes(packet, 2, DNS_CLASS_IN)) {
529 XLOG("unsupported CLASS");
530 return 0;
531 }
532
533 return 1;
534}
535
536/* check the header of a DNS Query packet, return 1 if it is one
537 * type of query we can cache, or 0 otherwise
538 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900539static int _dnsPacket_checkQuery(DnsPacket* packet) {
540 const uint8_t* p = packet->base;
541 int qdCount, anCount, dnCount, arCount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900542
543 if (p + DNS_HEADER_SIZE > packet->end) {
544 XLOG("query packet too small");
545 return 0;
546 }
547
548 /* QR must be set to 0, opcode must be 0 and AA must be 0 */
549 /* RA, Z, and RCODE must be 0 */
550 if ((p[2] & 0xFC) != 0 || (p[3] & 0xCF) != 0) {
551 XLOG("query packet flags unsupported");
552 return 0;
553 }
554
555 /* Note that we ignore the TC, RD, CD, and AD bits here for the
556 * following reasons:
557 *
558 * - there is no point for a query packet sent to a server
559 * to have the TC bit set, but the implementation might
560 * set the bit in the query buffer for its own needs
561 * between a _resolv_cache_lookup and a
562 * _resolv_cache_add. We should not freak out if this
563 * is the case.
564 *
565 * - we consider that the result from a query might depend on
566 * the RD, AD, and CD bits, so these bits
567 * should be used to differentiate cached result.
568 *
569 * this implies that these bits are checked when hashing or
570 * comparing query packets, but not TC
571 */
572
573 /* ANCOUNT, DNCOUNT and ARCOUNT must be 0 */
574 qdCount = (p[4] << 8) | p[5];
575 anCount = (p[6] << 8) | p[7];
576 dnCount = (p[8] << 8) | p[9];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900577 arCount = (p[10] << 8) | p[11];
Bernie Innocenti55864192018-08-30 04:05:20 +0900578
579 if (anCount != 0 || dnCount != 0 || arCount > 1) {
580 XLOG("query packet contains non-query records");
581 return 0;
582 }
583
584 if (qdCount == 0) {
585 XLOG("query packet doesn't contain query record");
586 return 0;
587 }
588
589 /* Check QDCOUNT QRs */
590 packet->cursor = p + DNS_HEADER_SIZE;
591
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900592 for (; qdCount > 0; qdCount--)
593 if (!_dnsPacket_checkQR(packet)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900594
595 return 1;
596}
597
598/** QUERY DEBUGGING
599 **/
600#if DEBUG
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900601static char* _dnsPacket_bprintQName(DnsPacket* packet, char* bp, char* bend) {
602 const uint8_t* p = packet->cursor;
603 const uint8_t* end = packet->end;
604 int first = 1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900605
606 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900607 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900608
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900609 if (p >= end) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900610
611 c = *p++;
612
613 if (c == 0) {
614 packet->cursor = p;
615 return bp;
616 }
617
618 /* we don't expect label compression in QNAMEs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900619 if (c >= 64) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900620
621 if (first)
622 first = 0;
623 else
624 bp = _bprint_c(bp, bend, '.');
625
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900626 bp = _bprint_b(bp, bend, (const char*) p, c);
Bernie Innocenti55864192018-08-30 04:05:20 +0900627
628 p += c;
629 /* we rely on the bound check at the start
630 * of the loop here */
631 }
632 /* malformed data */
633 bp = _bprint_s(bp, bend, "<MALFORMED>");
634 return bp;
635}
636
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900637static char* _dnsPacket_bprintQR(DnsPacket* packet, char* p, char* end) {
638#define QQ(x) \
639 { DNS_TYPE_##x, #x }
Bernie Innocenti55864192018-08-30 04:05:20 +0900640 static const struct {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900641 const char* typeBytes;
642 const char* typeString;
643 } qTypes[] = {QQ(A), QQ(PTR), QQ(MX), QQ(AAAA), QQ(ALL), {NULL, NULL}};
644 int nn;
645 const char* typeString = NULL;
Bernie Innocenti55864192018-08-30 04:05:20 +0900646
647 /* dump QNAME */
648 p = _dnsPacket_bprintQName(packet, p, end);
649
650 /* dump TYPE */
651 p = _bprint_s(p, end, " (");
652
653 for (nn = 0; qTypes[nn].typeBytes != NULL; nn++) {
654 if (_dnsPacket_checkBytes(packet, 2, qTypes[nn].typeBytes)) {
655 typeString = qTypes[nn].typeString;
656 break;
657 }
658 }
659
660 if (typeString != NULL)
661 p = _bprint_s(p, end, typeString);
662 else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900663 int typeCode = _dnsPacket_readInt16(packet);
Bernie Innocenti55864192018-08-30 04:05:20 +0900664 p = _bprint(p, end, "UNKNOWN-%d", typeCode);
665 }
666
667 p = _bprint_c(p, end, ')');
668
669 /* skip CLASS */
670 _dnsPacket_skip(packet, 2);
671 return p;
672}
673
674/* this function assumes the packet has already been checked */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900675static char* _dnsPacket_bprintQuery(DnsPacket* packet, char* p, char* end) {
676 int qdCount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900677
678 if (packet->base[2] & 0x1) {
679 p = _bprint_s(p, end, "RECURSIVE ");
680 }
681
682 _dnsPacket_skip(packet, 4);
683 qdCount = _dnsPacket_readInt16(packet);
684 _dnsPacket_skip(packet, 6);
685
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900686 for (; qdCount > 0; qdCount--) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900687 p = _dnsPacket_bprintQR(packet, p, end);
688 }
689 return p;
690}
691#endif
692
Bernie Innocenti55864192018-08-30 04:05:20 +0900693/** QUERY HASHING SUPPORT
694 **
695 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKET HAS ALREADY
696 ** BEEN SUCCESFULLY CHECKED.
697 **/
698
699/* use 32-bit FNV hash function */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900700#define FNV_MULT 16777619U
701#define FNV_BASIS 2166136261U
Bernie Innocenti55864192018-08-30 04:05:20 +0900702
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900703static unsigned _dnsPacket_hashBytes(DnsPacket* packet, int numBytes, unsigned hash) {
704 const uint8_t* p = packet->cursor;
705 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900706
707 while (numBytes > 0 && p < end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900708 hash = hash * FNV_MULT ^ *p++;
Bernie Innocenti55864192018-08-30 04:05:20 +0900709 }
710 packet->cursor = p;
711 return hash;
712}
713
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900714static unsigned _dnsPacket_hashQName(DnsPacket* packet, unsigned hash) {
715 const uint8_t* p = packet->cursor;
716 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900717
718 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900719 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900720
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900721 if (p >= end) { /* should not happen */
Bernie Innocenti55864192018-08-30 04:05:20 +0900722 XLOG("%s: INTERNAL_ERROR: read-overflow !!\n", __FUNCTION__);
723 break;
724 }
725
726 c = *p++;
727
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900728 if (c == 0) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900729
730 if (c >= 64) {
731 XLOG("%s: INTERNAL_ERROR: malformed domain !!\n", __FUNCTION__);
732 break;
733 }
734 if (p + c >= end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900735 XLOG("%s: INTERNAL_ERROR: simple label read-overflow !!\n", __FUNCTION__);
Bernie Innocenti55864192018-08-30 04:05:20 +0900736 break;
737 }
738 while (c > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900739 hash = hash * FNV_MULT ^ *p++;
740 c -= 1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900741 }
742 }
743 packet->cursor = p;
744 return hash;
745}
746
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900747static unsigned _dnsPacket_hashQR(DnsPacket* packet, unsigned hash) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900748 hash = _dnsPacket_hashQName(packet, hash);
749 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TYPE and CLASS */
750 return hash;
751}
752
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900753static unsigned _dnsPacket_hashRR(DnsPacket* packet, unsigned hash) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900754 int rdlength;
755 hash = _dnsPacket_hashQR(packet, hash);
756 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TTL */
757 rdlength = _dnsPacket_readInt16(packet);
758 hash = _dnsPacket_hashBytes(packet, rdlength, hash); /* RDATA */
759 return hash;
760}
761
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900762static unsigned _dnsPacket_hashQuery(DnsPacket* packet) {
763 unsigned hash = FNV_BASIS;
764 int count, arcount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900765 _dnsPacket_rewind(packet);
766
767 /* ignore the ID */
768 _dnsPacket_skip(packet, 2);
769
770 /* we ignore the TC bit for reasons explained in
771 * _dnsPacket_checkQuery().
772 *
773 * however we hash the RD bit to differentiate
774 * between answers for recursive and non-recursive
775 * queries.
776 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900777 hash = hash * FNV_MULT ^ (packet->base[2] & 1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900778
779 /* mark the first header byte as processed */
780 _dnsPacket_skip(packet, 1);
781
782 /* process the second header byte */
783 hash = _dnsPacket_hashBytes(packet, 1, hash);
784
785 /* read QDCOUNT */
786 count = _dnsPacket_readInt16(packet);
787
788 /* assume: ANcount and NScount are 0 */
789 _dnsPacket_skip(packet, 4);
790
791 /* read ARCOUNT */
792 arcount = _dnsPacket_readInt16(packet);
793
794 /* hash QDCOUNT QRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900795 for (; count > 0; count--) hash = _dnsPacket_hashQR(packet, hash);
Bernie Innocenti55864192018-08-30 04:05:20 +0900796
797 /* hash ARCOUNT RRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900798 for (; arcount > 0; arcount--) hash = _dnsPacket_hashRR(packet, hash);
Bernie Innocenti55864192018-08-30 04:05:20 +0900799
800 return hash;
801}
802
Bernie Innocenti55864192018-08-30 04:05:20 +0900803/** QUERY COMPARISON
804 **
805 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKETS HAVE ALREADY
806 ** BEEN SUCCESFULLY CHECKED.
807 **/
808
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900809static int _dnsPacket_isEqualDomainName(DnsPacket* pack1, DnsPacket* pack2) {
810 const uint8_t* p1 = pack1->cursor;
811 const uint8_t* end1 = pack1->end;
812 const uint8_t* p2 = pack2->cursor;
813 const uint8_t* end2 = pack2->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900814
815 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900816 int c1, c2;
Bernie Innocenti55864192018-08-30 04:05:20 +0900817
818 if (p1 >= end1 || p2 >= end2) {
819 XLOG("%s: INTERNAL_ERROR: read-overflow !!\n", __FUNCTION__);
820 break;
821 }
822 c1 = *p1++;
823 c2 = *p2++;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900824 if (c1 != c2) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900825
826 if (c1 == 0) {
827 pack1->cursor = p1;
828 pack2->cursor = p2;
829 return 1;
830 }
831 if (c1 >= 64) {
832 XLOG("%s: INTERNAL_ERROR: malformed domain !!\n", __FUNCTION__);
833 break;
834 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900835 if ((p1 + c1 > end1) || (p2 + c1 > end2)) {
836 XLOG("%s: INTERNAL_ERROR: simple label read-overflow !!\n", __FUNCTION__);
Bernie Innocenti55864192018-08-30 04:05:20 +0900837 break;
838 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900839 if (memcmp(p1, p2, c1) != 0) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900840 p1 += c1;
841 p2 += c1;
842 /* we rely on the bound checks at the start of the loop */
843 }
844 /* not the same, or one is malformed */
845 XLOG("different DN");
846 return 0;
847}
848
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900849static int _dnsPacket_isEqualBytes(DnsPacket* pack1, DnsPacket* pack2, int numBytes) {
850 const uint8_t* p1 = pack1->cursor;
851 const uint8_t* p2 = pack2->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900852
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900853 if (p1 + numBytes > pack1->end || p2 + numBytes > pack2->end) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900854
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900855 if (memcmp(p1, p2, numBytes) != 0) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900856
857 pack1->cursor += numBytes;
858 pack2->cursor += numBytes;
859 return 1;
860}
861
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900862static int _dnsPacket_isEqualQR(DnsPacket* pack1, DnsPacket* pack2) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900863 /* compare domain name encoding + TYPE + CLASS */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900864 if (!_dnsPacket_isEqualDomainName(pack1, pack2) ||
865 !_dnsPacket_isEqualBytes(pack1, pack2, 2 + 2))
Bernie Innocenti55864192018-08-30 04:05:20 +0900866 return 0;
867
868 return 1;
869}
870
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900871static int _dnsPacket_isEqualRR(DnsPacket* pack1, DnsPacket* pack2) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900872 int rdlength1, rdlength2;
873 /* compare query + TTL */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900874 if (!_dnsPacket_isEqualQR(pack1, pack2) || !_dnsPacket_isEqualBytes(pack1, pack2, 4)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900875
876 /* compare RDATA */
877 rdlength1 = _dnsPacket_readInt16(pack1);
878 rdlength2 = _dnsPacket_readInt16(pack2);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900879 if (rdlength1 != rdlength2 || !_dnsPacket_isEqualBytes(pack1, pack2, rdlength1)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900880
881 return 1;
882}
883
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900884static int _dnsPacket_isEqualQuery(DnsPacket* pack1, DnsPacket* pack2) {
885 int count1, count2, arcount1, arcount2;
Bernie Innocenti55864192018-08-30 04:05:20 +0900886
887 /* compare the headers, ignore most fields */
888 _dnsPacket_rewind(pack1);
889 _dnsPacket_rewind(pack2);
890
891 /* compare RD, ignore TC, see comment in _dnsPacket_checkQuery */
892 if ((pack1->base[2] & 1) != (pack2->base[2] & 1)) {
893 XLOG("different RD");
894 return 0;
895 }
896
897 if (pack1->base[3] != pack2->base[3]) {
898 XLOG("different CD or AD");
899 return 0;
900 }
901
902 /* mark ID and header bytes as compared */
903 _dnsPacket_skip(pack1, 4);
904 _dnsPacket_skip(pack2, 4);
905
906 /* compare QDCOUNT */
907 count1 = _dnsPacket_readInt16(pack1);
908 count2 = _dnsPacket_readInt16(pack2);
909 if (count1 != count2 || count1 < 0) {
910 XLOG("different QDCOUNT");
911 return 0;
912 }
913
914 /* assume: ANcount and NScount are 0 */
915 _dnsPacket_skip(pack1, 4);
916 _dnsPacket_skip(pack2, 4);
917
918 /* compare ARCOUNT */
919 arcount1 = _dnsPacket_readInt16(pack1);
920 arcount2 = _dnsPacket_readInt16(pack2);
921 if (arcount1 != arcount2 || arcount1 < 0) {
922 XLOG("different ARCOUNT");
923 return 0;
924 }
925
926 /* compare the QDCOUNT QRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900927 for (; count1 > 0; count1--) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900928 if (!_dnsPacket_isEqualQR(pack1, pack2)) {
929 XLOG("different QR");
930 return 0;
931 }
932 }
933
934 /* compare the ARCOUNT RRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900935 for (; arcount1 > 0; arcount1--) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900936 if (!_dnsPacket_isEqualRR(pack1, pack2)) {
937 XLOG("different additional RR");
938 return 0;
939 }
940 }
941 return 1;
942}
943
944/****************************************************************************/
945/****************************************************************************/
946/***** *****/
947/***** *****/
948/***** *****/
949/****************************************************************************/
950/****************************************************************************/
951
952/* cache entry. for simplicity, 'hash' and 'hlink' are inlined in this
953 * structure though they are conceptually part of the hash table.
954 *
955 * similarly, mru_next and mru_prev are part of the global MRU list
956 */
957typedef struct Entry {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900958 unsigned int hash; /* hash value */
959 struct Entry* hlink; /* next in collision chain */
960 struct Entry* mru_prev;
961 struct Entry* mru_next;
Bernie Innocenti55864192018-08-30 04:05:20 +0900962
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900963 const uint8_t* query;
964 int querylen;
965 const uint8_t* answer;
966 int answerlen;
967 time_t expires; /* time_t when the entry isn't valid any more */
968 int id; /* for debugging purpose */
Bernie Innocenti55864192018-08-30 04:05:20 +0900969} Entry;
970
971/**
972 * Find the TTL for a negative DNS result. This is defined as the minimum
973 * of the SOA records TTL and the MINIMUM-TTL field (RFC-2308).
974 *
975 * Return 0 if not found.
976 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900977static u_long answer_getNegativeTTL(ns_msg handle) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900978 int n, nscount;
979 u_long result = 0;
980 ns_rr rr;
981
982 nscount = ns_msg_count(handle, ns_s_ns);
983 for (n = 0; n < nscount; n++) {
984 if ((ns_parserr(&handle, ns_s_ns, n, &rr) == 0) && (ns_rr_type(rr) == ns_t_soa)) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900985 const u_char* rdata = ns_rr_rdata(rr); // find the data
986 const u_char* edata = rdata + ns_rr_rdlen(rr); // add the len to find the end
Bernie Innocenti55864192018-08-30 04:05:20 +0900987 int len;
988 u_long ttl, rec_result = ns_rr_ttl(rr);
989
990 // find the MINIMUM-TTL field from the blob of binary data for this record
991 // skip the server name
992 len = dn_skipname(rdata, edata);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900993 if (len == -1) continue; // error skipping
Bernie Innocenti55864192018-08-30 04:05:20 +0900994 rdata += len;
995
996 // skip the admin name
997 len = dn_skipname(rdata, edata);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900998 if (len == -1) continue; // error skipping
Bernie Innocenti55864192018-08-30 04:05:20 +0900999 rdata += len;
1000
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001001 if (edata - rdata != 5 * NS_INT32SZ) continue;
Bernie Innocenti55864192018-08-30 04:05:20 +09001002 // skip: serial number + refresh interval + retry interval + expiry
1003 rdata += NS_INT32SZ * 4;
1004 // finally read the MINIMUM TTL
1005 ttl = ns_get32(rdata);
1006 if (ttl < rec_result) {
1007 rec_result = ttl;
1008 }
1009 // Now that the record is read successfully, apply the new min TTL
1010 if (n == 0 || rec_result < result) {
1011 result = rec_result;
1012 }
1013 }
1014 }
1015 return result;
1016}
1017
1018/**
1019 * Parse the answer records and find the appropriate
1020 * smallest TTL among the records. This might be from
1021 * the answer records if found or from the SOA record
1022 * if it's a negative result.
1023 *
1024 * The returned TTL is the number of seconds to
1025 * keep the answer in the cache.
1026 *
1027 * In case of parse error zero (0) is returned which
1028 * indicates that the answer shall not be cached.
1029 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001030static u_long answer_getTTL(const void* answer, int answerlen) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001031 ns_msg handle;
1032 int ancount, n;
1033 u_long result, ttl;
1034 ns_rr rr;
1035
1036 result = 0;
1037 if (ns_initparse(answer, answerlen, &handle) >= 0) {
1038 // get number of answer records
1039 ancount = ns_msg_count(handle, ns_s_an);
1040
1041 if (ancount == 0) {
1042 // a response with no answers? Cache this negative result.
1043 result = answer_getNegativeTTL(handle);
1044 } else {
1045 for (n = 0; n < ancount; n++) {
1046 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
1047 ttl = ns_rr_ttl(rr);
1048 if (n == 0 || ttl < result) {
1049 result = ttl;
1050 }
1051 } else {
1052 XLOG("ns_parserr failed ancount no = %d. errno = %s\n", n, strerror(errno));
1053 }
1054 }
1055 }
1056 } else {
1057 XLOG("ns_parserr failed. %s\n", strerror(errno));
1058 }
1059
1060 XLOG("TTL = %lu\n", result);
1061
1062 return result;
1063}
1064
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001065static void entry_free(Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001066 /* everything is allocated in a single memory block */
1067 if (e) {
1068 free(e);
1069 }
1070}
1071
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001072static __inline__ void entry_mru_remove(Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001073 e->mru_prev->mru_next = e->mru_next;
1074 e->mru_next->mru_prev = e->mru_prev;
1075}
1076
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001077static __inline__ void entry_mru_add(Entry* e, Entry* list) {
1078 Entry* first = list->mru_next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001079
1080 e->mru_next = first;
1081 e->mru_prev = list;
1082
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001083 list->mru_next = e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001084 first->mru_prev = e;
1085}
1086
1087/* compute the hash of a given entry, this is a hash of most
1088 * data in the query (key) */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001089static unsigned entry_hash(const Entry* e) {
1090 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001091
1092 _dnsPacket_init(pack, e->query, e->querylen);
1093 return _dnsPacket_hashQuery(pack);
1094}
1095
1096/* initialize an Entry as a search key, this also checks the input query packet
1097 * returns 1 on success, or 0 in case of unsupported/malformed data */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001098static int entry_init_key(Entry* e, const void* query, int querylen) {
1099 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001100
1101 memset(e, 0, sizeof(*e));
1102
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001103 e->query = query;
Bernie Innocenti55864192018-08-30 04:05:20 +09001104 e->querylen = querylen;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001105 e->hash = entry_hash(e);
Bernie Innocenti55864192018-08-30 04:05:20 +09001106
1107 _dnsPacket_init(pack, query, querylen);
1108
1109 return _dnsPacket_checkQuery(pack);
1110}
1111
1112/* allocate a new entry as a cache node */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001113static Entry* entry_alloc(const Entry* init, const void* answer, int answerlen) {
1114 Entry* e;
1115 int size;
Bernie Innocenti55864192018-08-30 04:05:20 +09001116
1117 size = sizeof(*e) + init->querylen + answerlen;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001118 e = calloc(size, 1);
1119 if (e == NULL) return e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001120
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001121 e->hash = init->hash;
1122 e->query = (const uint8_t*) (e + 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001123 e->querylen = init->querylen;
1124
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001125 memcpy((char*) e->query, init->query, e->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001126
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001127 e->answer = e->query + e->querylen;
Bernie Innocenti55864192018-08-30 04:05:20 +09001128 e->answerlen = answerlen;
1129
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001130 memcpy((char*) e->answer, answer, e->answerlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001131
1132 return e;
1133}
1134
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001135static int entry_equals(const Entry* e1, const Entry* e2) {
1136 DnsPacket pack1[1], pack2[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001137
1138 if (e1->querylen != e2->querylen) {
1139 return 0;
1140 }
1141 _dnsPacket_init(pack1, e1->query, e1->querylen);
1142 _dnsPacket_init(pack2, e2->query, e2->querylen);
1143
1144 return _dnsPacket_isEqualQuery(pack1, pack2);
1145}
1146
1147/****************************************************************************/
1148/****************************************************************************/
1149/***** *****/
1150/***** *****/
1151/***** *****/
1152/****************************************************************************/
1153/****************************************************************************/
1154
1155/* We use a simple hash table with external collision lists
1156 * for simplicity, the hash-table fields 'hash' and 'hlink' are
1157 * inlined in the Entry structure.
1158 */
1159
1160/* Maximum time for a thread to wait for an pending request */
1161#define PENDING_REQUEST_TIMEOUT 20;
1162
1163typedef struct pending_req_info {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001164 unsigned int hash;
1165 pthread_cond_t cond;
1166 struct pending_req_info* next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001167} PendingReqInfo;
1168
1169typedef struct resolv_cache {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001170 int max_entries;
1171 int num_entries;
1172 Entry mru_list;
1173 int last_id;
1174 Entry* entries;
1175 PendingReqInfo pending_requests;
Bernie Innocenti55864192018-08-30 04:05:20 +09001176} Cache;
1177
1178struct resolv_cache_info {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001179 unsigned netid;
1180 Cache* cache;
1181 struct resolv_cache_info* next;
1182 int nscount;
1183 char* nameservers[MAXNS];
1184 struct addrinfo* nsaddrinfo[MAXNS];
1185 int revision_id; // # times the nameservers have been replaced
1186 struct __res_params params;
1187 struct __res_stats nsstats[MAXNS];
1188 char defdname[MAXDNSRCHPATH];
1189 int dnsrch_offset[MAXDNSRCH + 1]; // offsets into defdname
Bernie Innocenti55864192018-08-30 04:05:20 +09001190};
1191
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001192#define HTABLE_VALID(x) ((x) != NULL && (x) != HTABLE_DELETED)
Bernie Innocenti55864192018-08-30 04:05:20 +09001193
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001194static pthread_once_t _res_cache_once = PTHREAD_ONCE_INIT;
Bernie Innocenti55864192018-08-30 04:05:20 +09001195static void _res_cache_init(void);
1196
1197// lock protecting everything in the _resolve_cache_info structs (next ptr, etc)
1198static pthread_mutex_t _res_cache_list_lock;
1199
1200/* gets cache associated with a network, or NULL if none exists */
1201static struct resolv_cache* _find_named_cache_locked(unsigned netid);
1202
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001203static void _cache_flush_pending_requests_locked(struct resolv_cache* cache) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001204 struct pending_req_info *ri, *tmp;
1205 if (cache) {
1206 ri = cache->pending_requests.next;
1207
1208 while (ri) {
1209 tmp = ri;
1210 ri = ri->next;
1211 pthread_cond_broadcast(&tmp->cond);
1212
1213 pthread_cond_destroy(&tmp->cond);
1214 free(tmp);
1215 }
1216
1217 cache->pending_requests.next = NULL;
1218 }
1219}
1220
1221/* Return 0 if no pending request is found matching the key.
1222 * If a matching request is found the calling thread will wait until
1223 * the matching request completes, then update *cache and return 1. */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001224static int _cache_check_pending_request_locked(struct resolv_cache** cache, Entry* key,
1225 unsigned netid) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001226 struct pending_req_info *ri, *prev;
1227 int exist = 0;
1228
1229 if (*cache && key) {
1230 ri = (*cache)->pending_requests.next;
1231 prev = &(*cache)->pending_requests;
1232 while (ri) {
1233 if (ri->hash == key->hash) {
1234 exist = 1;
1235 break;
1236 }
1237 prev = ri;
1238 ri = ri->next;
1239 }
1240
1241 if (!exist) {
1242 ri = calloc(1, sizeof(struct pending_req_info));
1243 if (ri) {
1244 ri->hash = key->hash;
1245 pthread_cond_init(&ri->cond, NULL);
1246 prev->next = ri;
1247 }
1248 } else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001249 struct timespec ts = {0, 0};
Bernie Innocenti55864192018-08-30 04:05:20 +09001250 XLOG("Waiting for previous request");
1251 ts.tv_sec = _time_now() + PENDING_REQUEST_TIMEOUT;
1252 pthread_cond_timedwait(&ri->cond, &_res_cache_list_lock, &ts);
1253 /* Must update *cache as it could have been deleted. */
1254 *cache = _find_named_cache_locked(netid);
1255 }
1256 }
1257
1258 return exist;
1259}
1260
1261/* notify any waiting thread that waiting on a request
1262 * matching the key has been added to the cache */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001263static void _cache_notify_waiting_tid_locked(struct resolv_cache* cache, Entry* key) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001264 struct pending_req_info *ri, *prev;
1265
1266 if (cache && key) {
1267 ri = cache->pending_requests.next;
1268 prev = &cache->pending_requests;
1269 while (ri) {
1270 if (ri->hash == key->hash) {
1271 pthread_cond_broadcast(&ri->cond);
1272 break;
1273 }
1274 prev = ri;
1275 ri = ri->next;
1276 }
1277
1278 // remove item from list and destroy
1279 if (ri) {
1280 prev->next = ri->next;
1281 pthread_cond_destroy(&ri->cond);
1282 free(ri);
1283 }
1284 }
1285}
1286
1287/* notify the cache that the query failed */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001288void _resolv_cache_query_failed(unsigned netid, const void* query, int querylen) {
1289 Entry key[1];
1290 Cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001291
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001292 if (!entry_init_key(key, query, querylen)) return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001293
1294 pthread_mutex_lock(&_res_cache_list_lock);
1295
1296 cache = _find_named_cache_locked(netid);
1297
1298 if (cache) {
1299 _cache_notify_waiting_tid_locked(cache, key);
1300 }
1301
1302 pthread_mutex_unlock(&_res_cache_list_lock);
1303}
1304
1305static struct resolv_cache_info* _find_cache_info_locked(unsigned netid);
1306
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001307static void _cache_flush_locked(Cache* cache) {
1308 int nn;
Bernie Innocenti55864192018-08-30 04:05:20 +09001309
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001310 for (nn = 0; nn < cache->max_entries; nn++) {
1311 Entry** pnode = (Entry**) &cache->entries[nn];
Bernie Innocenti55864192018-08-30 04:05:20 +09001312
1313 while (*pnode != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001314 Entry* node = *pnode;
Bernie Innocenti55864192018-08-30 04:05:20 +09001315 *pnode = node->hlink;
1316 entry_free(node);
1317 }
1318 }
1319
1320 // flush pending request
1321 _cache_flush_pending_requests_locked(cache);
1322
1323 cache->mru_list.mru_next = cache->mru_list.mru_prev = &cache->mru_list;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001324 cache->num_entries = 0;
1325 cache->last_id = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +09001326
1327 XLOG("*************************\n"
1328 "*** DNS CACHE FLUSHED ***\n"
1329 "*************************");
1330}
1331
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001332static int _res_cache_get_max_entries(void) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001333 int cache_size = CONFIG_MAX_ENTRIES;
1334
1335 const char* cache_mode = getenv("ANDROID_DNS_MODE");
1336 if (cache_mode == NULL || strcmp(cache_mode, "local") != 0) {
1337 // Don't use the cache in local mode. This is used by the proxy itself.
1338 cache_size = 0;
1339 }
1340
1341 XLOG("cache size: %d", cache_size);
1342 return cache_size;
1343}
1344
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001345static struct resolv_cache* _resolv_cache_create(void) {
1346 struct resolv_cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001347
1348 cache = calloc(sizeof(*cache), 1);
1349 if (cache) {
1350 cache->max_entries = _res_cache_get_max_entries();
1351 cache->entries = calloc(sizeof(*cache->entries), cache->max_entries);
1352 if (cache->entries) {
1353 cache->mru_list.mru_prev = cache->mru_list.mru_next = &cache->mru_list;
1354 XLOG("%s: cache created\n", __FUNCTION__);
1355 } else {
1356 free(cache);
1357 cache = NULL;
1358 }
1359 }
1360 return cache;
1361}
1362
Bernie Innocenti55864192018-08-30 04:05:20 +09001363#if DEBUG
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001364static void _dump_query(const uint8_t* query, int querylen) {
1365 char temp[256], *p = temp, *end = p + sizeof(temp);
1366 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001367
1368 _dnsPacket_init(pack, query, querylen);
1369 p = _dnsPacket_bprintQuery(pack, p, end);
1370 XLOG("QUERY: %s", temp);
1371}
1372
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001373static void _cache_dump_mru(Cache* cache) {
1374 char temp[512], *p = temp, *end = p + sizeof(temp);
1375 Entry* e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001376
1377 p = _bprint(temp, end, "MRU LIST (%2d): ", cache->num_entries);
1378 for (e = cache->mru_list.mru_next; e != &cache->mru_list; e = e->mru_next)
1379 p = _bprint(p, end, " %d", e->id);
1380
1381 XLOG("%s", temp);
1382}
1383
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001384static void _dump_answer(const void* answer, int answerlen) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001385 res_state statep;
1386 FILE* fp;
1387 char* buf;
1388 int fileLen;
1389
1390 fp = fopen("/data/reslog.txt", "w+e");
1391 if (fp != NULL) {
1392 statep = __res_get_state();
1393
1394 res_pquery(statep, answer, answerlen, fp);
1395
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001396 // Get file length
Bernie Innocenti55864192018-08-30 04:05:20 +09001397 fseek(fp, 0, SEEK_END);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001398 fileLen = ftell(fp);
Bernie Innocenti55864192018-08-30 04:05:20 +09001399 fseek(fp, 0, SEEK_SET);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001400 buf = (char*) malloc(fileLen + 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001401 if (buf != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001402 // Read file contents into buffer
Bernie Innocenti55864192018-08-30 04:05:20 +09001403 fread(buf, fileLen, 1, fp);
1404 XLOG("%s\n", buf);
1405 free(buf);
1406 }
1407 fclose(fp);
1408 remove("/data/reslog.txt");
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001409 } else {
1410 errno = 0; // else debug is introducing error signals
Bernie Innocenti55864192018-08-30 04:05:20 +09001411 XLOG("%s: can't open file\n", __FUNCTION__);
1412 }
1413}
1414#endif
1415
1416#if DEBUG
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001417#define XLOG_QUERY(q, len) _dump_query((q), (len))
1418#define XLOG_ANSWER(a, len) _dump_answer((a), (len))
Bernie Innocenti55864192018-08-30 04:05:20 +09001419#else
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001420#define XLOG_QUERY(q, len) ((void) 0)
1421#define XLOG_ANSWER(a, len) ((void) 0)
Bernie Innocenti55864192018-08-30 04:05:20 +09001422#endif
1423
1424/* This function tries to find a key within the hash table
1425 * In case of success, it will return a *pointer* to the hashed key.
1426 * In case of failure, it will return a *pointer* to NULL
1427 *
1428 * So, the caller must check '*result' to check for success/failure.
1429 *
1430 * The main idea is that the result can later be used directly in
1431 * calls to _resolv_cache_add or _resolv_cache_remove as the 'lookup'
1432 * parameter. This makes the code simpler and avoids re-searching
1433 * for the key position in the htable.
1434 *
1435 * The result of a lookup_p is only valid until you alter the hash
1436 * table.
1437 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001438static Entry** _cache_lookup_p(Cache* cache, Entry* key) {
1439 int index = key->hash % cache->max_entries;
1440 Entry** pnode = (Entry**) &cache->entries[index];
Bernie Innocenti55864192018-08-30 04:05:20 +09001441
1442 while (*pnode != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001443 Entry* node = *pnode;
Bernie Innocenti55864192018-08-30 04:05:20 +09001444
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001445 if (node == NULL) break;
Bernie Innocenti55864192018-08-30 04:05:20 +09001446
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001447 if (node->hash == key->hash && entry_equals(node, key)) break;
Bernie Innocenti55864192018-08-30 04:05:20 +09001448
1449 pnode = &node->hlink;
1450 }
1451 return pnode;
1452}
1453
1454/* Add a new entry to the hash table. 'lookup' must be the
1455 * result of an immediate previous failed _lookup_p() call
1456 * (i.e. with *lookup == NULL), and 'e' is the pointer to the
1457 * newly created entry
1458 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001459static void _cache_add_p(Cache* cache, Entry** lookup, Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001460 *lookup = e;
1461 e->id = ++cache->last_id;
1462 entry_mru_add(e, &cache->mru_list);
1463 cache->num_entries += 1;
1464
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001465 XLOG("%s: entry %d added (count=%d)", __FUNCTION__, e->id, cache->num_entries);
Bernie Innocenti55864192018-08-30 04:05:20 +09001466}
1467
1468/* Remove an existing entry from the hash table,
1469 * 'lookup' must be the result of an immediate previous
1470 * and succesful _lookup_p() call.
1471 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001472static void _cache_remove_p(Cache* cache, Entry** lookup) {
1473 Entry* e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001474
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001475 XLOG("%s: entry %d removed (count=%d)", __FUNCTION__, e->id, cache->num_entries - 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001476
1477 entry_mru_remove(e);
1478 *lookup = e->hlink;
1479 entry_free(e);
1480 cache->num_entries -= 1;
1481}
1482
1483/* Remove the oldest entry from the hash table.
1484 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001485static void _cache_remove_oldest(Cache* cache) {
1486 Entry* oldest = cache->mru_list.mru_prev;
1487 Entry** lookup = _cache_lookup_p(cache, oldest);
Bernie Innocenti55864192018-08-30 04:05:20 +09001488
1489 if (*lookup == NULL) { /* should not happen */
1490 XLOG("%s: OLDEST NOT IN HTABLE ?", __FUNCTION__);
1491 return;
1492 }
1493 if (DEBUG) {
1494 XLOG("Cache full - removing oldest");
1495 XLOG_QUERY(oldest->query, oldest->querylen);
1496 }
1497 _cache_remove_p(cache, lookup);
1498}
1499
1500/* Remove all expired entries from the hash table.
1501 */
1502static void _cache_remove_expired(Cache* cache) {
1503 Entry* e;
1504 time_t now = _time_now();
1505
1506 for (e = cache->mru_list.mru_next; e != &cache->mru_list;) {
1507 // Entry is old, remove
1508 if (now >= e->expires) {
1509 Entry** lookup = _cache_lookup_p(cache, e);
1510 if (*lookup == NULL) { /* should not happen */
1511 XLOG("%s: ENTRY NOT IN HTABLE ?", __FUNCTION__);
1512 return;
1513 }
1514 e = e->mru_next;
1515 _cache_remove_p(cache, lookup);
1516 } else {
1517 e = e->mru_next;
1518 }
1519 }
1520}
1521
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001522ResolvCacheStatus _resolv_cache_lookup(unsigned netid, const void* query, int querylen,
1523 void* answer, int answersize, int* answerlen) {
1524 Entry key[1];
1525 Entry** lookup;
1526 Entry* e;
1527 time_t now;
1528 Cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001529
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001530 ResolvCacheStatus result = RESOLV_CACHE_NOTFOUND;
Bernie Innocenti55864192018-08-30 04:05:20 +09001531
1532 XLOG("%s: lookup", __FUNCTION__);
1533 XLOG_QUERY(query, querylen);
1534
1535 /* we don't cache malformed queries */
1536 if (!entry_init_key(key, query, querylen)) {
1537 XLOG("%s: unsupported query", __FUNCTION__);
1538 return RESOLV_CACHE_UNSUPPORTED;
1539 }
1540 /* lookup cache */
1541 pthread_once(&_res_cache_once, _res_cache_init);
1542 pthread_mutex_lock(&_res_cache_list_lock);
1543
1544 cache = _find_named_cache_locked(netid);
1545 if (cache == NULL) {
1546 result = RESOLV_CACHE_UNSUPPORTED;
1547 goto Exit;
1548 }
1549
1550 /* see the description of _lookup_p to understand this.
1551 * the function always return a non-NULL pointer.
1552 */
1553 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001554 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001555
1556 if (e == NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001557 XLOG("NOT IN CACHE");
Bernie Innocenti55864192018-08-30 04:05:20 +09001558 // calling thread will wait if an outstanding request is found
1559 // that matching this query
1560 if (!_cache_check_pending_request_locked(&cache, key, netid) || cache == NULL) {
1561 goto Exit;
1562 } else {
1563 lookup = _cache_lookup_p(cache, key);
1564 e = *lookup;
1565 if (e == NULL) {
1566 goto Exit;
1567 }
1568 }
1569 }
1570
1571 now = _time_now();
1572
1573 /* remove stale entries here */
1574 if (now >= e->expires) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001575 XLOG(" NOT IN CACHE (STALE ENTRY %p DISCARDED)", *lookup);
Bernie Innocenti55864192018-08-30 04:05:20 +09001576 XLOG_QUERY(e->query, e->querylen);
1577 _cache_remove_p(cache, lookup);
1578 goto Exit;
1579 }
1580
1581 *answerlen = e->answerlen;
1582 if (e->answerlen > answersize) {
1583 /* NOTE: we return UNSUPPORTED if the answer buffer is too short */
1584 result = RESOLV_CACHE_UNSUPPORTED;
1585 XLOG(" ANSWER TOO LONG");
1586 goto Exit;
1587 }
1588
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001589 memcpy(answer, e->answer, e->answerlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001590
1591 /* bump up this entry to the top of the MRU list */
1592 if (e != cache->mru_list.mru_next) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001593 entry_mru_remove(e);
1594 entry_mru_add(e, &cache->mru_list);
Bernie Innocenti55864192018-08-30 04:05:20 +09001595 }
1596
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001597 XLOG("FOUND IN CACHE entry=%p", e);
Bernie Innocenti55864192018-08-30 04:05:20 +09001598 result = RESOLV_CACHE_FOUND;
1599
1600Exit:
1601 pthread_mutex_unlock(&_res_cache_list_lock);
1602 return result;
1603}
1604
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001605void _resolv_cache_add(unsigned netid, const void* query, int querylen, const void* answer,
1606 int answerlen) {
1607 Entry key[1];
1608 Entry* e;
1609 Entry** lookup;
1610 u_long ttl;
1611 Cache* cache = NULL;
Bernie Innocenti55864192018-08-30 04:05:20 +09001612
1613 /* don't assume that the query has already been cached
1614 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001615 if (!entry_init_key(key, query, querylen)) {
1616 XLOG("%s: passed invalid query ?", __FUNCTION__);
Bernie Innocenti55864192018-08-30 04:05:20 +09001617 return;
1618 }
1619
1620 pthread_mutex_lock(&_res_cache_list_lock);
1621
1622 cache = _find_named_cache_locked(netid);
1623 if (cache == NULL) {
1624 goto Exit;
1625 }
1626
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001627 XLOG("%s: query:", __FUNCTION__);
1628 XLOG_QUERY(query, querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001629 XLOG_ANSWER(answer, answerlen);
1630#if DEBUG_DATA
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001631 XLOG("answer:");
1632 XLOG_BYTES(answer, answerlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001633#endif
1634
1635 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001636 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001637
1638 if (e != NULL) { /* should not happen */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001639 XLOG("%s: ALREADY IN CACHE (%p) ? IGNORING ADD", __FUNCTION__, e);
Bernie Innocenti55864192018-08-30 04:05:20 +09001640 goto Exit;
1641 }
1642
1643 if (cache->num_entries >= cache->max_entries) {
1644 _cache_remove_expired(cache);
1645 if (cache->num_entries >= cache->max_entries) {
1646 _cache_remove_oldest(cache);
1647 }
1648 /* need to lookup again */
1649 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001650 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001651 if (e != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001652 XLOG("%s: ALREADY IN CACHE (%p) ? IGNORING ADD", __FUNCTION__, e);
Bernie Innocenti55864192018-08-30 04:05:20 +09001653 goto Exit;
1654 }
1655 }
1656
1657 ttl = answer_getTTL(answer, answerlen);
1658 if (ttl > 0) {
1659 e = entry_alloc(key, answer, answerlen);
1660 if (e != NULL) {
1661 e->expires = ttl + _time_now();
1662 _cache_add_p(cache, lookup, e);
1663 }
1664 }
1665#if DEBUG
1666 _cache_dump_mru(cache);
1667#endif
1668Exit:
1669 if (cache != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001670 _cache_notify_waiting_tid_locked(cache, key);
Bernie Innocenti55864192018-08-30 04:05:20 +09001671 }
1672 pthread_mutex_unlock(&_res_cache_list_lock);
1673}
1674
1675/****************************************************************************/
1676/****************************************************************************/
1677/***** *****/
1678/***** *****/
1679/***** *****/
1680/****************************************************************************/
1681/****************************************************************************/
1682
1683// Head of the list of caches. Protected by _res_cache_list_lock.
1684static struct resolv_cache_info _res_cache_list;
1685
1686/* insert resolv_cache_info into the list of resolv_cache_infos */
1687static void _insert_cache_info_locked(struct resolv_cache_info* cache_info);
1688/* creates a resolv_cache_info */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001689static struct resolv_cache_info* _create_cache_info(void);
Bernie Innocenti55864192018-08-30 04:05:20 +09001690/* gets a resolv_cache_info associated with a network, or NULL if not found */
1691static struct resolv_cache_info* _find_cache_info_locked(unsigned netid);
1692/* look up the named cache, and creates one if needed */
1693static struct resolv_cache* _get_res_cache_for_net_locked(unsigned netid);
1694/* empty the named cache */
1695static void _flush_cache_for_net_locked(unsigned netid);
1696/* empty the nameservers set for the named cache */
1697static void _free_nameservers_locked(struct resolv_cache_info* cache_info);
1698/* return 1 if the provided list of name servers differs from the list of name servers
1699 * currently attached to the provided cache_info */
1700static int _resolv_is_nameservers_equal_locked(struct resolv_cache_info* cache_info,
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001701 const char** servers, int numservers);
Bernie Innocenti55864192018-08-30 04:05:20 +09001702/* clears the stats samples contained withing the given cache_info */
1703static void _res_cache_clear_stats_locked(struct resolv_cache_info* cache_info);
1704
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001705static void _res_cache_init(void) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001706 memset(&_res_cache_list, 0, sizeof(_res_cache_list));
1707 pthread_mutex_init(&_res_cache_list_lock, NULL);
1708}
1709
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001710static struct resolv_cache* _get_res_cache_for_net_locked(unsigned netid) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001711 struct resolv_cache* cache = _find_named_cache_locked(netid);
1712 if (!cache) {
1713 struct resolv_cache_info* cache_info = _create_cache_info();
1714 if (cache_info) {
1715 cache = _resolv_cache_create();
1716 if (cache) {
1717 cache_info->cache = cache;
1718 cache_info->netid = netid;
1719 _insert_cache_info_locked(cache_info);
1720 } else {
1721 free(cache_info);
1722 }
1723 }
1724 }
1725 return cache;
1726}
1727
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001728void _resolv_flush_cache_for_net(unsigned netid) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001729 pthread_once(&_res_cache_once, _res_cache_init);
1730 pthread_mutex_lock(&_res_cache_list_lock);
1731
1732 _flush_cache_for_net_locked(netid);
1733
1734 pthread_mutex_unlock(&_res_cache_list_lock);
1735}
1736
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001737static void _flush_cache_for_net_locked(unsigned netid) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001738 struct resolv_cache* cache = _find_named_cache_locked(netid);
1739 if (cache) {
1740 _cache_flush_locked(cache);
1741 }
1742
1743 // Also clear the NS statistics.
1744 struct resolv_cache_info* cache_info = _find_cache_info_locked(netid);
1745 _res_cache_clear_stats_locked(cache_info);
1746}
1747
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001748void _resolv_delete_cache_for_net(unsigned netid) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001749 pthread_once(&_res_cache_once, _res_cache_init);
1750 pthread_mutex_lock(&_res_cache_list_lock);
1751
1752 struct resolv_cache_info* prev_cache_info = &_res_cache_list;
1753
1754 while (prev_cache_info->next) {
1755 struct resolv_cache_info* cache_info = prev_cache_info->next;
1756
1757 if (cache_info->netid == netid) {
1758 prev_cache_info->next = cache_info->next;
1759 _cache_flush_locked(cache_info->cache);
1760 free(cache_info->cache->entries);
1761 free(cache_info->cache);
1762 _free_nameservers_locked(cache_info);
1763 free(cache_info);
1764 break;
1765 }
1766
1767 prev_cache_info = prev_cache_info->next;
1768 }
1769
1770 pthread_mutex_unlock(&_res_cache_list_lock);
1771}
1772
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001773static struct resolv_cache_info* _create_cache_info(void) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001774 struct resolv_cache_info* cache_info;
1775
1776 cache_info = calloc(sizeof(*cache_info), 1);
1777 return cache_info;
1778}
1779
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001780static void _insert_cache_info_locked(struct resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001781 struct resolv_cache_info* last;
1782
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001783 for (last = &_res_cache_list; last->next; last = last->next)
1784 ;
Bernie Innocenti55864192018-08-30 04:05:20 +09001785
1786 last->next = cache_info;
Bernie Innocenti55864192018-08-30 04:05:20 +09001787}
1788
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001789static struct resolv_cache* _find_named_cache_locked(unsigned netid) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001790 struct resolv_cache_info* info = _find_cache_info_locked(netid);
1791
1792 if (info != NULL) return info->cache;
1793
1794 return NULL;
1795}
1796
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001797static struct resolv_cache_info* _find_cache_info_locked(unsigned netid) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001798 struct resolv_cache_info* cache_info = _res_cache_list.next;
1799
1800 while (cache_info) {
1801 if (cache_info->netid == netid) {
1802 break;
1803 }
1804
1805 cache_info = cache_info->next;
1806 }
1807 return cache_info;
1808}
1809
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001810void _resolv_set_default_params(struct __res_params* params) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001811 params->sample_validity = NSSAMPLE_VALIDITY;
1812 params->success_threshold = SUCCESS_THRESHOLD;
1813 params->min_samples = 0;
1814 params->max_samples = 0;
1815 params->base_timeout_msec = 0; // 0 = legacy algorithm
1816}
1817
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001818int _resolv_set_nameservers_for_net(unsigned netid, const char** servers, unsigned numservers,
1819 const char* domains, const struct __res_params* params) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001820 char sbuf[NI_MAXSERV];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001821 register char* cp;
1822 int* offset;
Bernie Innocenti55864192018-08-30 04:05:20 +09001823 struct addrinfo* nsaddrinfo[MAXNS];
1824
1825 if (numservers > MAXNS) {
1826 XLOG("%s: numservers=%u, MAXNS=%u", __FUNCTION__, numservers, MAXNS);
1827 return E2BIG;
1828 }
1829
1830 // Parse the addresses before actually locking or changing any state, in case there is an error.
1831 // As a side effect this also reduces the time the lock is kept.
1832 struct addrinfo hints = {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001833 .ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM, .ai_flags = AI_NUMERICHOST};
Bernie Innocenti55864192018-08-30 04:05:20 +09001834 snprintf(sbuf, sizeof(sbuf), "%u", NAMESERVER_PORT);
1835 for (unsigned i = 0; i < numservers; i++) {
1836 // The addrinfo structures allocated here are freed in _free_nameservers_locked().
1837 int rt = getaddrinfo(servers[i], sbuf, &hints, &nsaddrinfo[i]);
1838 if (rt != 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001839 for (unsigned j = 0; j < i; j++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001840 freeaddrinfo(nsaddrinfo[j]);
1841 nsaddrinfo[j] = NULL;
1842 }
1843 XLOG("%s: getaddrinfo(%s)=%s", __FUNCTION__, servers[i], gai_strerror(rt));
1844 return EINVAL;
1845 }
1846 }
1847
1848 pthread_once(&_res_cache_once, _res_cache_init);
1849 pthread_mutex_lock(&_res_cache_list_lock);
1850
1851 // creates the cache if not created
1852 _get_res_cache_for_net_locked(netid);
1853
1854 struct resolv_cache_info* cache_info = _find_cache_info_locked(netid);
1855
1856 if (cache_info != NULL) {
1857 uint8_t old_max_samples = cache_info->params.max_samples;
1858 if (params != NULL) {
1859 cache_info->params = *params;
1860 } else {
1861 _resolv_set_default_params(&cache_info->params);
1862 }
1863
1864 if (!_resolv_is_nameservers_equal_locked(cache_info, servers, numservers)) {
1865 // free current before adding new
1866 _free_nameservers_locked(cache_info);
1867 unsigned i;
1868 for (i = 0; i < numservers; i++) {
1869 cache_info->nsaddrinfo[i] = nsaddrinfo[i];
1870 cache_info->nameservers[i] = strdup(servers[i]);
1871 XLOG("%s: netid = %u, addr = %s\n", __FUNCTION__, netid, servers[i]);
1872 }
1873 cache_info->nscount = numservers;
1874
1875 // Clear the NS statistics because the mapping to nameservers might have changed.
1876 _res_cache_clear_stats_locked(cache_info);
1877
1878 // increment the revision id to ensure that sample state is not written back if the
1879 // servers change; in theory it would suffice to do so only if the servers or
1880 // max_samples actually change, in practice the overhead of checking is higher than the
1881 // cost, and overflows are unlikely
1882 ++cache_info->revision_id;
1883 } else if (cache_info->params.max_samples != old_max_samples) {
1884 // If the maximum number of samples changes, the overhead of keeping the most recent
1885 // samples around is not considered worth the effort, so they are cleared instead. All
1886 // other parameters do not affect shared state: Changing these parameters does not
1887 // invalidate the samples, as they only affect aggregation and the conditions under
1888 // which servers are considered usable.
1889 _res_cache_clear_stats_locked(cache_info);
1890 ++cache_info->revision_id;
1891 }
1892
1893 // Always update the search paths, since determining whether they actually changed is
1894 // complex due to the zero-padding, and probably not worth the effort. Cache-flushing
1895 // however is not // necessary, since the stored cache entries do contain the domain, not
1896 // just the host name.
1897 // code moved from res_init.c, load_domain_search_list
1898 strlcpy(cache_info->defdname, domains, sizeof(cache_info->defdname));
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001899 if ((cp = strchr(cache_info->defdname, '\n')) != NULL) *cp = '\0';
Bernie Innocenti55864192018-08-30 04:05:20 +09001900
1901 cp = cache_info->defdname;
1902 offset = cache_info->dnsrch_offset;
1903 while (offset < cache_info->dnsrch_offset + MAXDNSRCH) {
1904 while (*cp == ' ' || *cp == '\t') /* skip leading white space */
1905 cp++;
1906 if (*cp == '\0') /* stop if nothing more to do */
1907 break;
1908 *offset++ = cp - cache_info->defdname; /* record this search domain */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001909 while (*cp) { /* zero-terminate it */
1910 if (*cp == ' ' || *cp == '\t') {
Bernie Innocenti55864192018-08-30 04:05:20 +09001911 *cp++ = '\0';
1912 break;
1913 }
1914 cp++;
1915 }
1916 }
1917 *offset = -1; /* cache_info->dnsrch_offset has MAXDNSRCH+1 items */
1918 }
1919
1920 pthread_mutex_unlock(&_res_cache_list_lock);
1921 return 0;
1922}
1923
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001924static int _resolv_is_nameservers_equal_locked(struct resolv_cache_info* cache_info,
1925 const char** servers, int numservers) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001926 if (cache_info->nscount != numservers) {
1927 return 0;
1928 }
1929
1930 // Compare each name server against current name servers.
1931 // TODO: this is incorrect if the list of current or previous nameservers
1932 // contains duplicates. This does not really matter because the framework
1933 // filters out duplicates, but we should probably fix it. It's also
1934 // insensitive to the order of the nameservers; we should probably fix that
1935 // too.
1936 for (int i = 0; i < numservers; i++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001937 for (int j = 0;; j++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001938 if (j >= numservers) {
1939 return 0;
1940 }
1941 if (strcmp(cache_info->nameservers[i], servers[j]) == 0) {
1942 break;
1943 }
1944 }
1945 }
1946
1947 return 1;
1948}
1949
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001950static void _free_nameservers_locked(struct resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001951 int i;
1952 for (i = 0; i < cache_info->nscount; i++) {
1953 free(cache_info->nameservers[i]);
1954 cache_info->nameservers[i] = NULL;
1955 if (cache_info->nsaddrinfo[i] != NULL) {
1956 freeaddrinfo(cache_info->nsaddrinfo[i]);
1957 cache_info->nsaddrinfo[i] = NULL;
1958 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001959 cache_info->nsstats[i].sample_count = cache_info->nsstats[i].sample_next = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +09001960 }
1961 cache_info->nscount = 0;
1962 _res_cache_clear_stats_locked(cache_info);
1963 ++cache_info->revision_id;
1964}
1965
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001966void _resolv_populate_res_for_net(res_state statp) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001967 if (statp == NULL) {
1968 return;
1969 }
1970
1971 pthread_once(&_res_cache_once, _res_cache_init);
1972 pthread_mutex_lock(&_res_cache_list_lock);
1973
1974 struct resolv_cache_info* info = _find_cache_info_locked(statp->netid);
1975 if (info != NULL) {
1976 int nserv;
1977 struct addrinfo* ai;
1978 XLOG("%s: %u\n", __FUNCTION__, statp->netid);
1979 for (nserv = 0; nserv < MAXNS; nserv++) {
1980 ai = info->nsaddrinfo[nserv];
1981 if (ai == NULL) {
1982 break;
1983 }
1984
1985 if ((size_t) ai->ai_addrlen <= sizeof(statp->_u._ext.ext->nsaddrs[0])) {
1986 if (statp->_u._ext.ext != NULL) {
1987 memcpy(&statp->_u._ext.ext->nsaddrs[nserv], ai->ai_addr, ai->ai_addrlen);
1988 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
1989 } else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001990 if ((size_t) ai->ai_addrlen <= sizeof(statp->nsaddr_list[0])) {
1991 memcpy(&statp->nsaddr_list[nserv], ai->ai_addr, ai->ai_addrlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001992 } else {
1993 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
1994 }
1995 }
1996 } else {
1997 XLOG("%s: found too long addrlen", __FUNCTION__);
1998 }
1999 }
2000 statp->nscount = nserv;
2001 // now do search domains. Note that we cache the offsets as this code runs alot
2002 // but the setting/offset-computer only runs when set/changed
2003 // WARNING: Don't use str*cpy() here, this string contains zeroes.
2004 memcpy(statp->defdname, info->defdname, sizeof(statp->defdname));
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002005 register char** pp = statp->dnsrch;
2006 register int* p = info->dnsrch_offset;
Bernie Innocenti55864192018-08-30 04:05:20 +09002007 while (pp < statp->dnsrch + MAXDNSRCH && *p != -1) {
2008 *pp++ = &statp->defdname[0] + *p++;
2009 }
2010 }
2011 pthread_mutex_unlock(&_res_cache_list_lock);
2012}
2013
2014/* Resolver reachability statistics. */
2015
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002016static void _res_cache_add_stats_sample_locked(struct __res_stats* stats,
2017 const struct __res_sample* sample, int max_samples) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002018 // Note: This function expects max_samples > 0, otherwise a (harmless) modification of the
2019 // allocated but supposedly unused memory for samples[0] will happen
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002020 XLOG("%s: adding sample to stats, next = %d, count = %d", __FUNCTION__, stats->sample_next,
2021 stats->sample_count);
Bernie Innocenti55864192018-08-30 04:05:20 +09002022 stats->samples[stats->sample_next] = *sample;
2023 if (stats->sample_count < max_samples) {
2024 ++stats->sample_count;
2025 }
2026 if (++stats->sample_next >= max_samples) {
2027 stats->sample_next = 0;
2028 }
2029}
2030
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002031static void _res_cache_clear_stats_locked(struct resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002032 if (cache_info) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002033 for (int i = 0; i < MAXNS; ++i) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002034 cache_info->nsstats->sample_count = cache_info->nsstats->sample_next = 0;
2035 }
2036 }
2037}
2038
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002039int android_net_res_stats_get_info_for_net(unsigned netid, int* nscount,
2040 struct sockaddr_storage servers[MAXNS], int* dcount,
2041 char domains[MAXDNSRCH][MAXDNSRCHPATH],
2042 struct __res_params* params,
2043 struct __res_stats stats[MAXNS]) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002044 int revision_id = -1;
2045 pthread_mutex_lock(&_res_cache_list_lock);
2046
2047 struct resolv_cache_info* info = _find_cache_info_locked(netid);
2048 if (info) {
2049 if (info->nscount > MAXNS) {
2050 pthread_mutex_unlock(&_res_cache_list_lock);
2051 XLOG("%s: nscount %d > MAXNS %d", __FUNCTION__, info->nscount, MAXNS);
2052 errno = EFAULT;
2053 return -1;
2054 }
2055 int i;
2056 for (i = 0; i < info->nscount; i++) {
2057 // Verify that the following assumptions are held, failure indicates corruption:
2058 // - getaddrinfo() may never return a sockaddr > sockaddr_storage
2059 // - all addresses are valid
2060 // - there is only one address per addrinfo thanks to numeric resolution
2061 int addrlen = info->nsaddrinfo[i]->ai_addrlen;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002062 if (addrlen < (int) sizeof(struct sockaddr) || addrlen > (int) sizeof(servers[0])) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002063 pthread_mutex_unlock(&_res_cache_list_lock);
2064 XLOG("%s: nsaddrinfo[%d].ai_addrlen == %d", __FUNCTION__, i, addrlen);
2065 errno = EMSGSIZE;
2066 return -1;
2067 }
2068 if (info->nsaddrinfo[i]->ai_addr == NULL) {
2069 pthread_mutex_unlock(&_res_cache_list_lock);
2070 XLOG("%s: nsaddrinfo[%d].ai_addr == NULL", __FUNCTION__, i);
2071 errno = ENOENT;
2072 return -1;
2073 }
2074 if (info->nsaddrinfo[i]->ai_next != NULL) {
2075 pthread_mutex_unlock(&_res_cache_list_lock);
2076 XLOG("%s: nsaddrinfo[%d].ai_next != NULL", __FUNCTION__, i);
2077 errno = ENOTUNIQ;
2078 return -1;
2079 }
2080 }
2081 *nscount = info->nscount;
2082 for (i = 0; i < info->nscount; i++) {
2083 memcpy(&servers[i], info->nsaddrinfo[i]->ai_addr, info->nsaddrinfo[i]->ai_addrlen);
2084 stats[i] = info->nsstats[i];
2085 }
2086 for (i = 0; i < MAXDNSRCH; i++) {
2087 const char* cur_domain = info->defdname + info->dnsrch_offset[i];
2088 // dnsrch_offset[i] can either be -1 or point to an empty string to indicate the end
2089 // of the search offsets. Checking for < 0 is not strictly necessary, but safer.
2090 // TODO: Pass in a search domain array instead of a string to
2091 // _resolv_set_nameservers_for_net() and make this double check unnecessary.
2092 if (info->dnsrch_offset[i] < 0 ||
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002093 ((size_t) info->dnsrch_offset[i]) >= sizeof(info->defdname) || !cur_domain[0]) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002094 break;
2095 }
2096 strlcpy(domains[i], cur_domain, MAXDNSRCHPATH);
2097 }
2098 *dcount = i;
2099 *params = info->params;
2100 revision_id = info->revision_id;
2101 }
2102
2103 pthread_mutex_unlock(&_res_cache_list_lock);
2104 return revision_id;
2105}
2106
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002107int _resolv_cache_get_resolver_stats(unsigned netid, struct __res_params* params,
2108 struct __res_stats stats[MAXNS]) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002109 int revision_id = -1;
2110 pthread_mutex_lock(&_res_cache_list_lock);
2111
2112 struct resolv_cache_info* info = _find_cache_info_locked(netid);
2113 if (info) {
2114 memcpy(stats, info->nsstats, sizeof(info->nsstats));
2115 *params = info->params;
2116 revision_id = info->revision_id;
2117 }
2118
2119 pthread_mutex_unlock(&_res_cache_list_lock);
2120 return revision_id;
2121}
2122
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002123void _resolv_cache_add_resolver_stats_sample(unsigned netid, int revision_id, int ns,
2124 const struct __res_sample* sample, int max_samples) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002125 if (max_samples <= 0) return;
2126
2127 pthread_mutex_lock(&_res_cache_list_lock);
2128
2129 struct resolv_cache_info* info = _find_cache_info_locked(netid);
2130
2131 if (info && info->revision_id == revision_id) {
2132 _res_cache_add_stats_sample_locked(&info->nsstats[ns], sample, max_samples);
2133 }
2134
2135 pthread_mutex_unlock(&_res_cache_list_lock);
2136}