blob: 60a60dfcb47b51539a8f03a11a3c30183b30c226 [file] [log] [blame]
Bernie Innocenti55864192018-08-30 04:05:20 +09001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090029// NOTE: verbose logging MUST NOT be left enabled in production binaries.
30// It floods logs at high rate, and can leak privacy-sensitive information.
31constexpr bool kVerboseLogging = false;
32constexpr bool kDumpData = false;
33#define LOG_TAG "res_cache"
34
Bernie Innocentif89b3512018-08-30 07:34:37 +090035#include <pthread.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090036#include <resolv.h>
37#include <stdarg.h>
38#include <stdio.h>
39#include <stdlib.h>
40#include <string.h>
41#include <time.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090042
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090043#include <arpa/inet.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090044#include <arpa/nameser.h>
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090045#include <errno.h>
46#include <linux/if.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090047#include <net/if.h>
48#include <netdb.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090049
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090050#include <android-base/logging.h>
Bernie Innocentif89b3512018-08-30 07:34:37 +090051
Bernie Innocenti189eb502018-10-01 23:10:18 +090052#include "netd_resolv/resolv.h"
53#include "res_state_ext.h"
Bernie Innocentif89b3512018-08-30 07:34:37 +090054#include "resolv_cache.h"
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090055#include "resolv_private.h"
Bernie Innocenti55864192018-08-30 04:05:20 +090056
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090057#define VLOG if (!kVerboseLogging) {} else LOG(INFO)
58
59#ifndef RESOLV_ALLOW_VERBOSE_LOGGING
60static_assert(kVerboseLogging == false && kDumpData == false,
61 "Verbose logging floods logs at high-rate and exposes privacy-sensitive information. "
62 "Do not enable in release builds.");
63#endif
Bernie Innocenti55864192018-08-30 04:05:20 +090064
65/* This code implements a small and *simple* DNS resolver cache.
66 *
67 * It is only used to cache DNS answers for a time defined by the smallest TTL
68 * among the answer records in order to reduce DNS traffic. It is not supposed
69 * to be a full DNS cache, since we plan to implement that in the future in a
70 * dedicated process running on the system.
71 *
72 * Note that its design is kept simple very intentionally, i.e.:
73 *
74 * - it takes raw DNS query packet data as input, and returns raw DNS
75 * answer packet data as output
76 *
77 * (this means that two similar queries that encode the DNS name
78 * differently will be treated distinctly).
79 *
80 * the smallest TTL value among the answer records are used as the time
81 * to keep an answer in the cache.
82 *
83 * this is bad, but we absolutely want to avoid parsing the answer packets
84 * (and should be solved by the later full DNS cache process).
85 *
86 * - the implementation is just a (query-data) => (answer-data) hash table
87 * with a trivial least-recently-used expiration policy.
88 *
89 * Doing this keeps the code simple and avoids to deal with a lot of things
90 * that a full DNS cache is expected to do.
91 *
92 * The API is also very simple:
93 *
94 * - the client calls _resolv_cache_get() to obtain a handle to the cache.
95 * this will initialize the cache on first usage. the result can be NULL
96 * if the cache is disabled.
97 *
98 * - the client calls _resolv_cache_lookup() before performing a query
99 *
100 * if the function returns RESOLV_CACHE_FOUND, a copy of the answer data
101 * has been copied into the client-provided answer buffer.
102 *
103 * if the function returns RESOLV_CACHE_NOTFOUND, the client should perform
104 * a request normally, *then* call _resolv_cache_add() to add the received
105 * answer to the cache.
106 *
107 * if the function returns RESOLV_CACHE_UNSUPPORTED, the client should
108 * perform a request normally, and *not* call _resolv_cache_add()
109 *
110 * note that RESOLV_CACHE_UNSUPPORTED is also returned if the answer buffer
111 * is too short to accomodate the cached result.
112 */
113
114/* default number of entries kept in the cache. This value has been
115 * determined by browsing through various sites and counting the number
116 * of corresponding requests. Keep in mind that our framework is currently
117 * performing two requests per name lookup (one for IPv4, the other for IPv6)
118 *
119 * www.google.com 4
120 * www.ysearch.com 6
121 * www.amazon.com 8
122 * www.nytimes.com 22
123 * www.espn.com 28
124 * www.msn.com 28
125 * www.lemonde.fr 35
126 *
127 * (determined in 2009-2-17 from Paris, France, results may vary depending
128 * on location)
129 *
130 * most high-level websites use lots of media/ad servers with different names
131 * but these are generally reused when browsing through the site.
132 *
133 * As such, a value of 64 should be relatively comfortable at the moment.
134 *
135 * ******************************************
136 * * NOTE - this has changed.
137 * * 1) we've added IPv6 support so each dns query results in 2 responses
138 * * 2) we've made this a system-wide cache, so the cost is less (it's not
139 * * duplicated in each process) and the need is greater (more processes
140 * * making different requests).
141 * * Upping by 2x for IPv6
142 * * Upping by another 5x for the centralized nature
143 * *****************************************
144 */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900145#define CONFIG_MAX_ENTRIES (64 * 2 * 5)
Bernie Innocenti55864192018-08-30 04:05:20 +0900146
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900147/** BOUNDED BUFFER FORMATTING **/
Bernie Innocenti55864192018-08-30 04:05:20 +0900148
149/* technical note:
150 *
151 * the following debugging routines are used to append data to a bounded
152 * buffer they take two parameters that are:
153 *
154 * - p : a pointer to the current cursor position in the buffer
155 * this value is initially set to the buffer's address.
156 *
157 * - end : the address of the buffer's limit, i.e. of the first byte
158 * after the buffer. this address should never be touched.
159 *
160 * IMPORTANT: it is assumed that end > buffer_address, i.e.
161 * that the buffer is at least one byte.
162 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900163 * the bprint_x() functions return the new value of 'p' after the data
Bernie Innocenti55864192018-08-30 04:05:20 +0900164 * has been appended, and also ensure the following:
165 *
166 * - the returned value will never be strictly greater than 'end'
167 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900168 * - a return value equal to 'end' means that truncation occurred
Bernie Innocenti55864192018-08-30 04:05:20 +0900169 * (in which case, end[-1] will be set to 0)
170 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900171 * - after returning from a bprint_x() function, the content of the buffer
Bernie Innocenti55864192018-08-30 04:05:20 +0900172 * is always 0-terminated, even in the event of truncation.
173 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900174 * these conventions allow you to call bprint_x() functions multiple times and
Bernie Innocenti55864192018-08-30 04:05:20 +0900175 * only check for truncation at the end of the sequence, as in:
176 *
177 * char buff[1000], *p = buff, *end = p + sizeof(buff);
178 *
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900179 * p = bprint_c(p, end, '"');
180 * p = bprint_s(p, end, my_string);
181 * p = bprint_c(p, end, '"');
Bernie Innocenti55864192018-08-30 04:05:20 +0900182 *
183 * if (p >= end) {
184 * // buffer was too small
185 * }
186 *
187 * printf( "%s", buff );
188 */
189
Bernie Innocenti1fbca5c2018-10-01 20:46:20 +0900190/* Defaults used for initializing __res_params */
191
192// If successes * 100 / total_samples is less than this value, the server is considered failing
193#define SUCCESS_THRESHOLD 75
194// Sample validity in seconds. Set to -1 to disable skipping failing servers.
195#define NSSAMPLE_VALIDITY 1800
196
Bernie Innocenti55864192018-08-30 04:05:20 +0900197/* add a char to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900198static char* bprint_c(char* p, char* end, int c) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900199 if (p < end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900200 if (p + 1 == end)
Bernie Innocenti55864192018-08-30 04:05:20 +0900201 *p++ = 0;
202 else {
203 *p++ = (char) c;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900204 *p = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900205 }
206 }
207 return p;
208}
209
210/* add a sequence of bytes to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900211static char* bprint_b(char* p, char* end, const char* buf, int len) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900212 int avail = end - p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900213
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900214 if (avail <= 0 || len <= 0) return p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900215
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900216 if (avail > len) avail = len;
Bernie Innocenti55864192018-08-30 04:05:20 +0900217
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900218 memcpy(p, buf, avail);
Bernie Innocenti55864192018-08-30 04:05:20 +0900219 p += avail;
220
221 if (p < end)
222 p[0] = 0;
223 else
224 end[-1] = 0;
225
226 return p;
227}
228
229/* add a string to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900230static char* bprint_s(char* p, char* end, const char* str) {
231 return bprint_b(p, end, str, strlen(str));
Bernie Innocenti55864192018-08-30 04:05:20 +0900232}
233
234/* add a formatted string to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900235static char* bprint(char* p, char* end, const char* format, ...) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900236 int avail, n;
237 va_list args;
Bernie Innocenti55864192018-08-30 04:05:20 +0900238
239 avail = end - p;
240
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900241 if (avail <= 0) return p;
Bernie Innocenti55864192018-08-30 04:05:20 +0900242
243 va_start(args, format);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900244 n = vsnprintf(p, avail, format, args);
Bernie Innocenti55864192018-08-30 04:05:20 +0900245 va_end(args);
246
247 /* certain C libraries return -1 in case of truncation */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900248 if (n < 0 || n > avail) n = avail;
Bernie Innocenti55864192018-08-30 04:05:20 +0900249
250 p += n;
251 /* certain C libraries do not zero-terminate in case of truncation */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900252 if (p == end) p[-1] = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900253
254 return p;
255}
256
257/* add a hex value to a bounded buffer, up to 8 digits */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900258static char* bprint_hex(char* p, char* end, unsigned value, int numDigits) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900259 char text[sizeof(unsigned) * 2];
260 int nn = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900261
262 while (numDigits-- > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900263 text[nn++] = "0123456789abcdef"[(value >> (numDigits * 4)) & 15];
Bernie Innocenti55864192018-08-30 04:05:20 +0900264 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900265 return bprint_b(p, end, text, nn);
Bernie Innocenti55864192018-08-30 04:05:20 +0900266}
267
268/* add the hexadecimal dump of some memory area to a bounded buffer */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900269static char* bprint_hexdump(char* p, char* end, const uint8_t* data, int datalen) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900270 int lineSize = 16;
Bernie Innocenti55864192018-08-30 04:05:20 +0900271
272 while (datalen > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900273 int avail = datalen;
274 int nn;
Bernie Innocenti55864192018-08-30 04:05:20 +0900275
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900276 if (avail > lineSize) avail = lineSize;
Bernie Innocenti55864192018-08-30 04:05:20 +0900277
278 for (nn = 0; nn < avail; nn++) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900279 if (nn > 0) p = bprint_c(p, end, ' ');
280 p = bprint_hex(p, end, data[nn], 2);
Bernie Innocenti55864192018-08-30 04:05:20 +0900281 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900282 for (; nn < lineSize; nn++) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900283 p = bprint_s(p, end, " ");
Bernie Innocenti55864192018-08-30 04:05:20 +0900284 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900285 p = bprint_s(p, end, " ");
Bernie Innocenti55864192018-08-30 04:05:20 +0900286
287 for (nn = 0; nn < avail; nn++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900288 int c = data[nn];
Bernie Innocenti55864192018-08-30 04:05:20 +0900289
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900290 if (c < 32 || c > 127) c = '.';
Bernie Innocenti55864192018-08-30 04:05:20 +0900291
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900292 p = bprint_c(p, end, c);
Bernie Innocenti55864192018-08-30 04:05:20 +0900293 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900294 p = bprint_c(p, end, '\n');
Bernie Innocenti55864192018-08-30 04:05:20 +0900295
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900296 data += avail;
Bernie Innocenti55864192018-08-30 04:05:20 +0900297 datalen -= avail;
298 }
299 return p;
300}
301
302/* dump the content of a query of packet to the log */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900303static void dump_bytes(const uint8_t* base, int len) {
304 if (!kDumpData) return;
Bernie Innocenti55864192018-08-30 04:05:20 +0900305
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900306 char buff[1024];
307 char *p = buff, *end = p + sizeof(buff);
308
309 p = bprint_hexdump(p, end, base, len);
310 VLOG << buff;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900311}
Bernie Innocenti55864192018-08-30 04:05:20 +0900312
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900313static time_t _time_now(void) {
314 struct timeval tv;
Bernie Innocenti55864192018-08-30 04:05:20 +0900315
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900316 gettimeofday(&tv, NULL);
Bernie Innocenti55864192018-08-30 04:05:20 +0900317 return tv.tv_sec;
318}
319
320/* reminder: the general format of a DNS packet is the following:
321 *
322 * HEADER (12 bytes)
323 * QUESTION (variable)
324 * ANSWER (variable)
325 * AUTHORITY (variable)
326 * ADDITIONNAL (variable)
327 *
328 * the HEADER is made of:
329 *
330 * ID : 16 : 16-bit unique query identification field
331 *
332 * QR : 1 : set to 0 for queries, and 1 for responses
333 * Opcode : 4 : set to 0 for queries
334 * AA : 1 : set to 0 for queries
335 * TC : 1 : truncation flag, will be set to 0 in queries
336 * RD : 1 : recursion desired
337 *
338 * RA : 1 : recursion available (0 in queries)
339 * Z : 3 : three reserved zero bits
340 * RCODE : 4 : response code (always 0=NOERROR in queries)
341 *
342 * QDCount: 16 : question count
343 * ANCount: 16 : Answer count (0 in queries)
344 * NSCount: 16: Authority Record count (0 in queries)
345 * ARCount: 16: Additionnal Record count (0 in queries)
346 *
347 * the QUESTION is made of QDCount Question Record (QRs)
348 * the ANSWER is made of ANCount RRs
349 * the AUTHORITY is made of NSCount RRs
350 * the ADDITIONNAL is made of ARCount RRs
351 *
352 * Each Question Record (QR) is made of:
353 *
354 * QNAME : variable : Query DNS NAME
355 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
356 * CLASS : 16 : class of query (IN=1)
357 *
358 * Each Resource Record (RR) is made of:
359 *
360 * NAME : variable : DNS NAME
361 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
362 * CLASS : 16 : class of query (IN=1)
363 * TTL : 32 : seconds to cache this RR (0=none)
364 * RDLENGTH: 16 : size of RDDATA in bytes
365 * RDDATA : variable : RR data (depends on TYPE)
366 *
367 * Each QNAME contains a domain name encoded as a sequence of 'labels'
368 * terminated by a zero. Each label has the following format:
369 *
370 * LEN : 8 : lenght of label (MUST be < 64)
371 * NAME : 8*LEN : label length (must exclude dots)
372 *
373 * A value of 0 in the encoding is interpreted as the 'root' domain and
374 * terminates the encoding. So 'www.android.com' will be encoded as:
375 *
376 * <3>www<7>android<3>com<0>
377 *
378 * Where <n> represents the byte with value 'n'
379 *
380 * Each NAME reflects the QNAME of the question, but has a slightly more
381 * complex encoding in order to provide message compression. This is achieved
382 * by using a 2-byte pointer, with format:
383 *
384 * TYPE : 2 : 0b11 to indicate a pointer, 0b01 and 0b10 are reserved
385 * OFFSET : 14 : offset to another part of the DNS packet
386 *
387 * The offset is relative to the start of the DNS packet and must point
388 * A pointer terminates the encoding.
389 *
390 * The NAME can be encoded in one of the following formats:
391 *
392 * - a sequence of simple labels terminated by 0 (like QNAMEs)
393 * - a single pointer
394 * - a sequence of simple labels terminated by a pointer
395 *
396 * A pointer shall always point to either a pointer of a sequence of
397 * labels (which can themselves be terminated by either a 0 or a pointer)
398 *
399 * The expanded length of a given domain name should not exceed 255 bytes.
400 *
401 * NOTE: we don't parse the answer packets, so don't need to deal with NAME
402 * records, only QNAMEs.
403 */
404
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900405#define DNS_HEADER_SIZE 12
Bernie Innocenti55864192018-08-30 04:05:20 +0900406
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900407#define DNS_TYPE_A "\00\01" /* big-endian decimal 1 */
408#define DNS_TYPE_PTR "\00\014" /* big-endian decimal 12 */
409#define DNS_TYPE_MX "\00\017" /* big-endian decimal 15 */
410#define DNS_TYPE_AAAA "\00\034" /* big-endian decimal 28 */
411#define DNS_TYPE_ALL "\00\0377" /* big-endian decimal 255 */
Bernie Innocenti55864192018-08-30 04:05:20 +0900412
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900413#define DNS_CLASS_IN "\00\01" /* big-endian decimal 1 */
Bernie Innocenti55864192018-08-30 04:05:20 +0900414
415typedef struct {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900416 const uint8_t* base;
417 const uint8_t* end;
418 const uint8_t* cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900419} DnsPacket;
420
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900421static void _dnsPacket_init(DnsPacket* packet, const uint8_t* buff, int bufflen) {
422 packet->base = buff;
423 packet->end = buff + bufflen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900424 packet->cursor = buff;
425}
426
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900427static void _dnsPacket_rewind(DnsPacket* packet) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900428 packet->cursor = packet->base;
429}
430
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900431static void _dnsPacket_skip(DnsPacket* packet, int count) {
432 const uint8_t* p = packet->cursor + count;
Bernie Innocenti55864192018-08-30 04:05:20 +0900433
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900434 if (p > packet->end) p = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900435
436 packet->cursor = p;
437}
438
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900439static int _dnsPacket_readInt16(DnsPacket* packet) {
440 const uint8_t* p = packet->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900441
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900442 if (p + 2 > packet->end) return -1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900443
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900444 packet->cursor = p + 2;
445 return (p[0] << 8) | p[1];
Bernie Innocenti55864192018-08-30 04:05:20 +0900446}
447
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900448/** QUERY CHECKING **/
Bernie Innocenti55864192018-08-30 04:05:20 +0900449
450/* check bytes in a dns packet. returns 1 on success, 0 on failure.
451 * the cursor is only advanced in the case of success
452 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900453static int _dnsPacket_checkBytes(DnsPacket* packet, int numBytes, const void* bytes) {
454 const uint8_t* p = packet->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900455
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900456 if (p + numBytes > packet->end) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900457
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900458 if (memcmp(p, bytes, numBytes) != 0) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900459
460 packet->cursor = p + numBytes;
461 return 1;
462}
463
464/* parse and skip a given QNAME stored in a query packet,
465 * from the current cursor position. returns 1 on success,
466 * or 0 for malformed data.
467 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900468static int _dnsPacket_checkQName(DnsPacket* packet) {
469 const uint8_t* p = packet->cursor;
470 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900471
472 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900473 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900474
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900475 if (p >= end) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900476
477 c = *p++;
478
479 if (c == 0) {
480 packet->cursor = p;
481 return 1;
482 }
483
484 /* we don't expect label compression in QNAMEs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900485 if (c >= 64) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900486
487 p += c;
488 /* we rely on the bound check at the start
489 * of the loop here */
490 }
491 /* malformed data */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900492 VLOG << "malformed QNAME";
Bernie Innocenti55864192018-08-30 04:05:20 +0900493 return 0;
494}
495
496/* parse and skip a given QR stored in a packet.
497 * returns 1 on success, and 0 on failure
498 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900499static int _dnsPacket_checkQR(DnsPacket* packet) {
500 if (!_dnsPacket_checkQName(packet)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900501
502 /* TYPE must be one of the things we support */
503 if (!_dnsPacket_checkBytes(packet, 2, DNS_TYPE_A) &&
504 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_PTR) &&
505 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_MX) &&
506 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_AAAA) &&
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900507 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_ALL)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900508 VLOG << "unsupported TYPE";
Bernie Innocenti55864192018-08-30 04:05:20 +0900509 return 0;
510 }
511 /* CLASS must be IN */
512 if (!_dnsPacket_checkBytes(packet, 2, DNS_CLASS_IN)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900513 VLOG << "unsupported CLASS";
Bernie Innocenti55864192018-08-30 04:05:20 +0900514 return 0;
515 }
516
517 return 1;
518}
519
520/* check the header of a DNS Query packet, return 1 if it is one
521 * type of query we can cache, or 0 otherwise
522 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900523static int _dnsPacket_checkQuery(DnsPacket* packet) {
524 const uint8_t* p = packet->base;
525 int qdCount, anCount, dnCount, arCount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900526
527 if (p + DNS_HEADER_SIZE > packet->end) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900528 VLOG << "query packet too small";
Bernie Innocenti55864192018-08-30 04:05:20 +0900529 return 0;
530 }
531
532 /* QR must be set to 0, opcode must be 0 and AA must be 0 */
533 /* RA, Z, and RCODE must be 0 */
534 if ((p[2] & 0xFC) != 0 || (p[3] & 0xCF) != 0) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900535 VLOG << "query packet flags unsupported";
Bernie Innocenti55864192018-08-30 04:05:20 +0900536 return 0;
537 }
538
539 /* Note that we ignore the TC, RD, CD, and AD bits here for the
540 * following reasons:
541 *
542 * - there is no point for a query packet sent to a server
543 * to have the TC bit set, but the implementation might
544 * set the bit in the query buffer for its own needs
545 * between a _resolv_cache_lookup and a
546 * _resolv_cache_add. We should not freak out if this
547 * is the case.
548 *
549 * - we consider that the result from a query might depend on
550 * the RD, AD, and CD bits, so these bits
551 * should be used to differentiate cached result.
552 *
553 * this implies that these bits are checked when hashing or
554 * comparing query packets, but not TC
555 */
556
557 /* ANCOUNT, DNCOUNT and ARCOUNT must be 0 */
558 qdCount = (p[4] << 8) | p[5];
559 anCount = (p[6] << 8) | p[7];
560 dnCount = (p[8] << 8) | p[9];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900561 arCount = (p[10] << 8) | p[11];
Bernie Innocenti55864192018-08-30 04:05:20 +0900562
563 if (anCount != 0 || dnCount != 0 || arCount > 1) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900564 VLOG << "query packet contains non-query records";
Bernie Innocenti55864192018-08-30 04:05:20 +0900565 return 0;
566 }
567
568 if (qdCount == 0) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900569 VLOG << "query packet doesn't contain query record";
Bernie Innocenti55864192018-08-30 04:05:20 +0900570 return 0;
571 }
572
573 /* Check QDCOUNT QRs */
574 packet->cursor = p + DNS_HEADER_SIZE;
575
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900576 for (; qdCount > 0; qdCount--)
577 if (!_dnsPacket_checkQR(packet)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900578
579 return 1;
580}
581
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900582/** QUERY DEBUGGING **/
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900583static char* dnsPacket_bprintQName(DnsPacket* packet, char* bp, char* bend) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900584 const uint8_t* p = packet->cursor;
585 const uint8_t* end = packet->end;
586 int first = 1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900587
588 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900589 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900590
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900591 if (p >= end) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900592
593 c = *p++;
594
595 if (c == 0) {
596 packet->cursor = p;
597 return bp;
598 }
599
600 /* we don't expect label compression in QNAMEs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900601 if (c >= 64) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900602
603 if (first)
604 first = 0;
605 else
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900606 bp = bprint_c(bp, bend, '.');
Bernie Innocenti55864192018-08-30 04:05:20 +0900607
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900608 bp = bprint_b(bp, bend, (const char*) p, c);
Bernie Innocenti55864192018-08-30 04:05:20 +0900609
610 p += c;
611 /* we rely on the bound check at the start
612 * of the loop here */
613 }
614 /* malformed data */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900615 bp = bprint_s(bp, bend, "<MALFORMED>");
Bernie Innocenti55864192018-08-30 04:05:20 +0900616 return bp;
617}
618
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900619static char* dnsPacket_bprintQR(DnsPacket* packet, char* p, char* end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900620#define QQ(x) \
621 { DNS_TYPE_##x, #x }
Bernie Innocenti55864192018-08-30 04:05:20 +0900622 static const struct {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900623 const char* typeBytes;
624 const char* typeString;
625 } qTypes[] = {QQ(A), QQ(PTR), QQ(MX), QQ(AAAA), QQ(ALL), {NULL, NULL}};
626 int nn;
627 const char* typeString = NULL;
Bernie Innocenti55864192018-08-30 04:05:20 +0900628
629 /* dump QNAME */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900630 p = dnsPacket_bprintQName(packet, p, end);
Bernie Innocenti55864192018-08-30 04:05:20 +0900631
632 /* dump TYPE */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900633 p = bprint_s(p, end, " (");
Bernie Innocenti55864192018-08-30 04:05:20 +0900634
635 for (nn = 0; qTypes[nn].typeBytes != NULL; nn++) {
636 if (_dnsPacket_checkBytes(packet, 2, qTypes[nn].typeBytes)) {
637 typeString = qTypes[nn].typeString;
638 break;
639 }
640 }
641
642 if (typeString != NULL)
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900643 p = bprint_s(p, end, typeString);
Bernie Innocenti55864192018-08-30 04:05:20 +0900644 else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900645 int typeCode = _dnsPacket_readInt16(packet);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900646 p = bprint(p, end, "UNKNOWN-%d", typeCode);
Bernie Innocenti55864192018-08-30 04:05:20 +0900647 }
648
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900649 p = bprint_c(p, end, ')');
Bernie Innocenti55864192018-08-30 04:05:20 +0900650
651 /* skip CLASS */
652 _dnsPacket_skip(packet, 2);
653 return p;
654}
655
656/* this function assumes the packet has already been checked */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900657static char* dnsPacket_bprintQuery(DnsPacket* packet, char* p, char* end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900658 int qdCount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900659
660 if (packet->base[2] & 0x1) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900661 p = bprint_s(p, end, "RECURSIVE ");
Bernie Innocenti55864192018-08-30 04:05:20 +0900662 }
663
664 _dnsPacket_skip(packet, 4);
665 qdCount = _dnsPacket_readInt16(packet);
666 _dnsPacket_skip(packet, 6);
667
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900668 for (; qdCount > 0; qdCount--) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900669 p = dnsPacket_bprintQR(packet, p, end);
Bernie Innocenti55864192018-08-30 04:05:20 +0900670 }
671 return p;
672}
Bernie Innocenti55864192018-08-30 04:05:20 +0900673
Bernie Innocenti55864192018-08-30 04:05:20 +0900674/** QUERY HASHING SUPPORT
675 **
676 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKET HAS ALREADY
677 ** BEEN SUCCESFULLY CHECKED.
678 **/
679
680/* use 32-bit FNV hash function */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900681#define FNV_MULT 16777619U
682#define FNV_BASIS 2166136261U
Bernie Innocenti55864192018-08-30 04:05:20 +0900683
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900684static unsigned _dnsPacket_hashBytes(DnsPacket* packet, int numBytes, unsigned hash) {
685 const uint8_t* p = packet->cursor;
686 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900687
688 while (numBytes > 0 && p < end) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900689 hash = hash * FNV_MULT ^ *p++;
Bernie Innocenti55864192018-08-30 04:05:20 +0900690 }
691 packet->cursor = p;
692 return hash;
693}
694
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900695static unsigned _dnsPacket_hashQName(DnsPacket* packet, unsigned hash) {
696 const uint8_t* p = packet->cursor;
697 const uint8_t* end = packet->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900698
699 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900700 int c;
Bernie Innocenti55864192018-08-30 04:05:20 +0900701
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900702 if (p >= end) { /* should not happen */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900703 VLOG << __func__ << ": INTERNAL_ERROR: read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900704 break;
705 }
706
707 c = *p++;
708
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900709 if (c == 0) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900710
711 if (c >= 64) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900712 VLOG << __func__ << ": INTERNAL_ERROR: malformed domain";
Bernie Innocenti55864192018-08-30 04:05:20 +0900713 break;
714 }
715 if (p + c >= end) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900716 VLOG << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900717 break;
718 }
719 while (c > 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900720 hash = hash * FNV_MULT ^ *p++;
721 c -= 1;
Bernie Innocenti55864192018-08-30 04:05:20 +0900722 }
723 }
724 packet->cursor = p;
725 return hash;
726}
727
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900728static unsigned _dnsPacket_hashQR(DnsPacket* packet, unsigned hash) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900729 hash = _dnsPacket_hashQName(packet, hash);
730 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TYPE and CLASS */
731 return hash;
732}
733
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900734static unsigned _dnsPacket_hashRR(DnsPacket* packet, unsigned hash) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900735 int rdlength;
736 hash = _dnsPacket_hashQR(packet, hash);
737 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TTL */
738 rdlength = _dnsPacket_readInt16(packet);
739 hash = _dnsPacket_hashBytes(packet, rdlength, hash); /* RDATA */
740 return hash;
741}
742
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900743static unsigned _dnsPacket_hashQuery(DnsPacket* packet) {
744 unsigned hash = FNV_BASIS;
745 int count, arcount;
Bernie Innocenti55864192018-08-30 04:05:20 +0900746 _dnsPacket_rewind(packet);
747
748 /* ignore the ID */
749 _dnsPacket_skip(packet, 2);
750
751 /* we ignore the TC bit for reasons explained in
752 * _dnsPacket_checkQuery().
753 *
754 * however we hash the RD bit to differentiate
755 * between answers for recursive and non-recursive
756 * queries.
757 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900758 hash = hash * FNV_MULT ^ (packet->base[2] & 1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900759
760 /* mark the first header byte as processed */
761 _dnsPacket_skip(packet, 1);
762
763 /* process the second header byte */
764 hash = _dnsPacket_hashBytes(packet, 1, hash);
765
766 /* read QDCOUNT */
767 count = _dnsPacket_readInt16(packet);
768
769 /* assume: ANcount and NScount are 0 */
770 _dnsPacket_skip(packet, 4);
771
772 /* read ARCOUNT */
773 arcount = _dnsPacket_readInt16(packet);
774
775 /* hash QDCOUNT QRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900776 for (; count > 0; count--) hash = _dnsPacket_hashQR(packet, hash);
Bernie Innocenti55864192018-08-30 04:05:20 +0900777
778 /* hash ARCOUNT RRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900779 for (; arcount > 0; arcount--) hash = _dnsPacket_hashRR(packet, hash);
Bernie Innocenti55864192018-08-30 04:05:20 +0900780
781 return hash;
782}
783
Bernie Innocenti55864192018-08-30 04:05:20 +0900784/** QUERY COMPARISON
785 **
786 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKETS HAVE ALREADY
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900787 ** BEEN SUCCESSFULLY CHECKED.
Bernie Innocenti55864192018-08-30 04:05:20 +0900788 **/
789
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900790static int _dnsPacket_isEqualDomainName(DnsPacket* pack1, DnsPacket* pack2) {
791 const uint8_t* p1 = pack1->cursor;
792 const uint8_t* end1 = pack1->end;
793 const uint8_t* p2 = pack2->cursor;
794 const uint8_t* end2 = pack2->end;
Bernie Innocenti55864192018-08-30 04:05:20 +0900795
796 for (;;) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900797 int c1, c2;
Bernie Innocenti55864192018-08-30 04:05:20 +0900798
799 if (p1 >= end1 || p2 >= end2) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900800 VLOG << __func__ << ": INTERNAL_ERROR: read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900801 break;
802 }
803 c1 = *p1++;
804 c2 = *p2++;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900805 if (c1 != c2) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900806
807 if (c1 == 0) {
808 pack1->cursor = p1;
809 pack2->cursor = p2;
810 return 1;
811 }
812 if (c1 >= 64) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900813 VLOG << __func__ << ": INTERNAL_ERROR: malformed domain";
Bernie Innocenti55864192018-08-30 04:05:20 +0900814 break;
815 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900816 if ((p1 + c1 > end1) || (p2 + c1 > end2)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900817 VLOG << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
Bernie Innocenti55864192018-08-30 04:05:20 +0900818 break;
819 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900820 if (memcmp(p1, p2, c1) != 0) break;
Bernie Innocenti55864192018-08-30 04:05:20 +0900821 p1 += c1;
822 p2 += c1;
823 /* we rely on the bound checks at the start of the loop */
824 }
825 /* not the same, or one is malformed */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900826 VLOG << "different DN";
Bernie Innocenti55864192018-08-30 04:05:20 +0900827 return 0;
828}
829
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900830static int _dnsPacket_isEqualBytes(DnsPacket* pack1, DnsPacket* pack2, int numBytes) {
831 const uint8_t* p1 = pack1->cursor;
832 const uint8_t* p2 = pack2->cursor;
Bernie Innocenti55864192018-08-30 04:05:20 +0900833
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900834 if (p1 + numBytes > pack1->end || p2 + numBytes > pack2->end) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900835
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900836 if (memcmp(p1, p2, numBytes) != 0) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900837
838 pack1->cursor += numBytes;
839 pack2->cursor += numBytes;
840 return 1;
841}
842
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900843static int _dnsPacket_isEqualQR(DnsPacket* pack1, DnsPacket* pack2) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900844 /* compare domain name encoding + TYPE + CLASS */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900845 if (!_dnsPacket_isEqualDomainName(pack1, pack2) ||
846 !_dnsPacket_isEqualBytes(pack1, pack2, 2 + 2))
Bernie Innocenti55864192018-08-30 04:05:20 +0900847 return 0;
848
849 return 1;
850}
851
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900852static int _dnsPacket_isEqualRR(DnsPacket* pack1, DnsPacket* pack2) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900853 int rdlength1, rdlength2;
854 /* compare query + TTL */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900855 if (!_dnsPacket_isEqualQR(pack1, pack2) || !_dnsPacket_isEqualBytes(pack1, pack2, 4)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900856
857 /* compare RDATA */
858 rdlength1 = _dnsPacket_readInt16(pack1);
859 rdlength2 = _dnsPacket_readInt16(pack2);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900860 if (rdlength1 != rdlength2 || !_dnsPacket_isEqualBytes(pack1, pack2, rdlength1)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900861
862 return 1;
863}
864
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900865static int _dnsPacket_isEqualQuery(DnsPacket* pack1, DnsPacket* pack2) {
866 int count1, count2, arcount1, arcount2;
Bernie Innocenti55864192018-08-30 04:05:20 +0900867
868 /* compare the headers, ignore most fields */
869 _dnsPacket_rewind(pack1);
870 _dnsPacket_rewind(pack2);
871
872 /* compare RD, ignore TC, see comment in _dnsPacket_checkQuery */
873 if ((pack1->base[2] & 1) != (pack2->base[2] & 1)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900874 VLOG << "different RD";
Bernie Innocenti55864192018-08-30 04:05:20 +0900875 return 0;
876 }
877
878 if (pack1->base[3] != pack2->base[3]) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900879 VLOG << "different CD or AD";
Bernie Innocenti55864192018-08-30 04:05:20 +0900880 return 0;
881 }
882
883 /* mark ID and header bytes as compared */
884 _dnsPacket_skip(pack1, 4);
885 _dnsPacket_skip(pack2, 4);
886
887 /* compare QDCOUNT */
888 count1 = _dnsPacket_readInt16(pack1);
889 count2 = _dnsPacket_readInt16(pack2);
890 if (count1 != count2 || count1 < 0) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900891 VLOG << "different QDCOUNT";
Bernie Innocenti55864192018-08-30 04:05:20 +0900892 return 0;
893 }
894
895 /* assume: ANcount and NScount are 0 */
896 _dnsPacket_skip(pack1, 4);
897 _dnsPacket_skip(pack2, 4);
898
899 /* compare ARCOUNT */
900 arcount1 = _dnsPacket_readInt16(pack1);
901 arcount2 = _dnsPacket_readInt16(pack2);
902 if (arcount1 != arcount2 || arcount1 < 0) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900903 VLOG << "different ARCOUNT";
Bernie Innocenti55864192018-08-30 04:05:20 +0900904 return 0;
905 }
906
907 /* compare the QDCOUNT QRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900908 for (; count1 > 0; count1--) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900909 if (!_dnsPacket_isEqualQR(pack1, pack2)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900910 VLOG << "different QR";
Bernie Innocenti55864192018-08-30 04:05:20 +0900911 return 0;
912 }
913 }
914
915 /* compare the ARCOUNT RRs */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900916 for (; arcount1 > 0; arcount1--) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900917 if (!_dnsPacket_isEqualRR(pack1, pack2)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900918 VLOG << "different additional RR";
Bernie Innocenti55864192018-08-30 04:05:20 +0900919 return 0;
920 }
921 }
922 return 1;
923}
924
Bernie Innocenti55864192018-08-30 04:05:20 +0900925/* cache entry. for simplicity, 'hash' and 'hlink' are inlined in this
926 * structure though they are conceptually part of the hash table.
927 *
928 * similarly, mru_next and mru_prev are part of the global MRU list
929 */
930typedef struct Entry {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900931 unsigned int hash; /* hash value */
932 struct Entry* hlink; /* next in collision chain */
933 struct Entry* mru_prev;
934 struct Entry* mru_next;
Bernie Innocenti55864192018-08-30 04:05:20 +0900935
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900936 const uint8_t* query;
937 int querylen;
938 const uint8_t* answer;
939 int answerlen;
940 time_t expires; /* time_t when the entry isn't valid any more */
941 int id; /* for debugging purpose */
Bernie Innocenti55864192018-08-30 04:05:20 +0900942} Entry;
943
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900944/*
Bernie Innocenti55864192018-08-30 04:05:20 +0900945 * Find the TTL for a negative DNS result. This is defined as the minimum
946 * of the SOA records TTL and the MINIMUM-TTL field (RFC-2308).
947 *
948 * Return 0 if not found.
949 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900950static u_long answer_getNegativeTTL(ns_msg handle) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900951 int n, nscount;
952 u_long result = 0;
953 ns_rr rr;
954
955 nscount = ns_msg_count(handle, ns_s_ns);
956 for (n = 0; n < nscount; n++) {
957 if ((ns_parserr(&handle, ns_s_ns, n, &rr) == 0) && (ns_rr_type(rr) == ns_t_soa)) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900958 const u_char* rdata = ns_rr_rdata(rr); // find the data
959 const u_char* edata = rdata + ns_rr_rdlen(rr); // add the len to find the end
Bernie Innocenti55864192018-08-30 04:05:20 +0900960 int len;
961 u_long ttl, rec_result = ns_rr_ttl(rr);
962
963 // find the MINIMUM-TTL field from the blob of binary data for this record
964 // skip the server name
965 len = dn_skipname(rdata, edata);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900966 if (len == -1) continue; // error skipping
Bernie Innocenti55864192018-08-30 04:05:20 +0900967 rdata += len;
968
969 // skip the admin name
970 len = dn_skipname(rdata, edata);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900971 if (len == -1) continue; // error skipping
Bernie Innocenti55864192018-08-30 04:05:20 +0900972 rdata += len;
973
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900974 if (edata - rdata != 5 * NS_INT32SZ) continue;
Bernie Innocenti55864192018-08-30 04:05:20 +0900975 // skip: serial number + refresh interval + retry interval + expiry
976 rdata += NS_INT32SZ * 4;
977 // finally read the MINIMUM TTL
978 ttl = ns_get32(rdata);
979 if (ttl < rec_result) {
980 rec_result = ttl;
981 }
982 // Now that the record is read successfully, apply the new min TTL
983 if (n == 0 || rec_result < result) {
984 result = rec_result;
985 }
986 }
987 }
988 return result;
989}
990
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900991/*
Bernie Innocenti55864192018-08-30 04:05:20 +0900992 * Parse the answer records and find the appropriate
993 * smallest TTL among the records. This might be from
994 * the answer records if found or from the SOA record
995 * if it's a negative result.
996 *
997 * The returned TTL is the number of seconds to
998 * keep the answer in the cache.
999 *
1000 * In case of parse error zero (0) is returned which
1001 * indicates that the answer shall not be cached.
1002 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001003static u_long answer_getTTL(const void* answer, int answerlen) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001004 ns_msg handle;
1005 int ancount, n;
1006 u_long result, ttl;
1007 ns_rr rr;
1008
1009 result = 0;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001010 if (ns_initparse((const uint8_t*) answer, answerlen, &handle) >= 0) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001011 // get number of answer records
1012 ancount = ns_msg_count(handle, ns_s_an);
1013
1014 if (ancount == 0) {
1015 // a response with no answers? Cache this negative result.
1016 result = answer_getNegativeTTL(handle);
1017 } else {
1018 for (n = 0; n < ancount; n++) {
1019 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
1020 ttl = ns_rr_ttl(rr);
1021 if (n == 0 || ttl < result) {
1022 result = ttl;
1023 }
1024 } else {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001025 VLOG << "ns_parserr failed ancount no = "
1026 << n << ". errno = " << strerror(errno);
Bernie Innocenti55864192018-08-30 04:05:20 +09001027 }
1028 }
1029 }
1030 } else {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001031 VLOG << "ns_initparse failed: " << strerror(errno);
Bernie Innocenti55864192018-08-30 04:05:20 +09001032 }
1033
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001034 VLOG << "TTL = " << result;
Bernie Innocenti55864192018-08-30 04:05:20 +09001035 return result;
1036}
1037
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001038static void entry_free(Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001039 /* everything is allocated in a single memory block */
1040 if (e) {
1041 free(e);
1042 }
1043}
1044
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001045static void entry_mru_remove(Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001046 e->mru_prev->mru_next = e->mru_next;
1047 e->mru_next->mru_prev = e->mru_prev;
1048}
1049
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001050static void entry_mru_add(Entry* e, Entry* list) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001051 Entry* first = list->mru_next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001052
1053 e->mru_next = first;
1054 e->mru_prev = list;
1055
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001056 list->mru_next = e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001057 first->mru_prev = e;
1058}
1059
1060/* compute the hash of a given entry, this is a hash of most
1061 * data in the query (key) */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001062static unsigned entry_hash(const Entry* e) {
1063 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001064
1065 _dnsPacket_init(pack, e->query, e->querylen);
1066 return _dnsPacket_hashQuery(pack);
1067}
1068
1069/* initialize an Entry as a search key, this also checks the input query packet
1070 * returns 1 on success, or 0 in case of unsupported/malformed data */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001071static int entry_init_key(Entry* e, const void* query, int querylen) {
1072 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001073
1074 memset(e, 0, sizeof(*e));
1075
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001076 e->query = (const uint8_t*) query;
Bernie Innocenti55864192018-08-30 04:05:20 +09001077 e->querylen = querylen;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001078 e->hash = entry_hash(e);
Bernie Innocenti55864192018-08-30 04:05:20 +09001079
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001080 _dnsPacket_init(pack, e->query, e->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001081
1082 return _dnsPacket_checkQuery(pack);
1083}
1084
1085/* allocate a new entry as a cache node */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001086static Entry* entry_alloc(const Entry* init, const void* answer, int answerlen) {
1087 Entry* e;
1088 int size;
Bernie Innocenti55864192018-08-30 04:05:20 +09001089
1090 size = sizeof(*e) + init->querylen + answerlen;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001091 e = (Entry*) calloc(size, 1);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001092 if (e == NULL) return e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001093
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001094 e->hash = init->hash;
1095 e->query = (const uint8_t*) (e + 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001096 e->querylen = init->querylen;
1097
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001098 memcpy((char*) e->query, init->query, e->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001099
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001100 e->answer = e->query + e->querylen;
Bernie Innocenti55864192018-08-30 04:05:20 +09001101 e->answerlen = answerlen;
1102
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001103 memcpy((char*) e->answer, answer, e->answerlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001104
1105 return e;
1106}
1107
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001108static int entry_equals(const Entry* e1, const Entry* e2) {
1109 DnsPacket pack1[1], pack2[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001110
1111 if (e1->querylen != e2->querylen) {
1112 return 0;
1113 }
1114 _dnsPacket_init(pack1, e1->query, e1->querylen);
1115 _dnsPacket_init(pack2, e2->query, e2->querylen);
1116
1117 return _dnsPacket_isEqualQuery(pack1, pack2);
1118}
1119
Bernie Innocenti55864192018-08-30 04:05:20 +09001120/* We use a simple hash table with external collision lists
1121 * for simplicity, the hash-table fields 'hash' and 'hlink' are
1122 * inlined in the Entry structure.
1123 */
1124
1125/* Maximum time for a thread to wait for an pending request */
1126#define PENDING_REQUEST_TIMEOUT 20;
1127
1128typedef struct pending_req_info {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001129 unsigned int hash;
1130 pthread_cond_t cond;
1131 struct pending_req_info* next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001132} PendingReqInfo;
1133
1134typedef struct resolv_cache {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001135 int max_entries;
1136 int num_entries;
1137 Entry mru_list;
1138 int last_id;
1139 Entry* entries;
1140 PendingReqInfo pending_requests;
Bernie Innocenti55864192018-08-30 04:05:20 +09001141} Cache;
1142
1143struct resolv_cache_info {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001144 unsigned netid;
1145 Cache* cache;
1146 struct resolv_cache_info* next;
1147 int nscount;
1148 char* nameservers[MAXNS];
1149 struct addrinfo* nsaddrinfo[MAXNS];
1150 int revision_id; // # times the nameservers have been replaced
1151 struct __res_params params;
Bernie Innocenti189eb502018-10-01 23:10:18 +09001152 struct res_stats nsstats[MAXNS];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001153 char defdname[MAXDNSRCHPATH];
1154 int dnsrch_offset[MAXDNSRCH + 1]; // offsets into defdname
Bernie Innocenti55864192018-08-30 04:05:20 +09001155};
1156
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001157static pthread_once_t _res_cache_once = PTHREAD_ONCE_INIT;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001158static void res_cache_init(void);
Bernie Innocenti55864192018-08-30 04:05:20 +09001159
1160// lock protecting everything in the _resolve_cache_info structs (next ptr, etc)
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001161static pthread_mutex_t res_cache_list_lock;
Bernie Innocenti55864192018-08-30 04:05:20 +09001162
1163/* gets cache associated with a network, or NULL if none exists */
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001164static struct resolv_cache* find_named_cache_locked(unsigned netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001165
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001166static void _cache_flush_pending_requests_locked(struct resolv_cache* cache) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001167 struct pending_req_info *ri, *tmp;
1168 if (cache) {
1169 ri = cache->pending_requests.next;
1170
1171 while (ri) {
1172 tmp = ri;
1173 ri = ri->next;
1174 pthread_cond_broadcast(&tmp->cond);
1175
1176 pthread_cond_destroy(&tmp->cond);
1177 free(tmp);
1178 }
1179
1180 cache->pending_requests.next = NULL;
1181 }
1182}
1183
1184/* Return 0 if no pending request is found matching the key.
1185 * If a matching request is found the calling thread will wait until
1186 * the matching request completes, then update *cache and return 1. */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001187static int _cache_check_pending_request_locked(struct resolv_cache** cache, Entry* key,
1188 unsigned netid) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001189 struct pending_req_info *ri, *prev;
1190 int exist = 0;
1191
1192 if (*cache && key) {
1193 ri = (*cache)->pending_requests.next;
1194 prev = &(*cache)->pending_requests;
1195 while (ri) {
1196 if (ri->hash == key->hash) {
1197 exist = 1;
1198 break;
1199 }
1200 prev = ri;
1201 ri = ri->next;
1202 }
1203
1204 if (!exist) {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001205 ri = (struct pending_req_info*) calloc(1, sizeof(struct pending_req_info));
Bernie Innocenti55864192018-08-30 04:05:20 +09001206 if (ri) {
1207 ri->hash = key->hash;
1208 pthread_cond_init(&ri->cond, NULL);
1209 prev->next = ri;
1210 }
1211 } else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001212 struct timespec ts = {0, 0};
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001213 VLOG << "Waiting for previous request";
Bernie Innocenti55864192018-08-30 04:05:20 +09001214 ts.tv_sec = _time_now() + PENDING_REQUEST_TIMEOUT;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001215 pthread_cond_timedwait(&ri->cond, &res_cache_list_lock, &ts);
Bernie Innocenti55864192018-08-30 04:05:20 +09001216 /* Must update *cache as it could have been deleted. */
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001217 *cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001218 }
1219 }
1220
1221 return exist;
1222}
1223
1224/* notify any waiting thread that waiting on a request
1225 * matching the key has been added to the cache */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001226static void _cache_notify_waiting_tid_locked(struct resolv_cache* cache, Entry* key) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001227 struct pending_req_info *ri, *prev;
1228
1229 if (cache && key) {
1230 ri = cache->pending_requests.next;
1231 prev = &cache->pending_requests;
1232 while (ri) {
1233 if (ri->hash == key->hash) {
1234 pthread_cond_broadcast(&ri->cond);
1235 break;
1236 }
1237 prev = ri;
1238 ri = ri->next;
1239 }
1240
1241 // remove item from list and destroy
1242 if (ri) {
1243 prev->next = ri->next;
1244 pthread_cond_destroy(&ri->cond);
1245 free(ri);
1246 }
1247 }
1248}
1249
1250/* notify the cache that the query failed */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001251void _resolv_cache_query_failed(unsigned netid, const void* query, int querylen) {
1252 Entry key[1];
1253 Cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001254
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001255 if (!entry_init_key(key, query, querylen)) return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001256
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001257 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001258
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001259 cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001260
1261 if (cache) {
1262 _cache_notify_waiting_tid_locked(cache, key);
1263 }
1264
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001265 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001266}
1267
ckenb1a69a42018-12-01 17:45:18 +09001268static resolv_cache_info* find_cache_info_locked(unsigned netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001269
Bernie Innocentid2b27032018-12-18 19:53:42 +09001270static void cache_flush_locked(Cache* cache) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001271 int nn;
Bernie Innocenti55864192018-08-30 04:05:20 +09001272
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001273 for (nn = 0; nn < cache->max_entries; nn++) {
1274 Entry** pnode = (Entry**) &cache->entries[nn];
Bernie Innocenti55864192018-08-30 04:05:20 +09001275
1276 while (*pnode != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001277 Entry* node = *pnode;
Bernie Innocenti55864192018-08-30 04:05:20 +09001278 *pnode = node->hlink;
1279 entry_free(node);
1280 }
1281 }
1282
1283 // flush pending request
1284 _cache_flush_pending_requests_locked(cache);
1285
1286 cache->mru_list.mru_next = cache->mru_list.mru_prev = &cache->mru_list;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001287 cache->num_entries = 0;
1288 cache->last_id = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +09001289
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001290 VLOG << "*** DNS CACHE FLUSHED ***";
Bernie Innocenti55864192018-08-30 04:05:20 +09001291}
1292
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001293static struct resolv_cache* _resolv_cache_create(void) {
1294 struct resolv_cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001295
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001296 cache = (struct resolv_cache*) calloc(sizeof(*cache), 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001297 if (cache) {
nuccachen989d2232018-11-29 17:41:12 +08001298 cache->max_entries = CONFIG_MAX_ENTRIES;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001299 cache->entries = (Entry*) calloc(sizeof(*cache->entries), cache->max_entries);
Bernie Innocenti55864192018-08-30 04:05:20 +09001300 if (cache->entries) {
1301 cache->mru_list.mru_prev = cache->mru_list.mru_next = &cache->mru_list;
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001302 VLOG << __func__ << ": cache created";
Bernie Innocenti55864192018-08-30 04:05:20 +09001303 } else {
1304 free(cache);
1305 cache = NULL;
1306 }
1307 }
1308 return cache;
1309}
1310
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001311static void dump_query(const uint8_t* query, int querylen) {
1312 if (!kVerboseLogging) return;
1313
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001314 char temp[256], *p = temp, *end = p + sizeof(temp);
1315 DnsPacket pack[1];
Bernie Innocenti55864192018-08-30 04:05:20 +09001316
1317 _dnsPacket_init(pack, query, querylen);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001318 p = dnsPacket_bprintQuery(pack, p, end);
1319 VLOG << temp;
Bernie Innocenti55864192018-08-30 04:05:20 +09001320}
1321
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001322static void cache_dump_mru(Cache* cache) {
1323 if (!kVerboseLogging) return;
1324
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001325 char temp[512], *p = temp, *end = p + sizeof(temp);
1326 Entry* e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001327
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001328 p = bprint(temp, end, "MRU LIST (%2d): ", cache->num_entries);
Bernie Innocenti55864192018-08-30 04:05:20 +09001329 for (e = cache->mru_list.mru_next; e != &cache->mru_list; e = e->mru_next)
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001330 p = bprint(p, end, " %d", e->id);
Bernie Innocenti55864192018-08-30 04:05:20 +09001331
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001332 VLOG << temp;
Bernie Innocenti55864192018-08-30 04:05:20 +09001333}
1334
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001335// TODO: Rewrite to avoid creating a file in /data as temporary buffer (WAT).
1336static void dump_answer(const u_char* answer, int answerlen) {
1337 if (!kVerboseLogging) return;
1338
Bernie Innocenti55864192018-08-30 04:05:20 +09001339 res_state statep;
1340 FILE* fp;
1341 char* buf;
1342 int fileLen;
1343
1344 fp = fopen("/data/reslog.txt", "w+e");
1345 if (fp != NULL) {
Bernie Innocenti4acba1a2018-09-26 11:52:04 +09001346 statep = res_get_state();
Bernie Innocenti55864192018-08-30 04:05:20 +09001347
1348 res_pquery(statep, answer, answerlen, fp);
1349
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001350 // Get file length
Bernie Innocenti55864192018-08-30 04:05:20 +09001351 fseek(fp, 0, SEEK_END);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001352 fileLen = ftell(fp);
Bernie Innocenti55864192018-08-30 04:05:20 +09001353 fseek(fp, 0, SEEK_SET);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001354 buf = (char*) malloc(fileLen + 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001355 if (buf != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001356 // Read file contents into buffer
Bernie Innocenti55864192018-08-30 04:05:20 +09001357 fread(buf, fileLen, 1, fp);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001358 VLOG << buf;
Bernie Innocenti55864192018-08-30 04:05:20 +09001359 free(buf);
1360 }
1361 fclose(fp);
1362 remove("/data/reslog.txt");
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001363 } else {
1364 errno = 0; // else debug is introducing error signals
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001365 VLOG << __func__ << ": can't open file";
Bernie Innocenti55864192018-08-30 04:05:20 +09001366 }
1367}
Bernie Innocenti55864192018-08-30 04:05:20 +09001368
1369/* This function tries to find a key within the hash table
1370 * In case of success, it will return a *pointer* to the hashed key.
1371 * In case of failure, it will return a *pointer* to NULL
1372 *
1373 * So, the caller must check '*result' to check for success/failure.
1374 *
1375 * The main idea is that the result can later be used directly in
1376 * calls to _resolv_cache_add or _resolv_cache_remove as the 'lookup'
1377 * parameter. This makes the code simpler and avoids re-searching
1378 * for the key position in the htable.
1379 *
1380 * The result of a lookup_p is only valid until you alter the hash
1381 * table.
1382 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001383static Entry** _cache_lookup_p(Cache* cache, Entry* key) {
1384 int index = key->hash % cache->max_entries;
1385 Entry** pnode = (Entry**) &cache->entries[index];
Bernie Innocenti55864192018-08-30 04:05:20 +09001386
1387 while (*pnode != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001388 Entry* node = *pnode;
Bernie Innocenti55864192018-08-30 04:05:20 +09001389
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001390 if (node == NULL) break;
Bernie Innocenti55864192018-08-30 04:05:20 +09001391
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001392 if (node->hash == key->hash && entry_equals(node, key)) break;
Bernie Innocenti55864192018-08-30 04:05:20 +09001393
1394 pnode = &node->hlink;
1395 }
1396 return pnode;
1397}
1398
1399/* Add a new entry to the hash table. 'lookup' must be the
1400 * result of an immediate previous failed _lookup_p() call
1401 * (i.e. with *lookup == NULL), and 'e' is the pointer to the
1402 * newly created entry
1403 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001404static void _cache_add_p(Cache* cache, Entry** lookup, Entry* e) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001405 *lookup = e;
1406 e->id = ++cache->last_id;
1407 entry_mru_add(e, &cache->mru_list);
1408 cache->num_entries += 1;
1409
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001410 VLOG << __func__ << ": entry " << e->id << " added (count=" << cache->num_entries << ")";
Bernie Innocenti55864192018-08-30 04:05:20 +09001411}
1412
1413/* Remove an existing entry from the hash table,
1414 * 'lookup' must be the result of an immediate previous
1415 * and succesful _lookup_p() call.
1416 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001417static void _cache_remove_p(Cache* cache, Entry** lookup) {
1418 Entry* e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001419
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001420 VLOG << __func__ << ": entry " << e->id << " removed (count=" << cache->num_entries - 1 << ")";
Bernie Innocenti55864192018-08-30 04:05:20 +09001421
1422 entry_mru_remove(e);
1423 *lookup = e->hlink;
1424 entry_free(e);
1425 cache->num_entries -= 1;
1426}
1427
1428/* Remove the oldest entry from the hash table.
1429 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001430static void _cache_remove_oldest(Cache* cache) {
1431 Entry* oldest = cache->mru_list.mru_prev;
1432 Entry** lookup = _cache_lookup_p(cache, oldest);
Bernie Innocenti55864192018-08-30 04:05:20 +09001433
1434 if (*lookup == NULL) { /* should not happen */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001435 VLOG << __func__ << ": OLDEST NOT IN HTABLE ?";
Bernie Innocenti55864192018-08-30 04:05:20 +09001436 return;
1437 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001438 VLOG << "Cache full - removing oldest";
1439 dump_query(oldest->query, oldest->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001440 _cache_remove_p(cache, lookup);
1441}
1442
1443/* Remove all expired entries from the hash table.
1444 */
1445static void _cache_remove_expired(Cache* cache) {
1446 Entry* e;
1447 time_t now = _time_now();
1448
1449 for (e = cache->mru_list.mru_next; e != &cache->mru_list;) {
1450 // Entry is old, remove
1451 if (now >= e->expires) {
1452 Entry** lookup = _cache_lookup_p(cache, e);
1453 if (*lookup == NULL) { /* should not happen */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001454 VLOG << __func__ << ": ENTRY NOT IN HTABLE ?";
Bernie Innocenti55864192018-08-30 04:05:20 +09001455 return;
1456 }
1457 e = e->mru_next;
1458 _cache_remove_p(cache, lookup);
1459 } else {
1460 e = e->mru_next;
1461 }
1462 }
1463}
1464
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001465ResolvCacheStatus _resolv_cache_lookup(unsigned netid, const void* query, int querylen,
1466 void* answer, int answersize, int* answerlen) {
1467 Entry key[1];
1468 Entry** lookup;
1469 Entry* e;
1470 time_t now;
1471 Cache* cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001472
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001473 ResolvCacheStatus result = RESOLV_CACHE_NOTFOUND;
Bernie Innocenti55864192018-08-30 04:05:20 +09001474
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001475 VLOG << __func__ << ": lookup";
1476 dump_query((u_char*) query, querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001477
1478 /* we don't cache malformed queries */
1479 if (!entry_init_key(key, query, querylen)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001480 VLOG << __func__ << ": unsupported query";
Bernie Innocenti55864192018-08-30 04:05:20 +09001481 return RESOLV_CACHE_UNSUPPORTED;
1482 }
1483 /* lookup cache */
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001484 pthread_once(&_res_cache_once, res_cache_init);
1485 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001486
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001487 cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001488 if (cache == NULL) {
1489 result = RESOLV_CACHE_UNSUPPORTED;
1490 goto Exit;
1491 }
1492
1493 /* see the description of _lookup_p to understand this.
1494 * the function always return a non-NULL pointer.
1495 */
1496 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001497 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001498
1499 if (e == NULL) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001500 VLOG << "NOT IN CACHE";
Bernie Innocenti55864192018-08-30 04:05:20 +09001501 // calling thread will wait if an outstanding request is found
1502 // that matching this query
1503 if (!_cache_check_pending_request_locked(&cache, key, netid) || cache == NULL) {
1504 goto Exit;
1505 } else {
1506 lookup = _cache_lookup_p(cache, key);
1507 e = *lookup;
1508 if (e == NULL) {
1509 goto Exit;
1510 }
1511 }
1512 }
1513
1514 now = _time_now();
1515
1516 /* remove stale entries here */
1517 if (now >= e->expires) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001518 VLOG << " NOT IN CACHE (STALE ENTRY " << *lookup << "DISCARDED)";
1519 dump_query(e->query, e->querylen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001520 _cache_remove_p(cache, lookup);
1521 goto Exit;
1522 }
1523
1524 *answerlen = e->answerlen;
1525 if (e->answerlen > answersize) {
1526 /* NOTE: we return UNSUPPORTED if the answer buffer is too short */
1527 result = RESOLV_CACHE_UNSUPPORTED;
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001528 VLOG << " ANSWER TOO LONG";
Bernie Innocenti55864192018-08-30 04:05:20 +09001529 goto Exit;
1530 }
1531
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001532 memcpy(answer, e->answer, e->answerlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001533
1534 /* bump up this entry to the top of the MRU list */
1535 if (e != cache->mru_list.mru_next) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001536 entry_mru_remove(e);
1537 entry_mru_add(e, &cache->mru_list);
Bernie Innocenti55864192018-08-30 04:05:20 +09001538 }
1539
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001540 VLOG << "FOUND IN CACHE entry=" << e;
Bernie Innocenti55864192018-08-30 04:05:20 +09001541 result = RESOLV_CACHE_FOUND;
1542
1543Exit:
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001544 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001545 return result;
1546}
1547
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001548void _resolv_cache_add(unsigned netid, const void* query, int querylen, const void* answer,
1549 int answerlen) {
1550 Entry key[1];
1551 Entry* e;
1552 Entry** lookup;
1553 u_long ttl;
1554 Cache* cache = NULL;
Bernie Innocenti55864192018-08-30 04:05:20 +09001555
1556 /* don't assume that the query has already been cached
1557 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001558 if (!entry_init_key(key, query, querylen)) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001559 VLOG << __func__ << ": passed invalid query?";
Bernie Innocenti55864192018-08-30 04:05:20 +09001560 return;
1561 }
1562
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001563 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001564
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001565 cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001566 if (cache == NULL) {
1567 goto Exit;
1568 }
1569
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001570 VLOG << __func__ << ": query:";
1571 dump_query((u_char*) query, querylen);
1572 dump_answer((u_char*) answer, answerlen);
1573 if (kDumpData) {
1574 VLOG << "answer:";
1575 dump_bytes((u_char*) answer, answerlen);
1576 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001577
1578 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001579 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001580
1581 if (e != NULL) { /* should not happen */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001582 VLOG << __func__ << ": ALREADY IN CACHE (" << e << ") ? IGNORING ADD";
Bernie Innocenti55864192018-08-30 04:05:20 +09001583 goto Exit;
1584 }
1585
1586 if (cache->num_entries >= cache->max_entries) {
1587 _cache_remove_expired(cache);
1588 if (cache->num_entries >= cache->max_entries) {
1589 _cache_remove_oldest(cache);
1590 }
1591 /* need to lookup again */
1592 lookup = _cache_lookup_p(cache, key);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001593 e = *lookup;
Bernie Innocenti55864192018-08-30 04:05:20 +09001594 if (e != NULL) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001595 VLOG << __func__ << ": ALREADY IN CACHE (" << e << ") ? IGNORING ADD";
Bernie Innocenti55864192018-08-30 04:05:20 +09001596 goto Exit;
1597 }
1598 }
1599
1600 ttl = answer_getTTL(answer, answerlen);
1601 if (ttl > 0) {
1602 e = entry_alloc(key, answer, answerlen);
1603 if (e != NULL) {
1604 e->expires = ttl + _time_now();
1605 _cache_add_p(cache, lookup, e);
1606 }
1607 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001608 cache_dump_mru(cache);
1609
Bernie Innocenti55864192018-08-30 04:05:20 +09001610Exit:
1611 if (cache != NULL) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001612 _cache_notify_waiting_tid_locked(cache, key);
Bernie Innocenti55864192018-08-30 04:05:20 +09001613 }
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001614 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001615}
1616
Bernie Innocenti55864192018-08-30 04:05:20 +09001617// Head of the list of caches. Protected by _res_cache_list_lock.
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001618static struct resolv_cache_info res_cache_list;
Bernie Innocenti55864192018-08-30 04:05:20 +09001619
ckenb1a69a42018-12-01 17:45:18 +09001620// insert resolv_cache_info into the list of resolv_cache_infos
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001621static void insert_cache_info_locked(resolv_cache_info* cache_info);
ckenb1a69a42018-12-01 17:45:18 +09001622// creates a resolv_cache_info
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001623static resolv_cache_info* create_cache_info();
ckenb1a69a42018-12-01 17:45:18 +09001624// gets a resolv_cache_info associated with a network, or NULL if not found
1625static resolv_cache_info* find_cache_info_locked(unsigned netid);
ckenb1a69a42018-12-01 17:45:18 +09001626// empty the nameservers set for the named cache
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001627static void free_nameservers_locked(resolv_cache_info* cache_info);
1628// return 1 if the provided list of name servers differs from the list of name servers
1629// currently attached to the provided cache_info
1630static int resolv_is_nameservers_equal_locked(resolv_cache_info* cache_info, const char** servers,
1631 int numservers);
ckenb1a69a42018-12-01 17:45:18 +09001632// clears the stats samples contained withing the given cache_info
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001633static void res_cache_clear_stats_locked(resolv_cache_info* cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001634
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001635static void res_cache_init(void) {
1636 memset(&res_cache_list, 0, sizeof(res_cache_list));
1637 pthread_mutex_init(&res_cache_list_lock, NULL);
Bernie Innocenti55864192018-08-30 04:05:20 +09001638}
1639
ckenb1a69a42018-12-01 17:45:18 +09001640// public API for netd to query if name server is set on specific netid
1641bool resolv_has_nameservers(unsigned netid) {
1642 pthread_once(&_res_cache_once, res_cache_init);
1643 pthread_mutex_lock(&res_cache_list_lock);
1644 resolv_cache_info* info = find_cache_info_locked(netid);
1645 const bool ret = (info != nullptr) && (info->nscount > 0);
1646 pthread_mutex_unlock(&res_cache_list_lock);
1647
1648 return ret;
1649}
1650
1651// look up the named cache, and creates one if needed
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001652static resolv_cache* get_res_cache_for_net_locked(unsigned netid) {
1653 resolv_cache* cache = find_named_cache_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001654 if (!cache) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001655 resolv_cache_info* cache_info = create_cache_info();
Bernie Innocenti55864192018-08-30 04:05:20 +09001656 if (cache_info) {
1657 cache = _resolv_cache_create();
1658 if (cache) {
1659 cache_info->cache = cache;
1660 cache_info->netid = netid;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001661 insert_cache_info_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001662 } else {
1663 free(cache_info);
1664 }
1665 }
1666 }
1667 return cache;
1668}
1669
Bernie Innocenti189eb502018-10-01 23:10:18 +09001670void resolv_delete_cache_for_net(unsigned netid) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001671 pthread_once(&_res_cache_once, res_cache_init);
1672 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001673
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001674 struct resolv_cache_info* prev_cache_info = &res_cache_list;
Bernie Innocenti55864192018-08-30 04:05:20 +09001675
1676 while (prev_cache_info->next) {
1677 struct resolv_cache_info* cache_info = prev_cache_info->next;
1678
1679 if (cache_info->netid == netid) {
1680 prev_cache_info->next = cache_info->next;
Bernie Innocentid2b27032018-12-18 19:53:42 +09001681 cache_flush_locked(cache_info->cache);
Bernie Innocenti55864192018-08-30 04:05:20 +09001682 free(cache_info->cache->entries);
1683 free(cache_info->cache);
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001684 free_nameservers_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001685 free(cache_info);
1686 break;
1687 }
1688
1689 prev_cache_info = prev_cache_info->next;
1690 }
1691
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001692 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001693}
1694
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001695static resolv_cache_info* create_cache_info() {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001696 return (struct resolv_cache_info*) calloc(sizeof(struct resolv_cache_info), 1);
Bernie Innocenti55864192018-08-30 04:05:20 +09001697}
1698
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001699static void insert_cache_info_locked(struct resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001700 struct resolv_cache_info* last;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001701 for (last = &res_cache_list; last->next; last = last->next) {}
Bernie Innocenti55864192018-08-30 04:05:20 +09001702 last->next = cache_info;
Bernie Innocenti55864192018-08-30 04:05:20 +09001703}
1704
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001705static resolv_cache* find_named_cache_locked(unsigned netid) {
ckenb1a69a42018-12-01 17:45:18 +09001706 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001707 if (info != NULL) return info->cache;
Bernie Innocenti55864192018-08-30 04:05:20 +09001708 return NULL;
1709}
1710
ckenb1a69a42018-12-01 17:45:18 +09001711static resolv_cache_info* find_cache_info_locked(unsigned netid) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001712 struct resolv_cache_info* cache_info = res_cache_list.next;
Bernie Innocenti55864192018-08-30 04:05:20 +09001713
1714 while (cache_info) {
1715 if (cache_info->netid == netid) {
1716 break;
1717 }
1718
1719 cache_info = cache_info->next;
1720 }
1721 return cache_info;
1722}
1723
Bernie Innocenti1fbca5c2018-10-01 20:46:20 +09001724static void resolv_set_default_params(struct __res_params* params) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001725 params->sample_validity = NSSAMPLE_VALIDITY;
1726 params->success_threshold = SUCCESS_THRESHOLD;
1727 params->min_samples = 0;
1728 params->max_samples = 0;
1729 params->base_timeout_msec = 0; // 0 = legacy algorithm
1730}
1731
Bernie Innocenti45238a12018-12-04 14:57:48 +09001732int resolv_set_nameservers_for_net(unsigned netid, const char** servers, const int numservers,
Bernie Innocenti189eb502018-10-01 23:10:18 +09001733 const char* domains, const __res_params* params) {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001734 char* cp;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001735 int* offset;
Bernie Innocenti55864192018-08-30 04:05:20 +09001736 struct addrinfo* nsaddrinfo[MAXNS];
1737
1738 if (numservers > MAXNS) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001739 VLOG << __func__ << ": numservers=" << numservers << ", MAXNS=" << MAXNS;
Bernie Innocenti55864192018-08-30 04:05:20 +09001740 return E2BIG;
1741 }
1742
1743 // Parse the addresses before actually locking or changing any state, in case there is an error.
1744 // As a side effect this also reduces the time the lock is kept.
Bernie Innocentic165ce82018-10-16 23:35:28 +09001745 char sbuf[NI_MAXSERV];
Bernie Innocenti55864192018-08-30 04:05:20 +09001746 snprintf(sbuf, sizeof(sbuf), "%u", NAMESERVER_PORT);
Bernie Innocenti45238a12018-12-04 14:57:48 +09001747 for (int i = 0; i < numservers; i++) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001748 // The addrinfo structures allocated here are freed in free_nameservers_locked().
Bernie Innocentic165ce82018-10-16 23:35:28 +09001749 const addrinfo hints = {
1750 .ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM, .ai_flags = AI_NUMERICHOST};
1751 int rt = getaddrinfo_numeric(servers[i], sbuf, hints, &nsaddrinfo[i]);
Bernie Innocenti55864192018-08-30 04:05:20 +09001752 if (rt != 0) {
Bernie Innocenti45238a12018-12-04 14:57:48 +09001753 for (int j = 0; j < i; j++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001754 freeaddrinfo(nsaddrinfo[j]);
Bernie Innocenti55864192018-08-30 04:05:20 +09001755 }
Bernie Innocentic165ce82018-10-16 23:35:28 +09001756 VLOG << __func__ << ": getaddrinfo_numeric(" << servers[i]
1757 << ") = " << gai_strerror(rt);
Bernie Innocenti55864192018-08-30 04:05:20 +09001758 return EINVAL;
1759 }
1760 }
1761
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001762 pthread_once(&_res_cache_once, res_cache_init);
1763 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001764
1765 // creates the cache if not created
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001766 get_res_cache_for_net_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001767
ckenb1a69a42018-12-01 17:45:18 +09001768 resolv_cache_info* cache_info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001769
1770 if (cache_info != NULL) {
1771 uint8_t old_max_samples = cache_info->params.max_samples;
1772 if (params != NULL) {
1773 cache_info->params = *params;
1774 } else {
Bernie Innocenti1fbca5c2018-10-01 20:46:20 +09001775 resolv_set_default_params(&cache_info->params);
Bernie Innocenti55864192018-08-30 04:05:20 +09001776 }
1777
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001778 if (!resolv_is_nameservers_equal_locked(cache_info, servers, numservers)) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001779 // free current before adding new
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001780 free_nameservers_locked(cache_info);
Bernie Innocenti45238a12018-12-04 14:57:48 +09001781 for (int i = 0; i < numservers; i++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001782 cache_info->nsaddrinfo[i] = nsaddrinfo[i];
1783 cache_info->nameservers[i] = strdup(servers[i]);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001784 VLOG << __func__ << ": netid = " << netid << ", addr = " << servers[i];
Bernie Innocenti55864192018-08-30 04:05:20 +09001785 }
1786 cache_info->nscount = numservers;
1787
1788 // Clear the NS statistics because the mapping to nameservers might have changed.
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001789 res_cache_clear_stats_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001790
1791 // increment the revision id to ensure that sample state is not written back if the
1792 // servers change; in theory it would suffice to do so only if the servers or
1793 // max_samples actually change, in practice the overhead of checking is higher than the
1794 // cost, and overflows are unlikely
1795 ++cache_info->revision_id;
Ken Chen26f01e42018-11-02 13:18:40 +08001796 } else {
1797 if (cache_info->params.max_samples != old_max_samples) {
1798 // If the maximum number of samples changes, the overhead of keeping the most recent
1799 // samples around is not considered worth the effort, so they are cleared instead.
1800 // All other parameters do not affect shared state: Changing these parameters does
1801 // not invalidate the samples, as they only affect aggregation and the conditions
1802 // under which servers are considered usable.
1803 res_cache_clear_stats_locked(cache_info);
1804 ++cache_info->revision_id;
1805 }
Bernie Innocenti45238a12018-12-04 14:57:48 +09001806 for (int j = 0; j < numservers; j++) {
Ken Chen26f01e42018-11-02 13:18:40 +08001807 freeaddrinfo(nsaddrinfo[j]);
1808 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001809 }
1810
1811 // Always update the search paths, since determining whether they actually changed is
1812 // complex due to the zero-padding, and probably not worth the effort. Cache-flushing
1813 // however is not // necessary, since the stored cache entries do contain the domain, not
1814 // just the host name.
1815 // code moved from res_init.c, load_domain_search_list
1816 strlcpy(cache_info->defdname, domains, sizeof(cache_info->defdname));
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001817 if ((cp = strchr(cache_info->defdname, '\n')) != NULL) *cp = '\0';
Bernie Innocenti55864192018-08-30 04:05:20 +09001818
1819 cp = cache_info->defdname;
1820 offset = cache_info->dnsrch_offset;
1821 while (offset < cache_info->dnsrch_offset + MAXDNSRCH) {
1822 while (*cp == ' ' || *cp == '\t') /* skip leading white space */
1823 cp++;
1824 if (*cp == '\0') /* stop if nothing more to do */
1825 break;
1826 *offset++ = cp - cache_info->defdname; /* record this search domain */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001827 while (*cp) { /* zero-terminate it */
1828 if (*cp == ' ' || *cp == '\t') {
Bernie Innocenti55864192018-08-30 04:05:20 +09001829 *cp++ = '\0';
1830 break;
1831 }
1832 cp++;
1833 }
1834 }
1835 *offset = -1; /* cache_info->dnsrch_offset has MAXDNSRCH+1 items */
1836 }
1837
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001838 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001839 return 0;
1840}
1841
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001842static int resolv_is_nameservers_equal_locked(resolv_cache_info* cache_info, const char** servers,
1843 int numservers) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001844 if (cache_info->nscount != numservers) {
1845 return 0;
1846 }
1847
1848 // Compare each name server against current name servers.
1849 // TODO: this is incorrect if the list of current or previous nameservers
1850 // contains duplicates. This does not really matter because the framework
1851 // filters out duplicates, but we should probably fix it. It's also
1852 // insensitive to the order of the nameservers; we should probably fix that
1853 // too.
1854 for (int i = 0; i < numservers; i++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001855 for (int j = 0;; j++) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001856 if (j >= numservers) {
1857 return 0;
1858 }
1859 if (strcmp(cache_info->nameservers[i], servers[j]) == 0) {
1860 break;
1861 }
1862 }
1863 }
1864
1865 return 1;
1866}
1867
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001868static void free_nameservers_locked(resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001869 int i;
1870 for (i = 0; i < cache_info->nscount; i++) {
1871 free(cache_info->nameservers[i]);
1872 cache_info->nameservers[i] = NULL;
1873 if (cache_info->nsaddrinfo[i] != NULL) {
1874 freeaddrinfo(cache_info->nsaddrinfo[i]);
1875 cache_info->nsaddrinfo[i] = NULL;
1876 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001877 cache_info->nsstats[i].sample_count = cache_info->nsstats[i].sample_next = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +09001878 }
1879 cache_info->nscount = 0;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001880 res_cache_clear_stats_locked(cache_info);
Bernie Innocenti55864192018-08-30 04:05:20 +09001881 ++cache_info->revision_id;
1882}
1883
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001884void _resolv_populate_res_for_net(res_state statp) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001885 if (statp == NULL) {
1886 return;
1887 }
1888
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001889 pthread_once(&_res_cache_once, res_cache_init);
1890 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001891
ckenb1a69a42018-12-01 17:45:18 +09001892 resolv_cache_info* info = find_cache_info_locked(statp->netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001893 if (info != NULL) {
1894 int nserv;
1895 struct addrinfo* ai;
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001896 VLOG << __func__ << ": " << statp->netid;
Bernie Innocenti55864192018-08-30 04:05:20 +09001897 for (nserv = 0; nserv < MAXNS; nserv++) {
1898 ai = info->nsaddrinfo[nserv];
1899 if (ai == NULL) {
1900 break;
1901 }
1902
1903 if ((size_t) ai->ai_addrlen <= sizeof(statp->_u._ext.ext->nsaddrs[0])) {
1904 if (statp->_u._ext.ext != NULL) {
1905 memcpy(&statp->_u._ext.ext->nsaddrs[nserv], ai->ai_addr, ai->ai_addrlen);
1906 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
1907 } else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001908 if ((size_t) ai->ai_addrlen <= sizeof(statp->nsaddr_list[0])) {
1909 memcpy(&statp->nsaddr_list[nserv], ai->ai_addr, ai->ai_addrlen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001910 } else {
1911 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
1912 }
1913 }
1914 } else {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001915 VLOG << __func__ << ": found too long addrlen";
Bernie Innocenti55864192018-08-30 04:05:20 +09001916 }
1917 }
1918 statp->nscount = nserv;
1919 // now do search domains. Note that we cache the offsets as this code runs alot
1920 // but the setting/offset-computer only runs when set/changed
1921 // WARNING: Don't use str*cpy() here, this string contains zeroes.
1922 memcpy(statp->defdname, info->defdname, sizeof(statp->defdname));
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +09001923 char** pp = statp->dnsrch;
1924 int* p = info->dnsrch_offset;
Bernie Innocenti55864192018-08-30 04:05:20 +09001925 while (pp < statp->dnsrch + MAXDNSRCH && *p != -1) {
1926 *pp++ = &statp->defdname[0] + *p++;
1927 }
1928 }
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001929 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001930}
1931
1932/* Resolver reachability statistics. */
1933
Bernie Innocenti189eb502018-10-01 23:10:18 +09001934static void _res_cache_add_stats_sample_locked(res_stats* stats, const res_sample* sample,
1935 int max_samples) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001936 // Note: This function expects max_samples > 0, otherwise a (harmless) modification of the
1937 // allocated but supposedly unused memory for samples[0] will happen
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001938 VLOG << __func__ << ": adding sample to stats, next = " << stats->sample_next
1939 << ", count = " << stats->sample_count;
Bernie Innocenti55864192018-08-30 04:05:20 +09001940 stats->samples[stats->sample_next] = *sample;
1941 if (stats->sample_count < max_samples) {
1942 ++stats->sample_count;
1943 }
1944 if (++stats->sample_next >= max_samples) {
1945 stats->sample_next = 0;
1946 }
1947}
1948
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001949static void res_cache_clear_stats_locked(resolv_cache_info* cache_info) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001950 if (cache_info) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001951 for (int i = 0; i < MAXNS; ++i) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001952 cache_info->nsstats->sample_count = cache_info->nsstats->sample_next = 0;
1953 }
1954 }
1955}
1956
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001957int android_net_res_stats_get_info_for_net(unsigned netid, int* nscount,
1958 struct sockaddr_storage servers[MAXNS], int* dcount,
1959 char domains[MAXDNSRCH][MAXDNSRCHPATH],
1960 struct __res_params* params,
Bernie Innocenti189eb502018-10-01 23:10:18 +09001961 struct res_stats stats[MAXNS]) {
Bernie Innocenti55864192018-08-30 04:05:20 +09001962 int revision_id = -1;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001963 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09001964
ckenb1a69a42018-12-01 17:45:18 +09001965 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09001966 if (info) {
1967 if (info->nscount > MAXNS) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001968 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001969 VLOG << __func__ << ": nscount " << info->nscount << " > MAXNS " << MAXNS;
Bernie Innocenti55864192018-08-30 04:05:20 +09001970 errno = EFAULT;
1971 return -1;
1972 }
1973 int i;
1974 for (i = 0; i < info->nscount; i++) {
1975 // Verify that the following assumptions are held, failure indicates corruption:
1976 // - getaddrinfo() may never return a sockaddr > sockaddr_storage
1977 // - all addresses are valid
1978 // - there is only one address per addrinfo thanks to numeric resolution
1979 int addrlen = info->nsaddrinfo[i]->ai_addrlen;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001980 if (addrlen < (int) sizeof(struct sockaddr) || addrlen > (int) sizeof(servers[0])) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001981 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001982 VLOG << __func__ << ": nsaddrinfo[" << i << "].ai_addrlen == " << addrlen;
Bernie Innocenti55864192018-08-30 04:05:20 +09001983 errno = EMSGSIZE;
1984 return -1;
1985 }
1986 if (info->nsaddrinfo[i]->ai_addr == NULL) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001987 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001988 VLOG << __func__ << ": nsaddrinfo[" << i << "].ai_addr == NULL";
Bernie Innocenti55864192018-08-30 04:05:20 +09001989 errno = ENOENT;
1990 return -1;
1991 }
1992 if (info->nsaddrinfo[i]->ai_next != NULL) {
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09001993 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001994 VLOG << __func__ << ": nsaddrinfo[" << i << "].ai_next != NULL";
Bernie Innocenti55864192018-08-30 04:05:20 +09001995 errno = ENOTUNIQ;
1996 return -1;
1997 }
1998 }
1999 *nscount = info->nscount;
2000 for (i = 0; i < info->nscount; i++) {
2001 memcpy(&servers[i], info->nsaddrinfo[i]->ai_addr, info->nsaddrinfo[i]->ai_addrlen);
2002 stats[i] = info->nsstats[i];
2003 }
2004 for (i = 0; i < MAXDNSRCH; i++) {
2005 const char* cur_domain = info->defdname + info->dnsrch_offset[i];
2006 // dnsrch_offset[i] can either be -1 or point to an empty string to indicate the end
2007 // of the search offsets. Checking for < 0 is not strictly necessary, but safer.
2008 // TODO: Pass in a search domain array instead of a string to
Bernie Innocenti189eb502018-10-01 23:10:18 +09002009 // resolv_set_nameservers_for_net() and make this double check unnecessary.
Bernie Innocenti55864192018-08-30 04:05:20 +09002010 if (info->dnsrch_offset[i] < 0 ||
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002011 ((size_t) info->dnsrch_offset[i]) >= sizeof(info->defdname) || !cur_domain[0]) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002012 break;
2013 }
2014 strlcpy(domains[i], cur_domain, MAXDNSRCHPATH);
2015 }
2016 *dcount = i;
2017 *params = info->params;
2018 revision_id = info->revision_id;
2019 }
2020
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09002021 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09002022 return revision_id;
2023}
2024
Bernie Innocenti189eb502018-10-01 23:10:18 +09002025int resolv_cache_get_resolver_stats(unsigned netid, __res_params* params, res_stats stats[MAXNS]) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002026 int revision_id = -1;
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09002027 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09002028
ckenb1a69a42018-12-01 17:45:18 +09002029 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09002030 if (info) {
2031 memcpy(stats, info->nsstats, sizeof(info->nsstats));
2032 *params = info->params;
2033 revision_id = info->revision_id;
2034 }
2035
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09002036 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09002037 return revision_id;
2038}
2039
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09002040void _resolv_cache_add_resolver_stats_sample(unsigned netid, int revision_id, int ns,
Bernie Innocenti189eb502018-10-01 23:10:18 +09002041 const res_sample* sample, int max_samples) {
Bernie Innocenti55864192018-08-30 04:05:20 +09002042 if (max_samples <= 0) return;
2043
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09002044 pthread_mutex_lock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09002045
ckenb1a69a42018-12-01 17:45:18 +09002046 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti55864192018-08-30 04:05:20 +09002047
2048 if (info && info->revision_id == revision_id) {
2049 _res_cache_add_stats_sample_locked(&info->nsstats[ns], sample, max_samples);
2050 }
2051
Bernie Innocenti84ec88d2018-09-27 13:44:29 +09002052 pthread_mutex_unlock(&res_cache_list_lock);
Bernie Innocenti55864192018-08-30 04:05:20 +09002053}