blob: 68dc48b5c65e0ab0423a6159429b7f612d0d3e35 [file] [log] [blame]
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
Ken Chen5471dca2019-04-15 15:25:35 +080029#define LOG_TAG "resolv"
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +090030
Bernie Innocenti758005f2019-02-19 18:08:36 +090031#include "resolv_cache.h"
32
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090033#include <resolv.h>
34#include <stdarg.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090035#include <stdlib.h>
36#include <string.h>
37#include <time.h>
Luke Huang2dac4382019-06-24 13:28:44 +080038#include <algorithm>
Ken Chen92bed612018-12-22 21:46:55 +080039#include <mutex>
Luke Huang2dac4382019-06-24 13:28:44 +080040#include <set>
Mike Yuc7649d12019-05-22 15:28:07 +080041#include <string>
Luke Huange126fbe2019-07-20 17:36:30 +080042#include <unordered_map>
Luke Huang2dac4382019-06-24 13:28:44 +080043#include <vector>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090044
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +090045#include <arpa/inet.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090046#include <arpa/nameser.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090047#include <errno.h>
48#include <linux/if.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090049#include <net/if.h>
50#include <netdb.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090051
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +090052#include <android-base/logging.h>
waynemaa74195e2019-01-18 14:02:31 +080053#include <android-base/parseint.h>
Luke Huange126fbe2019-07-20 17:36:30 +080054#include <android-base/stringprintf.h>
Luke Huang2dac4382019-06-24 13:28:44 +080055#include <android-base/strings.h>
Ken Chen92bed612018-12-22 21:46:55 +080056#include <android-base/thread_annotations.h>
Bernie Innocenti758005f2019-02-19 18:08:36 +090057#include <android/multinetwork.h> // ResNsendFlags
Bernie Innocentiafaacf72018-08-30 07:34:37 +090058
waynemaa74195e2019-01-18 14:02:31 +080059#include <server_configurable_flags/get_flags.h>
60
Mike Yu34433c62019-08-20 20:17:36 +080061#include "res_debug.h"
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090062#include "resolv_private.h"
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090063
Mike Yu34433c62019-08-20 20:17:36 +080064using android::base::StringAppendF;
Bernie Innocenti3952ccc2019-03-03 19:39:53 +090065
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090066/* This code implements a small and *simple* DNS resolver cache.
67 *
68 * It is only used to cache DNS answers for a time defined by the smallest TTL
69 * among the answer records in order to reduce DNS traffic. It is not supposed
70 * to be a full DNS cache, since we plan to implement that in the future in a
71 * dedicated process running on the system.
72 *
73 * Note that its design is kept simple very intentionally, i.e.:
74 *
75 * - it takes raw DNS query packet data as input, and returns raw DNS
76 * answer packet data as output
77 *
78 * (this means that two similar queries that encode the DNS name
79 * differently will be treated distinctly).
80 *
81 * the smallest TTL value among the answer records are used as the time
82 * to keep an answer in the cache.
83 *
84 * this is bad, but we absolutely want to avoid parsing the answer packets
85 * (and should be solved by the later full DNS cache process).
86 *
87 * - the implementation is just a (query-data) => (answer-data) hash table
88 * with a trivial least-recently-used expiration policy.
89 *
90 * Doing this keeps the code simple and avoids to deal with a lot of things
91 * that a full DNS cache is expected to do.
92 *
93 * The API is also very simple:
94 *
Mike Yud1ec2542019-06-06 17:17:53 +080095 * - the client calls resolv_cache_lookup() before performing a query
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090096 *
Bernie Innocenti802eccd2019-10-03 15:11:22 +090097 * If the function returns RESOLV_CACHE_FOUND, a copy of the answer data
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090098 * has been copied into the client-provided answer buffer.
99 *
Bernie Innocenti802eccd2019-10-03 15:11:22 +0900100 * If the function returns RESOLV_CACHE_NOTFOUND, the client should perform
Mike Yud1ec2542019-06-06 17:17:53 +0800101 * a request normally, *then* call resolv_cache_add() to add the received
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900102 * answer to the cache.
103 *
Bernie Innocenti802eccd2019-10-03 15:11:22 +0900104 * If the function returns RESOLV_CACHE_UNSUPPORTED, the client should
Mike Yud1ec2542019-06-06 17:17:53 +0800105 * perform a request normally, and *not* call resolv_cache_add()
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900106 *
Bernie Innocenti802eccd2019-10-03 15:11:22 +0900107 * Note that RESOLV_CACHE_UNSUPPORTED is also returned if the answer buffer
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900108 * is too short to accomodate the cached result.
109 */
110
Bernie Innocenti802eccd2019-10-03 15:11:22 +0900111/* Default number of entries kept in the cache. This value has been
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900112 * determined by browsing through various sites and counting the number
113 * of corresponding requests. Keep in mind that our framework is currently
114 * performing two requests per name lookup (one for IPv4, the other for IPv6)
115 *
116 * www.google.com 4
117 * www.ysearch.com 6
118 * www.amazon.com 8
119 * www.nytimes.com 22
120 * www.espn.com 28
121 * www.msn.com 28
122 * www.lemonde.fr 35
123 *
124 * (determined in 2009-2-17 from Paris, France, results may vary depending
125 * on location)
126 *
127 * most high-level websites use lots of media/ad servers with different names
128 * but these are generally reused when browsing through the site.
129 *
130 * As such, a value of 64 should be relatively comfortable at the moment.
131 *
132 * ******************************************
133 * * NOTE - this has changed.
134 * * 1) we've added IPv6 support so each dns query results in 2 responses
135 * * 2) we've made this a system-wide cache, so the cost is less (it's not
136 * * duplicated in each process) and the need is greater (more processes
137 * * making different requests).
138 * * Upping by 2x for IPv6
139 * * Upping by another 5x for the centralized nature
140 * *****************************************
141 */
Bernie Innocentic4f469a2019-10-03 15:50:06 +0900142const int CONFIG_MAX_ENTRIES = 64 * 2 * 5;
Bernie Innocenti136af7b2018-10-01 20:46:20 +0900143
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900144static time_t _time_now(void) {
145 struct timeval tv;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900146
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900147 gettimeofday(&tv, NULL);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900148 return tv.tv_sec;
149}
150
151/* reminder: the general format of a DNS packet is the following:
152 *
153 * HEADER (12 bytes)
154 * QUESTION (variable)
155 * ANSWER (variable)
156 * AUTHORITY (variable)
157 * ADDITIONNAL (variable)
158 *
159 * the HEADER is made of:
160 *
161 * ID : 16 : 16-bit unique query identification field
162 *
163 * QR : 1 : set to 0 for queries, and 1 for responses
164 * Opcode : 4 : set to 0 for queries
165 * AA : 1 : set to 0 for queries
166 * TC : 1 : truncation flag, will be set to 0 in queries
167 * RD : 1 : recursion desired
168 *
169 * RA : 1 : recursion available (0 in queries)
170 * Z : 3 : three reserved zero bits
171 * RCODE : 4 : response code (always 0=NOERROR in queries)
172 *
173 * QDCount: 16 : question count
174 * ANCount: 16 : Answer count (0 in queries)
175 * NSCount: 16: Authority Record count (0 in queries)
176 * ARCount: 16: Additionnal Record count (0 in queries)
177 *
178 * the QUESTION is made of QDCount Question Record (QRs)
179 * the ANSWER is made of ANCount RRs
180 * the AUTHORITY is made of NSCount RRs
181 * the ADDITIONNAL is made of ARCount RRs
182 *
183 * Each Question Record (QR) is made of:
184 *
185 * QNAME : variable : Query DNS NAME
186 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
187 * CLASS : 16 : class of query (IN=1)
188 *
189 * Each Resource Record (RR) is made of:
190 *
191 * NAME : variable : DNS NAME
192 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
193 * CLASS : 16 : class of query (IN=1)
194 * TTL : 32 : seconds to cache this RR (0=none)
195 * RDLENGTH: 16 : size of RDDATA in bytes
196 * RDDATA : variable : RR data (depends on TYPE)
197 *
198 * Each QNAME contains a domain name encoded as a sequence of 'labels'
199 * terminated by a zero. Each label has the following format:
200 *
201 * LEN : 8 : lenght of label (MUST be < 64)
202 * NAME : 8*LEN : label length (must exclude dots)
203 *
204 * A value of 0 in the encoding is interpreted as the 'root' domain and
205 * terminates the encoding. So 'www.android.com' will be encoded as:
206 *
207 * <3>www<7>android<3>com<0>
208 *
209 * Where <n> represents the byte with value 'n'
210 *
211 * Each NAME reflects the QNAME of the question, but has a slightly more
212 * complex encoding in order to provide message compression. This is achieved
213 * by using a 2-byte pointer, with format:
214 *
215 * TYPE : 2 : 0b11 to indicate a pointer, 0b01 and 0b10 are reserved
216 * OFFSET : 14 : offset to another part of the DNS packet
217 *
218 * The offset is relative to the start of the DNS packet and must point
219 * A pointer terminates the encoding.
220 *
221 * The NAME can be encoded in one of the following formats:
222 *
223 * - a sequence of simple labels terminated by 0 (like QNAMEs)
224 * - a single pointer
225 * - a sequence of simple labels terminated by a pointer
226 *
227 * A pointer shall always point to either a pointer of a sequence of
228 * labels (which can themselves be terminated by either a 0 or a pointer)
229 *
230 * The expanded length of a given domain name should not exceed 255 bytes.
231 *
232 * NOTE: we don't parse the answer packets, so don't need to deal with NAME
233 * records, only QNAMEs.
234 */
235
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900236#define DNS_HEADER_SIZE 12
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900237
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900238#define DNS_TYPE_A "\00\01" /* big-endian decimal 1 */
239#define DNS_TYPE_PTR "\00\014" /* big-endian decimal 12 */
240#define DNS_TYPE_MX "\00\017" /* big-endian decimal 15 */
241#define DNS_TYPE_AAAA "\00\034" /* big-endian decimal 28 */
242#define DNS_TYPE_ALL "\00\0377" /* big-endian decimal 255 */
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900243
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900244#define DNS_CLASS_IN "\00\01" /* big-endian decimal 1 */
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900245
Bernie Innocenti802eccd2019-10-03 15:11:22 +0900246struct DnsPacket {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900247 const uint8_t* base;
248 const uint8_t* end;
249 const uint8_t* cursor;
Bernie Innocenti802eccd2019-10-03 15:11:22 +0900250};
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900251
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900252static void _dnsPacket_init(DnsPacket* packet, const uint8_t* buff, int bufflen) {
253 packet->base = buff;
254 packet->end = buff + bufflen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900255 packet->cursor = buff;
256}
257
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900258static void _dnsPacket_rewind(DnsPacket* packet) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900259 packet->cursor = packet->base;
260}
261
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900262static void _dnsPacket_skip(DnsPacket* packet, int count) {
263 const uint8_t* p = packet->cursor + count;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900264
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900265 if (p > packet->end) p = packet->end;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900266
267 packet->cursor = p;
268}
269
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900270static int _dnsPacket_readInt16(DnsPacket* packet) {
271 const uint8_t* p = packet->cursor;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900272
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900273 if (p + 2 > packet->end) return -1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900274
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900275 packet->cursor = p + 2;
276 return (p[0] << 8) | p[1];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900277}
278
Bernie Innocenti9c575932018-09-07 21:10:25 +0900279/** QUERY CHECKING **/
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900280
281/* check bytes in a dns packet. returns 1 on success, 0 on failure.
282 * the cursor is only advanced in the case of success
283 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900284static int _dnsPacket_checkBytes(DnsPacket* packet, int numBytes, const void* bytes) {
285 const uint8_t* p = packet->cursor;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900286
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900287 if (p + numBytes > packet->end) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900288
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900289 if (memcmp(p, bytes, numBytes) != 0) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900290
291 packet->cursor = p + numBytes;
292 return 1;
293}
294
295/* parse and skip a given QNAME stored in a query packet,
296 * from the current cursor position. returns 1 on success,
297 * or 0 for malformed data.
298 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900299static int _dnsPacket_checkQName(DnsPacket* packet) {
300 const uint8_t* p = packet->cursor;
301 const uint8_t* end = packet->end;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900302
303 for (;;) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900304 int c;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900305
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900306 if (p >= end) break;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900307
308 c = *p++;
309
310 if (c == 0) {
311 packet->cursor = p;
312 return 1;
313 }
314
315 /* we don't expect label compression in QNAMEs */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900316 if (c >= 64) break;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900317
318 p += c;
319 /* we rely on the bound check at the start
320 * of the loop here */
321 }
322 /* malformed data */
Ken Chenffc224a2019-03-19 17:41:28 +0800323 LOG(INFO) << __func__ << ": malformed QNAME";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900324 return 0;
325}
326
327/* parse and skip a given QR stored in a packet.
328 * returns 1 on success, and 0 on failure
329 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900330static int _dnsPacket_checkQR(DnsPacket* packet) {
331 if (!_dnsPacket_checkQName(packet)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900332
333 /* TYPE must be one of the things we support */
334 if (!_dnsPacket_checkBytes(packet, 2, DNS_TYPE_A) &&
335 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_PTR) &&
336 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_MX) &&
337 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_AAAA) &&
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900338 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_ALL)) {
Ken Chenffc224a2019-03-19 17:41:28 +0800339 LOG(INFO) << __func__ << ": unsupported TYPE";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900340 return 0;
341 }
342 /* CLASS must be IN */
343 if (!_dnsPacket_checkBytes(packet, 2, DNS_CLASS_IN)) {
Ken Chenffc224a2019-03-19 17:41:28 +0800344 LOG(INFO) << __func__ << ": unsupported CLASS";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900345 return 0;
346 }
347
348 return 1;
349}
350
351/* check the header of a DNS Query packet, return 1 if it is one
352 * type of query we can cache, or 0 otherwise
353 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900354static int _dnsPacket_checkQuery(DnsPacket* packet) {
355 const uint8_t* p = packet->base;
356 int qdCount, anCount, dnCount, arCount;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900357
358 if (p + DNS_HEADER_SIZE > packet->end) {
Ken Chenffc224a2019-03-19 17:41:28 +0800359 LOG(INFO) << __func__ << ": query packet too small";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900360 return 0;
361 }
362
363 /* QR must be set to 0, opcode must be 0 and AA must be 0 */
364 /* RA, Z, and RCODE must be 0 */
365 if ((p[2] & 0xFC) != 0 || (p[3] & 0xCF) != 0) {
Ken Chenffc224a2019-03-19 17:41:28 +0800366 LOG(INFO) << __func__ << ": query packet flags unsupported";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900367 return 0;
368 }
369
370 /* Note that we ignore the TC, RD, CD, and AD bits here for the
371 * following reasons:
372 *
373 * - there is no point for a query packet sent to a server
374 * to have the TC bit set, but the implementation might
375 * set the bit in the query buffer for its own needs
Mike Yuc7649d12019-05-22 15:28:07 +0800376 * between a resolv_cache_lookup and a resolv_cache_add.
377 * We should not freak out if this is the case.
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900378 *
379 * - we consider that the result from a query might depend on
380 * the RD, AD, and CD bits, so these bits
381 * should be used to differentiate cached result.
382 *
383 * this implies that these bits are checked when hashing or
384 * comparing query packets, but not TC
385 */
386
387 /* ANCOUNT, DNCOUNT and ARCOUNT must be 0 */
388 qdCount = (p[4] << 8) | p[5];
389 anCount = (p[6] << 8) | p[7];
390 dnCount = (p[8] << 8) | p[9];
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900391 arCount = (p[10] << 8) | p[11];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900392
393 if (anCount != 0 || dnCount != 0 || arCount > 1) {
Ken Chenffc224a2019-03-19 17:41:28 +0800394 LOG(INFO) << __func__ << ": query packet contains non-query records";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900395 return 0;
396 }
397
398 if (qdCount == 0) {
Ken Chenffc224a2019-03-19 17:41:28 +0800399 LOG(INFO) << __func__ << ": query packet doesn't contain query record";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900400 return 0;
401 }
402
403 /* Check QDCOUNT QRs */
404 packet->cursor = p + DNS_HEADER_SIZE;
405
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900406 for (; qdCount > 0; qdCount--)
407 if (!_dnsPacket_checkQR(packet)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900408
409 return 1;
410}
411
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900412/** QUERY HASHING SUPPORT
413 **
414 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKET HAS ALREADY
415 ** BEEN SUCCESFULLY CHECKED.
416 **/
417
418/* use 32-bit FNV hash function */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900419#define FNV_MULT 16777619U
420#define FNV_BASIS 2166136261U
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900421
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900422static unsigned _dnsPacket_hashBytes(DnsPacket* packet, int numBytes, unsigned hash) {
423 const uint8_t* p = packet->cursor;
424 const uint8_t* end = packet->end;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900425
426 while (numBytes > 0 && p < end) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900427 hash = hash * FNV_MULT ^ *p++;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900428 }
429 packet->cursor = p;
430 return hash;
431}
432
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900433static unsigned _dnsPacket_hashQName(DnsPacket* packet, unsigned hash) {
434 const uint8_t* p = packet->cursor;
435 const uint8_t* end = packet->end;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900436
437 for (;;) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900438 int c;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900439
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900440 if (p >= end) { /* should not happen */
chenbruceacb832c2019-02-20 19:45:50 +0800441 LOG(INFO) << __func__ << ": INTERNAL_ERROR: read-overflow";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900442 break;
443 }
444
445 c = *p++;
446
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900447 if (c == 0) break;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900448
449 if (c >= 64) {
chenbruceacb832c2019-02-20 19:45:50 +0800450 LOG(INFO) << __func__ << ": INTERNAL_ERROR: malformed domain";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900451 break;
452 }
453 if (p + c >= end) {
chenbruceacb832c2019-02-20 19:45:50 +0800454 LOG(INFO) << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900455 break;
456 }
457 while (c > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900458 hash = hash * FNV_MULT ^ *p++;
459 c -= 1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900460 }
461 }
462 packet->cursor = p;
463 return hash;
464}
465
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900466static unsigned _dnsPacket_hashQR(DnsPacket* packet, unsigned hash) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900467 hash = _dnsPacket_hashQName(packet, hash);
468 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TYPE and CLASS */
469 return hash;
470}
471
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900472static unsigned _dnsPacket_hashRR(DnsPacket* packet, unsigned hash) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900473 int rdlength;
474 hash = _dnsPacket_hashQR(packet, hash);
475 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TTL */
476 rdlength = _dnsPacket_readInt16(packet);
477 hash = _dnsPacket_hashBytes(packet, rdlength, hash); /* RDATA */
478 return hash;
479}
480
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900481static unsigned _dnsPacket_hashQuery(DnsPacket* packet) {
482 unsigned hash = FNV_BASIS;
483 int count, arcount;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900484 _dnsPacket_rewind(packet);
485
486 /* ignore the ID */
487 _dnsPacket_skip(packet, 2);
488
489 /* we ignore the TC bit for reasons explained in
490 * _dnsPacket_checkQuery().
491 *
492 * however we hash the RD bit to differentiate
493 * between answers for recursive and non-recursive
494 * queries.
495 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900496 hash = hash * FNV_MULT ^ (packet->base[2] & 1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900497
498 /* mark the first header byte as processed */
499 _dnsPacket_skip(packet, 1);
500
501 /* process the second header byte */
502 hash = _dnsPacket_hashBytes(packet, 1, hash);
503
504 /* read QDCOUNT */
505 count = _dnsPacket_readInt16(packet);
506
507 /* assume: ANcount and NScount are 0 */
508 _dnsPacket_skip(packet, 4);
509
510 /* read ARCOUNT */
511 arcount = _dnsPacket_readInt16(packet);
512
513 /* hash QDCOUNT QRs */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900514 for (; count > 0; count--) hash = _dnsPacket_hashQR(packet, hash);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900515
516 /* hash ARCOUNT RRs */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900517 for (; arcount > 0; arcount--) hash = _dnsPacket_hashRR(packet, hash);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900518
519 return hash;
520}
521
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900522/** QUERY COMPARISON
523 **
524 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKETS HAVE ALREADY
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900525 ** BEEN SUCCESSFULLY CHECKED.
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900526 **/
527
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900528static int _dnsPacket_isEqualDomainName(DnsPacket* pack1, DnsPacket* pack2) {
529 const uint8_t* p1 = pack1->cursor;
530 const uint8_t* end1 = pack1->end;
531 const uint8_t* p2 = pack2->cursor;
532 const uint8_t* end2 = pack2->end;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900533
534 for (;;) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900535 int c1, c2;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900536
537 if (p1 >= end1 || p2 >= end2) {
chenbruceacb832c2019-02-20 19:45:50 +0800538 LOG(INFO) << __func__ << ": INTERNAL_ERROR: read-overflow";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900539 break;
540 }
541 c1 = *p1++;
542 c2 = *p2++;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900543 if (c1 != c2) break;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900544
545 if (c1 == 0) {
546 pack1->cursor = p1;
547 pack2->cursor = p2;
548 return 1;
549 }
550 if (c1 >= 64) {
chenbruceacb832c2019-02-20 19:45:50 +0800551 LOG(INFO) << __func__ << ": INTERNAL_ERROR: malformed domain";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900552 break;
553 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900554 if ((p1 + c1 > end1) || (p2 + c1 > end2)) {
chenbruceacb832c2019-02-20 19:45:50 +0800555 LOG(INFO) << __func__ << ": INTERNAL_ERROR: simple label read-overflow";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900556 break;
557 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900558 if (memcmp(p1, p2, c1) != 0) break;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900559 p1 += c1;
560 p2 += c1;
561 /* we rely on the bound checks at the start of the loop */
562 }
563 /* not the same, or one is malformed */
Ken Chenffc224a2019-03-19 17:41:28 +0800564 LOG(INFO) << __func__ << ": different DN";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900565 return 0;
566}
567
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900568static int _dnsPacket_isEqualBytes(DnsPacket* pack1, DnsPacket* pack2, int numBytes) {
569 const uint8_t* p1 = pack1->cursor;
570 const uint8_t* p2 = pack2->cursor;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900571
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900572 if (p1 + numBytes > pack1->end || p2 + numBytes > pack2->end) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900573
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900574 if (memcmp(p1, p2, numBytes) != 0) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900575
576 pack1->cursor += numBytes;
577 pack2->cursor += numBytes;
578 return 1;
579}
580
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900581static int _dnsPacket_isEqualQR(DnsPacket* pack1, DnsPacket* pack2) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900582 /* compare domain name encoding + TYPE + CLASS */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900583 if (!_dnsPacket_isEqualDomainName(pack1, pack2) ||
584 !_dnsPacket_isEqualBytes(pack1, pack2, 2 + 2))
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900585 return 0;
586
587 return 1;
588}
589
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900590static int _dnsPacket_isEqualRR(DnsPacket* pack1, DnsPacket* pack2) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900591 int rdlength1, rdlength2;
592 /* compare query + TTL */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900593 if (!_dnsPacket_isEqualQR(pack1, pack2) || !_dnsPacket_isEqualBytes(pack1, pack2, 4)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900594
595 /* compare RDATA */
596 rdlength1 = _dnsPacket_readInt16(pack1);
597 rdlength2 = _dnsPacket_readInt16(pack2);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900598 if (rdlength1 != rdlength2 || !_dnsPacket_isEqualBytes(pack1, pack2, rdlength1)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900599
600 return 1;
601}
602
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900603static int _dnsPacket_isEqualQuery(DnsPacket* pack1, DnsPacket* pack2) {
604 int count1, count2, arcount1, arcount2;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900605
606 /* compare the headers, ignore most fields */
607 _dnsPacket_rewind(pack1);
608 _dnsPacket_rewind(pack2);
609
610 /* compare RD, ignore TC, see comment in _dnsPacket_checkQuery */
611 if ((pack1->base[2] & 1) != (pack2->base[2] & 1)) {
Ken Chenffc224a2019-03-19 17:41:28 +0800612 LOG(INFO) << __func__ << ": different RD";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900613 return 0;
614 }
615
616 if (pack1->base[3] != pack2->base[3]) {
Ken Chenffc224a2019-03-19 17:41:28 +0800617 LOG(INFO) << __func__ << ": different CD or AD";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900618 return 0;
619 }
620
621 /* mark ID and header bytes as compared */
622 _dnsPacket_skip(pack1, 4);
623 _dnsPacket_skip(pack2, 4);
624
625 /* compare QDCOUNT */
626 count1 = _dnsPacket_readInt16(pack1);
627 count2 = _dnsPacket_readInt16(pack2);
628 if (count1 != count2 || count1 < 0) {
Ken Chenffc224a2019-03-19 17:41:28 +0800629 LOG(INFO) << __func__ << ": different QDCOUNT";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900630 return 0;
631 }
632
633 /* assume: ANcount and NScount are 0 */
634 _dnsPacket_skip(pack1, 4);
635 _dnsPacket_skip(pack2, 4);
636
637 /* compare ARCOUNT */
638 arcount1 = _dnsPacket_readInt16(pack1);
639 arcount2 = _dnsPacket_readInt16(pack2);
640 if (arcount1 != arcount2 || arcount1 < 0) {
Ken Chenffc224a2019-03-19 17:41:28 +0800641 LOG(INFO) << __func__ << ": different ARCOUNT";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900642 return 0;
643 }
644
645 /* compare the QDCOUNT QRs */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900646 for (; count1 > 0; count1--) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900647 if (!_dnsPacket_isEqualQR(pack1, pack2)) {
Ken Chenffc224a2019-03-19 17:41:28 +0800648 LOG(INFO) << __func__ << ": different QR";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900649 return 0;
650 }
651 }
652
653 /* compare the ARCOUNT RRs */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900654 for (; arcount1 > 0; arcount1--) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900655 if (!_dnsPacket_isEqualRR(pack1, pack2)) {
Ken Chenffc224a2019-03-19 17:41:28 +0800656 LOG(INFO) << __func__ << ": different additional RR";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900657 return 0;
658 }
659 }
660 return 1;
661}
662
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900663/* cache entry. for simplicity, 'hash' and 'hlink' are inlined in this
664 * structure though they are conceptually part of the hash table.
665 *
666 * similarly, mru_next and mru_prev are part of the global MRU list
667 */
Bernie Innocenti802eccd2019-10-03 15:11:22 +0900668struct Entry {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900669 unsigned int hash; /* hash value */
670 struct Entry* hlink; /* next in collision chain */
671 struct Entry* mru_prev;
672 struct Entry* mru_next;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900673
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900674 const uint8_t* query;
675 int querylen;
676 const uint8_t* answer;
677 int answerlen;
678 time_t expires; /* time_t when the entry isn't valid any more */
679 int id; /* for debugging purpose */
Bernie Innocenti802eccd2019-10-03 15:11:22 +0900680};
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900681
Bernie Innocenti9c575932018-09-07 21:10:25 +0900682/*
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900683 * Find the TTL for a negative DNS result. This is defined as the minimum
684 * of the SOA records TTL and the MINIMUM-TTL field (RFC-2308).
685 *
686 * Return 0 if not found.
687 */
chenbrucec51f1212019-09-12 16:59:33 +0800688static uint32_t answer_getNegativeTTL(ns_msg handle) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900689 int n, nscount;
chenbrucec51f1212019-09-12 16:59:33 +0800690 uint32_t result = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900691 ns_rr rr;
692
693 nscount = ns_msg_count(handle, ns_s_ns);
694 for (n = 0; n < nscount; n++) {
695 if ((ns_parserr(&handle, ns_s_ns, n, &rr) == 0) && (ns_rr_type(rr) == ns_t_soa)) {
chenbrucec51f1212019-09-12 16:59:33 +0800696 const uint8_t* rdata = ns_rr_rdata(rr); // find the data
697 const uint8_t* edata = rdata + ns_rr_rdlen(rr); // add the len to find the end
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900698 int len;
chenbrucec51f1212019-09-12 16:59:33 +0800699 uint32_t ttl, rec_result = rr.ttl;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900700
701 // find the MINIMUM-TTL field from the blob of binary data for this record
702 // skip the server name
703 len = dn_skipname(rdata, edata);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900704 if (len == -1) continue; // error skipping
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900705 rdata += len;
706
707 // skip the admin name
708 len = dn_skipname(rdata, edata);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900709 if (len == -1) continue; // error skipping
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900710 rdata += len;
711
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900712 if (edata - rdata != 5 * NS_INT32SZ) continue;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900713 // skip: serial number + refresh interval + retry interval + expiry
714 rdata += NS_INT32SZ * 4;
715 // finally read the MINIMUM TTL
chenbruce0d470422019-03-28 18:44:37 +0800716 ttl = ntohl(*reinterpret_cast<const uint32_t*>(rdata));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900717 if (ttl < rec_result) {
718 rec_result = ttl;
719 }
720 // Now that the record is read successfully, apply the new min TTL
721 if (n == 0 || rec_result < result) {
722 result = rec_result;
723 }
724 }
725 }
726 return result;
727}
728
Bernie Innocenti9c575932018-09-07 21:10:25 +0900729/*
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900730 * Parse the answer records and find the appropriate
731 * smallest TTL among the records. This might be from
732 * the answer records if found or from the SOA record
733 * if it's a negative result.
734 *
735 * The returned TTL is the number of seconds to
736 * keep the answer in the cache.
737 *
738 * In case of parse error zero (0) is returned which
739 * indicates that the answer shall not be cached.
740 */
chenbrucec51f1212019-09-12 16:59:33 +0800741static uint32_t answer_getTTL(const void* answer, int answerlen) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900742 ns_msg handle;
743 int ancount, n;
chenbrucec51f1212019-09-12 16:59:33 +0800744 uint32_t result, ttl;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900745 ns_rr rr;
746
747 result = 0;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900748 if (ns_initparse((const uint8_t*) answer, answerlen, &handle) >= 0) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900749 // get number of answer records
750 ancount = ns_msg_count(handle, ns_s_an);
751
752 if (ancount == 0) {
753 // a response with no answers? Cache this negative result.
754 result = answer_getNegativeTTL(handle);
755 } else {
756 for (n = 0; n < ancount; n++) {
757 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
chenbrucec51f1212019-09-12 16:59:33 +0800758 ttl = rr.ttl;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900759 if (n == 0 || ttl < result) {
760 result = ttl;
761 }
762 } else {
Ken Chenffc224a2019-03-19 17:41:28 +0800763 PLOG(INFO) << __func__ << ": ns_parserr failed ancount no = " << n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900764 }
765 }
766 }
767 } else {
Ken Chenffc224a2019-03-19 17:41:28 +0800768 PLOG(INFO) << __func__ << ": ns_initparse failed";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900769 }
770
Ken Chenffc224a2019-03-19 17:41:28 +0800771 LOG(INFO) << __func__ << ": TTL = " << result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900772 return result;
773}
774
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900775static void entry_free(Entry* e) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900776 /* everything is allocated in a single memory block */
777 if (e) {
778 free(e);
779 }
780}
781
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +0900782static void entry_mru_remove(Entry* e) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900783 e->mru_prev->mru_next = e->mru_next;
784 e->mru_next->mru_prev = e->mru_prev;
785}
786
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +0900787static void entry_mru_add(Entry* e, Entry* list) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900788 Entry* first = list->mru_next;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900789
790 e->mru_next = first;
791 e->mru_prev = list;
792
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900793 list->mru_next = e;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900794 first->mru_prev = e;
795}
796
797/* compute the hash of a given entry, this is a hash of most
798 * data in the query (key) */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900799static unsigned entry_hash(const Entry* e) {
800 DnsPacket pack[1];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900801
802 _dnsPacket_init(pack, e->query, e->querylen);
803 return _dnsPacket_hashQuery(pack);
804}
805
806/* initialize an Entry as a search key, this also checks the input query packet
807 * returns 1 on success, or 0 in case of unsupported/malformed data */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900808static int entry_init_key(Entry* e, const void* query, int querylen) {
809 DnsPacket pack[1];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900810
811 memset(e, 0, sizeof(*e));
812
Bernie Innocenti9c575932018-09-07 21:10:25 +0900813 e->query = (const uint8_t*) query;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900814 e->querylen = querylen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900815 e->hash = entry_hash(e);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900816
Bernie Innocenti9c575932018-09-07 21:10:25 +0900817 _dnsPacket_init(pack, e->query, e->querylen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900818
819 return _dnsPacket_checkQuery(pack);
820}
821
822/* allocate a new entry as a cache node */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900823static Entry* entry_alloc(const Entry* init, const void* answer, int answerlen) {
824 Entry* e;
825 int size;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900826
827 size = sizeof(*e) + init->querylen + answerlen;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900828 e = (Entry*) calloc(size, 1);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900829 if (e == NULL) return e;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900830
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900831 e->hash = init->hash;
832 e->query = (const uint8_t*) (e + 1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900833 e->querylen = init->querylen;
834
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900835 memcpy((char*) e->query, init->query, e->querylen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900836
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900837 e->answer = e->query + e->querylen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900838 e->answerlen = answerlen;
839
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900840 memcpy((char*) e->answer, answer, e->answerlen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900841
842 return e;
843}
844
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900845static int entry_equals(const Entry* e1, const Entry* e2) {
846 DnsPacket pack1[1], pack2[1];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900847
848 if (e1->querylen != e2->querylen) {
849 return 0;
850 }
851 _dnsPacket_init(pack1, e1->query, e1->querylen);
852 _dnsPacket_init(pack2, e2->query, e2->querylen);
853
854 return _dnsPacket_isEqualQuery(pack1, pack2);
855}
856
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900857/* We use a simple hash table with external collision lists
858 * for simplicity, the hash-table fields 'hash' and 'hlink' are
859 * inlined in the Entry structure.
860 */
861
862/* Maximum time for a thread to wait for an pending request */
Ken Chen92bed612018-12-22 21:46:55 +0800863constexpr int PENDING_REQUEST_TIMEOUT = 20;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900864
Bernie Innocentic4f469a2019-10-03 15:50:06 +0900865// lock protecting everything in the resolve_cache_info structs (next ptr, etc)
866static std::mutex cache_mutex;
867static std::condition_variable cv;
868
869// Note that Cache is not thread-safe per se, access to its members must be protected
870// by an external mutex.
871//
872// TODO: move all cache manipulation code here and make data members private.
Bernie Innocenti802eccd2019-10-03 15:11:22 +0900873struct Cache {
Bernie Innocentic4f469a2019-10-03 15:50:06 +0900874 Cache() {
875 entries.resize(CONFIG_MAX_ENTRIES);
876 mru_list.mru_prev = mru_list.mru_next = &mru_list;
877 }
878 ~Cache() { flush(); }
879
880 void flush() {
881 for (int nn = 0; nn < CONFIG_MAX_ENTRIES; nn++) {
882 Entry** pnode = (Entry**)&entries[nn];
883
884 while (*pnode) {
885 Entry* node = *pnode;
886 *pnode = node->hlink;
887 entry_free(node);
888 }
889 }
890
891 flushPendingRequests();
892
893 mru_list.mru_next = mru_list.mru_prev = &mru_list;
894 num_entries = 0;
895 last_id = 0;
896
897 LOG(INFO) << "DNS cache flushed";
898 }
899
900 void flushPendingRequests() {
901 pending_req_info* ri = pending_requests.next;
902 while (ri) {
903 pending_req_info* tmp = ri;
904 ri = ri->next;
905 free(tmp);
906 }
907
908 pending_requests.next = nullptr;
909 cv.notify_all();
910 }
911
912 int num_entries = 0;
913
914 // TODO: convert to std::list
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900915 Entry mru_list;
Bernie Innocentic4f469a2019-10-03 15:50:06 +0900916 int last_id = 0;
917 std::vector<Entry> entries;
918
919 // TODO: convert to std::vector
Ken Chen92bed612018-12-22 21:46:55 +0800920 struct pending_req_info {
921 unsigned int hash;
922 struct pending_req_info* next;
Bernie Innocentic4f469a2019-10-03 15:50:06 +0900923 } pending_requests{};
Bernie Innocenti802eccd2019-10-03 15:11:22 +0900924};
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900925
Bernie Innocentic4f469a2019-10-03 15:50:06 +0900926// TODO: allocate with new
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900927struct resolv_cache_info {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900928 unsigned netid;
Bernie Innocentic4f469a2019-10-03 15:50:06 +0900929 Cache* cache; // TODO: use unique_ptr or embed
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900930 struct resolv_cache_info* next;
931 int nscount;
Mike Yuc7649d12019-05-22 15:28:07 +0800932 std::vector<std::string> nameservers;
933 struct addrinfo* nsaddrinfo[MAXNS]; // TODO: Use struct sockaddr_storage.
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900934 int revision_id; // # times the nameservers have been replaced
Bernie Innocenti758005f2019-02-19 18:08:36 +0900935 res_params params;
Bernie Innocentiac18b122018-10-01 23:10:18 +0900936 struct res_stats nsstats[MAXNS];
Luke Huang2dac4382019-06-24 13:28:44 +0800937 std::vector<std::string> search_domains;
Ken Chen92bed612018-12-22 21:46:55 +0800938 int wait_for_pending_req_timeout_count;
Luke Huange126fbe2019-07-20 17:36:30 +0800939 // Map format: ReturnCode:rate_denom
940 std::unordered_map<int, uint32_t> dns_event_subsampling_map;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900941};
942
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900943/* gets cache associated with a network, or NULL if none exists */
Bernie Innocenti802eccd2019-10-03 15:11:22 +0900944static Cache* find_named_cache_locked(unsigned netid) REQUIRES(cache_mutex);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900945
Ken Chen92bed612018-12-22 21:46:55 +0800946// Return true - if there is a pending request in |cache| matching |key|.
947// Return false - if no pending request is found matching the key. Optionally
948// link a new one if parameter append_if_not_found is true.
Bernie Innocenti802eccd2019-10-03 15:11:22 +0900949static bool cache_has_pending_request_locked(Cache* cache, const Entry* key,
Ken Chen92bed612018-12-22 21:46:55 +0800950 bool append_if_not_found) {
951 if (!cache || !key) return false;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900952
Bernie Innocenti802eccd2019-10-03 15:11:22 +0900953 Cache::pending_req_info* ri = cache->pending_requests.next;
954 Cache::pending_req_info* prev = &cache->pending_requests;
Ken Chen92bed612018-12-22 21:46:55 +0800955 while (ri) {
956 if (ri->hash == key->hash) {
957 return true;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900958 }
Ken Chen92bed612018-12-22 21:46:55 +0800959 prev = ri;
960 ri = ri->next;
961 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900962
Ken Chen92bed612018-12-22 21:46:55 +0800963 if (append_if_not_found) {
Bernie Innocenti802eccd2019-10-03 15:11:22 +0900964 ri = (Cache::pending_req_info*)calloc(1, sizeof(Cache::pending_req_info));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900965 if (ri) {
Ken Chen92bed612018-12-22 21:46:55 +0800966 ri->hash = key->hash;
967 prev->next = ri;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900968 }
969 }
Ken Chen92bed612018-12-22 21:46:55 +0800970 return false;
971}
972
973// Notify all threads that the cache entry |key| has become available
Bernie Innocenti802eccd2019-10-03 15:11:22 +0900974static void cache_notify_waiting_tid_locked(struct Cache* cache, const Entry* key) {
Ken Chen92bed612018-12-22 21:46:55 +0800975 if (!cache || !key) return;
976
Bernie Innocenti802eccd2019-10-03 15:11:22 +0900977 Cache::pending_req_info* ri = cache->pending_requests.next;
978 Cache::pending_req_info* prev = &cache->pending_requests;
Ken Chen92bed612018-12-22 21:46:55 +0800979 while (ri) {
980 if (ri->hash == key->hash) {
981 // remove item from list and destroy
982 prev->next = ri->next;
983 free(ri);
984 cv.notify_all();
985 return;
986 }
987 prev = ri;
988 ri = ri->next;
989 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900990}
991
Luke Huangba7bef92018-12-26 16:53:03 +0800992void _resolv_cache_query_failed(unsigned netid, const void* query, int querylen, uint32_t flags) {
993 // We should not notify with these flags.
994 if (flags & (ANDROID_RESOLV_NO_CACHE_STORE | ANDROID_RESOLV_NO_CACHE_LOOKUP)) {
995 return;
996 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900997 Entry key[1];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900998
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900999 if (!entry_init_key(key, query, querylen)) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001000
Ken Chen92bed612018-12-22 21:46:55 +08001001 std::lock_guard guard(cache_mutex);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001002
Bernie Innocenti802eccd2019-10-03 15:11:22 +09001003 Cache* cache = find_named_cache_locked(netid);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001004
1005 if (cache) {
Bernie Innocenti802eccd2019-10-03 15:11:22 +09001006 cache_notify_waiting_tid_locked(cache, key);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001007 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001008}
1009
Mike Yu34433c62019-08-20 20:17:36 +08001010static void cache_dump_mru_locked(Cache* cache) {
1011 std::string buf;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001012
Mike Yu34433c62019-08-20 20:17:36 +08001013 StringAppendF(&buf, "MRU LIST (%2d): ", cache->num_entries);
1014 for (Entry* e = cache->mru_list.mru_next; e != &cache->mru_list; e = e->mru_next) {
1015 StringAppendF(&buf, " %d", e->id);
1016 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001017
Mike Yu34433c62019-08-20 20:17:36 +08001018 LOG(INFO) << __func__ << ": " << buf;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001019}
1020
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001021/* This function tries to find a key within the hash table
1022 * In case of success, it will return a *pointer* to the hashed key.
1023 * In case of failure, it will return a *pointer* to NULL
1024 *
1025 * So, the caller must check '*result' to check for success/failure.
1026 *
1027 * The main idea is that the result can later be used directly in
Mike Yuc7649d12019-05-22 15:28:07 +08001028 * calls to resolv_cache_add or _resolv_cache_remove as the 'lookup'
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001029 * parameter. This makes the code simpler and avoids re-searching
1030 * for the key position in the htable.
1031 *
1032 * The result of a lookup_p is only valid until you alter the hash
1033 * table.
1034 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001035static Entry** _cache_lookup_p(Cache* cache, Entry* key) {
Bernie Innocentic4f469a2019-10-03 15:50:06 +09001036 int index = key->hash % CONFIG_MAX_ENTRIES;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001037 Entry** pnode = (Entry**) &cache->entries[index];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001038
1039 while (*pnode != NULL) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001040 Entry* node = *pnode;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001041
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001042 if (node == NULL) break;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001043
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001044 if (node->hash == key->hash && entry_equals(node, key)) break;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001045
1046 pnode = &node->hlink;
1047 }
1048 return pnode;
1049}
1050
1051/* Add a new entry to the hash table. 'lookup' must be the
1052 * result of an immediate previous failed _lookup_p() call
1053 * (i.e. with *lookup == NULL), and 'e' is the pointer to the
1054 * newly created entry
1055 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001056static void _cache_add_p(Cache* cache, Entry** lookup, Entry* e) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001057 *lookup = e;
1058 e->id = ++cache->last_id;
1059 entry_mru_add(e, &cache->mru_list);
1060 cache->num_entries += 1;
1061
chenbruceacb832c2019-02-20 19:45:50 +08001062 LOG(INFO) << __func__ << ": entry " << e->id << " added (count=" << cache->num_entries << ")";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001063}
1064
1065/* Remove an existing entry from the hash table,
1066 * 'lookup' must be the result of an immediate previous
1067 * and succesful _lookup_p() call.
1068 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001069static void _cache_remove_p(Cache* cache, Entry** lookup) {
1070 Entry* e = *lookup;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001071
chenbruceacb832c2019-02-20 19:45:50 +08001072 LOG(INFO) << __func__ << ": entry " << e->id << " removed (count=" << cache->num_entries - 1
1073 << ")";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001074
1075 entry_mru_remove(e);
1076 *lookup = e->hlink;
1077 entry_free(e);
1078 cache->num_entries -= 1;
1079}
1080
1081/* Remove the oldest entry from the hash table.
1082 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001083static void _cache_remove_oldest(Cache* cache) {
1084 Entry* oldest = cache->mru_list.mru_prev;
1085 Entry** lookup = _cache_lookup_p(cache, oldest);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001086
1087 if (*lookup == NULL) { /* should not happen */
chenbruceacb832c2019-02-20 19:45:50 +08001088 LOG(INFO) << __func__ << ": OLDEST NOT IN HTABLE ?";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001089 return;
1090 }
Ken Chenffc224a2019-03-19 17:41:28 +08001091 LOG(INFO) << __func__ << ": Cache full - removing oldest";
Mike Yufbfc27d2019-08-20 17:42:51 +08001092 res_pquery(oldest->query, oldest->querylen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001093 _cache_remove_p(cache, lookup);
1094}
1095
1096/* Remove all expired entries from the hash table.
1097 */
1098static void _cache_remove_expired(Cache* cache) {
1099 Entry* e;
1100 time_t now = _time_now();
1101
1102 for (e = cache->mru_list.mru_next; e != &cache->mru_list;) {
1103 // Entry is old, remove
1104 if (now >= e->expires) {
1105 Entry** lookup = _cache_lookup_p(cache, e);
1106 if (*lookup == NULL) { /* should not happen */
chenbruceacb832c2019-02-20 19:45:50 +08001107 LOG(INFO) << __func__ << ": ENTRY NOT IN HTABLE ?";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001108 return;
1109 }
1110 e = e->mru_next;
1111 _cache_remove_p(cache, lookup);
1112 } else {
1113 e = e->mru_next;
1114 }
1115 }
1116}
1117
Ken Chen92bed612018-12-22 21:46:55 +08001118// gets a resolv_cache_info associated with a network, or NULL if not found
1119static resolv_cache_info* find_cache_info_locked(unsigned netid) REQUIRES(cache_mutex);
1120
Mike Yud1ec2542019-06-06 17:17:53 +08001121ResolvCacheStatus resolv_cache_lookup(unsigned netid, const void* query, int querylen, void* answer,
1122 int answersize, int* answerlen, uint32_t flags) {
Luke Huanga1d74182019-03-19 17:30:36 +08001123 // Skip cache lookup, return RESOLV_CACHE_NOTFOUND directly so that it is
1124 // possible to cache the answer of this query.
Luke Huang40f5f492019-05-09 19:37:35 +08001125 // If ANDROID_RESOLV_NO_CACHE_STORE is set, return RESOLV_CACHE_SKIP to skip possible cache
1126 // storing.
Luke Huangba7bef92018-12-26 16:53:03 +08001127 if (flags & ANDROID_RESOLV_NO_CACHE_LOOKUP) {
Luke Huang40f5f492019-05-09 19:37:35 +08001128 return flags & ANDROID_RESOLV_NO_CACHE_STORE ? RESOLV_CACHE_SKIP : RESOLV_CACHE_NOTFOUND;
Luke Huangba7bef92018-12-26 16:53:03 +08001129 }
Ken Chen92bed612018-12-22 21:46:55 +08001130 Entry key;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001131 Entry** lookup;
1132 Entry* e;
1133 time_t now;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001134
chenbruceacb832c2019-02-20 19:45:50 +08001135 LOG(INFO) << __func__ << ": lookup";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001136
1137 /* we don't cache malformed queries */
Ken Chen92bed612018-12-22 21:46:55 +08001138 if (!entry_init_key(&key, query, querylen)) {
chenbruceacb832c2019-02-20 19:45:50 +08001139 LOG(INFO) << __func__ << ": unsupported query";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001140 return RESOLV_CACHE_UNSUPPORTED;
1141 }
1142 /* lookup cache */
Ken Chen92bed612018-12-22 21:46:55 +08001143 std::unique_lock lock(cache_mutex);
Mike Yu411ea7f2019-09-17 11:10:08 +08001144 android::base::ScopedLockAssertion assume_lock(cache_mutex);
Bernie Innocenti802eccd2019-10-03 15:11:22 +09001145 Cache* cache = find_named_cache_locked(netid);
Mike Yud1ec2542019-06-06 17:17:53 +08001146 if (cache == nullptr) {
Ken Chen92bed612018-12-22 21:46:55 +08001147 return RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001148 }
1149
1150 /* see the description of _lookup_p to understand this.
1151 * the function always return a non-NULL pointer.
1152 */
Ken Chen92bed612018-12-22 21:46:55 +08001153 lookup = _cache_lookup_p(cache, &key);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001154 e = *lookup;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001155
1156 if (e == NULL) {
Ken Chenffc224a2019-03-19 17:41:28 +08001157 LOG(INFO) << __func__ << ": NOT IN CACHE";
Luke Huangba7bef92018-12-26 16:53:03 +08001158 // If it is no-cache-store mode, we won't wait for possible query.
1159 if (flags & ANDROID_RESOLV_NO_CACHE_STORE) {
Ken Chen92bed612018-12-22 21:46:55 +08001160 return RESOLV_CACHE_SKIP;
Luke Huangba7bef92018-12-26 16:53:03 +08001161 }
Ken Chen92bed612018-12-22 21:46:55 +08001162
1163 if (!cache_has_pending_request_locked(cache, &key, true)) {
1164 return RESOLV_CACHE_NOTFOUND;
1165
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001166 } else {
Ken Chenffc224a2019-03-19 17:41:28 +08001167 LOG(INFO) << __func__ << ": Waiting for previous request";
Ken Chen92bed612018-12-22 21:46:55 +08001168 // wait until (1) timeout OR
1169 // (2) cv is notified AND no pending request matching the |key|
1170 // (cv notifier should delete pending request before sending notification.)
1171 bool ret = cv.wait_for(lock, std::chrono::seconds(PENDING_REQUEST_TIMEOUT),
1172 [netid, &cache, &key]() REQUIRES(cache_mutex) {
1173 // Must update cache as it could have been deleted
1174 cache = find_named_cache_locked(netid);
1175 return !cache_has_pending_request_locked(cache, &key, false);
1176 });
Ken Chen553b1172019-02-21 03:50:11 +08001177 if (!cache) {
1178 return RESOLV_CACHE_NOTFOUND;
1179 }
Ken Chen92bed612018-12-22 21:46:55 +08001180 if (ret == false) {
1181 resolv_cache_info* info = find_cache_info_locked(netid);
1182 if (info != NULL) {
1183 info->wait_for_pending_req_timeout_count++;
1184 }
1185 }
1186 lookup = _cache_lookup_p(cache, &key);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001187 e = *lookup;
1188 if (e == NULL) {
Ken Chen92bed612018-12-22 21:46:55 +08001189 return RESOLV_CACHE_NOTFOUND;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001190 }
1191 }
1192 }
1193
1194 now = _time_now();
1195
1196 /* remove stale entries here */
1197 if (now >= e->expires) {
Ken Chenffc224a2019-03-19 17:41:28 +08001198 LOG(INFO) << __func__ << ": NOT IN CACHE (STALE ENTRY " << *lookup << "DISCARDED)";
Mike Yufbfc27d2019-08-20 17:42:51 +08001199 res_pquery(e->query, e->querylen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001200 _cache_remove_p(cache, lookup);
Ken Chen92bed612018-12-22 21:46:55 +08001201 return RESOLV_CACHE_NOTFOUND;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001202 }
1203
1204 *answerlen = e->answerlen;
1205 if (e->answerlen > answersize) {
1206 /* NOTE: we return UNSUPPORTED if the answer buffer is too short */
Ken Chenffc224a2019-03-19 17:41:28 +08001207 LOG(INFO) << __func__ << ": ANSWER TOO LONG";
Ken Chen92bed612018-12-22 21:46:55 +08001208 return RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001209 }
1210
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001211 memcpy(answer, e->answer, e->answerlen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001212
1213 /* bump up this entry to the top of the MRU list */
1214 if (e != cache->mru_list.mru_next) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001215 entry_mru_remove(e);
1216 entry_mru_add(e, &cache->mru_list);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001217 }
1218
Ken Chenffc224a2019-03-19 17:41:28 +08001219 LOG(INFO) << __func__ << ": FOUND IN CACHE entry=" << e;
Ken Chen92bed612018-12-22 21:46:55 +08001220 return RESOLV_CACHE_FOUND;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001221}
1222
Mike Yud1ec2542019-06-06 17:17:53 +08001223int resolv_cache_add(unsigned netid, const void* query, int querylen, const void* answer,
1224 int answerlen) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001225 Entry key[1];
1226 Entry* e;
1227 Entry** lookup;
chenbrucec51f1212019-09-12 16:59:33 +08001228 uint32_t ttl;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001229 Cache* cache = NULL;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001230
1231 /* don't assume that the query has already been cached
1232 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001233 if (!entry_init_key(key, query, querylen)) {
chenbruceacb832c2019-02-20 19:45:50 +08001234 LOG(INFO) << __func__ << ": passed invalid query?";
Mike Yud1ec2542019-06-06 17:17:53 +08001235 return -EINVAL;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001236 }
1237
Ken Chen92bed612018-12-22 21:46:55 +08001238 std::lock_guard guard(cache_mutex);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001239
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001240 cache = find_named_cache_locked(netid);
Mike Yud1ec2542019-06-06 17:17:53 +08001241 if (cache == nullptr) {
1242 return -ENONET;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001243 }
1244
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001245 lookup = _cache_lookup_p(cache, key);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001246 e = *lookup;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001247
Luke Huanga1d74182019-03-19 17:30:36 +08001248 // Should only happen on ANDROID_RESOLV_NO_CACHE_LOOKUP
1249 if (e != NULL) {
chenbruceacb832c2019-02-20 19:45:50 +08001250 LOG(INFO) << __func__ << ": ALREADY IN CACHE (" << e << ") ? IGNORING ADD";
Bernie Innocenti802eccd2019-10-03 15:11:22 +09001251 cache_notify_waiting_tid_locked(cache, key);
Mike Yud1ec2542019-06-06 17:17:53 +08001252 return -EEXIST;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001253 }
1254
Bernie Innocentic4f469a2019-10-03 15:50:06 +09001255 if (cache->num_entries >= CONFIG_MAX_ENTRIES) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001256 _cache_remove_expired(cache);
Bernie Innocentic4f469a2019-10-03 15:50:06 +09001257 if (cache->num_entries >= CONFIG_MAX_ENTRIES) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001258 _cache_remove_oldest(cache);
1259 }
Luke Huanga1d74182019-03-19 17:30:36 +08001260 // TODO: It looks useless, remove below code after having test to prove it.
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001261 lookup = _cache_lookup_p(cache, key);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001262 e = *lookup;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001263 if (e != NULL) {
chenbruceacb832c2019-02-20 19:45:50 +08001264 LOG(INFO) << __func__ << ": ALREADY IN CACHE (" << e << ") ? IGNORING ADD";
Bernie Innocenti802eccd2019-10-03 15:11:22 +09001265 cache_notify_waiting_tid_locked(cache, key);
Mike Yud1ec2542019-06-06 17:17:53 +08001266 return -EEXIST;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001267 }
1268 }
1269
1270 ttl = answer_getTTL(answer, answerlen);
1271 if (ttl > 0) {
1272 e = entry_alloc(key, answer, answerlen);
1273 if (e != NULL) {
1274 e->expires = ttl + _time_now();
1275 _cache_add_p(cache, lookup, e);
1276 }
1277 }
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001278
Mike Yu34433c62019-08-20 20:17:36 +08001279 cache_dump_mru_locked(cache);
Bernie Innocenti802eccd2019-10-03 15:11:22 +09001280 cache_notify_waiting_tid_locked(cache, key);
Mike Yud1ec2542019-06-06 17:17:53 +08001281
1282 return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001283}
1284
Ken Chen92bed612018-12-22 21:46:55 +08001285// Head of the list of caches.
1286static struct resolv_cache_info res_cache_list GUARDED_BY(cache_mutex);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001287
cken418cfb62018-12-01 17:45:18 +09001288// insert resolv_cache_info into the list of resolv_cache_infos
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001289static void insert_cache_info_locked(resolv_cache_info* cache_info);
cken418cfb62018-12-01 17:45:18 +09001290// creates a resolv_cache_info
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001291static resolv_cache_info* create_cache_info();
Bernie Innocenti863e39b2019-08-28 15:46:58 +09001292// Clears nameservers set for |cache_info| and clears the stats
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001293static void free_nameservers_locked(resolv_cache_info* cache_info);
Mike Yuc7649d12019-05-22 15:28:07 +08001294// Order-insensitive comparison for the two set of servers.
1295static bool resolv_is_nameservers_equal(const std::vector<std::string>& oldServers,
1296 const std::vector<std::string>& newServers);
cken418cfb62018-12-01 17:45:18 +09001297// clears the stats samples contained withing the given cache_info
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001298static void res_cache_clear_stats_locked(resolv_cache_info* cache_info);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001299
cken418cfb62018-12-01 17:45:18 +09001300// public API for netd to query if name server is set on specific netid
1301bool resolv_has_nameservers(unsigned netid) {
Ken Chen92bed612018-12-22 21:46:55 +08001302 std::lock_guard guard(cache_mutex);
cken418cfb62018-12-01 17:45:18 +09001303 resolv_cache_info* info = find_cache_info_locked(netid);
Ken Chen92bed612018-12-22 21:46:55 +08001304 return (info != nullptr) && (info->nscount > 0);
cken418cfb62018-12-01 17:45:18 +09001305}
1306
Luke Huange126fbe2019-07-20 17:36:30 +08001307namespace {
1308
1309// Map format: ReturnCode:rate_denom
1310// if the ReturnCode is not associated with any rate_denom, use default
1311// Sampling rate varies by return code; events to log are chosen randomly, with a
1312// probability proportional to the sampling rate.
1313constexpr const char DEFAULT_SUBSAMPLING_MAP[] = "default:1 0:100 7:10";
1314
1315std::unordered_map<int, uint32_t> resolv_get_dns_event_subsampling_map() {
1316 using android::base::ParseInt;
1317 using android::base::ParseUint;
1318 using android::base::Split;
1319 using server_configurable_flags::GetServerConfigurableFlag;
1320 std::unordered_map<int, uint32_t> sampling_rate_map{};
1321 std::vector<std::string> subsampling_vector =
1322 Split(GetServerConfigurableFlag("netd_native", "dns_event_subsample_map",
1323 DEFAULT_SUBSAMPLING_MAP),
1324 " ");
1325 for (const auto& pair : subsampling_vector) {
1326 std::vector<std::string> rate_denom = Split(pair, ":");
1327 int return_code;
1328 uint32_t denom;
1329 if (rate_denom.size() != 2) {
1330 LOG(ERROR) << __func__ << ": invalid subsampling_pair = " << pair;
1331 continue;
1332 }
1333 if (rate_denom[0] == "default") {
1334 return_code = DNSEVENT_SUBSAMPLING_MAP_DEFAULT_KEY;
1335 } else if (!ParseInt(rate_denom[0], &return_code)) {
1336 LOG(ERROR) << __func__ << ": parse subsampling_pair failed = " << pair;
1337 continue;
1338 }
1339 if (!ParseUint(rate_denom[1], &denom)) {
1340 LOG(ERROR) << __func__ << ": parse subsampling_pair failed = " << pair;
1341 continue;
1342 }
1343 sampling_rate_map[return_code] = denom;
1344 }
1345 return sampling_rate_map;
1346}
1347
1348} // namespace
1349
Bernie Innocentic4f469a2019-10-03 15:50:06 +09001350int resolv_create_cache_for_net(unsigned netid) {
1351 std::lock_guard guard(cache_mutex);
Bernie Innocenti802eccd2019-10-03 15:11:22 +09001352 Cache* cache = find_named_cache_locked(netid);
Luke Huang9b80e6c2019-04-09 17:54:09 +08001353 // Should not happen
1354 if (cache) {
1355 LOG(ERROR) << __func__ << ": Cache is already created, netId: " << netid;
1356 return -EEXIST;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001357 }
Luke Huang9b80e6c2019-04-09 17:54:09 +08001358
1359 resolv_cache_info* cache_info = create_cache_info();
1360 if (!cache_info) return -ENOMEM;
Luke Huang9b80e6c2019-04-09 17:54:09 +08001361 cache_info->netid = netid;
Bernie Innocentic4f469a2019-10-03 15:50:06 +09001362 cache_info->cache = new Cache;
Luke Huange126fbe2019-07-20 17:36:30 +08001363 cache_info->dns_event_subsampling_map = resolv_get_dns_event_subsampling_map();
Luke Huang9b80e6c2019-04-09 17:54:09 +08001364 insert_cache_info_locked(cache_info);
1365
1366 return 0;
1367}
1368
Bernie Innocentiac18b122018-10-01 23:10:18 +09001369void resolv_delete_cache_for_net(unsigned netid) {
Ken Chen92bed612018-12-22 21:46:55 +08001370 std::lock_guard guard(cache_mutex);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001371
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001372 struct resolv_cache_info* prev_cache_info = &res_cache_list;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001373
1374 while (prev_cache_info->next) {
1375 struct resolv_cache_info* cache_info = prev_cache_info->next;
1376
1377 if (cache_info->netid == netid) {
1378 prev_cache_info->next = cache_info->next;
Bernie Innocentic4f469a2019-10-03 15:50:06 +09001379 delete cache_info->cache;
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001380 free_nameservers_locked(cache_info);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001381 free(cache_info);
1382 break;
1383 }
1384
1385 prev_cache_info = prev_cache_info->next;
1386 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001387}
1388
Bernie Innocentia4be3c82019-03-28 19:25:11 +09001389std::vector<unsigned> resolv_list_caches() {
1390 std::lock_guard guard(cache_mutex);
1391 struct resolv_cache_info* cache_info = res_cache_list.next;
1392 std::vector<unsigned> result;
1393 while (cache_info) {
1394 result.push_back(cache_info->netid);
1395 cache_info = cache_info->next;
1396 }
1397 return result;
1398}
1399
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001400static resolv_cache_info* create_cache_info() {
Bernie Innocenti9c575932018-09-07 21:10:25 +09001401 return (struct resolv_cache_info*) calloc(sizeof(struct resolv_cache_info), 1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001402}
1403
Ken Chen92bed612018-12-22 21:46:55 +08001404// TODO: convert this to a simple and efficient C++ container.
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001405static void insert_cache_info_locked(struct resolv_cache_info* cache_info) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001406 struct resolv_cache_info* last;
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001407 for (last = &res_cache_list; last->next; last = last->next) {}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001408 last->next = cache_info;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001409}
1410
Bernie Innocenti802eccd2019-10-03 15:11:22 +09001411static Cache* find_named_cache_locked(unsigned netid) {
cken418cfb62018-12-01 17:45:18 +09001412 resolv_cache_info* info = find_cache_info_locked(netid);
Mike Yud1ec2542019-06-06 17:17:53 +08001413 if (info != nullptr) return info->cache;
1414 return nullptr;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001415}
1416
cken418cfb62018-12-01 17:45:18 +09001417static resolv_cache_info* find_cache_info_locked(unsigned netid) {
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001418 struct resolv_cache_info* cache_info = res_cache_list.next;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001419
1420 while (cache_info) {
1421 if (cache_info->netid == netid) {
1422 break;
1423 }
1424
1425 cache_info = cache_info->next;
1426 }
1427 return cache_info;
1428}
1429
waynemaa74195e2019-01-18 14:02:31 +08001430static void resolv_set_experiment_params(res_params* params) {
1431 using android::base::ParseInt;
1432 using server_configurable_flags::GetServerConfigurableFlag;
1433
1434 if (params->retry_count == 0) {
1435 params->retry_count = RES_DFLRETRY;
1436 ParseInt(GetServerConfigurableFlag("netd_native", "retry_count", ""), &params->retry_count);
1437 }
1438
1439 if (params->base_timeout_msec == 0) {
1440 params->base_timeout_msec = RES_TIMEOUT;
1441 ParseInt(GetServerConfigurableFlag("netd_native", "retransmission_time_interval", ""),
1442 &params->base_timeout_msec);
1443 }
1444}
1445
Luke Huang2dac4382019-06-24 13:28:44 +08001446namespace {
1447
1448// Returns valid domains without duplicates which are limited to max size |MAXDNSRCH|.
1449std::vector<std::string> filter_domains(const std::vector<std::string>& domains) {
1450 std::set<std::string> tmp_set;
1451 std::vector<std::string> res;
1452
1453 std::copy_if(domains.begin(), domains.end(), std::back_inserter(res),
1454 [&tmp_set](const std::string& str) {
1455 return !(str.size() > MAXDNSRCHPATH - 1) && (tmp_set.insert(str).second);
1456 });
1457 if (res.size() > MAXDNSRCH) {
1458 LOG(WARNING) << __func__ << ": valid domains=" << res.size()
1459 << ", but MAXDNSRCH=" << MAXDNSRCH;
1460 res.resize(MAXDNSRCH);
1461 }
1462 return res;
1463}
1464
Mike Yuc7649d12019-05-22 15:28:07 +08001465std::vector<std::string> filter_nameservers(const std::vector<std::string>& servers) {
1466 std::vector<std::string> res = servers;
1467 if (res.size() > MAXNS) {
1468 LOG(WARNING) << __func__ << ": too many servers: " << res.size();
1469 res.resize(MAXNS);
1470 }
1471 return res;
1472}
1473
Luke Huang2dac4382019-06-24 13:28:44 +08001474} // namespace
1475
Mike Yuc7649d12019-05-22 15:28:07 +08001476int resolv_set_nameservers(unsigned netid, const std::vector<std::string>& servers,
1477 const std::vector<std::string>& domains, const res_params& params) {
1478 std::vector<std::string> nameservers = filter_nameservers(servers);
1479 const int numservers = static_cast<int>(nameservers.size());
1480
1481 LOG(INFO) << __func__ << ": netId = " << netid << ", numservers = " << numservers;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001482
1483 // Parse the addresses before actually locking or changing any state, in case there is an error.
1484 // As a side effect this also reduces the time the lock is kept.
Luke Huang2dac4382019-06-24 13:28:44 +08001485 // TODO: find a better way to replace addrinfo*, something like std::vector<SafeAddrinfo>
1486 addrinfo* nsaddrinfo[MAXNS];
Bernie Innocentib102dd22018-12-04 14:57:48 +09001487 for (int i = 0; i < numservers; i++) {
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001488 // The addrinfo structures allocated here are freed in free_nameservers_locked().
Bernie Innocentie2bc46f2018-10-16 23:35:28 +09001489 const addrinfo hints = {
1490 .ai_family = AF_UNSPEC, .ai_socktype = SOCK_DGRAM, .ai_flags = AI_NUMERICHOST};
Mike Yuc7649d12019-05-22 15:28:07 +08001491 const int rt = getaddrinfo_numeric(nameservers[i].c_str(), "53", hints, &nsaddrinfo[i]);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001492 if (rt != 0) {
Bernie Innocentib102dd22018-12-04 14:57:48 +09001493 for (int j = 0; j < i; j++) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001494 freeaddrinfo(nsaddrinfo[j]);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001495 }
Mike Yuc7649d12019-05-22 15:28:07 +08001496 LOG(INFO) << __func__ << ": getaddrinfo_numeric(" << nameservers[i]
chenbruceacb832c2019-02-20 19:45:50 +08001497 << ") = " << gai_strerror(rt);
Mike Yuc7649d12019-05-22 15:28:07 +08001498 return -EINVAL;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001499 }
1500 }
1501
Ken Chen92bed612018-12-22 21:46:55 +08001502 std::lock_guard guard(cache_mutex);
cken418cfb62018-12-01 17:45:18 +09001503 resolv_cache_info* cache_info = find_cache_info_locked(netid);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001504
Mike Yuc7649d12019-05-22 15:28:07 +08001505 if (cache_info == nullptr) return -ENONET;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001506
Luke Huang9b80e6c2019-04-09 17:54:09 +08001507 uint8_t old_max_samples = cache_info->params.max_samples;
Mike Yuc7649d12019-05-22 15:28:07 +08001508 cache_info->params = params;
Luke Huang9b80e6c2019-04-09 17:54:09 +08001509 resolv_set_experiment_params(&cache_info->params);
Mike Yuc7649d12019-05-22 15:28:07 +08001510 if (!resolv_is_nameservers_equal(cache_info->nameservers, nameservers)) {
Luke Huang9b80e6c2019-04-09 17:54:09 +08001511 // free current before adding new
1512 free_nameservers_locked(cache_info);
Mike Yuc7649d12019-05-22 15:28:07 +08001513 cache_info->nameservers = std::move(nameservers);
Luke Huang9b80e6c2019-04-09 17:54:09 +08001514 for (int i = 0; i < numservers; i++) {
1515 cache_info->nsaddrinfo[i] = nsaddrinfo[i];
Mike Yuc7649d12019-05-22 15:28:07 +08001516 LOG(INFO) << __func__ << ": netid = " << netid
1517 << ", addr = " << cache_info->nameservers[i];
Luke Huang9b80e6c2019-04-09 17:54:09 +08001518 }
1519 cache_info->nscount = numservers;
Luke Huang9b80e6c2019-04-09 17:54:09 +08001520 } else {
1521 if (cache_info->params.max_samples != old_max_samples) {
1522 // If the maximum number of samples changes, the overhead of keeping the most recent
1523 // samples around is not considered worth the effort, so they are cleared instead.
1524 // All other parameters do not affect shared state: Changing these parameters does
1525 // not invalidate the samples, as they only affect aggregation and the conditions
1526 // under which servers are considered usable.
1527 res_cache_clear_stats_locked(cache_info);
Luke Huang9b80e6c2019-04-09 17:54:09 +08001528 }
1529 for (int j = 0; j < numservers; j++) {
1530 freeaddrinfo(nsaddrinfo[j]);
1531 }
1532 }
1533
Luke Huang2dac4382019-06-24 13:28:44 +08001534 // Always update the search paths. Cache-flushing however is not necessary,
1535 // since the stored cache entries do contain the domain, not just the host name.
1536 cache_info->search_domains = filter_domains(domains);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001537
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001538 return 0;
1539}
1540
Mike Yuc7649d12019-05-22 15:28:07 +08001541static bool resolv_is_nameservers_equal(const std::vector<std::string>& oldServers,
1542 const std::vector<std::string>& newServers) {
1543 const std::set<std::string> olds(oldServers.begin(), oldServers.end());
1544 const std::set<std::string> news(newServers.begin(), newServers.end());
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001545
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001546 // TODO: this is incorrect if the list of current or previous nameservers
1547 // contains duplicates. This does not really matter because the framework
1548 // filters out duplicates, but we should probably fix it. It's also
1549 // insensitive to the order of the nameservers; we should probably fix that
1550 // too.
Mike Yuc7649d12019-05-22 15:28:07 +08001551 return olds == news;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001552}
1553
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001554static void free_nameservers_locked(resolv_cache_info* cache_info) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001555 int i;
1556 for (i = 0; i < cache_info->nscount; i++) {
Mike Yuc7649d12019-05-22 15:28:07 +08001557 cache_info->nameservers.clear();
Bernie Innocenti863e39b2019-08-28 15:46:58 +09001558 if (cache_info->nsaddrinfo[i] != nullptr) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001559 freeaddrinfo(cache_info->nsaddrinfo[i]);
Bernie Innocenti863e39b2019-08-28 15:46:58 +09001560 cache_info->nsaddrinfo[i] = nullptr;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001561 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001562 }
1563 cache_info->nscount = 0;
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001564 res_cache_clear_stats_locked(cache_info);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001565}
1566
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001567void _resolv_populate_res_for_net(res_state statp) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001568 if (statp == NULL) {
1569 return;
1570 }
Ken Chenffc224a2019-03-19 17:41:28 +08001571 LOG(INFO) << __func__ << ": netid=" << statp->netid;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001572
Ken Chen92bed612018-12-22 21:46:55 +08001573 std::lock_guard guard(cache_mutex);
cken418cfb62018-12-01 17:45:18 +09001574 resolv_cache_info* info = find_cache_info_locked(statp->netid);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001575 if (info != NULL) {
1576 int nserv;
1577 struct addrinfo* ai;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001578 for (nserv = 0; nserv < MAXNS; nserv++) {
1579 ai = info->nsaddrinfo[nserv];
1580 if (ai == NULL) {
1581 break;
1582 }
1583
Bernie Innocentic977ab72019-10-09 00:34:06 +09001584 if ((size_t)ai->ai_addrlen <= sizeof(statp->nsaddrs[0])) {
1585 memcpy(&statp->nsaddrs[nserv], ai->ai_addr, ai->ai_addrlen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001586 } else {
chenbruceacb832c2019-02-20 19:45:50 +08001587 LOG(INFO) << __func__ << ": found too long addrlen";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001588 }
1589 }
1590 statp->nscount = nserv;
Luke Huang2dac4382019-06-24 13:28:44 +08001591 statp->search_domains = info->search_domains;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001592 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001593}
1594
1595/* Resolver reachability statistics. */
1596
Bernie Innocentiac18b122018-10-01 23:10:18 +09001597static void _res_cache_add_stats_sample_locked(res_stats* stats, const res_sample* sample,
1598 int max_samples) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001599 // Note: This function expects max_samples > 0, otherwise a (harmless) modification of the
1600 // allocated but supposedly unused memory for samples[0] will happen
Ken Chenffc224a2019-03-19 17:41:28 +08001601 LOG(INFO) << __func__ << ": adding sample to stats, next = " << unsigned(stats->sample_next)
1602 << ", count = " << unsigned(stats->sample_count);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001603 stats->samples[stats->sample_next] = *sample;
1604 if (stats->sample_count < max_samples) {
1605 ++stats->sample_count;
1606 }
1607 if (++stats->sample_next >= max_samples) {
1608 stats->sample_next = 0;
1609 }
1610}
1611
Bernie Innocenti68bb7aa2018-09-27 13:44:29 +09001612static void res_cache_clear_stats_locked(resolv_cache_info* cache_info) {
Bernie Innocenti863e39b2019-08-28 15:46:58 +09001613 for (int i = 0; i < MAXNS; ++i) {
1614 cache_info->nsstats[i].sample_count = 0;
1615 cache_info->nsstats[i].sample_next = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001616 }
Bernie Innocenti863e39b2019-08-28 15:46:58 +09001617
1618 // Increment the revision id to ensure that sample state is not written back if the
1619 // servers change; in theory it would suffice to do so only if the servers or
1620 // max_samples actually change, in practice the overhead of checking is higher than the
1621 // cost, and overflows are unlikely.
1622 ++cache_info->revision_id;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001623}
1624
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001625int android_net_res_stats_get_info_for_net(unsigned netid, int* nscount,
1626 struct sockaddr_storage servers[MAXNS], int* dcount,
1627 char domains[MAXDNSRCH][MAXDNSRCHPATH],
Bernie Innocenti758005f2019-02-19 18:08:36 +09001628 res_params* params, struct res_stats stats[MAXNS],
Ken Chen92bed612018-12-22 21:46:55 +08001629 int* wait_for_pending_req_timeout_count) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001630 int revision_id = -1;
Ken Chen92bed612018-12-22 21:46:55 +08001631 std::lock_guard guard(cache_mutex);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001632
cken418cfb62018-12-01 17:45:18 +09001633 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001634 if (info) {
1635 if (info->nscount > MAXNS) {
chenbruceacb832c2019-02-20 19:45:50 +08001636 LOG(INFO) << __func__ << ": nscount " << info->nscount << " > MAXNS " << MAXNS;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001637 errno = EFAULT;
1638 return -1;
1639 }
1640 int i;
1641 for (i = 0; i < info->nscount; i++) {
1642 // Verify that the following assumptions are held, failure indicates corruption:
1643 // - getaddrinfo() may never return a sockaddr > sockaddr_storage
1644 // - all addresses are valid
1645 // - there is only one address per addrinfo thanks to numeric resolution
1646 int addrlen = info->nsaddrinfo[i]->ai_addrlen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001647 if (addrlen < (int) sizeof(struct sockaddr) || addrlen > (int) sizeof(servers[0])) {
chenbruceacb832c2019-02-20 19:45:50 +08001648 LOG(INFO) << __func__ << ": nsaddrinfo[" << i << "].ai_addrlen == " << addrlen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001649 errno = EMSGSIZE;
1650 return -1;
1651 }
1652 if (info->nsaddrinfo[i]->ai_addr == NULL) {
chenbruceacb832c2019-02-20 19:45:50 +08001653 LOG(INFO) << __func__ << ": nsaddrinfo[" << i << "].ai_addr == NULL";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001654 errno = ENOENT;
1655 return -1;
1656 }
1657 if (info->nsaddrinfo[i]->ai_next != NULL) {
chenbruceacb832c2019-02-20 19:45:50 +08001658 LOG(INFO) << __func__ << ": nsaddrinfo[" << i << "].ai_next != NULL";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001659 errno = ENOTUNIQ;
1660 return -1;
1661 }
1662 }
1663 *nscount = info->nscount;
1664 for (i = 0; i < info->nscount; i++) {
1665 memcpy(&servers[i], info->nsaddrinfo[i]->ai_addr, info->nsaddrinfo[i]->ai_addrlen);
1666 stats[i] = info->nsstats[i];
1667 }
Luke Huang2dac4382019-06-24 13:28:44 +08001668
1669 for (i = 0; i < static_cast<int>(info->search_domains.size()); i++) {
1670 strlcpy(domains[i], info->search_domains[i].c_str(), MAXDNSRCHPATH);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001671 }
1672 *dcount = i;
1673 *params = info->params;
1674 revision_id = info->revision_id;
Ken Chen92bed612018-12-22 21:46:55 +08001675 *wait_for_pending_req_timeout_count = info->wait_for_pending_req_timeout_count;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001676 }
1677
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001678 return revision_id;
1679}
1680
Luke Huange126fbe2019-07-20 17:36:30 +08001681std::vector<std::string> resolv_cache_dump_subsampling_map(unsigned netid) {
1682 using android::base::StringPrintf;
1683 std::lock_guard guard(cache_mutex);
1684 resolv_cache_info* cache_info = find_cache_info_locked(netid);
1685 if (cache_info == nullptr) return {};
1686 std::vector<std::string> result;
1687 for (const auto& pair : cache_info->dns_event_subsampling_map) {
1688 result.push_back(StringPrintf("%s:%d",
1689 (pair.first == DNSEVENT_SUBSAMPLING_MAP_DEFAULT_KEY)
1690 ? "default"
1691 : std::to_string(pair.first).c_str(),
1692 pair.second));
1693 }
1694 return result;
1695}
1696
1697// Decides whether an event should be sampled using a random number generator and
1698// a sampling factor derived from the netid and the return code.
1699//
1700// Returns the subsampling rate if the event should be sampled, or 0 if it should be discarded.
1701uint32_t resolv_cache_get_subsampling_denom(unsigned netid, int return_code) {
1702 std::lock_guard guard(cache_mutex);
1703 resolv_cache_info* cache_info = find_cache_info_locked(netid);
1704 if (cache_info == nullptr) return 0; // Don't log anything at all.
1705 const auto& subsampling_map = cache_info->dns_event_subsampling_map;
1706 auto search_returnCode = subsampling_map.find(return_code);
1707 uint32_t denom;
1708 if (search_returnCode != subsampling_map.end()) {
1709 denom = search_returnCode->second;
1710 } else {
1711 auto search_default = subsampling_map.find(DNSEVENT_SUBSAMPLING_MAP_DEFAULT_KEY);
1712 denom = (search_default == subsampling_map.end()) ? 0 : search_default->second;
1713 }
1714 return denom;
1715}
1716
Bernie Innocenti758005f2019-02-19 18:08:36 +09001717int resolv_cache_get_resolver_stats(unsigned netid, res_params* params, res_stats stats[MAXNS]) {
Ken Chen92bed612018-12-22 21:46:55 +08001718 std::lock_guard guard(cache_mutex);
cken418cfb62018-12-01 17:45:18 +09001719 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001720 if (info) {
1721 memcpy(stats, info->nsstats, sizeof(info->nsstats));
1722 *params = info->params;
Ken Chen92bed612018-12-22 21:46:55 +08001723 return info->revision_id;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001724 }
1725
Ken Chen92bed612018-12-22 21:46:55 +08001726 return -1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001727}
1728
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001729void _resolv_cache_add_resolver_stats_sample(unsigned netid, int revision_id, int ns,
Bernie Innocentiac18b122018-10-01 23:10:18 +09001730 const res_sample* sample, int max_samples) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001731 if (max_samples <= 0) return;
1732
Ken Chen92bed612018-12-22 21:46:55 +08001733 std::lock_guard guard(cache_mutex);
cken418cfb62018-12-01 17:45:18 +09001734 resolv_cache_info* info = find_cache_info_locked(netid);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001735
1736 if (info && info->revision_id == revision_id) {
1737 _res_cache_add_stats_sample_locked(&info->nsstats[ns], sample, max_samples);
1738 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001739}
Mike Yud1ec2542019-06-06 17:17:53 +08001740
1741bool has_named_cache(unsigned netid) {
1742 std::lock_guard guard(cache_mutex);
1743 return find_named_cache_locked(netid) != nullptr;
1744}
1745
Mike Yuc7649d12019-05-22 15:28:07 +08001746int resolv_cache_get_expiration(unsigned netid, const std::vector<char>& query,
1747 time_t* expiration) {
Mike Yud1ec2542019-06-06 17:17:53 +08001748 Entry key;
Mike Yud1ec2542019-06-06 17:17:53 +08001749 *expiration = -1;
1750
Mike Yuc7649d12019-05-22 15:28:07 +08001751 // A malformed query is not allowed.
Mike Yud1ec2542019-06-06 17:17:53 +08001752 if (!entry_init_key(&key, query.data(), query.size())) {
1753 LOG(WARNING) << __func__ << ": unsupported query";
1754 return -EINVAL;
1755 }
1756
1757 // lookup cache.
Mike Yuc7649d12019-05-22 15:28:07 +08001758 Cache* cache;
Mike Yud1ec2542019-06-06 17:17:53 +08001759 std::lock_guard guard(cache_mutex);
1760 if (cache = find_named_cache_locked(netid); cache == nullptr) {
1761 LOG(WARNING) << __func__ << ": cache not created in the network " << netid;
1762 return -ENONET;
1763 }
Mike Yuc7649d12019-05-22 15:28:07 +08001764 Entry** lookup = _cache_lookup_p(cache, &key);
1765 Entry* e = *lookup;
Mike Yud1ec2542019-06-06 17:17:53 +08001766 if (e == NULL) {
1767 LOG(WARNING) << __func__ << ": not in cache";
1768 return -ENODATA;
1769 }
1770
1771 if (_time_now() >= e->expires) {
1772 LOG(WARNING) << __func__ << ": entry expired";
1773 return -ENODATA;
1774 }
1775
1776 *expiration = e->expires;
1777 return 0;
1778}