blob: afc9a365facda6ecb62cc08ef48d1700a6e34e9c [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 Falk3e0c5102011-01-31 12:42:26 +010046
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080047/* This code implements a small and *simple* DNS resolver cache.
48 *
Mattias Falk3e0c5102011-01-31 12:42:26 +010049 * It is only used to cache DNS answers for a time defined by the smallest TTL
50 * among the answer records in order to reduce DNS traffic. It is not supposed
51 * to be a full DNS cache, since we plan to implement that in the future in a
52 * dedicated process running on the system.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080053 *
54 * Note that its design is kept simple very intentionally, i.e.:
55 *
56 * - it takes raw DNS query packet data as input, and returns raw DNS
57 * answer packet data as output
58 *
59 * (this means that two similar queries that encode the DNS name
60 * differently will be treated distinctly).
61 *
Mattias Falk3e0c5102011-01-31 12:42:26 +010062 * the smallest TTL value among the answer records are used as the time
63 * to keep an answer in the cache.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080064 *
65 * this is bad, but we absolutely want to avoid parsing the answer packets
66 * (and should be solved by the later full DNS cache process).
67 *
68 * - the implementation is just a (query-data) => (answer-data) hash table
69 * with a trivial least-recently-used expiration policy.
70 *
71 * Doing this keeps the code simple and avoids to deal with a lot of things
72 * that a full DNS cache is expected to do.
73 *
74 * The API is also very simple:
75 *
76 * - the client calls _resolv_cache_get() to obtain a handle to the cache.
77 * this will initialize the cache on first usage. the result can be NULL
78 * if the cache is disabled.
79 *
80 * - the client calls _resolv_cache_lookup() before performing a query
81 *
82 * if the function returns RESOLV_CACHE_FOUND, a copy of the answer data
83 * has been copied into the client-provided answer buffer.
84 *
85 * if the function returns RESOLV_CACHE_NOTFOUND, the client should perform
86 * a request normally, *then* call _resolv_cache_add() to add the received
87 * answer to the cache.
88 *
89 * if the function returns RESOLV_CACHE_UNSUPPORTED, the client should
90 * perform a request normally, and *not* call _resolv_cache_add()
91 *
92 * note that RESOLV_CACHE_UNSUPPORTED is also returned if the answer buffer
93 * is too short to accomodate the cached result.
94 *
95 * - when network settings change, the cache must be flushed since the list
96 * of DNS servers probably changed. this is done by calling
97 * _resolv_cache_reset()
98 *
99 * the parameter to this function must be an ever-increasing generation
100 * number corresponding to the current network settings state.
101 *
102 * This is done because several threads could detect the same network
103 * settings change (but at different times) and will all end up calling the
104 * same function. Comparing with the last used generation number ensures
105 * that the cache is only flushed once per network change.
106 */
107
108/* the name of an environment variable that will be checked the first time
109 * this code is called if its value is "0", then the resolver cache is
110 * disabled.
111 */
112#define CONFIG_ENV "BIONIC_DNSCACHE"
113
114/* entries older than CONFIG_SECONDS seconds are always discarded.
115 */
116#define CONFIG_SECONDS (60*10) /* 10 minutes */
117
Mattias Falk3a4910c2011-02-14 12:41:11 +0100118/* default number of entries kept in the cache. This value has been
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800119 * determined by browsing through various sites and counting the number
120 * of corresponding requests. Keep in mind that our framework is currently
121 * performing two requests per name lookup (one for IPv4, the other for IPv6)
122 *
123 * www.google.com 4
124 * www.ysearch.com 6
125 * www.amazon.com 8
126 * www.nytimes.com 22
127 * www.espn.com 28
128 * www.msn.com 28
129 * www.lemonde.fr 35
130 *
131 * (determined in 2009-2-17 from Paris, France, results may vary depending
132 * on location)
133 *
134 * most high-level websites use lots of media/ad servers with different names
135 * but these are generally reused when browsing through the site.
136 *
Mattias Falk3a4910c2011-02-14 12:41:11 +0100137 * As such, a value of 64 should be relatively comfortable at the moment.
138 *
139 * The system property ro.net.dns_cache_size can be used to override the default
140 * value with a custom value
Robert Greenwalt52764f52012-01-25 15:16:03 -0800141 *
142 *
143 * ******************************************
144 * * NOTE - this has changed.
145 * * 1) we've added IPv6 support so each dns query results in 2 responses
146 * * 2) we've made this a system-wide cache, so the cost is less (it's not
147 * * duplicated in each process) and the need is greater (more processes
148 * * making different requests).
149 * * Upping by 2x for IPv6
150 * * Upping by another 5x for the centralized nature
151 * *****************************************
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800152 */
Robert Greenwalt52764f52012-01-25 15:16:03 -0800153#define CONFIG_MAX_ENTRIES 64 * 2 * 5
Mattias Falk3a4910c2011-02-14 12:41:11 +0100154/* name of the system property that can be used to set the cache size */
155#define DNS_CACHE_SIZE_PROP_NAME "ro.net.dns_cache_size"
156
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800157/****************************************************************************/
158/****************************************************************************/
159/***** *****/
160/***** *****/
161/***** *****/
162/****************************************************************************/
163/****************************************************************************/
164
165/* set to 1 to debug cache operations */
166#define DEBUG 0
167
168/* set to 1 to debug query data */
169#define DEBUG_DATA 0
170
Mattias Falk3e0c5102011-01-31 12:42:26 +0100171#undef XLOG
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800172#if DEBUG
173# include <logd.h>
174# define XLOG(...) \
175 __libc_android_log_print(ANDROID_LOG_DEBUG,"libc",__VA_ARGS__)
176
177#include <stdio.h>
178#include <stdarg.h>
179
180/** BOUNDED BUFFER FORMATTING
181 **/
182
183/* technical note:
184 *
185 * the following debugging routines are used to append data to a bounded
186 * buffer they take two parameters that are:
187 *
188 * - p : a pointer to the current cursor position in the buffer
189 * this value is initially set to the buffer's address.
190 *
191 * - end : the address of the buffer's limit, i.e. of the first byte
192 * after the buffer. this address should never be touched.
193 *
194 * IMPORTANT: it is assumed that end > buffer_address, i.e.
195 * that the buffer is at least one byte.
196 *
197 * the _bprint_() functions return the new value of 'p' after the data
198 * has been appended, and also ensure the following:
199 *
200 * - the returned value will never be strictly greater than 'end'
201 *
202 * - a return value equal to 'end' means that truncation occured
203 * (in which case, end[-1] will be set to 0)
204 *
205 * - after returning from a _bprint_() function, the content of the buffer
206 * is always 0-terminated, even in the event of truncation.
207 *
208 * these conventions allow you to call _bprint_ functions multiple times and
209 * only check for truncation at the end of the sequence, as in:
210 *
211 * char buff[1000], *p = buff, *end = p + sizeof(buff);
212 *
213 * p = _bprint_c(p, end, '"');
214 * p = _bprint_s(p, end, my_string);
215 * p = _bprint_c(p, end, '"');
216 *
217 * if (p >= end) {
218 * // buffer was too small
219 * }
220 *
221 * printf( "%s", buff );
222 */
223
224/* add a char to a bounded buffer */
225static char*
226_bprint_c( char* p, char* end, int c )
227{
228 if (p < end) {
229 if (p+1 == end)
230 *p++ = 0;
231 else {
232 *p++ = (char) c;
233 *p = 0;
234 }
235 }
236 return p;
237}
238
239/* add a sequence of bytes to a bounded buffer */
240static char*
241_bprint_b( char* p, char* end, const char* buf, int len )
242{
243 int avail = end - p;
244
245 if (avail <= 0 || len <= 0)
246 return p;
247
248 if (avail > len)
249 avail = len;
250
251 memcpy( p, buf, avail );
252 p += avail;
253
254 if (p < end)
255 p[0] = 0;
256 else
257 end[-1] = 0;
258
259 return p;
260}
261
262/* add a string to a bounded buffer */
263static char*
264_bprint_s( char* p, char* end, const char* str )
265{
266 return _bprint_b(p, end, str, strlen(str));
267}
268
269/* add a formatted string to a bounded buffer */
270static char*
271_bprint( char* p, char* end, const char* format, ... )
272{
273 int avail, n;
274 va_list args;
275
276 avail = end - p;
277
278 if (avail <= 0)
279 return p;
280
281 va_start(args, format);
David 'Digit' Turnerd378c682010-03-08 15:13:04 -0800282 n = vsnprintf( p, avail, format, args);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800283 va_end(args);
284
285 /* certain C libraries return -1 in case of truncation */
286 if (n < 0 || n > avail)
287 n = avail;
288
289 p += n;
290 /* certain C libraries do not zero-terminate in case of truncation */
291 if (p == end)
292 p[-1] = 0;
293
294 return p;
295}
296
297/* add a hex value to a bounded buffer, up to 8 digits */
298static char*
299_bprint_hex( char* p, char* end, unsigned value, int numDigits )
300{
301 char text[sizeof(unsigned)*2];
302 int nn = 0;
303
304 while (numDigits-- > 0) {
305 text[nn++] = "0123456789abcdef"[(value >> (numDigits*4)) & 15];
306 }
307 return _bprint_b(p, end, text, nn);
308}
309
310/* add the hexadecimal dump of some memory area to a bounded buffer */
311static char*
312_bprint_hexdump( char* p, char* end, const uint8_t* data, int datalen )
313{
314 int lineSize = 16;
315
316 while (datalen > 0) {
317 int avail = datalen;
318 int nn;
319
320 if (avail > lineSize)
321 avail = lineSize;
322
323 for (nn = 0; nn < avail; nn++) {
324 if (nn > 0)
325 p = _bprint_c(p, end, ' ');
326 p = _bprint_hex(p, end, data[nn], 2);
327 }
328 for ( ; nn < lineSize; nn++ ) {
329 p = _bprint_s(p, end, " ");
330 }
331 p = _bprint_s(p, end, " ");
332
333 for (nn = 0; nn < avail; nn++) {
334 int c = data[nn];
335
336 if (c < 32 || c > 127)
337 c = '.';
338
339 p = _bprint_c(p, end, c);
340 }
341 p = _bprint_c(p, end, '\n');
342
343 data += avail;
344 datalen -= avail;
345 }
346 return p;
347}
348
349/* dump the content of a query of packet to the log */
350static void
351XLOG_BYTES( const void* base, int len )
352{
353 char buff[1024];
354 char* p = buff, *end = p + sizeof(buff);
355
356 p = _bprint_hexdump(p, end, base, len);
357 XLOG("%s",buff);
358}
359
360#else /* !DEBUG */
361# define XLOG(...) ((void)0)
362# define XLOG_BYTES(a,b) ((void)0)
363#endif
364
365static time_t
366_time_now( void )
367{
368 struct timeval tv;
369
370 gettimeofday( &tv, NULL );
371 return tv.tv_sec;
372}
373
374/* reminder: the general format of a DNS packet is the following:
375 *
376 * HEADER (12 bytes)
377 * QUESTION (variable)
378 * ANSWER (variable)
379 * AUTHORITY (variable)
380 * ADDITIONNAL (variable)
381 *
382 * the HEADER is made of:
383 *
384 * ID : 16 : 16-bit unique query identification field
385 *
386 * QR : 1 : set to 0 for queries, and 1 for responses
387 * Opcode : 4 : set to 0 for queries
388 * AA : 1 : set to 0 for queries
389 * TC : 1 : truncation flag, will be set to 0 in queries
390 * RD : 1 : recursion desired
391 *
392 * RA : 1 : recursion available (0 in queries)
393 * Z : 3 : three reserved zero bits
394 * RCODE : 4 : response code (always 0=NOERROR in queries)
395 *
396 * QDCount: 16 : question count
397 * ANCount: 16 : Answer count (0 in queries)
398 * NSCount: 16: Authority Record count (0 in queries)
399 * ARCount: 16: Additionnal Record count (0 in queries)
400 *
401 * the QUESTION is made of QDCount Question Record (QRs)
402 * the ANSWER is made of ANCount RRs
403 * the AUTHORITY is made of NSCount RRs
404 * the ADDITIONNAL is made of ARCount RRs
405 *
406 * Each Question Record (QR) is made of:
407 *
408 * QNAME : variable : Query DNS NAME
409 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
410 * CLASS : 16 : class of query (IN=1)
411 *
412 * Each Resource Record (RR) is made of:
413 *
414 * NAME : variable : DNS NAME
415 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
416 * CLASS : 16 : class of query (IN=1)
417 * TTL : 32 : seconds to cache this RR (0=none)
418 * RDLENGTH: 16 : size of RDDATA in bytes
419 * RDDATA : variable : RR data (depends on TYPE)
420 *
421 * Each QNAME contains a domain name encoded as a sequence of 'labels'
422 * terminated by a zero. Each label has the following format:
423 *
424 * LEN : 8 : lenght of label (MUST be < 64)
425 * NAME : 8*LEN : label length (must exclude dots)
426 *
427 * A value of 0 in the encoding is interpreted as the 'root' domain and
428 * terminates the encoding. So 'www.android.com' will be encoded as:
429 *
430 * <3>www<7>android<3>com<0>
431 *
432 * Where <n> represents the byte with value 'n'
433 *
434 * Each NAME reflects the QNAME of the question, but has a slightly more
435 * complex encoding in order to provide message compression. This is achieved
436 * by using a 2-byte pointer, with format:
437 *
438 * TYPE : 2 : 0b11 to indicate a pointer, 0b01 and 0b10 are reserved
439 * OFFSET : 14 : offset to another part of the DNS packet
440 *
441 * The offset is relative to the start of the DNS packet and must point
442 * A pointer terminates the encoding.
443 *
444 * The NAME can be encoded in one of the following formats:
445 *
446 * - a sequence of simple labels terminated by 0 (like QNAMEs)
447 * - a single pointer
448 * - a sequence of simple labels terminated by a pointer
449 *
450 * A pointer shall always point to either a pointer of a sequence of
451 * labels (which can themselves be terminated by either a 0 or a pointer)
452 *
453 * The expanded length of a given domain name should not exceed 255 bytes.
454 *
455 * NOTE: we don't parse the answer packets, so don't need to deal with NAME
456 * records, only QNAMEs.
457 */
458
459#define DNS_HEADER_SIZE 12
460
461#define DNS_TYPE_A "\00\01" /* big-endian decimal 1 */
462#define DNS_TYPE_PTR "\00\014" /* big-endian decimal 12 */
463#define DNS_TYPE_MX "\00\017" /* big-endian decimal 15 */
464#define DNS_TYPE_AAAA "\00\034" /* big-endian decimal 28 */
465#define DNS_TYPE_ALL "\00\0377" /* big-endian decimal 255 */
466
467#define DNS_CLASS_IN "\00\01" /* big-endian decimal 1 */
468
469typedef struct {
470 const uint8_t* base;
471 const uint8_t* end;
472 const uint8_t* cursor;
473} DnsPacket;
474
475static void
476_dnsPacket_init( DnsPacket* packet, const uint8_t* buff, int bufflen )
477{
478 packet->base = buff;
479 packet->end = buff + bufflen;
480 packet->cursor = buff;
481}
482
483static void
484_dnsPacket_rewind( DnsPacket* packet )
485{
486 packet->cursor = packet->base;
487}
488
489static void
490_dnsPacket_skip( DnsPacket* packet, int count )
491{
492 const uint8_t* p = packet->cursor + count;
493
494 if (p > packet->end)
495 p = packet->end;
496
497 packet->cursor = p;
498}
499
500static int
501_dnsPacket_readInt16( DnsPacket* packet )
502{
503 const uint8_t* p = packet->cursor;
504
505 if (p+2 > packet->end)
506 return -1;
507
508 packet->cursor = p+2;
509 return (p[0]<< 8) | p[1];
510}
511
512/** QUERY CHECKING
513 **/
514
515/* check bytes in a dns packet. returns 1 on success, 0 on failure.
516 * the cursor is only advanced in the case of success
517 */
518static int
519_dnsPacket_checkBytes( DnsPacket* packet, int numBytes, const void* bytes )
520{
521 const uint8_t* p = packet->cursor;
522
523 if (p + numBytes > packet->end)
524 return 0;
525
526 if (memcmp(p, bytes, numBytes) != 0)
527 return 0;
528
529 packet->cursor = p + numBytes;
530 return 1;
531}
532
533/* parse and skip a given QNAME stored in a query packet,
534 * from the current cursor position. returns 1 on success,
535 * or 0 for malformed data.
536 */
537static int
538_dnsPacket_checkQName( DnsPacket* packet )
539{
540 const uint8_t* p = packet->cursor;
541 const uint8_t* end = packet->end;
542
543 for (;;) {
544 int c;
545
546 if (p >= end)
547 break;
548
549 c = *p++;
550
551 if (c == 0) {
552 packet->cursor = p;
553 return 1;
554 }
555
556 /* we don't expect label compression in QNAMEs */
557 if (c >= 64)
558 break;
559
560 p += c;
561 /* we rely on the bound check at the start
562 * of the loop here */
563 }
564 /* malformed data */
565 XLOG("malformed QNAME");
566 return 0;
567}
568
569/* parse and skip a given QR stored in a packet.
570 * returns 1 on success, and 0 on failure
571 */
572static int
573_dnsPacket_checkQR( DnsPacket* packet )
574{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800575 if (!_dnsPacket_checkQName(packet))
576 return 0;
577
578 /* TYPE must be one of the things we support */
579 if (!_dnsPacket_checkBytes(packet, 2, DNS_TYPE_A) &&
580 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_PTR) &&
581 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_MX) &&
582 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_AAAA) &&
583 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_ALL))
584 {
585 XLOG("unsupported TYPE");
586 return 0;
587 }
588 /* CLASS must be IN */
589 if (!_dnsPacket_checkBytes(packet, 2, DNS_CLASS_IN)) {
590 XLOG("unsupported CLASS");
591 return 0;
592 }
593
594 return 1;
595}
596
597/* check the header of a DNS Query packet, return 1 if it is one
598 * type of query we can cache, or 0 otherwise
599 */
600static int
601_dnsPacket_checkQuery( DnsPacket* packet )
602{
603 const uint8_t* p = packet->base;
604 int qdCount, anCount, dnCount, arCount;
605
606 if (p + DNS_HEADER_SIZE > packet->end) {
607 XLOG("query packet too small");
608 return 0;
609 }
610
611 /* QR must be set to 0, opcode must be 0 and AA must be 0 */
612 /* RA, Z, and RCODE must be 0 */
613 if ((p[2] & 0xFC) != 0 || p[3] != 0) {
614 XLOG("query packet flags unsupported");
615 return 0;
616 }
617
618 /* Note that we ignore the TC and RD bits here for the
619 * following reasons:
620 *
621 * - there is no point for a query packet sent to a server
622 * to have the TC bit set, but the implementation might
623 * set the bit in the query buffer for its own needs
624 * between a _resolv_cache_lookup and a
625 * _resolv_cache_add. We should not freak out if this
626 * is the case.
627 *
628 * - we consider that the result from a RD=0 or a RD=1
629 * query might be different, hence that the RD bit
630 * should be used to differentiate cached result.
631 *
632 * this implies that RD is checked when hashing or
633 * comparing query packets, but not TC
634 */
635
636 /* ANCOUNT, DNCOUNT and ARCOUNT must be 0 */
637 qdCount = (p[4] << 8) | p[5];
638 anCount = (p[6] << 8) | p[7];
639 dnCount = (p[8] << 8) | p[9];
640 arCount = (p[10]<< 8) | p[11];
641
642 if (anCount != 0 || dnCount != 0 || arCount != 0) {
643 XLOG("query packet contains non-query records");
644 return 0;
645 }
646
647 if (qdCount == 0) {
648 XLOG("query packet doesn't contain query record");
649 return 0;
650 }
651
652 /* Check QDCOUNT QRs */
653 packet->cursor = p + DNS_HEADER_SIZE;
654
655 for (;qdCount > 0; qdCount--)
656 if (!_dnsPacket_checkQR(packet))
657 return 0;
658
659 return 1;
660}
661
662/** QUERY DEBUGGING
663 **/
664#if DEBUG
665static char*
666_dnsPacket_bprintQName(DnsPacket* packet, char* bp, char* bend)
667{
668 const uint8_t* p = packet->cursor;
669 const uint8_t* end = packet->end;
670 int first = 1;
671
672 for (;;) {
673 int c;
674
675 if (p >= end)
676 break;
677
678 c = *p++;
679
680 if (c == 0) {
681 packet->cursor = p;
682 return bp;
683 }
684
685 /* we don't expect label compression in QNAMEs */
686 if (c >= 64)
687 break;
688
689 if (first)
690 first = 0;
691 else
692 bp = _bprint_c(bp, bend, '.');
693
694 bp = _bprint_b(bp, bend, (const char*)p, c);
695
696 p += c;
697 /* we rely on the bound check at the start
698 * of the loop here */
699 }
700 /* malformed data */
701 bp = _bprint_s(bp, bend, "<MALFORMED>");
702 return bp;
703}
704
705static char*
706_dnsPacket_bprintQR(DnsPacket* packet, char* p, char* end)
707{
708#define QQ(x) { DNS_TYPE_##x, #x }
709 static const struct {
710 const char* typeBytes;
711 const char* typeString;
712 } qTypes[] =
713 {
714 QQ(A), QQ(PTR), QQ(MX), QQ(AAAA), QQ(ALL),
715 { NULL, NULL }
716 };
717 int nn;
718 const char* typeString = NULL;
719
720 /* dump QNAME */
721 p = _dnsPacket_bprintQName(packet, p, end);
722
723 /* dump TYPE */
724 p = _bprint_s(p, end, " (");
725
726 for (nn = 0; qTypes[nn].typeBytes != NULL; nn++) {
727 if (_dnsPacket_checkBytes(packet, 2, qTypes[nn].typeBytes)) {
728 typeString = qTypes[nn].typeString;
729 break;
730 }
731 }
732
733 if (typeString != NULL)
734 p = _bprint_s(p, end, typeString);
735 else {
736 int typeCode = _dnsPacket_readInt16(packet);
737 p = _bprint(p, end, "UNKNOWN-%d", typeCode);
738 }
739
740 p = _bprint_c(p, end, ')');
741
742 /* skip CLASS */
743 _dnsPacket_skip(packet, 2);
744 return p;
745}
746
747/* this function assumes the packet has already been checked */
748static char*
749_dnsPacket_bprintQuery( DnsPacket* packet, char* p, char* end )
750{
751 int qdCount;
752
753 if (packet->base[2] & 0x1) {
754 p = _bprint_s(p, end, "RECURSIVE ");
755 }
756
757 _dnsPacket_skip(packet, 4);
758 qdCount = _dnsPacket_readInt16(packet);
759 _dnsPacket_skip(packet, 6);
760
761 for ( ; qdCount > 0; qdCount-- ) {
762 p = _dnsPacket_bprintQR(packet, p, end);
763 }
764 return p;
765}
766#endif
767
768
769/** QUERY HASHING SUPPORT
770 **
771 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKET HAS ALREADY
772 ** BEEN SUCCESFULLY CHECKED.
773 **/
774
775/* use 32-bit FNV hash function */
776#define FNV_MULT 16777619U
777#define FNV_BASIS 2166136261U
778
779static unsigned
780_dnsPacket_hashBytes( DnsPacket* packet, int numBytes, unsigned hash )
781{
782 const uint8_t* p = packet->cursor;
783 const uint8_t* end = packet->end;
784
785 while (numBytes > 0 && p < end) {
786 hash = hash*FNV_MULT ^ *p++;
787 }
788 packet->cursor = p;
789 return hash;
790}
791
792
793static unsigned
794_dnsPacket_hashQName( DnsPacket* packet, unsigned hash )
795{
796 const uint8_t* p = packet->cursor;
797 const uint8_t* end = packet->end;
798
799 for (;;) {
800 int c;
801
802 if (p >= end) { /* should not happen */
803 XLOG("%s: INTERNAL_ERROR: read-overflow !!\n", __FUNCTION__);
804 break;
805 }
806
807 c = *p++;
808
809 if (c == 0)
810 break;
811
812 if (c >= 64) {
813 XLOG("%s: INTERNAL_ERROR: malformed domain !!\n", __FUNCTION__);
814 break;
815 }
816 if (p + c >= end) {
817 XLOG("%s: INTERNAL_ERROR: simple label read-overflow !!\n",
818 __FUNCTION__);
819 break;
820 }
821 while (c > 0) {
822 hash = hash*FNV_MULT ^ *p++;
823 c -= 1;
824 }
825 }
826 packet->cursor = p;
827 return hash;
828}
829
830static unsigned
831_dnsPacket_hashQR( DnsPacket* packet, unsigned hash )
832{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800833 hash = _dnsPacket_hashQName(packet, hash);
834 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TYPE and CLASS */
835 return hash;
836}
837
838static unsigned
839_dnsPacket_hashQuery( DnsPacket* packet )
840{
841 unsigned hash = FNV_BASIS;
842 int count;
843 _dnsPacket_rewind(packet);
844
845 /* we ignore the TC bit for reasons explained in
846 * _dnsPacket_checkQuery().
847 *
848 * however we hash the RD bit to differentiate
849 * between answers for recursive and non-recursive
850 * queries.
851 */
852 hash = hash*FNV_MULT ^ (packet->base[2] & 1);
853
854 /* assume: other flags are 0 */
855 _dnsPacket_skip(packet, 4);
856
857 /* read QDCOUNT */
858 count = _dnsPacket_readInt16(packet);
859
860 /* assume: ANcount, NScount, ARcount are 0 */
861 _dnsPacket_skip(packet, 6);
862
863 /* hash QDCOUNT QRs */
864 for ( ; count > 0; count-- )
865 hash = _dnsPacket_hashQR(packet, hash);
866
867 return hash;
868}
869
870
871/** QUERY COMPARISON
872 **
873 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKETS HAVE ALREADY
874 ** BEEN SUCCESFULLY CHECKED.
875 **/
876
877static int
878_dnsPacket_isEqualDomainName( DnsPacket* pack1, DnsPacket* pack2 )
879{
880 const uint8_t* p1 = pack1->cursor;
881 const uint8_t* end1 = pack1->end;
882 const uint8_t* p2 = pack2->cursor;
883 const uint8_t* end2 = pack2->end;
884
885 for (;;) {
886 int c1, c2;
887
888 if (p1 >= end1 || p2 >= end2) {
889 XLOG("%s: INTERNAL_ERROR: read-overflow !!\n", __FUNCTION__);
890 break;
891 }
892 c1 = *p1++;
893 c2 = *p2++;
894 if (c1 != c2)
895 break;
896
897 if (c1 == 0) {
898 pack1->cursor = p1;
899 pack2->cursor = p2;
900 return 1;
901 }
902 if (c1 >= 64) {
903 XLOG("%s: INTERNAL_ERROR: malformed domain !!\n", __FUNCTION__);
904 break;
905 }
906 if ((p1+c1 > end1) || (p2+c1 > end2)) {
907 XLOG("%s: INTERNAL_ERROR: simple label read-overflow !!\n",
908 __FUNCTION__);
909 break;
910 }
911 if (memcmp(p1, p2, c1) != 0)
912 break;
913 p1 += c1;
914 p2 += c1;
915 /* we rely on the bound checks at the start of the loop */
916 }
917 /* not the same, or one is malformed */
918 XLOG("different DN");
919 return 0;
920}
921
922static int
923_dnsPacket_isEqualBytes( DnsPacket* pack1, DnsPacket* pack2, int numBytes )
924{
925 const uint8_t* p1 = pack1->cursor;
926 const uint8_t* p2 = pack2->cursor;
927
928 if ( p1 + numBytes > pack1->end || p2 + numBytes > pack2->end )
929 return 0;
930
931 if ( memcmp(p1, p2, numBytes) != 0 )
932 return 0;
933
934 pack1->cursor += numBytes;
935 pack2->cursor += numBytes;
936 return 1;
937}
938
939static int
940_dnsPacket_isEqualQR( DnsPacket* pack1, DnsPacket* pack2 )
941{
942 /* compare domain name encoding + TYPE + CLASS */
943 if ( !_dnsPacket_isEqualDomainName(pack1, pack2) ||
944 !_dnsPacket_isEqualBytes(pack1, pack2, 2+2) )
945 return 0;
946
947 return 1;
948}
949
950static int
951_dnsPacket_isEqualQuery( DnsPacket* pack1, DnsPacket* pack2 )
952{
953 int count1, count2;
954
955 /* compare the headers, ignore most fields */
956 _dnsPacket_rewind(pack1);
957 _dnsPacket_rewind(pack2);
958
959 /* compare RD, ignore TC, see comment in _dnsPacket_checkQuery */
960 if ((pack1->base[2] & 1) != (pack2->base[2] & 1)) {
961 XLOG("different RD");
962 return 0;
963 }
964
965 /* assume: other flags are all 0 */
966 _dnsPacket_skip(pack1, 4);
967 _dnsPacket_skip(pack2, 4);
968
969 /* compare QDCOUNT */
970 count1 = _dnsPacket_readInt16(pack1);
971 count2 = _dnsPacket_readInt16(pack2);
972 if (count1 != count2 || count1 < 0) {
973 XLOG("different QDCOUNT");
974 return 0;
975 }
976
977 /* assume: ANcount, NScount and ARcount are all 0 */
978 _dnsPacket_skip(pack1, 6);
979 _dnsPacket_skip(pack2, 6);
980
981 /* compare the QDCOUNT QRs */
982 for ( ; count1 > 0; count1-- ) {
983 if (!_dnsPacket_isEqualQR(pack1, pack2)) {
984 XLOG("different QR");
985 return 0;
986 }
987 }
988 return 1;
989}
990
991/****************************************************************************/
992/****************************************************************************/
993/***** *****/
994/***** *****/
995/***** *****/
996/****************************************************************************/
997/****************************************************************************/
998
999/* cache entry. for simplicity, 'hash' and 'hlink' are inlined in this
1000 * structure though they are conceptually part of the hash table.
1001 *
1002 * similarly, mru_next and mru_prev are part of the global MRU list
1003 */
1004typedef struct Entry {
1005 unsigned int hash; /* hash value */
1006 struct Entry* hlink; /* next in collision chain */
1007 struct Entry* mru_prev;
1008 struct Entry* mru_next;
1009
1010 const uint8_t* query;
1011 int querylen;
1012 const uint8_t* answer;
1013 int answerlen;
Mattias Falk3e0c5102011-01-31 12:42:26 +01001014 time_t expires; /* time_t when the entry isn't valid any more */
1015 int id; /* for debugging purpose */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001016} Entry;
1017
Mattias Falk3e0c5102011-01-31 12:42:26 +01001018/**
Robert Greenwalt78851f12013-01-07 12:10:06 -08001019 * Find the TTL for a negative DNS result. This is defined as the minimum
1020 * of the SOA records TTL and the MINIMUM-TTL field (RFC-2308).
1021 *
1022 * Return 0 if not found.
1023 */
1024static u_long
1025answer_getNegativeTTL(ns_msg handle) {
1026 int n, nscount;
1027 u_long result = 0;
1028 ns_rr rr;
1029
1030 nscount = ns_msg_count(handle, ns_s_ns);
1031 for (n = 0; n < nscount; n++) {
1032 if ((ns_parserr(&handle, ns_s_ns, n, &rr) == 0) && (ns_rr_type(rr) == ns_t_soa)) {
1033 const u_char *rdata = ns_rr_rdata(rr); // find the data
1034 const u_char *edata = rdata + ns_rr_rdlen(rr); // add the len to find the end
1035 int len;
1036 u_long ttl, rec_result = ns_rr_ttl(rr);
1037
1038 // find the MINIMUM-TTL field from the blob of binary data for this record
1039 // skip the server name
1040 len = dn_skipname(rdata, edata);
1041 if (len == -1) continue; // error skipping
1042 rdata += len;
1043
1044 // skip the admin name
1045 len = dn_skipname(rdata, edata);
1046 if (len == -1) continue; // error skipping
1047 rdata += len;
1048
1049 if (edata - rdata != 5*NS_INT32SZ) continue;
1050 // skip: serial number + refresh interval + retry interval + expiry
1051 rdata += NS_INT32SZ * 4;
1052 // finally read the MINIMUM TTL
1053 ttl = ns_get32(rdata);
1054 if (ttl < rec_result) {
1055 rec_result = ttl;
1056 }
1057 // Now that the record is read successfully, apply the new min TTL
1058 if (n == 0 || rec_result < result) {
1059 result = rec_result;
1060 }
1061 }
1062 }
1063 return result;
1064}
1065
1066/**
1067 * Parse the answer records and find the appropriate
1068 * smallest TTL among the records. This might be from
1069 * the answer records if found or from the SOA record
1070 * if it's a negative result.
Mattias Falk3e0c5102011-01-31 12:42:26 +01001071 *
1072 * The returned TTL is the number of seconds to
1073 * keep the answer in the cache.
1074 *
1075 * In case of parse error zero (0) is returned which
1076 * indicates that the answer shall not be cached.
1077 */
1078static u_long
1079answer_getTTL(const void* answer, int answerlen)
1080{
1081 ns_msg handle;
1082 int ancount, n;
1083 u_long result, ttl;
1084 ns_rr rr;
1085
1086 result = 0;
1087 if (ns_initparse(answer, answerlen, &handle) >= 0) {
1088 // get number of answer records
1089 ancount = ns_msg_count(handle, ns_s_an);
Robert Greenwalt78851f12013-01-07 12:10:06 -08001090
1091 if (ancount == 0) {
1092 // a response with no answers? Cache this negative result.
1093 result = answer_getNegativeTTL(handle);
1094 } else {
1095 for (n = 0; n < ancount; n++) {
1096 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
1097 ttl = ns_rr_ttl(rr);
1098 if (n == 0 || ttl < result) {
1099 result = ttl;
1100 }
1101 } else {
1102 XLOG("ns_parserr failed ancount no = %d. errno = %s\n", n, strerror(errno));
Mattias Falk3e0c5102011-01-31 12:42:26 +01001103 }
Mattias Falk3e0c5102011-01-31 12:42:26 +01001104 }
1105 }
1106 } else {
1107 XLOG("ns_parserr failed. %s\n", strerror(errno));
1108 }
1109
1110 XLOG("TTL = %d\n", result);
1111
1112 return result;
1113}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001114
1115static void
1116entry_free( Entry* e )
1117{
1118 /* everything is allocated in a single memory block */
1119 if (e) {
1120 free(e);
1121 }
1122}
1123
1124static __inline__ void
1125entry_mru_remove( Entry* e )
1126{
1127 e->mru_prev->mru_next = e->mru_next;
1128 e->mru_next->mru_prev = e->mru_prev;
1129}
1130
1131static __inline__ void
1132entry_mru_add( Entry* e, Entry* list )
1133{
1134 Entry* first = list->mru_next;
1135
1136 e->mru_next = first;
1137 e->mru_prev = list;
1138
1139 list->mru_next = e;
1140 first->mru_prev = e;
1141}
1142
1143/* compute the hash of a given entry, this is a hash of most
1144 * data in the query (key) */
1145static unsigned
1146entry_hash( const Entry* e )
1147{
1148 DnsPacket pack[1];
1149
1150 _dnsPacket_init(pack, e->query, e->querylen);
1151 return _dnsPacket_hashQuery(pack);
1152}
1153
1154/* initialize an Entry as a search key, this also checks the input query packet
1155 * returns 1 on success, or 0 in case of unsupported/malformed data */
1156static int
1157entry_init_key( Entry* e, const void* query, int querylen )
1158{
1159 DnsPacket pack[1];
1160
1161 memset(e, 0, sizeof(*e));
1162
1163 e->query = query;
1164 e->querylen = querylen;
1165 e->hash = entry_hash(e);
1166
1167 _dnsPacket_init(pack, query, querylen);
1168
1169 return _dnsPacket_checkQuery(pack);
1170}
1171
1172/* allocate a new entry as a cache node */
1173static Entry*
1174entry_alloc( const Entry* init, const void* answer, int answerlen )
1175{
1176 Entry* e;
1177 int size;
1178
1179 size = sizeof(*e) + init->querylen + answerlen;
1180 e = calloc(size, 1);
1181 if (e == NULL)
1182 return e;
1183
1184 e->hash = init->hash;
1185 e->query = (const uint8_t*)(e+1);
1186 e->querylen = init->querylen;
1187
1188 memcpy( (char*)e->query, init->query, e->querylen );
1189
1190 e->answer = e->query + e->querylen;
1191 e->answerlen = answerlen;
1192
1193 memcpy( (char*)e->answer, answer, e->answerlen );
1194
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001195 return e;
1196}
1197
1198static int
1199entry_equals( const Entry* e1, const Entry* e2 )
1200{
1201 DnsPacket pack1[1], pack2[1];
1202
1203 if (e1->querylen != e2->querylen) {
1204 return 0;
1205 }
1206 _dnsPacket_init(pack1, e1->query, e1->querylen);
1207 _dnsPacket_init(pack2, e2->query, e2->querylen);
1208
1209 return _dnsPacket_isEqualQuery(pack1, pack2);
1210}
1211
1212/****************************************************************************/
1213/****************************************************************************/
1214/***** *****/
1215/***** *****/
1216/***** *****/
1217/****************************************************************************/
1218/****************************************************************************/
1219
1220/* We use a simple hash table with external collision lists
1221 * for simplicity, the hash-table fields 'hash' and 'hlink' are
1222 * inlined in the Entry structure.
1223 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001224
Mattias Falka59cfcf2011-09-06 15:15:06 +02001225/* Maximum time for a thread to wait for an pending request */
1226#define PENDING_REQUEST_TIMEOUT 20;
1227
1228typedef struct pending_req_info {
1229 unsigned int hash;
1230 pthread_cond_t cond;
1231 struct pending_req_info* next;
1232} PendingReqInfo;
1233
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001234typedef struct resolv_cache {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001235 int max_entries;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001236 int num_entries;
1237 Entry mru_list;
1238 pthread_mutex_t lock;
1239 unsigned generation;
1240 int last_id;
Mattias Falk3a4910c2011-02-14 12:41:11 +01001241 Entry* entries;
Mattias Falka59cfcf2011-09-06 15:15:06 +02001242 PendingReqInfo pending_requests;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001243} Cache;
1244
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001245typedef struct resolv_cache_info {
1246 char ifname[IF_NAMESIZE + 1];
1247 struct in_addr ifaddr;
1248 Cache* cache;
1249 struct resolv_cache_info* next;
1250 char* nameservers[MAXNS +1];
1251 struct addrinfo* nsaddrinfo[MAXNS + 1];
Robert Greenwaltb002a2f2013-01-19 00:40:24 +00001252 char* domains;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001253} CacheInfo;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001254
1255#define HTABLE_VALID(x) ((x) != NULL && (x) != HTABLE_DELETED)
1256
1257static void
Mattias Falka59cfcf2011-09-06 15:15:06 +02001258_cache_flush_pending_requests_locked( struct resolv_cache* cache )
1259{
1260 struct pending_req_info *ri, *tmp;
1261 if (cache) {
1262 ri = cache->pending_requests.next;
1263
1264 while (ri) {
1265 tmp = ri;
1266 ri = ri->next;
1267 pthread_cond_broadcast(&tmp->cond);
1268
1269 pthread_cond_destroy(&tmp->cond);
1270 free(tmp);
1271 }
1272
1273 cache->pending_requests.next = NULL;
1274 }
1275}
1276
1277/* return 0 if no pending request is found matching the key
1278 * if a matching request is found the calling thread will wait
1279 * and return 1 when released */
1280static int
1281_cache_check_pending_request_locked( struct resolv_cache* cache, Entry* key )
1282{
1283 struct pending_req_info *ri, *prev;
1284 int exist = 0;
1285
1286 if (cache && key) {
1287 ri = cache->pending_requests.next;
1288 prev = &cache->pending_requests;
1289 while (ri) {
1290 if (ri->hash == key->hash) {
1291 exist = 1;
1292 break;
1293 }
1294 prev = ri;
1295 ri = ri->next;
1296 }
1297
1298 if (!exist) {
1299 ri = calloc(1, sizeof(struct pending_req_info));
1300 if (ri) {
1301 ri->hash = key->hash;
1302 pthread_cond_init(&ri->cond, NULL);
1303 prev->next = ri;
1304 }
1305 } else {
1306 struct timespec ts = {0,0};
1307 ts.tv_sec = _time_now() + PENDING_REQUEST_TIMEOUT;
Robert Greenwalt78851f12013-01-07 12:10:06 -08001308 pthread_cond_timedwait(&ri->cond, &cache->lock, &ts);
Mattias Falka59cfcf2011-09-06 15:15:06 +02001309 }
1310 }
1311
1312 return exist;
1313}
1314
1315/* notify any waiting thread that waiting on a request
1316 * matching the key has been added to the cache */
1317static void
1318_cache_notify_waiting_tid_locked( struct resolv_cache* cache, Entry* key )
1319{
1320 struct pending_req_info *ri, *prev;
1321
1322 if (cache && key) {
1323 ri = cache->pending_requests.next;
1324 prev = &cache->pending_requests;
1325 while (ri) {
1326 if (ri->hash == key->hash) {
1327 pthread_cond_broadcast(&ri->cond);
1328 break;
1329 }
1330 prev = ri;
1331 ri = ri->next;
1332 }
1333
1334 // remove item from list and destroy
1335 if (ri) {
1336 prev->next = ri->next;
1337 pthread_cond_destroy(&ri->cond);
1338 free(ri);
1339 }
1340 }
1341}
1342
1343/* notify the cache that the query failed */
1344void
1345_resolv_cache_query_failed( struct resolv_cache* cache,
1346 const void* query,
1347 int querylen)
1348{
1349 Entry key[1];
1350
1351 if (cache && entry_init_key(key, query, querylen)) {
1352 pthread_mutex_lock(&cache->lock);
1353 _cache_notify_waiting_tid_locked(cache, key);
1354 pthread_mutex_unlock(&cache->lock);
1355 }
1356}
1357
1358static void
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001359_cache_flush_locked( Cache* cache )
1360{
1361 int nn;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001362
Mattias Falk3a4910c2011-02-14 12:41:11 +01001363 for (nn = 0; nn < cache->max_entries; nn++)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001364 {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001365 Entry** pnode = (Entry**) &cache->entries[nn];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001366
1367 while (*pnode != NULL) {
1368 Entry* node = *pnode;
1369 *pnode = node->hlink;
1370 entry_free(node);
1371 }
1372 }
1373
Mattias Falka59cfcf2011-09-06 15:15:06 +02001374 // flush pending request
1375 _cache_flush_pending_requests_locked(cache);
1376
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001377 cache->mru_list.mru_next = cache->mru_list.mru_prev = &cache->mru_list;
1378 cache->num_entries = 0;
1379 cache->last_id = 0;
1380
1381 XLOG("*************************\n"
1382 "*** DNS CACHE FLUSHED ***\n"
1383 "*************************");
1384}
1385
Mattias Falk3a4910c2011-02-14 12:41:11 +01001386/* Return max number of entries allowed in the cache,
1387 * i.e. cache size. The cache size is either defined
1388 * by system property ro.net.dns_cache_size or by
1389 * CONFIG_MAX_ENTRIES if system property not set
1390 * or set to invalid value. */
1391static int
1392_res_cache_get_max_entries( void )
1393{
1394 int result = -1;
1395 char cache_size[PROP_VALUE_MAX];
1396
Robert Greenwalt52764f52012-01-25 15:16:03 -08001397 const char* cache_mode = getenv("ANDROID_DNS_MODE");
1398
1399 if (cache_mode == NULL || strcmp(cache_mode, "local") != 0) {
1400 // Don't use the cache in local mode. This is used by the
1401 // proxy itself.
Robert Greenwaltb002a2f2013-01-19 00:40:24 +00001402 // TODO - change this to 0 when all dns stuff uses proxy (5918973)
1403 XLOG("setup cache for non-cache process. size=1");
1404 return 1;
Robert Greenwalt52764f52012-01-25 15:16:03 -08001405 }
1406
Mattias Falk3a4910c2011-02-14 12:41:11 +01001407 if (__system_property_get(DNS_CACHE_SIZE_PROP_NAME, cache_size) > 0) {
1408 result = atoi(cache_size);
1409 }
1410
1411 // ro.net.dns_cache_size not set or set to negative value
1412 if (result <= 0) {
1413 result = CONFIG_MAX_ENTRIES;
1414 }
1415
1416 XLOG("cache size: %d", result);
1417 return result;
1418}
1419
Jim Huang7cc56662010-10-15 02:02:57 +08001420static struct resolv_cache*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001421_resolv_cache_create( void )
1422{
1423 struct resolv_cache* cache;
1424
1425 cache = calloc(sizeof(*cache), 1);
1426 if (cache) {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001427 cache->max_entries = _res_cache_get_max_entries();
1428 cache->entries = calloc(sizeof(*cache->entries), cache->max_entries);
1429 if (cache->entries) {
1430 cache->generation = ~0U;
1431 pthread_mutex_init( &cache->lock, NULL );
1432 cache->mru_list.mru_prev = cache->mru_list.mru_next = &cache->mru_list;
1433 XLOG("%s: cache created\n", __FUNCTION__);
1434 } else {
1435 free(cache);
1436 cache = NULL;
1437 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001438 }
1439 return cache;
1440}
1441
1442
1443#if DEBUG
1444static void
1445_dump_query( const uint8_t* query, int querylen )
1446{
1447 char temp[256], *p=temp, *end=p+sizeof(temp);
1448 DnsPacket pack[1];
1449
1450 _dnsPacket_init(pack, query, querylen);
1451 p = _dnsPacket_bprintQuery(pack, p, end);
1452 XLOG("QUERY: %s", temp);
1453}
1454
1455static void
1456_cache_dump_mru( Cache* cache )
1457{
1458 char temp[512], *p=temp, *end=p+sizeof(temp);
1459 Entry* e;
1460
1461 p = _bprint(temp, end, "MRU LIST (%2d): ", cache->num_entries);
1462 for (e = cache->mru_list.mru_next; e != &cache->mru_list; e = e->mru_next)
1463 p = _bprint(p, end, " %d", e->id);
1464
1465 XLOG("%s", temp);
1466}
Mattias Falk3e0c5102011-01-31 12:42:26 +01001467
1468static void
1469_dump_answer(const void* answer, int answerlen)
1470{
1471 res_state statep;
1472 FILE* fp;
1473 char* buf;
1474 int fileLen;
1475
1476 fp = fopen("/data/reslog.txt", "w+");
1477 if (fp != NULL) {
1478 statep = __res_get_state();
1479
1480 res_pquery(statep, answer, answerlen, fp);
1481
1482 //Get file length
1483 fseek(fp, 0, SEEK_END);
1484 fileLen=ftell(fp);
1485 fseek(fp, 0, SEEK_SET);
1486 buf = (char *)malloc(fileLen+1);
1487 if (buf != NULL) {
1488 //Read file contents into buffer
1489 fread(buf, fileLen, 1, fp);
1490 XLOG("%s\n", buf);
1491 free(buf);
1492 }
1493 fclose(fp);
1494 remove("/data/reslog.txt");
1495 }
1496 else {
Robert Greenwalt78851f12013-01-07 12:10:06 -08001497 errno = 0; // else debug is introducing error signals
Mattias Falk3e0c5102011-01-31 12:42:26 +01001498 XLOG("_dump_answer: can't open file\n");
1499 }
1500}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001501#endif
1502
1503#if DEBUG
1504# define XLOG_QUERY(q,len) _dump_query((q), (len))
Mattias Falk3e0c5102011-01-31 12:42:26 +01001505# define XLOG_ANSWER(a, len) _dump_answer((a), (len))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001506#else
1507# define XLOG_QUERY(q,len) ((void)0)
Mattias Falk3e0c5102011-01-31 12:42:26 +01001508# define XLOG_ANSWER(a,len) ((void)0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001509#endif
1510
1511/* This function tries to find a key within the hash table
1512 * In case of success, it will return a *pointer* to the hashed key.
1513 * In case of failure, it will return a *pointer* to NULL
1514 *
1515 * So, the caller must check '*result' to check for success/failure.
1516 *
1517 * The main idea is that the result can later be used directly in
1518 * calls to _resolv_cache_add or _resolv_cache_remove as the 'lookup'
1519 * parameter. This makes the code simpler and avoids re-searching
1520 * for the key position in the htable.
1521 *
1522 * The result of a lookup_p is only valid until you alter the hash
1523 * table.
1524 */
1525static Entry**
1526_cache_lookup_p( Cache* cache,
1527 Entry* key )
1528{
Mattias Falk3a4910c2011-02-14 12:41:11 +01001529 int index = key->hash % cache->max_entries;
1530 Entry** pnode = (Entry**) &cache->entries[ index ];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001531
1532 while (*pnode != NULL) {
1533 Entry* node = *pnode;
1534
1535 if (node == NULL)
1536 break;
1537
1538 if (node->hash == key->hash && entry_equals(node, key))
1539 break;
1540
1541 pnode = &node->hlink;
1542 }
Robert Greenwaltb002a2f2013-01-19 00:40:24 +00001543 return pnode;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001544}
1545
1546/* Add a new entry to the hash table. 'lookup' must be the
1547 * result of an immediate previous failed _lookup_p() call
1548 * (i.e. with *lookup == NULL), and 'e' is the pointer to the
1549 * newly created entry
1550 */
1551static void
1552_cache_add_p( Cache* cache,
1553 Entry** lookup,
1554 Entry* e )
1555{
1556 *lookup = e;
1557 e->id = ++cache->last_id;
1558 entry_mru_add(e, &cache->mru_list);
1559 cache->num_entries += 1;
1560
1561 XLOG("%s: entry %d added (count=%d)", __FUNCTION__,
1562 e->id, cache->num_entries);
1563}
1564
1565/* Remove an existing entry from the hash table,
1566 * 'lookup' must be the result of an immediate previous
1567 * and succesful _lookup_p() call.
1568 */
1569static void
1570_cache_remove_p( Cache* cache,
1571 Entry** lookup )
1572{
1573 Entry* e = *lookup;
1574
1575 XLOG("%s: entry %d removed (count=%d)", __FUNCTION__,
1576 e->id, cache->num_entries-1);
1577
1578 entry_mru_remove(e);
1579 *lookup = e->hlink;
1580 entry_free(e);
1581 cache->num_entries -= 1;
1582}
1583
1584/* Remove the oldest entry from the hash table.
1585 */
1586static void
1587_cache_remove_oldest( Cache* cache )
1588{
1589 Entry* oldest = cache->mru_list.mru_prev;
1590 Entry** lookup = _cache_lookup_p(cache, oldest);
1591
1592 if (*lookup == NULL) { /* should not happen */
1593 XLOG("%s: OLDEST NOT IN HTABLE ?", __FUNCTION__);
1594 return;
1595 }
Robert Greenwalt7f84da62011-09-02 07:44:36 -07001596 if (DEBUG) {
1597 XLOG("Cache full - removing oldest");
1598 XLOG_QUERY(oldest->query, oldest->querylen);
1599 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001600 _cache_remove_p(cache, lookup);
1601}
1602
Anders Fredlunddd161822011-05-20 08:12:37 +02001603/* Remove all expired entries from the hash table.
1604 */
1605static void _cache_remove_expired(Cache* cache) {
1606 Entry* e;
1607 time_t now = _time_now();
1608
1609 for (e = cache->mru_list.mru_next; e != &cache->mru_list;) {
1610 // Entry is old, remove
1611 if (now >= e->expires) {
1612 Entry** lookup = _cache_lookup_p(cache, e);
1613 if (*lookup == NULL) { /* should not happen */
1614 XLOG("%s: ENTRY NOT IN HTABLE ?", __FUNCTION__);
1615 return;
1616 }
1617 e = e->mru_next;
1618 _cache_remove_p(cache, lookup);
1619 } else {
1620 e = e->mru_next;
1621 }
1622 }
1623}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001624
1625ResolvCacheStatus
1626_resolv_cache_lookup( struct resolv_cache* cache,
1627 const void* query,
1628 int querylen,
1629 void* answer,
1630 int answersize,
1631 int *answerlen )
1632{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001633 Entry key[1];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001634 Entry** lookup;
1635 Entry* e;
1636 time_t now;
1637
1638 ResolvCacheStatus result = RESOLV_CACHE_NOTFOUND;
1639
1640 XLOG("%s: lookup", __FUNCTION__);
1641 XLOG_QUERY(query, querylen);
1642
1643 /* we don't cache malformed queries */
1644 if (!entry_init_key(key, query, querylen)) {
1645 XLOG("%s: unsupported query", __FUNCTION__);
1646 return RESOLV_CACHE_UNSUPPORTED;
1647 }
1648 /* lookup cache */
1649 pthread_mutex_lock( &cache->lock );
1650
1651 /* see the description of _lookup_p to understand this.
1652 * the function always return a non-NULL pointer.
1653 */
1654 lookup = _cache_lookup_p(cache, key);
1655 e = *lookup;
1656
1657 if (e == NULL) {
1658 XLOG( "NOT IN CACHE");
Mattias Falka59cfcf2011-09-06 15:15:06 +02001659 // calling thread will wait if an outstanding request is found
1660 // that matching this query
1661 if (!_cache_check_pending_request_locked(cache, key)) {
1662 goto Exit;
1663 } else {
1664 lookup = _cache_lookup_p(cache, key);
1665 e = *lookup;
1666 if (e == NULL) {
1667 goto Exit;
1668 }
1669 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001670 }
1671
1672 now = _time_now();
1673
1674 /* remove stale entries here */
Mattias Falk3e0c5102011-01-31 12:42:26 +01001675 if (now >= e->expires) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001676 XLOG( " NOT IN CACHE (STALE ENTRY %p DISCARDED)", *lookup );
Robert Greenwalt7f84da62011-09-02 07:44:36 -07001677 XLOG_QUERY(e->query, e->querylen);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001678 _cache_remove_p(cache, lookup);
1679 goto Exit;
1680 }
1681
1682 *answerlen = e->answerlen;
1683 if (e->answerlen > answersize) {
1684 /* NOTE: we return UNSUPPORTED if the answer buffer is too short */
1685 result = RESOLV_CACHE_UNSUPPORTED;
1686 XLOG(" ANSWER TOO LONG");
1687 goto Exit;
1688 }
1689
1690 memcpy( answer, e->answer, e->answerlen );
1691
1692 /* bump up this entry to the top of the MRU list */
1693 if (e != cache->mru_list.mru_next) {
1694 entry_mru_remove( e );
1695 entry_mru_add( e, &cache->mru_list );
1696 }
1697
1698 XLOG( "FOUND IN CACHE entry=%p", e );
1699 result = RESOLV_CACHE_FOUND;
1700
1701Exit:
1702 pthread_mutex_unlock( &cache->lock );
1703 return result;
1704}
1705
1706
1707void
1708_resolv_cache_add( struct resolv_cache* cache,
1709 const void* query,
1710 int querylen,
1711 const void* answer,
1712 int answerlen )
1713{
1714 Entry key[1];
1715 Entry* e;
1716 Entry** lookup;
Mattias Falk3e0c5102011-01-31 12:42:26 +01001717 u_long ttl;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001718
1719 /* don't assume that the query has already been cached
1720 */
1721 if (!entry_init_key( key, query, querylen )) {
1722 XLOG( "%s: passed invalid query ?", __FUNCTION__);
1723 return;
1724 }
1725
1726 pthread_mutex_lock( &cache->lock );
1727
1728 XLOG( "%s: query:", __FUNCTION__ );
1729 XLOG_QUERY(query,querylen);
Mattias Falk3e0c5102011-01-31 12:42:26 +01001730 XLOG_ANSWER(answer, answerlen);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001731#if DEBUG_DATA
1732 XLOG( "answer:");
1733 XLOG_BYTES(answer,answerlen);
1734#endif
1735
1736 lookup = _cache_lookup_p(cache, key);
1737 e = *lookup;
1738
1739 if (e != NULL) { /* should not happen */
1740 XLOG("%s: ALREADY IN CACHE (%p) ? IGNORING ADD",
1741 __FUNCTION__, e);
1742 goto Exit;
1743 }
1744
Mattias Falk3a4910c2011-02-14 12:41:11 +01001745 if (cache->num_entries >= cache->max_entries) {
Anders Fredlunddd161822011-05-20 08:12:37 +02001746 _cache_remove_expired(cache);
1747 if (cache->num_entries >= cache->max_entries) {
1748 _cache_remove_oldest(cache);
1749 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001750 /* need to lookup again */
1751 lookup = _cache_lookup_p(cache, key);
1752 e = *lookup;
1753 if (e != NULL) {
1754 XLOG("%s: ALREADY IN CACHE (%p) ? IGNORING ADD",
1755 __FUNCTION__, e);
1756 goto Exit;
1757 }
1758 }
1759
Mattias Falk3e0c5102011-01-31 12:42:26 +01001760 ttl = answer_getTTL(answer, answerlen);
1761 if (ttl > 0) {
1762 e = entry_alloc(key, answer, answerlen);
1763 if (e != NULL) {
1764 e->expires = ttl + _time_now();
1765 _cache_add_p(cache, lookup, e);
1766 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001767 }
1768#if DEBUG
1769 _cache_dump_mru(cache);
1770#endif
1771Exit:
Mattias Falka59cfcf2011-09-06 15:15:06 +02001772 _cache_notify_waiting_tid_locked(cache, key);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001773 pthread_mutex_unlock( &cache->lock );
1774}
1775
1776/****************************************************************************/
1777/****************************************************************************/
1778/***** *****/
1779/***** *****/
1780/***** *****/
1781/****************************************************************************/
1782/****************************************************************************/
1783
Robert Greenwaltb002a2f2013-01-19 00:40:24 +00001784static pthread_once_t _res_cache_once;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001785
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001786// Head of the list of caches. Protected by _res_cache_list_lock.
1787static struct resolv_cache_info _res_cache_list;
1788
1789// name of the current default inteface
1790static char _res_default_ifname[IF_NAMESIZE + 1];
1791
1792// lock protecting everything in the _resolve_cache_info structs (next ptr, etc)
1793static pthread_mutex_t _res_cache_list_lock;
1794
1795
1796/* lookup the default interface name */
1797static char *_get_default_iface_locked();
1798/* insert resolv_cache_info into the list of resolv_cache_infos */
1799static void _insert_cache_info_locked(struct resolv_cache_info* cache_info);
1800/* creates a resolv_cache_info */
1801static struct resolv_cache_info* _create_cache_info( void );
1802/* gets cache associated with an interface name, or NULL if none exists */
1803static struct resolv_cache* _find_named_cache_locked(const char* ifname);
1804/* gets a resolv_cache_info associated with an interface name, or NULL if not found */
1805static struct resolv_cache_info* _find_cache_info_locked(const char* ifname);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001806/* look up the named cache, and creates one if needed */
1807static struct resolv_cache* _get_res_cache_for_iface_locked(const char* ifname);
1808/* empty the named cache */
1809static void _flush_cache_for_iface_locked(const char* ifname);
1810/* empty the nameservers set for the named cache */
1811static void _free_nameservers_locked(struct resolv_cache_info* cache_info);
1812/* lookup the namserver for the name interface */
1813static int _get_nameserver_locked(const char* ifname, int n, char* addr, int addrLen);
1814/* lookup the addr of the nameserver for the named interface */
1815static struct addrinfo* _get_nameserver_addr_locked(const char* ifname, int n);
1816/* lookup the inteface's address */
1817static struct in_addr* _get_addr_locked(const char * ifname);
Robert Greenwaltb002a2f2013-01-19 00:40:24 +00001818
1819
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001820
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001821static void
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001822_res_cache_init(void)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001823{
1824 const char* env = getenv(CONFIG_ENV);
1825
1826 if (env && atoi(env) == 0) {
1827 /* the cache is disabled */
1828 return;
1829 }
1830
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001831 memset(&_res_default_ifname, 0, sizeof(_res_default_ifname));
1832 memset(&_res_cache_list, 0, sizeof(_res_cache_list));
1833 pthread_mutex_init(&_res_cache_list_lock, NULL);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001834}
1835
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001836struct resolv_cache*
Robert Greenwaltb002a2f2013-01-19 00:40:24 +00001837__get_res_cache(void)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001838{
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001839 struct resolv_cache *cache;
1840
1841 pthread_once(&_res_cache_once, _res_cache_init);
Robert Greenwaltb002a2f2013-01-19 00:40:24 +00001842
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001843 pthread_mutex_lock(&_res_cache_list_lock);
1844
Robert Greenwaltb002a2f2013-01-19 00:40:24 +00001845 char* ifname = _get_default_iface_locked();
Mattias Falkf1464ff2011-08-23 14:34:14 +02001846
Robert Greenwaltb002a2f2013-01-19 00:40:24 +00001847 // if default interface not set then use the first cache
1848 // associated with an interface as the default one.
1849 if (ifname[0] == '\0') {
1850 struct resolv_cache_info* cache_info = _res_cache_list.next;
1851 while (cache_info) {
1852 if (cache_info->ifname[0] != '\0') {
1853 ifname = cache_info->ifname;
1854 break;
1855 }
1856
1857 cache_info = cache_info->next;
1858 }
1859 }
1860 cache = _get_res_cache_for_iface_locked(ifname);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001861
1862 pthread_mutex_unlock(&_res_cache_list_lock);
Robert Greenwaltb002a2f2013-01-19 00:40:24 +00001863 XLOG("_get_res_cache. default_ifname = %s\n", ifname);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001864 return cache;
1865}
1866
1867static struct resolv_cache*
1868_get_res_cache_for_iface_locked(const char* ifname)
1869{
1870 if (ifname == NULL)
1871 return NULL;
1872
1873 struct resolv_cache* cache = _find_named_cache_locked(ifname);
1874 if (!cache) {
1875 struct resolv_cache_info* cache_info = _create_cache_info();
1876 if (cache_info) {
1877 cache = _resolv_cache_create();
1878 if (cache) {
1879 int len = sizeof(cache_info->ifname);
1880 cache_info->cache = cache;
1881 strncpy(cache_info->ifname, ifname, len - 1);
1882 cache_info->ifname[len - 1] = '\0';
1883
1884 _insert_cache_info_locked(cache_info);
1885 } else {
1886 free(cache_info);
1887 }
1888 }
1889 }
1890 return cache;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001891}
1892
1893void
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001894_resolv_cache_reset(unsigned generation)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001895{
1896 XLOG("%s: generation=%d", __FUNCTION__, generation);
1897
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001898 pthread_once(&_res_cache_once, _res_cache_init);
1899 pthread_mutex_lock(&_res_cache_list_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001900
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001901 char* ifname = _get_default_iface_locked();
1902 // if default interface not set then use the first cache
1903 // associated with an interface as the default one.
1904 // Note: Copied the code from __get_res_cache since this
1905 // method will be deleted/obsolete when cache per interface
1906 // implemented all over
1907 if (ifname[0] == '\0') {
1908 struct resolv_cache_info* cache_info = _res_cache_list.next;
1909 while (cache_info) {
1910 if (cache_info->ifname[0] != '\0') {
1911 ifname = cache_info->ifname;
Robert Greenwalt9363d912011-07-25 12:30:17 -07001912 break;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001913 }
1914
1915 cache_info = cache_info->next;
1916 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001917 }
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001918 struct resolv_cache* cache = _get_res_cache_for_iface_locked(ifname);
1919
Robert Greenwalt9363d912011-07-25 12:30:17 -07001920 if (cache != NULL) {
1921 pthread_mutex_lock( &cache->lock );
1922 if (cache->generation != generation) {
1923 _cache_flush_locked(cache);
1924 cache->generation = generation;
1925 }
1926 pthread_mutex_unlock( &cache->lock );
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001927 }
1928
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001929 pthread_mutex_unlock(&_res_cache_list_lock);
1930}
1931
1932void
1933_resolv_flush_cache_for_default_iface(void)
1934{
1935 char* ifname;
1936
1937 pthread_once(&_res_cache_once, _res_cache_init);
1938 pthread_mutex_lock(&_res_cache_list_lock);
1939
1940 ifname = _get_default_iface_locked();
1941 _flush_cache_for_iface_locked(ifname);
1942
1943 pthread_mutex_unlock(&_res_cache_list_lock);
1944}
1945
1946void
1947_resolv_flush_cache_for_iface(const char* ifname)
1948{
1949 pthread_once(&_res_cache_once, _res_cache_init);
1950 pthread_mutex_lock(&_res_cache_list_lock);
1951
1952 _flush_cache_for_iface_locked(ifname);
1953
1954 pthread_mutex_unlock(&_res_cache_list_lock);
1955}
1956
1957static void
1958_flush_cache_for_iface_locked(const char* ifname)
1959{
1960 struct resolv_cache* cache = _find_named_cache_locked(ifname);
1961 if (cache) {
1962 pthread_mutex_lock(&cache->lock);
1963 _cache_flush_locked(cache);
1964 pthread_mutex_unlock(&cache->lock);
1965 }
1966}
1967
1968static struct resolv_cache_info*
1969_create_cache_info(void)
1970{
1971 struct resolv_cache_info* cache_info;
1972
1973 cache_info = calloc(sizeof(*cache_info), 1);
1974 return cache_info;
1975}
1976
1977static void
1978_insert_cache_info_locked(struct resolv_cache_info* cache_info)
1979{
1980 struct resolv_cache_info* last;
1981
1982 for (last = &_res_cache_list; last->next; last = last->next);
1983
1984 last->next = cache_info;
1985
1986}
1987
1988static struct resolv_cache*
1989_find_named_cache_locked(const char* ifname) {
1990
1991 struct resolv_cache_info* info = _find_cache_info_locked(ifname);
1992
1993 if (info != NULL) return info->cache;
1994
1995 return NULL;
1996}
1997
1998static struct resolv_cache_info*
1999_find_cache_info_locked(const char* ifname)
2000{
2001 if (ifname == NULL)
2002 return NULL;
2003
2004 struct resolv_cache_info* cache_info = _res_cache_list.next;
2005
2006 while (cache_info) {
2007 if (strcmp(cache_info->ifname, ifname) == 0) {
2008 break;
2009 }
2010
2011 cache_info = cache_info->next;
2012 }
2013 return cache_info;
2014}
2015
2016static char*
2017_get_default_iface_locked(void)
2018{
2019 char* iface = _res_default_ifname;
2020
2021 return iface;
2022}
2023
2024void
2025_resolv_set_default_iface(const char* ifname)
2026{
2027 XLOG("_resolv_set_default_if ifname %s\n",ifname);
2028
2029 pthread_once(&_res_cache_once, _res_cache_init);
2030 pthread_mutex_lock(&_res_cache_list_lock);
2031
2032 int size = sizeof(_res_default_ifname);
2033 memset(_res_default_ifname, 0, size);
2034 strncpy(_res_default_ifname, ifname, size - 1);
2035 _res_default_ifname[size - 1] = '\0';
2036
2037 pthread_mutex_unlock(&_res_cache_list_lock);
2038}
2039
2040void
Robert Greenwalt6f3222e2012-11-13 11:50:57 -08002041_resolv_set_nameservers_for_iface(const char* ifname, char** servers, int numservers,
2042 const char *domains)
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002043{
2044 int i, rt, index;
2045 struct addrinfo hints;
2046 char sbuf[NI_MAXSERV];
2047
2048 pthread_once(&_res_cache_once, _res_cache_init);
Mattias Falkf1464ff2011-08-23 14:34:14 +02002049
Robert Greenwaltb002a2f2013-01-19 00:40:24 +00002050 pthread_mutex_lock(&_res_cache_list_lock);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002051 // creates the cache if not created
2052 _get_res_cache_for_iface_locked(ifname);
2053
2054 struct resolv_cache_info* cache_info = _find_cache_info_locked(ifname);
2055
Robert Greenwaltb002a2f2013-01-19 00:40:24 +00002056 if (cache_info != NULL) {
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002057 // free current before adding new
2058 _free_nameservers_locked(cache_info);
2059
2060 memset(&hints, 0, sizeof(hints));
2061 hints.ai_family = PF_UNSPEC;
2062 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
2063 hints.ai_flags = AI_NUMERICHOST;
2064 sprintf(sbuf, "%u", NAMESERVER_PORT);
2065
2066 index = 0;
2067 for (i = 0; i < numservers && i < MAXNS; i++) {
2068 rt = getaddrinfo(servers[i], sbuf, &hints, &cache_info->nsaddrinfo[index]);
2069 if (rt == 0) {
2070 cache_info->nameservers[index] = strdup(servers[i]);
2071 index++;
2072 } else {
2073 cache_info->nsaddrinfo[index] = NULL;
2074 }
2075 }
Robert Greenwaltb002a2f2013-01-19 00:40:24 +00002076 cache_info->domains = strdup(domains);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002077 }
2078 pthread_mutex_unlock(&_res_cache_list_lock);
2079}
2080
2081static void
2082_free_nameservers_locked(struct resolv_cache_info* cache_info)
2083{
2084 int i;
2085 for (i = 0; i <= MAXNS; i++) {
2086 free(cache_info->nameservers[i]);
2087 cache_info->nameservers[i] = NULL;
Robert Greenwalt9363d912011-07-25 12:30:17 -07002088 if (cache_info->nsaddrinfo[i] != NULL) {
2089 freeaddrinfo(cache_info->nsaddrinfo[i]);
2090 cache_info->nsaddrinfo[i] = NULL;
2091 }
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002092 }
2093}
2094
2095int
2096_resolv_cache_get_nameserver(int n, char* addr, int addrLen)
2097{
2098 char *ifname;
2099 int result = 0;
2100
2101 pthread_once(&_res_cache_once, _res_cache_init);
2102 pthread_mutex_lock(&_res_cache_list_lock);
2103
2104 ifname = _get_default_iface_locked();
2105 result = _get_nameserver_locked(ifname, n, addr, addrLen);
2106
2107 pthread_mutex_unlock(&_res_cache_list_lock);
2108 return result;
2109}
2110
2111static int
2112_get_nameserver_locked(const char* ifname, int n, char* addr, int addrLen)
2113{
2114 int len = 0;
2115 char* ns;
2116 struct resolv_cache_info* cache_info;
2117
2118 if (n < 1 || n > MAXNS || !addr)
2119 return 0;
2120
2121 cache_info = _find_cache_info_locked(ifname);
2122 if (cache_info) {
2123 ns = cache_info->nameservers[n - 1];
2124 if (ns) {
2125 len = strlen(ns);
2126 if (len < addrLen) {
2127 strncpy(addr, ns, len);
2128 addr[len] = '\0';
2129 } else {
2130 len = 0;
2131 }
2132 }
2133 }
2134
2135 return len;
2136}
2137
2138struct addrinfo*
2139_cache_get_nameserver_addr(int n)
2140{
2141 struct addrinfo *result;
2142 char* ifname;
2143
2144 pthread_once(&_res_cache_once, _res_cache_init);
2145 pthread_mutex_lock(&_res_cache_list_lock);
2146
2147 ifname = _get_default_iface_locked();
2148
2149 result = _get_nameserver_addr_locked(ifname, n);
2150 pthread_mutex_unlock(&_res_cache_list_lock);
2151 return result;
2152}
2153
2154static struct addrinfo*
2155_get_nameserver_addr_locked(const char* ifname, int n)
2156{
2157 struct addrinfo* ai = NULL;
2158 struct resolv_cache_info* cache_info;
2159
2160 if (n < 1 || n > MAXNS)
2161 return NULL;
2162
2163 cache_info = _find_cache_info_locked(ifname);
2164 if (cache_info) {
2165 ai = cache_info->nsaddrinfo[n - 1];
2166 }
2167 return ai;
2168}
2169
2170void
2171_resolv_set_addr_of_iface(const char* ifname, struct in_addr* addr)
2172{
2173 pthread_once(&_res_cache_once, _res_cache_init);
2174 pthread_mutex_lock(&_res_cache_list_lock);
2175 struct resolv_cache_info* cache_info = _find_cache_info_locked(ifname);
2176 if (cache_info) {
2177 memcpy(&cache_info->ifaddr, addr, sizeof(*addr));
2178
2179 if (DEBUG) {
2180 char* addr_s = inet_ntoa(cache_info->ifaddr);
2181 XLOG("address of interface %s is %s\n", ifname, addr_s);
2182 }
2183 }
2184 pthread_mutex_unlock(&_res_cache_list_lock);
2185}
2186
2187struct in_addr*
2188_resolv_get_addr_of_default_iface(void)
2189{
2190 struct in_addr* ai = NULL;
2191 char* ifname;
2192
2193 pthread_once(&_res_cache_once, _res_cache_init);
2194 pthread_mutex_lock(&_res_cache_list_lock);
2195 ifname = _get_default_iface_locked();
2196 ai = _get_addr_locked(ifname);
2197 pthread_mutex_unlock(&_res_cache_list_lock);
2198
2199 return ai;
2200}
2201
2202struct in_addr*
2203_resolv_get_addr_of_iface(const char* ifname)
2204{
2205 struct in_addr* ai = NULL;
2206
2207 pthread_once(&_res_cache_once, _res_cache_init);
2208 pthread_mutex_lock(&_res_cache_list_lock);
2209 ai =_get_addr_locked(ifname);
2210 pthread_mutex_unlock(&_res_cache_list_lock);
2211 return ai;
2212}
2213
2214static struct in_addr*
2215_get_addr_locked(const char * ifname)
2216{
2217 struct resolv_cache_info* cache_info = _find_cache_info_locked(ifname);
2218 if (cache_info) {
2219 return &cache_info->ifaddr;
2220 }
2221 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002222}