blob: 08a25576c65ca8a1e28b1ad63b304db86572eed1 [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>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080031#include <stdlib.h>
32#include <string.h>
33#include <time.h>
34#include "pthread.h"
35
Mattias Falk3e0c5102011-01-31 12:42:26 +010036#include <errno.h>
37#include "arpa_nameser.h"
Mattias Falk3a4910c2011-02-14 12:41:11 +010038#include <sys/system_properties.h>
Mattias Falk23d3e6b2011-04-04 16:12:35 +020039#include <net/if.h>
40#include <netdb.h>
41#include <linux/if.h>
42
43#include <arpa/inet.h>
44#include "resolv_private.h"
David 'Digit' Turner208898e2012-01-13 14:24:08 +010045#include "resolv_iface.h"
Mattias Falkc63e5902011-08-23 14:34:14 +020046#include "res_private.h"
Mattias Falk3e0c5102011-01-31 12:42:26 +010047
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080048/* This code implements a small and *simple* DNS resolver cache.
49 *
Mattias Falk3e0c5102011-01-31 12:42:26 +010050 * It is only used to cache DNS answers for a time defined by the smallest TTL
51 * among the answer records in order to reduce DNS traffic. It is not supposed
52 * to be a full DNS cache, since we plan to implement that in the future in a
53 * dedicated process running on the system.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080054 *
55 * Note that its design is kept simple very intentionally, i.e.:
56 *
57 * - it takes raw DNS query packet data as input, and returns raw DNS
58 * answer packet data as output
59 *
60 * (this means that two similar queries that encode the DNS name
61 * differently will be treated distinctly).
62 *
Mattias Falk3e0c5102011-01-31 12:42:26 +010063 * the smallest TTL value among the answer records are used as the time
64 * to keep an answer in the cache.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080065 *
66 * this is bad, but we absolutely want to avoid parsing the answer packets
67 * (and should be solved by the later full DNS cache process).
68 *
69 * - the implementation is just a (query-data) => (answer-data) hash table
70 * with a trivial least-recently-used expiration policy.
71 *
72 * Doing this keeps the code simple and avoids to deal with a lot of things
73 * that a full DNS cache is expected to do.
74 *
75 * The API is also very simple:
76 *
77 * - the client calls _resolv_cache_get() to obtain a handle to the cache.
78 * this will initialize the cache on first usage. the result can be NULL
79 * if the cache is disabled.
80 *
81 * - the client calls _resolv_cache_lookup() before performing a query
82 *
83 * if the function returns RESOLV_CACHE_FOUND, a copy of the answer data
84 * has been copied into the client-provided answer buffer.
85 *
86 * if the function returns RESOLV_CACHE_NOTFOUND, the client should perform
87 * a request normally, *then* call _resolv_cache_add() to add the received
88 * answer to the cache.
89 *
90 * if the function returns RESOLV_CACHE_UNSUPPORTED, the client should
91 * perform a request normally, and *not* call _resolv_cache_add()
92 *
93 * note that RESOLV_CACHE_UNSUPPORTED is also returned if the answer buffer
94 * is too short to accomodate the cached result.
95 *
96 * - when network settings change, the cache must be flushed since the list
97 * of DNS servers probably changed. this is done by calling
98 * _resolv_cache_reset()
99 *
100 * the parameter to this function must be an ever-increasing generation
101 * number corresponding to the current network settings state.
102 *
103 * This is done because several threads could detect the same network
104 * settings change (but at different times) and will all end up calling the
105 * same function. Comparing with the last used generation number ensures
106 * that the cache is only flushed once per network change.
107 */
108
109/* the name of an environment variable that will be checked the first time
110 * this code is called if its value is "0", then the resolver cache is
111 * disabled.
112 */
113#define CONFIG_ENV "BIONIC_DNSCACHE"
114
115/* entries older than CONFIG_SECONDS seconds are always discarded.
116 */
117#define CONFIG_SECONDS (60*10) /* 10 minutes */
118
Mattias Falk3a4910c2011-02-14 12:41:11 +0100119/* default number of entries kept in the cache. This value has been
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800120 * determined by browsing through various sites and counting the number
121 * of corresponding requests. Keep in mind that our framework is currently
122 * performing two requests per name lookup (one for IPv4, the other for IPv6)
123 *
124 * www.google.com 4
125 * www.ysearch.com 6
126 * www.amazon.com 8
127 * www.nytimes.com 22
128 * www.espn.com 28
129 * www.msn.com 28
130 * www.lemonde.fr 35
131 *
132 * (determined in 2009-2-17 from Paris, France, results may vary depending
133 * on location)
134 *
135 * most high-level websites use lots of media/ad servers with different names
136 * but these are generally reused when browsing through the site.
137 *
Mattias Falk3a4910c2011-02-14 12:41:11 +0100138 * As such, a value of 64 should be relatively comfortable at the moment.
139 *
140 * The system property ro.net.dns_cache_size can be used to override the default
141 * value with a custom value
Robert Greenwalt52764f52012-01-25 15:16:03 -0800142 *
143 *
144 * ******************************************
145 * * NOTE - this has changed.
146 * * 1) we've added IPv6 support so each dns query results in 2 responses
147 * * 2) we've made this a system-wide cache, so the cost is less (it's not
148 * * duplicated in each process) and the need is greater (more processes
149 * * making different requests).
150 * * Upping by 2x for IPv6
151 * * Upping by another 5x for the centralized nature
152 * *****************************************
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800153 */
Robert Greenwalt52764f52012-01-25 15:16:03 -0800154#define CONFIG_MAX_ENTRIES 64 * 2 * 5
Mattias Falk3a4910c2011-02-14 12:41:11 +0100155/* name of the system property that can be used to set the cache size */
156#define DNS_CACHE_SIZE_PROP_NAME "ro.net.dns_cache_size"
157
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800158/****************************************************************************/
159/****************************************************************************/
160/***** *****/
161/***** *****/
162/***** *****/
163/****************************************************************************/
164/****************************************************************************/
165
166/* set to 1 to debug cache operations */
167#define DEBUG 0
168
169/* set to 1 to debug query data */
170#define DEBUG_DATA 0
171
Mattias Falk3e0c5102011-01-31 12:42:26 +0100172#undef XLOG
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800173#if DEBUG
174# include <logd.h>
175# define XLOG(...) \
176 __libc_android_log_print(ANDROID_LOG_DEBUG,"libc",__VA_ARGS__)
177
178#include <stdio.h>
179#include <stdarg.h>
180
181/** BOUNDED BUFFER FORMATTING
182 **/
183
184/* technical note:
185 *
186 * the following debugging routines are used to append data to a bounded
187 * buffer they take two parameters that are:
188 *
189 * - p : a pointer to the current cursor position in the buffer
190 * this value is initially set to the buffer's address.
191 *
192 * - end : the address of the buffer's limit, i.e. of the first byte
193 * after the buffer. this address should never be touched.
194 *
195 * IMPORTANT: it is assumed that end > buffer_address, i.e.
196 * that the buffer is at least one byte.
197 *
198 * the _bprint_() functions return the new value of 'p' after the data
199 * has been appended, and also ensure the following:
200 *
201 * - the returned value will never be strictly greater than 'end'
202 *
203 * - a return value equal to 'end' means that truncation occured
204 * (in which case, end[-1] will be set to 0)
205 *
206 * - after returning from a _bprint_() function, the content of the buffer
207 * is always 0-terminated, even in the event of truncation.
208 *
209 * these conventions allow you to call _bprint_ functions multiple times and
210 * only check for truncation at the end of the sequence, as in:
211 *
212 * char buff[1000], *p = buff, *end = p + sizeof(buff);
213 *
214 * p = _bprint_c(p, end, '"');
215 * p = _bprint_s(p, end, my_string);
216 * p = _bprint_c(p, end, '"');
217 *
218 * if (p >= end) {
219 * // buffer was too small
220 * }
221 *
222 * printf( "%s", buff );
223 */
224
225/* add a char to a bounded buffer */
226static char*
227_bprint_c( char* p, char* end, int c )
228{
229 if (p < end) {
230 if (p+1 == end)
231 *p++ = 0;
232 else {
233 *p++ = (char) c;
234 *p = 0;
235 }
236 }
237 return p;
238}
239
240/* add a sequence of bytes to a bounded buffer */
241static char*
242_bprint_b( char* p, char* end, const char* buf, int len )
243{
244 int avail = end - p;
245
246 if (avail <= 0 || len <= 0)
247 return p;
248
249 if (avail > len)
250 avail = len;
251
252 memcpy( p, buf, avail );
253 p += avail;
254
255 if (p < end)
256 p[0] = 0;
257 else
258 end[-1] = 0;
259
260 return p;
261}
262
263/* add a string to a bounded buffer */
264static char*
265_bprint_s( char* p, char* end, const char* str )
266{
267 return _bprint_b(p, end, str, strlen(str));
268}
269
270/* add a formatted string to a bounded buffer */
271static char*
272_bprint( char* p, char* end, const char* format, ... )
273{
274 int avail, n;
275 va_list args;
276
277 avail = end - p;
278
279 if (avail <= 0)
280 return p;
281
282 va_start(args, format);
David 'Digit' Turnerd378c682010-03-08 15:13:04 -0800283 n = vsnprintf( p, avail, format, args);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800284 va_end(args);
285
286 /* certain C libraries return -1 in case of truncation */
287 if (n < 0 || n > avail)
288 n = avail;
289
290 p += n;
291 /* certain C libraries do not zero-terminate in case of truncation */
292 if (p == end)
293 p[-1] = 0;
294
295 return p;
296}
297
298/* add a hex value to a bounded buffer, up to 8 digits */
299static char*
300_bprint_hex( char* p, char* end, unsigned value, int numDigits )
301{
302 char text[sizeof(unsigned)*2];
303 int nn = 0;
304
305 while (numDigits-- > 0) {
306 text[nn++] = "0123456789abcdef"[(value >> (numDigits*4)) & 15];
307 }
308 return _bprint_b(p, end, text, nn);
309}
310
311/* add the hexadecimal dump of some memory area to a bounded buffer */
312static char*
313_bprint_hexdump( char* p, char* end, const uint8_t* data, int datalen )
314{
315 int lineSize = 16;
316
317 while (datalen > 0) {
318 int avail = datalen;
319 int nn;
320
321 if (avail > lineSize)
322 avail = lineSize;
323
324 for (nn = 0; nn < avail; nn++) {
325 if (nn > 0)
326 p = _bprint_c(p, end, ' ');
327 p = _bprint_hex(p, end, data[nn], 2);
328 }
329 for ( ; nn < lineSize; nn++ ) {
330 p = _bprint_s(p, end, " ");
331 }
332 p = _bprint_s(p, end, " ");
333
334 for (nn = 0; nn < avail; nn++) {
335 int c = data[nn];
336
337 if (c < 32 || c > 127)
338 c = '.';
339
340 p = _bprint_c(p, end, c);
341 }
342 p = _bprint_c(p, end, '\n');
343
344 data += avail;
345 datalen -= avail;
346 }
347 return p;
348}
349
350/* dump the content of a query of packet to the log */
351static void
352XLOG_BYTES( const void* base, int len )
353{
354 char buff[1024];
355 char* p = buff, *end = p + sizeof(buff);
356
357 p = _bprint_hexdump(p, end, base, len);
358 XLOG("%s",buff);
359}
360
361#else /* !DEBUG */
362# define XLOG(...) ((void)0)
363# define XLOG_BYTES(a,b) ((void)0)
364#endif
365
366static time_t
367_time_now( void )
368{
369 struct timeval tv;
370
371 gettimeofday( &tv, NULL );
372 return tv.tv_sec;
373}
374
375/* reminder: the general format of a DNS packet is the following:
376 *
377 * HEADER (12 bytes)
378 * QUESTION (variable)
379 * ANSWER (variable)
380 * AUTHORITY (variable)
381 * ADDITIONNAL (variable)
382 *
383 * the HEADER is made of:
384 *
385 * ID : 16 : 16-bit unique query identification field
386 *
387 * QR : 1 : set to 0 for queries, and 1 for responses
388 * Opcode : 4 : set to 0 for queries
389 * AA : 1 : set to 0 for queries
390 * TC : 1 : truncation flag, will be set to 0 in queries
391 * RD : 1 : recursion desired
392 *
393 * RA : 1 : recursion available (0 in queries)
394 * Z : 3 : three reserved zero bits
395 * RCODE : 4 : response code (always 0=NOERROR in queries)
396 *
397 * QDCount: 16 : question count
398 * ANCount: 16 : Answer count (0 in queries)
399 * NSCount: 16: Authority Record count (0 in queries)
400 * ARCount: 16: Additionnal Record count (0 in queries)
401 *
402 * the QUESTION is made of QDCount Question Record (QRs)
403 * the ANSWER is made of ANCount RRs
404 * the AUTHORITY is made of NSCount RRs
405 * the ADDITIONNAL is made of ARCount RRs
406 *
407 * Each Question Record (QR) is made of:
408 *
409 * QNAME : variable : Query DNS NAME
410 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
411 * CLASS : 16 : class of query (IN=1)
412 *
413 * Each Resource Record (RR) is made of:
414 *
415 * NAME : variable : DNS NAME
416 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
417 * CLASS : 16 : class of query (IN=1)
418 * TTL : 32 : seconds to cache this RR (0=none)
419 * RDLENGTH: 16 : size of RDDATA in bytes
420 * RDDATA : variable : RR data (depends on TYPE)
421 *
422 * Each QNAME contains a domain name encoded as a sequence of 'labels'
423 * terminated by a zero. Each label has the following format:
424 *
425 * LEN : 8 : lenght of label (MUST be < 64)
426 * NAME : 8*LEN : label length (must exclude dots)
427 *
428 * A value of 0 in the encoding is interpreted as the 'root' domain and
429 * terminates the encoding. So 'www.android.com' will be encoded as:
430 *
431 * <3>www<7>android<3>com<0>
432 *
433 * Where <n> represents the byte with value 'n'
434 *
435 * Each NAME reflects the QNAME of the question, but has a slightly more
436 * complex encoding in order to provide message compression. This is achieved
437 * by using a 2-byte pointer, with format:
438 *
439 * TYPE : 2 : 0b11 to indicate a pointer, 0b01 and 0b10 are reserved
440 * OFFSET : 14 : offset to another part of the DNS packet
441 *
442 * The offset is relative to the start of the DNS packet and must point
443 * A pointer terminates the encoding.
444 *
445 * The NAME can be encoded in one of the following formats:
446 *
447 * - a sequence of simple labels terminated by 0 (like QNAMEs)
448 * - a single pointer
449 * - a sequence of simple labels terminated by a pointer
450 *
451 * A pointer shall always point to either a pointer of a sequence of
452 * labels (which can themselves be terminated by either a 0 or a pointer)
453 *
454 * The expanded length of a given domain name should not exceed 255 bytes.
455 *
456 * NOTE: we don't parse the answer packets, so don't need to deal with NAME
457 * records, only QNAMEs.
458 */
459
460#define DNS_HEADER_SIZE 12
461
462#define DNS_TYPE_A "\00\01" /* big-endian decimal 1 */
463#define DNS_TYPE_PTR "\00\014" /* big-endian decimal 12 */
464#define DNS_TYPE_MX "\00\017" /* big-endian decimal 15 */
465#define DNS_TYPE_AAAA "\00\034" /* big-endian decimal 28 */
466#define DNS_TYPE_ALL "\00\0377" /* big-endian decimal 255 */
467
468#define DNS_CLASS_IN "\00\01" /* big-endian decimal 1 */
469
470typedef struct {
471 const uint8_t* base;
472 const uint8_t* end;
473 const uint8_t* cursor;
474} DnsPacket;
475
476static void
477_dnsPacket_init( DnsPacket* packet, const uint8_t* buff, int bufflen )
478{
479 packet->base = buff;
480 packet->end = buff + bufflen;
481 packet->cursor = buff;
482}
483
484static void
485_dnsPacket_rewind( DnsPacket* packet )
486{
487 packet->cursor = packet->base;
488}
489
490static void
491_dnsPacket_skip( DnsPacket* packet, int count )
492{
493 const uint8_t* p = packet->cursor + count;
494
495 if (p > packet->end)
496 p = packet->end;
497
498 packet->cursor = p;
499}
500
501static int
502_dnsPacket_readInt16( DnsPacket* packet )
503{
504 const uint8_t* p = packet->cursor;
505
506 if (p+2 > packet->end)
507 return -1;
508
509 packet->cursor = p+2;
510 return (p[0]<< 8) | p[1];
511}
512
513/** QUERY CHECKING
514 **/
515
516/* check bytes in a dns packet. returns 1 on success, 0 on failure.
517 * the cursor is only advanced in the case of success
518 */
519static int
520_dnsPacket_checkBytes( DnsPacket* packet, int numBytes, const void* bytes )
521{
522 const uint8_t* p = packet->cursor;
523
524 if (p + numBytes > packet->end)
525 return 0;
526
527 if (memcmp(p, bytes, numBytes) != 0)
528 return 0;
529
530 packet->cursor = p + numBytes;
531 return 1;
532}
533
534/* parse and skip a given QNAME stored in a query packet,
535 * from the current cursor position. returns 1 on success,
536 * or 0 for malformed data.
537 */
538static int
539_dnsPacket_checkQName( DnsPacket* packet )
540{
541 const uint8_t* p = packet->cursor;
542 const uint8_t* end = packet->end;
543
544 for (;;) {
545 int c;
546
547 if (p >= end)
548 break;
549
550 c = *p++;
551
552 if (c == 0) {
553 packet->cursor = p;
554 return 1;
555 }
556
557 /* we don't expect label compression in QNAMEs */
558 if (c >= 64)
559 break;
560
561 p += c;
562 /* we rely on the bound check at the start
563 * of the loop here */
564 }
565 /* malformed data */
566 XLOG("malformed QNAME");
567 return 0;
568}
569
570/* parse and skip a given QR stored in a packet.
571 * returns 1 on success, and 0 on failure
572 */
573static int
574_dnsPacket_checkQR( DnsPacket* packet )
575{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800576 if (!_dnsPacket_checkQName(packet))
577 return 0;
578
579 /* TYPE must be one of the things we support */
580 if (!_dnsPacket_checkBytes(packet, 2, DNS_TYPE_A) &&
581 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_PTR) &&
582 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_MX) &&
583 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_AAAA) &&
584 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_ALL))
585 {
586 XLOG("unsupported TYPE");
587 return 0;
588 }
589 /* CLASS must be IN */
590 if (!_dnsPacket_checkBytes(packet, 2, DNS_CLASS_IN)) {
591 XLOG("unsupported CLASS");
592 return 0;
593 }
594
595 return 1;
596}
597
598/* check the header of a DNS Query packet, return 1 if it is one
599 * type of query we can cache, or 0 otherwise
600 */
601static int
602_dnsPacket_checkQuery( DnsPacket* packet )
603{
604 const uint8_t* p = packet->base;
605 int qdCount, anCount, dnCount, arCount;
606
607 if (p + DNS_HEADER_SIZE > packet->end) {
608 XLOG("query packet too small");
609 return 0;
610 }
611
612 /* QR must be set to 0, opcode must be 0 and AA must be 0 */
613 /* RA, Z, and RCODE must be 0 */
614 if ((p[2] & 0xFC) != 0 || p[3] != 0) {
615 XLOG("query packet flags unsupported");
616 return 0;
617 }
618
619 /* Note that we ignore the TC and RD bits here for the
620 * following reasons:
621 *
622 * - there is no point for a query packet sent to a server
623 * to have the TC bit set, but the implementation might
624 * set the bit in the query buffer for its own needs
625 * between a _resolv_cache_lookup and a
626 * _resolv_cache_add. We should not freak out if this
627 * is the case.
628 *
629 * - we consider that the result from a RD=0 or a RD=1
630 * query might be different, hence that the RD bit
631 * should be used to differentiate cached result.
632 *
633 * this implies that RD is checked when hashing or
634 * comparing query packets, but not TC
635 */
636
637 /* ANCOUNT, DNCOUNT and ARCOUNT must be 0 */
638 qdCount = (p[4] << 8) | p[5];
639 anCount = (p[6] << 8) | p[7];
640 dnCount = (p[8] << 8) | p[9];
641 arCount = (p[10]<< 8) | p[11];
642
643 if (anCount != 0 || dnCount != 0 || arCount != 0) {
644 XLOG("query packet contains non-query records");
645 return 0;
646 }
647
648 if (qdCount == 0) {
649 XLOG("query packet doesn't contain query record");
650 return 0;
651 }
652
653 /* Check QDCOUNT QRs */
654 packet->cursor = p + DNS_HEADER_SIZE;
655
656 for (;qdCount > 0; qdCount--)
657 if (!_dnsPacket_checkQR(packet))
658 return 0;
659
660 return 1;
661}
662
663/** QUERY DEBUGGING
664 **/
665#if DEBUG
666static char*
667_dnsPacket_bprintQName(DnsPacket* packet, char* bp, char* bend)
668{
669 const uint8_t* p = packet->cursor;
670 const uint8_t* end = packet->end;
671 int first = 1;
672
673 for (;;) {
674 int c;
675
676 if (p >= end)
677 break;
678
679 c = *p++;
680
681 if (c == 0) {
682 packet->cursor = p;
683 return bp;
684 }
685
686 /* we don't expect label compression in QNAMEs */
687 if (c >= 64)
688 break;
689
690 if (first)
691 first = 0;
692 else
693 bp = _bprint_c(bp, bend, '.');
694
695 bp = _bprint_b(bp, bend, (const char*)p, c);
696
697 p += c;
698 /* we rely on the bound check at the start
699 * of the loop here */
700 }
701 /* malformed data */
702 bp = _bprint_s(bp, bend, "<MALFORMED>");
703 return bp;
704}
705
706static char*
707_dnsPacket_bprintQR(DnsPacket* packet, char* p, char* end)
708{
709#define QQ(x) { DNS_TYPE_##x, #x }
710 static const struct {
711 const char* typeBytes;
712 const char* typeString;
713 } qTypes[] =
714 {
715 QQ(A), QQ(PTR), QQ(MX), QQ(AAAA), QQ(ALL),
716 { NULL, NULL }
717 };
718 int nn;
719 const char* typeString = NULL;
720
721 /* dump QNAME */
722 p = _dnsPacket_bprintQName(packet, p, end);
723
724 /* dump TYPE */
725 p = _bprint_s(p, end, " (");
726
727 for (nn = 0; qTypes[nn].typeBytes != NULL; nn++) {
728 if (_dnsPacket_checkBytes(packet, 2, qTypes[nn].typeBytes)) {
729 typeString = qTypes[nn].typeString;
730 break;
731 }
732 }
733
734 if (typeString != NULL)
735 p = _bprint_s(p, end, typeString);
736 else {
737 int typeCode = _dnsPacket_readInt16(packet);
738 p = _bprint(p, end, "UNKNOWN-%d", typeCode);
739 }
740
741 p = _bprint_c(p, end, ')');
742
743 /* skip CLASS */
744 _dnsPacket_skip(packet, 2);
745 return p;
746}
747
748/* this function assumes the packet has already been checked */
749static char*
750_dnsPacket_bprintQuery( DnsPacket* packet, char* p, char* end )
751{
752 int qdCount;
753
754 if (packet->base[2] & 0x1) {
755 p = _bprint_s(p, end, "RECURSIVE ");
756 }
757
758 _dnsPacket_skip(packet, 4);
759 qdCount = _dnsPacket_readInt16(packet);
760 _dnsPacket_skip(packet, 6);
761
762 for ( ; qdCount > 0; qdCount-- ) {
763 p = _dnsPacket_bprintQR(packet, p, end);
764 }
765 return p;
766}
767#endif
768
769
770/** QUERY HASHING SUPPORT
771 **
772 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKET HAS ALREADY
773 ** BEEN SUCCESFULLY CHECKED.
774 **/
775
776/* use 32-bit FNV hash function */
777#define FNV_MULT 16777619U
778#define FNV_BASIS 2166136261U
779
780static unsigned
781_dnsPacket_hashBytes( DnsPacket* packet, int numBytes, unsigned hash )
782{
783 const uint8_t* p = packet->cursor;
784 const uint8_t* end = packet->end;
785
786 while (numBytes > 0 && p < end) {
787 hash = hash*FNV_MULT ^ *p++;
788 }
789 packet->cursor = p;
790 return hash;
791}
792
793
794static unsigned
795_dnsPacket_hashQName( DnsPacket* packet, unsigned hash )
796{
797 const uint8_t* p = packet->cursor;
798 const uint8_t* end = packet->end;
799
800 for (;;) {
801 int c;
802
803 if (p >= end) { /* should not happen */
804 XLOG("%s: INTERNAL_ERROR: read-overflow !!\n", __FUNCTION__);
805 break;
806 }
807
808 c = *p++;
809
810 if (c == 0)
811 break;
812
813 if (c >= 64) {
814 XLOG("%s: INTERNAL_ERROR: malformed domain !!\n", __FUNCTION__);
815 break;
816 }
817 if (p + c >= end) {
818 XLOG("%s: INTERNAL_ERROR: simple label read-overflow !!\n",
819 __FUNCTION__);
820 break;
821 }
822 while (c > 0) {
823 hash = hash*FNV_MULT ^ *p++;
824 c -= 1;
825 }
826 }
827 packet->cursor = p;
828 return hash;
829}
830
831static unsigned
832_dnsPacket_hashQR( DnsPacket* packet, unsigned hash )
833{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800834 hash = _dnsPacket_hashQName(packet, hash);
835 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TYPE and CLASS */
836 return hash;
837}
838
839static unsigned
840_dnsPacket_hashQuery( DnsPacket* packet )
841{
842 unsigned hash = FNV_BASIS;
843 int count;
844 _dnsPacket_rewind(packet);
845
846 /* we ignore the TC bit for reasons explained in
847 * _dnsPacket_checkQuery().
848 *
849 * however we hash the RD bit to differentiate
850 * between answers for recursive and non-recursive
851 * queries.
852 */
853 hash = hash*FNV_MULT ^ (packet->base[2] & 1);
854
855 /* assume: other flags are 0 */
856 _dnsPacket_skip(packet, 4);
857
858 /* read QDCOUNT */
859 count = _dnsPacket_readInt16(packet);
860
861 /* assume: ANcount, NScount, ARcount are 0 */
862 _dnsPacket_skip(packet, 6);
863
864 /* hash QDCOUNT QRs */
865 for ( ; count > 0; count-- )
866 hash = _dnsPacket_hashQR(packet, hash);
867
868 return hash;
869}
870
871
872/** QUERY COMPARISON
873 **
874 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKETS HAVE ALREADY
875 ** BEEN SUCCESFULLY CHECKED.
876 **/
877
878static int
879_dnsPacket_isEqualDomainName( DnsPacket* pack1, DnsPacket* pack2 )
880{
881 const uint8_t* p1 = pack1->cursor;
882 const uint8_t* end1 = pack1->end;
883 const uint8_t* p2 = pack2->cursor;
884 const uint8_t* end2 = pack2->end;
885
886 for (;;) {
887 int c1, c2;
888
889 if (p1 >= end1 || p2 >= end2) {
890 XLOG("%s: INTERNAL_ERROR: read-overflow !!\n", __FUNCTION__);
891 break;
892 }
893 c1 = *p1++;
894 c2 = *p2++;
895 if (c1 != c2)
896 break;
897
898 if (c1 == 0) {
899 pack1->cursor = p1;
900 pack2->cursor = p2;
901 return 1;
902 }
903 if (c1 >= 64) {
904 XLOG("%s: INTERNAL_ERROR: malformed domain !!\n", __FUNCTION__);
905 break;
906 }
907 if ((p1+c1 > end1) || (p2+c1 > end2)) {
908 XLOG("%s: INTERNAL_ERROR: simple label read-overflow !!\n",
909 __FUNCTION__);
910 break;
911 }
912 if (memcmp(p1, p2, c1) != 0)
913 break;
914 p1 += c1;
915 p2 += c1;
916 /* we rely on the bound checks at the start of the loop */
917 }
918 /* not the same, or one is malformed */
919 XLOG("different DN");
920 return 0;
921}
922
923static int
924_dnsPacket_isEqualBytes( DnsPacket* pack1, DnsPacket* pack2, int numBytes )
925{
926 const uint8_t* p1 = pack1->cursor;
927 const uint8_t* p2 = pack2->cursor;
928
929 if ( p1 + numBytes > pack1->end || p2 + numBytes > pack2->end )
930 return 0;
931
932 if ( memcmp(p1, p2, numBytes) != 0 )
933 return 0;
934
935 pack1->cursor += numBytes;
936 pack2->cursor += numBytes;
937 return 1;
938}
939
940static int
941_dnsPacket_isEqualQR( DnsPacket* pack1, DnsPacket* pack2 )
942{
943 /* compare domain name encoding + TYPE + CLASS */
944 if ( !_dnsPacket_isEqualDomainName(pack1, pack2) ||
945 !_dnsPacket_isEqualBytes(pack1, pack2, 2+2) )
946 return 0;
947
948 return 1;
949}
950
951static int
952_dnsPacket_isEqualQuery( DnsPacket* pack1, DnsPacket* pack2 )
953{
954 int count1, count2;
955
956 /* compare the headers, ignore most fields */
957 _dnsPacket_rewind(pack1);
958 _dnsPacket_rewind(pack2);
959
960 /* compare RD, ignore TC, see comment in _dnsPacket_checkQuery */
961 if ((pack1->base[2] & 1) != (pack2->base[2] & 1)) {
962 XLOG("different RD");
963 return 0;
964 }
965
966 /* assume: other flags are all 0 */
967 _dnsPacket_skip(pack1, 4);
968 _dnsPacket_skip(pack2, 4);
969
970 /* compare QDCOUNT */
971 count1 = _dnsPacket_readInt16(pack1);
972 count2 = _dnsPacket_readInt16(pack2);
973 if (count1 != count2 || count1 < 0) {
974 XLOG("different QDCOUNT");
975 return 0;
976 }
977
978 /* assume: ANcount, NScount and ARcount are all 0 */
979 _dnsPacket_skip(pack1, 6);
980 _dnsPacket_skip(pack2, 6);
981
982 /* compare the QDCOUNT QRs */
983 for ( ; count1 > 0; count1-- ) {
984 if (!_dnsPacket_isEqualQR(pack1, pack2)) {
985 XLOG("different QR");
986 return 0;
987 }
988 }
989 return 1;
990}
991
992/****************************************************************************/
993/****************************************************************************/
994/***** *****/
995/***** *****/
996/***** *****/
997/****************************************************************************/
998/****************************************************************************/
999
1000/* cache entry. for simplicity, 'hash' and 'hlink' are inlined in this
1001 * structure though they are conceptually part of the hash table.
1002 *
1003 * similarly, mru_next and mru_prev are part of the global MRU list
1004 */
1005typedef struct Entry {
1006 unsigned int hash; /* hash value */
1007 struct Entry* hlink; /* next in collision chain */
1008 struct Entry* mru_prev;
1009 struct Entry* mru_next;
1010
1011 const uint8_t* query;
1012 int querylen;
1013 const uint8_t* answer;
1014 int answerlen;
Mattias Falk3e0c5102011-01-31 12:42:26 +01001015 time_t expires; /* time_t when the entry isn't valid any more */
1016 int id; /* for debugging purpose */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001017} Entry;
1018
Mattias Falk3e0c5102011-01-31 12:42:26 +01001019/**
Robert Greenwalt78851f12013-01-07 12:10:06 -08001020 * Find the TTL for a negative DNS result. This is defined as the minimum
1021 * of the SOA records TTL and the MINIMUM-TTL field (RFC-2308).
1022 *
1023 * Return 0 if not found.
1024 */
1025static u_long
1026answer_getNegativeTTL(ns_msg handle) {
1027 int n, nscount;
1028 u_long result = 0;
1029 ns_rr rr;
1030
1031 nscount = ns_msg_count(handle, ns_s_ns);
1032 for (n = 0; n < nscount; n++) {
1033 if ((ns_parserr(&handle, ns_s_ns, n, &rr) == 0) && (ns_rr_type(rr) == ns_t_soa)) {
1034 const u_char *rdata = ns_rr_rdata(rr); // find the data
1035 const u_char *edata = rdata + ns_rr_rdlen(rr); // add the len to find the end
1036 int len;
1037 u_long ttl, rec_result = ns_rr_ttl(rr);
1038
1039 // find the MINIMUM-TTL field from the blob of binary data for this record
1040 // skip the server name
1041 len = dn_skipname(rdata, edata);
1042 if (len == -1) continue; // error skipping
1043 rdata += len;
1044
1045 // skip the admin name
1046 len = dn_skipname(rdata, edata);
1047 if (len == -1) continue; // error skipping
1048 rdata += len;
1049
1050 if (edata - rdata != 5*NS_INT32SZ) continue;
1051 // skip: serial number + refresh interval + retry interval + expiry
1052 rdata += NS_INT32SZ * 4;
1053 // finally read the MINIMUM TTL
1054 ttl = ns_get32(rdata);
1055 if (ttl < rec_result) {
1056 rec_result = ttl;
1057 }
1058 // Now that the record is read successfully, apply the new min TTL
1059 if (n == 0 || rec_result < result) {
1060 result = rec_result;
1061 }
1062 }
1063 }
1064 return result;
1065}
1066
1067/**
1068 * Parse the answer records and find the appropriate
1069 * smallest TTL among the records. This might be from
1070 * the answer records if found or from the SOA record
1071 * if it's a negative result.
Mattias Falk3e0c5102011-01-31 12:42:26 +01001072 *
1073 * The returned TTL is the number of seconds to
1074 * keep the answer in the cache.
1075 *
1076 * In case of parse error zero (0) is returned which
1077 * indicates that the answer shall not be cached.
1078 */
1079static u_long
1080answer_getTTL(const void* answer, int answerlen)
1081{
1082 ns_msg handle;
1083 int ancount, n;
1084 u_long result, ttl;
1085 ns_rr rr;
1086
1087 result = 0;
1088 if (ns_initparse(answer, answerlen, &handle) >= 0) {
1089 // get number of answer records
1090 ancount = ns_msg_count(handle, ns_s_an);
Robert Greenwalt78851f12013-01-07 12:10:06 -08001091
1092 if (ancount == 0) {
1093 // a response with no answers? Cache this negative result.
1094 result = answer_getNegativeTTL(handle);
1095 } else {
1096 for (n = 0; n < ancount; n++) {
1097 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
1098 ttl = ns_rr_ttl(rr);
1099 if (n == 0 || ttl < result) {
1100 result = ttl;
1101 }
1102 } else {
1103 XLOG("ns_parserr failed ancount no = %d. errno = %s\n", n, strerror(errno));
Mattias Falk3e0c5102011-01-31 12:42:26 +01001104 }
Mattias Falk3e0c5102011-01-31 12:42:26 +01001105 }
1106 }
1107 } else {
1108 XLOG("ns_parserr failed. %s\n", strerror(errno));
1109 }
1110
1111 XLOG("TTL = %d\n", result);
1112
1113 return result;
1114}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001115
1116static void
1117entry_free( Entry* e )
1118{
1119 /* everything is allocated in a single memory block */
1120 if (e) {
1121 free(e);
1122 }
1123}
1124
1125static __inline__ void
1126entry_mru_remove( Entry* e )
1127{
1128 e->mru_prev->mru_next = e->mru_next;
1129 e->mru_next->mru_prev = e->mru_prev;
1130}
1131
1132static __inline__ void
1133entry_mru_add( Entry* e, Entry* list )
1134{
1135 Entry* first = list->mru_next;
1136
1137 e->mru_next = first;
1138 e->mru_prev = list;
1139
1140 list->mru_next = e;
1141 first->mru_prev = e;
1142}
1143
1144/* compute the hash of a given entry, this is a hash of most
1145 * data in the query (key) */
1146static unsigned
1147entry_hash( const Entry* e )
1148{
1149 DnsPacket pack[1];
1150
1151 _dnsPacket_init(pack, e->query, e->querylen);
1152 return _dnsPacket_hashQuery(pack);
1153}
1154
1155/* initialize an Entry as a search key, this also checks the input query packet
1156 * returns 1 on success, or 0 in case of unsupported/malformed data */
1157static int
1158entry_init_key( Entry* e, const void* query, int querylen )
1159{
1160 DnsPacket pack[1];
1161
1162 memset(e, 0, sizeof(*e));
1163
1164 e->query = query;
1165 e->querylen = querylen;
1166 e->hash = entry_hash(e);
1167
1168 _dnsPacket_init(pack, query, querylen);
1169
1170 return _dnsPacket_checkQuery(pack);
1171}
1172
1173/* allocate a new entry as a cache node */
1174static Entry*
1175entry_alloc( const Entry* init, const void* answer, int answerlen )
1176{
1177 Entry* e;
1178 int size;
1179
1180 size = sizeof(*e) + init->querylen + answerlen;
1181 e = calloc(size, 1);
1182 if (e == NULL)
1183 return e;
1184
1185 e->hash = init->hash;
1186 e->query = (const uint8_t*)(e+1);
1187 e->querylen = init->querylen;
1188
1189 memcpy( (char*)e->query, init->query, e->querylen );
1190
1191 e->answer = e->query + e->querylen;
1192 e->answerlen = answerlen;
1193
1194 memcpy( (char*)e->answer, answer, e->answerlen );
1195
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001196 return e;
1197}
1198
1199static int
1200entry_equals( const Entry* e1, const Entry* e2 )
1201{
1202 DnsPacket pack1[1], pack2[1];
1203
1204 if (e1->querylen != e2->querylen) {
1205 return 0;
1206 }
1207 _dnsPacket_init(pack1, e1->query, e1->querylen);
1208 _dnsPacket_init(pack2, e2->query, e2->querylen);
1209
1210 return _dnsPacket_isEqualQuery(pack1, pack2);
1211}
1212
1213/****************************************************************************/
1214/****************************************************************************/
1215/***** *****/
1216/***** *****/
1217/***** *****/
1218/****************************************************************************/
1219/****************************************************************************/
1220
1221/* We use a simple hash table with external collision lists
1222 * for simplicity, the hash-table fields 'hash' and 'hlink' are
1223 * inlined in the Entry structure.
1224 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001225
Mattias Falka59cfcf2011-09-06 15:15:06 +02001226/* Maximum time for a thread to wait for an pending request */
1227#define PENDING_REQUEST_TIMEOUT 20;
1228
1229typedef struct pending_req_info {
1230 unsigned int hash;
1231 pthread_cond_t cond;
1232 struct pending_req_info* next;
1233} PendingReqInfo;
1234
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001235typedef struct resolv_cache {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001236 int max_entries;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001237 int num_entries;
1238 Entry mru_list;
1239 pthread_mutex_t lock;
1240 unsigned generation;
1241 int last_id;
Mattias Falk3a4910c2011-02-14 12:41:11 +01001242 Entry* entries;
Mattias Falka59cfcf2011-09-06 15:15:06 +02001243 PendingReqInfo pending_requests;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001244} Cache;
1245
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001246typedef struct resolv_cache_info {
1247 char ifname[IF_NAMESIZE + 1];
1248 struct in_addr ifaddr;
1249 Cache* cache;
1250 struct resolv_cache_info* next;
1251 char* nameservers[MAXNS +1];
1252 struct addrinfo* nsaddrinfo[MAXNS + 1];
Mattias Falkc63e5902011-08-23 14:34:14 +02001253 char defdname[256];
1254 int dnsrch_offset[MAXDNSRCH+1]; // offsets into defdname
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001255} CacheInfo;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001256
Mattias Falkc63e5902011-08-23 14:34:14 +02001257typedef struct resolv_pidiface_info {
1258 int pid;
1259 char ifname[IF_NAMESIZE + 1];
1260 struct resolv_pidiface_info* next;
1261} PidIfaceInfo;
1262
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001263#define HTABLE_VALID(x) ((x) != NULL && (x) != HTABLE_DELETED)
1264
1265static void
Mattias Falka59cfcf2011-09-06 15:15:06 +02001266_cache_flush_pending_requests_locked( struct resolv_cache* cache )
1267{
1268 struct pending_req_info *ri, *tmp;
1269 if (cache) {
1270 ri = cache->pending_requests.next;
1271
1272 while (ri) {
1273 tmp = ri;
1274 ri = ri->next;
1275 pthread_cond_broadcast(&tmp->cond);
1276
1277 pthread_cond_destroy(&tmp->cond);
1278 free(tmp);
1279 }
1280
1281 cache->pending_requests.next = NULL;
1282 }
1283}
1284
1285/* return 0 if no pending request is found matching the key
1286 * if a matching request is found the calling thread will wait
1287 * and return 1 when released */
1288static int
1289_cache_check_pending_request_locked( struct resolv_cache* cache, Entry* key )
1290{
1291 struct pending_req_info *ri, *prev;
1292 int exist = 0;
1293
1294 if (cache && key) {
1295 ri = cache->pending_requests.next;
1296 prev = &cache->pending_requests;
1297 while (ri) {
1298 if (ri->hash == key->hash) {
1299 exist = 1;
1300 break;
1301 }
1302 prev = ri;
1303 ri = ri->next;
1304 }
1305
1306 if (!exist) {
1307 ri = calloc(1, sizeof(struct pending_req_info));
1308 if (ri) {
1309 ri->hash = key->hash;
1310 pthread_cond_init(&ri->cond, NULL);
1311 prev->next = ri;
1312 }
1313 } else {
1314 struct timespec ts = {0,0};
Mattias Falkc63e5902011-08-23 14:34:14 +02001315 XLOG("Waiting for previous request");
Mattias Falka59cfcf2011-09-06 15:15:06 +02001316 ts.tv_sec = _time_now() + PENDING_REQUEST_TIMEOUT;
Robert Greenwalt78851f12013-01-07 12:10:06 -08001317 pthread_cond_timedwait(&ri->cond, &cache->lock, &ts);
Mattias Falka59cfcf2011-09-06 15:15:06 +02001318 }
1319 }
1320
1321 return exist;
1322}
1323
1324/* notify any waiting thread that waiting on a request
1325 * matching the key has been added to the cache */
1326static void
1327_cache_notify_waiting_tid_locked( struct resolv_cache* cache, Entry* key )
1328{
1329 struct pending_req_info *ri, *prev;
1330
1331 if (cache && key) {
1332 ri = cache->pending_requests.next;
1333 prev = &cache->pending_requests;
1334 while (ri) {
1335 if (ri->hash == key->hash) {
1336 pthread_cond_broadcast(&ri->cond);
1337 break;
1338 }
1339 prev = ri;
1340 ri = ri->next;
1341 }
1342
1343 // remove item from list and destroy
1344 if (ri) {
1345 prev->next = ri->next;
1346 pthread_cond_destroy(&ri->cond);
1347 free(ri);
1348 }
1349 }
1350}
1351
1352/* notify the cache that the query failed */
1353void
1354_resolv_cache_query_failed( struct resolv_cache* cache,
1355 const void* query,
1356 int querylen)
1357{
1358 Entry key[1];
1359
1360 if (cache && entry_init_key(key, query, querylen)) {
1361 pthread_mutex_lock(&cache->lock);
1362 _cache_notify_waiting_tid_locked(cache, key);
1363 pthread_mutex_unlock(&cache->lock);
1364 }
1365}
1366
1367static void
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001368_cache_flush_locked( Cache* cache )
1369{
1370 int nn;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001371
Mattias Falk3a4910c2011-02-14 12:41:11 +01001372 for (nn = 0; nn < cache->max_entries; nn++)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001373 {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001374 Entry** pnode = (Entry**) &cache->entries[nn];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001375
1376 while (*pnode != NULL) {
1377 Entry* node = *pnode;
1378 *pnode = node->hlink;
1379 entry_free(node);
1380 }
1381 }
1382
Mattias Falka59cfcf2011-09-06 15:15:06 +02001383 // flush pending request
1384 _cache_flush_pending_requests_locked(cache);
1385
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001386 cache->mru_list.mru_next = cache->mru_list.mru_prev = &cache->mru_list;
1387 cache->num_entries = 0;
1388 cache->last_id = 0;
1389
1390 XLOG("*************************\n"
1391 "*** DNS CACHE FLUSHED ***\n"
1392 "*************************");
1393}
1394
Mattias Falk3a4910c2011-02-14 12:41:11 +01001395/* Return max number of entries allowed in the cache,
1396 * i.e. cache size. The cache size is either defined
1397 * by system property ro.net.dns_cache_size or by
1398 * CONFIG_MAX_ENTRIES if system property not set
1399 * or set to invalid value. */
1400static int
1401_res_cache_get_max_entries( void )
1402{
1403 int result = -1;
1404 char cache_size[PROP_VALUE_MAX];
1405
Robert Greenwalt52764f52012-01-25 15:16:03 -08001406 const char* cache_mode = getenv("ANDROID_DNS_MODE");
1407
1408 if (cache_mode == NULL || strcmp(cache_mode, "local") != 0) {
1409 // Don't use the cache in local mode. This is used by the
1410 // proxy itself.
Mattias Falkc63e5902011-08-23 14:34:14 +02001411 XLOG("setup cache for non-cache process. size=0, %s", cache_mode);
1412 return 0;
Robert Greenwalt52764f52012-01-25 15:16:03 -08001413 }
1414
Mattias Falk3a4910c2011-02-14 12:41:11 +01001415 if (__system_property_get(DNS_CACHE_SIZE_PROP_NAME, cache_size) > 0) {
1416 result = atoi(cache_size);
1417 }
1418
1419 // ro.net.dns_cache_size not set or set to negative value
1420 if (result <= 0) {
1421 result = CONFIG_MAX_ENTRIES;
1422 }
1423
1424 XLOG("cache size: %d", result);
1425 return result;
1426}
1427
Jim Huang7cc56662010-10-15 02:02:57 +08001428static struct resolv_cache*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001429_resolv_cache_create( void )
1430{
1431 struct resolv_cache* cache;
1432
1433 cache = calloc(sizeof(*cache), 1);
1434 if (cache) {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001435 cache->max_entries = _res_cache_get_max_entries();
1436 cache->entries = calloc(sizeof(*cache->entries), cache->max_entries);
1437 if (cache->entries) {
1438 cache->generation = ~0U;
1439 pthread_mutex_init( &cache->lock, NULL );
1440 cache->mru_list.mru_prev = cache->mru_list.mru_next = &cache->mru_list;
1441 XLOG("%s: cache created\n", __FUNCTION__);
1442 } else {
1443 free(cache);
1444 cache = NULL;
1445 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001446 }
1447 return cache;
1448}
1449
1450
1451#if DEBUG
1452static void
1453_dump_query( const uint8_t* query, int querylen )
1454{
1455 char temp[256], *p=temp, *end=p+sizeof(temp);
1456 DnsPacket pack[1];
1457
1458 _dnsPacket_init(pack, query, querylen);
1459 p = _dnsPacket_bprintQuery(pack, p, end);
1460 XLOG("QUERY: %s", temp);
1461}
1462
1463static void
1464_cache_dump_mru( Cache* cache )
1465{
1466 char temp[512], *p=temp, *end=p+sizeof(temp);
1467 Entry* e;
1468
1469 p = _bprint(temp, end, "MRU LIST (%2d): ", cache->num_entries);
1470 for (e = cache->mru_list.mru_next; e != &cache->mru_list; e = e->mru_next)
1471 p = _bprint(p, end, " %d", e->id);
1472
1473 XLOG("%s", temp);
1474}
Mattias Falk3e0c5102011-01-31 12:42:26 +01001475
1476static void
1477_dump_answer(const void* answer, int answerlen)
1478{
1479 res_state statep;
1480 FILE* fp;
1481 char* buf;
1482 int fileLen;
1483
1484 fp = fopen("/data/reslog.txt", "w+");
1485 if (fp != NULL) {
1486 statep = __res_get_state();
1487
1488 res_pquery(statep, answer, answerlen, fp);
1489
1490 //Get file length
1491 fseek(fp, 0, SEEK_END);
1492 fileLen=ftell(fp);
1493 fseek(fp, 0, SEEK_SET);
1494 buf = (char *)malloc(fileLen+1);
1495 if (buf != NULL) {
1496 //Read file contents into buffer
1497 fread(buf, fileLen, 1, fp);
1498 XLOG("%s\n", buf);
1499 free(buf);
1500 }
1501 fclose(fp);
1502 remove("/data/reslog.txt");
1503 }
1504 else {
Robert Greenwalt78851f12013-01-07 12:10:06 -08001505 errno = 0; // else debug is introducing error signals
Mattias Falk3e0c5102011-01-31 12:42:26 +01001506 XLOG("_dump_answer: can't open file\n");
1507 }
1508}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001509#endif
1510
1511#if DEBUG
1512# define XLOG_QUERY(q,len) _dump_query((q), (len))
Mattias Falk3e0c5102011-01-31 12:42:26 +01001513# define XLOG_ANSWER(a, len) _dump_answer((a), (len))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001514#else
1515# define XLOG_QUERY(q,len) ((void)0)
Mattias Falk3e0c5102011-01-31 12:42:26 +01001516# define XLOG_ANSWER(a,len) ((void)0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001517#endif
1518
1519/* This function tries to find a key within the hash table
1520 * In case of success, it will return a *pointer* to the hashed key.
1521 * In case of failure, it will return a *pointer* to NULL
1522 *
1523 * So, the caller must check '*result' to check for success/failure.
1524 *
1525 * The main idea is that the result can later be used directly in
1526 * calls to _resolv_cache_add or _resolv_cache_remove as the 'lookup'
1527 * parameter. This makes the code simpler and avoids re-searching
1528 * for the key position in the htable.
1529 *
1530 * The result of a lookup_p is only valid until you alter the hash
1531 * table.
1532 */
1533static Entry**
1534_cache_lookup_p( Cache* cache,
1535 Entry* key )
1536{
Mattias Falk3a4910c2011-02-14 12:41:11 +01001537 int index = key->hash % cache->max_entries;
1538 Entry** pnode = (Entry**) &cache->entries[ index ];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001539
1540 while (*pnode != NULL) {
1541 Entry* node = *pnode;
1542
1543 if (node == NULL)
1544 break;
1545
1546 if (node->hash == key->hash && entry_equals(node, key))
1547 break;
1548
1549 pnode = &node->hlink;
1550 }
Mattias Falkc63e5902011-08-23 14:34:14 +02001551 return pnode;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001552}
1553
1554/* Add a new entry to the hash table. 'lookup' must be the
1555 * result of an immediate previous failed _lookup_p() call
1556 * (i.e. with *lookup == NULL), and 'e' is the pointer to the
1557 * newly created entry
1558 */
1559static void
1560_cache_add_p( Cache* cache,
1561 Entry** lookup,
1562 Entry* e )
1563{
1564 *lookup = e;
1565 e->id = ++cache->last_id;
1566 entry_mru_add(e, &cache->mru_list);
1567 cache->num_entries += 1;
1568
1569 XLOG("%s: entry %d added (count=%d)", __FUNCTION__,
1570 e->id, cache->num_entries);
1571}
1572
1573/* Remove an existing entry from the hash table,
1574 * 'lookup' must be the result of an immediate previous
1575 * and succesful _lookup_p() call.
1576 */
1577static void
1578_cache_remove_p( Cache* cache,
1579 Entry** lookup )
1580{
1581 Entry* e = *lookup;
1582
1583 XLOG("%s: entry %d removed (count=%d)", __FUNCTION__,
1584 e->id, cache->num_entries-1);
1585
1586 entry_mru_remove(e);
1587 *lookup = e->hlink;
1588 entry_free(e);
1589 cache->num_entries -= 1;
1590}
1591
1592/* Remove the oldest entry from the hash table.
1593 */
1594static void
1595_cache_remove_oldest( Cache* cache )
1596{
1597 Entry* oldest = cache->mru_list.mru_prev;
1598 Entry** lookup = _cache_lookup_p(cache, oldest);
1599
1600 if (*lookup == NULL) { /* should not happen */
1601 XLOG("%s: OLDEST NOT IN HTABLE ?", __FUNCTION__);
1602 return;
1603 }
Robert Greenwalt7f84da62011-09-02 07:44:36 -07001604 if (DEBUG) {
1605 XLOG("Cache full - removing oldest");
1606 XLOG_QUERY(oldest->query, oldest->querylen);
1607 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001608 _cache_remove_p(cache, lookup);
1609}
1610
Anders Fredlunddd161822011-05-20 08:12:37 +02001611/* Remove all expired entries from the hash table.
1612 */
1613static void _cache_remove_expired(Cache* cache) {
1614 Entry* e;
1615 time_t now = _time_now();
1616
1617 for (e = cache->mru_list.mru_next; e != &cache->mru_list;) {
1618 // Entry is old, remove
1619 if (now >= e->expires) {
1620 Entry** lookup = _cache_lookup_p(cache, e);
1621 if (*lookup == NULL) { /* should not happen */
1622 XLOG("%s: ENTRY NOT IN HTABLE ?", __FUNCTION__);
1623 return;
1624 }
1625 e = e->mru_next;
1626 _cache_remove_p(cache, lookup);
1627 } else {
1628 e = e->mru_next;
1629 }
1630 }
1631}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001632
1633ResolvCacheStatus
1634_resolv_cache_lookup( struct resolv_cache* cache,
1635 const void* query,
1636 int querylen,
1637 void* answer,
1638 int answersize,
1639 int *answerlen )
1640{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001641 Entry key[1];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001642 Entry** lookup;
1643 Entry* e;
1644 time_t now;
1645
1646 ResolvCacheStatus result = RESOLV_CACHE_NOTFOUND;
1647
1648 XLOG("%s: lookup", __FUNCTION__);
1649 XLOG_QUERY(query, querylen);
1650
1651 /* we don't cache malformed queries */
1652 if (!entry_init_key(key, query, querylen)) {
1653 XLOG("%s: unsupported query", __FUNCTION__);
1654 return RESOLV_CACHE_UNSUPPORTED;
1655 }
1656 /* lookup cache */
1657 pthread_mutex_lock( &cache->lock );
1658
1659 /* see the description of _lookup_p to understand this.
1660 * the function always return a non-NULL pointer.
1661 */
1662 lookup = _cache_lookup_p(cache, key);
1663 e = *lookup;
1664
1665 if (e == NULL) {
1666 XLOG( "NOT IN CACHE");
Mattias Falka59cfcf2011-09-06 15:15:06 +02001667 // calling thread will wait if an outstanding request is found
1668 // that matching this query
1669 if (!_cache_check_pending_request_locked(cache, key)) {
1670 goto Exit;
1671 } else {
1672 lookup = _cache_lookup_p(cache, key);
1673 e = *lookup;
1674 if (e == NULL) {
1675 goto Exit;
1676 }
1677 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001678 }
1679
1680 now = _time_now();
1681
1682 /* remove stale entries here */
Mattias Falk3e0c5102011-01-31 12:42:26 +01001683 if (now >= e->expires) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001684 XLOG( " NOT IN CACHE (STALE ENTRY %p DISCARDED)", *lookup );
Robert Greenwalt7f84da62011-09-02 07:44:36 -07001685 XLOG_QUERY(e->query, e->querylen);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001686 _cache_remove_p(cache, lookup);
1687 goto Exit;
1688 }
1689
1690 *answerlen = e->answerlen;
1691 if (e->answerlen > answersize) {
1692 /* NOTE: we return UNSUPPORTED if the answer buffer is too short */
1693 result = RESOLV_CACHE_UNSUPPORTED;
1694 XLOG(" ANSWER TOO LONG");
1695 goto Exit;
1696 }
1697
1698 memcpy( answer, e->answer, e->answerlen );
1699
1700 /* bump up this entry to the top of the MRU list */
1701 if (e != cache->mru_list.mru_next) {
1702 entry_mru_remove( e );
1703 entry_mru_add( e, &cache->mru_list );
1704 }
1705
1706 XLOG( "FOUND IN CACHE entry=%p", e );
1707 result = RESOLV_CACHE_FOUND;
1708
1709Exit:
1710 pthread_mutex_unlock( &cache->lock );
1711 return result;
1712}
1713
1714
1715void
1716_resolv_cache_add( struct resolv_cache* cache,
1717 const void* query,
1718 int querylen,
1719 const void* answer,
1720 int answerlen )
1721{
1722 Entry key[1];
1723 Entry* e;
1724 Entry** lookup;
Mattias Falk3e0c5102011-01-31 12:42:26 +01001725 u_long ttl;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001726
1727 /* don't assume that the query has already been cached
1728 */
1729 if (!entry_init_key( key, query, querylen )) {
1730 XLOG( "%s: passed invalid query ?", __FUNCTION__);
1731 return;
1732 }
1733
1734 pthread_mutex_lock( &cache->lock );
1735
1736 XLOG( "%s: query:", __FUNCTION__ );
1737 XLOG_QUERY(query,querylen);
Mattias Falk3e0c5102011-01-31 12:42:26 +01001738 XLOG_ANSWER(answer, answerlen);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001739#if DEBUG_DATA
1740 XLOG( "answer:");
1741 XLOG_BYTES(answer,answerlen);
1742#endif
1743
1744 lookup = _cache_lookup_p(cache, key);
1745 e = *lookup;
1746
1747 if (e != NULL) { /* should not happen */
1748 XLOG("%s: ALREADY IN CACHE (%p) ? IGNORING ADD",
1749 __FUNCTION__, e);
1750 goto Exit;
1751 }
1752
Mattias Falk3a4910c2011-02-14 12:41:11 +01001753 if (cache->num_entries >= cache->max_entries) {
Anders Fredlunddd161822011-05-20 08:12:37 +02001754 _cache_remove_expired(cache);
1755 if (cache->num_entries >= cache->max_entries) {
1756 _cache_remove_oldest(cache);
1757 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001758 /* need to lookup again */
1759 lookup = _cache_lookup_p(cache, key);
1760 e = *lookup;
1761 if (e != NULL) {
1762 XLOG("%s: ALREADY IN CACHE (%p) ? IGNORING ADD",
1763 __FUNCTION__, e);
1764 goto Exit;
1765 }
1766 }
1767
Mattias Falk3e0c5102011-01-31 12:42:26 +01001768 ttl = answer_getTTL(answer, answerlen);
1769 if (ttl > 0) {
1770 e = entry_alloc(key, answer, answerlen);
1771 if (e != NULL) {
1772 e->expires = ttl + _time_now();
1773 _cache_add_p(cache, lookup, e);
1774 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001775 }
1776#if DEBUG
1777 _cache_dump_mru(cache);
1778#endif
1779Exit:
Mattias Falka59cfcf2011-09-06 15:15:06 +02001780 _cache_notify_waiting_tid_locked(cache, key);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001781 pthread_mutex_unlock( &cache->lock );
1782}
1783
1784/****************************************************************************/
1785/****************************************************************************/
1786/***** *****/
1787/***** *****/
1788/***** *****/
1789/****************************************************************************/
1790/****************************************************************************/
1791
Mattias Falkc63e5902011-08-23 14:34:14 +02001792static pthread_once_t _res_cache_once = PTHREAD_ONCE_INIT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001793
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001794// Head of the list of caches. Protected by _res_cache_list_lock.
1795static struct resolv_cache_info _res_cache_list;
1796
Mattias Falkc63e5902011-08-23 14:34:14 +02001797// List of pid iface pairs
1798static struct resolv_pidiface_info _res_pidiface_list;
1799
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001800// name of the current default inteface
1801static char _res_default_ifname[IF_NAMESIZE + 1];
1802
1803// lock protecting everything in the _resolve_cache_info structs (next ptr, etc)
1804static pthread_mutex_t _res_cache_list_lock;
1805
Mattias Falkc63e5902011-08-23 14:34:14 +02001806// lock protecting the _res_pid_iface_list
1807static pthread_mutex_t _res_pidiface_list_lock;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001808
1809/* lookup the default interface name */
1810static char *_get_default_iface_locked();
Mattias Falkc63e5902011-08-23 14:34:14 +02001811/* find the first cache that has an associated interface and return the name of the interface */
1812static char* _find_any_iface_name_locked( void );
1813
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001814/* insert resolv_cache_info into the list of resolv_cache_infos */
1815static void _insert_cache_info_locked(struct resolv_cache_info* cache_info);
1816/* creates a resolv_cache_info */
1817static struct resolv_cache_info* _create_cache_info( void );
1818/* gets cache associated with an interface name, or NULL if none exists */
1819static struct resolv_cache* _find_named_cache_locked(const char* ifname);
1820/* gets a resolv_cache_info associated with an interface name, or NULL if not found */
1821static struct resolv_cache_info* _find_cache_info_locked(const char* ifname);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001822/* look up the named cache, and creates one if needed */
1823static struct resolv_cache* _get_res_cache_for_iface_locked(const char* ifname);
1824/* empty the named cache */
1825static void _flush_cache_for_iface_locked(const char* ifname);
1826/* empty the nameservers set for the named cache */
1827static void _free_nameservers_locked(struct resolv_cache_info* cache_info);
1828/* lookup the namserver for the name interface */
1829static int _get_nameserver_locked(const char* ifname, int n, char* addr, int addrLen);
1830/* lookup the addr of the nameserver for the named interface */
1831static struct addrinfo* _get_nameserver_addr_locked(const char* ifname, int n);
1832/* lookup the inteface's address */
1833static struct in_addr* _get_addr_locked(const char * ifname);
Mattias Falkc63e5902011-08-23 14:34:14 +02001834/* return 1 if the provided list of name servers differs from the list of name servers
1835 * currently attached to the provided cache_info */
1836static int _resolv_is_nameservers_equal_locked(struct resolv_cache_info* cache_info,
1837 char** servers, int numservers);
1838/* remove a resolv_pidiface_info structure from _res_pidiface_list */
1839static void _remove_pidiface_info_locked(int pid);
1840/* get a resolv_pidiface_info structure from _res_pidiface_list with a certain pid */
1841static struct resolv_pidiface_info* _get_pid_iface_info_locked(int pid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001842
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001843static void
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001844_res_cache_init(void)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001845{
1846 const char* env = getenv(CONFIG_ENV);
1847
1848 if (env && atoi(env) == 0) {
1849 /* the cache is disabled */
1850 return;
1851 }
1852
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001853 memset(&_res_default_ifname, 0, sizeof(_res_default_ifname));
1854 memset(&_res_cache_list, 0, sizeof(_res_cache_list));
Mattias Falkc63e5902011-08-23 14:34:14 +02001855 memset(&_res_pidiface_list, 0, sizeof(_res_pidiface_list));
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001856 pthread_mutex_init(&_res_cache_list_lock, NULL);
Mattias Falkc63e5902011-08-23 14:34:14 +02001857 pthread_mutex_init(&_res_pidiface_list_lock, NULL);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001858}
1859
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001860struct resolv_cache*
Mattias Falkc63e5902011-08-23 14:34:14 +02001861__get_res_cache(const char* ifname)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001862{
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001863 struct resolv_cache *cache;
1864
1865 pthread_once(&_res_cache_once, _res_cache_init);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001866 pthread_mutex_lock(&_res_cache_list_lock);
1867
Mattias Falkc63e5902011-08-23 14:34:14 +02001868 char* iface;
1869 if (ifname == NULL || ifname[0] == '\0') {
1870 iface = _get_default_iface_locked();
1871 if (iface[0] == '\0') {
1872 char* tmp = _find_any_iface_name_locked();
1873 if (tmp) {
1874 iface = tmp;
Robert Greenwaltb002a2f2013-01-19 00:40:24 +00001875 }
Robert Greenwaltb002a2f2013-01-19 00:40:24 +00001876 }
Mattias Falkc63e5902011-08-23 14:34:14 +02001877 } else {
1878 iface = (char *) ifname;
Robert Greenwaltb002a2f2013-01-19 00:40:24 +00001879 }
Mattias Falkc63e5902011-08-23 14:34:14 +02001880
1881 cache = _get_res_cache_for_iface_locked(iface);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001882
1883 pthread_mutex_unlock(&_res_cache_list_lock);
Mattias Falkc63e5902011-08-23 14:34:14 +02001884 XLOG("_get_res_cache: iface = %s, cache=%p\n", iface, cache);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001885 return cache;
1886}
1887
1888static struct resolv_cache*
1889_get_res_cache_for_iface_locked(const char* ifname)
1890{
1891 if (ifname == NULL)
1892 return NULL;
1893
1894 struct resolv_cache* cache = _find_named_cache_locked(ifname);
1895 if (!cache) {
1896 struct resolv_cache_info* cache_info = _create_cache_info();
1897 if (cache_info) {
1898 cache = _resolv_cache_create();
1899 if (cache) {
1900 int len = sizeof(cache_info->ifname);
1901 cache_info->cache = cache;
1902 strncpy(cache_info->ifname, ifname, len - 1);
1903 cache_info->ifname[len - 1] = '\0';
1904
1905 _insert_cache_info_locked(cache_info);
1906 } else {
1907 free(cache_info);
1908 }
1909 }
1910 }
1911 return cache;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001912}
1913
1914void
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001915_resolv_cache_reset(unsigned generation)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001916{
1917 XLOG("%s: generation=%d", __FUNCTION__, generation);
1918
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001919 pthread_once(&_res_cache_once, _res_cache_init);
1920 pthread_mutex_lock(&_res_cache_list_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001921
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001922 char* ifname = _get_default_iface_locked();
1923 // if default interface not set then use the first cache
1924 // associated with an interface as the default one.
1925 // Note: Copied the code from __get_res_cache since this
1926 // method will be deleted/obsolete when cache per interface
1927 // implemented all over
1928 if (ifname[0] == '\0') {
1929 struct resolv_cache_info* cache_info = _res_cache_list.next;
1930 while (cache_info) {
1931 if (cache_info->ifname[0] != '\0') {
1932 ifname = cache_info->ifname;
Robert Greenwalt9363d912011-07-25 12:30:17 -07001933 break;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001934 }
1935
1936 cache_info = cache_info->next;
1937 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001938 }
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001939 struct resolv_cache* cache = _get_res_cache_for_iface_locked(ifname);
1940
Robert Greenwalt9363d912011-07-25 12:30:17 -07001941 if (cache != NULL) {
1942 pthread_mutex_lock( &cache->lock );
1943 if (cache->generation != generation) {
1944 _cache_flush_locked(cache);
1945 cache->generation = generation;
1946 }
1947 pthread_mutex_unlock( &cache->lock );
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001948 }
1949
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001950 pthread_mutex_unlock(&_res_cache_list_lock);
1951}
1952
1953void
1954_resolv_flush_cache_for_default_iface(void)
1955{
1956 char* ifname;
1957
1958 pthread_once(&_res_cache_once, _res_cache_init);
1959 pthread_mutex_lock(&_res_cache_list_lock);
1960
1961 ifname = _get_default_iface_locked();
1962 _flush_cache_for_iface_locked(ifname);
1963
1964 pthread_mutex_unlock(&_res_cache_list_lock);
1965}
1966
1967void
1968_resolv_flush_cache_for_iface(const char* ifname)
1969{
1970 pthread_once(&_res_cache_once, _res_cache_init);
1971 pthread_mutex_lock(&_res_cache_list_lock);
1972
1973 _flush_cache_for_iface_locked(ifname);
1974
1975 pthread_mutex_unlock(&_res_cache_list_lock);
1976}
1977
1978static void
1979_flush_cache_for_iface_locked(const char* ifname)
1980{
1981 struct resolv_cache* cache = _find_named_cache_locked(ifname);
1982 if (cache) {
1983 pthread_mutex_lock(&cache->lock);
1984 _cache_flush_locked(cache);
1985 pthread_mutex_unlock(&cache->lock);
1986 }
1987}
1988
1989static struct resolv_cache_info*
1990_create_cache_info(void)
1991{
1992 struct resolv_cache_info* cache_info;
1993
1994 cache_info = calloc(sizeof(*cache_info), 1);
1995 return cache_info;
1996}
1997
1998static void
1999_insert_cache_info_locked(struct resolv_cache_info* cache_info)
2000{
2001 struct resolv_cache_info* last;
2002
2003 for (last = &_res_cache_list; last->next; last = last->next);
2004
2005 last->next = cache_info;
2006
2007}
2008
2009static struct resolv_cache*
2010_find_named_cache_locked(const char* ifname) {
2011
2012 struct resolv_cache_info* info = _find_cache_info_locked(ifname);
2013
2014 if (info != NULL) return info->cache;
2015
2016 return NULL;
2017}
2018
2019static struct resolv_cache_info*
2020_find_cache_info_locked(const char* ifname)
2021{
2022 if (ifname == NULL)
2023 return NULL;
2024
2025 struct resolv_cache_info* cache_info = _res_cache_list.next;
2026
2027 while (cache_info) {
2028 if (strcmp(cache_info->ifname, ifname) == 0) {
2029 break;
2030 }
2031
2032 cache_info = cache_info->next;
2033 }
2034 return cache_info;
2035}
2036
2037static char*
2038_get_default_iface_locked(void)
2039{
Mattias Falkc63e5902011-08-23 14:34:14 +02002040
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002041 char* iface = _res_default_ifname;
2042
2043 return iface;
2044}
2045
Mattias Falkc63e5902011-08-23 14:34:14 +02002046static char*
2047_find_any_iface_name_locked( void ) {
2048 char* ifname = NULL;
2049
2050 struct resolv_cache_info* cache_info = _res_cache_list.next;
2051 while (cache_info) {
2052 if (cache_info->ifname[0] != '\0') {
2053 ifname = cache_info->ifname;
2054 break;
2055 }
2056
2057 cache_info = cache_info->next;
2058 }
2059
2060 return ifname;
2061}
2062
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002063void
2064_resolv_set_default_iface(const char* ifname)
2065{
2066 XLOG("_resolv_set_default_if ifname %s\n",ifname);
2067
2068 pthread_once(&_res_cache_once, _res_cache_init);
2069 pthread_mutex_lock(&_res_cache_list_lock);
2070
2071 int size = sizeof(_res_default_ifname);
2072 memset(_res_default_ifname, 0, size);
2073 strncpy(_res_default_ifname, ifname, size - 1);
2074 _res_default_ifname[size - 1] = '\0';
2075
2076 pthread_mutex_unlock(&_res_cache_list_lock);
2077}
2078
2079void
Robert Greenwalt6f3222e2012-11-13 11:50:57 -08002080_resolv_set_nameservers_for_iface(const char* ifname, char** servers, int numservers,
2081 const char *domains)
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002082{
2083 int i, rt, index;
2084 struct addrinfo hints;
2085 char sbuf[NI_MAXSERV];
Mattias Falkc63e5902011-08-23 14:34:14 +02002086 register char *cp;
2087 int *offset;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002088
2089 pthread_once(&_res_cache_once, _res_cache_init);
Robert Greenwaltb002a2f2013-01-19 00:40:24 +00002090 pthread_mutex_lock(&_res_cache_list_lock);
Mattias Falkc63e5902011-08-23 14:34:14 +02002091
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002092 // creates the cache if not created
2093 _get_res_cache_for_iface_locked(ifname);
2094
2095 struct resolv_cache_info* cache_info = _find_cache_info_locked(ifname);
2096
Mattias Falkc63e5902011-08-23 14:34:14 +02002097 if (cache_info != NULL &&
2098 !_resolv_is_nameservers_equal_locked(cache_info, servers, numservers)) {
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002099 // free current before adding new
2100 _free_nameservers_locked(cache_info);
2101
2102 memset(&hints, 0, sizeof(hints));
2103 hints.ai_family = PF_UNSPEC;
2104 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
2105 hints.ai_flags = AI_NUMERICHOST;
2106 sprintf(sbuf, "%u", NAMESERVER_PORT);
2107
2108 index = 0;
2109 for (i = 0; i < numservers && i < MAXNS; i++) {
2110 rt = getaddrinfo(servers[i], sbuf, &hints, &cache_info->nsaddrinfo[index]);
2111 if (rt == 0) {
2112 cache_info->nameservers[index] = strdup(servers[i]);
2113 index++;
Mattias Falkc63e5902011-08-23 14:34:14 +02002114 XLOG("_resolv_set_nameservers_for_iface: iface = %s, addr = %s\n",
2115 ifname, servers[i]);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002116 } else {
2117 cache_info->nsaddrinfo[index] = NULL;
2118 }
2119 }
Mattias Falkc63e5902011-08-23 14:34:14 +02002120
2121 // code moved from res_init.c, load_domain_search_list
2122 strlcpy(cache_info->defdname, domains, sizeof(cache_info->defdname));
2123 if ((cp = strchr(cache_info->defdname, '\n')) != NULL)
2124 *cp = '\0';
2125 cp = cache_info->defdname;
2126 offset = cache_info->dnsrch_offset;
2127 while (offset < cache_info->dnsrch_offset + MAXDNSRCH) {
2128 while (*cp == ' ' || *cp == '\t') /* skip leading white space */
2129 cp++;
2130 if (*cp == '\0') /* stop if nothing more to do */
2131 break;
2132 *offset++ = cp - cache_info->defdname; /* record this search domain */
2133 while (*cp) { /* zero-terminate it */
2134 if (*cp == ' '|| *cp == '\t') {
2135 *cp++ = '\0';
2136 break;
2137 }
2138 cp++;
2139 }
2140 }
2141 *offset = -1; /* cache_info->dnsrch_offset has MAXDNSRCH+1 items */
2142
2143 // flush cache since new settings
2144 _flush_cache_for_iface_locked(ifname);
2145
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002146 }
Mattias Falkc63e5902011-08-23 14:34:14 +02002147
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002148 pthread_mutex_unlock(&_res_cache_list_lock);
2149}
2150
Mattias Falkc63e5902011-08-23 14:34:14 +02002151static int
2152_resolv_is_nameservers_equal_locked(struct resolv_cache_info* cache_info,
2153 char** servers, int numservers)
2154{
2155 int i;
2156 char** ns;
2157 int equal = 1;
2158
2159 // compare each name server against current name servers
2160 if (numservers > MAXNS) numservers = MAXNS;
2161 for (i = 0; i < numservers && equal; i++) {
2162 ns = cache_info->nameservers;
2163 equal = 0;
2164 while(*ns) {
2165 if (strcmp(*ns, servers[i]) == 0) {
2166 equal = 1;
2167 break;
2168 }
2169 ns++;
2170 }
2171 }
2172
2173 return equal;
2174}
2175
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002176static void
2177_free_nameservers_locked(struct resolv_cache_info* cache_info)
2178{
2179 int i;
2180 for (i = 0; i <= MAXNS; i++) {
2181 free(cache_info->nameservers[i]);
2182 cache_info->nameservers[i] = NULL;
Robert Greenwalt9363d912011-07-25 12:30:17 -07002183 if (cache_info->nsaddrinfo[i] != NULL) {
2184 freeaddrinfo(cache_info->nsaddrinfo[i]);
2185 cache_info->nsaddrinfo[i] = NULL;
2186 }
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002187 }
2188}
2189
2190int
2191_resolv_cache_get_nameserver(int n, char* addr, int addrLen)
2192{
2193 char *ifname;
2194 int result = 0;
2195
2196 pthread_once(&_res_cache_once, _res_cache_init);
2197 pthread_mutex_lock(&_res_cache_list_lock);
2198
2199 ifname = _get_default_iface_locked();
2200 result = _get_nameserver_locked(ifname, n, addr, addrLen);
2201
2202 pthread_mutex_unlock(&_res_cache_list_lock);
2203 return result;
2204}
2205
2206static int
2207_get_nameserver_locked(const char* ifname, int n, char* addr, int addrLen)
2208{
2209 int len = 0;
2210 char* ns;
2211 struct resolv_cache_info* cache_info;
2212
2213 if (n < 1 || n > MAXNS || !addr)
2214 return 0;
2215
2216 cache_info = _find_cache_info_locked(ifname);
2217 if (cache_info) {
2218 ns = cache_info->nameservers[n - 1];
2219 if (ns) {
2220 len = strlen(ns);
2221 if (len < addrLen) {
2222 strncpy(addr, ns, len);
2223 addr[len] = '\0';
2224 } else {
2225 len = 0;
2226 }
2227 }
2228 }
2229
2230 return len;
2231}
2232
2233struct addrinfo*
2234_cache_get_nameserver_addr(int n)
2235{
2236 struct addrinfo *result;
2237 char* ifname;
2238
2239 pthread_once(&_res_cache_once, _res_cache_init);
2240 pthread_mutex_lock(&_res_cache_list_lock);
2241
2242 ifname = _get_default_iface_locked();
2243
2244 result = _get_nameserver_addr_locked(ifname, n);
2245 pthread_mutex_unlock(&_res_cache_list_lock);
2246 return result;
2247}
2248
2249static struct addrinfo*
2250_get_nameserver_addr_locked(const char* ifname, int n)
2251{
2252 struct addrinfo* ai = NULL;
2253 struct resolv_cache_info* cache_info;
2254
2255 if (n < 1 || n > MAXNS)
2256 return NULL;
2257
2258 cache_info = _find_cache_info_locked(ifname);
2259 if (cache_info) {
2260 ai = cache_info->nsaddrinfo[n - 1];
2261 }
2262 return ai;
2263}
2264
2265void
2266_resolv_set_addr_of_iface(const char* ifname, struct in_addr* addr)
2267{
2268 pthread_once(&_res_cache_once, _res_cache_init);
2269 pthread_mutex_lock(&_res_cache_list_lock);
2270 struct resolv_cache_info* cache_info = _find_cache_info_locked(ifname);
2271 if (cache_info) {
2272 memcpy(&cache_info->ifaddr, addr, sizeof(*addr));
2273
2274 if (DEBUG) {
2275 char* addr_s = inet_ntoa(cache_info->ifaddr);
2276 XLOG("address of interface %s is %s\n", ifname, addr_s);
2277 }
2278 }
2279 pthread_mutex_unlock(&_res_cache_list_lock);
2280}
2281
2282struct in_addr*
2283_resolv_get_addr_of_default_iface(void)
2284{
2285 struct in_addr* ai = NULL;
2286 char* ifname;
2287
2288 pthread_once(&_res_cache_once, _res_cache_init);
2289 pthread_mutex_lock(&_res_cache_list_lock);
2290 ifname = _get_default_iface_locked();
2291 ai = _get_addr_locked(ifname);
2292 pthread_mutex_unlock(&_res_cache_list_lock);
2293
2294 return ai;
2295}
2296
2297struct in_addr*
2298_resolv_get_addr_of_iface(const char* ifname)
2299{
2300 struct in_addr* ai = NULL;
2301
2302 pthread_once(&_res_cache_once, _res_cache_init);
2303 pthread_mutex_lock(&_res_cache_list_lock);
2304 ai =_get_addr_locked(ifname);
2305 pthread_mutex_unlock(&_res_cache_list_lock);
2306 return ai;
2307}
2308
2309static struct in_addr*
2310_get_addr_locked(const char * ifname)
2311{
2312 struct resolv_cache_info* cache_info = _find_cache_info_locked(ifname);
2313 if (cache_info) {
2314 return &cache_info->ifaddr;
2315 }
2316 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002317}
Mattias Falkc63e5902011-08-23 14:34:14 +02002318
2319static void
2320_remove_pidiface_info_locked(int pid) {
2321 struct resolv_pidiface_info* result = &_res_pidiface_list;
2322 struct resolv_pidiface_info* prev = NULL;
2323
2324 while (result != NULL && result->pid != pid) {
2325 prev = result;
2326 result = result->next;
2327 }
2328 if (prev != NULL && result != NULL) {
2329 prev->next = result->next;
2330 free(result);
2331 }
2332}
2333
2334static struct resolv_pidiface_info*
2335_get_pid_iface_info_locked(int pid)
2336{
2337 struct resolv_pidiface_info* result = &_res_pidiface_list;
2338 while (result != NULL && result->pid != pid) {
2339 result = result->next;
2340 }
2341
2342 return result;
2343}
2344
2345void
2346_resolv_set_iface_for_pid(const char* ifname, int pid)
2347{
2348 // make sure the pid iface list is created
2349 pthread_once(&_res_cache_once, _res_cache_init);
2350 pthread_mutex_lock(&_res_pidiface_list_lock);
2351
2352 struct resolv_pidiface_info* pidiface_info = _get_pid_iface_info_locked(pid);
2353 if (!pidiface_info) {
2354 pidiface_info = calloc(sizeof(*pidiface_info), 1);
2355 if (pidiface_info) {
2356 pidiface_info->pid = pid;
2357 int len = sizeof(pidiface_info->ifname);
2358 strncpy(pidiface_info->ifname, ifname, len - 1);
2359 pidiface_info->ifname[len - 1] = '\0';
2360
2361 pidiface_info->next = _res_pidiface_list.next;
2362 _res_pidiface_list.next = pidiface_info;
2363
2364 XLOG("_resolv_set_iface_for_pid: pid %d , iface %s\n", pid, ifname);
2365 } else {
2366 XLOG("_resolv_set_iface_for_pid failing calloc");
2367 }
2368 }
2369
2370 pthread_mutex_unlock(&_res_pidiface_list_lock);
2371}
2372
2373void
2374_resolv_clear_iface_for_pid(int pid)
2375{
2376 pthread_once(&_res_cache_once, _res_cache_init);
2377 pthread_mutex_lock(&_res_pidiface_list_lock);
2378
2379 _remove_pidiface_info_locked(pid);
2380
2381 XLOG("_resolv_clear_iface_for_pid: pid %d\n", pid);
2382
2383 pthread_mutex_unlock(&_res_pidiface_list_lock);
2384}
2385
2386int
2387_resolv_get_pids_associated_interface(int pid, char* buff, int buffLen)
2388{
2389 int len = 0;
2390
2391 if (!buff) {
2392 return -1;
2393 }
2394
2395 pthread_once(&_res_cache_once, _res_cache_init);
2396 pthread_mutex_lock(&_res_pidiface_list_lock);
2397
2398 struct resolv_pidiface_info* pidiface_info = _get_pid_iface_info_locked(pid);
2399 buff[0] = '\0';
2400 if (pidiface_info) {
2401 len = strlen(pidiface_info->ifname);
2402 if (len < buffLen) {
2403 strncpy(buff, pidiface_info->ifname, len);
2404 buff[len] = '\0';
2405 }
2406 }
2407
2408 XLOG("_resolv_get_pids_associated_interface buff: %s\n", buff);
2409
2410 pthread_mutex_unlock(&_res_pidiface_list_lock);
2411
2412 return len;
2413}
2414
2415int
2416_resolv_get_default_iface(char* buff, int buffLen)
2417{
2418 char* ifname;
2419 int len = 0;
2420
2421 if (!buff || buffLen == 0) {
2422 return -1;
2423 }
2424
2425 pthread_once(&_res_cache_once, _res_cache_init);
2426 pthread_mutex_lock(&_res_cache_list_lock);
2427
2428 ifname = _get_default_iface_locked(); // never null, but may be empty
2429
2430 // if default interface not set. Get first cache with an interface
2431 if (ifname[0] == '\0') {
2432 ifname = _find_any_iface_name_locked(); // may be null
2433 }
2434
2435 // if we got the default iface or if (no-default) the find_any call gave an answer
2436 if (ifname) {
2437 len = strlen(ifname);
2438 if (len < buffLen) {
2439 strncpy(buff, ifname, len);
2440 buff[len] = '\0';
2441 }
2442 } else {
2443 buff[0] = '\0';
2444 }
2445
2446 pthread_mutex_unlock(&_res_cache_list_lock);
2447
2448 return len;
2449}
2450
2451int
2452_resolv_populate_res_for_iface(res_state statp)
2453{
2454 int nserv;
2455 struct resolv_cache_info* info = NULL;
2456
2457 if (statp) {
2458 struct addrinfo* ai;
2459
2460 if (statp->iface[0] == '\0') { // no interface set assign default
2461 _resolv_get_default_iface(statp->iface, sizeof(statp->iface));
2462 }
2463
2464 pthread_once(&_res_cache_once, _res_cache_init);
2465 pthread_mutex_lock(&_res_cache_list_lock);
2466 info = _find_cache_info_locked(statp->iface);
2467
2468 if (info == NULL) {
2469 pthread_mutex_unlock(&_res_cache_list_lock);
2470 return 0;
2471 }
2472
2473 XLOG("_resolv_populate_res_for_iface: %s\n", statp->iface);
2474 for (nserv = 0; nserv < MAXNS; nserv++) {
2475 ai = info->nsaddrinfo[nserv];
2476 if (ai == NULL) {
2477 break;
2478 }
2479
2480 if ((size_t) ai->ai_addrlen <= sizeof(statp->_u._ext.ext->nsaddrs[0])) {
2481 if (statp->_u._ext.ext != NULL) {
2482 memcpy(&statp->_u._ext.ext->nsaddrs[nserv], ai->ai_addr, ai->ai_addrlen);
2483 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
2484 } else {
2485 if ((size_t) ai->ai_addrlen
2486 <= sizeof(statp->nsaddr_list[0])) {
2487 memcpy(&statp->nsaddr_list[nserv], ai->ai_addr,
2488 ai->ai_addrlen);
2489 } else {
2490 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
2491 }
2492 }
2493 } else {
2494 XLOG("_resolv_populate_res_for_iface found too long addrlen");
2495 }
2496 }
2497 statp->nscount = nserv;
2498 // now do search domains. Note that we cache the offsets as this code runs alot
2499 // but the setting/offset-computer only runs when set/changed
2500 strlcpy(statp->defdname, info->defdname, sizeof(statp->defdname));
2501 register char **pp = statp->dnsrch;
2502 register int *p = info->dnsrch_offset;
2503 while (pp < statp->dnsrch + MAXDNSRCH && *p != -1) {
2504 *pp++ = &statp->defdname + *p++;
2505 }
2506
2507 pthread_mutex_unlock(&_res_cache_list_lock);
2508 }
2509 return nserv;
2510}