blob: b298b39ca105f9de61fa0c8a1e9db7625c935ebc [file] [log] [blame]
Bernie Innocenti318ed2d2018-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 Innocenti9f05f5e2018-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 Innocentiafaacf72018-08-30 07:34:37 +090035#include <pthread.h>
Bernie Innocenti318ed2d2018-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 Innocenti318ed2d2018-08-30 04:05:20 +090042
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +090043#include <arpa/inet.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090044#include <arpa/nameser.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090045#include <errno.h>
46#include <linux/if.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090047#include <net/if.h>
48#include <netdb.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090049
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +090050#include <android-base/logging.h>
Bernie Innocentiafaacf72018-08-30 07:34:37 +090051
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090052#include "res_private.h"
Bernie Innocentiafaacf72018-08-30 07:34:37 +090053#include "resolv_cache.h"
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090054#include "resolv_netid.h"
55#include "resolv_private.h"
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090056
Bernie Innocenti9f05f5e2018-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 Innocenti318ed2d2018-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 Innocenti9f05f5e2018-09-12 23:20:10 +0900145#define CONFIG_MAX_ENTRIES (64 * 2 * 5)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900146
Bernie Innocenti9c575932018-09-07 21:10:25 +0900147/** BOUNDED BUFFER FORMATTING **/
Bernie Innocenti318ed2d2018-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 Innocenti9f05f5e2018-09-12 23:20:10 +0900163 * the bprint_x() functions return the new value of 'p' after the data
Bernie Innocenti318ed2d2018-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 Innocenti9f05f5e2018-09-12 23:20:10 +0900168 * - a return value equal to 'end' means that truncation occurred
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900169 * (in which case, end[-1] will be set to 0)
170 *
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900171 * - after returning from a bprint_x() function, the content of the buffer
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900172 * is always 0-terminated, even in the event of truncation.
173 *
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900174 * these conventions allow you to call bprint_x() functions multiple times and
Bernie Innocenti318ed2d2018-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 Innocenti9f05f5e2018-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 Innocenti318ed2d2018-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 Innocenti9f05f5e2018-09-12 23:20:10 +0900191static char* bprint_c(char* p, char* end, int c) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900192 if (p < end) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900193 if (p + 1 == end)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900194 *p++ = 0;
195 else {
196 *p++ = (char) c;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900197 *p = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900198 }
199 }
200 return p;
201}
202
203/* add a sequence of bytes to a bounded buffer */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900204static char* bprint_b(char* p, char* end, const char* buf, int len) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900205 int avail = end - p;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900206
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900207 if (avail <= 0 || len <= 0) return p;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900208
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900209 if (avail > len) avail = len;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900210
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900211 memcpy(p, buf, avail);
Bernie Innocenti318ed2d2018-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 Innocenti9f05f5e2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900225}
226
227/* add a formatted string to a bounded buffer */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900228static char* bprint(char* p, char* end, const char* format, ...) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900229 int avail, n;
230 va_list args;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900231
232 avail = end - p;
233
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900234 if (avail <= 0) return p;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900235
236 va_start(args, format);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900237 n = vsnprintf(p, avail, format, args);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900238 va_end(args);
239
240 /* certain C libraries return -1 in case of truncation */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900241 if (n < 0 || n > avail) n = avail;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900242
243 p += n;
244 /* certain C libraries do not zero-terminate in case of truncation */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900245 if (p == end) p[-1] = 0;
Bernie Innocenti318ed2d2018-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 Innocenti9f05f5e2018-09-12 23:20:10 +0900251static char* bprint_hex(char* p, char* end, unsigned value, int numDigits) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900252 char text[sizeof(unsigned) * 2];
253 int nn = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900254
255 while (numDigits-- > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900256 text[nn++] = "0123456789abcdef"[(value >> (numDigits * 4)) & 15];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900257 }
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900258 return bprint_b(p, end, text, nn);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900259}
260
261/* add the hexadecimal dump of some memory area to a bounded buffer */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900262static char* bprint_hexdump(char* p, char* end, const uint8_t* data, int datalen) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900263 int lineSize = 16;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900264
265 while (datalen > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900266 int avail = datalen;
267 int nn;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900268
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900269 if (avail > lineSize) avail = lineSize;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900270
271 for (nn = 0; nn < avail; nn++) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900272 if (nn > 0) p = bprint_c(p, end, ' ');
273 p = bprint_hex(p, end, data[nn], 2);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900274 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900275 for (; nn < lineSize; nn++) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900276 p = bprint_s(p, end, " ");
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900277 }
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900278 p = bprint_s(p, end, " ");
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900279
280 for (nn = 0; nn < avail; nn++) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900281 int c = data[nn];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900282
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900283 if (c < 32 || c > 127) c = '.';
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900284
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900285 p = bprint_c(p, end, c);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900286 }
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900287 p = bprint_c(p, end, '\n');
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900288
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900289 data += avail;
Bernie Innocenti318ed2d2018-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 Innocenti9f05f5e2018-09-12 23:20:10 +0900296static void dump_bytes(const uint8_t* base, int len) {
297 if (!kDumpData) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900298
Bernie Innocenti9f05f5e2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900304}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900305
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900306static time_t _time_now(void) {
307 struct timeval tv;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900308
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900309 gettimeofday(&tv, NULL);
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900398#define DNS_HEADER_SIZE 12
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900399
Bernie Innocenti8ad893f2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900405
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900406#define DNS_CLASS_IN "\00\01" /* big-endian decimal 1 */
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900407
408typedef struct {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900409 const uint8_t* base;
410 const uint8_t* end;
411 const uint8_t* cursor;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900412} DnsPacket;
413
Bernie Innocenti8ad893f2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900417 packet->cursor = buff;
418}
419
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900420static void _dnsPacket_rewind(DnsPacket* packet) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900421 packet->cursor = packet->base;
422}
423
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900424static void _dnsPacket_skip(DnsPacket* packet, int count) {
425 const uint8_t* p = packet->cursor + count;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900426
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900427 if (p > packet->end) p = packet->end;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900428
429 packet->cursor = p;
430}
431
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900432static int _dnsPacket_readInt16(DnsPacket* packet) {
433 const uint8_t* p = packet->cursor;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900434
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900435 if (p + 2 > packet->end) return -1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900436
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900437 packet->cursor = p + 2;
438 return (p[0] << 8) | p[1];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900439}
440
Bernie Innocenti9c575932018-09-07 21:10:25 +0900441/** QUERY CHECKING **/
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900446static int _dnsPacket_checkBytes(DnsPacket* packet, int numBytes, const void* bytes) {
447 const uint8_t* p = packet->cursor;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900448
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900449 if (p + numBytes > packet->end) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900450
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900451 if (memcmp(p, bytes, numBytes) != 0) return 0;
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900464
465 for (;;) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900466 int c;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900467
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900468 if (p >= end) break;
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900478 if (c >= 64) break;
Bernie Innocenti318ed2d2018-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 Innocenti9f05f5e2018-09-12 23:20:10 +0900485 VLOG << "malformed QNAME";
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900492static int _dnsPacket_checkQR(DnsPacket* packet) {
493 if (!_dnsPacket_checkQName(packet)) return 0;
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900500 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_ALL)) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900501 VLOG << "unsupported TYPE";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900502 return 0;
503 }
504 /* CLASS must be IN */
505 if (!_dnsPacket_checkBytes(packet, 2, DNS_CLASS_IN)) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900506 VLOG << "unsupported CLASS";
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900519
520 if (p + DNS_HEADER_SIZE > packet->end) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900521 VLOG << "query packet too small";
Bernie Innocenti318ed2d2018-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 Innocenti9f05f5e2018-09-12 23:20:10 +0900528 VLOG << "query packet flags unsupported";
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900554 arCount = (p[10] << 8) | p[11];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900555
556 if (anCount != 0 || dnCount != 0 || arCount > 1) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900557 VLOG << "query packet contains non-query records";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900558 return 0;
559 }
560
561 if (qdCount == 0) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900562 VLOG << "query packet doesn't contain query record";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900563 return 0;
564 }
565
566 /* Check QDCOUNT QRs */
567 packet->cursor = p + DNS_HEADER_SIZE;
568
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900569 for (; qdCount > 0; qdCount--)
570 if (!_dnsPacket_checkQR(packet)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900571
572 return 1;
573}
574
Bernie Innocenti9c575932018-09-07 21:10:25 +0900575/** QUERY DEBUGGING **/
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900576static char* dnsPacket_bprintQName(DnsPacket* packet, char* bp, char* bend) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900577 const uint8_t* p = packet->cursor;
578 const uint8_t* end = packet->end;
579 int first = 1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900580
581 for (;;) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900582 int c;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900583
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900584 if (p >= end) break;
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900594 if (c >= 64) break;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900595
596 if (first)
597 first = 0;
598 else
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900599 bp = bprint_c(bp, bend, '.');
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900600
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900601 bp = bprint_b(bp, bend, (const char*) p, c);
Bernie Innocenti318ed2d2018-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 Innocenti9f05f5e2018-09-12 23:20:10 +0900608 bp = bprint_s(bp, bend, "<MALFORMED>");
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900609 return bp;
610}
611
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900612static char* dnsPacket_bprintQR(DnsPacket* packet, char* p, char* end) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900613#define QQ(x) \
614 { DNS_TYPE_##x, #x }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900615 static const struct {
Bernie Innocenti8ad893f2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900621
622 /* dump QNAME */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900623 p = dnsPacket_bprintQName(packet, p, end);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900624
625 /* dump TYPE */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900626 p = bprint_s(p, end, " (");
Bernie Innocenti318ed2d2018-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 Innocenti9f05f5e2018-09-12 23:20:10 +0900636 p = bprint_s(p, end, typeString);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900637 else {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900638 int typeCode = _dnsPacket_readInt16(packet);
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900639 p = bprint(p, end, "UNKNOWN-%d", typeCode);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900640 }
641
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900642 p = bprint_c(p, end, ')');
Bernie Innocenti318ed2d2018-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 Innocenti9f05f5e2018-09-12 23:20:10 +0900650static char* dnsPacket_bprintQuery(DnsPacket* packet, char* p, char* end) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900651 int qdCount;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900652
653 if (packet->base[2] & 0x1) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900654 p = bprint_s(p, end, "RECURSIVE ");
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900655 }
656
657 _dnsPacket_skip(packet, 4);
658 qdCount = _dnsPacket_readInt16(packet);
659 _dnsPacket_skip(packet, 6);
660
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900661 for (; qdCount > 0; qdCount--) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900662 p = dnsPacket_bprintQR(packet, p, end);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900663 }
664 return p;
665}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900666
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900674#define FNV_MULT 16777619U
675#define FNV_BASIS 2166136261U
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900676
Bernie Innocenti8ad893f2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900680
681 while (numBytes > 0 && p < end) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900682 hash = hash * FNV_MULT ^ *p++;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900683 }
684 packet->cursor = p;
685 return hash;
686}
687
Bernie Innocenti8ad893f2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900691
692 for (;;) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900693 int c;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900694
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900695 if (p >= end) { /* should not happen */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900696 VLOG << __func__ << ": INTERNAL_ERROR: read-overflow";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900697 break;
698 }
699
700 c = *p++;
701
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900702 if (c == 0) break;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900703
704 if (c >= 64) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900705 VLOG << __func__ << ": INTERNAL_ERROR: malformed domain";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900706 break;
707 }
708 if (p + c >= end) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900709 VLOG << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900710 break;
711 }
712 while (c > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900713 hash = hash * FNV_MULT ^ *p++;
714 c -= 1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900715 }
716 }
717 packet->cursor = p;
718 return hash;
719}
720
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900721static unsigned _dnsPacket_hashQR(DnsPacket* packet, unsigned hash) {
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900727static unsigned _dnsPacket_hashRR(DnsPacket* packet, unsigned hash) {
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900736static unsigned _dnsPacket_hashQuery(DnsPacket* packet) {
737 unsigned hash = FNV_BASIS;
738 int count, arcount;
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900751 hash = hash * FNV_MULT ^ (packet->base[2] & 1);
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900769 for (; count > 0; count--) hash = _dnsPacket_hashQR(packet, hash);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900770
771 /* hash ARCOUNT RRs */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900772 for (; arcount > 0; arcount--) hash = _dnsPacket_hashRR(packet, hash);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900773
774 return hash;
775}
776
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900777/** QUERY COMPARISON
778 **
779 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKETS HAVE ALREADY
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900780 ** BEEN SUCCESSFULLY CHECKED.
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900781 **/
782
Bernie Innocenti8ad893f2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900788
789 for (;;) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900790 int c1, c2;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900791
792 if (p1 >= end1 || p2 >= end2) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900793 VLOG << __func__ << ": INTERNAL_ERROR: read-overflow";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900794 break;
795 }
796 c1 = *p1++;
797 c2 = *p2++;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900798 if (c1 != c2) break;
Bernie Innocenti318ed2d2018-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 Innocenti9f05f5e2018-09-12 23:20:10 +0900806 VLOG << __func__ << ": INTERNAL_ERROR: malformed domain";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900807 break;
808 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900809 if ((p1 + c1 > end1) || (p2 + c1 > end2)) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900810 VLOG << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900811 break;
812 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900813 if (memcmp(p1, p2, c1) != 0) break;
Bernie Innocenti318ed2d2018-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 Innocenti9f05f5e2018-09-12 23:20:10 +0900819 VLOG << "different DN";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900820 return 0;
821}
822
Bernie Innocenti8ad893f2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900826
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900827 if (p1 + numBytes > pack1->end || p2 + numBytes > pack2->end) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900828
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900829 if (memcmp(p1, p2, numBytes) != 0) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900830
831 pack1->cursor += numBytes;
832 pack2->cursor += numBytes;
833 return 1;
834}
835
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900836static int _dnsPacket_isEqualQR(DnsPacket* pack1, DnsPacket* pack2) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900837 /* compare domain name encoding + TYPE + CLASS */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900838 if (!_dnsPacket_isEqualDomainName(pack1, pack2) ||
839 !_dnsPacket_isEqualBytes(pack1, pack2, 2 + 2))
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900840 return 0;
841
842 return 1;
843}
844
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900845static int _dnsPacket_isEqualRR(DnsPacket* pack1, DnsPacket* pack2) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900846 int rdlength1, rdlength2;
847 /* compare query + TTL */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900848 if (!_dnsPacket_isEqualQR(pack1, pack2) || !_dnsPacket_isEqualBytes(pack1, pack2, 4)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900849
850 /* compare RDATA */
851 rdlength1 = _dnsPacket_readInt16(pack1);
852 rdlength2 = _dnsPacket_readInt16(pack2);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900853 if (rdlength1 != rdlength2 || !_dnsPacket_isEqualBytes(pack1, pack2, rdlength1)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900854
855 return 1;
856}
857
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900858static int _dnsPacket_isEqualQuery(DnsPacket* pack1, DnsPacket* pack2) {
859 int count1, count2, arcount1, arcount2;
Bernie Innocenti318ed2d2018-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 Innocenti9f05f5e2018-09-12 23:20:10 +0900867 VLOG << "different RD";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900868 return 0;
869 }
870
871 if (pack1->base[3] != pack2->base[3]) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900872 VLOG << "different CD or AD";
Bernie Innocenti318ed2d2018-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 Innocenti9f05f5e2018-09-12 23:20:10 +0900884 VLOG << "different QDCOUNT";
Bernie Innocenti318ed2d2018-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 Innocenti9f05f5e2018-09-12 23:20:10 +0900896 VLOG << "different ARCOUNT";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900897 return 0;
898 }
899
900 /* compare the QDCOUNT QRs */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900901 for (; count1 > 0; count1--) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900902 if (!_dnsPacket_isEqualQR(pack1, pack2)) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900903 VLOG << "different QR";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900904 return 0;
905 }
906 }
907
908 /* compare the ARCOUNT RRs */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900909 for (; arcount1 > 0; arcount1--) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900910 if (!_dnsPacket_isEqualRR(pack1, pack2)) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900911 VLOG << "different additional RR";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900912 return 0;
913 }
914 }
915 return 1;
916}
917
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900928
Bernie Innocenti8ad893f2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900935} Entry;
936
Bernie Innocenti9c575932018-09-07 21:10:25 +0900937/*
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900943static u_long answer_getNegativeTTL(ns_msg handle) {
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-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 Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900959 if (len == -1) continue; // error skipping
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900960 rdata += len;
961
962 // skip the admin name
963 len = dn_skipname(rdata, edata);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900964 if (len == -1) continue; // error skipping
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900965 rdata += len;
966
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900967 if (edata - rdata != 5 * NS_INT32SZ) continue;
Bernie Innocenti318ed2d2018-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 Innocenti9c575932018-09-07 21:10:25 +0900984/*
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900996static u_long answer_getTTL(const void* answer, int answerlen) {
Bernie Innocenti318ed2d2018-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 Innocenti9c575932018-09-07 21:10:25 +09001003 if (ns_initparse((const uint8_t*) answer, answerlen, &handle) >= 0) {
Bernie Innocenti318ed2d2018-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 Innocenti9f05f5e2018-09-12 23:20:10 +09001018 VLOG << "ns_parserr failed ancount no = "
1019 << n << ". errno = " << strerror(errno);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001020 }
1021 }
1022 }
1023 } else {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001024 VLOG << "ns_initparse failed: " << strerror(errno);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001025 }
1026
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001027 VLOG << "TTL = " << result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001028 return result;
1029}
1030
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001031static void entry_free(Entry* e) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001032 /* everything is allocated in a single memory block */
1033 if (e) {
1034 free(e);
1035 }
1036}
1037
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001038static __inline__ void entry_mru_remove(Entry* e) {
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +09001043static __inline__ void entry_mru_add(Entry* e, Entry* list) {
1044 Entry* first = list->mru_next;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001045
1046 e->mru_next = first;
1047 e->mru_prev = list;
1048
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001049 list->mru_next = e;
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +09001055static unsigned entry_hash(const Entry* e) {
1056 DnsPacket pack[1];
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +09001064static int entry_init_key(Entry* e, const void* query, int querylen) {
1065 DnsPacket pack[1];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001066
1067 memset(e, 0, sizeof(*e));
1068
Bernie Innocenti9c575932018-09-07 21:10:25 +09001069 e->query = (const uint8_t*) query;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001070 e->querylen = querylen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001071 e->hash = entry_hash(e);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001072
Bernie Innocenti9c575932018-09-07 21:10:25 +09001073 _dnsPacket_init(pack, e->query, e->querylen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001074
1075 return _dnsPacket_checkQuery(pack);
1076}
1077
1078/* allocate a new entry as a cache node */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001079static Entry* entry_alloc(const Entry* init, const void* answer, int answerlen) {
1080 Entry* e;
1081 int size;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001082
1083 size = sizeof(*e) + init->querylen + answerlen;
Bernie Innocenti9c575932018-09-07 21:10:25 +09001084 e = (Entry*) calloc(size, 1);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001085 if (e == NULL) return e;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001086
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001087 e->hash = init->hash;
1088 e->query = (const uint8_t*) (e + 1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001089 e->querylen = init->querylen;
1090
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001091 memcpy((char*) e->query, init->query, e->querylen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001092
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001093 e->answer = e->query + e->querylen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001094 e->answerlen = answerlen;
1095
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001096 memcpy((char*) e->answer, answer, e->answerlen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001097
1098 return e;
1099}
1100
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001101static int entry_equals(const Entry* e1, const Entry* e2) {
1102 DnsPacket pack1[1], pack2[1];
Bernie Innocenti318ed2d2018-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
1113/****************************************************************************/
1114/****************************************************************************/
1115/***** *****/
1116/***** *****/
1117/***** *****/
1118/****************************************************************************/
1119/****************************************************************************/
1120
1121/* We use a simple hash table with external collision lists
1122 * for simplicity, the hash-table fields 'hash' and 'hlink' are
1123 * inlined in the Entry structure.
1124 */
1125
1126/* Maximum time for a thread to wait for an pending request */
1127#define PENDING_REQUEST_TIMEOUT 20;
1128
1129typedef struct pending_req_info {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001130 unsigned int hash;
1131 pthread_cond_t cond;
1132 struct pending_req_info* next;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001133} PendingReqInfo;
1134
1135typedef struct resolv_cache {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001136 int max_entries;
1137 int num_entries;
1138 Entry mru_list;
1139 int last_id;
1140 Entry* entries;
1141 PendingReqInfo pending_requests;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001142} Cache;
1143
1144struct resolv_cache_info {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001145 unsigned netid;
1146 Cache* cache;
1147 struct resolv_cache_info* next;
1148 int nscount;
1149 char* nameservers[MAXNS];
1150 struct addrinfo* nsaddrinfo[MAXNS];
1151 int revision_id; // # times the nameservers have been replaced
1152 struct __res_params params;
1153 struct __res_stats nsstats[MAXNS];
1154 char defdname[MAXDNSRCHPATH];
1155 int dnsrch_offset[MAXDNSRCH + 1]; // offsets into defdname
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001156};
1157
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001158#define HTABLE_VALID(x) ((x) != NULL && (x) != HTABLE_DELETED)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001159
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001160static pthread_once_t _res_cache_once = PTHREAD_ONCE_INIT;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001161static void _res_cache_init(void);
1162
1163// lock protecting everything in the _resolve_cache_info structs (next ptr, etc)
1164static pthread_mutex_t _res_cache_list_lock;
1165
1166/* gets cache associated with a network, or NULL if none exists */
1167static struct resolv_cache* _find_named_cache_locked(unsigned netid);
1168
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001169static void _cache_flush_pending_requests_locked(struct resolv_cache* cache) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001170 struct pending_req_info *ri, *tmp;
1171 if (cache) {
1172 ri = cache->pending_requests.next;
1173
1174 while (ri) {
1175 tmp = ri;
1176 ri = ri->next;
1177 pthread_cond_broadcast(&tmp->cond);
1178
1179 pthread_cond_destroy(&tmp->cond);
1180 free(tmp);
1181 }
1182
1183 cache->pending_requests.next = NULL;
1184 }
1185}
1186
1187/* Return 0 if no pending request is found matching the key.
1188 * If a matching request is found the calling thread will wait until
1189 * the matching request completes, then update *cache and return 1. */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001190static int _cache_check_pending_request_locked(struct resolv_cache** cache, Entry* key,
1191 unsigned netid) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001192 struct pending_req_info *ri, *prev;
1193 int exist = 0;
1194
1195 if (*cache && key) {
1196 ri = (*cache)->pending_requests.next;
1197 prev = &(*cache)->pending_requests;
1198 while (ri) {
1199 if (ri->hash == key->hash) {
1200 exist = 1;
1201 break;
1202 }
1203 prev = ri;
1204 ri = ri->next;
1205 }
1206
1207 if (!exist) {
Bernie Innocenti9c575932018-09-07 21:10:25 +09001208 ri = (struct pending_req_info*) calloc(1, sizeof(struct pending_req_info));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001209 if (ri) {
1210 ri->hash = key->hash;
1211 pthread_cond_init(&ri->cond, NULL);
1212 prev->next = ri;
1213 }
1214 } else {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001215 struct timespec ts = {0, 0};
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001216 VLOG << "Waiting for previous request";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001217 ts.tv_sec = _time_now() + PENDING_REQUEST_TIMEOUT;
1218 pthread_cond_timedwait(&ri->cond, &_res_cache_list_lock, &ts);
1219 /* Must update *cache as it could have been deleted. */
1220 *cache = _find_named_cache_locked(netid);
1221 }
1222 }
1223
1224 return exist;
1225}
1226
1227/* notify any waiting thread that waiting on a request
1228 * matching the key has been added to the cache */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001229static void _cache_notify_waiting_tid_locked(struct resolv_cache* cache, Entry* key) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001230 struct pending_req_info *ri, *prev;
1231
1232 if (cache && key) {
1233 ri = cache->pending_requests.next;
1234 prev = &cache->pending_requests;
1235 while (ri) {
1236 if (ri->hash == key->hash) {
1237 pthread_cond_broadcast(&ri->cond);
1238 break;
1239 }
1240 prev = ri;
1241 ri = ri->next;
1242 }
1243
1244 // remove item from list and destroy
1245 if (ri) {
1246 prev->next = ri->next;
1247 pthread_cond_destroy(&ri->cond);
1248 free(ri);
1249 }
1250 }
1251}
1252
1253/* notify the cache that the query failed */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001254void _resolv_cache_query_failed(unsigned netid, const void* query, int querylen) {
1255 Entry key[1];
1256 Cache* cache;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001257
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001258 if (!entry_init_key(key, query, querylen)) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001259
1260 pthread_mutex_lock(&_res_cache_list_lock);
1261
1262 cache = _find_named_cache_locked(netid);
1263
1264 if (cache) {
1265 _cache_notify_waiting_tid_locked(cache, key);
1266 }
1267
1268 pthread_mutex_unlock(&_res_cache_list_lock);
1269}
1270
1271static struct resolv_cache_info* _find_cache_info_locked(unsigned netid);
1272
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001273static void _cache_flush_locked(Cache* cache) {
1274 int nn;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001275
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001276 for (nn = 0; nn < cache->max_entries; nn++) {
1277 Entry** pnode = (Entry**) &cache->entries[nn];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001278
1279 while (*pnode != NULL) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001280 Entry* node = *pnode;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001281 *pnode = node->hlink;
1282 entry_free(node);
1283 }
1284 }
1285
1286 // flush pending request
1287 _cache_flush_pending_requests_locked(cache);
1288
1289 cache->mru_list.mru_next = cache->mru_list.mru_prev = &cache->mru_list;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001290 cache->num_entries = 0;
1291 cache->last_id = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001292
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001293 VLOG << "*** DNS CACHE FLUSHED ***";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001294}
1295
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001296static int _res_cache_get_max_entries(void) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001297 int cache_size = CONFIG_MAX_ENTRIES;
1298
1299 const char* cache_mode = getenv("ANDROID_DNS_MODE");
1300 if (cache_mode == NULL || strcmp(cache_mode, "local") != 0) {
1301 // Don't use the cache in local mode. This is used by the proxy itself.
1302 cache_size = 0;
1303 }
1304
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001305 VLOG << "cache size: " << cache_size;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001306 return cache_size;
1307}
1308
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001309static struct resolv_cache* _resolv_cache_create(void) {
1310 struct resolv_cache* cache;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001311
Bernie Innocenti9c575932018-09-07 21:10:25 +09001312 cache = (struct resolv_cache*) calloc(sizeof(*cache), 1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001313 if (cache) {
1314 cache->max_entries = _res_cache_get_max_entries();
Bernie Innocenti9c575932018-09-07 21:10:25 +09001315 cache->entries = (Entry*) calloc(sizeof(*cache->entries), cache->max_entries);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001316 if (cache->entries) {
1317 cache->mru_list.mru_prev = cache->mru_list.mru_next = &cache->mru_list;
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001318 VLOG << __func__ << ": cache created";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001319 } else {
1320 free(cache);
1321 cache = NULL;
1322 }
1323 }
1324 return cache;
1325}
1326
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001327static void dump_query(const uint8_t* query, int querylen) {
1328 if (!kVerboseLogging) return;
1329
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001330 char temp[256], *p = temp, *end = p + sizeof(temp);
1331 DnsPacket pack[1];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001332
1333 _dnsPacket_init(pack, query, querylen);
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001334 p = dnsPacket_bprintQuery(pack, p, end);
1335 VLOG << temp;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001336}
1337
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001338static void cache_dump_mru(Cache* cache) {
1339 if (!kVerboseLogging) return;
1340
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001341 char temp[512], *p = temp, *end = p + sizeof(temp);
1342 Entry* e;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001343
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001344 p = bprint(temp, end, "MRU LIST (%2d): ", cache->num_entries);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001345 for (e = cache->mru_list.mru_next; e != &cache->mru_list; e = e->mru_next)
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001346 p = bprint(p, end, " %d", e->id);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001347
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001348 VLOG << temp;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001349}
1350
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001351// TODO: Rewrite to avoid creating a file in /data as temporary buffer (WAT).
1352static void dump_answer(const u_char* answer, int answerlen) {
1353 if (!kVerboseLogging) return;
1354
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001355 res_state statep;
1356 FILE* fp;
1357 char* buf;
1358 int fileLen;
1359
1360 fp = fopen("/data/reslog.txt", "w+e");
1361 if (fp != NULL) {
1362 statep = __res_get_state();
1363
1364 res_pquery(statep, answer, answerlen, fp);
1365
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001366 // Get file length
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001367 fseek(fp, 0, SEEK_END);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001368 fileLen = ftell(fp);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001369 fseek(fp, 0, SEEK_SET);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001370 buf = (char*) malloc(fileLen + 1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001371 if (buf != NULL) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001372 // Read file contents into buffer
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001373 fread(buf, fileLen, 1, fp);
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001374 VLOG << buf;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001375 free(buf);
1376 }
1377 fclose(fp);
1378 remove("/data/reslog.txt");
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001379 } else {
1380 errno = 0; // else debug is introducing error signals
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001381 VLOG << __func__ << ": can't open file";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001382 }
1383}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001384
1385/* This function tries to find a key within the hash table
1386 * In case of success, it will return a *pointer* to the hashed key.
1387 * In case of failure, it will return a *pointer* to NULL
1388 *
1389 * So, the caller must check '*result' to check for success/failure.
1390 *
1391 * The main idea is that the result can later be used directly in
1392 * calls to _resolv_cache_add or _resolv_cache_remove as the 'lookup'
1393 * parameter. This makes the code simpler and avoids re-searching
1394 * for the key position in the htable.
1395 *
1396 * The result of a lookup_p is only valid until you alter the hash
1397 * table.
1398 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001399static Entry** _cache_lookup_p(Cache* cache, Entry* key) {
1400 int index = key->hash % cache->max_entries;
1401 Entry** pnode = (Entry**) &cache->entries[index];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001402
1403 while (*pnode != NULL) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001404 Entry* node = *pnode;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001405
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001406 if (node == NULL) break;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001407
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001408 if (node->hash == key->hash && entry_equals(node, key)) break;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001409
1410 pnode = &node->hlink;
1411 }
1412 return pnode;
1413}
1414
1415/* Add a new entry to the hash table. 'lookup' must be the
1416 * result of an immediate previous failed _lookup_p() call
1417 * (i.e. with *lookup == NULL), and 'e' is the pointer to the
1418 * newly created entry
1419 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001420static void _cache_add_p(Cache* cache, Entry** lookup, Entry* e) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001421 *lookup = e;
1422 e->id = ++cache->last_id;
1423 entry_mru_add(e, &cache->mru_list);
1424 cache->num_entries += 1;
1425
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001426 VLOG << __func__ << ": entry " << e->id << " added (count=" << cache->num_entries << ")";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001427}
1428
1429/* Remove an existing entry from the hash table,
1430 * 'lookup' must be the result of an immediate previous
1431 * and succesful _lookup_p() call.
1432 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001433static void _cache_remove_p(Cache* cache, Entry** lookup) {
1434 Entry* e = *lookup;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001435
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001436 VLOG << __func__ << ": entry " << e->id << " removed (count=" << cache->num_entries - 1 << ")";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001437
1438 entry_mru_remove(e);
1439 *lookup = e->hlink;
1440 entry_free(e);
1441 cache->num_entries -= 1;
1442}
1443
1444/* Remove the oldest entry from the hash table.
1445 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001446static void _cache_remove_oldest(Cache* cache) {
1447 Entry* oldest = cache->mru_list.mru_prev;
1448 Entry** lookup = _cache_lookup_p(cache, oldest);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001449
1450 if (*lookup == NULL) { /* should not happen */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001451 VLOG << __func__ << ": OLDEST NOT IN HTABLE ?";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001452 return;
1453 }
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001454 VLOG << "Cache full - removing oldest";
1455 dump_query(oldest->query, oldest->querylen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001456 _cache_remove_p(cache, lookup);
1457}
1458
1459/* Remove all expired entries from the hash table.
1460 */
1461static void _cache_remove_expired(Cache* cache) {
1462 Entry* e;
1463 time_t now = _time_now();
1464
1465 for (e = cache->mru_list.mru_next; e != &cache->mru_list;) {
1466 // Entry is old, remove
1467 if (now >= e->expires) {
1468 Entry** lookup = _cache_lookup_p(cache, e);
1469 if (*lookup == NULL) { /* should not happen */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001470 VLOG << __func__ << ": ENTRY NOT IN HTABLE ?";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001471 return;
1472 }
1473 e = e->mru_next;
1474 _cache_remove_p(cache, lookup);
1475 } else {
1476 e = e->mru_next;
1477 }
1478 }
1479}
1480
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001481ResolvCacheStatus _resolv_cache_lookup(unsigned netid, const void* query, int querylen,
1482 void* answer, int answersize, int* answerlen) {
1483 Entry key[1];
1484 Entry** lookup;
1485 Entry* e;
1486 time_t now;
1487 Cache* cache;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001488
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001489 ResolvCacheStatus result = RESOLV_CACHE_NOTFOUND;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001490
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001491 VLOG << __func__ << ": lookup";
1492 dump_query((u_char*) query, querylen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001493
1494 /* we don't cache malformed queries */
1495 if (!entry_init_key(key, query, querylen)) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001496 VLOG << __func__ << ": unsupported query";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001497 return RESOLV_CACHE_UNSUPPORTED;
1498 }
1499 /* lookup cache */
1500 pthread_once(&_res_cache_once, _res_cache_init);
1501 pthread_mutex_lock(&_res_cache_list_lock);
1502
1503 cache = _find_named_cache_locked(netid);
1504 if (cache == NULL) {
1505 result = RESOLV_CACHE_UNSUPPORTED;
1506 goto Exit;
1507 }
1508
1509 /* see the description of _lookup_p to understand this.
1510 * the function always return a non-NULL pointer.
1511 */
1512 lookup = _cache_lookup_p(cache, key);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001513 e = *lookup;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001514
1515 if (e == NULL) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001516 VLOG << "NOT IN CACHE";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001517 // calling thread will wait if an outstanding request is found
1518 // that matching this query
1519 if (!_cache_check_pending_request_locked(&cache, key, netid) || cache == NULL) {
1520 goto Exit;
1521 } else {
1522 lookup = _cache_lookup_p(cache, key);
1523 e = *lookup;
1524 if (e == NULL) {
1525 goto Exit;
1526 }
1527 }
1528 }
1529
1530 now = _time_now();
1531
1532 /* remove stale entries here */
1533 if (now >= e->expires) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001534 VLOG << " NOT IN CACHE (STALE ENTRY " << *lookup << "DISCARDED)";
1535 dump_query(e->query, e->querylen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001536 _cache_remove_p(cache, lookup);
1537 goto Exit;
1538 }
1539
1540 *answerlen = e->answerlen;
1541 if (e->answerlen > answersize) {
1542 /* NOTE: we return UNSUPPORTED if the answer buffer is too short */
1543 result = RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001544 VLOG << " ANSWER TOO LONG";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001545 goto Exit;
1546 }
1547
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001548 memcpy(answer, e->answer, e->answerlen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001549
1550 /* bump up this entry to the top of the MRU list */
1551 if (e != cache->mru_list.mru_next) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001552 entry_mru_remove(e);
1553 entry_mru_add(e, &cache->mru_list);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001554 }
1555
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001556 VLOG << "FOUND IN CACHE entry=" << e;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001557 result = RESOLV_CACHE_FOUND;
1558
1559Exit:
1560 pthread_mutex_unlock(&_res_cache_list_lock);
1561 return result;
1562}
1563
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001564void _resolv_cache_add(unsigned netid, const void* query, int querylen, const void* answer,
1565 int answerlen) {
1566 Entry key[1];
1567 Entry* e;
1568 Entry** lookup;
1569 u_long ttl;
1570 Cache* cache = NULL;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001571
1572 /* don't assume that the query has already been cached
1573 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001574 if (!entry_init_key(key, query, querylen)) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001575 VLOG << __func__ << ": passed invalid query?";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001576 return;
1577 }
1578
1579 pthread_mutex_lock(&_res_cache_list_lock);
1580
1581 cache = _find_named_cache_locked(netid);
1582 if (cache == NULL) {
1583 goto Exit;
1584 }
1585
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001586 VLOG << __func__ << ": query:";
1587 dump_query((u_char*) query, querylen);
1588 dump_answer((u_char*) answer, answerlen);
1589 if (kDumpData) {
1590 VLOG << "answer:";
1591 dump_bytes((u_char*) answer, answerlen);
1592 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001593
1594 lookup = _cache_lookup_p(cache, key);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001595 e = *lookup;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001596
1597 if (e != NULL) { /* should not happen */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001598 VLOG << __func__ << ": ALREADY IN CACHE (" << e << ") ? IGNORING ADD";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001599 goto Exit;
1600 }
1601
1602 if (cache->num_entries >= cache->max_entries) {
1603 _cache_remove_expired(cache);
1604 if (cache->num_entries >= cache->max_entries) {
1605 _cache_remove_oldest(cache);
1606 }
1607 /* need to lookup again */
1608 lookup = _cache_lookup_p(cache, key);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001609 e = *lookup;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001610 if (e != NULL) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001611 VLOG << __func__ << ": ALREADY IN CACHE (" << e << ") ? IGNORING ADD";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001612 goto Exit;
1613 }
1614 }
1615
1616 ttl = answer_getTTL(answer, answerlen);
1617 if (ttl > 0) {
1618 e = entry_alloc(key, answer, answerlen);
1619 if (e != NULL) {
1620 e->expires = ttl + _time_now();
1621 _cache_add_p(cache, lookup, e);
1622 }
1623 }
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001624 cache_dump_mru(cache);
1625
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001626Exit:
1627 if (cache != NULL) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001628 _cache_notify_waiting_tid_locked(cache, key);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001629 }
1630 pthread_mutex_unlock(&_res_cache_list_lock);
1631}
1632
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001633// Head of the list of caches. Protected by _res_cache_list_lock.
1634static struct resolv_cache_info _res_cache_list;
1635
1636/* insert resolv_cache_info into the list of resolv_cache_infos */
1637static void _insert_cache_info_locked(struct resolv_cache_info* cache_info);
1638/* creates a resolv_cache_info */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001639static struct resolv_cache_info* _create_cache_info(void);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001640/* gets a resolv_cache_info associated with a network, or NULL if not found */
1641static struct resolv_cache_info* _find_cache_info_locked(unsigned netid);
1642/* look up the named cache, and creates one if needed */
1643static struct resolv_cache* _get_res_cache_for_net_locked(unsigned netid);
1644/* empty the named cache */
1645static void _flush_cache_for_net_locked(unsigned netid);
1646/* empty the nameservers set for the named cache */
1647static void _free_nameservers_locked(struct resolv_cache_info* cache_info);
1648/* return 1 if the provided list of name servers differs from the list of name servers
1649 * currently attached to the provided cache_info */
1650static int _resolv_is_nameservers_equal_locked(struct resolv_cache_info* cache_info,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001651 const char** servers, int numservers);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001652/* clears the stats samples contained withing the given cache_info */
1653static void _res_cache_clear_stats_locked(struct resolv_cache_info* cache_info);
1654
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001655static void _res_cache_init(void) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001656 memset(&_res_cache_list, 0, sizeof(_res_cache_list));
1657 pthread_mutex_init(&_res_cache_list_lock, NULL);
1658}
1659
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001660static struct resolv_cache* _get_res_cache_for_net_locked(unsigned netid) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001661 struct resolv_cache* cache = _find_named_cache_locked(netid);
1662 if (!cache) {
1663 struct resolv_cache_info* cache_info = _create_cache_info();
1664 if (cache_info) {
1665 cache = _resolv_cache_create();
1666 if (cache) {
1667 cache_info->cache = cache;
1668 cache_info->netid = netid;
1669 _insert_cache_info_locked(cache_info);
1670 } else {
1671 free(cache_info);
1672 }
1673 }
1674 }
1675 return cache;
1676}
1677
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001678void _resolv_flush_cache_for_net(unsigned netid) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001679 pthread_once(&_res_cache_once, _res_cache_init);
1680 pthread_mutex_lock(&_res_cache_list_lock);
1681
1682 _flush_cache_for_net_locked(netid);
1683
1684 pthread_mutex_unlock(&_res_cache_list_lock);
1685}
1686
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001687static void _flush_cache_for_net_locked(unsigned netid) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001688 struct resolv_cache* cache = _find_named_cache_locked(netid);
1689 if (cache) {
1690 _cache_flush_locked(cache);
1691 }
1692
1693 // Also clear the NS statistics.
1694 struct resolv_cache_info* cache_info = _find_cache_info_locked(netid);
1695 _res_cache_clear_stats_locked(cache_info);
1696}
1697
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001698void _resolv_delete_cache_for_net(unsigned netid) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001699 pthread_once(&_res_cache_once, _res_cache_init);
1700 pthread_mutex_lock(&_res_cache_list_lock);
1701
1702 struct resolv_cache_info* prev_cache_info = &_res_cache_list;
1703
1704 while (prev_cache_info->next) {
1705 struct resolv_cache_info* cache_info = prev_cache_info->next;
1706
1707 if (cache_info->netid == netid) {
1708 prev_cache_info->next = cache_info->next;
1709 _cache_flush_locked(cache_info->cache);
1710 free(cache_info->cache->entries);
1711 free(cache_info->cache);
1712 _free_nameservers_locked(cache_info);
1713 free(cache_info);
1714 break;
1715 }
1716
1717 prev_cache_info = prev_cache_info->next;
1718 }
1719
1720 pthread_mutex_unlock(&_res_cache_list_lock);
1721}
1722
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001723static struct resolv_cache_info* _create_cache_info(void) {
Bernie Innocenti9c575932018-09-07 21:10:25 +09001724 return (struct resolv_cache_info*) calloc(sizeof(struct resolv_cache_info), 1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001725}
1726
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001727static void _insert_cache_info_locked(struct resolv_cache_info* cache_info) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001728 struct resolv_cache_info* last;
Bernie Innocenti9c575932018-09-07 21:10:25 +09001729 for (last = &_res_cache_list; last->next; last = last->next) {}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001730 last->next = cache_info;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001731}
1732
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001733static struct resolv_cache* _find_named_cache_locked(unsigned netid) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001734 struct resolv_cache_info* info = _find_cache_info_locked(netid);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001735 if (info != NULL) return info->cache;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001736 return NULL;
1737}
1738
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001739static struct resolv_cache_info* _find_cache_info_locked(unsigned netid) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001740 struct resolv_cache_info* cache_info = _res_cache_list.next;
1741
1742 while (cache_info) {
1743 if (cache_info->netid == netid) {
1744 break;
1745 }
1746
1747 cache_info = cache_info->next;
1748 }
1749 return cache_info;
1750}
1751
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001752void _resolv_set_default_params(struct __res_params* params) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001753 params->sample_validity = NSSAMPLE_VALIDITY;
1754 params->success_threshold = SUCCESS_THRESHOLD;
1755 params->min_samples = 0;
1756 params->max_samples = 0;
1757 params->base_timeout_msec = 0; // 0 = legacy algorithm
1758}
1759
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001760int _resolv_set_nameservers_for_net(unsigned netid, const char** servers, unsigned numservers,
1761 const char* domains, const struct __res_params* params) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001762 char sbuf[NI_MAXSERV];
Bernie Innocenti9c575932018-09-07 21:10:25 +09001763 char* cp;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001764 int* offset;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001765 struct addrinfo* nsaddrinfo[MAXNS];
1766
1767 if (numservers > MAXNS) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001768 VLOG << __func__ << ": numservers=" << numservers << ", MAXNS=" << MAXNS;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001769 return E2BIG;
1770 }
1771
1772 // Parse the addresses before actually locking or changing any state, in case there is an error.
1773 // As a side effect this also reduces the time the lock is kept.
1774 struct addrinfo hints = {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001775 .ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM, .ai_flags = AI_NUMERICHOST};
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001776 snprintf(sbuf, sizeof(sbuf), "%u", NAMESERVER_PORT);
1777 for (unsigned i = 0; i < numservers; i++) {
1778 // The addrinfo structures allocated here are freed in _free_nameservers_locked().
1779 int rt = getaddrinfo(servers[i], sbuf, &hints, &nsaddrinfo[i]);
1780 if (rt != 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001781 for (unsigned j = 0; j < i; j++) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001782 freeaddrinfo(nsaddrinfo[j]);
1783 nsaddrinfo[j] = NULL;
1784 }
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001785 VLOG << __func__ << ": getaddrinfo(" << servers[i] << ") = " << gai_strerror(rt);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001786 return EINVAL;
1787 }
1788 }
1789
1790 pthread_once(&_res_cache_once, _res_cache_init);
1791 pthread_mutex_lock(&_res_cache_list_lock);
1792
1793 // creates the cache if not created
1794 _get_res_cache_for_net_locked(netid);
1795
1796 struct resolv_cache_info* cache_info = _find_cache_info_locked(netid);
1797
1798 if (cache_info != NULL) {
1799 uint8_t old_max_samples = cache_info->params.max_samples;
1800 if (params != NULL) {
1801 cache_info->params = *params;
1802 } else {
1803 _resolv_set_default_params(&cache_info->params);
1804 }
1805
1806 if (!_resolv_is_nameservers_equal_locked(cache_info, servers, numservers)) {
1807 // free current before adding new
1808 _free_nameservers_locked(cache_info);
1809 unsigned i;
1810 for (i = 0; i < numservers; i++) {
1811 cache_info->nsaddrinfo[i] = nsaddrinfo[i];
1812 cache_info->nameservers[i] = strdup(servers[i]);
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001813 VLOG << __func__ << ": netid = " << netid << ", addr = " << servers[i];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001814 }
1815 cache_info->nscount = numservers;
1816
1817 // Clear the NS statistics because the mapping to nameservers might have changed.
1818 _res_cache_clear_stats_locked(cache_info);
1819
1820 // increment the revision id to ensure that sample state is not written back if the
1821 // servers change; in theory it would suffice to do so only if the servers or
1822 // max_samples actually change, in practice the overhead of checking is higher than the
1823 // cost, and overflows are unlikely
1824 ++cache_info->revision_id;
1825 } else if (cache_info->params.max_samples != old_max_samples) {
1826 // If the maximum number of samples changes, the overhead of keeping the most recent
1827 // samples around is not considered worth the effort, so they are cleared instead. All
1828 // other parameters do not affect shared state: Changing these parameters does not
1829 // invalidate the samples, as they only affect aggregation and the conditions under
1830 // which servers are considered usable.
1831 _res_cache_clear_stats_locked(cache_info);
1832 ++cache_info->revision_id;
1833 }
1834
1835 // Always update the search paths, since determining whether they actually changed is
1836 // complex due to the zero-padding, and probably not worth the effort. Cache-flushing
1837 // however is not // necessary, since the stored cache entries do contain the domain, not
1838 // just the host name.
1839 // code moved from res_init.c, load_domain_search_list
1840 strlcpy(cache_info->defdname, domains, sizeof(cache_info->defdname));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001841 if ((cp = strchr(cache_info->defdname, '\n')) != NULL) *cp = '\0';
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001842
1843 cp = cache_info->defdname;
1844 offset = cache_info->dnsrch_offset;
1845 while (offset < cache_info->dnsrch_offset + MAXDNSRCH) {
1846 while (*cp == ' ' || *cp == '\t') /* skip leading white space */
1847 cp++;
1848 if (*cp == '\0') /* stop if nothing more to do */
1849 break;
1850 *offset++ = cp - cache_info->defdname; /* record this search domain */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001851 while (*cp) { /* zero-terminate it */
1852 if (*cp == ' ' || *cp == '\t') {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001853 *cp++ = '\0';
1854 break;
1855 }
1856 cp++;
1857 }
1858 }
1859 *offset = -1; /* cache_info->dnsrch_offset has MAXDNSRCH+1 items */
1860 }
1861
1862 pthread_mutex_unlock(&_res_cache_list_lock);
1863 return 0;
1864}
1865
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001866static int _resolv_is_nameservers_equal_locked(struct resolv_cache_info* cache_info,
1867 const char** servers, int numservers) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001868 if (cache_info->nscount != numservers) {
1869 return 0;
1870 }
1871
1872 // Compare each name server against current name servers.
1873 // TODO: this is incorrect if the list of current or previous nameservers
1874 // contains duplicates. This does not really matter because the framework
1875 // filters out duplicates, but we should probably fix it. It's also
1876 // insensitive to the order of the nameservers; we should probably fix that
1877 // too.
1878 for (int i = 0; i < numservers; i++) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001879 for (int j = 0;; j++) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001880 if (j >= numservers) {
1881 return 0;
1882 }
1883 if (strcmp(cache_info->nameservers[i], servers[j]) == 0) {
1884 break;
1885 }
1886 }
1887 }
1888
1889 return 1;
1890}
1891
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001892static void _free_nameservers_locked(struct resolv_cache_info* cache_info) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001893 int i;
1894 for (i = 0; i < cache_info->nscount; i++) {
1895 free(cache_info->nameservers[i]);
1896 cache_info->nameservers[i] = NULL;
1897 if (cache_info->nsaddrinfo[i] != NULL) {
1898 freeaddrinfo(cache_info->nsaddrinfo[i]);
1899 cache_info->nsaddrinfo[i] = NULL;
1900 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001901 cache_info->nsstats[i].sample_count = cache_info->nsstats[i].sample_next = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001902 }
1903 cache_info->nscount = 0;
1904 _res_cache_clear_stats_locked(cache_info);
1905 ++cache_info->revision_id;
1906}
1907
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001908void _resolv_populate_res_for_net(res_state statp) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001909 if (statp == NULL) {
1910 return;
1911 }
1912
1913 pthread_once(&_res_cache_once, _res_cache_init);
1914 pthread_mutex_lock(&_res_cache_list_lock);
1915
1916 struct resolv_cache_info* info = _find_cache_info_locked(statp->netid);
1917 if (info != NULL) {
1918 int nserv;
1919 struct addrinfo* ai;
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001920 VLOG << __func__ << ": " << statp->netid;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001921 for (nserv = 0; nserv < MAXNS; nserv++) {
1922 ai = info->nsaddrinfo[nserv];
1923 if (ai == NULL) {
1924 break;
1925 }
1926
1927 if ((size_t) ai->ai_addrlen <= sizeof(statp->_u._ext.ext->nsaddrs[0])) {
1928 if (statp->_u._ext.ext != NULL) {
1929 memcpy(&statp->_u._ext.ext->nsaddrs[nserv], ai->ai_addr, ai->ai_addrlen);
1930 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
1931 } else {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001932 if ((size_t) ai->ai_addrlen <= sizeof(statp->nsaddr_list[0])) {
1933 memcpy(&statp->nsaddr_list[nserv], ai->ai_addr, ai->ai_addrlen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001934 } else {
1935 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
1936 }
1937 }
1938 } else {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001939 VLOG << __func__ << ": found too long addrlen";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001940 }
1941 }
1942 statp->nscount = nserv;
1943 // now do search domains. Note that we cache the offsets as this code runs alot
1944 // but the setting/offset-computer only runs when set/changed
1945 // WARNING: Don't use str*cpy() here, this string contains zeroes.
1946 memcpy(statp->defdname, info->defdname, sizeof(statp->defdname));
Bernie Innocenti9c575932018-09-07 21:10:25 +09001947 char** pp = statp->dnsrch;
1948 int* p = info->dnsrch_offset;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001949 while (pp < statp->dnsrch + MAXDNSRCH && *p != -1) {
1950 *pp++ = &statp->defdname[0] + *p++;
1951 }
1952 }
1953 pthread_mutex_unlock(&_res_cache_list_lock);
1954}
1955
1956/* Resolver reachability statistics. */
1957
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001958static void _res_cache_add_stats_sample_locked(struct __res_stats* stats,
1959 const struct __res_sample* sample, int max_samples) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001960 // Note: This function expects max_samples > 0, otherwise a (harmless) modification of the
1961 // allocated but supposedly unused memory for samples[0] will happen
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001962 VLOG << __func__ << ": adding sample to stats, next = " << stats->sample_next
1963 << ", count = " << stats->sample_count;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001964 stats->samples[stats->sample_next] = *sample;
1965 if (stats->sample_count < max_samples) {
1966 ++stats->sample_count;
1967 }
1968 if (++stats->sample_next >= max_samples) {
1969 stats->sample_next = 0;
1970 }
1971}
1972
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001973static void _res_cache_clear_stats_locked(struct resolv_cache_info* cache_info) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001974 if (cache_info) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001975 for (int i = 0; i < MAXNS; ++i) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001976 cache_info->nsstats->sample_count = cache_info->nsstats->sample_next = 0;
1977 }
1978 }
1979}
1980
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001981int android_net_res_stats_get_info_for_net(unsigned netid, int* nscount,
1982 struct sockaddr_storage servers[MAXNS], int* dcount,
1983 char domains[MAXDNSRCH][MAXDNSRCHPATH],
1984 struct __res_params* params,
1985 struct __res_stats stats[MAXNS]) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001986 int revision_id = -1;
1987 pthread_mutex_lock(&_res_cache_list_lock);
1988
1989 struct resolv_cache_info* info = _find_cache_info_locked(netid);
1990 if (info) {
1991 if (info->nscount > MAXNS) {
1992 pthread_mutex_unlock(&_res_cache_list_lock);
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001993 VLOG << __func__ << ": nscount " << info->nscount << " > MAXNS " << MAXNS;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001994 errno = EFAULT;
1995 return -1;
1996 }
1997 int i;
1998 for (i = 0; i < info->nscount; i++) {
1999 // Verify that the following assumptions are held, failure indicates corruption:
2000 // - getaddrinfo() may never return a sockaddr > sockaddr_storage
2001 // - all addresses are valid
2002 // - there is only one address per addrinfo thanks to numeric resolution
2003 int addrlen = info->nsaddrinfo[i]->ai_addrlen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09002004 if (addrlen < (int) sizeof(struct sockaddr) || addrlen > (int) sizeof(servers[0])) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09002005 pthread_mutex_unlock(&_res_cache_list_lock);
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09002006 VLOG << __func__ << ": nsaddrinfo[" << i << "].ai_addrlen == " << addrlen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09002007 errno = EMSGSIZE;
2008 return -1;
2009 }
2010 if (info->nsaddrinfo[i]->ai_addr == NULL) {
2011 pthread_mutex_unlock(&_res_cache_list_lock);
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09002012 VLOG << __func__ << ": nsaddrinfo[" << i << "].ai_addr == NULL";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09002013 errno = ENOENT;
2014 return -1;
2015 }
2016 if (info->nsaddrinfo[i]->ai_next != NULL) {
2017 pthread_mutex_unlock(&_res_cache_list_lock);
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09002018 VLOG << __func__ << ": nsaddrinfo[" << i << "].ai_next != NULL";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09002019 errno = ENOTUNIQ;
2020 return -1;
2021 }
2022 }
2023 *nscount = info->nscount;
2024 for (i = 0; i < info->nscount; i++) {
2025 memcpy(&servers[i], info->nsaddrinfo[i]->ai_addr, info->nsaddrinfo[i]->ai_addrlen);
2026 stats[i] = info->nsstats[i];
2027 }
2028 for (i = 0; i < MAXDNSRCH; i++) {
2029 const char* cur_domain = info->defdname + info->dnsrch_offset[i];
2030 // dnsrch_offset[i] can either be -1 or point to an empty string to indicate the end
2031 // of the search offsets. Checking for < 0 is not strictly necessary, but safer.
2032 // TODO: Pass in a search domain array instead of a string to
2033 // _resolv_set_nameservers_for_net() and make this double check unnecessary.
2034 if (info->dnsrch_offset[i] < 0 ||
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09002035 ((size_t) info->dnsrch_offset[i]) >= sizeof(info->defdname) || !cur_domain[0]) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09002036 break;
2037 }
2038 strlcpy(domains[i], cur_domain, MAXDNSRCHPATH);
2039 }
2040 *dcount = i;
2041 *params = info->params;
2042 revision_id = info->revision_id;
2043 }
2044
2045 pthread_mutex_unlock(&_res_cache_list_lock);
2046 return revision_id;
2047}
2048
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09002049int _resolv_cache_get_resolver_stats(unsigned netid, struct __res_params* params,
2050 struct __res_stats stats[MAXNS]) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09002051 int revision_id = -1;
2052 pthread_mutex_lock(&_res_cache_list_lock);
2053
2054 struct resolv_cache_info* info = _find_cache_info_locked(netid);
2055 if (info) {
2056 memcpy(stats, info->nsstats, sizeof(info->nsstats));
2057 *params = info->params;
2058 revision_id = info->revision_id;
2059 }
2060
2061 pthread_mutex_unlock(&_res_cache_list_lock);
2062 return revision_id;
2063}
2064
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09002065void _resolv_cache_add_resolver_stats_sample(unsigned netid, int revision_id, int ns,
2066 const struct __res_sample* sample, int max_samples) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09002067 if (max_samples <= 0) return;
2068
2069 pthread_mutex_lock(&_res_cache_list_lock);
2070
2071 struct resolv_cache_info* info = _find_cache_info_locked(netid);
2072
2073 if (info && info->revision_id == revision_id) {
2074 _res_cache_add_stats_sample_locked(&info->nsstats[ns], sample, max_samples);
2075 }
2076
2077 pthread_mutex_unlock(&_res_cache_list_lock);
2078}