blob: 5f51c49595417ded53ed5b2f141147563d1ec416 [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"
Mattias Falk23d3e6b2011-04-04 16:12:35 +020030#include <resolv.h>
Lorenzo Colitti616344d2014-11-28 11:47:13 +090031#include <stdarg.h>
32#include <stdio.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080033#include <stdlib.h>
34#include <string.h>
35#include <time.h>
36#include "pthread.h"
37
Mattias Falk3e0c5102011-01-31 12:42:26 +010038#include <errno.h>
Calin Juravle569fb982014-03-04 15:01:29 +000039#include <arpa/nameser.h>
Mattias Falk3a4910c2011-02-14 12:41:11 +010040#include <sys/system_properties.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
Lorenzo Colitti616344d2014-11-28 11:47:13 +090050#include "private/libc_logging.h"
51
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
101/* the name of an environment variable that will be checked the first time
102 * this code is called if its value is "0", then the resolver cache is
103 * disabled.
104 */
105#define CONFIG_ENV "BIONIC_DNSCACHE"
106
Mattias Falk3a4910c2011-02-14 12:41:11 +0100107/* default number of entries kept in the cache. This value has been
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800108 * determined by browsing through various sites and counting the number
109 * of corresponding requests. Keep in mind that our framework is currently
110 * performing two requests per name lookup (one for IPv4, the other for IPv6)
111 *
112 * www.google.com 4
113 * www.ysearch.com 6
114 * www.amazon.com 8
115 * www.nytimes.com 22
116 * www.espn.com 28
117 * www.msn.com 28
118 * www.lemonde.fr 35
119 *
120 * (determined in 2009-2-17 from Paris, France, results may vary depending
121 * on location)
122 *
123 * most high-level websites use lots of media/ad servers with different names
124 * but these are generally reused when browsing through the site.
125 *
Mattias Falk3a4910c2011-02-14 12:41:11 +0100126 * As such, a value of 64 should be relatively comfortable at the moment.
127 *
Robert Greenwalt52764f52012-01-25 15:16:03 -0800128 * ******************************************
129 * * NOTE - this has changed.
130 * * 1) we've added IPv6 support so each dns query results in 2 responses
131 * * 2) we've made this a system-wide cache, so the cost is less (it's not
132 * * duplicated in each process) and the need is greater (more processes
133 * * making different requests).
134 * * Upping by 2x for IPv6
135 * * Upping by another 5x for the centralized nature
136 * *****************************************
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800137 */
Robert Greenwalt52764f52012-01-25 15:16:03 -0800138#define CONFIG_MAX_ENTRIES 64 * 2 * 5
Mattias Falk3a4910c2011-02-14 12:41:11 +0100139/* name of the system property that can be used to set the cache size */
Mattias Falk3a4910c2011-02-14 12:41:11 +0100140
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800141/****************************************************************************/
142/****************************************************************************/
143/***** *****/
144/***** *****/
145/***** *****/
146/****************************************************************************/
147/****************************************************************************/
148
149/* set to 1 to debug cache operations */
150#define DEBUG 0
151
152/* set to 1 to debug query data */
153#define DEBUG_DATA 0
154
155#if DEBUG
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900156#define __DEBUG__
157#else
158#define __DEBUG__ __attribute__((unused))
159#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800160
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900161#undef XLOG
162
163#define XLOG(...) ({ \
164 if (DEBUG) { \
165 __libc_format_log(ANDROID_LOG_DEBUG,"libc",__VA_ARGS__); \
166 } else { \
167 ((void)0); \
168 } \
169})
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800170
171/** BOUNDED BUFFER FORMATTING
172 **/
173
174/* technical note:
175 *
176 * the following debugging routines are used to append data to a bounded
177 * buffer they take two parameters that are:
178 *
179 * - p : a pointer to the current cursor position in the buffer
180 * this value is initially set to the buffer's address.
181 *
182 * - end : the address of the buffer's limit, i.e. of the first byte
183 * after the buffer. this address should never be touched.
184 *
185 * IMPORTANT: it is assumed that end > buffer_address, i.e.
186 * that the buffer is at least one byte.
187 *
188 * the _bprint_() functions return the new value of 'p' after the data
189 * has been appended, and also ensure the following:
190 *
191 * - the returned value will never be strictly greater than 'end'
192 *
193 * - a return value equal to 'end' means that truncation occured
194 * (in which case, end[-1] will be set to 0)
195 *
196 * - after returning from a _bprint_() function, the content of the buffer
197 * is always 0-terminated, even in the event of truncation.
198 *
199 * these conventions allow you to call _bprint_ functions multiple times and
200 * only check for truncation at the end of the sequence, as in:
201 *
202 * char buff[1000], *p = buff, *end = p + sizeof(buff);
203 *
204 * p = _bprint_c(p, end, '"');
205 * p = _bprint_s(p, end, my_string);
206 * p = _bprint_c(p, end, '"');
207 *
208 * if (p >= end) {
209 * // buffer was too small
210 * }
211 *
212 * printf( "%s", buff );
213 */
214
215/* add a char to a bounded buffer */
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900216char*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800217_bprint_c( char* p, char* end, int c )
218{
219 if (p < end) {
220 if (p+1 == end)
221 *p++ = 0;
222 else {
223 *p++ = (char) c;
224 *p = 0;
225 }
226 }
227 return p;
228}
229
230/* add a sequence of bytes to a bounded buffer */
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900231char*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800232_bprint_b( char* p, char* end, const char* buf, int len )
233{
234 int avail = end - p;
235
236 if (avail <= 0 || len <= 0)
237 return p;
238
239 if (avail > len)
240 avail = len;
241
242 memcpy( p, buf, avail );
243 p += avail;
244
245 if (p < end)
246 p[0] = 0;
247 else
248 end[-1] = 0;
249
250 return p;
251}
252
253/* add a string to a bounded buffer */
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900254char*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800255_bprint_s( char* p, char* end, const char* str )
256{
257 return _bprint_b(p, end, str, strlen(str));
258}
259
260/* add a formatted string to a bounded buffer */
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900261char* _bprint( char* p, char* end, const char* format, ... ) __DEBUG__;
262char* _bprint( char* p, char* end, const char* format, ... )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800263{
264 int avail, n;
265 va_list args;
266
267 avail = end - p;
268
269 if (avail <= 0)
270 return p;
271
272 va_start(args, format);
David 'Digit' Turnerd378c682010-03-08 15:13:04 -0800273 n = vsnprintf( p, avail, format, args);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800274 va_end(args);
275
276 /* certain C libraries return -1 in case of truncation */
277 if (n < 0 || n > avail)
278 n = avail;
279
280 p += n;
281 /* certain C libraries do not zero-terminate in case of truncation */
282 if (p == end)
283 p[-1] = 0;
284
285 return p;
286}
287
288/* add a hex value to a bounded buffer, up to 8 digits */
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900289char*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800290_bprint_hex( char* p, char* end, unsigned value, int numDigits )
291{
292 char text[sizeof(unsigned)*2];
293 int nn = 0;
294
295 while (numDigits-- > 0) {
296 text[nn++] = "0123456789abcdef"[(value >> (numDigits*4)) & 15];
297 }
298 return _bprint_b(p, end, text, nn);
299}
300
301/* add the hexadecimal dump of some memory area to a bounded buffer */
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900302char*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800303_bprint_hexdump( char* p, char* end, const uint8_t* data, int datalen )
304{
305 int lineSize = 16;
306
307 while (datalen > 0) {
308 int avail = datalen;
309 int nn;
310
311 if (avail > lineSize)
312 avail = lineSize;
313
314 for (nn = 0; nn < avail; nn++) {
315 if (nn > 0)
316 p = _bprint_c(p, end, ' ');
317 p = _bprint_hex(p, end, data[nn], 2);
318 }
319 for ( ; nn < lineSize; nn++ ) {
320 p = _bprint_s(p, end, " ");
321 }
322 p = _bprint_s(p, end, " ");
323
324 for (nn = 0; nn < avail; nn++) {
325 int c = data[nn];
326
327 if (c < 32 || c > 127)
328 c = '.';
329
330 p = _bprint_c(p, end, c);
331 }
332 p = _bprint_c(p, end, '\n');
333
334 data += avail;
335 datalen -= avail;
336 }
337 return p;
338}
339
340/* dump the content of a query of packet to the log */
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900341void XLOG_BYTES( const void* base, int len ) __DEBUG__;
342void XLOG_BYTES( const void* base, int len )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800343{
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900344 if (DEBUG_DATA) {
345 char buff[1024];
346 char* p = buff, *end = p + sizeof(buff);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800347
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900348 p = _bprint_hexdump(p, end, base, len);
349 XLOG("%s",buff);
350 }
351} __DEBUG__
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800352
353static time_t
354_time_now( void )
355{
356 struct timeval tv;
357
358 gettimeofday( &tv, NULL );
359 return tv.tv_sec;
360}
361
362/* reminder: the general format of a DNS packet is the following:
363 *
364 * HEADER (12 bytes)
365 * QUESTION (variable)
366 * ANSWER (variable)
367 * AUTHORITY (variable)
368 * ADDITIONNAL (variable)
369 *
370 * the HEADER is made of:
371 *
372 * ID : 16 : 16-bit unique query identification field
373 *
374 * QR : 1 : set to 0 for queries, and 1 for responses
375 * Opcode : 4 : set to 0 for queries
376 * AA : 1 : set to 0 for queries
377 * TC : 1 : truncation flag, will be set to 0 in queries
378 * RD : 1 : recursion desired
379 *
380 * RA : 1 : recursion available (0 in queries)
381 * Z : 3 : three reserved zero bits
382 * RCODE : 4 : response code (always 0=NOERROR in queries)
383 *
384 * QDCount: 16 : question count
385 * ANCount: 16 : Answer count (0 in queries)
386 * NSCount: 16: Authority Record count (0 in queries)
387 * ARCount: 16: Additionnal Record count (0 in queries)
388 *
389 * the QUESTION is made of QDCount Question Record (QRs)
390 * the ANSWER is made of ANCount RRs
391 * the AUTHORITY is made of NSCount RRs
392 * the ADDITIONNAL is made of ARCount RRs
393 *
394 * Each Question Record (QR) is made of:
395 *
396 * QNAME : variable : Query DNS NAME
397 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
398 * CLASS : 16 : class of query (IN=1)
399 *
400 * Each Resource Record (RR) is made of:
401 *
402 * NAME : variable : DNS NAME
403 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
404 * CLASS : 16 : class of query (IN=1)
405 * TTL : 32 : seconds to cache this RR (0=none)
406 * RDLENGTH: 16 : size of RDDATA in bytes
407 * RDDATA : variable : RR data (depends on TYPE)
408 *
409 * Each QNAME contains a domain name encoded as a sequence of 'labels'
410 * terminated by a zero. Each label has the following format:
411 *
412 * LEN : 8 : lenght of label (MUST be < 64)
413 * NAME : 8*LEN : label length (must exclude dots)
414 *
415 * A value of 0 in the encoding is interpreted as the 'root' domain and
416 * terminates the encoding. So 'www.android.com' will be encoded as:
417 *
418 * <3>www<7>android<3>com<0>
419 *
420 * Where <n> represents the byte with value 'n'
421 *
422 * Each NAME reflects the QNAME of the question, but has a slightly more
423 * complex encoding in order to provide message compression. This is achieved
424 * by using a 2-byte pointer, with format:
425 *
426 * TYPE : 2 : 0b11 to indicate a pointer, 0b01 and 0b10 are reserved
427 * OFFSET : 14 : offset to another part of the DNS packet
428 *
429 * The offset is relative to the start of the DNS packet and must point
430 * A pointer terminates the encoding.
431 *
432 * The NAME can be encoded in one of the following formats:
433 *
434 * - a sequence of simple labels terminated by 0 (like QNAMEs)
435 * - a single pointer
436 * - a sequence of simple labels terminated by a pointer
437 *
438 * A pointer shall always point to either a pointer of a sequence of
439 * labels (which can themselves be terminated by either a 0 or a pointer)
440 *
441 * The expanded length of a given domain name should not exceed 255 bytes.
442 *
443 * NOTE: we don't parse the answer packets, so don't need to deal with NAME
444 * records, only QNAMEs.
445 */
446
447#define DNS_HEADER_SIZE 12
448
449#define DNS_TYPE_A "\00\01" /* big-endian decimal 1 */
450#define DNS_TYPE_PTR "\00\014" /* big-endian decimal 12 */
451#define DNS_TYPE_MX "\00\017" /* big-endian decimal 15 */
452#define DNS_TYPE_AAAA "\00\034" /* big-endian decimal 28 */
453#define DNS_TYPE_ALL "\00\0377" /* big-endian decimal 255 */
454
455#define DNS_CLASS_IN "\00\01" /* big-endian decimal 1 */
456
457typedef struct {
458 const uint8_t* base;
459 const uint8_t* end;
460 const uint8_t* cursor;
461} DnsPacket;
462
463static void
464_dnsPacket_init( DnsPacket* packet, const uint8_t* buff, int bufflen )
465{
466 packet->base = buff;
467 packet->end = buff + bufflen;
468 packet->cursor = buff;
469}
470
471static void
472_dnsPacket_rewind( DnsPacket* packet )
473{
474 packet->cursor = packet->base;
475}
476
477static void
478_dnsPacket_skip( DnsPacket* packet, int count )
479{
480 const uint8_t* p = packet->cursor + count;
481
482 if (p > packet->end)
483 p = packet->end;
484
485 packet->cursor = p;
486}
487
488static int
489_dnsPacket_readInt16( DnsPacket* packet )
490{
491 const uint8_t* p = packet->cursor;
492
493 if (p+2 > packet->end)
494 return -1;
495
496 packet->cursor = p+2;
497 return (p[0]<< 8) | p[1];
498}
499
500/** QUERY CHECKING
501 **/
502
503/* check bytes in a dns packet. returns 1 on success, 0 on failure.
504 * the cursor is only advanced in the case of success
505 */
506static int
507_dnsPacket_checkBytes( DnsPacket* packet, int numBytes, const void* bytes )
508{
509 const uint8_t* p = packet->cursor;
510
511 if (p + numBytes > packet->end)
512 return 0;
513
514 if (memcmp(p, bytes, numBytes) != 0)
515 return 0;
516
517 packet->cursor = p + numBytes;
518 return 1;
519}
520
521/* parse and skip a given QNAME stored in a query packet,
522 * from the current cursor position. returns 1 on success,
523 * or 0 for malformed data.
524 */
525static int
526_dnsPacket_checkQName( DnsPacket* packet )
527{
528 const uint8_t* p = packet->cursor;
529 const uint8_t* end = packet->end;
530
531 for (;;) {
532 int c;
533
534 if (p >= end)
535 break;
536
537 c = *p++;
538
539 if (c == 0) {
540 packet->cursor = p;
541 return 1;
542 }
543
544 /* we don't expect label compression in QNAMEs */
545 if (c >= 64)
546 break;
547
548 p += c;
549 /* we rely on the bound check at the start
550 * of the loop here */
551 }
552 /* malformed data */
553 XLOG("malformed QNAME");
554 return 0;
555}
556
557/* parse and skip a given QR stored in a packet.
558 * returns 1 on success, and 0 on failure
559 */
560static int
561_dnsPacket_checkQR( DnsPacket* packet )
562{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800563 if (!_dnsPacket_checkQName(packet))
564 return 0;
565
566 /* TYPE must be one of the things we support */
567 if (!_dnsPacket_checkBytes(packet, 2, DNS_TYPE_A) &&
568 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_PTR) &&
569 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_MX) &&
570 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_AAAA) &&
571 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_ALL))
572 {
573 XLOG("unsupported TYPE");
574 return 0;
575 }
576 /* CLASS must be IN */
577 if (!_dnsPacket_checkBytes(packet, 2, DNS_CLASS_IN)) {
578 XLOG("unsupported CLASS");
579 return 0;
580 }
581
582 return 1;
583}
584
585/* check the header of a DNS Query packet, return 1 if it is one
586 * type of query we can cache, or 0 otherwise
587 */
588static int
589_dnsPacket_checkQuery( DnsPacket* packet )
590{
591 const uint8_t* p = packet->base;
592 int qdCount, anCount, dnCount, arCount;
593
594 if (p + DNS_HEADER_SIZE > packet->end) {
595 XLOG("query packet too small");
596 return 0;
597 }
598
599 /* QR must be set to 0, opcode must be 0 and AA must be 0 */
600 /* RA, Z, and RCODE must be 0 */
601 if ((p[2] & 0xFC) != 0 || p[3] != 0) {
602 XLOG("query packet flags unsupported");
603 return 0;
604 }
605
606 /* Note that we ignore the TC and RD bits here for the
607 * following reasons:
608 *
609 * - there is no point for a query packet sent to a server
610 * to have the TC bit set, but the implementation might
611 * set the bit in the query buffer for its own needs
612 * between a _resolv_cache_lookup and a
613 * _resolv_cache_add. We should not freak out if this
614 * is the case.
615 *
616 * - we consider that the result from a RD=0 or a RD=1
617 * query might be different, hence that the RD bit
618 * should be used to differentiate cached result.
619 *
620 * this implies that RD is checked when hashing or
621 * comparing query packets, but not TC
622 */
623
624 /* ANCOUNT, DNCOUNT and ARCOUNT must be 0 */
625 qdCount = (p[4] << 8) | p[5];
626 anCount = (p[6] << 8) | p[7];
627 dnCount = (p[8] << 8) | p[9];
628 arCount = (p[10]<< 8) | p[11];
629
630 if (anCount != 0 || dnCount != 0 || arCount != 0) {
631 XLOG("query packet contains non-query records");
632 return 0;
633 }
634
635 if (qdCount == 0) {
636 XLOG("query packet doesn't contain query record");
637 return 0;
638 }
639
640 /* Check QDCOUNT QRs */
641 packet->cursor = p + DNS_HEADER_SIZE;
642
643 for (;qdCount > 0; qdCount--)
644 if (!_dnsPacket_checkQR(packet))
645 return 0;
646
647 return 1;
648}
649
650/** QUERY DEBUGGING
651 **/
652#if DEBUG
653static char*
654_dnsPacket_bprintQName(DnsPacket* packet, char* bp, char* bend)
655{
656 const uint8_t* p = packet->cursor;
657 const uint8_t* end = packet->end;
658 int first = 1;
659
660 for (;;) {
661 int c;
662
663 if (p >= end)
664 break;
665
666 c = *p++;
667
668 if (c == 0) {
669 packet->cursor = p;
670 return bp;
671 }
672
673 /* we don't expect label compression in QNAMEs */
674 if (c >= 64)
675 break;
676
677 if (first)
678 first = 0;
679 else
680 bp = _bprint_c(bp, bend, '.');
681
682 bp = _bprint_b(bp, bend, (const char*)p, c);
683
684 p += c;
685 /* we rely on the bound check at the start
686 * of the loop here */
687 }
688 /* malformed data */
689 bp = _bprint_s(bp, bend, "<MALFORMED>");
690 return bp;
691}
692
693static char*
694_dnsPacket_bprintQR(DnsPacket* packet, char* p, char* end)
695{
696#define QQ(x) { DNS_TYPE_##x, #x }
Elliott Hughes8f2a5a02013-03-15 15:30:25 -0700697 static const struct {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800698 const char* typeBytes;
Elliott Hughes8f2a5a02013-03-15 15:30:25 -0700699 const char* typeString;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800700 } qTypes[] =
701 {
702 QQ(A), QQ(PTR), QQ(MX), QQ(AAAA), QQ(ALL),
703 { NULL, NULL }
704 };
705 int nn;
706 const char* typeString = NULL;
707
708 /* dump QNAME */
709 p = _dnsPacket_bprintQName(packet, p, end);
710
711 /* dump TYPE */
712 p = _bprint_s(p, end, " (");
713
714 for (nn = 0; qTypes[nn].typeBytes != NULL; nn++) {
715 if (_dnsPacket_checkBytes(packet, 2, qTypes[nn].typeBytes)) {
716 typeString = qTypes[nn].typeString;
717 break;
718 }
719 }
720
721 if (typeString != NULL)
722 p = _bprint_s(p, end, typeString);
723 else {
724 int typeCode = _dnsPacket_readInt16(packet);
725 p = _bprint(p, end, "UNKNOWN-%d", typeCode);
726 }
727
728 p = _bprint_c(p, end, ')');
729
730 /* skip CLASS */
731 _dnsPacket_skip(packet, 2);
732 return p;
733}
734
735/* this function assumes the packet has already been checked */
736static char*
737_dnsPacket_bprintQuery( DnsPacket* packet, char* p, char* end )
738{
739 int qdCount;
740
741 if (packet->base[2] & 0x1) {
742 p = _bprint_s(p, end, "RECURSIVE ");
743 }
744
745 _dnsPacket_skip(packet, 4);
746 qdCount = _dnsPacket_readInt16(packet);
747 _dnsPacket_skip(packet, 6);
748
749 for ( ; qdCount > 0; qdCount-- ) {
750 p = _dnsPacket_bprintQR(packet, p, end);
751 }
752 return p;
753}
754#endif
755
756
757/** QUERY HASHING SUPPORT
758 **
759 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKET HAS ALREADY
760 ** BEEN SUCCESFULLY CHECKED.
761 **/
762
763/* use 32-bit FNV hash function */
764#define FNV_MULT 16777619U
765#define FNV_BASIS 2166136261U
766
767static unsigned
768_dnsPacket_hashBytes( DnsPacket* packet, int numBytes, unsigned hash )
769{
770 const uint8_t* p = packet->cursor;
771 const uint8_t* end = packet->end;
772
773 while (numBytes > 0 && p < end) {
774 hash = hash*FNV_MULT ^ *p++;
775 }
776 packet->cursor = p;
777 return hash;
778}
779
780
781static unsigned
782_dnsPacket_hashQName( DnsPacket* packet, unsigned hash )
783{
784 const uint8_t* p = packet->cursor;
785 const uint8_t* end = packet->end;
786
787 for (;;) {
788 int c;
789
790 if (p >= end) { /* should not happen */
791 XLOG("%s: INTERNAL_ERROR: read-overflow !!\n", __FUNCTION__);
792 break;
793 }
794
795 c = *p++;
796
797 if (c == 0)
798 break;
799
800 if (c >= 64) {
801 XLOG("%s: INTERNAL_ERROR: malformed domain !!\n", __FUNCTION__);
802 break;
803 }
804 if (p + c >= end) {
805 XLOG("%s: INTERNAL_ERROR: simple label read-overflow !!\n",
806 __FUNCTION__);
807 break;
808 }
809 while (c > 0) {
810 hash = hash*FNV_MULT ^ *p++;
811 c -= 1;
812 }
813 }
814 packet->cursor = p;
815 return hash;
816}
817
818static unsigned
819_dnsPacket_hashQR( DnsPacket* packet, unsigned hash )
820{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800821 hash = _dnsPacket_hashQName(packet, hash);
822 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TYPE and CLASS */
823 return hash;
824}
825
826static unsigned
827_dnsPacket_hashQuery( DnsPacket* packet )
828{
829 unsigned hash = FNV_BASIS;
830 int count;
831 _dnsPacket_rewind(packet);
832
833 /* we ignore the TC bit for reasons explained in
834 * _dnsPacket_checkQuery().
835 *
836 * however we hash the RD bit to differentiate
837 * between answers for recursive and non-recursive
838 * queries.
839 */
840 hash = hash*FNV_MULT ^ (packet->base[2] & 1);
841
842 /* assume: other flags are 0 */
843 _dnsPacket_skip(packet, 4);
844
845 /* read QDCOUNT */
846 count = _dnsPacket_readInt16(packet);
847
848 /* assume: ANcount, NScount, ARcount are 0 */
849 _dnsPacket_skip(packet, 6);
850
851 /* hash QDCOUNT QRs */
852 for ( ; count > 0; count-- )
853 hash = _dnsPacket_hashQR(packet, hash);
854
855 return hash;
856}
857
858
859/** QUERY COMPARISON
860 **
861 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKETS HAVE ALREADY
862 ** BEEN SUCCESFULLY CHECKED.
863 **/
864
865static int
866_dnsPacket_isEqualDomainName( DnsPacket* pack1, DnsPacket* pack2 )
867{
868 const uint8_t* p1 = pack1->cursor;
869 const uint8_t* end1 = pack1->end;
870 const uint8_t* p2 = pack2->cursor;
871 const uint8_t* end2 = pack2->end;
872
873 for (;;) {
874 int c1, c2;
875
876 if (p1 >= end1 || p2 >= end2) {
877 XLOG("%s: INTERNAL_ERROR: read-overflow !!\n", __FUNCTION__);
878 break;
879 }
880 c1 = *p1++;
881 c2 = *p2++;
882 if (c1 != c2)
883 break;
884
885 if (c1 == 0) {
886 pack1->cursor = p1;
887 pack2->cursor = p2;
888 return 1;
889 }
890 if (c1 >= 64) {
891 XLOG("%s: INTERNAL_ERROR: malformed domain !!\n", __FUNCTION__);
892 break;
893 }
894 if ((p1+c1 > end1) || (p2+c1 > end2)) {
895 XLOG("%s: INTERNAL_ERROR: simple label read-overflow !!\n",
896 __FUNCTION__);
897 break;
898 }
899 if (memcmp(p1, p2, c1) != 0)
900 break;
901 p1 += c1;
902 p2 += c1;
903 /* we rely on the bound checks at the start of the loop */
904 }
905 /* not the same, or one is malformed */
906 XLOG("different DN");
907 return 0;
908}
909
910static int
911_dnsPacket_isEqualBytes( DnsPacket* pack1, DnsPacket* pack2, int numBytes )
912{
913 const uint8_t* p1 = pack1->cursor;
914 const uint8_t* p2 = pack2->cursor;
915
916 if ( p1 + numBytes > pack1->end || p2 + numBytes > pack2->end )
917 return 0;
918
919 if ( memcmp(p1, p2, numBytes) != 0 )
920 return 0;
921
922 pack1->cursor += numBytes;
923 pack2->cursor += numBytes;
924 return 1;
925}
926
927static int
928_dnsPacket_isEqualQR( DnsPacket* pack1, DnsPacket* pack2 )
929{
930 /* compare domain name encoding + TYPE + CLASS */
931 if ( !_dnsPacket_isEqualDomainName(pack1, pack2) ||
932 !_dnsPacket_isEqualBytes(pack1, pack2, 2+2) )
933 return 0;
934
935 return 1;
936}
937
938static int
939_dnsPacket_isEqualQuery( DnsPacket* pack1, DnsPacket* pack2 )
940{
941 int count1, count2;
942
943 /* compare the headers, ignore most fields */
944 _dnsPacket_rewind(pack1);
945 _dnsPacket_rewind(pack2);
946
947 /* compare RD, ignore TC, see comment in _dnsPacket_checkQuery */
948 if ((pack1->base[2] & 1) != (pack2->base[2] & 1)) {
949 XLOG("different RD");
950 return 0;
951 }
952
953 /* assume: other flags are all 0 */
954 _dnsPacket_skip(pack1, 4);
955 _dnsPacket_skip(pack2, 4);
956
957 /* compare QDCOUNT */
958 count1 = _dnsPacket_readInt16(pack1);
959 count2 = _dnsPacket_readInt16(pack2);
960 if (count1 != count2 || count1 < 0) {
961 XLOG("different QDCOUNT");
962 return 0;
963 }
964
965 /* assume: ANcount, NScount and ARcount are all 0 */
966 _dnsPacket_skip(pack1, 6);
967 _dnsPacket_skip(pack2, 6);
968
969 /* compare the QDCOUNT QRs */
970 for ( ; count1 > 0; count1-- ) {
971 if (!_dnsPacket_isEqualQR(pack1, pack2)) {
972 XLOG("different QR");
973 return 0;
974 }
975 }
976 return 1;
977}
978
979/****************************************************************************/
980/****************************************************************************/
981/***** *****/
982/***** *****/
983/***** *****/
984/****************************************************************************/
985/****************************************************************************/
986
987/* cache entry. for simplicity, 'hash' and 'hlink' are inlined in this
988 * structure though they are conceptually part of the hash table.
989 *
990 * similarly, mru_next and mru_prev are part of the global MRU list
991 */
992typedef struct Entry {
993 unsigned int hash; /* hash value */
994 struct Entry* hlink; /* next in collision chain */
995 struct Entry* mru_prev;
996 struct Entry* mru_next;
997
998 const uint8_t* query;
999 int querylen;
1000 const uint8_t* answer;
1001 int answerlen;
Mattias Falk3e0c5102011-01-31 12:42:26 +01001002 time_t expires; /* time_t when the entry isn't valid any more */
1003 int id; /* for debugging purpose */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001004} Entry;
1005
Mattias Falk3e0c5102011-01-31 12:42:26 +01001006/**
Robert Greenwalt78851f12013-01-07 12:10:06 -08001007 * Find the TTL for a negative DNS result. This is defined as the minimum
1008 * of the SOA records TTL and the MINIMUM-TTL field (RFC-2308).
1009 *
1010 * Return 0 if not found.
1011 */
1012static u_long
1013answer_getNegativeTTL(ns_msg handle) {
1014 int n, nscount;
1015 u_long result = 0;
1016 ns_rr rr;
1017
1018 nscount = ns_msg_count(handle, ns_s_ns);
1019 for (n = 0; n < nscount; n++) {
1020 if ((ns_parserr(&handle, ns_s_ns, n, &rr) == 0) && (ns_rr_type(rr) == ns_t_soa)) {
1021 const u_char *rdata = ns_rr_rdata(rr); // find the data
1022 const u_char *edata = rdata + ns_rr_rdlen(rr); // add the len to find the end
1023 int len;
1024 u_long ttl, rec_result = ns_rr_ttl(rr);
1025
1026 // find the MINIMUM-TTL field from the blob of binary data for this record
1027 // skip the server name
1028 len = dn_skipname(rdata, edata);
1029 if (len == -1) continue; // error skipping
1030 rdata += len;
1031
1032 // skip the admin name
1033 len = dn_skipname(rdata, edata);
1034 if (len == -1) continue; // error skipping
1035 rdata += len;
1036
1037 if (edata - rdata != 5*NS_INT32SZ) continue;
1038 // skip: serial number + refresh interval + retry interval + expiry
1039 rdata += NS_INT32SZ * 4;
1040 // finally read the MINIMUM TTL
1041 ttl = ns_get32(rdata);
1042 if (ttl < rec_result) {
1043 rec_result = ttl;
1044 }
1045 // Now that the record is read successfully, apply the new min TTL
1046 if (n == 0 || rec_result < result) {
1047 result = rec_result;
1048 }
1049 }
1050 }
1051 return result;
1052}
1053
1054/**
1055 * Parse the answer records and find the appropriate
1056 * smallest TTL among the records. This might be from
1057 * the answer records if found or from the SOA record
1058 * if it's a negative result.
Mattias Falk3e0c5102011-01-31 12:42:26 +01001059 *
1060 * The returned TTL is the number of seconds to
1061 * keep the answer in the cache.
1062 *
1063 * In case of parse error zero (0) is returned which
1064 * indicates that the answer shall not be cached.
1065 */
1066static u_long
1067answer_getTTL(const void* answer, int answerlen)
1068{
1069 ns_msg handle;
1070 int ancount, n;
1071 u_long result, ttl;
1072 ns_rr rr;
1073
1074 result = 0;
1075 if (ns_initparse(answer, answerlen, &handle) >= 0) {
1076 // get number of answer records
1077 ancount = ns_msg_count(handle, ns_s_an);
Robert Greenwalt78851f12013-01-07 12:10:06 -08001078
1079 if (ancount == 0) {
1080 // a response with no answers? Cache this negative result.
1081 result = answer_getNegativeTTL(handle);
1082 } else {
1083 for (n = 0; n < ancount; n++) {
1084 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
1085 ttl = ns_rr_ttl(rr);
1086 if (n == 0 || ttl < result) {
1087 result = ttl;
1088 }
1089 } else {
1090 XLOG("ns_parserr failed ancount no = %d. errno = %s\n", n, strerror(errno));
Mattias Falk3e0c5102011-01-31 12:42:26 +01001091 }
Mattias Falk3e0c5102011-01-31 12:42:26 +01001092 }
1093 }
1094 } else {
1095 XLOG("ns_parserr failed. %s\n", strerror(errno));
1096 }
1097
Patrick Tjina6a09492015-01-20 16:02:04 -08001098 XLOG("TTL = %lu\n", result);
Mattias Falk3e0c5102011-01-31 12:42:26 +01001099
1100 return result;
1101}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001102
1103static void
1104entry_free( Entry* e )
1105{
1106 /* everything is allocated in a single memory block */
1107 if (e) {
1108 free(e);
1109 }
1110}
1111
1112static __inline__ void
1113entry_mru_remove( Entry* e )
1114{
1115 e->mru_prev->mru_next = e->mru_next;
1116 e->mru_next->mru_prev = e->mru_prev;
1117}
1118
1119static __inline__ void
1120entry_mru_add( Entry* e, Entry* list )
1121{
1122 Entry* first = list->mru_next;
1123
1124 e->mru_next = first;
1125 e->mru_prev = list;
1126
1127 list->mru_next = e;
1128 first->mru_prev = e;
1129}
1130
1131/* compute the hash of a given entry, this is a hash of most
1132 * data in the query (key) */
1133static unsigned
1134entry_hash( const Entry* e )
1135{
1136 DnsPacket pack[1];
1137
1138 _dnsPacket_init(pack, e->query, e->querylen);
1139 return _dnsPacket_hashQuery(pack);
1140}
1141
1142/* initialize an Entry as a search key, this also checks the input query packet
1143 * returns 1 on success, or 0 in case of unsupported/malformed data */
1144static int
1145entry_init_key( Entry* e, const void* query, int querylen )
1146{
1147 DnsPacket pack[1];
1148
1149 memset(e, 0, sizeof(*e));
1150
1151 e->query = query;
1152 e->querylen = querylen;
1153 e->hash = entry_hash(e);
1154
1155 _dnsPacket_init(pack, query, querylen);
1156
1157 return _dnsPacket_checkQuery(pack);
1158}
1159
1160/* allocate a new entry as a cache node */
1161static Entry*
1162entry_alloc( const Entry* init, const void* answer, int answerlen )
1163{
1164 Entry* e;
1165 int size;
1166
1167 size = sizeof(*e) + init->querylen + answerlen;
1168 e = calloc(size, 1);
1169 if (e == NULL)
1170 return e;
1171
1172 e->hash = init->hash;
1173 e->query = (const uint8_t*)(e+1);
1174 e->querylen = init->querylen;
1175
1176 memcpy( (char*)e->query, init->query, e->querylen );
1177
1178 e->answer = e->query + e->querylen;
1179 e->answerlen = answerlen;
1180
1181 memcpy( (char*)e->answer, answer, e->answerlen );
1182
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001183 return e;
1184}
1185
1186static int
1187entry_equals( const Entry* e1, const Entry* e2 )
1188{
1189 DnsPacket pack1[1], pack2[1];
1190
1191 if (e1->querylen != e2->querylen) {
1192 return 0;
1193 }
1194 _dnsPacket_init(pack1, e1->query, e1->querylen);
1195 _dnsPacket_init(pack2, e2->query, e2->querylen);
1196
1197 return _dnsPacket_isEqualQuery(pack1, pack2);
1198}
1199
1200/****************************************************************************/
1201/****************************************************************************/
1202/***** *****/
1203/***** *****/
1204/***** *****/
1205/****************************************************************************/
1206/****************************************************************************/
1207
1208/* We use a simple hash table with external collision lists
1209 * for simplicity, the hash-table fields 'hash' and 'hlink' are
1210 * inlined in the Entry structure.
1211 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001212
Mattias Falka59cfcf2011-09-06 15:15:06 +02001213/* Maximum time for a thread to wait for an pending request */
1214#define PENDING_REQUEST_TIMEOUT 20;
1215
1216typedef struct pending_req_info {
1217 unsigned int hash;
1218 pthread_cond_t cond;
1219 struct pending_req_info* next;
1220} PendingReqInfo;
1221
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001222typedef struct resolv_cache {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001223 int max_entries;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001224 int num_entries;
1225 Entry mru_list;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001226 int last_id;
Mattias Falk3a4910c2011-02-14 12:41:11 +01001227 Entry* entries;
Mattias Falka59cfcf2011-09-06 15:15:06 +02001228 PendingReqInfo pending_requests;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001229} Cache;
1230
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001231struct resolv_cache_info {
1232 unsigned netid;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001233 Cache* cache;
1234 struct resolv_cache_info* next;
Pierre Imaifff35672016-04-18 11:42:14 +09001235 int nscount;
1236 char* nameservers[MAXNS];
1237 struct addrinfo* nsaddrinfo[MAXNS];
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001238 int revision_id; // # times the nameservers have been replaced
1239 struct __res_params params;
Pierre Imaifff35672016-04-18 11:42:14 +09001240 struct __res_stats nsstats[MAXNS];
1241 // TODO: replace with char* defdname[MAXDNSRCH]
Mattias Falkc63e5902011-08-23 14:34:14 +02001242 char defdname[256];
1243 int dnsrch_offset[MAXDNSRCH+1]; // offsets into defdname
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001244};
Mattias Falkc63e5902011-08-23 14:34:14 +02001245
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001246#define HTABLE_VALID(x) ((x) != NULL && (x) != HTABLE_DELETED)
1247
Paul Jensen41d9a502014-04-08 15:43:41 -04001248static pthread_once_t _res_cache_once = PTHREAD_ONCE_INIT;
1249static void _res_cache_init(void);
1250
1251// lock protecting everything in the _resolve_cache_info structs (next ptr, etc)
1252static pthread_mutex_t _res_cache_list_lock;
1253
1254/* gets cache associated with a network, or NULL if none exists */
1255static struct resolv_cache* _find_named_cache_locked(unsigned netid);
1256
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001257static void
Mattias Falka59cfcf2011-09-06 15:15:06 +02001258_cache_flush_pending_requests_locked( struct resolv_cache* cache )
1259{
1260 struct pending_req_info *ri, *tmp;
1261 if (cache) {
1262 ri = cache->pending_requests.next;
1263
1264 while (ri) {
1265 tmp = ri;
1266 ri = ri->next;
1267 pthread_cond_broadcast(&tmp->cond);
1268
1269 pthread_cond_destroy(&tmp->cond);
1270 free(tmp);
1271 }
1272
1273 cache->pending_requests.next = NULL;
1274 }
1275}
1276
Paul Jensen41d9a502014-04-08 15:43:41 -04001277/* Return 0 if no pending request is found matching the key.
1278 * If a matching request is found the calling thread will wait until
1279 * the matching request completes, then update *cache and return 1. */
Mattias Falka59cfcf2011-09-06 15:15:06 +02001280static int
Paul Jensen41d9a502014-04-08 15:43:41 -04001281_cache_check_pending_request_locked( struct resolv_cache** cache, Entry* key, unsigned netid )
Mattias Falka59cfcf2011-09-06 15:15:06 +02001282{
1283 struct pending_req_info *ri, *prev;
1284 int exist = 0;
1285
Paul Jensen41d9a502014-04-08 15:43:41 -04001286 if (*cache && key) {
1287 ri = (*cache)->pending_requests.next;
1288 prev = &(*cache)->pending_requests;
Mattias Falka59cfcf2011-09-06 15:15:06 +02001289 while (ri) {
1290 if (ri->hash == key->hash) {
1291 exist = 1;
1292 break;
1293 }
1294 prev = ri;
1295 ri = ri->next;
1296 }
1297
1298 if (!exist) {
1299 ri = calloc(1, sizeof(struct pending_req_info));
1300 if (ri) {
1301 ri->hash = key->hash;
1302 pthread_cond_init(&ri->cond, NULL);
1303 prev->next = ri;
1304 }
1305 } else {
1306 struct timespec ts = {0,0};
Mattias Falkc63e5902011-08-23 14:34:14 +02001307 XLOG("Waiting for previous request");
Mattias Falka59cfcf2011-09-06 15:15:06 +02001308 ts.tv_sec = _time_now() + PENDING_REQUEST_TIMEOUT;
Paul Jensen41d9a502014-04-08 15:43:41 -04001309 pthread_cond_timedwait(&ri->cond, &_res_cache_list_lock, &ts);
1310 /* Must update *cache as it could have been deleted. */
1311 *cache = _find_named_cache_locked(netid);
Mattias Falka59cfcf2011-09-06 15:15:06 +02001312 }
1313 }
1314
1315 return exist;
1316}
1317
1318/* notify any waiting thread that waiting on a request
1319 * matching the key has been added to the cache */
1320static void
1321_cache_notify_waiting_tid_locked( struct resolv_cache* cache, Entry* key )
1322{
1323 struct pending_req_info *ri, *prev;
1324
1325 if (cache && key) {
1326 ri = cache->pending_requests.next;
1327 prev = &cache->pending_requests;
1328 while (ri) {
1329 if (ri->hash == key->hash) {
1330 pthread_cond_broadcast(&ri->cond);
1331 break;
1332 }
1333 prev = ri;
1334 ri = ri->next;
1335 }
1336
1337 // remove item from list and destroy
1338 if (ri) {
1339 prev->next = ri->next;
1340 pthread_cond_destroy(&ri->cond);
1341 free(ri);
1342 }
1343 }
1344}
1345
1346/* notify the cache that the query failed */
1347void
Paul Jensen41d9a502014-04-08 15:43:41 -04001348_resolv_cache_query_failed( unsigned netid,
Mattias Falka59cfcf2011-09-06 15:15:06 +02001349 const void* query,
1350 int querylen)
1351{
1352 Entry key[1];
Paul Jensen41d9a502014-04-08 15:43:41 -04001353 Cache* cache;
Mattias Falka59cfcf2011-09-06 15:15:06 +02001354
Paul Jensen41d9a502014-04-08 15:43:41 -04001355 if (!entry_init_key(key, query, querylen))
1356 return;
1357
1358 pthread_mutex_lock(&_res_cache_list_lock);
1359
1360 cache = _find_named_cache_locked(netid);
1361
1362 if (cache) {
Mattias Falka59cfcf2011-09-06 15:15:06 +02001363 _cache_notify_waiting_tid_locked(cache, key);
Mattias Falka59cfcf2011-09-06 15:15:06 +02001364 }
Paul Jensen41d9a502014-04-08 15:43:41 -04001365
1366 pthread_mutex_unlock(&_res_cache_list_lock);
Mattias Falka59cfcf2011-09-06 15:15:06 +02001367}
1368
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001369static struct resolv_cache_info* _find_cache_info_locked(unsigned netid);
1370
Mattias Falka59cfcf2011-09-06 15:15:06 +02001371static void
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001372_cache_flush_locked( Cache* cache )
1373{
1374 int nn;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001375
Mattias Falk3a4910c2011-02-14 12:41:11 +01001376 for (nn = 0; nn < cache->max_entries; nn++)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001377 {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001378 Entry** pnode = (Entry**) &cache->entries[nn];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001379
1380 while (*pnode != NULL) {
1381 Entry* node = *pnode;
1382 *pnode = node->hlink;
1383 entry_free(node);
1384 }
1385 }
1386
Mattias Falka59cfcf2011-09-06 15:15:06 +02001387 // flush pending request
1388 _cache_flush_pending_requests_locked(cache);
1389
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001390 cache->mru_list.mru_next = cache->mru_list.mru_prev = &cache->mru_list;
1391 cache->num_entries = 0;
1392 cache->last_id = 0;
1393
1394 XLOG("*************************\n"
1395 "*** DNS CACHE FLUSHED ***\n"
1396 "*************************");
1397}
1398
Mattias Falk3a4910c2011-02-14 12:41:11 +01001399static int
1400_res_cache_get_max_entries( void )
1401{
Elliott Hughes908e8c22014-01-28 14:54:11 -08001402 int cache_size = CONFIG_MAX_ENTRIES;
Mattias Falk3a4910c2011-02-14 12:41:11 +01001403
Robert Greenwalt52764f52012-01-25 15:16:03 -08001404 const char* cache_mode = getenv("ANDROID_DNS_MODE");
Robert Greenwalt52764f52012-01-25 15:16:03 -08001405 if (cache_mode == NULL || strcmp(cache_mode, "local") != 0) {
Elliott Hughes908e8c22014-01-28 14:54:11 -08001406 // Don't use the cache in local mode. This is used by the proxy itself.
1407 cache_size = 0;
Robert Greenwalt52764f52012-01-25 15:16:03 -08001408 }
1409
Elliott Hughes908e8c22014-01-28 14:54:11 -08001410 XLOG("cache size: %d", cache_size);
1411 return cache_size;
Mattias Falk3a4910c2011-02-14 12:41:11 +01001412}
1413
Jim Huang7cc56662010-10-15 02:02:57 +08001414static struct resolv_cache*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001415_resolv_cache_create( void )
1416{
1417 struct resolv_cache* cache;
1418
1419 cache = calloc(sizeof(*cache), 1);
1420 if (cache) {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001421 cache->max_entries = _res_cache_get_max_entries();
1422 cache->entries = calloc(sizeof(*cache->entries), cache->max_entries);
1423 if (cache->entries) {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001424 cache->mru_list.mru_prev = cache->mru_list.mru_next = &cache->mru_list;
1425 XLOG("%s: cache created\n", __FUNCTION__);
1426 } else {
1427 free(cache);
1428 cache = NULL;
1429 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001430 }
1431 return cache;
1432}
1433
1434
1435#if DEBUG
1436static void
1437_dump_query( const uint8_t* query, int querylen )
1438{
1439 char temp[256], *p=temp, *end=p+sizeof(temp);
1440 DnsPacket pack[1];
1441
1442 _dnsPacket_init(pack, query, querylen);
1443 p = _dnsPacket_bprintQuery(pack, p, end);
1444 XLOG("QUERY: %s", temp);
1445}
1446
1447static void
1448_cache_dump_mru( Cache* cache )
1449{
1450 char temp[512], *p=temp, *end=p+sizeof(temp);
1451 Entry* e;
1452
1453 p = _bprint(temp, end, "MRU LIST (%2d): ", cache->num_entries);
1454 for (e = cache->mru_list.mru_next; e != &cache->mru_list; e = e->mru_next)
1455 p = _bprint(p, end, " %d", e->id);
1456
1457 XLOG("%s", temp);
1458}
Mattias Falk3e0c5102011-01-31 12:42:26 +01001459
1460static void
1461_dump_answer(const void* answer, int answerlen)
1462{
1463 res_state statep;
1464 FILE* fp;
1465 char* buf;
1466 int fileLen;
1467
Elliott Hughesc674edb2014-08-26 15:56:54 -07001468 fp = fopen("/data/reslog.txt", "w+e");
Mattias Falk3e0c5102011-01-31 12:42:26 +01001469 if (fp != NULL) {
1470 statep = __res_get_state();
1471
1472 res_pquery(statep, answer, answerlen, fp);
1473
1474 //Get file length
1475 fseek(fp, 0, SEEK_END);
1476 fileLen=ftell(fp);
1477 fseek(fp, 0, SEEK_SET);
1478 buf = (char *)malloc(fileLen+1);
1479 if (buf != NULL) {
1480 //Read file contents into buffer
1481 fread(buf, fileLen, 1, fp);
1482 XLOG("%s\n", buf);
1483 free(buf);
1484 }
1485 fclose(fp);
1486 remove("/data/reslog.txt");
1487 }
1488 else {
Robert Greenwalt78851f12013-01-07 12:10:06 -08001489 errno = 0; // else debug is introducing error signals
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001490 XLOG("%s: can't open file\n", __FUNCTION__);
Mattias Falk3e0c5102011-01-31 12:42:26 +01001491 }
1492}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001493#endif
1494
1495#if DEBUG
1496# define XLOG_QUERY(q,len) _dump_query((q), (len))
Mattias Falk3e0c5102011-01-31 12:42:26 +01001497# define XLOG_ANSWER(a, len) _dump_answer((a), (len))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001498#else
1499# define XLOG_QUERY(q,len) ((void)0)
Mattias Falk3e0c5102011-01-31 12:42:26 +01001500# define XLOG_ANSWER(a,len) ((void)0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001501#endif
1502
1503/* This function tries to find a key within the hash table
1504 * In case of success, it will return a *pointer* to the hashed key.
1505 * In case of failure, it will return a *pointer* to NULL
1506 *
1507 * So, the caller must check '*result' to check for success/failure.
1508 *
1509 * The main idea is that the result can later be used directly in
1510 * calls to _resolv_cache_add or _resolv_cache_remove as the 'lookup'
1511 * parameter. This makes the code simpler and avoids re-searching
1512 * for the key position in the htable.
1513 *
1514 * The result of a lookup_p is only valid until you alter the hash
1515 * table.
1516 */
1517static Entry**
1518_cache_lookup_p( Cache* cache,
1519 Entry* key )
1520{
Mattias Falk3a4910c2011-02-14 12:41:11 +01001521 int index = key->hash % cache->max_entries;
1522 Entry** pnode = (Entry**) &cache->entries[ index ];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001523
1524 while (*pnode != NULL) {
1525 Entry* node = *pnode;
1526
1527 if (node == NULL)
1528 break;
1529
1530 if (node->hash == key->hash && entry_equals(node, key))
1531 break;
1532
1533 pnode = &node->hlink;
1534 }
Mattias Falkc63e5902011-08-23 14:34:14 +02001535 return pnode;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001536}
1537
1538/* Add a new entry to the hash table. 'lookup' must be the
1539 * result of an immediate previous failed _lookup_p() call
1540 * (i.e. with *lookup == NULL), and 'e' is the pointer to the
1541 * newly created entry
1542 */
1543static void
1544_cache_add_p( Cache* cache,
1545 Entry** lookup,
1546 Entry* e )
1547{
1548 *lookup = e;
1549 e->id = ++cache->last_id;
1550 entry_mru_add(e, &cache->mru_list);
1551 cache->num_entries += 1;
1552
1553 XLOG("%s: entry %d added (count=%d)", __FUNCTION__,
1554 e->id, cache->num_entries);
1555}
1556
1557/* Remove an existing entry from the hash table,
1558 * 'lookup' must be the result of an immediate previous
1559 * and succesful _lookup_p() call.
1560 */
1561static void
1562_cache_remove_p( Cache* cache,
1563 Entry** lookup )
1564{
1565 Entry* e = *lookup;
1566
1567 XLOG("%s: entry %d removed (count=%d)", __FUNCTION__,
1568 e->id, cache->num_entries-1);
1569
1570 entry_mru_remove(e);
1571 *lookup = e->hlink;
1572 entry_free(e);
1573 cache->num_entries -= 1;
1574}
1575
1576/* Remove the oldest entry from the hash table.
1577 */
1578static void
1579_cache_remove_oldest( Cache* cache )
1580{
1581 Entry* oldest = cache->mru_list.mru_prev;
1582 Entry** lookup = _cache_lookup_p(cache, oldest);
1583
1584 if (*lookup == NULL) { /* should not happen */
1585 XLOG("%s: OLDEST NOT IN HTABLE ?", __FUNCTION__);
1586 return;
1587 }
Robert Greenwalt7f84da62011-09-02 07:44:36 -07001588 if (DEBUG) {
1589 XLOG("Cache full - removing oldest");
1590 XLOG_QUERY(oldest->query, oldest->querylen);
1591 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001592 _cache_remove_p(cache, lookup);
1593}
1594
Anders Fredlunddd161822011-05-20 08:12:37 +02001595/* Remove all expired entries from the hash table.
1596 */
1597static void _cache_remove_expired(Cache* cache) {
1598 Entry* e;
1599 time_t now = _time_now();
1600
1601 for (e = cache->mru_list.mru_next; e != &cache->mru_list;) {
1602 // Entry is old, remove
1603 if (now >= e->expires) {
1604 Entry** lookup = _cache_lookup_p(cache, e);
1605 if (*lookup == NULL) { /* should not happen */
1606 XLOG("%s: ENTRY NOT IN HTABLE ?", __FUNCTION__);
1607 return;
1608 }
1609 e = e->mru_next;
1610 _cache_remove_p(cache, lookup);
1611 } else {
1612 e = e->mru_next;
1613 }
1614 }
1615}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001616
1617ResolvCacheStatus
Paul Jensen41d9a502014-04-08 15:43:41 -04001618_resolv_cache_lookup( unsigned netid,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001619 const void* query,
1620 int querylen,
1621 void* answer,
1622 int answersize,
1623 int *answerlen )
1624{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001625 Entry key[1];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001626 Entry** lookup;
1627 Entry* e;
1628 time_t now;
Paul Jensen41d9a502014-04-08 15:43:41 -04001629 Cache* cache;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001630
1631 ResolvCacheStatus result = RESOLV_CACHE_NOTFOUND;
1632
1633 XLOG("%s: lookup", __FUNCTION__);
1634 XLOG_QUERY(query, querylen);
1635
1636 /* we don't cache malformed queries */
1637 if (!entry_init_key(key, query, querylen)) {
1638 XLOG("%s: unsupported query", __FUNCTION__);
1639 return RESOLV_CACHE_UNSUPPORTED;
1640 }
1641 /* lookup cache */
Paul Jensen41d9a502014-04-08 15:43:41 -04001642 pthread_once(&_res_cache_once, _res_cache_init);
1643 pthread_mutex_lock(&_res_cache_list_lock);
1644
1645 cache = _find_named_cache_locked(netid);
1646 if (cache == NULL) {
1647 result = RESOLV_CACHE_UNSUPPORTED;
1648 goto Exit;
1649 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001650
1651 /* see the description of _lookup_p to understand this.
1652 * the function always return a non-NULL pointer.
1653 */
1654 lookup = _cache_lookup_p(cache, key);
1655 e = *lookup;
1656
1657 if (e == NULL) {
1658 XLOG( "NOT IN CACHE");
Mattias Falka59cfcf2011-09-06 15:15:06 +02001659 // calling thread will wait if an outstanding request is found
1660 // that matching this query
Paul Jensen41d9a502014-04-08 15:43:41 -04001661 if (!_cache_check_pending_request_locked(&cache, key, netid) || cache == NULL) {
Mattias Falka59cfcf2011-09-06 15:15:06 +02001662 goto Exit;
1663 } else {
1664 lookup = _cache_lookup_p(cache, key);
1665 e = *lookup;
1666 if (e == NULL) {
1667 goto Exit;
1668 }
1669 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001670 }
1671
1672 now = _time_now();
1673
1674 /* remove stale entries here */
Mattias Falk3e0c5102011-01-31 12:42:26 +01001675 if (now >= e->expires) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001676 XLOG( " NOT IN CACHE (STALE ENTRY %p DISCARDED)", *lookup );
Robert Greenwalt7f84da62011-09-02 07:44:36 -07001677 XLOG_QUERY(e->query, e->querylen);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001678 _cache_remove_p(cache, lookup);
1679 goto Exit;
1680 }
1681
1682 *answerlen = e->answerlen;
1683 if (e->answerlen > answersize) {
1684 /* NOTE: we return UNSUPPORTED if the answer buffer is too short */
1685 result = RESOLV_CACHE_UNSUPPORTED;
1686 XLOG(" ANSWER TOO LONG");
1687 goto Exit;
1688 }
1689
1690 memcpy( answer, e->answer, e->answerlen );
1691
1692 /* bump up this entry to the top of the MRU list */
1693 if (e != cache->mru_list.mru_next) {
1694 entry_mru_remove( e );
1695 entry_mru_add( e, &cache->mru_list );
1696 }
1697
1698 XLOG( "FOUND IN CACHE entry=%p", e );
1699 result = RESOLV_CACHE_FOUND;
1700
1701Exit:
Paul Jensen41d9a502014-04-08 15:43:41 -04001702 pthread_mutex_unlock(&_res_cache_list_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001703 return result;
1704}
1705
1706
1707void
Paul Jensen41d9a502014-04-08 15:43:41 -04001708_resolv_cache_add( unsigned netid,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001709 const void* query,
1710 int querylen,
1711 const void* answer,
1712 int answerlen )
1713{
1714 Entry key[1];
1715 Entry* e;
1716 Entry** lookup;
Mattias Falk3e0c5102011-01-31 12:42:26 +01001717 u_long ttl;
Paul Jensen41d9a502014-04-08 15:43:41 -04001718 Cache* cache = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001719
1720 /* don't assume that the query has already been cached
1721 */
1722 if (!entry_init_key( key, query, querylen )) {
1723 XLOG( "%s: passed invalid query ?", __FUNCTION__);
1724 return;
1725 }
1726
Paul Jensen41d9a502014-04-08 15:43:41 -04001727 pthread_mutex_lock(&_res_cache_list_lock);
1728
1729 cache = _find_named_cache_locked(netid);
1730 if (cache == NULL) {
1731 goto Exit;
1732 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001733
1734 XLOG( "%s: query:", __FUNCTION__ );
1735 XLOG_QUERY(query,querylen);
Mattias Falk3e0c5102011-01-31 12:42:26 +01001736 XLOG_ANSWER(answer, answerlen);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001737#if DEBUG_DATA
1738 XLOG( "answer:");
1739 XLOG_BYTES(answer,answerlen);
1740#endif
1741
1742 lookup = _cache_lookup_p(cache, key);
1743 e = *lookup;
1744
1745 if (e != NULL) { /* should not happen */
1746 XLOG("%s: ALREADY IN CACHE (%p) ? IGNORING ADD",
1747 __FUNCTION__, e);
1748 goto Exit;
1749 }
1750
Mattias Falk3a4910c2011-02-14 12:41:11 +01001751 if (cache->num_entries >= cache->max_entries) {
Anders Fredlunddd161822011-05-20 08:12:37 +02001752 _cache_remove_expired(cache);
1753 if (cache->num_entries >= cache->max_entries) {
1754 _cache_remove_oldest(cache);
1755 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001756 /* need to lookup again */
1757 lookup = _cache_lookup_p(cache, key);
1758 e = *lookup;
1759 if (e != NULL) {
1760 XLOG("%s: ALREADY IN CACHE (%p) ? IGNORING ADD",
1761 __FUNCTION__, e);
1762 goto Exit;
1763 }
1764 }
1765
Mattias Falk3e0c5102011-01-31 12:42:26 +01001766 ttl = answer_getTTL(answer, answerlen);
1767 if (ttl > 0) {
1768 e = entry_alloc(key, answer, answerlen);
1769 if (e != NULL) {
1770 e->expires = ttl + _time_now();
1771 _cache_add_p(cache, lookup, e);
1772 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001773 }
1774#if DEBUG
1775 _cache_dump_mru(cache);
1776#endif
1777Exit:
Paul Jensen41d9a502014-04-08 15:43:41 -04001778 if (cache != NULL) {
1779 _cache_notify_waiting_tid_locked(cache, key);
1780 }
1781 pthread_mutex_unlock(&_res_cache_list_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001782}
1783
1784/****************************************************************************/
1785/****************************************************************************/
1786/***** *****/
1787/***** *****/
1788/***** *****/
1789/****************************************************************************/
1790/****************************************************************************/
1791
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001792// Head of the list of caches. Protected by _res_cache_list_lock.
1793static struct resolv_cache_info _res_cache_list;
1794
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001795/* insert resolv_cache_info into the list of resolv_cache_infos */
1796static void _insert_cache_info_locked(struct resolv_cache_info* cache_info);
1797/* creates a resolv_cache_info */
1798static struct resolv_cache_info* _create_cache_info( void );
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001799/* gets a resolv_cache_info associated with a network, or NULL if not found */
1800static struct resolv_cache_info* _find_cache_info_locked(unsigned netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001801/* look up the named cache, and creates one if needed */
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001802static struct resolv_cache* _get_res_cache_for_net_locked(unsigned netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001803/* empty the named cache */
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001804static void _flush_cache_for_net_locked(unsigned netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001805/* empty the nameservers set for the named cache */
1806static void _free_nameservers_locked(struct resolv_cache_info* cache_info);
Mattias Falkc63e5902011-08-23 14:34:14 +02001807/* return 1 if the provided list of name servers differs from the list of name servers
1808 * currently attached to the provided cache_info */
1809static int _resolv_is_nameservers_equal_locked(struct resolv_cache_info* cache_info,
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08001810 const char** servers, int numservers);
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001811/* clears the stats samples contained withing the given cache_info */
1812static void _res_cache_clear_stats_locked(struct resolv_cache_info* cache_info);
Chad Brubaker0c9bb492013-05-30 13:37:02 -07001813
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001814static void
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001815_res_cache_init(void)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001816{
1817 const char* env = getenv(CONFIG_ENV);
1818
1819 if (env && atoi(env) == 0) {
1820 /* the cache is disabled */
1821 return;
1822 }
1823
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001824 memset(&_res_cache_list, 0, sizeof(_res_cache_list));
1825 pthread_mutex_init(&_res_cache_list_lock, NULL);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001826}
1827
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001828static struct resolv_cache*
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001829_get_res_cache_for_net_locked(unsigned netid)
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001830{
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001831 struct resolv_cache* cache = _find_named_cache_locked(netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001832 if (!cache) {
1833 struct resolv_cache_info* cache_info = _create_cache_info();
1834 if (cache_info) {
1835 cache = _resolv_cache_create();
1836 if (cache) {
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001837 cache_info->cache = cache;
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001838 cache_info->netid = netid;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001839 _insert_cache_info_locked(cache_info);
1840 } else {
1841 free(cache_info);
1842 }
1843 }
1844 }
1845 return cache;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001846}
1847
Paul Jensen1544eae2014-08-06 17:34:22 +00001848void
1849_resolv_flush_cache_for_net(unsigned netid)
1850{
1851 pthread_once(&_res_cache_once, _res_cache_init);
1852 pthread_mutex_lock(&_res_cache_list_lock);
1853
1854 _flush_cache_for_net_locked(netid);
1855
1856 pthread_mutex_unlock(&_res_cache_list_lock);
1857}
1858
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001859static void
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001860_flush_cache_for_net_locked(unsigned netid)
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001861{
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001862 struct resolv_cache* cache = _find_named_cache_locked(netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001863 if (cache) {
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001864 _cache_flush_locked(cache);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001865 }
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001866
1867 // Also clear the NS statistics.
1868 struct resolv_cache_info* cache_info = _find_cache_info_locked(netid);
1869 _res_cache_clear_stats_locked(cache_info);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001870}
1871
Paul Jensen41d9a502014-04-08 15:43:41 -04001872void _resolv_delete_cache_for_net(unsigned netid)
1873{
1874 pthread_once(&_res_cache_once, _res_cache_init);
1875 pthread_mutex_lock(&_res_cache_list_lock);
1876
1877 struct resolv_cache_info* prev_cache_info = &_res_cache_list;
1878
1879 while (prev_cache_info->next) {
1880 struct resolv_cache_info* cache_info = prev_cache_info->next;
1881
1882 if (cache_info->netid == netid) {
1883 prev_cache_info->next = cache_info->next;
1884 _cache_flush_locked(cache_info->cache);
1885 free(cache_info->cache->entries);
1886 free(cache_info->cache);
1887 _free_nameservers_locked(cache_info);
1888 free(cache_info);
1889 break;
1890 }
1891
1892 prev_cache_info = prev_cache_info->next;
1893 }
1894
1895 pthread_mutex_unlock(&_res_cache_list_lock);
1896}
1897
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001898static struct resolv_cache_info*
1899_create_cache_info(void)
1900{
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001901 struct resolv_cache_info* cache_info;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001902
1903 cache_info = calloc(sizeof(*cache_info), 1);
1904 return cache_info;
1905}
1906
1907static void
1908_insert_cache_info_locked(struct resolv_cache_info* cache_info)
1909{
1910 struct resolv_cache_info* last;
1911
1912 for (last = &_res_cache_list; last->next; last = last->next);
1913
1914 last->next = cache_info;
1915
1916}
1917
1918static struct resolv_cache*
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001919_find_named_cache_locked(unsigned netid) {
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001920
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001921 struct resolv_cache_info* info = _find_cache_info_locked(netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001922
1923 if (info != NULL) return info->cache;
1924
1925 return NULL;
1926}
1927
1928static struct resolv_cache_info*
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001929_find_cache_info_locked(unsigned netid)
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001930{
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001931 struct resolv_cache_info* cache_info = _res_cache_list.next;
1932
1933 while (cache_info) {
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001934 if (cache_info->netid == netid) {
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001935 break;
1936 }
1937
1938 cache_info = cache_info->next;
1939 }
1940 return cache_info;
1941}
1942
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001943void
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001944_resolv_set_default_params(struct __res_params* params) {
1945 params->sample_validity = NSSAMPLE_VALIDITY;
1946 params->success_threshold = SUCCESS_THRESHOLD;
1947 params->min_samples = 0;
1948 params->max_samples = 0;
1949}
1950
Pierre Imaifff35672016-04-18 11:42:14 +09001951int
1952_resolv_set_nameservers_for_net(unsigned netid, const char** servers, unsigned numservers,
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001953 const char *domains, const struct __res_params* params)
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001954{
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001955 char sbuf[NI_MAXSERV];
Mattias Falkc63e5902011-08-23 14:34:14 +02001956 register char *cp;
1957 int *offset;
Pierre Imaifff35672016-04-18 11:42:14 +09001958 struct addrinfo* nsaddrinfo[MAXNS];
1959
1960 if (numservers > MAXNS) {
1961 XLOG("%s: numservers=%u, MAXNS=%u", __FUNCTION__, numservers, MAXNS);
1962 return E2BIG;
1963 }
1964
1965 // Parse the addresses before actually locking or changing any state, in case there is an error.
1966 // As a side effect this also reduces the time the lock is kept.
1967 struct addrinfo hints = {
1968 .ai_family = AF_UNSPEC,
1969 .ai_socktype = SOCK_DGRAM,
1970 .ai_flags = AI_NUMERICHOST
1971 };
1972 snprintf(sbuf, sizeof(sbuf), "%u", NAMESERVER_PORT);
1973 for (unsigned i = 0; i < numservers; i++) {
1974 // The addrinfo structures allocated here are freed in _free_nameservers_locked().
1975 int rt = getaddrinfo(servers[i], sbuf, &hints, &nsaddrinfo[i]);
1976 if (rt != 0) {
1977 for (unsigned j = 0 ; j < i ; j++) {
1978 freeaddrinfo(nsaddrinfo[j]);
1979 nsaddrinfo[j] = NULL;
1980 }
1981 XLOG("%s: getaddrinfo(%s)=%s", __FUNCTION__, servers[i], gai_strerror(rt));
1982 return EINVAL;
1983 }
1984 }
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001985
1986 pthread_once(&_res_cache_once, _res_cache_init);
Robert Greenwaltb002a2f2013-01-19 00:40:24 +00001987 pthread_mutex_lock(&_res_cache_list_lock);
Mattias Falkc63e5902011-08-23 14:34:14 +02001988
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001989 // creates the cache if not created
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001990 _get_res_cache_for_net_locked(netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001991
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001992 struct resolv_cache_info* cache_info = _find_cache_info_locked(netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001993
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001994 if (cache_info != NULL) {
1995 uint8_t old_max_samples = cache_info->params.max_samples;
1996 if (params != NULL) {
1997 cache_info->params = *params;
1998 } else {
1999 _resolv_set_default_params(&cache_info->params);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002000 }
Mattias Falkc63e5902011-08-23 14:34:14 +02002001
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002002 if (!_resolv_is_nameservers_equal_locked(cache_info, servers, numservers)) {
2003 // free current before adding new
2004 _free_nameservers_locked(cache_info);
Pierre Imaifff35672016-04-18 11:42:14 +09002005 unsigned i;
2006 for (i = 0; i < numservers; i++) {
2007 cache_info->nsaddrinfo[i] = nsaddrinfo[i];
2008 cache_info->nameservers[i] = strdup(servers[i]);
2009 XLOG("%s: netid = %u, addr = %s\n", __FUNCTION__, netid, servers[i]);
Mattias Falkc63e5902011-08-23 14:34:14 +02002010 }
Pierre Imaifff35672016-04-18 11:42:14 +09002011 cache_info->nscount = numservers;
Mattias Falkc63e5902011-08-23 14:34:14 +02002012
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002013 // code moved from res_init.c, load_domain_search_list
2014 strlcpy(cache_info->defdname, domains, sizeof(cache_info->defdname));
2015 if ((cp = strchr(cache_info->defdname, '\n')) != NULL)
2016 *cp = '\0';
Mattias Falkc63e5902011-08-23 14:34:14 +02002017
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002018 cp = cache_info->defdname;
2019 offset = cache_info->dnsrch_offset;
2020 while (offset < cache_info->dnsrch_offset + MAXDNSRCH) {
2021 while (*cp == ' ' || *cp == '\t') /* skip leading white space */
2022 cp++;
2023 if (*cp == '\0') /* stop if nothing more to do */
2024 break;
2025 *offset++ = cp - cache_info->defdname; /* record this search domain */
2026 while (*cp) { /* zero-terminate it */
2027 if (*cp == ' '|| *cp == '\t') {
2028 *cp++ = '\0';
2029 break;
2030 }
2031 cp++;
2032 }
2033 }
2034 *offset = -1; /* cache_info->dnsrch_offset has MAXDNSRCH+1 items */
2035
2036 // Flush the cache and reset the stats.
2037 _flush_cache_for_net_locked(netid);
2038
2039 // increment the revision id to ensure that sample state is not written back if the
2040 // servers change; in theory it would suffice to do so only if the servers or
2041 // max_samples actually change, in practice the overhead of checking is higher than the
2042 // cost, and overflows are unlikely
2043 ++cache_info->revision_id;
2044 } else if (cache_info->params.max_samples != old_max_samples) {
2045 // If the maximum number of samples changes, the overhead of keeping the most recent
2046 // samples around is not considered worth the effort, so they are cleared instead. All
2047 // other parameters do not affect shared state: Changing these parameters does not
2048 // invalidate the samples, as they only affect aggregation and the conditions under which
2049 // servers are considered usable.
2050 _res_cache_clear_stats_locked(cache_info);
2051 ++cache_info->revision_id;
2052 }
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002053 }
Mattias Falkc63e5902011-08-23 14:34:14 +02002054
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002055 pthread_mutex_unlock(&_res_cache_list_lock);
Pierre Imaifff35672016-04-18 11:42:14 +09002056 return 0;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002057}
2058
Mattias Falkc63e5902011-08-23 14:34:14 +02002059static int
2060_resolv_is_nameservers_equal_locked(struct resolv_cache_info* cache_info,
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08002061 const char** servers, int numservers)
Mattias Falkc63e5902011-08-23 14:34:14 +02002062{
Pierre Imaifff35672016-04-18 11:42:14 +09002063 if (cache_info->nscount != numservers) {
Lorenzo Colittibce18c92014-09-08 18:09:43 +09002064 return 0;
Pierre Imaifff35672016-04-18 11:42:14 +09002065 }
Lorenzo Colittibce18c92014-09-08 18:09:43 +09002066
2067 // Compare each name server against current name servers.
2068 // TODO: this is incorrect if the list of current or previous nameservers
2069 // contains duplicates. This does not really matter because the framework
2070 // filters out duplicates, but we should probably fix it. It's also
2071 // insensitive to the order of the nameservers; we should probably fix that
2072 // too.
Pierre Imaifff35672016-04-18 11:42:14 +09002073 for (int i = 0; i < numservers; i++) {
2074 for (int j = 0 ; ; j++) {
2075 if (j >= numservers) {
2076 return 0;
2077 }
2078 if (strcmp(cache_info->nameservers[i], servers[j]) == 0) {
Mattias Falkc63e5902011-08-23 14:34:14 +02002079 break;
2080 }
Mattias Falkc63e5902011-08-23 14:34:14 +02002081 }
2082 }
2083
Pierre Imaifff35672016-04-18 11:42:14 +09002084 return 1;
Mattias Falkc63e5902011-08-23 14:34:14 +02002085}
2086
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002087static void
2088_free_nameservers_locked(struct resolv_cache_info* cache_info)
2089{
2090 int i;
Pierre Imaifff35672016-04-18 11:42:14 +09002091 for (i = 0; i < cache_info->nscount; i++) {
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002092 free(cache_info->nameservers[i]);
2093 cache_info->nameservers[i] = NULL;
Robert Greenwalt9363d912011-07-25 12:30:17 -07002094 if (cache_info->nsaddrinfo[i] != NULL) {
2095 freeaddrinfo(cache_info->nsaddrinfo[i]);
2096 cache_info->nsaddrinfo[i] = NULL;
2097 }
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002098 cache_info->nsstats[i].sample_count =
2099 cache_info->nsstats[i].sample_next = 0;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002100 }
Pierre Imaifff35672016-04-18 11:42:14 +09002101 cache_info->nscount = 0;
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002102 _res_cache_clear_stats_locked(cache_info);
2103 ++cache_info->revision_id;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002104}
2105
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002106void
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002107_resolv_populate_res_for_net(res_state statp)
Mattias Falkc63e5902011-08-23 14:34:14 +02002108{
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08002109 if (statp == NULL) {
2110 return;
2111 }
Mattias Falkc63e5902011-08-23 14:34:14 +02002112
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08002113 pthread_once(&_res_cache_once, _res_cache_init);
2114 pthread_mutex_lock(&_res_cache_list_lock);
2115
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002116 struct resolv_cache_info* info = _find_cache_info_locked(statp->netid);
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08002117 if (info != NULL) {
2118 int nserv;
Mattias Falkc63e5902011-08-23 14:34:14 +02002119 struct addrinfo* ai;
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002120 XLOG("%s: %u\n", __FUNCTION__, statp->netid);
Mattias Falkc63e5902011-08-23 14:34:14 +02002121 for (nserv = 0; nserv < MAXNS; nserv++) {
2122 ai = info->nsaddrinfo[nserv];
2123 if (ai == NULL) {
2124 break;
2125 }
2126
2127 if ((size_t) ai->ai_addrlen <= sizeof(statp->_u._ext.ext->nsaddrs[0])) {
2128 if (statp->_u._ext.ext != NULL) {
2129 memcpy(&statp->_u._ext.ext->nsaddrs[nserv], ai->ai_addr, ai->ai_addrlen);
2130 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
2131 } else {
2132 if ((size_t) ai->ai_addrlen
2133 <= sizeof(statp->nsaddr_list[0])) {
2134 memcpy(&statp->nsaddr_list[nserv], ai->ai_addr,
2135 ai->ai_addrlen);
2136 } else {
2137 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
2138 }
2139 }
2140 } else {
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002141 XLOG("%s: found too long addrlen", __FUNCTION__);
Mattias Falkc63e5902011-08-23 14:34:14 +02002142 }
2143 }
2144 statp->nscount = nserv;
2145 // now do search domains. Note that we cache the offsets as this code runs alot
2146 // but the setting/offset-computer only runs when set/changed
Pierre Imai0967fc72016-02-29 16:31:55 +09002147 // WARNING: Don't use str*cpy() here, this string contains zeroes.
2148 memcpy(statp->defdname, info->defdname, sizeof(statp->defdname));
Mattias Falkc63e5902011-08-23 14:34:14 +02002149 register char **pp = statp->dnsrch;
2150 register int *p = info->dnsrch_offset;
2151 while (pp < statp->dnsrch + MAXDNSRCH && *p != -1) {
Elliott Hughes37b1b5b2014-07-02 16:27:20 -07002152 *pp++ = &statp->defdname[0] + *p++;
Mattias Falkc63e5902011-08-23 14:34:14 +02002153 }
Mattias Falkc63e5902011-08-23 14:34:14 +02002154 }
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08002155 pthread_mutex_unlock(&_res_cache_list_lock);
Mattias Falkc63e5902011-08-23 14:34:14 +02002156}
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002157
2158/* Resolver reachability statistics. */
2159
2160static void
2161_res_cache_add_stats_sample_locked(struct __res_stats* stats, const struct __res_sample* sample,
2162 int max_samples) {
2163 // Note: This function expects max_samples > 0, otherwise a (harmless) modification of the
2164 // allocated but supposedly unused memory for samples[0] will happen
2165 XLOG("%s: adding sample to stats, next = %d, count = %d", __FUNCTION__,
2166 stats->sample_next, stats->sample_count);
2167 stats->samples[stats->sample_next] = *sample;
2168 if (stats->sample_count < max_samples) {
2169 ++stats->sample_count;
2170 }
2171 if (++stats->sample_next >= max_samples) {
2172 stats->sample_next = 0;
2173 }
2174}
2175
2176static void
2177_res_cache_clear_stats_locked(struct resolv_cache_info* cache_info) {
2178 if (cache_info) {
2179 for (int i = 0 ; i < MAXNS ; ++i) {
2180 cache_info->nsstats->sample_count = cache_info->nsstats->sample_next = 0;
2181 }
2182 }
2183}
2184
2185int
2186_resolv_cache_get_resolver_stats( unsigned netid, struct __res_params* params,
2187 struct __res_stats stats[MAXNS]) {
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002188 int revision_id = -1;
2189 pthread_mutex_lock(&_res_cache_list_lock);
2190
2191 struct resolv_cache_info* info = _find_cache_info_locked(netid);
2192 if (info) {
2193 memcpy(stats, info->nsstats, sizeof(info->nsstats));
2194 *params = info->params;
2195 revision_id = info->revision_id;
2196 }
2197
2198 pthread_mutex_unlock(&_res_cache_list_lock);
2199 return revision_id;
2200}
2201
2202void
2203_resolv_cache_add_resolver_stats_sample( unsigned netid, int revision_id, int ns,
2204 const struct __res_sample* sample, int max_samples) {
2205 if (max_samples <= 0) return;
2206
2207 pthread_mutex_lock(&_res_cache_list_lock);
2208
2209 struct resolv_cache_info* info = _find_cache_info_locked(netid);
2210
2211 if (info && info->revision_id == revision_id) {
2212 _res_cache_add_stats_sample_locked(&info->nsstats[ns], sample, max_samples);
2213 }
2214
2215 pthread_mutex_unlock(&_res_cache_list_lock);
2216}
2217