blob: 39a0c1ede2ce2af145d9c74e345a5cb391624757 [file] [log] [blame]
Bernie Innocenti55864192018-08-30 04:05:20 +09001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090029// NOTE: verbose logging MUST NOT be left enabled in production binaries.
30// It floods logs at high rate, and can leak privacy-sensitive information.
31constexpr bool kVerboseLogging = false;
32constexpr bool kDumpData = false;
33#define LOG_TAG "res_cache"
34
Bernie Innocentif89b3512018-08-30 07:34:37 +090035#include <pthread.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090036#include <resolv.h>
37#include <stdarg.h>
38#include <stdio.h>
39#include <stdlib.h>
40#include <string.h>
41#include <time.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090042
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090043#include <arpa/inet.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090044#include <arpa/nameser.h>
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090045#include <errno.h>
46#include <linux/if.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090047#include <net/if.h>
48#include <netdb.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090049
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090050#include <android-base/logging.h>
Bernie Innocentif89b3512018-08-30 07:34:37 +090051
Bernie Innocenti55864192018-08-30 04:05:20 +090052#include "res_private.h"
Bernie Innocentif89b3512018-08-30 07:34:37 +090053#include "resolv_cache.h"
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090054#include "resolv_netid.h"
55#include "resolv_private.h"
Bernie Innocenti55864192018-08-30 04:05:20 +090056
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090057#define VLOG if (!kVerboseLogging) {} else LOG(INFO)
58
59#ifndef RESOLV_ALLOW_VERBOSE_LOGGING
60static_assert(kVerboseLogging == false && kDumpData == false,
61 "Verbose logging floods logs at high-rate and exposes privacy-sensitive information. "
62 "Do not enable in release builds.");
63#endif
Bernie Innocenti55864192018-08-30 04:05:20 +090064
65/* This code implements a small and *simple* DNS resolver cache.
66 *
67 * It is only used to cache DNS answers for a time defined by the smallest TTL
68 * among the answer records in order to reduce DNS traffic. It is not supposed
69 * to be a full DNS cache, since we plan to implement that in the future in a
70 * dedicated process running on the system.
71 *
72 * Note that its design is kept simple very intentionally, i.e.:
73 *
74 * - it takes raw DNS query packet data as input, and returns raw DNS
75 * answer packet data as output
76 *
77 * (this means that two similar queries that encode the DNS name
78 * differently will be treated distinctly).
79 *
80 * the smallest TTL value among the answer records are used as the time
81 * to keep an answer in the cache.
82 *
83 * this is bad, but we absolutely want to avoid parsing the answer packets
84 * (and should be solved by the later full DNS cache process).
85 *
86 * - the implementation is just a (query-data) => (answer-data) hash table
87 * with a trivial least-recently-used expiration policy.
88 *
89 * Doing this keeps the code simple and avoids to deal with a lot of things
90 * that a full DNS cache is expected to do.
91 *
92 * The API is also very simple:
93 *
94 * - the client calls _resolv_cache_get() to obtain a handle to the cache.
95 * this will initialize the cache on first usage. the result can be NULL
96 * if the cache is disabled.
97 *
98 * - the client calls _resolv_cache_lookup() before performing a query
99 *
100 * if the function returns RESOLV_CACHE_FOUND, a copy of the answer data
101 * has been copied into the client-provided answer buffer.
102 *
103 * if the function returns RESOLV_CACHE_NOTFOUND, the client should perform
104 * a request normally, *then* call _resolv_cache_add() to add the received
105 * answer to the cache.
106 *
107 * if the function returns RESOLV_CACHE_UNSUPPORTED, the client should
108 * perform a request normally, and *not* call _resolv_cache_add()
109 *
110 * note that RESOLV_CACHE_UNSUPPORTED is also returned if the answer buffer
111 * is too short to accomodate the cached result.
112 */
113
114/* default number of entries kept in the cache. This value has been
115 * determined by browsing through various sites and counting the number
116 * of corresponding requests. Keep in mind that our framework is currently
117 * performing two requests per name lookup (one for IPv4, the other for IPv6)
118 *
119 * www.google.com 4
120 * www.ysearch.com 6
121 * www.amazon.com 8
122 * www.nytimes.com 22
123 * www.espn.com 28
124 * www.msn.com 28
125 * www.lemonde.fr 35
126 *
127 * (determined in 2009-2-17 from Paris, France, results may vary depending
128 * on location)
129 *
130 * most high-level websites use lots of media/ad servers with different names
131 * but these are generally reused when browsing through the site.
132 *
133 * As such, a value of 64 should be relatively comfortable at the moment.
134 *
135 * ******************************************
136 * * NOTE - this has changed.
137 * * 1) we've added IPv6 support so each dns query results in 2 responses
138 * * 2) we've made this a system-wide cache, so the cost is less (it's not
139 * * duplicated in each process) and the need is greater (more processes
140 * * making different requests).
141 * * Upping by 2x for IPv6
142 * * Upping by another 5x for the centralized nature
143 * *****************************************
144 */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900145#define CONFIG_MAX_ENTRIES (64 * 2 * 5)
Bernie Innocenti55864192018-08-30 04:05:20 +0900146
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900147/** BOUNDED BUFFER FORMATTING **/
Bernie Innocenti55864192018-08-30 04:05:20 +0900148
149/* technical note:
150 *
151 * the following debugging routines are used to append data to a bounded
152 * buffer they take two parameters that are:
153 *
154 * - p : a pointer to the current cursor position in the buffer
155 * this value is initially set to the buffer's address.
156 *
157 * - end : the address of the buffer's limit, i.e. of the first byte
158 * after the buffer. this address should never be touched.
159 *
160 * IMPORTANT: it is assumed that end > buffer_address, i.e.
161 * that the buffer is at least one byte.
162 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900163 * the bprint_x() functions return the new value of 'p' after the data
Bernie Innocenti55864192018-08-30 04:05:20 +0900164 * has been appended, and also ensure the following:
165 *
166 * - the returned value will never be strictly greater than 'end'
167 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900168 * - a return value equal to 'end' means that truncation occurred
Bernie Innocenti55864192018-08-30 04:05:20 +0900169 * (in which case, end[-1] will be set to 0)
170 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900171 * - after returning from a bprint_x() function, the content of the buffer
Bernie Innocenti55864192018-08-30 04:05:20 +0900172 * is always 0-terminated, even in the event of truncation.
173 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900174 * these conventions allow you to call bprint_x() functions multiple times and
Bernie Innocenti55864192018-08-30 04:05:20 +0900175 * only check for truncation at the end of the sequence, as in:
176 *
177 * char buff[1000], *p = buff, *end = p + sizeof(buff);
178 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900179 * p = bprint_c(p, end, '"');
180 * p = bprint_s(p, end, my_string);
181 * p = bprint_c(p, end, '"');
Bernie Innocenti55864192018-08-30 04:05:20 +0900182 *
183 * if (p >= end) {
184 * // buffer was too small
185 * }
186 *
187 * printf( "%s", buff );
188 */
189
190/* add a char to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900191static char* bprint_c(char* p, char* end, int c) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900192 if (p < end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900193 if (p + 1 == end)
Bernie Innocenti55864192018-08-30 04:05:20 +0900194 *p++ = 0;
195 else {
196 *p++ = (char) c;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900197 *p = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900198 }
199 }
200 return p;
201}
202
203/* add a sequence of bytes to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900204static char* bprint_b(char* p, char* end, const char* buf, int len) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900205 int avail = end - p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900206
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900207 if (avail <= 0 || len <= 0) return p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900208
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900209 if (avail > len) avail = len;
Bernie Innocenti55864192018-08-30 04:05:20 +0900210
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900211 memcpy(p, buf, avail);
Bernie Innocenti55864192018-08-30 04:05:20 +0900212 p += avail;
213
214 if (p < end)
215 p[0] = 0;
216 else
217 end[-1] = 0;
218
219 return p;
220}
221
222/* add a string to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900223static char* bprint_s(char* p, char* end, const char* str) {
224 return bprint_b(p, end, str, strlen(str));
Bernie Innocenti55864192018-08-30 04:05:20 +0900225}
226
227/* add a formatted string to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900228static char* bprint(char* p, char* end, const char* format, ...) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900229 int avail, n;
230 va_list args;
Bernie Innocenti55864192018-08-30 04:05:20 +0900231
232 avail = end - p;
233
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900234 if (avail <= 0) return p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900235
236 va_start(args, format);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900237 n = vsnprintf(p, avail, format, args);
Bernie Innocenti55864192018-08-30 04:05:20 +0900238 va_end(args);
239
240 /* certain C libraries return -1 in case of truncation */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900241 if (n < 0 || n > avail) n = avail;
Bernie Innocenti55864192018-08-30 04:05:20 +0900242
243 p += n;
244 /* certain C libraries do not zero-terminate in case of truncation */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900245 if (p == end) p[-1] = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900246
247 return p;
248}
249
250/* add a hex value to a bounded buffer, up to 8 digits */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900251static char* bprint_hex(char* p, char* end, unsigned value, int numDigits) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900252 char text[sizeof(unsigned) * 2];
253 int nn = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900254
255 while (numDigits-- > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900256 text[nn++] = "0123456789abcdef"[(value >> (numDigits * 4)) & 15];
Bernie Innocenti55864192018-08-30 04:05:20 +0900257 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900258 return bprint_b(p, end, text, nn);
Bernie Innocenti55864192018-08-30 04:05:20 +0900259}
260
261/* add the hexadecimal dump of some memory area to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900262static char* bprint_hexdump(char* p, char* end, const uint8_t* data, int datalen) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900263 int lineSize = 16;
Bernie Innocenti55864192018-08-30 04:05:20 +0900264
265 while (datalen > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900266 int avail = datalen;
267 int nn;
Bernie Innocenti55864192018-08-30 04:05:20 +0900268
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900269 if (avail > lineSize) avail = lineSize;
Bernie Innocenti55864192018-08-30 04:05:20 +0900270
271 for (nn = 0; nn < avail; nn++) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900272 if (nn > 0) p = bprint_c(p, end, ' ');
273 p = bprint_hex(p, end, data[nn], 2);
Bernie Innocenti55864192018-08-30 04:05:20 +0900274 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900275 for (; nn < lineSize; nn++) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900276 p = bprint_s(p, end, " ");
Bernie Innocenti55864192018-08-30 04:05:20 +0900277 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900278 p = bprint_s(p, end, " ");
Bernie Innocenti55864192018-08-30 04:05:20 +0900279
280 for (nn = 0; nn < avail; nn++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900281 int c = data[nn];
Bernie Innocenti55864192018-08-30 04:05:20 +0900282
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900283 if (c < 32 || c > 127) c = '.';
Bernie Innocenti55864192018-08-30 04:05:20 +0900284
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900285 p = bprint_c(p, end, c);
Bernie Innocenti55864192018-08-30 04:05:20 +0900286 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900287 p = bprint_c(p, end, '\n');
Bernie Innocenti55864192018-08-30 04:05:20 +0900288
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900289 data += avail;
Bernie Innocenti55864192018-08-30 04:05:20 +0900290 datalen -= avail;
291 }
292 return p;
293}
294
295/* dump the content of a query of packet to the log */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900296static void dump_bytes(const uint8_t* base, int len) {
297 if (!kDumpData) return;
Bernie Innocenti55864192018-08-30 04:05:20 +0900298
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900299 char buff[1024];
300 char *p = buff, *end = p + sizeof(buff);
301
302 p = bprint_hexdump(p, end, base, len);
303 VLOG << buff;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900304}
Bernie Innocenti55864192018-08-30 04:05:20 +0900305
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900306static time_t _time_now(void) {
307 struct timeval tv;
Bernie Innocenti55864192018-08-30 04:05:20 +0900308
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900309 gettimeofday(&tv, NULL);
Bernie Innocenti55864192018-08-30 04:05:20 +0900310 return tv.tv_sec;
311}
312
313/* reminder: the general format of a DNS packet is the following:
314 *
315 * HEADER (12 bytes)
316 * QUESTION (variable)
317 * ANSWER (variable)
318 * AUTHORITY (variable)
319 * ADDITIONNAL (variable)
320 *
321 * the HEADER is made of:
322 *
323 * ID : 16 : 16-bit unique query identification field
324 *
325 * QR : 1 : set to 0 for queries, and 1 for responses
326 * Opcode : 4 : set to 0 for queries
327 * AA : 1 : set to 0 for queries
328 * TC : 1 : truncation flag, will be set to 0 in queries
329 * RD : 1 : recursion desired
330 *
331 * RA : 1 : recursion available (0 in queries)
332 * Z : 3 : three reserved zero bits
333 * RCODE : 4 : response code (always 0=NOERROR in queries)
334 *
335 * QDCount: 16 : question count
336 * ANCount: 16 : Answer count (0 in queries)
337 * NSCount: 16: Authority Record count (0 in queries)
338 * ARCount: 16: Additionnal Record count (0 in queries)
339 *
340 * the QUESTION is made of QDCount Question Record (QRs)
341 * the ANSWER is made of ANCount RRs
342 * the AUTHORITY is made of NSCount RRs
343 * the ADDITIONNAL is made of ARCount RRs
344 *
345 * Each Question Record (QR) is made of:
346 *
347 * QNAME : variable : Query DNS NAME
348 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
349 * CLASS : 16 : class of query (IN=1)
350 *
351 * Each Resource Record (RR) is made of:
352 *
353 * NAME : variable : DNS NAME
354 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
355 * CLASS : 16 : class of query (IN=1)
356 * TTL : 32 : seconds to cache this RR (0=none)
357 * RDLENGTH: 16 : size of RDDATA in bytes
358 * RDDATA : variable : RR data (depends on TYPE)
359 *
360 * Each QNAME contains a domain name encoded as a sequence of 'labels'
361 * terminated by a zero. Each label has the following format:
362 *
363 * LEN : 8 : lenght of label (MUST be < 64)
364 * NAME : 8*LEN : label length (must exclude dots)
365 *
366 * A value of 0 in the encoding is interpreted as the 'root' domain and
367 * terminates the encoding. So 'www.android.com' will be encoded as:
368 *
369 * <3>www<7>android<3>com<0>
370 *
371 * Where <n> represents the byte with value 'n'
372 *
373 * Each NAME reflects the QNAME of the question, but has a slightly more
374 * complex encoding in order to provide message compression. This is achieved
375 * by using a 2-byte pointer, with format:
376 *
377 * TYPE : 2 : 0b11 to indicate a pointer, 0b01 and 0b10 are reserved
378 * OFFSET : 14 : offset to another part of the DNS packet
379 *
380 * The offset is relative to the start of the DNS packet and must point
381 * A pointer terminates the encoding.
382 *
383 * The NAME can be encoded in one of the following formats:
384 *
385 * - a sequence of simple labels terminated by 0 (like QNAMEs)
386 * - a single pointer
387 * - a sequence of simple labels terminated by a pointer
388 *
389 * A pointer shall always point to either a pointer of a sequence of
390 * labels (which can themselves be terminated by either a 0 or a pointer)
391 *
392 * The expanded length of a given domain name should not exceed 255 bytes.
393 *
394 * NOTE: we don't parse the answer packets, so don't need to deal with NAME
395 * records, only QNAMEs.
396 */
397
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900398#define DNS_HEADER_SIZE 12
Bernie Innocenti55864192018-08-30 04:05:20 +0900399
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900400#define DNS_TYPE_A "\00\01" /* big-endian decimal 1 */
401#define DNS_TYPE_PTR "\00\014" /* big-endian decimal 12 */
402#define DNS_TYPE_MX "\00\017" /* big-endian decimal 15 */
403#define DNS_TYPE_AAAA "\00\034" /* big-endian decimal 28 */
404#define DNS_TYPE_ALL "\00\0377" /* big-endian decimal 255 */
Bernie Innocenti55864192018-08-30 04:05:20 +0900405
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900406#define DNS_CLASS_IN "\00\01" /* big-endian decimal 1 */
Bernie Innocenti55864192018-08-30 04:05:20 +0900407
408typedef struct {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900409 const uint8_t* base;
410 const uint8_t* end;
411 const uint8_t* cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900412} DnsPacket;
413
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900414static void _dnsPacket_init(DnsPacket* packet, const uint8_t* buff, int bufflen) {
415 packet->base = buff;
416 packet->end = buff + bufflen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900417 packet->cursor = buff;
418}
419
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900420static void _dnsPacket_rewind(DnsPacket* packet) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900421 packet->cursor = packet->base;
422}
423
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900424static void _dnsPacket_skip(DnsPacket* packet, int count) {
425 const uint8_t* p = packet->cursor + count;
Bernie Innocenti55864192018-08-30 04:05:20 +0900426
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900427 if (p > packet->end) p = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900428
429 packet->cursor = p;
430}
431
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900432static int _dnsPacket_readInt16(DnsPacket* packet) {
433 const uint8_t* p = packet->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900434
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900435 if (p + 2 > packet->end) return -1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900436
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900437 packet->cursor = p + 2;
438 return (p[0] << 8) | p[1];
Bernie Innocenti55864192018-08-30 04:05:20 +0900439}
440
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900441/** QUERY CHECKING **/
Bernie Innocenti55864192018-08-30 04:05:20 +0900442
443/* check bytes in a dns packet. returns 1 on success, 0 on failure.
444 * the cursor is only advanced in the case of success
445 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900446static int _dnsPacket_checkBytes(DnsPacket* packet, int numBytes, const void* bytes) {
447 const uint8_t* p = packet->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900448
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900449 if (p + numBytes > packet->end) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900450
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900451 if (memcmp(p, bytes, numBytes) != 0) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900452
453 packet->cursor = p + numBytes;
454 return 1;
455}
456
457/* parse and skip a given QNAME stored in a query packet,
458 * from the current cursor position. returns 1 on success,
459 * or 0 for malformed data.
460 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900461static int _dnsPacket_checkQName(DnsPacket* packet) {
462 const uint8_t* p = packet->cursor;
463 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900464
465 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900466 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900467
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900468 if (p >= end) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900469
470 c = *p++;
471
472 if (c == 0) {
473 packet->cursor = p;
474 return 1;
475 }
476
477 /* we don't expect label compression in QNAMEs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900478 if (c >= 64) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900479
480 p += c;
481 /* we rely on the bound check at the start
482 * of the loop here */
483 }
484 /* malformed data */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900485 VLOG << "malformed QNAME";
Bernie Innocenti55864192018-08-30 04:05:20 +0900486 return 0;
487}
488
489/* parse and skip a given QR stored in a packet.
490 * returns 1 on success, and 0 on failure
491 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900492static int _dnsPacket_checkQR(DnsPacket* packet) {
493 if (!_dnsPacket_checkQName(packet)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900494
495 /* TYPE must be one of the things we support */
496 if (!_dnsPacket_checkBytes(packet, 2, DNS_TYPE_A) &&
497 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_PTR) &&
498 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_MX) &&
499 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_AAAA) &&
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900500 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_ALL)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900501 VLOG << "unsupported TYPE";
Bernie Innocenti55864192018-08-30 04:05:20 +0900502 return 0;
503 }
504 /* CLASS must be IN */
505 if (!_dnsPacket_checkBytes(packet, 2, DNS_CLASS_IN)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900506 VLOG << "unsupported CLASS";
Bernie Innocenti55864192018-08-30 04:05:20 +0900507 return 0;
508 }
509
510 return 1;
511}
512
513/* check the header of a DNS Query packet, return 1 if it is one
514 * type of query we can cache, or 0 otherwise
515 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900516static int _dnsPacket_checkQuery(DnsPacket* packet) {
517 const uint8_t* p = packet->base;
518 int qdCount, anCount, dnCount, arCount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900519
520 if (p + DNS_HEADER_SIZE > packet->end) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900521 VLOG << "query packet too small";
Bernie Innocenti55864192018-08-30 04:05:20 +0900522 return 0;
523 }
524
525 /* QR must be set to 0, opcode must be 0 and AA must be 0 */
526 /* RA, Z, and RCODE must be 0 */
527 if ((p[2] & 0xFC) != 0 || (p[3] & 0xCF) != 0) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900528 VLOG << "query packet flags unsupported";
Bernie Innocenti55864192018-08-30 04:05:20 +0900529 return 0;
530 }
531
532 /* Note that we ignore the TC, RD, CD, and AD bits here for the
533 * following reasons:
534 *
535 * - there is no point for a query packet sent to a server
536 * to have the TC bit set, but the implementation might
537 * set the bit in the query buffer for its own needs
538 * between a _resolv_cache_lookup and a
539 * _resolv_cache_add. We should not freak out if this
540 * is the case.
541 *
542 * - we consider that the result from a query might depend on
543 * the RD, AD, and CD bits, so these bits
544 * should be used to differentiate cached result.
545 *
546 * this implies that these bits are checked when hashing or
547 * comparing query packets, but not TC
548 */
549
550 /* ANCOUNT, DNCOUNT and ARCOUNT must be 0 */
551 qdCount = (p[4] << 8) | p[5];
552 anCount = (p[6] << 8) | p[7];
553 dnCount = (p[8] << 8) | p[9];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900554 arCount = (p[10] << 8) | p[11];
Bernie Innocenti55864192018-08-30 04:05:20 +0900555
556 if (anCount != 0 || dnCount != 0 || arCount > 1) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900557 VLOG << "query packet contains non-query records";
Bernie Innocenti55864192018-08-30 04:05:20 +0900558 return 0;
559 }
560
561 if (qdCount == 0) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900562 VLOG << "query packet doesn't contain query record";
Bernie Innocenti55864192018-08-30 04:05:20 +0900563 return 0;
564 }
565
566 /* Check QDCOUNT QRs */
567 packet->cursor = p + DNS_HEADER_SIZE;
568
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900569 for (; qdCount > 0; qdCount--)
570 if (!_dnsPacket_checkQR(packet)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900571
572 return 1;
573}
574
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900575/** QUERY DEBUGGING **/
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900576static char* dnsPacket_bprintQName(DnsPacket* packet, char* bp, char* bend) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900577 const uint8_t* p = packet->cursor;
578 const uint8_t* end = packet->end;
579 int first = 1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900580
581 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900582 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900583
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900584 if (p >= end) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900585
586 c = *p++;
587
588 if (c == 0) {
589 packet->cursor = p;
590 return bp;
591 }
592
593 /* we don't expect label compression in QNAMEs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900594 if (c >= 64) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900595
596 if (first)
597 first = 0;
598 else
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900599 bp = bprint_c(bp, bend, '.');
Bernie Innocenti55864192018-08-30 04:05:20 +0900600
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900601 bp = bprint_b(bp, bend, (const char*) p, c);
Bernie Innocenti55864192018-08-30 04:05:20 +0900602
603 p += c;
604 /* we rely on the bound check at the start
605 * of the loop here */
606 }
607 /* malformed data */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900608 bp = bprint_s(bp, bend, "<MALFORMED>");
Bernie Innocenti55864192018-08-30 04:05:20 +0900609 return bp;
610}
611
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900612static char* dnsPacket_bprintQR(DnsPacket* packet, char* p, char* end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900613#define QQ(x) \
614 { DNS_TYPE_##x, #x }
Bernie Innocenti55864192018-08-30 04:05:20 +0900615 static const struct {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900616 const char* typeBytes;
617 const char* typeString;
618 } qTypes[] = {QQ(A), QQ(PTR), QQ(MX), QQ(AAAA), QQ(ALL), {NULL, NULL}};
619 int nn;
620 const char* typeString = NULL;
Bernie Innocenti55864192018-08-30 04:05:20 +0900621
622 /* dump QNAME */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900623 p = dnsPacket_bprintQName(packet, p, end);
Bernie Innocenti55864192018-08-30 04:05:20 +0900624
625 /* dump TYPE */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900626 p = bprint_s(p, end, " (");
Bernie Innocenti55864192018-08-30 04:05:20 +0900627
628 for (nn = 0; qTypes[nn].typeBytes != NULL; nn++) {
629 if (_dnsPacket_checkBytes(packet, 2, qTypes[nn].typeBytes)) {
630 typeString = qTypes[nn].typeString;
631 break;
632 }
633 }
634
635 if (typeString != NULL)
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900636 p = bprint_s(p, end, typeString);
Bernie Innocenti55864192018-08-30 04:05:20 +0900637 else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900638 int typeCode = _dnsPacket_readInt16(packet);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900639 p = bprint(p, end, "UNKNOWN-%d", typeCode);
Bernie Innocenti55864192018-08-30 04:05:20 +0900640 }
641
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900642 p = bprint_c(p, end, ')');
Bernie Innocenti55864192018-08-30 04:05:20 +0900643
644 /* skip CLASS */
645 _dnsPacket_skip(packet, 2);
646 return p;
647}
648
649/* this function assumes the packet has already been checked */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900650static char* dnsPacket_bprintQuery(DnsPacket* packet, char* p, char* end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900651 int qdCount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900652
653 if (packet->base[2] & 0x1) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900654 p = bprint_s(p, end, "RECURSIVE ");
Bernie Innocenti55864192018-08-30 04:05:20 +0900655 }
656
657 _dnsPacket_skip(packet, 4);
658 qdCount = _dnsPacket_readInt16(packet);
659 _dnsPacket_skip(packet, 6);
660
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900661 for (; qdCount > 0; qdCount--) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900662 p = dnsPacket_bprintQR(packet, p, end);
Bernie Innocenti55864192018-08-30 04:05:20 +0900663 }
664 return p;
665}
Bernie Innocenti55864192018-08-30 04:05:20 +0900666
Bernie Innocenti55864192018-08-30 04:05:20 +0900667/** QUERY HASHING SUPPORT
668 **
669 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKET HAS ALREADY
670 ** BEEN SUCCESFULLY CHECKED.
671 **/
672
673/* use 32-bit FNV hash function */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900674#define FNV_MULT 16777619U
675#define FNV_BASIS 2166136261U
Bernie Innocenti55864192018-08-30 04:05:20 +0900676
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900677static unsigned _dnsPacket_hashBytes(DnsPacket* packet, int numBytes, unsigned hash) {
678 const uint8_t* p = packet->cursor;
679 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900680
681 while (numBytes > 0 && p < end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900682 hash = hash * FNV_MULT ^ *p++;
Bernie Innocenti55864192018-08-30 04:05:20 +0900683 }
684 packet->cursor = p;
685 return hash;
686}
687
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900688static unsigned _dnsPacket_hashQName(DnsPacket* packet, unsigned hash) {
689 const uint8_t* p = packet->cursor;
690 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900691
692 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900693 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900694
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900695 if (p >= end) { /* should not happen */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900696 VLOG << __func__ << ": INTERNAL_ERROR: read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900697 break;
698 }
699
700 c = *p++;
701
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900702 if (c == 0) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900703
704 if (c >= 64) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900705 VLOG << __func__ << ": INTERNAL_ERROR: malformed domain";
Bernie Innocenti55864192018-08-30 04:05:20 +0900706 break;
707 }
708 if (p + c >= end) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900709 VLOG << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900710 break;
711 }
712 while (c > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900713 hash = hash * FNV_MULT ^ *p++;
714 c -= 1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900715 }
716 }
717 packet->cursor = p;
718 return hash;
719}
720
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900721static unsigned _dnsPacket_hashQR(DnsPacket* packet, unsigned hash) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900722 hash = _dnsPacket_hashQName(packet, hash);
723 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TYPE and CLASS */
724 return hash;
725}
726
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900727static unsigned _dnsPacket_hashRR(DnsPacket* packet, unsigned hash) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900728 int rdlength;
729 hash = _dnsPacket_hashQR(packet, hash);
730 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TTL */
731 rdlength = _dnsPacket_readInt16(packet);
732 hash = _dnsPacket_hashBytes(packet, rdlength, hash); /* RDATA */
733 return hash;
734}
735
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900736static unsigned _dnsPacket_hashQuery(DnsPacket* packet) {
737 unsigned hash = FNV_BASIS;
738 int count, arcount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900739 _dnsPacket_rewind(packet);
740
741 /* ignore the ID */
742 _dnsPacket_skip(packet, 2);
743
744 /* we ignore the TC bit for reasons explained in
745 * _dnsPacket_checkQuery().
746 *
747 * however we hash the RD bit to differentiate
748 * between answers for recursive and non-recursive
749 * queries.
750 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900751 hash = hash * FNV_MULT ^ (packet->base[2] & 1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900752
753 /* mark the first header byte as processed */
754 _dnsPacket_skip(packet, 1);
755
756 /* process the second header byte */
757 hash = _dnsPacket_hashBytes(packet, 1, hash);
758
759 /* read QDCOUNT */
760 count = _dnsPacket_readInt16(packet);
761
762 /* assume: ANcount and NScount are 0 */
763 _dnsPacket_skip(packet, 4);
764
765 /* read ARCOUNT */
766 arcount = _dnsPacket_readInt16(packet);
767
768 /* hash QDCOUNT QRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900769 for (; count > 0; count--) hash = _dnsPacket_hashQR(packet, hash);
Bernie Innocenti55864192018-08-30 04:05:20 +0900770
771 /* hash ARCOUNT RRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900772 for (; arcount > 0; arcount--) hash = _dnsPacket_hashRR(packet, hash);
Bernie Innocenti55864192018-08-30 04:05:20 +0900773
774 return hash;
775}
776
Bernie Innocenti55864192018-08-30 04:05:20 +0900777/** QUERY COMPARISON
778 **
779 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKETS HAVE ALREADY
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900780 ** BEEN SUCCESSFULLY CHECKED.
Bernie Innocenti55864192018-08-30 04:05:20 +0900781 **/
782
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900783static int _dnsPacket_isEqualDomainName(DnsPacket* pack1, DnsPacket* pack2) {
784 const uint8_t* p1 = pack1->cursor;
785 const uint8_t* end1 = pack1->end;
786 const uint8_t* p2 = pack2->cursor;
787 const uint8_t* end2 = pack2->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900788
789 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900790 int c1, c2;
Bernie Innocenti55864192018-08-30 04:05:20 +0900791
792 if (p1 >= end1 || p2 >= end2) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900793 VLOG << __func__ << ": INTERNAL_ERROR: read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900794 break;
795 }
796 c1 = *p1++;
797 c2 = *p2++;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900798 if (c1 != c2) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900799
800 if (c1 == 0) {
801 pack1->cursor = p1;
802 pack2->cursor = p2;
803 return 1;
804 }
805 if (c1 >= 64) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900806 VLOG << __func__ << ": INTERNAL_ERROR: malformed domain";
Bernie Innocenti55864192018-08-30 04:05:20 +0900807 break;
808 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900809 if ((p1 + c1 > end1) || (p2 + c1 > end2)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900810 VLOG << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900811 break;
812 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900813 if (memcmp(p1, p2, c1) != 0) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900814 p1 += c1;
815 p2 += c1;
816 /* we rely on the bound checks at the start of the loop */
817 }
818 /* not the same, or one is malformed */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900819 VLOG << "different DN";
Bernie Innocenti55864192018-08-30 04:05:20 +0900820 return 0;
821}
822
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900823static int _dnsPacket_isEqualBytes(DnsPacket* pack1, DnsPacket* pack2, int numBytes) {
824 const uint8_t* p1 = pack1->cursor;
825 const uint8_t* p2 = pack2->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900826
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900827 if (p1 + numBytes > pack1->end || p2 + numBytes > pack2->end) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900828
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900829 if (memcmp(p1, p2, numBytes) != 0) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900830
831 pack1->cursor += numBytes;
832 pack2->cursor += numBytes;
833 return 1;
834}
835
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900836static int _dnsPacket_isEqualQR(DnsPacket* pack1, DnsPacket* pack2) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900837 /* compare domain name encoding + TYPE + CLASS */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900838 if (!_dnsPacket_isEqualDomainName(pack1, pack2) ||
839 !_dnsPacket_isEqualBytes(pack1, pack2, 2 + 2))
Bernie Innocenti55864192018-08-30 04:05:20 +0900840 return 0;
841
842 return 1;
843}
844
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900845static int _dnsPacket_isEqualRR(DnsPacket* pack1, DnsPacket* pack2) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900846 int rdlength1, rdlength2;
847 /* compare query + TTL */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900848 if (!_dnsPacket_isEqualQR(pack1, pack2) || !_dnsPacket_isEqualBytes(pack1, pack2, 4)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900849
850 /* compare RDATA */
851 rdlength1 = _dnsPacket_readInt16(pack1);
852 rdlength2 = _dnsPacket_readInt16(pack2);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900853 if (rdlength1 != rdlength2 || !_dnsPacket_isEqualBytes(pack1, pack2, rdlength1)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900854
855 return 1;
856}
857
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900858static int _dnsPacket_isEqualQuery(DnsPacket* pack1, DnsPacket* pack2) {
859 int count1, count2, arcount1, arcount2;
Bernie Innocenti55864192018-08-30 04:05:20 +0900860
861 /* compare the headers, ignore most fields */
862 _dnsPacket_rewind(pack1);
863 _dnsPacket_rewind(pack2);
864
865 /* compare RD, ignore TC, see comment in _dnsPacket_checkQuery */
866 if ((pack1->base[2] & 1) != (pack2->base[2] & 1)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900867 VLOG << "different RD";
Bernie Innocenti55864192018-08-30 04:05:20 +0900868 return 0;
869 }
870
871 if (pack1->base[3] != pack2->base[3]) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900872 VLOG << "different CD or AD";
Bernie Innocenti55864192018-08-30 04:05:20 +0900873 return 0;
874 }
875
876 /* mark ID and header bytes as compared */
877 _dnsPacket_skip(pack1, 4);
878 _dnsPacket_skip(pack2, 4);
879
880 /* compare QDCOUNT */
881 count1 = _dnsPacket_readInt16(pack1);
882 count2 = _dnsPacket_readInt16(pack2);
883 if (count1 != count2 || count1 < 0) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900884 VLOG << "different QDCOUNT";
Bernie Innocenti55864192018-08-30 04:05:20 +0900885 return 0;
886 }
887
888 /* assume: ANcount and NScount are 0 */
889 _dnsPacket_skip(pack1, 4);
890 _dnsPacket_skip(pack2, 4);
891
892 /* compare ARCOUNT */
893 arcount1 = _dnsPacket_readInt16(pack1);
894 arcount2 = _dnsPacket_readInt16(pack2);
895 if (arcount1 != arcount2 || arcount1 < 0) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900896 VLOG << "different ARCOUNT";
Bernie Innocenti55864192018-08-30 04:05:20 +0900897 return 0;
898 }
899
900 /* compare the QDCOUNT QRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900901 for (; count1 > 0; count1--) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900902 if (!_dnsPacket_isEqualQR(pack1, pack2)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900903 VLOG << "different QR";
Bernie Innocenti55864192018-08-30 04:05:20 +0900904 return 0;
905 }
906 }
907
908 /* compare the ARCOUNT RRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900909 for (; arcount1 > 0; arcount1--) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900910 if (!_dnsPacket_isEqualRR(pack1, pack2)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900911 VLOG << "different additional RR";
Bernie Innocenti55864192018-08-30 04:05:20 +0900912 return 0;
913 }
914 }
915 return 1;
916}
917
Bernie Innocenti55864192018-08-30 04:05:20 +0900918/* cache entry. for simplicity, 'hash' and 'hlink' are inlined in this
919 * structure though they are conceptually part of the hash table.
920 *
921 * similarly, mru_next and mru_prev are part of the global MRU list
922 */
923typedef struct Entry {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900924 unsigned int hash; /* hash value */
925 struct Entry* hlink; /* next in collision chain */
926 struct Entry* mru_prev;
927 struct Entry* mru_next;
Bernie Innocenti55864192018-08-30 04:05:20 +0900928
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900929 const uint8_t* query;
930 int querylen;
931 const uint8_t* answer;
932 int answerlen;
933 time_t expires; /* time_t when the entry isn't valid any more */
934 int id; /* for debugging purpose */
Bernie Innocenti55864192018-08-30 04:05:20 +0900935} Entry;
936
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900937/*
Bernie Innocenti55864192018-08-30 04:05:20 +0900938 * Find the TTL for a negative DNS result. This is defined as the minimum
939 * of the SOA records TTL and the MINIMUM-TTL field (RFC-2308).
940 *
941 * Return 0 if not found.
942 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900943static u_long answer_getNegativeTTL(ns_msg handle) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900944 int n, nscount;
945 u_long result = 0;
946 ns_rr rr;
947
948 nscount = ns_msg_count(handle, ns_s_ns);
949 for (n = 0; n < nscount; n++) {
950 if ((ns_parserr(&handle, ns_s_ns, n, &rr) == 0) && (ns_rr_type(rr) == ns_t_soa)) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900951 const u_char* rdata = ns_rr_rdata(rr); // find the data
952 const u_char* edata = rdata + ns_rr_rdlen(rr); // add the len to find the end
Bernie Innocenti55864192018-08-30 04:05:20 +0900953 int len;
954 u_long ttl, rec_result = ns_rr_ttl(rr);
955
956 // find the MINIMUM-TTL field from the blob of binary data for this record
957 // skip the server name
958 len = dn_skipname(rdata, edata);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900959 if (len == -1) continue; // error skipping
Bernie Innocenti55864192018-08-30 04:05:20 +0900960 rdata += len;
961
962 // skip the admin name
963 len = dn_skipname(rdata, edata);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900964 if (len == -1) continue; // error skipping
Bernie Innocenti55864192018-08-30 04:05:20 +0900965 rdata += len;
966
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900967 if (edata - rdata != 5 * NS_INT32SZ) continue;
Bernie Innocenti55864192018-08-30 04:05:20 +0900968 // skip: serial number + refresh interval + retry interval + expiry
969 rdata += NS_INT32SZ * 4;
970 // finally read the MINIMUM TTL
971 ttl = ns_get32(rdata);
972 if (ttl < rec_result) {
973 rec_result = ttl;
974 }
975 // Now that the record is read successfully, apply the new min TTL
976 if (n == 0 || rec_result < result) {
977 result = rec_result;
978 }
979 }
980 }
981 return result;
982}
983
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900984/*
Bernie Innocenti55864192018-08-30 04:05:20 +0900985 * Parse the answer records and find the appropriate
986 * smallest TTL among the records. This might be from
987 * the answer records if found or from the SOA record
988 * if it's a negative result.
989 *
990 * The returned TTL is the number of seconds to
991 * keep the answer in the cache.
992 *
993 * In case of parse error zero (0) is returned which
994 * indicates that the answer shall not be cached.
995 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900996static u_long answer_getTTL(const void* answer, int answerlen) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900997 ns_msg handle;
998 int ancount, n;
999 u_long result, ttl;
1000 ns_rr rr;
1001
1002 result = 0;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001003 if (ns_initparse((const uint8_t*) answer, answerlen, &handle) >= 0) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001004 // get number of answer records
1005 ancount = ns_msg_count(handle, ns_s_an);
1006
1007 if (ancount == 0) {
1008 // a response with no answers? Cache this negative result.
1009 result = answer_getNegativeTTL(handle);
1010 } else {
1011 for (n = 0; n < ancount; n++) {
1012 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
1013 ttl = ns_rr_ttl(rr);
1014 if (n == 0 || ttl < result) {
1015 result = ttl;
1016 }
1017 } else {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001018 VLOG << "ns_parserr failed ancount no = "
1019 << n << ". errno = " << strerror(errno);
Bernie Innocenti55864192018-08-30 04:05:20 +09001020 }
1021 }
1022 }
1023 } else {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001024 VLOG << "ns_initparse failed: " << strerror(errno);
Bernie Innocenti55864192018-08-30 04:05:20 +09001025 }
1026
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001027 VLOG << "TTL = " << result;
Bernie Innocenti55864192018-08-30 04:05:20 +09001028 return result;
1029}
1030
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001031static void entry_free(Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001032 /* everything is allocated in a single memory block */
1033 if (e) {
1034 free(e);
1035 }
1036}
1037
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001038static void entry_mru_remove(Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001039 e->mru_prev->mru_next = e->mru_next;
1040 e->mru_next->mru_prev = e->mru_prev;
1041}
1042
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001043static void entry_mru_add(Entry* e, Entry* list) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001044 Entry* first = list->mru_next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001045
1046 e->mru_next = first;
1047 e->mru_prev = list;
1048
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001049 list->mru_next = e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001050 first->mru_prev = e;
1051}
1052
1053/* compute the hash of a given entry, this is a hash of most
1054 * data in the query (key) */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001055static unsigned entry_hash(const Entry* e) {
1056 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001057
1058 _dnsPacket_init(pack, e->query, e->querylen);
1059 return _dnsPacket_hashQuery(pack);
1060}
1061
1062/* initialize an Entry as a search key, this also checks the input query packet
1063 * returns 1 on success, or 0 in case of unsupported/malformed data */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001064static int entry_init_key(Entry* e, const void* query, int querylen) {
1065 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001066
1067 memset(e, 0, sizeof(*e));
1068
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001069 e->query = (const uint8_t*) query;
Bernie Innocenti55864192018-08-30 04:05:20 +09001070 e->querylen = querylen;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001071 e->hash = entry_hash(e);
Bernie Innocenti55864192018-08-30 04:05:20 +09001072
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001073 _dnsPacket_init(pack, e->query, e->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001074
1075 return _dnsPacket_checkQuery(pack);
1076}
1077
1078/* allocate a new entry as a cache node */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001079static Entry* entry_alloc(const Entry* init, const void* answer, int answerlen) {
1080 Entry* e;
1081 int size;
Bernie Innocenti55864192018-08-30 04:05:20 +09001082
1083 size = sizeof(*e) + init->querylen + answerlen;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001084 e = (Entry*) calloc(size, 1);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001085 if (e == NULL) return e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001086
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001087 e->hash = init->hash;
1088 e->query = (const uint8_t*) (e + 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001089 e->querylen = init->querylen;
1090
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001091 memcpy((char*) e->query, init->query, e->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001092
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001093 e->answer = e->query + e->querylen;
Bernie Innocenti55864192018-08-30 04:05:20 +09001094 e->answerlen = answerlen;
1095
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001096 memcpy((char*) e->answer, answer, e->answerlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001097
1098 return e;
1099}
1100
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001101static int entry_equals(const Entry* e1, const Entry* e2) {
1102 DnsPacket pack1[1], pack2[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001103
1104 if (e1->querylen != e2->querylen) {
1105 return 0;
1106 }
1107 _dnsPacket_init(pack1, e1->query, e1->querylen);
1108 _dnsPacket_init(pack2, e2->query, e2->querylen);
1109
1110 return _dnsPacket_isEqualQuery(pack1, pack2);
1111}
1112
Bernie Innocenti55864192018-08-30 04:05:20 +09001113/* We use a simple hash table with external collision lists
1114 * for simplicity, the hash-table fields 'hash' and 'hlink' are
1115 * inlined in the Entry structure.
1116 */
1117
1118/* Maximum time for a thread to wait for an pending request */
1119#define PENDING_REQUEST_TIMEOUT 20;
1120
1121typedef struct pending_req_info {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001122 unsigned int hash;
1123 pthread_cond_t cond;
1124 struct pending_req_info* next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001125} PendingReqInfo;
1126
1127typedef struct resolv_cache {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001128 int max_entries;
1129 int num_entries;
1130 Entry mru_list;
1131 int last_id;
1132 Entry* entries;
1133 PendingReqInfo pending_requests;
Bernie Innocenti55864192018-08-30 04:05:20 +09001134} Cache;
1135
1136struct resolv_cache_info {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001137 unsigned netid;
1138 Cache* cache;
1139 struct resolv_cache_info* next;
1140 int nscount;
1141 char* nameservers[MAXNS];
1142 struct addrinfo* nsaddrinfo[MAXNS];
1143 int revision_id; // # times the nameservers have been replaced
1144 struct __res_params params;
1145 struct __res_stats nsstats[MAXNS];
1146 char defdname[MAXDNSRCHPATH];
1147 int dnsrch_offset[MAXDNSRCH + 1]; // offsets into defdname
Bernie Innocenti55864192018-08-30 04:05:20 +09001148};
1149
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001150#define HTABLE_VALID(x) ((x) != NULL && (x) != HTABLE_DELETED)
Bernie Innocenti55864192018-08-30 04:05:20 +09001151
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001152static pthread_once_t _res_cache_once = PTHREAD_ONCE_INIT;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001153static void res_cache_init(void);
Bernie Innocenti55864192018-08-30 04:05:20 +09001154
1155// lock protecting everything in the _resolve_cache_info structs (next ptr, etc)
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001156static pthread_mutex_t res_cache_list_lock;
Bernie Innocenti55864192018-08-30 04:05:20 +09001157
1158/* gets cache associated with a network, or NULL if none exists */
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001159static struct resolv_cache* find_named_cache_locked(unsigned netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001160
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001161static void _cache_flush_pending_requests_locked(struct resolv_cache* cache) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001162 struct pending_req_info *ri, *tmp;
1163 if (cache) {
1164 ri = cache->pending_requests.next;
1165
1166 while (ri) {
1167 tmp = ri;
1168 ri = ri->next;
1169 pthread_cond_broadcast(&tmp->cond);
1170
1171 pthread_cond_destroy(&tmp->cond);
1172 free(tmp);
1173 }
1174
1175 cache->pending_requests.next = NULL;
1176 }
1177}
1178
1179/* Return 0 if no pending request is found matching the key.
1180 * If a matching request is found the calling thread will wait until
1181 * the matching request completes, then update *cache and return 1. */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001182static int _cache_check_pending_request_locked(struct resolv_cache** cache, Entry* key,
1183 unsigned netid) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001184 struct pending_req_info *ri, *prev;
1185 int exist = 0;
1186
1187 if (*cache && key) {
1188 ri = (*cache)->pending_requests.next;
1189 prev = &(*cache)->pending_requests;
1190 while (ri) {
1191 if (ri->hash == key->hash) {
1192 exist = 1;
1193 break;
1194 }
1195 prev = ri;
1196 ri = ri->next;
1197 }
1198
1199 if (!exist) {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001200 ri = (struct pending_req_info*) calloc(1, sizeof(struct pending_req_info));
Bernie Innocenti55864192018-08-30 04:05:20 +09001201 if (ri) {
1202 ri->hash = key->hash;
1203 pthread_cond_init(&ri->cond, NULL);
1204 prev->next = ri;
1205 }
1206 } else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001207 struct timespec ts = {0, 0};
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001208 VLOG << "Waiting for previous request";
Bernie Innocenti55864192018-08-30 04:05:20 +09001209 ts.tv_sec = _time_now() + PENDING_REQUEST_TIMEOUT;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001210 pthread_cond_timedwait(&ri->cond, &res_cache_list_lock, &ts);
Bernie Innocenti55864192018-08-30 04:05:20 +09001211 /* Must update *cache as it could have been deleted. */
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001212 *cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001213 }
1214 }
1215
1216 return exist;
1217}
1218
1219/* notify any waiting thread that waiting on a request
1220 * matching the key has been added to the cache */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001221static void _cache_notify_waiting_tid_locked(struct resolv_cache* cache, Entry* key) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001222 struct pending_req_info *ri, *prev;
1223
1224 if (cache && key) {
1225 ri = cache->pending_requests.next;
1226 prev = &cache->pending_requests;
1227 while (ri) {
1228 if (ri->hash == key->hash) {
1229 pthread_cond_broadcast(&ri->cond);
1230 break;
1231 }
1232 prev = ri;
1233 ri = ri->next;
1234 }
1235
1236 // remove item from list and destroy
1237 if (ri) {
1238 prev->next = ri->next;
1239 pthread_cond_destroy(&ri->cond);
1240 free(ri);
1241 }
1242 }
1243}
1244
1245/* notify the cache that the query failed */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001246void _resolv_cache_query_failed(unsigned netid, const void* query, int querylen) {
1247 Entry key[1];
1248 Cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001249
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001250 if (!entry_init_key(key, query, querylen)) return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001251
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001252 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001253
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001254 cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001255
1256 if (cache) {
1257 _cache_notify_waiting_tid_locked(cache, key);
1258 }
1259
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001260 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001261}
1262
1263static struct resolv_cache_info* _find_cache_info_locked(unsigned netid);
1264
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001265static void _cache_flush_locked(Cache* cache) {
1266 int nn;
Bernie Innocenti55864192018-08-30 04:05:20 +09001267
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001268 for (nn = 0; nn < cache->max_entries; nn++) {
1269 Entry** pnode = (Entry**) &cache->entries[nn];
Bernie Innocenti55864192018-08-30 04:05:20 +09001270
1271 while (*pnode != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001272 Entry* node = *pnode;
Bernie Innocenti55864192018-08-30 04:05:20 +09001273 *pnode = node->hlink;
1274 entry_free(node);
1275 }
1276 }
1277
1278 // flush pending request
1279 _cache_flush_pending_requests_locked(cache);
1280
1281 cache->mru_list.mru_next = cache->mru_list.mru_prev = &cache->mru_list;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001282 cache->num_entries = 0;
1283 cache->last_id = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +09001284
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001285 VLOG << "*** DNS CACHE FLUSHED ***";
Bernie Innocenti55864192018-08-30 04:05:20 +09001286}
1287
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001288static int _res_cache_get_max_entries(void) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001289 int cache_size = CONFIG_MAX_ENTRIES;
1290
1291 const char* cache_mode = getenv("ANDROID_DNS_MODE");
1292 if (cache_mode == NULL || strcmp(cache_mode, "local") != 0) {
1293 // Don't use the cache in local mode. This is used by the proxy itself.
1294 cache_size = 0;
1295 }
1296
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001297 VLOG << "cache size: " << cache_size;
Bernie Innocenti55864192018-08-30 04:05:20 +09001298 return cache_size;
1299}
1300
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001301static struct resolv_cache* _resolv_cache_create(void) {
1302 struct resolv_cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001303
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001304 cache = (struct resolv_cache*) calloc(sizeof(*cache), 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001305 if (cache) {
1306 cache->max_entries = _res_cache_get_max_entries();
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001307 cache->entries = (Entry*) calloc(sizeof(*cache->entries), cache->max_entries);
Bernie Innocenti55864192018-08-30 04:05:20 +09001308 if (cache->entries) {
1309 cache->mru_list.mru_prev = cache->mru_list.mru_next = &cache->mru_list;
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001310 VLOG << __func__ << ": cache created";
Bernie Innocenti55864192018-08-30 04:05:20 +09001311 } else {
1312 free(cache);
1313 cache = NULL;
1314 }
1315 }
1316 return cache;
1317}
1318
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001319static void dump_query(const uint8_t* query, int querylen) {
1320 if (!kVerboseLogging) return;
1321
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001322 char temp[256], *p = temp, *end = p + sizeof(temp);
1323 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001324
1325 _dnsPacket_init(pack, query, querylen);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001326 p = dnsPacket_bprintQuery(pack, p, end);
1327 VLOG << temp;
Bernie Innocenti55864192018-08-30 04:05:20 +09001328}
1329
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001330static void cache_dump_mru(Cache* cache) {
1331 if (!kVerboseLogging) return;
1332
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001333 char temp[512], *p = temp, *end = p + sizeof(temp);
1334 Entry* e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001335
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001336 p = bprint(temp, end, "MRU LIST (%2d): ", cache->num_entries);
Bernie Innocenti55864192018-08-30 04:05:20 +09001337 for (e = cache->mru_list.mru_next; e != &cache->mru_list; e = e->mru_next)
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001338 p = bprint(p, end, " %d", e->id);
Bernie Innocenti55864192018-08-30 04:05:20 +09001339
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001340 VLOG << temp;
Bernie Innocenti55864192018-08-30 04:05:20 +09001341}
1342
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001343// TODO: Rewrite to avoid creating a file in /data as temporary buffer (WAT).
1344static void dump_answer(const u_char* answer, int answerlen) {
1345 if (!kVerboseLogging) return;
1346
Bernie Innocenti55864192018-08-30 04:05:20 +09001347 res_state statep;
1348 FILE* fp;
1349 char* buf;
1350 int fileLen;
1351
1352 fp = fopen("/data/reslog.txt", "w+e");
1353 if (fp != NULL) {
Bernie Innocenti4acba1a2018-09-26 11:52:04 +09001354 statep = res_get_state();
Bernie Innocenti55864192018-08-30 04:05:20 +09001355
1356 res_pquery(statep, answer, answerlen, fp);
1357
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001358 // Get file length
Bernie Innocenti55864192018-08-30 04:05:20 +09001359 fseek(fp, 0, SEEK_END);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001360 fileLen = ftell(fp);
Bernie Innocenti55864192018-08-30 04:05:20 +09001361 fseek(fp, 0, SEEK_SET);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001362 buf = (char*) malloc(fileLen + 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001363 if (buf != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001364 // Read file contents into buffer
Bernie Innocenti55864192018-08-30 04:05:20 +09001365 fread(buf, fileLen, 1, fp);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001366 VLOG << buf;
Bernie Innocenti55864192018-08-30 04:05:20 +09001367 free(buf);
1368 }
1369 fclose(fp);
1370 remove("/data/reslog.txt");
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001371 } else {
1372 errno = 0; // else debug is introducing error signals
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001373 VLOG << __func__ << ": can't open file";
Bernie Innocenti55864192018-08-30 04:05:20 +09001374 }
1375}
Bernie Innocenti55864192018-08-30 04:05:20 +09001376
1377/* This function tries to find a key within the hash table
1378 * In case of success, it will return a *pointer* to the hashed key.
1379 * In case of failure, it will return a *pointer* to NULL
1380 *
1381 * So, the caller must check '*result' to check for success/failure.
1382 *
1383 * The main idea is that the result can later be used directly in
1384 * calls to _resolv_cache_add or _resolv_cache_remove as the 'lookup'
1385 * parameter. This makes the code simpler and avoids re-searching
1386 * for the key position in the htable.
1387 *
1388 * The result of a lookup_p is only valid until you alter the hash
1389 * table.
1390 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001391static Entry** _cache_lookup_p(Cache* cache, Entry* key) {
1392 int index = key->hash % cache->max_entries;
1393 Entry** pnode = (Entry**) &cache->entries[index];
Bernie Innocenti55864192018-08-30 04:05:20 +09001394
1395 while (*pnode != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001396 Entry* node = *pnode;
Bernie Innocenti55864192018-08-30 04:05:20 +09001397
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001398 if (node == NULL) break;
Bernie Innocenti55864192018-08-30 04:05:20 +09001399
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001400 if (node->hash == key->hash && entry_equals(node, key)) break;
Bernie Innocenti55864192018-08-30 04:05:20 +09001401
1402 pnode = &node->hlink;
1403 }
1404 return pnode;
1405}
1406
1407/* Add a new entry to the hash table. 'lookup' must be the
1408 * result of an immediate previous failed _lookup_p() call
1409 * (i.e. with *lookup == NULL), and 'e' is the pointer to the
1410 * newly created entry
1411 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001412static void _cache_add_p(Cache* cache, Entry** lookup, Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001413 *lookup = e;
1414 e->id = ++cache->last_id;
1415 entry_mru_add(e, &cache->mru_list);
1416 cache->num_entries += 1;
1417
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001418 VLOG << __func__ << ": entry " << e->id << " added (count=" << cache->num_entries << ")";
Bernie Innocenti55864192018-08-30 04:05:20 +09001419}
1420
1421/* Remove an existing entry from the hash table,
1422 * 'lookup' must be the result of an immediate previous
1423 * and succesful _lookup_p() call.
1424 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001425static void _cache_remove_p(Cache* cache, Entry** lookup) {
1426 Entry* e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001427
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001428 VLOG << __func__ << ": entry " << e->id << " removed (count=" << cache->num_entries - 1 << ")";
Bernie Innocenti55864192018-08-30 04:05:20 +09001429
1430 entry_mru_remove(e);
1431 *lookup = e->hlink;
1432 entry_free(e);
1433 cache->num_entries -= 1;
1434}
1435
1436/* Remove the oldest entry from the hash table.
1437 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001438static void _cache_remove_oldest(Cache* cache) {
1439 Entry* oldest = cache->mru_list.mru_prev;
1440 Entry** lookup = _cache_lookup_p(cache, oldest);
Bernie Innocenti55864192018-08-30 04:05:20 +09001441
1442 if (*lookup == NULL) { /* should not happen */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001443 VLOG << __func__ << ": OLDEST NOT IN HTABLE ?";
Bernie Innocenti55864192018-08-30 04:05:20 +09001444 return;
1445 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001446 VLOG << "Cache full - removing oldest";
1447 dump_query(oldest->query, oldest->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001448 _cache_remove_p(cache, lookup);
1449}
1450
1451/* Remove all expired entries from the hash table.
1452 */
1453static void _cache_remove_expired(Cache* cache) {
1454 Entry* e;
1455 time_t now = _time_now();
1456
1457 for (e = cache->mru_list.mru_next; e != &cache->mru_list;) {
1458 // Entry is old, remove
1459 if (now >= e->expires) {
1460 Entry** lookup = _cache_lookup_p(cache, e);
1461 if (*lookup == NULL) { /* should not happen */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001462 VLOG << __func__ << ": ENTRY NOT IN HTABLE ?";
Bernie Innocenti55864192018-08-30 04:05:20 +09001463 return;
1464 }
1465 e = e->mru_next;
1466 _cache_remove_p(cache, lookup);
1467 } else {
1468 e = e->mru_next;
1469 }
1470 }
1471}
1472
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001473ResolvCacheStatus _resolv_cache_lookup(unsigned netid, const void* query, int querylen,
1474 void* answer, int answersize, int* answerlen) {
1475 Entry key[1];
1476 Entry** lookup;
1477 Entry* e;
1478 time_t now;
1479 Cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001480
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001481 ResolvCacheStatus result = RESOLV_CACHE_NOTFOUND;
Bernie Innocenti55864192018-08-30 04:05:20 +09001482
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001483 VLOG << __func__ << ": lookup";
1484 dump_query((u_char*) query, querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001485
1486 /* we don't cache malformed queries */
1487 if (!entry_init_key(key, query, querylen)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001488 VLOG << __func__ << ": unsupported query";
Bernie Innocenti55864192018-08-30 04:05:20 +09001489 return RESOLV_CACHE_UNSUPPORTED;
1490 }
1491 /* lookup cache */
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001492 pthread_once(&_res_cache_once, res_cache_init);
1493 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001494
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001495 cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001496 if (cache == NULL) {
1497 result = RESOLV_CACHE_UNSUPPORTED;
1498 goto Exit;
1499 }
1500
1501 /* see the description of _lookup_p to understand this.
1502 * the function always return a non-NULL pointer.
1503 */
1504 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001505 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001506
1507 if (e == NULL) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001508 VLOG << "NOT IN CACHE";
Bernie Innocenti55864192018-08-30 04:05:20 +09001509 // calling thread will wait if an outstanding request is found
1510 // that matching this query
1511 if (!_cache_check_pending_request_locked(&cache, key, netid) || cache == NULL) {
1512 goto Exit;
1513 } else {
1514 lookup = _cache_lookup_p(cache, key);
1515 e = *lookup;
1516 if (e == NULL) {
1517 goto Exit;
1518 }
1519 }
1520 }
1521
1522 now = _time_now();
1523
1524 /* remove stale entries here */
1525 if (now >= e->expires) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001526 VLOG << " NOT IN CACHE (STALE ENTRY " << *lookup << "DISCARDED)";
1527 dump_query(e->query, e->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001528 _cache_remove_p(cache, lookup);
1529 goto Exit;
1530 }
1531
1532 *answerlen = e->answerlen;
1533 if (e->answerlen > answersize) {
1534 /* NOTE: we return UNSUPPORTED if the answer buffer is too short */
1535 result = RESOLV_CACHE_UNSUPPORTED;
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001536 VLOG << " ANSWER TOO LONG";
Bernie Innocenti55864192018-08-30 04:05:20 +09001537 goto Exit;
1538 }
1539
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001540 memcpy(answer, e->answer, e->answerlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001541
1542 /* bump up this entry to the top of the MRU list */
1543 if (e != cache->mru_list.mru_next) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001544 entry_mru_remove(e);
1545 entry_mru_add(e, &cache->mru_list);
Bernie Innocenti55864192018-08-30 04:05:20 +09001546 }
1547
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001548 VLOG << "FOUND IN CACHE entry=" << e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001549 result = RESOLV_CACHE_FOUND;
1550
1551Exit:
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001552 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001553 return result;
1554}
1555
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001556void _resolv_cache_add(unsigned netid, const void* query, int querylen, const void* answer,
1557 int answerlen) {
1558 Entry key[1];
1559 Entry* e;
1560 Entry** lookup;
1561 u_long ttl;
1562 Cache* cache = NULL;
Bernie Innocenti55864192018-08-30 04:05:20 +09001563
1564 /* don't assume that the query has already been cached
1565 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001566 if (!entry_init_key(key, query, querylen)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001567 VLOG << __func__ << ": passed invalid query?";
Bernie Innocenti55864192018-08-30 04:05:20 +09001568 return;
1569 }
1570
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001571 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001572
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001573 cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001574 if (cache == NULL) {
1575 goto Exit;
1576 }
1577
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001578 VLOG << __func__ << ": query:";
1579 dump_query((u_char*) query, querylen);
1580 dump_answer((u_char*) answer, answerlen);
1581 if (kDumpData) {
1582 VLOG << "answer:";
1583 dump_bytes((u_char*) answer, answerlen);
1584 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001585
1586 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001587 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001588
1589 if (e != NULL) { /* should not happen */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001590 VLOG << __func__ << ": ALREADY IN CACHE (" << e << ") ? IGNORING ADD";
Bernie Innocenti55864192018-08-30 04:05:20 +09001591 goto Exit;
1592 }
1593
1594 if (cache->num_entries >= cache->max_entries) {
1595 _cache_remove_expired(cache);
1596 if (cache->num_entries >= cache->max_entries) {
1597 _cache_remove_oldest(cache);
1598 }
1599 /* need to lookup again */
1600 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001601 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001602 if (e != NULL) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001603 VLOG << __func__ << ": ALREADY IN CACHE (" << e << ") ? IGNORING ADD";
Bernie Innocenti55864192018-08-30 04:05:20 +09001604 goto Exit;
1605 }
1606 }
1607
1608 ttl = answer_getTTL(answer, answerlen);
1609 if (ttl > 0) {
1610 e = entry_alloc(key, answer, answerlen);
1611 if (e != NULL) {
1612 e->expires = ttl + _time_now();
1613 _cache_add_p(cache, lookup, e);
1614 }
1615 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001616 cache_dump_mru(cache);
1617
Bernie Innocenti55864192018-08-30 04:05:20 +09001618Exit:
1619 if (cache != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001620 _cache_notify_waiting_tid_locked(cache, key);
Bernie Innocenti55864192018-08-30 04:05:20 +09001621 }
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001622 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001623}
1624
Bernie Innocenti55864192018-08-30 04:05:20 +09001625// Head of the list of caches. Protected by _res_cache_list_lock.
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001626static struct resolv_cache_info res_cache_list;
Bernie Innocenti55864192018-08-30 04:05:20 +09001627
1628/* insert resolv_cache_info into the list of resolv_cache_infos */
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001629static void insert_cache_info_locked(resolv_cache_info* cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001630/* creates a resolv_cache_info */
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001631static resolv_cache_info* create_cache_info();
Bernie Innocenti55864192018-08-30 04:05:20 +09001632/* gets a resolv_cache_info associated with a network, or NULL if not found */
1633static struct resolv_cache_info* _find_cache_info_locked(unsigned netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001634/* empty the named cache */
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001635static void flush_cache_for_net_locked(unsigned netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001636/* empty the nameservers set for the named cache */
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001637static void free_nameservers_locked(resolv_cache_info* cache_info);
1638// return 1 if the provided list of name servers differs from the list of name servers
1639// currently attached to the provided cache_info
1640static int resolv_is_nameservers_equal_locked(resolv_cache_info* cache_info, const char** servers,
1641 int numservers);
Bernie Innocenti55864192018-08-30 04:05:20 +09001642/* clears the stats samples contained withing the given cache_info */
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001643static void res_cache_clear_stats_locked(resolv_cache_info* cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001644
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001645static void res_cache_init(void) {
1646 memset(&res_cache_list, 0, sizeof(res_cache_list));
1647 pthread_mutex_init(&res_cache_list_lock, NULL);
Bernie Innocenti55864192018-08-30 04:05:20 +09001648}
1649
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001650/* look up the named cache, and creates one if needed */
1651static resolv_cache* get_res_cache_for_net_locked(unsigned netid) {
1652 resolv_cache* cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001653 if (!cache) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001654 resolv_cache_info* cache_info = create_cache_info();
Bernie Innocenti55864192018-08-30 04:05:20 +09001655 if (cache_info) {
1656 cache = _resolv_cache_create();
1657 if (cache) {
1658 cache_info->cache = cache;
1659 cache_info->netid = netid;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001660 insert_cache_info_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001661 } else {
1662 free(cache_info);
1663 }
1664 }
1665 }
1666 return cache;
1667}
1668
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001669void _resolv_flush_cache_for_net(unsigned netid) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001670 pthread_once(&_res_cache_once, res_cache_init);
1671 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001672
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001673 flush_cache_for_net_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001674
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001675 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001676}
1677
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001678static void flush_cache_for_net_locked(unsigned netid) {
1679 resolv_cache* cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001680 if (cache) {
1681 _cache_flush_locked(cache);
1682 }
1683
1684 // Also clear the NS statistics.
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001685 resolv_cache_info* cache_info = _find_cache_info_locked(netid);
1686 res_cache_clear_stats_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001687}
1688
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001689void _resolv_delete_cache_for_net(unsigned netid) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001690 pthread_once(&_res_cache_once, res_cache_init);
1691 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001692
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001693 struct resolv_cache_info* prev_cache_info = &res_cache_list;
Bernie Innocenti55864192018-08-30 04:05:20 +09001694
1695 while (prev_cache_info->next) {
1696 struct resolv_cache_info* cache_info = prev_cache_info->next;
1697
1698 if (cache_info->netid == netid) {
1699 prev_cache_info->next = cache_info->next;
1700 _cache_flush_locked(cache_info->cache);
1701 free(cache_info->cache->entries);
1702 free(cache_info->cache);
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001703 free_nameservers_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001704 free(cache_info);
1705 break;
1706 }
1707
1708 prev_cache_info = prev_cache_info->next;
1709 }
1710
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001711 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001712}
1713
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001714static resolv_cache_info* create_cache_info() {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001715 return (struct resolv_cache_info*) calloc(sizeof(struct resolv_cache_info), 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001716}
1717
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001718static void insert_cache_info_locked(struct resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001719 struct resolv_cache_info* last;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001720 for (last = &res_cache_list; last->next; last = last->next) {}
Bernie Innocenti55864192018-08-30 04:05:20 +09001721 last->next = cache_info;
Bernie Innocenti55864192018-08-30 04:05:20 +09001722}
1723
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001724static resolv_cache* find_named_cache_locked(unsigned netid) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001725 struct resolv_cache_info* info = _find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001726 if (info != NULL) return info->cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001727 return NULL;
1728}
1729
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001730static struct resolv_cache_info* _find_cache_info_locked(unsigned netid) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001731 struct resolv_cache_info* cache_info = res_cache_list.next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001732
1733 while (cache_info) {
1734 if (cache_info->netid == netid) {
1735 break;
1736 }
1737
1738 cache_info = cache_info->next;
1739 }
1740 return cache_info;
1741}
1742
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001743void _resolv_set_default_params(struct __res_params* params) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001744 params->sample_validity = NSSAMPLE_VALIDITY;
1745 params->success_threshold = SUCCESS_THRESHOLD;
1746 params->min_samples = 0;
1747 params->max_samples = 0;
1748 params->base_timeout_msec = 0; // 0 = legacy algorithm
1749}
1750
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001751int _resolv_set_nameservers_for_net(unsigned netid, const char** servers, unsigned numservers,
1752 const char* domains, const struct __res_params* params) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001753 char sbuf[NI_MAXSERV];
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001754 char* cp;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001755 int* offset;
Bernie Innocenti55864192018-08-30 04:05:20 +09001756 struct addrinfo* nsaddrinfo[MAXNS];
1757
1758 if (numservers > MAXNS) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001759 VLOG << __func__ << ": numservers=" << numservers << ", MAXNS=" << MAXNS;
Bernie Innocenti55864192018-08-30 04:05:20 +09001760 return E2BIG;
1761 }
1762
1763 // Parse the addresses before actually locking or changing any state, in case there is an error.
1764 // As a side effect this also reduces the time the lock is kept.
1765 struct addrinfo hints = {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001766 .ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM, .ai_flags = AI_NUMERICHOST};
Bernie Innocenti55864192018-08-30 04:05:20 +09001767 snprintf(sbuf, sizeof(sbuf), "%u", NAMESERVER_PORT);
1768 for (unsigned i = 0; i < numservers; i++) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001769 // The addrinfo structures allocated here are freed in free_nameservers_locked().
Bernie Innocenti55864192018-08-30 04:05:20 +09001770 int rt = getaddrinfo(servers[i], sbuf, &hints, &nsaddrinfo[i]);
1771 if (rt != 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001772 for (unsigned j = 0; j < i; j++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001773 freeaddrinfo(nsaddrinfo[j]);
1774 nsaddrinfo[j] = NULL;
1775 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001776 VLOG << __func__ << ": getaddrinfo(" << servers[i] << ") = " << gai_strerror(rt);
Bernie Innocenti55864192018-08-30 04:05:20 +09001777 return EINVAL;
1778 }
1779 }
1780
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001781 pthread_once(&_res_cache_once, res_cache_init);
1782 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001783
1784 // creates the cache if not created
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001785 get_res_cache_for_net_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001786
1787 struct resolv_cache_info* cache_info = _find_cache_info_locked(netid);
1788
1789 if (cache_info != NULL) {
1790 uint8_t old_max_samples = cache_info->params.max_samples;
1791 if (params != NULL) {
1792 cache_info->params = *params;
1793 } else {
1794 _resolv_set_default_params(&cache_info->params);
1795 }
1796
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001797 if (!resolv_is_nameservers_equal_locked(cache_info, servers, numservers)) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001798 // free current before adding new
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001799 free_nameservers_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001800 unsigned i;
1801 for (i = 0; i < numservers; i++) {
1802 cache_info->nsaddrinfo[i] = nsaddrinfo[i];
1803 cache_info->nameservers[i] = strdup(servers[i]);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001804 VLOG << __func__ << ": netid = " << netid << ", addr = " << servers[i];
Bernie Innocenti55864192018-08-30 04:05:20 +09001805 }
1806 cache_info->nscount = numservers;
1807
1808 // Clear the NS statistics because the mapping to nameservers might have changed.
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001809 res_cache_clear_stats_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001810
1811 // increment the revision id to ensure that sample state is not written back if the
1812 // servers change; in theory it would suffice to do so only if the servers or
1813 // max_samples actually change, in practice the overhead of checking is higher than the
1814 // cost, and overflows are unlikely
1815 ++cache_info->revision_id;
1816 } else if (cache_info->params.max_samples != old_max_samples) {
1817 // If the maximum number of samples changes, the overhead of keeping the most recent
1818 // samples around is not considered worth the effort, so they are cleared instead. All
1819 // other parameters do not affect shared state: Changing these parameters does not
1820 // invalidate the samples, as they only affect aggregation and the conditions under
1821 // which servers are considered usable.
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001822 res_cache_clear_stats_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001823 ++cache_info->revision_id;
1824 }
1825
1826 // Always update the search paths, since determining whether they actually changed is
1827 // complex due to the zero-padding, and probably not worth the effort. Cache-flushing
1828 // however is not // necessary, since the stored cache entries do contain the domain, not
1829 // just the host name.
1830 // code moved from res_init.c, load_domain_search_list
1831 strlcpy(cache_info->defdname, domains, sizeof(cache_info->defdname));
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001832 if ((cp = strchr(cache_info->defdname, '\n')) != NULL) *cp = '\0';
Bernie Innocenti55864192018-08-30 04:05:20 +09001833
1834 cp = cache_info->defdname;
1835 offset = cache_info->dnsrch_offset;
1836 while (offset < cache_info->dnsrch_offset + MAXDNSRCH) {
1837 while (*cp == ' ' || *cp == '\t') /* skip leading white space */
1838 cp++;
1839 if (*cp == '\0') /* stop if nothing more to do */
1840 break;
1841 *offset++ = cp - cache_info->defdname; /* record this search domain */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001842 while (*cp) { /* zero-terminate it */
1843 if (*cp == ' ' || *cp == '\t') {
Bernie Innocenti55864192018-08-30 04:05:20 +09001844 *cp++ = '\0';
1845 break;
1846 }
1847 cp++;
1848 }
1849 }
1850 *offset = -1; /* cache_info->dnsrch_offset has MAXDNSRCH+1 items */
1851 }
1852
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001853 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001854 return 0;
1855}
1856
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001857static int resolv_is_nameservers_equal_locked(resolv_cache_info* cache_info, const char** servers,
1858 int numservers) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001859 if (cache_info->nscount != numservers) {
1860 return 0;
1861 }
1862
1863 // Compare each name server against current name servers.
1864 // TODO: this is incorrect if the list of current or previous nameservers
1865 // contains duplicates. This does not really matter because the framework
1866 // filters out duplicates, but we should probably fix it. It's also
1867 // insensitive to the order of the nameservers; we should probably fix that
1868 // too.
1869 for (int i = 0; i < numservers; i++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001870 for (int j = 0;; j++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001871 if (j >= numservers) {
1872 return 0;
1873 }
1874 if (strcmp(cache_info->nameservers[i], servers[j]) == 0) {
1875 break;
1876 }
1877 }
1878 }
1879
1880 return 1;
1881}
1882
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001883static void free_nameservers_locked(resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001884 int i;
1885 for (i = 0; i < cache_info->nscount; i++) {
1886 free(cache_info->nameservers[i]);
1887 cache_info->nameservers[i] = NULL;
1888 if (cache_info->nsaddrinfo[i] != NULL) {
1889 freeaddrinfo(cache_info->nsaddrinfo[i]);
1890 cache_info->nsaddrinfo[i] = NULL;
1891 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001892 cache_info->nsstats[i].sample_count = cache_info->nsstats[i].sample_next = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +09001893 }
1894 cache_info->nscount = 0;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001895 res_cache_clear_stats_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001896 ++cache_info->revision_id;
1897}
1898
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001899void _resolv_populate_res_for_net(res_state statp) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001900 if (statp == NULL) {
1901 return;
1902 }
1903
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001904 pthread_once(&_res_cache_once, res_cache_init);
1905 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001906
1907 struct resolv_cache_info* info = _find_cache_info_locked(statp->netid);
1908 if (info != NULL) {
1909 int nserv;
1910 struct addrinfo* ai;
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001911 VLOG << __func__ << ": " << statp->netid;
Bernie Innocenti55864192018-08-30 04:05:20 +09001912 for (nserv = 0; nserv < MAXNS; nserv++) {
1913 ai = info->nsaddrinfo[nserv];
1914 if (ai == NULL) {
1915 break;
1916 }
1917
1918 if ((size_t) ai->ai_addrlen <= sizeof(statp->_u._ext.ext->nsaddrs[0])) {
1919 if (statp->_u._ext.ext != NULL) {
1920 memcpy(&statp->_u._ext.ext->nsaddrs[nserv], ai->ai_addr, ai->ai_addrlen);
1921 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
1922 } else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001923 if ((size_t) ai->ai_addrlen <= sizeof(statp->nsaddr_list[0])) {
1924 memcpy(&statp->nsaddr_list[nserv], ai->ai_addr, ai->ai_addrlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001925 } else {
1926 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
1927 }
1928 }
1929 } else {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001930 VLOG << __func__ << ": found too long addrlen";
Bernie Innocenti55864192018-08-30 04:05:20 +09001931 }
1932 }
1933 statp->nscount = nserv;
1934 // now do search domains. Note that we cache the offsets as this code runs alot
1935 // but the setting/offset-computer only runs when set/changed
1936 // WARNING: Don't use str*cpy() here, this string contains zeroes.
1937 memcpy(statp->defdname, info->defdname, sizeof(statp->defdname));
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001938 char** pp = statp->dnsrch;
1939 int* p = info->dnsrch_offset;
Bernie Innocenti55864192018-08-30 04:05:20 +09001940 while (pp < statp->dnsrch + MAXDNSRCH && *p != -1) {
1941 *pp++ = &statp->defdname[0] + *p++;
1942 }
1943 }
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001944 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001945}
1946
1947/* Resolver reachability statistics. */
1948
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001949static void _res_cache_add_stats_sample_locked(struct __res_stats* stats,
1950 const struct __res_sample* sample, int max_samples) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001951 // Note: This function expects max_samples > 0, otherwise a (harmless) modification of the
1952 // allocated but supposedly unused memory for samples[0] will happen
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001953 VLOG << __func__ << ": adding sample to stats, next = " << stats->sample_next
1954 << ", count = " << stats->sample_count;
Bernie Innocenti55864192018-08-30 04:05:20 +09001955 stats->samples[stats->sample_next] = *sample;
1956 if (stats->sample_count < max_samples) {
1957 ++stats->sample_count;
1958 }
1959 if (++stats->sample_next >= max_samples) {
1960 stats->sample_next = 0;
1961 }
1962}
1963
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001964static void res_cache_clear_stats_locked(resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001965 if (cache_info) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001966 for (int i = 0; i < MAXNS; ++i) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001967 cache_info->nsstats->sample_count = cache_info->nsstats->sample_next = 0;
1968 }
1969 }
1970}
1971
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001972int android_net_res_stats_get_info_for_net(unsigned netid, int* nscount,
1973 struct sockaddr_storage servers[MAXNS], int* dcount,
1974 char domains[MAXDNSRCH][MAXDNSRCHPATH],
1975 struct __res_params* params,
1976 struct __res_stats stats[MAXNS]) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001977 int revision_id = -1;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001978 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001979
1980 struct resolv_cache_info* info = _find_cache_info_locked(netid);
1981 if (info) {
1982 if (info->nscount > MAXNS) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001983 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001984 VLOG << __func__ << ": nscount " << info->nscount << " > MAXNS " << MAXNS;
Bernie Innocenti55864192018-08-30 04:05:20 +09001985 errno = EFAULT;
1986 return -1;
1987 }
1988 int i;
1989 for (i = 0; i < info->nscount; i++) {
1990 // Verify that the following assumptions are held, failure indicates corruption:
1991 // - getaddrinfo() may never return a sockaddr > sockaddr_storage
1992 // - all addresses are valid
1993 // - there is only one address per addrinfo thanks to numeric resolution
1994 int addrlen = info->nsaddrinfo[i]->ai_addrlen;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001995 if (addrlen < (int) sizeof(struct sockaddr) || addrlen > (int) sizeof(servers[0])) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001996 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001997 VLOG << __func__ << ": nsaddrinfo[" << i << "].ai_addrlen == " << addrlen;
Bernie Innocenti55864192018-08-30 04:05:20 +09001998 errno = EMSGSIZE;
1999 return -1;
2000 }
2001 if (info->nsaddrinfo[i]->ai_addr == NULL) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09002002 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09002003 VLOG << __func__ << ": nsaddrinfo[" << i << "].ai_addr == NULL";
Bernie Innocenti55864192018-08-30 04:05:20 +09002004 errno = ENOENT;
2005 return -1;
2006 }
2007 if (info->nsaddrinfo[i]->ai_next != NULL) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09002008 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09002009 VLOG << __func__ << ": nsaddrinfo[" << i << "].ai_next != NULL";
Bernie Innocenti55864192018-08-30 04:05:20 +09002010 errno = ENOTUNIQ;
2011 return -1;
2012 }
2013 }
2014 *nscount = info->nscount;
2015 for (i = 0; i < info->nscount; i++) {
2016 memcpy(&servers[i], info->nsaddrinfo[i]->ai_addr, info->nsaddrinfo[i]->ai_addrlen);
2017 stats[i] = info->nsstats[i];
2018 }
2019 for (i = 0; i < MAXDNSRCH; i++) {
2020 const char* cur_domain = info->defdname + info->dnsrch_offset[i];
2021 // dnsrch_offset[i] can either be -1 or point to an empty string to indicate the end
2022 // of the search offsets. Checking for < 0 is not strictly necessary, but safer.
2023 // TODO: Pass in a search domain array instead of a string to
2024 // _resolv_set_nameservers_for_net() and make this double check unnecessary.
2025 if (info->dnsrch_offset[i] < 0 ||
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002026 ((size_t) info->dnsrch_offset[i]) >= sizeof(info->defdname) || !cur_domain[0]) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002027 break;
2028 }
2029 strlcpy(domains[i], cur_domain, MAXDNSRCHPATH);
2030 }
2031 *dcount = i;
2032 *params = info->params;
2033 revision_id = info->revision_id;
2034 }
2035
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09002036 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09002037 return revision_id;
2038}
2039
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002040int _resolv_cache_get_resolver_stats(unsigned netid, struct __res_params* params,
2041 struct __res_stats stats[MAXNS]) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002042 int revision_id = -1;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09002043 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09002044
2045 struct resolv_cache_info* info = _find_cache_info_locked(netid);
2046 if (info) {
2047 memcpy(stats, info->nsstats, sizeof(info->nsstats));
2048 *params = info->params;
2049 revision_id = info->revision_id;
2050 }
2051
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09002052 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09002053 return revision_id;
2054}
2055
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002056void _resolv_cache_add_resolver_stats_sample(unsigned netid, int revision_id, int ns,
2057 const struct __res_sample* sample, int max_samples) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002058 if (max_samples <= 0) return;
2059
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09002060 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09002061
2062 struct resolv_cache_info* info = _find_cache_info_locked(netid);
2063
2064 if (info && info->revision_id == revision_id) {
2065 _res_cache_add_stats_sample_locked(&info->nsstats[ns], sample, max_samples);
2066 }
2067
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09002068 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09002069}