blob: 526c91bc540eea502bd9c7371fd7159f93cd1f28 [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;
1235 char* nameservers[MAXNS +1];
1236 struct addrinfo* nsaddrinfo[MAXNS + 1];
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001237 int revision_id; // # times the nameservers have been replaced
1238 struct __res_params params;
1239 struct __res_stats nsstats[MAXNS];
Mattias Falkc63e5902011-08-23 14:34:14 +02001240 char defdname[256];
1241 int dnsrch_offset[MAXDNSRCH+1]; // offsets into defdname
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001242};
Mattias Falkc63e5902011-08-23 14:34:14 +02001243
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001244#define HTABLE_VALID(x) ((x) != NULL && (x) != HTABLE_DELETED)
1245
Paul Jensen41d9a502014-04-08 15:43:41 -04001246static pthread_once_t _res_cache_once = PTHREAD_ONCE_INIT;
1247static void _res_cache_init(void);
1248
1249// lock protecting everything in the _resolve_cache_info structs (next ptr, etc)
1250static pthread_mutex_t _res_cache_list_lock;
1251
1252/* gets cache associated with a network, or NULL if none exists */
1253static struct resolv_cache* _find_named_cache_locked(unsigned netid);
1254
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001255static void
Mattias Falka59cfcf2011-09-06 15:15:06 +02001256_cache_flush_pending_requests_locked( struct resolv_cache* cache )
1257{
1258 struct pending_req_info *ri, *tmp;
1259 if (cache) {
1260 ri = cache->pending_requests.next;
1261
1262 while (ri) {
1263 tmp = ri;
1264 ri = ri->next;
1265 pthread_cond_broadcast(&tmp->cond);
1266
1267 pthread_cond_destroy(&tmp->cond);
1268 free(tmp);
1269 }
1270
1271 cache->pending_requests.next = NULL;
1272 }
1273}
1274
Paul Jensen41d9a502014-04-08 15:43:41 -04001275/* Return 0 if no pending request is found matching the key.
1276 * If a matching request is found the calling thread will wait until
1277 * the matching request completes, then update *cache and return 1. */
Mattias Falka59cfcf2011-09-06 15:15:06 +02001278static int
Paul Jensen41d9a502014-04-08 15:43:41 -04001279_cache_check_pending_request_locked( struct resolv_cache** cache, Entry* key, unsigned netid )
Mattias Falka59cfcf2011-09-06 15:15:06 +02001280{
1281 struct pending_req_info *ri, *prev;
1282 int exist = 0;
1283
Paul Jensen41d9a502014-04-08 15:43:41 -04001284 if (*cache && key) {
1285 ri = (*cache)->pending_requests.next;
1286 prev = &(*cache)->pending_requests;
Mattias Falka59cfcf2011-09-06 15:15:06 +02001287 while (ri) {
1288 if (ri->hash == key->hash) {
1289 exist = 1;
1290 break;
1291 }
1292 prev = ri;
1293 ri = ri->next;
1294 }
1295
1296 if (!exist) {
1297 ri = calloc(1, sizeof(struct pending_req_info));
1298 if (ri) {
1299 ri->hash = key->hash;
1300 pthread_cond_init(&ri->cond, NULL);
1301 prev->next = ri;
1302 }
1303 } else {
1304 struct timespec ts = {0,0};
Mattias Falkc63e5902011-08-23 14:34:14 +02001305 XLOG("Waiting for previous request");
Mattias Falka59cfcf2011-09-06 15:15:06 +02001306 ts.tv_sec = _time_now() + PENDING_REQUEST_TIMEOUT;
Paul Jensen41d9a502014-04-08 15:43:41 -04001307 pthread_cond_timedwait(&ri->cond, &_res_cache_list_lock, &ts);
1308 /* Must update *cache as it could have been deleted. */
1309 *cache = _find_named_cache_locked(netid);
Mattias Falka59cfcf2011-09-06 15:15:06 +02001310 }
1311 }
1312
1313 return exist;
1314}
1315
1316/* notify any waiting thread that waiting on a request
1317 * matching the key has been added to the cache */
1318static void
1319_cache_notify_waiting_tid_locked( struct resolv_cache* cache, Entry* key )
1320{
1321 struct pending_req_info *ri, *prev;
1322
1323 if (cache && key) {
1324 ri = cache->pending_requests.next;
1325 prev = &cache->pending_requests;
1326 while (ri) {
1327 if (ri->hash == key->hash) {
1328 pthread_cond_broadcast(&ri->cond);
1329 break;
1330 }
1331 prev = ri;
1332 ri = ri->next;
1333 }
1334
1335 // remove item from list and destroy
1336 if (ri) {
1337 prev->next = ri->next;
1338 pthread_cond_destroy(&ri->cond);
1339 free(ri);
1340 }
1341 }
1342}
1343
1344/* notify the cache that the query failed */
1345void
Paul Jensen41d9a502014-04-08 15:43:41 -04001346_resolv_cache_query_failed( unsigned netid,
Mattias Falka59cfcf2011-09-06 15:15:06 +02001347 const void* query,
1348 int querylen)
1349{
1350 Entry key[1];
Paul Jensen41d9a502014-04-08 15:43:41 -04001351 Cache* cache;
Mattias Falka59cfcf2011-09-06 15:15:06 +02001352
Paul Jensen41d9a502014-04-08 15:43:41 -04001353 if (!entry_init_key(key, query, querylen))
1354 return;
1355
1356 pthread_mutex_lock(&_res_cache_list_lock);
1357
1358 cache = _find_named_cache_locked(netid);
1359
1360 if (cache) {
Mattias Falka59cfcf2011-09-06 15:15:06 +02001361 _cache_notify_waiting_tid_locked(cache, key);
Mattias Falka59cfcf2011-09-06 15:15:06 +02001362 }
Paul Jensen41d9a502014-04-08 15:43:41 -04001363
1364 pthread_mutex_unlock(&_res_cache_list_lock);
Mattias Falka59cfcf2011-09-06 15:15:06 +02001365}
1366
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001367static struct resolv_cache_info* _find_cache_info_locked(unsigned netid);
1368
Mattias Falka59cfcf2011-09-06 15:15:06 +02001369static void
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001370_cache_flush_locked( Cache* cache )
1371{
1372 int nn;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001373
Mattias Falk3a4910c2011-02-14 12:41:11 +01001374 for (nn = 0; nn < cache->max_entries; nn++)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001375 {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001376 Entry** pnode = (Entry**) &cache->entries[nn];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001377
1378 while (*pnode != NULL) {
1379 Entry* node = *pnode;
1380 *pnode = node->hlink;
1381 entry_free(node);
1382 }
1383 }
1384
Mattias Falka59cfcf2011-09-06 15:15:06 +02001385 // flush pending request
1386 _cache_flush_pending_requests_locked(cache);
1387
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001388 cache->mru_list.mru_next = cache->mru_list.mru_prev = &cache->mru_list;
1389 cache->num_entries = 0;
1390 cache->last_id = 0;
1391
1392 XLOG("*************************\n"
1393 "*** DNS CACHE FLUSHED ***\n"
1394 "*************************");
1395}
1396
Mattias Falk3a4910c2011-02-14 12:41:11 +01001397static int
1398_res_cache_get_max_entries( void )
1399{
Elliott Hughes908e8c22014-01-28 14:54:11 -08001400 int cache_size = CONFIG_MAX_ENTRIES;
Mattias Falk3a4910c2011-02-14 12:41:11 +01001401
Robert Greenwalt52764f52012-01-25 15:16:03 -08001402 const char* cache_mode = getenv("ANDROID_DNS_MODE");
Robert Greenwalt52764f52012-01-25 15:16:03 -08001403 if (cache_mode == NULL || strcmp(cache_mode, "local") != 0) {
Elliott Hughes908e8c22014-01-28 14:54:11 -08001404 // Don't use the cache in local mode. This is used by the proxy itself.
1405 cache_size = 0;
Robert Greenwalt52764f52012-01-25 15:16:03 -08001406 }
1407
Elliott Hughes908e8c22014-01-28 14:54:11 -08001408 XLOG("cache size: %d", cache_size);
1409 return cache_size;
Mattias Falk3a4910c2011-02-14 12:41:11 +01001410}
1411
Jim Huang7cc56662010-10-15 02:02:57 +08001412static struct resolv_cache*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001413_resolv_cache_create( void )
1414{
1415 struct resolv_cache* cache;
1416
1417 cache = calloc(sizeof(*cache), 1);
1418 if (cache) {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001419 cache->max_entries = _res_cache_get_max_entries();
1420 cache->entries = calloc(sizeof(*cache->entries), cache->max_entries);
1421 if (cache->entries) {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001422 cache->mru_list.mru_prev = cache->mru_list.mru_next = &cache->mru_list;
1423 XLOG("%s: cache created\n", __FUNCTION__);
1424 } else {
1425 free(cache);
1426 cache = NULL;
1427 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001428 }
1429 return cache;
1430}
1431
1432
1433#if DEBUG
1434static void
1435_dump_query( const uint8_t* query, int querylen )
1436{
1437 char temp[256], *p=temp, *end=p+sizeof(temp);
1438 DnsPacket pack[1];
1439
1440 _dnsPacket_init(pack, query, querylen);
1441 p = _dnsPacket_bprintQuery(pack, p, end);
1442 XLOG("QUERY: %s", temp);
1443}
1444
1445static void
1446_cache_dump_mru( Cache* cache )
1447{
1448 char temp[512], *p=temp, *end=p+sizeof(temp);
1449 Entry* e;
1450
1451 p = _bprint(temp, end, "MRU LIST (%2d): ", cache->num_entries);
1452 for (e = cache->mru_list.mru_next; e != &cache->mru_list; e = e->mru_next)
1453 p = _bprint(p, end, " %d", e->id);
1454
1455 XLOG("%s", temp);
1456}
Mattias Falk3e0c5102011-01-31 12:42:26 +01001457
1458static void
1459_dump_answer(const void* answer, int answerlen)
1460{
1461 res_state statep;
1462 FILE* fp;
1463 char* buf;
1464 int fileLen;
1465
Elliott Hughesc674edb2014-08-26 15:56:54 -07001466 fp = fopen("/data/reslog.txt", "w+e");
Mattias Falk3e0c5102011-01-31 12:42:26 +01001467 if (fp != NULL) {
1468 statep = __res_get_state();
1469
1470 res_pquery(statep, answer, answerlen, fp);
1471
1472 //Get file length
1473 fseek(fp, 0, SEEK_END);
1474 fileLen=ftell(fp);
1475 fseek(fp, 0, SEEK_SET);
1476 buf = (char *)malloc(fileLen+1);
1477 if (buf != NULL) {
1478 //Read file contents into buffer
1479 fread(buf, fileLen, 1, fp);
1480 XLOG("%s\n", buf);
1481 free(buf);
1482 }
1483 fclose(fp);
1484 remove("/data/reslog.txt");
1485 }
1486 else {
Robert Greenwalt78851f12013-01-07 12:10:06 -08001487 errno = 0; // else debug is introducing error signals
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001488 XLOG("%s: can't open file\n", __FUNCTION__);
Mattias Falk3e0c5102011-01-31 12:42:26 +01001489 }
1490}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001491#endif
1492
1493#if DEBUG
1494# define XLOG_QUERY(q,len) _dump_query((q), (len))
Mattias Falk3e0c5102011-01-31 12:42:26 +01001495# define XLOG_ANSWER(a, len) _dump_answer((a), (len))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001496#else
1497# define XLOG_QUERY(q,len) ((void)0)
Mattias Falk3e0c5102011-01-31 12:42:26 +01001498# define XLOG_ANSWER(a,len) ((void)0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001499#endif
1500
1501/* This function tries to find a key within the hash table
1502 * In case of success, it will return a *pointer* to the hashed key.
1503 * In case of failure, it will return a *pointer* to NULL
1504 *
1505 * So, the caller must check '*result' to check for success/failure.
1506 *
1507 * The main idea is that the result can later be used directly in
1508 * calls to _resolv_cache_add or _resolv_cache_remove as the 'lookup'
1509 * parameter. This makes the code simpler and avoids re-searching
1510 * for the key position in the htable.
1511 *
1512 * The result of a lookup_p is only valid until you alter the hash
1513 * table.
1514 */
1515static Entry**
1516_cache_lookup_p( Cache* cache,
1517 Entry* key )
1518{
Mattias Falk3a4910c2011-02-14 12:41:11 +01001519 int index = key->hash % cache->max_entries;
1520 Entry** pnode = (Entry**) &cache->entries[ index ];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001521
1522 while (*pnode != NULL) {
1523 Entry* node = *pnode;
1524
1525 if (node == NULL)
1526 break;
1527
1528 if (node->hash == key->hash && entry_equals(node, key))
1529 break;
1530
1531 pnode = &node->hlink;
1532 }
Mattias Falkc63e5902011-08-23 14:34:14 +02001533 return pnode;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001534}
1535
1536/* Add a new entry to the hash table. 'lookup' must be the
1537 * result of an immediate previous failed _lookup_p() call
1538 * (i.e. with *lookup == NULL), and 'e' is the pointer to the
1539 * newly created entry
1540 */
1541static void
1542_cache_add_p( Cache* cache,
1543 Entry** lookup,
1544 Entry* e )
1545{
1546 *lookup = e;
1547 e->id = ++cache->last_id;
1548 entry_mru_add(e, &cache->mru_list);
1549 cache->num_entries += 1;
1550
1551 XLOG("%s: entry %d added (count=%d)", __FUNCTION__,
1552 e->id, cache->num_entries);
1553}
1554
1555/* Remove an existing entry from the hash table,
1556 * 'lookup' must be the result of an immediate previous
1557 * and succesful _lookup_p() call.
1558 */
1559static void
1560_cache_remove_p( Cache* cache,
1561 Entry** lookup )
1562{
1563 Entry* e = *lookup;
1564
1565 XLOG("%s: entry %d removed (count=%d)", __FUNCTION__,
1566 e->id, cache->num_entries-1);
1567
1568 entry_mru_remove(e);
1569 *lookup = e->hlink;
1570 entry_free(e);
1571 cache->num_entries -= 1;
1572}
1573
1574/* Remove the oldest entry from the hash table.
1575 */
1576static void
1577_cache_remove_oldest( Cache* cache )
1578{
1579 Entry* oldest = cache->mru_list.mru_prev;
1580 Entry** lookup = _cache_lookup_p(cache, oldest);
1581
1582 if (*lookup == NULL) { /* should not happen */
1583 XLOG("%s: OLDEST NOT IN HTABLE ?", __FUNCTION__);
1584 return;
1585 }
Robert Greenwalt7f84da62011-09-02 07:44:36 -07001586 if (DEBUG) {
1587 XLOG("Cache full - removing oldest");
1588 XLOG_QUERY(oldest->query, oldest->querylen);
1589 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001590 _cache_remove_p(cache, lookup);
1591}
1592
Anders Fredlunddd161822011-05-20 08:12:37 +02001593/* Remove all expired entries from the hash table.
1594 */
1595static void _cache_remove_expired(Cache* cache) {
1596 Entry* e;
1597 time_t now = _time_now();
1598
1599 for (e = cache->mru_list.mru_next; e != &cache->mru_list;) {
1600 // Entry is old, remove
1601 if (now >= e->expires) {
1602 Entry** lookup = _cache_lookup_p(cache, e);
1603 if (*lookup == NULL) { /* should not happen */
1604 XLOG("%s: ENTRY NOT IN HTABLE ?", __FUNCTION__);
1605 return;
1606 }
1607 e = e->mru_next;
1608 _cache_remove_p(cache, lookup);
1609 } else {
1610 e = e->mru_next;
1611 }
1612 }
1613}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001614
1615ResolvCacheStatus
Paul Jensen41d9a502014-04-08 15:43:41 -04001616_resolv_cache_lookup( unsigned netid,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001617 const void* query,
1618 int querylen,
1619 void* answer,
1620 int answersize,
1621 int *answerlen )
1622{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001623 Entry key[1];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001624 Entry** lookup;
1625 Entry* e;
1626 time_t now;
Paul Jensen41d9a502014-04-08 15:43:41 -04001627 Cache* cache;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001628
1629 ResolvCacheStatus result = RESOLV_CACHE_NOTFOUND;
1630
1631 XLOG("%s: lookup", __FUNCTION__);
1632 XLOG_QUERY(query, querylen);
1633
1634 /* we don't cache malformed queries */
1635 if (!entry_init_key(key, query, querylen)) {
1636 XLOG("%s: unsupported query", __FUNCTION__);
1637 return RESOLV_CACHE_UNSUPPORTED;
1638 }
1639 /* lookup cache */
Paul Jensen41d9a502014-04-08 15:43:41 -04001640 pthread_once(&_res_cache_once, _res_cache_init);
1641 pthread_mutex_lock(&_res_cache_list_lock);
1642
1643 cache = _find_named_cache_locked(netid);
1644 if (cache == NULL) {
1645 result = RESOLV_CACHE_UNSUPPORTED;
1646 goto Exit;
1647 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001648
1649 /* see the description of _lookup_p to understand this.
1650 * the function always return a non-NULL pointer.
1651 */
1652 lookup = _cache_lookup_p(cache, key);
1653 e = *lookup;
1654
1655 if (e == NULL) {
1656 XLOG( "NOT IN CACHE");
Mattias Falka59cfcf2011-09-06 15:15:06 +02001657 // calling thread will wait if an outstanding request is found
1658 // that matching this query
Paul Jensen41d9a502014-04-08 15:43:41 -04001659 if (!_cache_check_pending_request_locked(&cache, key, netid) || cache == NULL) {
Mattias Falka59cfcf2011-09-06 15:15:06 +02001660 goto Exit;
1661 } else {
1662 lookup = _cache_lookup_p(cache, key);
1663 e = *lookup;
1664 if (e == NULL) {
1665 goto Exit;
1666 }
1667 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001668 }
1669
1670 now = _time_now();
1671
1672 /* remove stale entries here */
Mattias Falk3e0c5102011-01-31 12:42:26 +01001673 if (now >= e->expires) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001674 XLOG( " NOT IN CACHE (STALE ENTRY %p DISCARDED)", *lookup );
Robert Greenwalt7f84da62011-09-02 07:44:36 -07001675 XLOG_QUERY(e->query, e->querylen);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001676 _cache_remove_p(cache, lookup);
1677 goto Exit;
1678 }
1679
1680 *answerlen = e->answerlen;
1681 if (e->answerlen > answersize) {
1682 /* NOTE: we return UNSUPPORTED if the answer buffer is too short */
1683 result = RESOLV_CACHE_UNSUPPORTED;
1684 XLOG(" ANSWER TOO LONG");
1685 goto Exit;
1686 }
1687
1688 memcpy( answer, e->answer, e->answerlen );
1689
1690 /* bump up this entry to the top of the MRU list */
1691 if (e != cache->mru_list.mru_next) {
1692 entry_mru_remove( e );
1693 entry_mru_add( e, &cache->mru_list );
1694 }
1695
1696 XLOG( "FOUND IN CACHE entry=%p", e );
1697 result = RESOLV_CACHE_FOUND;
1698
1699Exit:
Paul Jensen41d9a502014-04-08 15:43:41 -04001700 pthread_mutex_unlock(&_res_cache_list_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001701 return result;
1702}
1703
1704
1705void
Paul Jensen41d9a502014-04-08 15:43:41 -04001706_resolv_cache_add( unsigned netid,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001707 const void* query,
1708 int querylen,
1709 const void* answer,
1710 int answerlen )
1711{
1712 Entry key[1];
1713 Entry* e;
1714 Entry** lookup;
Mattias Falk3e0c5102011-01-31 12:42:26 +01001715 u_long ttl;
Paul Jensen41d9a502014-04-08 15:43:41 -04001716 Cache* cache = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001717
1718 /* don't assume that the query has already been cached
1719 */
1720 if (!entry_init_key( key, query, querylen )) {
1721 XLOG( "%s: passed invalid query ?", __FUNCTION__);
1722 return;
1723 }
1724
Paul Jensen41d9a502014-04-08 15:43:41 -04001725 pthread_mutex_lock(&_res_cache_list_lock);
1726
1727 cache = _find_named_cache_locked(netid);
1728 if (cache == NULL) {
1729 goto Exit;
1730 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001731
1732 XLOG( "%s: query:", __FUNCTION__ );
1733 XLOG_QUERY(query,querylen);
Mattias Falk3e0c5102011-01-31 12:42:26 +01001734 XLOG_ANSWER(answer, answerlen);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001735#if DEBUG_DATA
1736 XLOG( "answer:");
1737 XLOG_BYTES(answer,answerlen);
1738#endif
1739
1740 lookup = _cache_lookup_p(cache, key);
1741 e = *lookup;
1742
1743 if (e != NULL) { /* should not happen */
1744 XLOG("%s: ALREADY IN CACHE (%p) ? IGNORING ADD",
1745 __FUNCTION__, e);
1746 goto Exit;
1747 }
1748
Mattias Falk3a4910c2011-02-14 12:41:11 +01001749 if (cache->num_entries >= cache->max_entries) {
Anders Fredlunddd161822011-05-20 08:12:37 +02001750 _cache_remove_expired(cache);
1751 if (cache->num_entries >= cache->max_entries) {
1752 _cache_remove_oldest(cache);
1753 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001754 /* need to lookup again */
1755 lookup = _cache_lookup_p(cache, key);
1756 e = *lookup;
1757 if (e != NULL) {
1758 XLOG("%s: ALREADY IN CACHE (%p) ? IGNORING ADD",
1759 __FUNCTION__, e);
1760 goto Exit;
1761 }
1762 }
1763
Mattias Falk3e0c5102011-01-31 12:42:26 +01001764 ttl = answer_getTTL(answer, answerlen);
1765 if (ttl > 0) {
1766 e = entry_alloc(key, answer, answerlen);
1767 if (e != NULL) {
1768 e->expires = ttl + _time_now();
1769 _cache_add_p(cache, lookup, e);
1770 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001771 }
1772#if DEBUG
1773 _cache_dump_mru(cache);
1774#endif
1775Exit:
Paul Jensen41d9a502014-04-08 15:43:41 -04001776 if (cache != NULL) {
1777 _cache_notify_waiting_tid_locked(cache, key);
1778 }
1779 pthread_mutex_unlock(&_res_cache_list_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001780}
1781
1782/****************************************************************************/
1783/****************************************************************************/
1784/***** *****/
1785/***** *****/
1786/***** *****/
1787/****************************************************************************/
1788/****************************************************************************/
1789
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001790// Head of the list of caches. Protected by _res_cache_list_lock.
1791static struct resolv_cache_info _res_cache_list;
1792
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001793/* insert resolv_cache_info into the list of resolv_cache_infos */
1794static void _insert_cache_info_locked(struct resolv_cache_info* cache_info);
1795/* creates a resolv_cache_info */
1796static struct resolv_cache_info* _create_cache_info( void );
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001797/* gets a resolv_cache_info associated with a network, or NULL if not found */
1798static struct resolv_cache_info* _find_cache_info_locked(unsigned netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001799/* look up the named cache, and creates one if needed */
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001800static struct resolv_cache* _get_res_cache_for_net_locked(unsigned netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001801/* empty the named cache */
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001802static void _flush_cache_for_net_locked(unsigned netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001803/* empty the nameservers set for the named cache */
1804static void _free_nameservers_locked(struct resolv_cache_info* cache_info);
Mattias Falkc63e5902011-08-23 14:34:14 +02001805/* return 1 if the provided list of name servers differs from the list of name servers
1806 * currently attached to the provided cache_info */
1807static int _resolv_is_nameservers_equal_locked(struct resolv_cache_info* cache_info,
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08001808 const char** servers, int numservers);
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001809/* clears the stats samples contained withing the given cache_info */
1810static void _res_cache_clear_stats_locked(struct resolv_cache_info* cache_info);
Chad Brubaker0c9bb492013-05-30 13:37:02 -07001811
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001812static void
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001813_res_cache_init(void)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001814{
1815 const char* env = getenv(CONFIG_ENV);
1816
1817 if (env && atoi(env) == 0) {
1818 /* the cache is disabled */
1819 return;
1820 }
1821
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001822 memset(&_res_cache_list, 0, sizeof(_res_cache_list));
1823 pthread_mutex_init(&_res_cache_list_lock, NULL);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001824}
1825
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001826static struct resolv_cache*
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001827_get_res_cache_for_net_locked(unsigned netid)
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001828{
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001829 struct resolv_cache* cache = _find_named_cache_locked(netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001830 if (!cache) {
1831 struct resolv_cache_info* cache_info = _create_cache_info();
1832 if (cache_info) {
1833 cache = _resolv_cache_create();
1834 if (cache) {
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001835 cache_info->cache = cache;
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001836 cache_info->netid = netid;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001837 _insert_cache_info_locked(cache_info);
1838 } else {
1839 free(cache_info);
1840 }
1841 }
1842 }
1843 return cache;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001844}
1845
Paul Jensen1544eae2014-08-06 17:34:22 +00001846void
1847_resolv_flush_cache_for_net(unsigned netid)
1848{
1849 pthread_once(&_res_cache_once, _res_cache_init);
1850 pthread_mutex_lock(&_res_cache_list_lock);
1851
1852 _flush_cache_for_net_locked(netid);
1853
1854 pthread_mutex_unlock(&_res_cache_list_lock);
1855}
1856
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001857static void
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001858_flush_cache_for_net_locked(unsigned netid)
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001859{
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001860 struct resolv_cache* cache = _find_named_cache_locked(netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001861 if (cache) {
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001862 _cache_flush_locked(cache);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001863 }
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001864
1865 // Also clear the NS statistics.
1866 struct resolv_cache_info* cache_info = _find_cache_info_locked(netid);
1867 _res_cache_clear_stats_locked(cache_info);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001868}
1869
Paul Jensen41d9a502014-04-08 15:43:41 -04001870void _resolv_delete_cache_for_net(unsigned netid)
1871{
1872 pthread_once(&_res_cache_once, _res_cache_init);
1873 pthread_mutex_lock(&_res_cache_list_lock);
1874
1875 struct resolv_cache_info* prev_cache_info = &_res_cache_list;
1876
1877 while (prev_cache_info->next) {
1878 struct resolv_cache_info* cache_info = prev_cache_info->next;
1879
1880 if (cache_info->netid == netid) {
1881 prev_cache_info->next = cache_info->next;
1882 _cache_flush_locked(cache_info->cache);
1883 free(cache_info->cache->entries);
1884 free(cache_info->cache);
1885 _free_nameservers_locked(cache_info);
1886 free(cache_info);
1887 break;
1888 }
1889
1890 prev_cache_info = prev_cache_info->next;
1891 }
1892
1893 pthread_mutex_unlock(&_res_cache_list_lock);
1894}
1895
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001896static struct resolv_cache_info*
1897_create_cache_info(void)
1898{
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001899 struct resolv_cache_info* cache_info;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001900
1901 cache_info = calloc(sizeof(*cache_info), 1);
1902 return cache_info;
1903}
1904
1905static void
1906_insert_cache_info_locked(struct resolv_cache_info* cache_info)
1907{
1908 struct resolv_cache_info* last;
1909
1910 for (last = &_res_cache_list; last->next; last = last->next);
1911
1912 last->next = cache_info;
1913
1914}
1915
1916static struct resolv_cache*
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001917_find_named_cache_locked(unsigned netid) {
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001918
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001919 struct resolv_cache_info* info = _find_cache_info_locked(netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001920
1921 if (info != NULL) return info->cache;
1922
1923 return NULL;
1924}
1925
1926static struct resolv_cache_info*
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001927_find_cache_info_locked(unsigned netid)
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001928{
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001929 struct resolv_cache_info* cache_info = _res_cache_list.next;
1930
1931 while (cache_info) {
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001932 if (cache_info->netid == netid) {
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001933 break;
1934 }
1935
1936 cache_info = cache_info->next;
1937 }
1938 return cache_info;
1939}
1940
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001941void
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001942_resolv_set_default_params(struct __res_params* params) {
1943 params->sample_validity = NSSAMPLE_VALIDITY;
1944 params->success_threshold = SUCCESS_THRESHOLD;
1945 params->min_samples = 0;
1946 params->max_samples = 0;
1947}
1948
1949void
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001950_resolv_set_nameservers_for_net(unsigned netid, const char** servers, int numservers,
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001951 const char *domains, const struct __res_params* params)
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001952{
1953 int i, rt, index;
1954 struct addrinfo hints;
1955 char sbuf[NI_MAXSERV];
Mattias Falkc63e5902011-08-23 14:34:14 +02001956 register char *cp;
1957 int *offset;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001958
1959 pthread_once(&_res_cache_once, _res_cache_init);
Robert Greenwaltb002a2f2013-01-19 00:40:24 +00001960 pthread_mutex_lock(&_res_cache_list_lock);
Mattias Falkc63e5902011-08-23 14:34:14 +02001961
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001962 // creates the cache if not created
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001963 _get_res_cache_for_net_locked(netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001964
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001965 struct resolv_cache_info* cache_info = _find_cache_info_locked(netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001966
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001967 if (cache_info != NULL) {
1968 uint8_t old_max_samples = cache_info->params.max_samples;
1969 if (params != NULL) {
1970 cache_info->params = *params;
1971 } else {
1972 _resolv_set_default_params(&cache_info->params);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001973 }
Mattias Falkc63e5902011-08-23 14:34:14 +02001974
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001975 if (!_resolv_is_nameservers_equal_locked(cache_info, servers, numservers)) {
1976 // free current before adding new
1977 _free_nameservers_locked(cache_info);
1978
1979 memset(&hints, 0, sizeof(hints));
1980 hints.ai_family = PF_UNSPEC;
1981 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
1982 hints.ai_flags = AI_NUMERICHOST;
1983 snprintf(sbuf, sizeof(sbuf), "%u", NAMESERVER_PORT);
1984
1985 index = 0;
1986 for (i = 0; i < numservers && i < MAXNS; i++) {
1987 rt = getaddrinfo(servers[i], sbuf, &hints, &cache_info->nsaddrinfo[index]);
1988 if (rt == 0) {
1989 cache_info->nameservers[index] = strdup(servers[i]);
1990 index++;
1991 XLOG("%s: netid = %u, addr = %s\n", __FUNCTION__, netid, servers[i]);
1992 } else {
1993 cache_info->nsaddrinfo[index] = NULL;
Mattias Falkc63e5902011-08-23 14:34:14 +02001994 }
Mattias Falkc63e5902011-08-23 14:34:14 +02001995 }
Mattias Falkc63e5902011-08-23 14:34:14 +02001996
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001997 // code moved from res_init.c, load_domain_search_list
1998 strlcpy(cache_info->defdname, domains, sizeof(cache_info->defdname));
1999 if ((cp = strchr(cache_info->defdname, '\n')) != NULL)
2000 *cp = '\0';
Mattias Falkc63e5902011-08-23 14:34:14 +02002001
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002002 cp = cache_info->defdname;
2003 offset = cache_info->dnsrch_offset;
2004 while (offset < cache_info->dnsrch_offset + MAXDNSRCH) {
2005 while (*cp == ' ' || *cp == '\t') /* skip leading white space */
2006 cp++;
2007 if (*cp == '\0') /* stop if nothing more to do */
2008 break;
2009 *offset++ = cp - cache_info->defdname; /* record this search domain */
2010 while (*cp) { /* zero-terminate it */
2011 if (*cp == ' '|| *cp == '\t') {
2012 *cp++ = '\0';
2013 break;
2014 }
2015 cp++;
2016 }
2017 }
2018 *offset = -1; /* cache_info->dnsrch_offset has MAXDNSRCH+1 items */
2019
2020 // Flush the cache and reset the stats.
2021 _flush_cache_for_net_locked(netid);
2022
2023 // increment the revision id to ensure that sample state is not written back if the
2024 // servers change; in theory it would suffice to do so only if the servers or
2025 // max_samples actually change, in practice the overhead of checking is higher than the
2026 // cost, and overflows are unlikely
2027 ++cache_info->revision_id;
2028 } else if (cache_info->params.max_samples != old_max_samples) {
2029 // If the maximum number of samples changes, the overhead of keeping the most recent
2030 // samples around is not considered worth the effort, so they are cleared instead. All
2031 // other parameters do not affect shared state: Changing these parameters does not
2032 // invalidate the samples, as they only affect aggregation and the conditions under which
2033 // servers are considered usable.
2034 _res_cache_clear_stats_locked(cache_info);
2035 ++cache_info->revision_id;
2036 }
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002037 }
Mattias Falkc63e5902011-08-23 14:34:14 +02002038
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002039 pthread_mutex_unlock(&_res_cache_list_lock);
2040}
2041
Mattias Falkc63e5902011-08-23 14:34:14 +02002042static int
2043_resolv_is_nameservers_equal_locked(struct resolv_cache_info* cache_info,
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08002044 const char** servers, int numservers)
Mattias Falkc63e5902011-08-23 14:34:14 +02002045{
2046 int i;
2047 char** ns;
Lorenzo Colittibce18c92014-09-08 18:09:43 +09002048 int currentservers;
Mattias Falkc63e5902011-08-23 14:34:14 +02002049 int equal = 1;
2050
Mattias Falkc63e5902011-08-23 14:34:14 +02002051 if (numservers > MAXNS) numservers = MAXNS;
Lorenzo Colittibce18c92014-09-08 18:09:43 +09002052
2053 // Find out how many nameservers we had before.
2054 currentservers = 0;
2055 for (ns = cache_info->nameservers; *ns; ns++)
2056 currentservers++;
2057
2058 if (currentservers != numservers)
2059 return 0;
2060
2061 // Compare each name server against current name servers.
2062 // TODO: this is incorrect if the list of current or previous nameservers
2063 // contains duplicates. This does not really matter because the framework
2064 // filters out duplicates, but we should probably fix it. It's also
2065 // insensitive to the order of the nameservers; we should probably fix that
2066 // too.
Mattias Falkc63e5902011-08-23 14:34:14 +02002067 for (i = 0; i < numservers && equal; i++) {
2068 ns = cache_info->nameservers;
2069 equal = 0;
2070 while(*ns) {
2071 if (strcmp(*ns, servers[i]) == 0) {
2072 equal = 1;
2073 break;
2074 }
2075 ns++;
2076 }
2077 }
2078
2079 return equal;
2080}
2081
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002082static void
2083_free_nameservers_locked(struct resolv_cache_info* cache_info)
2084{
2085 int i;
2086 for (i = 0; i <= MAXNS; i++) {
2087 free(cache_info->nameservers[i]);
2088 cache_info->nameservers[i] = NULL;
Robert Greenwalt9363d912011-07-25 12:30:17 -07002089 if (cache_info->nsaddrinfo[i] != NULL) {
2090 freeaddrinfo(cache_info->nsaddrinfo[i]);
2091 cache_info->nsaddrinfo[i] = NULL;
2092 }
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002093 cache_info->nsstats[i].sample_count =
2094 cache_info->nsstats[i].sample_next = 0;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002095 }
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002096 _res_cache_clear_stats_locked(cache_info);
2097 ++cache_info->revision_id;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002098}
2099
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002100void
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002101_resolv_populate_res_for_net(res_state statp)
Mattias Falkc63e5902011-08-23 14:34:14 +02002102{
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08002103 if (statp == NULL) {
2104 return;
2105 }
Mattias Falkc63e5902011-08-23 14:34:14 +02002106
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08002107 pthread_once(&_res_cache_once, _res_cache_init);
2108 pthread_mutex_lock(&_res_cache_list_lock);
2109
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002110 struct resolv_cache_info* info = _find_cache_info_locked(statp->netid);
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08002111 if (info != NULL) {
2112 int nserv;
Mattias Falkc63e5902011-08-23 14:34:14 +02002113 struct addrinfo* ai;
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002114 XLOG("%s: %u\n", __FUNCTION__, statp->netid);
Mattias Falkc63e5902011-08-23 14:34:14 +02002115 for (nserv = 0; nserv < MAXNS; nserv++) {
2116 ai = info->nsaddrinfo[nserv];
2117 if (ai == NULL) {
2118 break;
2119 }
2120
2121 if ((size_t) ai->ai_addrlen <= sizeof(statp->_u._ext.ext->nsaddrs[0])) {
2122 if (statp->_u._ext.ext != NULL) {
2123 memcpy(&statp->_u._ext.ext->nsaddrs[nserv], ai->ai_addr, ai->ai_addrlen);
2124 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
2125 } else {
2126 if ((size_t) ai->ai_addrlen
2127 <= sizeof(statp->nsaddr_list[0])) {
2128 memcpy(&statp->nsaddr_list[nserv], ai->ai_addr,
2129 ai->ai_addrlen);
2130 } else {
2131 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
2132 }
2133 }
2134 } else {
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002135 XLOG("%s: found too long addrlen", __FUNCTION__);
Mattias Falkc63e5902011-08-23 14:34:14 +02002136 }
2137 }
2138 statp->nscount = nserv;
2139 // now do search domains. Note that we cache the offsets as this code runs alot
2140 // but the setting/offset-computer only runs when set/changed
Pierre Imai0967fc72016-02-29 16:31:55 +09002141 // WARNING: Don't use str*cpy() here, this string contains zeroes.
2142 memcpy(statp->defdname, info->defdname, sizeof(statp->defdname));
Mattias Falkc63e5902011-08-23 14:34:14 +02002143 register char **pp = statp->dnsrch;
2144 register int *p = info->dnsrch_offset;
2145 while (pp < statp->dnsrch + MAXDNSRCH && *p != -1) {
Elliott Hughes37b1b5b2014-07-02 16:27:20 -07002146 *pp++ = &statp->defdname[0] + *p++;
Mattias Falkc63e5902011-08-23 14:34:14 +02002147 }
Mattias Falkc63e5902011-08-23 14:34:14 +02002148 }
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08002149 pthread_mutex_unlock(&_res_cache_list_lock);
Mattias Falkc63e5902011-08-23 14:34:14 +02002150}
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002151
2152/* Resolver reachability statistics. */
2153
2154static void
2155_res_cache_add_stats_sample_locked(struct __res_stats* stats, const struct __res_sample* sample,
2156 int max_samples) {
2157 // Note: This function expects max_samples > 0, otherwise a (harmless) modification of the
2158 // allocated but supposedly unused memory for samples[0] will happen
2159 XLOG("%s: adding sample to stats, next = %d, count = %d", __FUNCTION__,
2160 stats->sample_next, stats->sample_count);
2161 stats->samples[stats->sample_next] = *sample;
2162 if (stats->sample_count < max_samples) {
2163 ++stats->sample_count;
2164 }
2165 if (++stats->sample_next >= max_samples) {
2166 stats->sample_next = 0;
2167 }
2168}
2169
2170static void
2171_res_cache_clear_stats_locked(struct resolv_cache_info* cache_info) {
2172 if (cache_info) {
2173 for (int i = 0 ; i < MAXNS ; ++i) {
2174 cache_info->nsstats->sample_count = cache_info->nsstats->sample_next = 0;
2175 }
2176 }
2177}
2178
2179int
2180_resolv_cache_get_resolver_stats( unsigned netid, struct __res_params* params,
2181 struct __res_stats stats[MAXNS]) {
2182
2183 int revision_id = -1;
2184 pthread_mutex_lock(&_res_cache_list_lock);
2185
2186 struct resolv_cache_info* info = _find_cache_info_locked(netid);
2187 if (info) {
2188 memcpy(stats, info->nsstats, sizeof(info->nsstats));
2189 *params = info->params;
2190 revision_id = info->revision_id;
2191 }
2192
2193 pthread_mutex_unlock(&_res_cache_list_lock);
2194 return revision_id;
2195}
2196
2197void
2198_resolv_cache_add_resolver_stats_sample( unsigned netid, int revision_id, int ns,
2199 const struct __res_sample* sample, int max_samples) {
2200 if (max_samples <= 0) return;
2201
2202 pthread_mutex_lock(&_res_cache_list_lock);
2203
2204 struct resolv_cache_info* info = _find_cache_info_locked(netid);
2205
2206 if (info && info->revision_id == revision_id) {
2207 _res_cache_add_stats_sample_locked(&info->nsstats[ns], sample, max_samples);
2208 }
2209
2210 pthread_mutex_unlock(&_res_cache_list_lock);
2211}
2212