blob: 9c6557090e38b27b65a17fecb1ea5e7c629ef0a1 [file] [log] [blame]
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001/*
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
29#include "resolv_cache.h"
Pierre Imai97c9d732016-04-18 12:00:12 +090030
Mattias Falk23d3e6b2011-04-04 16:12:35 +020031#include <resolv.h>
Lorenzo Colitti616344d2014-11-28 11:47:13 +090032#include <stdarg.h>
33#include <stdio.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080034#include <stdlib.h>
35#include <string.h>
36#include <time.h>
37#include "pthread.h"
38
Mattias Falk3e0c5102011-01-31 12:42:26 +010039#include <errno.h>
Calin Juravle569fb982014-03-04 15:01:29 +000040#include <arpa/nameser.h>
Mattias Falk23d3e6b2011-04-04 16:12:35 +020041#include <net/if.h>
42#include <netdb.h>
43#include <linux/if.h>
44
45#include <arpa/inet.h>
46#include "resolv_private.h"
Szymon Jakubczakea9bf672014-02-14 17:07:23 -050047#include "resolv_netid.h"
Mattias Falkc63e5902011-08-23 14:34:14 +020048#include "res_private.h"
Mattias Falk3e0c5102011-01-31 12:42:26 +010049
Christopher Ferris7a3681e2017-04-24 17:48:32 -070050#include <async_safe/log.h>
Lorenzo Colitti616344d2014-11-28 11:47:13 +090051
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080052/* This code implements a small and *simple* DNS resolver cache.
53 *
Mattias Falk3e0c5102011-01-31 12:42:26 +010054 * It is only used to cache DNS answers for a time defined by the smallest TTL
55 * among the answer records in order to reduce DNS traffic. It is not supposed
56 * to be a full DNS cache, since we plan to implement that in the future in a
57 * dedicated process running on the system.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080058 *
59 * Note that its design is kept simple very intentionally, i.e.:
60 *
61 * - it takes raw DNS query packet data as input, and returns raw DNS
62 * answer packet data as output
63 *
64 * (this means that two similar queries that encode the DNS name
65 * differently will be treated distinctly).
66 *
Mattias Falk3e0c5102011-01-31 12:42:26 +010067 * the smallest TTL value among the answer records are used as the time
68 * to keep an answer in the cache.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080069 *
70 * this is bad, but we absolutely want to avoid parsing the answer packets
71 * (and should be solved by the later full DNS cache process).
72 *
73 * - the implementation is just a (query-data) => (answer-data) hash table
74 * with a trivial least-recently-used expiration policy.
75 *
76 * Doing this keeps the code simple and avoids to deal with a lot of things
77 * that a full DNS cache is expected to do.
78 *
79 * The API is also very simple:
80 *
81 * - the client calls _resolv_cache_get() to obtain a handle to the cache.
82 * this will initialize the cache on first usage. the result can be NULL
83 * if the cache is disabled.
84 *
85 * - the client calls _resolv_cache_lookup() before performing a query
86 *
87 * if the function returns RESOLV_CACHE_FOUND, a copy of the answer data
88 * has been copied into the client-provided answer buffer.
89 *
90 * if the function returns RESOLV_CACHE_NOTFOUND, the client should perform
91 * a request normally, *then* call _resolv_cache_add() to add the received
92 * answer to the cache.
93 *
94 * if the function returns RESOLV_CACHE_UNSUPPORTED, the client should
95 * perform a request normally, and *not* call _resolv_cache_add()
96 *
97 * note that RESOLV_CACHE_UNSUPPORTED is also returned if the answer buffer
98 * is too short to accomodate the cached result.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080099 */
100
Mattias Falk3a4910c2011-02-14 12:41:11 +0100101/* default number of entries kept in the cache. This value has been
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800102 * determined by browsing through various sites and counting the number
103 * of corresponding requests. Keep in mind that our framework is currently
104 * performing two requests per name lookup (one for IPv4, the other for IPv6)
105 *
106 * www.google.com 4
107 * www.ysearch.com 6
108 * www.amazon.com 8
109 * www.nytimes.com 22
110 * www.espn.com 28
111 * www.msn.com 28
112 * www.lemonde.fr 35
113 *
114 * (determined in 2009-2-17 from Paris, France, results may vary depending
115 * on location)
116 *
117 * most high-level websites use lots of media/ad servers with different names
118 * but these are generally reused when browsing through the site.
119 *
Mattias Falk3a4910c2011-02-14 12:41:11 +0100120 * As such, a value of 64 should be relatively comfortable at the moment.
121 *
Robert Greenwalt52764f52012-01-25 15:16:03 -0800122 * ******************************************
123 * * NOTE - this has changed.
124 * * 1) we've added IPv6 support so each dns query results in 2 responses
125 * * 2) we've made this a system-wide cache, so the cost is less (it's not
126 * * duplicated in each process) and the need is greater (more processes
127 * * making different requests).
128 * * Upping by 2x for IPv6
129 * * Upping by another 5x for the centralized nature
130 * *****************************************
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800131 */
Robert Greenwalt52764f52012-01-25 15:16:03 -0800132#define CONFIG_MAX_ENTRIES 64 * 2 * 5
Mattias Falk3a4910c2011-02-14 12:41:11 +0100133
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800134/****************************************************************************/
135/****************************************************************************/
136/***** *****/
137/***** *****/
138/***** *****/
139/****************************************************************************/
140/****************************************************************************/
141
142/* set to 1 to debug cache operations */
143#define DEBUG 0
144
145/* set to 1 to debug query data */
146#define DEBUG_DATA 0
147
148#if DEBUG
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900149#define __DEBUG__
150#else
151#define __DEBUG__ __attribute__((unused))
152#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800153
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900154#undef XLOG
155
156#define XLOG(...) ({ \
157 if (DEBUG) { \
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700158 async_safe_format_log(ANDROID_LOG_DEBUG,"libc",__VA_ARGS__); \
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900159 } else { \
160 ((void)0); \
161 } \
162})
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800163
164/** BOUNDED BUFFER FORMATTING
165 **/
166
167/* technical note:
168 *
169 * the following debugging routines are used to append data to a bounded
170 * buffer they take two parameters that are:
171 *
172 * - p : a pointer to the current cursor position in the buffer
173 * this value is initially set to the buffer's address.
174 *
175 * - end : the address of the buffer's limit, i.e. of the first byte
176 * after the buffer. this address should never be touched.
177 *
178 * IMPORTANT: it is assumed that end > buffer_address, i.e.
179 * that the buffer is at least one byte.
180 *
181 * the _bprint_() functions return the new value of 'p' after the data
182 * has been appended, and also ensure the following:
183 *
184 * - the returned value will never be strictly greater than 'end'
185 *
186 * - a return value equal to 'end' means that truncation occured
187 * (in which case, end[-1] will be set to 0)
188 *
189 * - after returning from a _bprint_() function, the content of the buffer
190 * is always 0-terminated, even in the event of truncation.
191 *
192 * these conventions allow you to call _bprint_ functions multiple times and
193 * only check for truncation at the end of the sequence, as in:
194 *
195 * char buff[1000], *p = buff, *end = p + sizeof(buff);
196 *
197 * p = _bprint_c(p, end, '"');
198 * p = _bprint_s(p, end, my_string);
199 * p = _bprint_c(p, end, '"');
200 *
201 * if (p >= end) {
202 * // buffer was too small
203 * }
204 *
205 * printf( "%s", buff );
206 */
207
208/* add a char to a bounded buffer */
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900209char*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800210_bprint_c( char* p, char* end, int c )
211{
212 if (p < end) {
213 if (p+1 == end)
214 *p++ = 0;
215 else {
216 *p++ = (char) c;
217 *p = 0;
218 }
219 }
220 return p;
221}
222
223/* add a sequence of bytes to a bounded buffer */
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900224char*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800225_bprint_b( char* p, char* end, const char* buf, int len )
226{
227 int avail = end - p;
228
229 if (avail <= 0 || len <= 0)
230 return p;
231
232 if (avail > len)
233 avail = len;
234
235 memcpy( p, buf, avail );
236 p += avail;
237
238 if (p < end)
239 p[0] = 0;
240 else
241 end[-1] = 0;
242
243 return p;
244}
245
246/* add a string to a bounded buffer */
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900247char*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800248_bprint_s( char* p, char* end, const char* str )
249{
250 return _bprint_b(p, end, str, strlen(str));
251}
252
253/* add a formatted string to a bounded buffer */
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900254char* _bprint( char* p, char* end, const char* format, ... ) __DEBUG__;
255char* _bprint( char* p, char* end, const char* format, ... )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800256{
257 int avail, n;
258 va_list args;
259
260 avail = end - p;
261
262 if (avail <= 0)
263 return p;
264
265 va_start(args, format);
David 'Digit' Turnerd378c682010-03-08 15:13:04 -0800266 n = vsnprintf( p, avail, format, args);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800267 va_end(args);
268
269 /* certain C libraries return -1 in case of truncation */
270 if (n < 0 || n > avail)
271 n = avail;
272
273 p += n;
274 /* certain C libraries do not zero-terminate in case of truncation */
275 if (p == end)
276 p[-1] = 0;
277
278 return p;
279}
280
281/* add a hex value to a bounded buffer, up to 8 digits */
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900282char*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800283_bprint_hex( char* p, char* end, unsigned value, int numDigits )
284{
285 char text[sizeof(unsigned)*2];
286 int nn = 0;
287
288 while (numDigits-- > 0) {
289 text[nn++] = "0123456789abcdef"[(value >> (numDigits*4)) & 15];
290 }
291 return _bprint_b(p, end, text, nn);
292}
293
294/* add the hexadecimal dump of some memory area to a bounded buffer */
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900295char*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800296_bprint_hexdump( char* p, char* end, const uint8_t* data, int datalen )
297{
298 int lineSize = 16;
299
300 while (datalen > 0) {
301 int avail = datalen;
302 int nn;
303
304 if (avail > lineSize)
305 avail = lineSize;
306
307 for (nn = 0; nn < avail; nn++) {
308 if (nn > 0)
309 p = _bprint_c(p, end, ' ');
310 p = _bprint_hex(p, end, data[nn], 2);
311 }
312 for ( ; nn < lineSize; nn++ ) {
313 p = _bprint_s(p, end, " ");
314 }
315 p = _bprint_s(p, end, " ");
316
317 for (nn = 0; nn < avail; nn++) {
318 int c = data[nn];
319
320 if (c < 32 || c > 127)
321 c = '.';
322
323 p = _bprint_c(p, end, c);
324 }
325 p = _bprint_c(p, end, '\n');
326
327 data += avail;
328 datalen -= avail;
329 }
330 return p;
331}
332
333/* dump the content of a query of packet to the log */
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900334void XLOG_BYTES( const void* base, int len ) __DEBUG__;
335void XLOG_BYTES( const void* base, int len )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800336{
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900337 if (DEBUG_DATA) {
338 char buff[1024];
339 char* p = buff, *end = p + sizeof(buff);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800340
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900341 p = _bprint_hexdump(p, end, base, len);
342 XLOG("%s",buff);
343 }
344} __DEBUG__
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800345
346static time_t
347_time_now( void )
348{
349 struct timeval tv;
350
351 gettimeofday( &tv, NULL );
352 return tv.tv_sec;
353}
354
355/* reminder: the general format of a DNS packet is the following:
356 *
357 * HEADER (12 bytes)
358 * QUESTION (variable)
359 * ANSWER (variable)
360 * AUTHORITY (variable)
361 * ADDITIONNAL (variable)
362 *
363 * the HEADER is made of:
364 *
365 * ID : 16 : 16-bit unique query identification field
366 *
367 * QR : 1 : set to 0 for queries, and 1 for responses
368 * Opcode : 4 : set to 0 for queries
369 * AA : 1 : set to 0 for queries
370 * TC : 1 : truncation flag, will be set to 0 in queries
371 * RD : 1 : recursion desired
372 *
373 * RA : 1 : recursion available (0 in queries)
374 * Z : 3 : three reserved zero bits
375 * RCODE : 4 : response code (always 0=NOERROR in queries)
376 *
377 * QDCount: 16 : question count
378 * ANCount: 16 : Answer count (0 in queries)
379 * NSCount: 16: Authority Record count (0 in queries)
380 * ARCount: 16: Additionnal Record count (0 in queries)
381 *
382 * the QUESTION is made of QDCount Question Record (QRs)
383 * the ANSWER is made of ANCount RRs
384 * the AUTHORITY is made of NSCount RRs
385 * the ADDITIONNAL is made of ARCount RRs
386 *
387 * Each Question Record (QR) is made of:
388 *
389 * QNAME : variable : Query DNS NAME
390 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
391 * CLASS : 16 : class of query (IN=1)
392 *
393 * Each Resource Record (RR) is made of:
394 *
395 * NAME : variable : DNS NAME
396 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
397 * CLASS : 16 : class of query (IN=1)
398 * TTL : 32 : seconds to cache this RR (0=none)
399 * RDLENGTH: 16 : size of RDDATA in bytes
400 * RDDATA : variable : RR data (depends on TYPE)
401 *
402 * Each QNAME contains a domain name encoded as a sequence of 'labels'
403 * terminated by a zero. Each label has the following format:
404 *
405 * LEN : 8 : lenght of label (MUST be < 64)
406 * NAME : 8*LEN : label length (must exclude dots)
407 *
408 * A value of 0 in the encoding is interpreted as the 'root' domain and
409 * terminates the encoding. So 'www.android.com' will be encoded as:
410 *
411 * <3>www<7>android<3>com<0>
412 *
413 * Where <n> represents the byte with value 'n'
414 *
415 * Each NAME reflects the QNAME of the question, but has a slightly more
416 * complex encoding in order to provide message compression. This is achieved
417 * by using a 2-byte pointer, with format:
418 *
419 * TYPE : 2 : 0b11 to indicate a pointer, 0b01 and 0b10 are reserved
420 * OFFSET : 14 : offset to another part of the DNS packet
421 *
422 * The offset is relative to the start of the DNS packet and must point
423 * A pointer terminates the encoding.
424 *
425 * The NAME can be encoded in one of the following formats:
426 *
427 * - a sequence of simple labels terminated by 0 (like QNAMEs)
428 * - a single pointer
429 * - a sequence of simple labels terminated by a pointer
430 *
431 * A pointer shall always point to either a pointer of a sequence of
432 * labels (which can themselves be terminated by either a 0 or a pointer)
433 *
434 * The expanded length of a given domain name should not exceed 255 bytes.
435 *
436 * NOTE: we don't parse the answer packets, so don't need to deal with NAME
437 * records, only QNAMEs.
438 */
439
440#define DNS_HEADER_SIZE 12
441
442#define DNS_TYPE_A "\00\01" /* big-endian decimal 1 */
443#define DNS_TYPE_PTR "\00\014" /* big-endian decimal 12 */
444#define DNS_TYPE_MX "\00\017" /* big-endian decimal 15 */
445#define DNS_TYPE_AAAA "\00\034" /* big-endian decimal 28 */
446#define DNS_TYPE_ALL "\00\0377" /* big-endian decimal 255 */
447
448#define DNS_CLASS_IN "\00\01" /* big-endian decimal 1 */
449
450typedef struct {
451 const uint8_t* base;
452 const uint8_t* end;
453 const uint8_t* cursor;
454} DnsPacket;
455
456static void
457_dnsPacket_init( DnsPacket* packet, const uint8_t* buff, int bufflen )
458{
459 packet->base = buff;
460 packet->end = buff + bufflen;
461 packet->cursor = buff;
462}
463
464static void
465_dnsPacket_rewind( DnsPacket* packet )
466{
467 packet->cursor = packet->base;
468}
469
470static void
471_dnsPacket_skip( DnsPacket* packet, int count )
472{
473 const uint8_t* p = packet->cursor + count;
474
475 if (p > packet->end)
476 p = packet->end;
477
478 packet->cursor = p;
479}
480
481static int
482_dnsPacket_readInt16( DnsPacket* packet )
483{
484 const uint8_t* p = packet->cursor;
485
486 if (p+2 > packet->end)
487 return -1;
488
489 packet->cursor = p+2;
490 return (p[0]<< 8) | p[1];
491}
492
493/** QUERY CHECKING
494 **/
495
496/* check bytes in a dns packet. returns 1 on success, 0 on failure.
497 * the cursor is only advanced in the case of success
498 */
499static int
500_dnsPacket_checkBytes( DnsPacket* packet, int numBytes, const void* bytes )
501{
502 const uint8_t* p = packet->cursor;
503
504 if (p + numBytes > packet->end)
505 return 0;
506
507 if (memcmp(p, bytes, numBytes) != 0)
508 return 0;
509
510 packet->cursor = p + numBytes;
511 return 1;
512}
513
514/* parse and skip a given QNAME stored in a query packet,
515 * from the current cursor position. returns 1 on success,
516 * or 0 for malformed data.
517 */
518static int
519_dnsPacket_checkQName( DnsPacket* packet )
520{
521 const uint8_t* p = packet->cursor;
522 const uint8_t* end = packet->end;
523
524 for (;;) {
525 int c;
526
527 if (p >= end)
528 break;
529
530 c = *p++;
531
532 if (c == 0) {
533 packet->cursor = p;
534 return 1;
535 }
536
537 /* we don't expect label compression in QNAMEs */
538 if (c >= 64)
539 break;
540
541 p += c;
542 /* we rely on the bound check at the start
543 * of the loop here */
544 }
545 /* malformed data */
546 XLOG("malformed QNAME");
547 return 0;
548}
549
550/* parse and skip a given QR stored in a packet.
551 * returns 1 on success, and 0 on failure
552 */
553static int
554_dnsPacket_checkQR( DnsPacket* packet )
555{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800556 if (!_dnsPacket_checkQName(packet))
557 return 0;
558
559 /* TYPE must be one of the things we support */
560 if (!_dnsPacket_checkBytes(packet, 2, DNS_TYPE_A) &&
561 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_PTR) &&
562 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_MX) &&
563 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_AAAA) &&
564 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_ALL))
565 {
566 XLOG("unsupported TYPE");
567 return 0;
568 }
569 /* CLASS must be IN */
570 if (!_dnsPacket_checkBytes(packet, 2, DNS_CLASS_IN)) {
571 XLOG("unsupported CLASS");
572 return 0;
573 }
574
575 return 1;
576}
577
578/* check the header of a DNS Query packet, return 1 if it is one
579 * type of query we can cache, or 0 otherwise
580 */
581static int
582_dnsPacket_checkQuery( DnsPacket* packet )
583{
584 const uint8_t* p = packet->base;
585 int qdCount, anCount, dnCount, arCount;
586
587 if (p + DNS_HEADER_SIZE > packet->end) {
588 XLOG("query packet too small");
589 return 0;
590 }
591
592 /* QR must be set to 0, opcode must be 0 and AA must be 0 */
593 /* RA, Z, and RCODE must be 0 */
594 if ((p[2] & 0xFC) != 0 || p[3] != 0) {
595 XLOG("query packet flags unsupported");
596 return 0;
597 }
598
599 /* Note that we ignore the TC and RD bits here for the
600 * following reasons:
601 *
602 * - there is no point for a query packet sent to a server
603 * to have the TC bit set, but the implementation might
604 * set the bit in the query buffer for its own needs
605 * between a _resolv_cache_lookup and a
606 * _resolv_cache_add. We should not freak out if this
607 * is the case.
608 *
609 * - we consider that the result from a RD=0 or a RD=1
610 * query might be different, hence that the RD bit
611 * should be used to differentiate cached result.
612 *
613 * this implies that RD is checked when hashing or
614 * comparing query packets, but not TC
615 */
616
617 /* ANCOUNT, DNCOUNT and ARCOUNT must be 0 */
618 qdCount = (p[4] << 8) | p[5];
619 anCount = (p[6] << 8) | p[7];
620 dnCount = (p[8] << 8) | p[9];
621 arCount = (p[10]<< 8) | p[11];
622
623 if (anCount != 0 || dnCount != 0 || arCount != 0) {
624 XLOG("query packet contains non-query records");
625 return 0;
626 }
627
628 if (qdCount == 0) {
629 XLOG("query packet doesn't contain query record");
630 return 0;
631 }
632
633 /* Check QDCOUNT QRs */
634 packet->cursor = p + DNS_HEADER_SIZE;
635
636 for (;qdCount > 0; qdCount--)
637 if (!_dnsPacket_checkQR(packet))
638 return 0;
639
640 return 1;
641}
642
643/** QUERY DEBUGGING
644 **/
645#if DEBUG
646static char*
647_dnsPacket_bprintQName(DnsPacket* packet, char* bp, char* bend)
648{
649 const uint8_t* p = packet->cursor;
650 const uint8_t* end = packet->end;
651 int first = 1;
652
653 for (;;) {
654 int c;
655
656 if (p >= end)
657 break;
658
659 c = *p++;
660
661 if (c == 0) {
662 packet->cursor = p;
663 return bp;
664 }
665
666 /* we don't expect label compression in QNAMEs */
667 if (c >= 64)
668 break;
669
670 if (first)
671 first = 0;
672 else
673 bp = _bprint_c(bp, bend, '.');
674
675 bp = _bprint_b(bp, bend, (const char*)p, c);
676
677 p += c;
678 /* we rely on the bound check at the start
679 * of the loop here */
680 }
681 /* malformed data */
682 bp = _bprint_s(bp, bend, "<MALFORMED>");
683 return bp;
684}
685
686static char*
687_dnsPacket_bprintQR(DnsPacket* packet, char* p, char* end)
688{
689#define QQ(x) { DNS_TYPE_##x, #x }
Elliott Hughes8f2a5a02013-03-15 15:30:25 -0700690 static const struct {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800691 const char* typeBytes;
Elliott Hughes8f2a5a02013-03-15 15:30:25 -0700692 const char* typeString;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800693 } qTypes[] =
694 {
695 QQ(A), QQ(PTR), QQ(MX), QQ(AAAA), QQ(ALL),
696 { NULL, NULL }
697 };
698 int nn;
699 const char* typeString = NULL;
700
701 /* dump QNAME */
702 p = _dnsPacket_bprintQName(packet, p, end);
703
704 /* dump TYPE */
705 p = _bprint_s(p, end, " (");
706
707 for (nn = 0; qTypes[nn].typeBytes != NULL; nn++) {
708 if (_dnsPacket_checkBytes(packet, 2, qTypes[nn].typeBytes)) {
709 typeString = qTypes[nn].typeString;
710 break;
711 }
712 }
713
714 if (typeString != NULL)
715 p = _bprint_s(p, end, typeString);
716 else {
717 int typeCode = _dnsPacket_readInt16(packet);
718 p = _bprint(p, end, "UNKNOWN-%d", typeCode);
719 }
720
721 p = _bprint_c(p, end, ')');
722
723 /* skip CLASS */
724 _dnsPacket_skip(packet, 2);
725 return p;
726}
727
728/* this function assumes the packet has already been checked */
729static char*
730_dnsPacket_bprintQuery( DnsPacket* packet, char* p, char* end )
731{
732 int qdCount;
733
734 if (packet->base[2] & 0x1) {
735 p = _bprint_s(p, end, "RECURSIVE ");
736 }
737
738 _dnsPacket_skip(packet, 4);
739 qdCount = _dnsPacket_readInt16(packet);
740 _dnsPacket_skip(packet, 6);
741
742 for ( ; qdCount > 0; qdCount-- ) {
743 p = _dnsPacket_bprintQR(packet, p, end);
744 }
745 return p;
746}
747#endif
748
749
750/** QUERY HASHING SUPPORT
751 **
752 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKET HAS ALREADY
753 ** BEEN SUCCESFULLY CHECKED.
754 **/
755
756/* use 32-bit FNV hash function */
757#define FNV_MULT 16777619U
758#define FNV_BASIS 2166136261U
759
760static unsigned
761_dnsPacket_hashBytes( DnsPacket* packet, int numBytes, unsigned hash )
762{
763 const uint8_t* p = packet->cursor;
764 const uint8_t* end = packet->end;
765
766 while (numBytes > 0 && p < end) {
767 hash = hash*FNV_MULT ^ *p++;
768 }
769 packet->cursor = p;
770 return hash;
771}
772
773
774static unsigned
775_dnsPacket_hashQName( DnsPacket* packet, unsigned hash )
776{
777 const uint8_t* p = packet->cursor;
778 const uint8_t* end = packet->end;
779
780 for (;;) {
781 int c;
782
783 if (p >= end) { /* should not happen */
784 XLOG("%s: INTERNAL_ERROR: read-overflow !!\n", __FUNCTION__);
785 break;
786 }
787
788 c = *p++;
789
790 if (c == 0)
791 break;
792
793 if (c >= 64) {
794 XLOG("%s: INTERNAL_ERROR: malformed domain !!\n", __FUNCTION__);
795 break;
796 }
797 if (p + c >= end) {
798 XLOG("%s: INTERNAL_ERROR: simple label read-overflow !!\n",
799 __FUNCTION__);
800 break;
801 }
802 while (c > 0) {
803 hash = hash*FNV_MULT ^ *p++;
804 c -= 1;
805 }
806 }
807 packet->cursor = p;
808 return hash;
809}
810
811static unsigned
812_dnsPacket_hashQR( DnsPacket* packet, unsigned hash )
813{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800814 hash = _dnsPacket_hashQName(packet, hash);
815 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TYPE and CLASS */
816 return hash;
817}
818
819static unsigned
820_dnsPacket_hashQuery( DnsPacket* packet )
821{
822 unsigned hash = FNV_BASIS;
823 int count;
824 _dnsPacket_rewind(packet);
825
826 /* we ignore the TC bit for reasons explained in
827 * _dnsPacket_checkQuery().
828 *
829 * however we hash the RD bit to differentiate
830 * between answers for recursive and non-recursive
831 * queries.
832 */
833 hash = hash*FNV_MULT ^ (packet->base[2] & 1);
834
835 /* assume: other flags are 0 */
836 _dnsPacket_skip(packet, 4);
837
838 /* read QDCOUNT */
839 count = _dnsPacket_readInt16(packet);
840
841 /* assume: ANcount, NScount, ARcount are 0 */
842 _dnsPacket_skip(packet, 6);
843
844 /* hash QDCOUNT QRs */
845 for ( ; count > 0; count-- )
846 hash = _dnsPacket_hashQR(packet, hash);
847
848 return hash;
849}
850
851
852/** QUERY COMPARISON
853 **
854 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKETS HAVE ALREADY
855 ** BEEN SUCCESFULLY CHECKED.
856 **/
857
858static int
859_dnsPacket_isEqualDomainName( DnsPacket* pack1, DnsPacket* pack2 )
860{
861 const uint8_t* p1 = pack1->cursor;
862 const uint8_t* end1 = pack1->end;
863 const uint8_t* p2 = pack2->cursor;
864 const uint8_t* end2 = pack2->end;
865
866 for (;;) {
867 int c1, c2;
868
869 if (p1 >= end1 || p2 >= end2) {
870 XLOG("%s: INTERNAL_ERROR: read-overflow !!\n", __FUNCTION__);
871 break;
872 }
873 c1 = *p1++;
874 c2 = *p2++;
875 if (c1 != c2)
876 break;
877
878 if (c1 == 0) {
879 pack1->cursor = p1;
880 pack2->cursor = p2;
881 return 1;
882 }
883 if (c1 >= 64) {
884 XLOG("%s: INTERNAL_ERROR: malformed domain !!\n", __FUNCTION__);
885 break;
886 }
887 if ((p1+c1 > end1) || (p2+c1 > end2)) {
888 XLOG("%s: INTERNAL_ERROR: simple label read-overflow !!\n",
889 __FUNCTION__);
890 break;
891 }
892 if (memcmp(p1, p2, c1) != 0)
893 break;
894 p1 += c1;
895 p2 += c1;
896 /* we rely on the bound checks at the start of the loop */
897 }
898 /* not the same, or one is malformed */
899 XLOG("different DN");
900 return 0;
901}
902
903static int
904_dnsPacket_isEqualBytes( DnsPacket* pack1, DnsPacket* pack2, int numBytes )
905{
906 const uint8_t* p1 = pack1->cursor;
907 const uint8_t* p2 = pack2->cursor;
908
909 if ( p1 + numBytes > pack1->end || p2 + numBytes > pack2->end )
910 return 0;
911
912 if ( memcmp(p1, p2, numBytes) != 0 )
913 return 0;
914
915 pack1->cursor += numBytes;
916 pack2->cursor += numBytes;
917 return 1;
918}
919
920static int
921_dnsPacket_isEqualQR( DnsPacket* pack1, DnsPacket* pack2 )
922{
923 /* compare domain name encoding + TYPE + CLASS */
924 if ( !_dnsPacket_isEqualDomainName(pack1, pack2) ||
925 !_dnsPacket_isEqualBytes(pack1, pack2, 2+2) )
926 return 0;
927
928 return 1;
929}
930
931static int
932_dnsPacket_isEqualQuery( DnsPacket* pack1, DnsPacket* pack2 )
933{
934 int count1, count2;
935
936 /* compare the headers, ignore most fields */
937 _dnsPacket_rewind(pack1);
938 _dnsPacket_rewind(pack2);
939
940 /* compare RD, ignore TC, see comment in _dnsPacket_checkQuery */
941 if ((pack1->base[2] & 1) != (pack2->base[2] & 1)) {
942 XLOG("different RD");
943 return 0;
944 }
945
946 /* assume: other flags are all 0 */
947 _dnsPacket_skip(pack1, 4);
948 _dnsPacket_skip(pack2, 4);
949
950 /* compare QDCOUNT */
951 count1 = _dnsPacket_readInt16(pack1);
952 count2 = _dnsPacket_readInt16(pack2);
953 if (count1 != count2 || count1 < 0) {
954 XLOG("different QDCOUNT");
955 return 0;
956 }
957
958 /* assume: ANcount, NScount and ARcount are all 0 */
959 _dnsPacket_skip(pack1, 6);
960 _dnsPacket_skip(pack2, 6);
961
962 /* compare the QDCOUNT QRs */
963 for ( ; count1 > 0; count1-- ) {
964 if (!_dnsPacket_isEqualQR(pack1, pack2)) {
965 XLOG("different QR");
966 return 0;
967 }
968 }
969 return 1;
970}
971
972/****************************************************************************/
973/****************************************************************************/
974/***** *****/
975/***** *****/
976/***** *****/
977/****************************************************************************/
978/****************************************************************************/
979
980/* cache entry. for simplicity, 'hash' and 'hlink' are inlined in this
981 * structure though they are conceptually part of the hash table.
982 *
983 * similarly, mru_next and mru_prev are part of the global MRU list
984 */
985typedef struct Entry {
986 unsigned int hash; /* hash value */
987 struct Entry* hlink; /* next in collision chain */
988 struct Entry* mru_prev;
989 struct Entry* mru_next;
990
991 const uint8_t* query;
992 int querylen;
993 const uint8_t* answer;
994 int answerlen;
Mattias Falk3e0c5102011-01-31 12:42:26 +0100995 time_t expires; /* time_t when the entry isn't valid any more */
996 int id; /* for debugging purpose */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800997} Entry;
998
Mattias Falk3e0c5102011-01-31 12:42:26 +0100999/**
Robert Greenwalt78851f12013-01-07 12:10:06 -08001000 * Find the TTL for a negative DNS result. This is defined as the minimum
1001 * of the SOA records TTL and the MINIMUM-TTL field (RFC-2308).
1002 *
1003 * Return 0 if not found.
1004 */
1005static u_long
1006answer_getNegativeTTL(ns_msg handle) {
1007 int n, nscount;
1008 u_long result = 0;
1009 ns_rr rr;
1010
1011 nscount = ns_msg_count(handle, ns_s_ns);
1012 for (n = 0; n < nscount; n++) {
1013 if ((ns_parserr(&handle, ns_s_ns, n, &rr) == 0) && (ns_rr_type(rr) == ns_t_soa)) {
1014 const u_char *rdata = ns_rr_rdata(rr); // find the data
1015 const u_char *edata = rdata + ns_rr_rdlen(rr); // add the len to find the end
1016 int len;
1017 u_long ttl, rec_result = ns_rr_ttl(rr);
1018
1019 // find the MINIMUM-TTL field from the blob of binary data for this record
1020 // skip the server name
1021 len = dn_skipname(rdata, edata);
1022 if (len == -1) continue; // error skipping
1023 rdata += len;
1024
1025 // skip the admin name
1026 len = dn_skipname(rdata, edata);
1027 if (len == -1) continue; // error skipping
1028 rdata += len;
1029
1030 if (edata - rdata != 5*NS_INT32SZ) continue;
1031 // skip: serial number + refresh interval + retry interval + expiry
1032 rdata += NS_INT32SZ * 4;
1033 // finally read the MINIMUM TTL
1034 ttl = ns_get32(rdata);
1035 if (ttl < rec_result) {
1036 rec_result = ttl;
1037 }
1038 // Now that the record is read successfully, apply the new min TTL
1039 if (n == 0 || rec_result < result) {
1040 result = rec_result;
1041 }
1042 }
1043 }
1044 return result;
1045}
1046
1047/**
1048 * Parse the answer records and find the appropriate
1049 * smallest TTL among the records. This might be from
1050 * the answer records if found or from the SOA record
1051 * if it's a negative result.
Mattias Falk3e0c5102011-01-31 12:42:26 +01001052 *
1053 * The returned TTL is the number of seconds to
1054 * keep the answer in the cache.
1055 *
1056 * In case of parse error zero (0) is returned which
1057 * indicates that the answer shall not be cached.
1058 */
1059static u_long
1060answer_getTTL(const void* answer, int answerlen)
1061{
1062 ns_msg handle;
1063 int ancount, n;
1064 u_long result, ttl;
1065 ns_rr rr;
1066
1067 result = 0;
1068 if (ns_initparse(answer, answerlen, &handle) >= 0) {
1069 // get number of answer records
1070 ancount = ns_msg_count(handle, ns_s_an);
Robert Greenwalt78851f12013-01-07 12:10:06 -08001071
1072 if (ancount == 0) {
1073 // a response with no answers? Cache this negative result.
1074 result = answer_getNegativeTTL(handle);
1075 } else {
1076 for (n = 0; n < ancount; n++) {
1077 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
1078 ttl = ns_rr_ttl(rr);
1079 if (n == 0 || ttl < result) {
1080 result = ttl;
1081 }
1082 } else {
1083 XLOG("ns_parserr failed ancount no = %d. errno = %s\n", n, strerror(errno));
Mattias Falk3e0c5102011-01-31 12:42:26 +01001084 }
Mattias Falk3e0c5102011-01-31 12:42:26 +01001085 }
1086 }
1087 } else {
1088 XLOG("ns_parserr failed. %s\n", strerror(errno));
1089 }
1090
Patrick Tjina6a09492015-01-20 16:02:04 -08001091 XLOG("TTL = %lu\n", result);
Mattias Falk3e0c5102011-01-31 12:42:26 +01001092
1093 return result;
1094}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001095
1096static void
1097entry_free( Entry* e )
1098{
1099 /* everything is allocated in a single memory block */
1100 if (e) {
1101 free(e);
1102 }
1103}
1104
1105static __inline__ void
1106entry_mru_remove( Entry* e )
1107{
1108 e->mru_prev->mru_next = e->mru_next;
1109 e->mru_next->mru_prev = e->mru_prev;
1110}
1111
1112static __inline__ void
1113entry_mru_add( Entry* e, Entry* list )
1114{
1115 Entry* first = list->mru_next;
1116
1117 e->mru_next = first;
1118 e->mru_prev = list;
1119
1120 list->mru_next = e;
1121 first->mru_prev = e;
1122}
1123
1124/* compute the hash of a given entry, this is a hash of most
1125 * data in the query (key) */
1126static unsigned
1127entry_hash( const Entry* e )
1128{
1129 DnsPacket pack[1];
1130
1131 _dnsPacket_init(pack, e->query, e->querylen);
1132 return _dnsPacket_hashQuery(pack);
1133}
1134
1135/* initialize an Entry as a search key, this also checks the input query packet
1136 * returns 1 on success, or 0 in case of unsupported/malformed data */
1137static int
1138entry_init_key( Entry* e, const void* query, int querylen )
1139{
1140 DnsPacket pack[1];
1141
1142 memset(e, 0, sizeof(*e));
1143
1144 e->query = query;
1145 e->querylen = querylen;
1146 e->hash = entry_hash(e);
1147
1148 _dnsPacket_init(pack, query, querylen);
1149
1150 return _dnsPacket_checkQuery(pack);
1151}
1152
1153/* allocate a new entry as a cache node */
1154static Entry*
1155entry_alloc( const Entry* init, const void* answer, int answerlen )
1156{
1157 Entry* e;
1158 int size;
1159
1160 size = sizeof(*e) + init->querylen + answerlen;
1161 e = calloc(size, 1);
1162 if (e == NULL)
1163 return e;
1164
1165 e->hash = init->hash;
1166 e->query = (const uint8_t*)(e+1);
1167 e->querylen = init->querylen;
1168
1169 memcpy( (char*)e->query, init->query, e->querylen );
1170
1171 e->answer = e->query + e->querylen;
1172 e->answerlen = answerlen;
1173
1174 memcpy( (char*)e->answer, answer, e->answerlen );
1175
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001176 return e;
1177}
1178
1179static int
1180entry_equals( const Entry* e1, const Entry* e2 )
1181{
1182 DnsPacket pack1[1], pack2[1];
1183
1184 if (e1->querylen != e2->querylen) {
1185 return 0;
1186 }
1187 _dnsPacket_init(pack1, e1->query, e1->querylen);
1188 _dnsPacket_init(pack2, e2->query, e2->querylen);
1189
1190 return _dnsPacket_isEqualQuery(pack1, pack2);
1191}
1192
1193/****************************************************************************/
1194/****************************************************************************/
1195/***** *****/
1196/***** *****/
1197/***** *****/
1198/****************************************************************************/
1199/****************************************************************************/
1200
1201/* We use a simple hash table with external collision lists
1202 * for simplicity, the hash-table fields 'hash' and 'hlink' are
1203 * inlined in the Entry structure.
1204 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001205
Mattias Falka59cfcf2011-09-06 15:15:06 +02001206/* Maximum time for a thread to wait for an pending request */
1207#define PENDING_REQUEST_TIMEOUT 20;
1208
1209typedef struct pending_req_info {
1210 unsigned int hash;
1211 pthread_cond_t cond;
1212 struct pending_req_info* next;
1213} PendingReqInfo;
1214
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001215typedef struct resolv_cache {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001216 int max_entries;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001217 int num_entries;
1218 Entry mru_list;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001219 int last_id;
Mattias Falk3a4910c2011-02-14 12:41:11 +01001220 Entry* entries;
Mattias Falka59cfcf2011-09-06 15:15:06 +02001221 PendingReqInfo pending_requests;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001222} Cache;
1223
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001224struct resolv_cache_info {
1225 unsigned netid;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001226 Cache* cache;
1227 struct resolv_cache_info* next;
Pierre Imaifff35672016-04-18 11:42:14 +09001228 int nscount;
1229 char* nameservers[MAXNS];
1230 struct addrinfo* nsaddrinfo[MAXNS];
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001231 int revision_id; // # times the nameservers have been replaced
1232 struct __res_params params;
Pierre Imaifff35672016-04-18 11:42:14 +09001233 struct __res_stats nsstats[MAXNS];
Pierre Imai97c9d732016-04-18 12:00:12 +09001234 char defdname[MAXDNSRCHPATH];
Mattias Falkc63e5902011-08-23 14:34:14 +02001235 int dnsrch_offset[MAXDNSRCH+1]; // offsets into defdname
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001236};
Mattias Falkc63e5902011-08-23 14:34:14 +02001237
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001238#define HTABLE_VALID(x) ((x) != NULL && (x) != HTABLE_DELETED)
1239
Paul Jensen41d9a502014-04-08 15:43:41 -04001240static pthread_once_t _res_cache_once = PTHREAD_ONCE_INIT;
1241static void _res_cache_init(void);
1242
1243// lock protecting everything in the _resolve_cache_info structs (next ptr, etc)
1244static pthread_mutex_t _res_cache_list_lock;
1245
1246/* gets cache associated with a network, or NULL if none exists */
1247static struct resolv_cache* _find_named_cache_locked(unsigned netid);
1248
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001249static void
Mattias Falka59cfcf2011-09-06 15:15:06 +02001250_cache_flush_pending_requests_locked( struct resolv_cache* cache )
1251{
1252 struct pending_req_info *ri, *tmp;
1253 if (cache) {
1254 ri = cache->pending_requests.next;
1255
1256 while (ri) {
1257 tmp = ri;
1258 ri = ri->next;
1259 pthread_cond_broadcast(&tmp->cond);
1260
1261 pthread_cond_destroy(&tmp->cond);
1262 free(tmp);
1263 }
1264
1265 cache->pending_requests.next = NULL;
1266 }
1267}
1268
Paul Jensen41d9a502014-04-08 15:43:41 -04001269/* Return 0 if no pending request is found matching the key.
1270 * If a matching request is found the calling thread will wait until
1271 * the matching request completes, then update *cache and return 1. */
Mattias Falka59cfcf2011-09-06 15:15:06 +02001272static int
Paul Jensen41d9a502014-04-08 15:43:41 -04001273_cache_check_pending_request_locked( struct resolv_cache** cache, Entry* key, unsigned netid )
Mattias Falka59cfcf2011-09-06 15:15:06 +02001274{
1275 struct pending_req_info *ri, *prev;
1276 int exist = 0;
1277
Paul Jensen41d9a502014-04-08 15:43:41 -04001278 if (*cache && key) {
1279 ri = (*cache)->pending_requests.next;
1280 prev = &(*cache)->pending_requests;
Mattias Falka59cfcf2011-09-06 15:15:06 +02001281 while (ri) {
1282 if (ri->hash == key->hash) {
1283 exist = 1;
1284 break;
1285 }
1286 prev = ri;
1287 ri = ri->next;
1288 }
1289
1290 if (!exist) {
1291 ri = calloc(1, sizeof(struct pending_req_info));
1292 if (ri) {
1293 ri->hash = key->hash;
1294 pthread_cond_init(&ri->cond, NULL);
1295 prev->next = ri;
1296 }
1297 } else {
1298 struct timespec ts = {0,0};
Mattias Falkc63e5902011-08-23 14:34:14 +02001299 XLOG("Waiting for previous request");
Mattias Falka59cfcf2011-09-06 15:15:06 +02001300 ts.tv_sec = _time_now() + PENDING_REQUEST_TIMEOUT;
Paul Jensen41d9a502014-04-08 15:43:41 -04001301 pthread_cond_timedwait(&ri->cond, &_res_cache_list_lock, &ts);
1302 /* Must update *cache as it could have been deleted. */
1303 *cache = _find_named_cache_locked(netid);
Mattias Falka59cfcf2011-09-06 15:15:06 +02001304 }
1305 }
1306
1307 return exist;
1308}
1309
1310/* notify any waiting thread that waiting on a request
1311 * matching the key has been added to the cache */
1312static void
1313_cache_notify_waiting_tid_locked( struct resolv_cache* cache, Entry* key )
1314{
1315 struct pending_req_info *ri, *prev;
1316
1317 if (cache && key) {
1318 ri = cache->pending_requests.next;
1319 prev = &cache->pending_requests;
1320 while (ri) {
1321 if (ri->hash == key->hash) {
1322 pthread_cond_broadcast(&ri->cond);
1323 break;
1324 }
1325 prev = ri;
1326 ri = ri->next;
1327 }
1328
1329 // remove item from list and destroy
1330 if (ri) {
1331 prev->next = ri->next;
1332 pthread_cond_destroy(&ri->cond);
1333 free(ri);
1334 }
1335 }
1336}
1337
1338/* notify the cache that the query failed */
1339void
Paul Jensen41d9a502014-04-08 15:43:41 -04001340_resolv_cache_query_failed( unsigned netid,
Mattias Falka59cfcf2011-09-06 15:15:06 +02001341 const void* query,
1342 int querylen)
1343{
1344 Entry key[1];
Paul Jensen41d9a502014-04-08 15:43:41 -04001345 Cache* cache;
Mattias Falka59cfcf2011-09-06 15:15:06 +02001346
Paul Jensen41d9a502014-04-08 15:43:41 -04001347 if (!entry_init_key(key, query, querylen))
1348 return;
1349
1350 pthread_mutex_lock(&_res_cache_list_lock);
1351
1352 cache = _find_named_cache_locked(netid);
1353
1354 if (cache) {
Mattias Falka59cfcf2011-09-06 15:15:06 +02001355 _cache_notify_waiting_tid_locked(cache, key);
Mattias Falka59cfcf2011-09-06 15:15:06 +02001356 }
Paul Jensen41d9a502014-04-08 15:43:41 -04001357
1358 pthread_mutex_unlock(&_res_cache_list_lock);
Mattias Falka59cfcf2011-09-06 15:15:06 +02001359}
1360
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001361static struct resolv_cache_info* _find_cache_info_locked(unsigned netid);
1362
Mattias Falka59cfcf2011-09-06 15:15:06 +02001363static void
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001364_cache_flush_locked( Cache* cache )
1365{
1366 int nn;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001367
Mattias Falk3a4910c2011-02-14 12:41:11 +01001368 for (nn = 0; nn < cache->max_entries; nn++)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001369 {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001370 Entry** pnode = (Entry**) &cache->entries[nn];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001371
1372 while (*pnode != NULL) {
1373 Entry* node = *pnode;
1374 *pnode = node->hlink;
1375 entry_free(node);
1376 }
1377 }
1378
Mattias Falka59cfcf2011-09-06 15:15:06 +02001379 // flush pending request
1380 _cache_flush_pending_requests_locked(cache);
1381
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001382 cache->mru_list.mru_next = cache->mru_list.mru_prev = &cache->mru_list;
1383 cache->num_entries = 0;
1384 cache->last_id = 0;
1385
1386 XLOG("*************************\n"
1387 "*** DNS CACHE FLUSHED ***\n"
1388 "*************************");
1389}
1390
Mattias Falk3a4910c2011-02-14 12:41:11 +01001391static int
1392_res_cache_get_max_entries( void )
1393{
Elliott Hughes908e8c22014-01-28 14:54:11 -08001394 int cache_size = CONFIG_MAX_ENTRIES;
Mattias Falk3a4910c2011-02-14 12:41:11 +01001395
Robert Greenwalt52764f52012-01-25 15:16:03 -08001396 const char* cache_mode = getenv("ANDROID_DNS_MODE");
Robert Greenwalt52764f52012-01-25 15:16:03 -08001397 if (cache_mode == NULL || strcmp(cache_mode, "local") != 0) {
Elliott Hughes908e8c22014-01-28 14:54:11 -08001398 // Don't use the cache in local mode. This is used by the proxy itself.
1399 cache_size = 0;
Robert Greenwalt52764f52012-01-25 15:16:03 -08001400 }
1401
Elliott Hughes908e8c22014-01-28 14:54:11 -08001402 XLOG("cache size: %d", cache_size);
1403 return cache_size;
Mattias Falk3a4910c2011-02-14 12:41:11 +01001404}
1405
Jim Huang7cc56662010-10-15 02:02:57 +08001406static struct resolv_cache*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001407_resolv_cache_create( void )
1408{
1409 struct resolv_cache* cache;
1410
1411 cache = calloc(sizeof(*cache), 1);
1412 if (cache) {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001413 cache->max_entries = _res_cache_get_max_entries();
1414 cache->entries = calloc(sizeof(*cache->entries), cache->max_entries);
1415 if (cache->entries) {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001416 cache->mru_list.mru_prev = cache->mru_list.mru_next = &cache->mru_list;
1417 XLOG("%s: cache created\n", __FUNCTION__);
1418 } else {
1419 free(cache);
1420 cache = NULL;
1421 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001422 }
1423 return cache;
1424}
1425
1426
1427#if DEBUG
1428static void
1429_dump_query( const uint8_t* query, int querylen )
1430{
1431 char temp[256], *p=temp, *end=p+sizeof(temp);
1432 DnsPacket pack[1];
1433
1434 _dnsPacket_init(pack, query, querylen);
1435 p = _dnsPacket_bprintQuery(pack, p, end);
1436 XLOG("QUERY: %s", temp);
1437}
1438
1439static void
1440_cache_dump_mru( Cache* cache )
1441{
1442 char temp[512], *p=temp, *end=p+sizeof(temp);
1443 Entry* e;
1444
1445 p = _bprint(temp, end, "MRU LIST (%2d): ", cache->num_entries);
1446 for (e = cache->mru_list.mru_next; e != &cache->mru_list; e = e->mru_next)
1447 p = _bprint(p, end, " %d", e->id);
1448
1449 XLOG("%s", temp);
1450}
Mattias Falk3e0c5102011-01-31 12:42:26 +01001451
1452static void
1453_dump_answer(const void* answer, int answerlen)
1454{
1455 res_state statep;
1456 FILE* fp;
1457 char* buf;
1458 int fileLen;
1459
Elliott Hughesc674edb2014-08-26 15:56:54 -07001460 fp = fopen("/data/reslog.txt", "w+e");
Mattias Falk3e0c5102011-01-31 12:42:26 +01001461 if (fp != NULL) {
1462 statep = __res_get_state();
1463
1464 res_pquery(statep, answer, answerlen, fp);
1465
1466 //Get file length
1467 fseek(fp, 0, SEEK_END);
1468 fileLen=ftell(fp);
1469 fseek(fp, 0, SEEK_SET);
1470 buf = (char *)malloc(fileLen+1);
1471 if (buf != NULL) {
1472 //Read file contents into buffer
1473 fread(buf, fileLen, 1, fp);
1474 XLOG("%s\n", buf);
1475 free(buf);
1476 }
1477 fclose(fp);
1478 remove("/data/reslog.txt");
1479 }
1480 else {
Robert Greenwalt78851f12013-01-07 12:10:06 -08001481 errno = 0; // else debug is introducing error signals
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001482 XLOG("%s: can't open file\n", __FUNCTION__);
Mattias Falk3e0c5102011-01-31 12:42:26 +01001483 }
1484}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001485#endif
1486
1487#if DEBUG
1488# define XLOG_QUERY(q,len) _dump_query((q), (len))
Mattias Falk3e0c5102011-01-31 12:42:26 +01001489# define XLOG_ANSWER(a, len) _dump_answer((a), (len))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001490#else
1491# define XLOG_QUERY(q,len) ((void)0)
Mattias Falk3e0c5102011-01-31 12:42:26 +01001492# define XLOG_ANSWER(a,len) ((void)0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001493#endif
1494
1495/* This function tries to find a key within the hash table
1496 * In case of success, it will return a *pointer* to the hashed key.
1497 * In case of failure, it will return a *pointer* to NULL
1498 *
1499 * So, the caller must check '*result' to check for success/failure.
1500 *
1501 * The main idea is that the result can later be used directly in
1502 * calls to _resolv_cache_add or _resolv_cache_remove as the 'lookup'
1503 * parameter. This makes the code simpler and avoids re-searching
1504 * for the key position in the htable.
1505 *
1506 * The result of a lookup_p is only valid until you alter the hash
1507 * table.
1508 */
1509static Entry**
1510_cache_lookup_p( Cache* cache,
1511 Entry* key )
1512{
Mattias Falk3a4910c2011-02-14 12:41:11 +01001513 int index = key->hash % cache->max_entries;
1514 Entry** pnode = (Entry**) &cache->entries[ index ];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001515
1516 while (*pnode != NULL) {
1517 Entry* node = *pnode;
1518
1519 if (node == NULL)
1520 break;
1521
1522 if (node->hash == key->hash && entry_equals(node, key))
1523 break;
1524
1525 pnode = &node->hlink;
1526 }
Mattias Falkc63e5902011-08-23 14:34:14 +02001527 return pnode;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001528}
1529
1530/* Add a new entry to the hash table. 'lookup' must be the
1531 * result of an immediate previous failed _lookup_p() call
1532 * (i.e. with *lookup == NULL), and 'e' is the pointer to the
1533 * newly created entry
1534 */
1535static void
1536_cache_add_p( Cache* cache,
1537 Entry** lookup,
1538 Entry* e )
1539{
1540 *lookup = e;
1541 e->id = ++cache->last_id;
1542 entry_mru_add(e, &cache->mru_list);
1543 cache->num_entries += 1;
1544
1545 XLOG("%s: entry %d added (count=%d)", __FUNCTION__,
1546 e->id, cache->num_entries);
1547}
1548
1549/* Remove an existing entry from the hash table,
1550 * 'lookup' must be the result of an immediate previous
1551 * and succesful _lookup_p() call.
1552 */
1553static void
1554_cache_remove_p( Cache* cache,
1555 Entry** lookup )
1556{
1557 Entry* e = *lookup;
1558
1559 XLOG("%s: entry %d removed (count=%d)", __FUNCTION__,
1560 e->id, cache->num_entries-1);
1561
1562 entry_mru_remove(e);
1563 *lookup = e->hlink;
1564 entry_free(e);
1565 cache->num_entries -= 1;
1566}
1567
1568/* Remove the oldest entry from the hash table.
1569 */
1570static void
1571_cache_remove_oldest( Cache* cache )
1572{
1573 Entry* oldest = cache->mru_list.mru_prev;
1574 Entry** lookup = _cache_lookup_p(cache, oldest);
1575
1576 if (*lookup == NULL) { /* should not happen */
1577 XLOG("%s: OLDEST NOT IN HTABLE ?", __FUNCTION__);
1578 return;
1579 }
Robert Greenwalt7f84da62011-09-02 07:44:36 -07001580 if (DEBUG) {
1581 XLOG("Cache full - removing oldest");
1582 XLOG_QUERY(oldest->query, oldest->querylen);
1583 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001584 _cache_remove_p(cache, lookup);
1585}
1586
Anders Fredlunddd161822011-05-20 08:12:37 +02001587/* Remove all expired entries from the hash table.
1588 */
1589static void _cache_remove_expired(Cache* cache) {
1590 Entry* e;
1591 time_t now = _time_now();
1592
1593 for (e = cache->mru_list.mru_next; e != &cache->mru_list;) {
1594 // Entry is old, remove
1595 if (now >= e->expires) {
1596 Entry** lookup = _cache_lookup_p(cache, e);
1597 if (*lookup == NULL) { /* should not happen */
1598 XLOG("%s: ENTRY NOT IN HTABLE ?", __FUNCTION__);
1599 return;
1600 }
1601 e = e->mru_next;
1602 _cache_remove_p(cache, lookup);
1603 } else {
1604 e = e->mru_next;
1605 }
1606 }
1607}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001608
1609ResolvCacheStatus
Paul Jensen41d9a502014-04-08 15:43:41 -04001610_resolv_cache_lookup( unsigned netid,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001611 const void* query,
1612 int querylen,
1613 void* answer,
1614 int answersize,
1615 int *answerlen )
1616{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001617 Entry key[1];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001618 Entry** lookup;
1619 Entry* e;
1620 time_t now;
Paul Jensen41d9a502014-04-08 15:43:41 -04001621 Cache* cache;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001622
1623 ResolvCacheStatus result = RESOLV_CACHE_NOTFOUND;
1624
1625 XLOG("%s: lookup", __FUNCTION__);
1626 XLOG_QUERY(query, querylen);
1627
1628 /* we don't cache malformed queries */
1629 if (!entry_init_key(key, query, querylen)) {
1630 XLOG("%s: unsupported query", __FUNCTION__);
1631 return RESOLV_CACHE_UNSUPPORTED;
1632 }
1633 /* lookup cache */
Paul Jensen41d9a502014-04-08 15:43:41 -04001634 pthread_once(&_res_cache_once, _res_cache_init);
1635 pthread_mutex_lock(&_res_cache_list_lock);
1636
1637 cache = _find_named_cache_locked(netid);
1638 if (cache == NULL) {
1639 result = RESOLV_CACHE_UNSUPPORTED;
1640 goto Exit;
1641 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001642
1643 /* see the description of _lookup_p to understand this.
1644 * the function always return a non-NULL pointer.
1645 */
1646 lookup = _cache_lookup_p(cache, key);
1647 e = *lookup;
1648
1649 if (e == NULL) {
1650 XLOG( "NOT IN CACHE");
Mattias Falka59cfcf2011-09-06 15:15:06 +02001651 // calling thread will wait if an outstanding request is found
1652 // that matching this query
Paul Jensen41d9a502014-04-08 15:43:41 -04001653 if (!_cache_check_pending_request_locked(&cache, key, netid) || cache == NULL) {
Mattias Falka59cfcf2011-09-06 15:15:06 +02001654 goto Exit;
1655 } else {
1656 lookup = _cache_lookup_p(cache, key);
1657 e = *lookup;
1658 if (e == NULL) {
1659 goto Exit;
1660 }
1661 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001662 }
1663
1664 now = _time_now();
1665
1666 /* remove stale entries here */
Mattias Falk3e0c5102011-01-31 12:42:26 +01001667 if (now >= e->expires) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001668 XLOG( " NOT IN CACHE (STALE ENTRY %p DISCARDED)", *lookup );
Robert Greenwalt7f84da62011-09-02 07:44:36 -07001669 XLOG_QUERY(e->query, e->querylen);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001670 _cache_remove_p(cache, lookup);
1671 goto Exit;
1672 }
1673
1674 *answerlen = e->answerlen;
1675 if (e->answerlen > answersize) {
1676 /* NOTE: we return UNSUPPORTED if the answer buffer is too short */
1677 result = RESOLV_CACHE_UNSUPPORTED;
1678 XLOG(" ANSWER TOO LONG");
1679 goto Exit;
1680 }
1681
1682 memcpy( answer, e->answer, e->answerlen );
1683
1684 /* bump up this entry to the top of the MRU list */
1685 if (e != cache->mru_list.mru_next) {
1686 entry_mru_remove( e );
1687 entry_mru_add( e, &cache->mru_list );
1688 }
1689
1690 XLOG( "FOUND IN CACHE entry=%p", e );
1691 result = RESOLV_CACHE_FOUND;
1692
1693Exit:
Paul Jensen41d9a502014-04-08 15:43:41 -04001694 pthread_mutex_unlock(&_res_cache_list_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001695 return result;
1696}
1697
1698
1699void
Paul Jensen41d9a502014-04-08 15:43:41 -04001700_resolv_cache_add( unsigned netid,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001701 const void* query,
1702 int querylen,
1703 const void* answer,
1704 int answerlen )
1705{
1706 Entry key[1];
1707 Entry* e;
1708 Entry** lookup;
Mattias Falk3e0c5102011-01-31 12:42:26 +01001709 u_long ttl;
Paul Jensen41d9a502014-04-08 15:43:41 -04001710 Cache* cache = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001711
1712 /* don't assume that the query has already been cached
1713 */
1714 if (!entry_init_key( key, query, querylen )) {
1715 XLOG( "%s: passed invalid query ?", __FUNCTION__);
1716 return;
1717 }
1718
Paul Jensen41d9a502014-04-08 15:43:41 -04001719 pthread_mutex_lock(&_res_cache_list_lock);
1720
1721 cache = _find_named_cache_locked(netid);
1722 if (cache == NULL) {
1723 goto Exit;
1724 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001725
1726 XLOG( "%s: query:", __FUNCTION__ );
1727 XLOG_QUERY(query,querylen);
Mattias Falk3e0c5102011-01-31 12:42:26 +01001728 XLOG_ANSWER(answer, answerlen);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001729#if DEBUG_DATA
1730 XLOG( "answer:");
1731 XLOG_BYTES(answer,answerlen);
1732#endif
1733
1734 lookup = _cache_lookup_p(cache, key);
1735 e = *lookup;
1736
1737 if (e != NULL) { /* should not happen */
1738 XLOG("%s: ALREADY IN CACHE (%p) ? IGNORING ADD",
1739 __FUNCTION__, e);
1740 goto Exit;
1741 }
1742
Mattias Falk3a4910c2011-02-14 12:41:11 +01001743 if (cache->num_entries >= cache->max_entries) {
Anders Fredlunddd161822011-05-20 08:12:37 +02001744 _cache_remove_expired(cache);
1745 if (cache->num_entries >= cache->max_entries) {
1746 _cache_remove_oldest(cache);
1747 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001748 /* need to lookup again */
1749 lookup = _cache_lookup_p(cache, key);
1750 e = *lookup;
1751 if (e != NULL) {
1752 XLOG("%s: ALREADY IN CACHE (%p) ? IGNORING ADD",
1753 __FUNCTION__, e);
1754 goto Exit;
1755 }
1756 }
1757
Mattias Falk3e0c5102011-01-31 12:42:26 +01001758 ttl = answer_getTTL(answer, answerlen);
1759 if (ttl > 0) {
1760 e = entry_alloc(key, answer, answerlen);
1761 if (e != NULL) {
1762 e->expires = ttl + _time_now();
1763 _cache_add_p(cache, lookup, e);
1764 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001765 }
1766#if DEBUG
1767 _cache_dump_mru(cache);
1768#endif
1769Exit:
Paul Jensen41d9a502014-04-08 15:43:41 -04001770 if (cache != NULL) {
1771 _cache_notify_waiting_tid_locked(cache, key);
1772 }
1773 pthread_mutex_unlock(&_res_cache_list_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001774}
1775
1776/****************************************************************************/
1777/****************************************************************************/
1778/***** *****/
1779/***** *****/
1780/***** *****/
1781/****************************************************************************/
1782/****************************************************************************/
1783
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001784// Head of the list of caches. Protected by _res_cache_list_lock.
1785static struct resolv_cache_info _res_cache_list;
1786
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001787/* insert resolv_cache_info into the list of resolv_cache_infos */
1788static void _insert_cache_info_locked(struct resolv_cache_info* cache_info);
1789/* creates a resolv_cache_info */
1790static struct resolv_cache_info* _create_cache_info( void );
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001791/* gets a resolv_cache_info associated with a network, or NULL if not found */
1792static struct resolv_cache_info* _find_cache_info_locked(unsigned netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001793/* look up the named cache, and creates one if needed */
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001794static struct resolv_cache* _get_res_cache_for_net_locked(unsigned netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001795/* empty the named cache */
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001796static void _flush_cache_for_net_locked(unsigned netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001797/* empty the nameservers set for the named cache */
1798static void _free_nameservers_locked(struct resolv_cache_info* cache_info);
Mattias Falkc63e5902011-08-23 14:34:14 +02001799/* return 1 if the provided list of name servers differs from the list of name servers
1800 * currently attached to the provided cache_info */
1801static int _resolv_is_nameservers_equal_locked(struct resolv_cache_info* cache_info,
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08001802 const char** servers, int numservers);
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001803/* clears the stats samples contained withing the given cache_info */
1804static void _res_cache_clear_stats_locked(struct resolv_cache_info* cache_info);
Chad Brubaker0c9bb492013-05-30 13:37:02 -07001805
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001806static void
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001807_res_cache_init(void)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001808{
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001809 memset(&_res_cache_list, 0, sizeof(_res_cache_list));
1810 pthread_mutex_init(&_res_cache_list_lock, NULL);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001811}
1812
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001813static struct resolv_cache*
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001814_get_res_cache_for_net_locked(unsigned netid)
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001815{
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001816 struct resolv_cache* cache = _find_named_cache_locked(netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001817 if (!cache) {
1818 struct resolv_cache_info* cache_info = _create_cache_info();
1819 if (cache_info) {
1820 cache = _resolv_cache_create();
1821 if (cache) {
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001822 cache_info->cache = cache;
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001823 cache_info->netid = netid;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001824 _insert_cache_info_locked(cache_info);
1825 } else {
1826 free(cache_info);
1827 }
1828 }
1829 }
1830 return cache;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001831}
1832
Paul Jensen1544eae2014-08-06 17:34:22 +00001833void
1834_resolv_flush_cache_for_net(unsigned netid)
1835{
1836 pthread_once(&_res_cache_once, _res_cache_init);
1837 pthread_mutex_lock(&_res_cache_list_lock);
1838
1839 _flush_cache_for_net_locked(netid);
1840
1841 pthread_mutex_unlock(&_res_cache_list_lock);
1842}
1843
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001844static void
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001845_flush_cache_for_net_locked(unsigned netid)
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001846{
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001847 struct resolv_cache* cache = _find_named_cache_locked(netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001848 if (cache) {
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001849 _cache_flush_locked(cache);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001850 }
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001851
1852 // Also clear the NS statistics.
1853 struct resolv_cache_info* cache_info = _find_cache_info_locked(netid);
1854 _res_cache_clear_stats_locked(cache_info);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001855}
1856
Paul Jensen41d9a502014-04-08 15:43:41 -04001857void _resolv_delete_cache_for_net(unsigned netid)
1858{
1859 pthread_once(&_res_cache_once, _res_cache_init);
1860 pthread_mutex_lock(&_res_cache_list_lock);
1861
1862 struct resolv_cache_info* prev_cache_info = &_res_cache_list;
1863
1864 while (prev_cache_info->next) {
1865 struct resolv_cache_info* cache_info = prev_cache_info->next;
1866
1867 if (cache_info->netid == netid) {
1868 prev_cache_info->next = cache_info->next;
1869 _cache_flush_locked(cache_info->cache);
1870 free(cache_info->cache->entries);
1871 free(cache_info->cache);
1872 _free_nameservers_locked(cache_info);
1873 free(cache_info);
1874 break;
1875 }
1876
1877 prev_cache_info = prev_cache_info->next;
1878 }
1879
1880 pthread_mutex_unlock(&_res_cache_list_lock);
1881}
1882
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001883static struct resolv_cache_info*
1884_create_cache_info(void)
1885{
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001886 struct resolv_cache_info* cache_info;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001887
1888 cache_info = calloc(sizeof(*cache_info), 1);
1889 return cache_info;
1890}
1891
1892static void
1893_insert_cache_info_locked(struct resolv_cache_info* cache_info)
1894{
1895 struct resolv_cache_info* last;
1896
1897 for (last = &_res_cache_list; last->next; last = last->next);
1898
1899 last->next = cache_info;
1900
1901}
1902
1903static struct resolv_cache*
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001904_find_named_cache_locked(unsigned netid) {
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001905
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001906 struct resolv_cache_info* info = _find_cache_info_locked(netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001907
1908 if (info != NULL) return info->cache;
1909
1910 return NULL;
1911}
1912
1913static struct resolv_cache_info*
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001914_find_cache_info_locked(unsigned netid)
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001915{
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001916 struct resolv_cache_info* cache_info = _res_cache_list.next;
1917
1918 while (cache_info) {
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001919 if (cache_info->netid == netid) {
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001920 break;
1921 }
1922
1923 cache_info = cache_info->next;
1924 }
1925 return cache_info;
1926}
1927
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001928void
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001929_resolv_set_default_params(struct __res_params* params) {
1930 params->sample_validity = NSSAMPLE_VALIDITY;
1931 params->success_threshold = SUCCESS_THRESHOLD;
1932 params->min_samples = 0;
1933 params->max_samples = 0;
1934}
1935
Pierre Imaifff35672016-04-18 11:42:14 +09001936int
1937_resolv_set_nameservers_for_net(unsigned netid, const char** servers, unsigned numservers,
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001938 const char *domains, const struct __res_params* params)
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001939{
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001940 char sbuf[NI_MAXSERV];
Mattias Falkc63e5902011-08-23 14:34:14 +02001941 register char *cp;
1942 int *offset;
Pierre Imaifff35672016-04-18 11:42:14 +09001943 struct addrinfo* nsaddrinfo[MAXNS];
1944
1945 if (numservers > MAXNS) {
1946 XLOG("%s: numservers=%u, MAXNS=%u", __FUNCTION__, numservers, MAXNS);
1947 return E2BIG;
1948 }
1949
1950 // Parse the addresses before actually locking or changing any state, in case there is an error.
1951 // As a side effect this also reduces the time the lock is kept.
1952 struct addrinfo hints = {
1953 .ai_family = AF_UNSPEC,
1954 .ai_socktype = SOCK_DGRAM,
1955 .ai_flags = AI_NUMERICHOST
1956 };
1957 snprintf(sbuf, sizeof(sbuf), "%u", NAMESERVER_PORT);
1958 for (unsigned i = 0; i < numservers; i++) {
1959 // The addrinfo structures allocated here are freed in _free_nameservers_locked().
1960 int rt = getaddrinfo(servers[i], sbuf, &hints, &nsaddrinfo[i]);
1961 if (rt != 0) {
1962 for (unsigned j = 0 ; j < i ; j++) {
1963 freeaddrinfo(nsaddrinfo[j]);
1964 nsaddrinfo[j] = NULL;
1965 }
1966 XLOG("%s: getaddrinfo(%s)=%s", __FUNCTION__, servers[i], gai_strerror(rt));
1967 return EINVAL;
1968 }
1969 }
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001970
1971 pthread_once(&_res_cache_once, _res_cache_init);
Robert Greenwaltb002a2f2013-01-19 00:40:24 +00001972 pthread_mutex_lock(&_res_cache_list_lock);
Mattias Falkc63e5902011-08-23 14:34:14 +02001973
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001974 // creates the cache if not created
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001975 _get_res_cache_for_net_locked(netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001976
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001977 struct resolv_cache_info* cache_info = _find_cache_info_locked(netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001978
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001979 if (cache_info != NULL) {
1980 uint8_t old_max_samples = cache_info->params.max_samples;
1981 if (params != NULL) {
1982 cache_info->params = *params;
1983 } else {
1984 _resolv_set_default_params(&cache_info->params);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001985 }
Mattias Falkc63e5902011-08-23 14:34:14 +02001986
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001987 if (!_resolv_is_nameservers_equal_locked(cache_info, servers, numservers)) {
1988 // free current before adding new
1989 _free_nameservers_locked(cache_info);
Pierre Imaifff35672016-04-18 11:42:14 +09001990 unsigned i;
1991 for (i = 0; i < numservers; i++) {
1992 cache_info->nsaddrinfo[i] = nsaddrinfo[i];
1993 cache_info->nameservers[i] = strdup(servers[i]);
1994 XLOG("%s: netid = %u, addr = %s\n", __FUNCTION__, netid, servers[i]);
Mattias Falkc63e5902011-08-23 14:34:14 +02001995 }
Pierre Imaifff35672016-04-18 11:42:14 +09001996 cache_info->nscount = numservers;
Mattias Falkc63e5902011-08-23 14:34:14 +02001997
Erik Kline0e4cdff2016-11-08 18:06:57 +09001998 // Clear the NS statistics because the mapping to nameservers might have changed.
1999 _res_cache_clear_stats_locked(cache_info);
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002000
2001 // increment the revision id to ensure that sample state is not written back if the
2002 // servers change; in theory it would suffice to do so only if the servers or
2003 // max_samples actually change, in practice the overhead of checking is higher than the
2004 // cost, and overflows are unlikely
2005 ++cache_info->revision_id;
Pierre Imai06e22022016-05-06 17:56:57 +09002006 } else if (cache_info->params.max_samples != old_max_samples) {
2007 // If the maximum number of samples changes, the overhead of keeping the most recent
2008 // samples around is not considered worth the effort, so they are cleared instead. All
2009 // other parameters do not affect shared state: Changing these parameters does not
2010 // invalidate the samples, as they only affect aggregation and the conditions under
2011 // which servers are considered usable.
2012 _res_cache_clear_stats_locked(cache_info);
2013 ++cache_info->revision_id;
2014 }
2015
2016 // Always update the search paths, since determining whether they actually changed is
2017 // complex due to the zero-padding, and probably not worth the effort. Cache-flushing
2018 // however is not // necessary, since the stored cache entries do contain the domain, not
2019 // just the host name.
2020 // code moved from res_init.c, load_domain_search_list
2021 strlcpy(cache_info->defdname, domains, sizeof(cache_info->defdname));
2022 if ((cp = strchr(cache_info->defdname, '\n')) != NULL)
2023 *cp = '\0';
2024
2025 cp = cache_info->defdname;
2026 offset = cache_info->dnsrch_offset;
2027 while (offset < cache_info->dnsrch_offset + MAXDNSRCH) {
2028 while (*cp == ' ' || *cp == '\t') /* skip leading white space */
2029 cp++;
2030 if (*cp == '\0') /* stop if nothing more to do */
2031 break;
2032 *offset++ = cp - cache_info->defdname; /* record this search domain */
2033 while (*cp) { /* zero-terminate it */
2034 if (*cp == ' '|| *cp == '\t') {
2035 *cp++ = '\0';
2036 break;
2037 }
2038 cp++;
2039 }
2040 }
2041 *offset = -1; /* cache_info->dnsrch_offset has MAXDNSRCH+1 items */
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002042 }
Mattias Falkc63e5902011-08-23 14:34:14 +02002043
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002044 pthread_mutex_unlock(&_res_cache_list_lock);
Pierre Imaifff35672016-04-18 11:42:14 +09002045 return 0;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002046}
2047
Mattias Falkc63e5902011-08-23 14:34:14 +02002048static int
2049_resolv_is_nameservers_equal_locked(struct resolv_cache_info* cache_info,
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08002050 const char** servers, int numservers)
Mattias Falkc63e5902011-08-23 14:34:14 +02002051{
Pierre Imaifff35672016-04-18 11:42:14 +09002052 if (cache_info->nscount != numservers) {
Lorenzo Colittibce18c92014-09-08 18:09:43 +09002053 return 0;
Pierre Imaifff35672016-04-18 11:42:14 +09002054 }
Lorenzo Colittibce18c92014-09-08 18:09:43 +09002055
2056 // Compare each name server against current name servers.
2057 // TODO: this is incorrect if the list of current or previous nameservers
2058 // contains duplicates. This does not really matter because the framework
2059 // filters out duplicates, but we should probably fix it. It's also
2060 // insensitive to the order of the nameservers; we should probably fix that
2061 // too.
Pierre Imaifff35672016-04-18 11:42:14 +09002062 for (int i = 0; i < numservers; i++) {
2063 for (int j = 0 ; ; j++) {
2064 if (j >= numservers) {
2065 return 0;
2066 }
2067 if (strcmp(cache_info->nameservers[i], servers[j]) == 0) {
Mattias Falkc63e5902011-08-23 14:34:14 +02002068 break;
2069 }
Mattias Falkc63e5902011-08-23 14:34:14 +02002070 }
2071 }
2072
Pierre Imaifff35672016-04-18 11:42:14 +09002073 return 1;
Mattias Falkc63e5902011-08-23 14:34:14 +02002074}
2075
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002076static void
2077_free_nameservers_locked(struct resolv_cache_info* cache_info)
2078{
2079 int i;
Pierre Imaifff35672016-04-18 11:42:14 +09002080 for (i = 0; i < cache_info->nscount; i++) {
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002081 free(cache_info->nameservers[i]);
2082 cache_info->nameservers[i] = NULL;
Robert Greenwalt9363d912011-07-25 12:30:17 -07002083 if (cache_info->nsaddrinfo[i] != NULL) {
2084 freeaddrinfo(cache_info->nsaddrinfo[i]);
2085 cache_info->nsaddrinfo[i] = NULL;
2086 }
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002087 cache_info->nsstats[i].sample_count =
2088 cache_info->nsstats[i].sample_next = 0;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002089 }
Pierre Imaifff35672016-04-18 11:42:14 +09002090 cache_info->nscount = 0;
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002091 _res_cache_clear_stats_locked(cache_info);
2092 ++cache_info->revision_id;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002093}
2094
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002095void
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002096_resolv_populate_res_for_net(res_state statp)
Mattias Falkc63e5902011-08-23 14:34:14 +02002097{
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08002098 if (statp == NULL) {
2099 return;
2100 }
Mattias Falkc63e5902011-08-23 14:34:14 +02002101
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08002102 pthread_once(&_res_cache_once, _res_cache_init);
2103 pthread_mutex_lock(&_res_cache_list_lock);
2104
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002105 struct resolv_cache_info* info = _find_cache_info_locked(statp->netid);
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08002106 if (info != NULL) {
2107 int nserv;
Mattias Falkc63e5902011-08-23 14:34:14 +02002108 struct addrinfo* ai;
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002109 XLOG("%s: %u\n", __FUNCTION__, statp->netid);
Mattias Falkc63e5902011-08-23 14:34:14 +02002110 for (nserv = 0; nserv < MAXNS; nserv++) {
2111 ai = info->nsaddrinfo[nserv];
2112 if (ai == NULL) {
2113 break;
2114 }
2115
2116 if ((size_t) ai->ai_addrlen <= sizeof(statp->_u._ext.ext->nsaddrs[0])) {
2117 if (statp->_u._ext.ext != NULL) {
2118 memcpy(&statp->_u._ext.ext->nsaddrs[nserv], ai->ai_addr, ai->ai_addrlen);
2119 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
2120 } else {
2121 if ((size_t) ai->ai_addrlen
2122 <= sizeof(statp->nsaddr_list[0])) {
2123 memcpy(&statp->nsaddr_list[nserv], ai->ai_addr,
2124 ai->ai_addrlen);
2125 } else {
2126 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
2127 }
2128 }
2129 } else {
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002130 XLOG("%s: found too long addrlen", __FUNCTION__);
Mattias Falkc63e5902011-08-23 14:34:14 +02002131 }
2132 }
2133 statp->nscount = nserv;
2134 // now do search domains. Note that we cache the offsets as this code runs alot
2135 // but the setting/offset-computer only runs when set/changed
Pierre Imai0967fc72016-02-29 16:31:55 +09002136 // WARNING: Don't use str*cpy() here, this string contains zeroes.
2137 memcpy(statp->defdname, info->defdname, sizeof(statp->defdname));
Mattias Falkc63e5902011-08-23 14:34:14 +02002138 register char **pp = statp->dnsrch;
2139 register int *p = info->dnsrch_offset;
2140 while (pp < statp->dnsrch + MAXDNSRCH && *p != -1) {
Elliott Hughes37b1b5b2014-07-02 16:27:20 -07002141 *pp++ = &statp->defdname[0] + *p++;
Mattias Falkc63e5902011-08-23 14:34:14 +02002142 }
Mattias Falkc63e5902011-08-23 14:34:14 +02002143 }
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08002144 pthread_mutex_unlock(&_res_cache_list_lock);
Mattias Falkc63e5902011-08-23 14:34:14 +02002145}
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002146
2147/* Resolver reachability statistics. */
2148
2149static void
2150_res_cache_add_stats_sample_locked(struct __res_stats* stats, const struct __res_sample* sample,
2151 int max_samples) {
2152 // Note: This function expects max_samples > 0, otherwise a (harmless) modification of the
2153 // allocated but supposedly unused memory for samples[0] will happen
2154 XLOG("%s: adding sample to stats, next = %d, count = %d", __FUNCTION__,
2155 stats->sample_next, stats->sample_count);
2156 stats->samples[stats->sample_next] = *sample;
2157 if (stats->sample_count < max_samples) {
2158 ++stats->sample_count;
2159 }
2160 if (++stats->sample_next >= max_samples) {
2161 stats->sample_next = 0;
2162 }
2163}
2164
2165static void
2166_res_cache_clear_stats_locked(struct resolv_cache_info* cache_info) {
2167 if (cache_info) {
2168 for (int i = 0 ; i < MAXNS ; ++i) {
2169 cache_info->nsstats->sample_count = cache_info->nsstats->sample_next = 0;
2170 }
2171 }
2172}
2173
2174int
Pierre Imai97c9d732016-04-18 12:00:12 +09002175android_net_res_stats_get_info_for_net(unsigned netid, int* nscount,
2176 struct sockaddr_storage servers[MAXNS], int* dcount, char domains[MAXDNSRCH][MAXDNSRCHPATH],
2177 struct __res_params* params, struct __res_stats stats[MAXNS]) {
2178 int revision_id = -1;
2179 pthread_mutex_lock(&_res_cache_list_lock);
2180
2181 struct resolv_cache_info* info = _find_cache_info_locked(netid);
2182 if (info) {
2183 if (info->nscount > MAXNS) {
2184 pthread_mutex_unlock(&_res_cache_list_lock);
2185 XLOG("%s: nscount %d > MAXNS %d", __FUNCTION__, info->nscount, MAXNS);
2186 errno = EFAULT;
2187 return -1;
2188 }
2189 int i;
2190 for (i = 0; i < info->nscount; i++) {
2191 // Verify that the following assumptions are held, failure indicates corruption:
2192 // - getaddrinfo() may never return a sockaddr > sockaddr_storage
2193 // - all addresses are valid
2194 // - there is only one address per addrinfo thanks to numeric resolution
2195 int addrlen = info->nsaddrinfo[i]->ai_addrlen;
2196 if (addrlen < (int) sizeof(struct sockaddr) ||
2197 addrlen > (int) sizeof(servers[0])) {
2198 pthread_mutex_unlock(&_res_cache_list_lock);
2199 XLOG("%s: nsaddrinfo[%d].ai_addrlen == %d", __FUNCTION__, i, addrlen);
2200 errno = EMSGSIZE;
2201 return -1;
2202 }
2203 if (info->nsaddrinfo[i]->ai_addr == NULL) {
2204 pthread_mutex_unlock(&_res_cache_list_lock);
2205 XLOG("%s: nsaddrinfo[%d].ai_addr == NULL", __FUNCTION__, i);
2206 errno = ENOENT;
2207 return -1;
2208 }
2209 if (info->nsaddrinfo[i]->ai_next != NULL) {
2210 pthread_mutex_unlock(&_res_cache_list_lock);
2211 XLOG("%s: nsaddrinfo[%d].ai_next != NULL", __FUNCTION__, i);
2212 errno = ENOTUNIQ;
2213 return -1;
2214 }
2215 }
2216 *nscount = info->nscount;
2217 for (i = 0; i < info->nscount; i++) {
2218 memcpy(&servers[i], info->nsaddrinfo[i]->ai_addr, info->nsaddrinfo[i]->ai_addrlen);
2219 stats[i] = info->nsstats[i];
2220 }
2221 for (i = 0; i < MAXDNSRCH; i++) {
Pierre Imai1b069a92016-04-26 22:08:40 +09002222 const char* cur_domain = info->defdname + info->dnsrch_offset[i];
2223 // dnsrch_offset[i] can either be -1 or point to an empty string to indicate the end
2224 // of the search offsets. Checking for < 0 is not strictly necessary, but safer.
2225 // TODO: Pass in a search domain array instead of a string to
2226 // _resolv_set_nameservers_for_net() and make this double check unnecessary.
2227 if (info->dnsrch_offset[i] < 0 ||
2228 ((size_t)info->dnsrch_offset[i]) >= sizeof(info->defdname) || !cur_domain[0]) {
Pierre Imai97c9d732016-04-18 12:00:12 +09002229 break;
2230 }
Pierre Imai1b069a92016-04-26 22:08:40 +09002231 strlcpy(domains[i], cur_domain, MAXDNSRCHPATH);
Pierre Imai97c9d732016-04-18 12:00:12 +09002232 }
2233 *dcount = i;
2234 *params = info->params;
2235 revision_id = info->revision_id;
2236 }
2237
2238 pthread_mutex_unlock(&_res_cache_list_lock);
2239 return revision_id;
2240}
2241
2242int
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002243_resolv_cache_get_resolver_stats( unsigned netid, struct __res_params* params,
2244 struct __res_stats stats[MAXNS]) {
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002245 int revision_id = -1;
2246 pthread_mutex_lock(&_res_cache_list_lock);
2247
2248 struct resolv_cache_info* info = _find_cache_info_locked(netid);
2249 if (info) {
2250 memcpy(stats, info->nsstats, sizeof(info->nsstats));
2251 *params = info->params;
2252 revision_id = info->revision_id;
2253 }
2254
2255 pthread_mutex_unlock(&_res_cache_list_lock);
2256 return revision_id;
2257}
2258
2259void
2260_resolv_cache_add_resolver_stats_sample( unsigned netid, int revision_id, int ns,
2261 const struct __res_sample* sample, int max_samples) {
2262 if (max_samples <= 0) return;
2263
2264 pthread_mutex_lock(&_res_cache_list_lock);
2265
2266 struct resolv_cache_info* info = _find_cache_info_locked(netid);
2267
2268 if (info && info->revision_id == revision_id) {
2269 _res_cache_add_stats_sample_locked(&info->nsstats[ns], sample, max_samples);
2270 }
2271
2272 pthread_mutex_unlock(&_res_cache_list_lock);
2273}