blob: 915fdf0568cd62cc2d8dd27f1af309ba0bbe5f94 [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{
575 int len;
576
577 if (!_dnsPacket_checkQName(packet))
578 return 0;
579
580 /* TYPE must be one of the things we support */
581 if (!_dnsPacket_checkBytes(packet, 2, DNS_TYPE_A) &&
582 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_PTR) &&
583 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_MX) &&
584 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_AAAA) &&
585 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_ALL))
586 {
587 XLOG("unsupported TYPE");
588 return 0;
589 }
590 /* CLASS must be IN */
591 if (!_dnsPacket_checkBytes(packet, 2, DNS_CLASS_IN)) {
592 XLOG("unsupported CLASS");
593 return 0;
594 }
595
596 return 1;
597}
598
599/* check the header of a DNS Query packet, return 1 if it is one
600 * type of query we can cache, or 0 otherwise
601 */
602static int
603_dnsPacket_checkQuery( DnsPacket* packet )
604{
605 const uint8_t* p = packet->base;
606 int qdCount, anCount, dnCount, arCount;
607
608 if (p + DNS_HEADER_SIZE > packet->end) {
609 XLOG("query packet too small");
610 return 0;
611 }
612
613 /* QR must be set to 0, opcode must be 0 and AA must be 0 */
614 /* RA, Z, and RCODE must be 0 */
615 if ((p[2] & 0xFC) != 0 || p[3] != 0) {
616 XLOG("query packet flags unsupported");
617 return 0;
618 }
619
620 /* Note that we ignore the TC and RD bits here for the
621 * following reasons:
622 *
623 * - there is no point for a query packet sent to a server
624 * to have the TC bit set, but the implementation might
625 * set the bit in the query buffer for its own needs
626 * between a _resolv_cache_lookup and a
627 * _resolv_cache_add. We should not freak out if this
628 * is the case.
629 *
630 * - we consider that the result from a RD=0 or a RD=1
631 * query might be different, hence that the RD bit
632 * should be used to differentiate cached result.
633 *
634 * this implies that RD is checked when hashing or
635 * comparing query packets, but not TC
636 */
637
638 /* ANCOUNT, DNCOUNT and ARCOUNT must be 0 */
639 qdCount = (p[4] << 8) | p[5];
640 anCount = (p[6] << 8) | p[7];
641 dnCount = (p[8] << 8) | p[9];
642 arCount = (p[10]<< 8) | p[11];
643
644 if (anCount != 0 || dnCount != 0 || arCount != 0) {
645 XLOG("query packet contains non-query records");
646 return 0;
647 }
648
649 if (qdCount == 0) {
650 XLOG("query packet doesn't contain query record");
651 return 0;
652 }
653
654 /* Check QDCOUNT QRs */
655 packet->cursor = p + DNS_HEADER_SIZE;
656
657 for (;qdCount > 0; qdCount--)
658 if (!_dnsPacket_checkQR(packet))
659 return 0;
660
661 return 1;
662}
663
664/** QUERY DEBUGGING
665 **/
666#if DEBUG
667static char*
668_dnsPacket_bprintQName(DnsPacket* packet, char* bp, char* bend)
669{
670 const uint8_t* p = packet->cursor;
671 const uint8_t* end = packet->end;
672 int first = 1;
673
674 for (;;) {
675 int c;
676
677 if (p >= end)
678 break;
679
680 c = *p++;
681
682 if (c == 0) {
683 packet->cursor = p;
684 return bp;
685 }
686
687 /* we don't expect label compression in QNAMEs */
688 if (c >= 64)
689 break;
690
691 if (first)
692 first = 0;
693 else
694 bp = _bprint_c(bp, bend, '.');
695
696 bp = _bprint_b(bp, bend, (const char*)p, c);
697
698 p += c;
699 /* we rely on the bound check at the start
700 * of the loop here */
701 }
702 /* malformed data */
703 bp = _bprint_s(bp, bend, "<MALFORMED>");
704 return bp;
705}
706
707static char*
708_dnsPacket_bprintQR(DnsPacket* packet, char* p, char* end)
709{
710#define QQ(x) { DNS_TYPE_##x, #x }
711 static const struct {
712 const char* typeBytes;
713 const char* typeString;
714 } qTypes[] =
715 {
716 QQ(A), QQ(PTR), QQ(MX), QQ(AAAA), QQ(ALL),
717 { NULL, NULL }
718 };
719 int nn;
720 const char* typeString = NULL;
721
722 /* dump QNAME */
723 p = _dnsPacket_bprintQName(packet, p, end);
724
725 /* dump TYPE */
726 p = _bprint_s(p, end, " (");
727
728 for (nn = 0; qTypes[nn].typeBytes != NULL; nn++) {
729 if (_dnsPacket_checkBytes(packet, 2, qTypes[nn].typeBytes)) {
730 typeString = qTypes[nn].typeString;
731 break;
732 }
733 }
734
735 if (typeString != NULL)
736 p = _bprint_s(p, end, typeString);
737 else {
738 int typeCode = _dnsPacket_readInt16(packet);
739 p = _bprint(p, end, "UNKNOWN-%d", typeCode);
740 }
741
742 p = _bprint_c(p, end, ')');
743
744 /* skip CLASS */
745 _dnsPacket_skip(packet, 2);
746 return p;
747}
748
749/* this function assumes the packet has already been checked */
750static char*
751_dnsPacket_bprintQuery( DnsPacket* packet, char* p, char* end )
752{
753 int qdCount;
754
755 if (packet->base[2] & 0x1) {
756 p = _bprint_s(p, end, "RECURSIVE ");
757 }
758
759 _dnsPacket_skip(packet, 4);
760 qdCount = _dnsPacket_readInt16(packet);
761 _dnsPacket_skip(packet, 6);
762
763 for ( ; qdCount > 0; qdCount-- ) {
764 p = _dnsPacket_bprintQR(packet, p, end);
765 }
766 return p;
767}
768#endif
769
770
771/** QUERY HASHING SUPPORT
772 **
773 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKET HAS ALREADY
774 ** BEEN SUCCESFULLY CHECKED.
775 **/
776
777/* use 32-bit FNV hash function */
778#define FNV_MULT 16777619U
779#define FNV_BASIS 2166136261U
780
781static unsigned
782_dnsPacket_hashBytes( DnsPacket* packet, int numBytes, unsigned hash )
783{
784 const uint8_t* p = packet->cursor;
785 const uint8_t* end = packet->end;
786
787 while (numBytes > 0 && p < end) {
788 hash = hash*FNV_MULT ^ *p++;
789 }
790 packet->cursor = p;
791 return hash;
792}
793
794
795static unsigned
796_dnsPacket_hashQName( DnsPacket* packet, unsigned hash )
797{
798 const uint8_t* p = packet->cursor;
799 const uint8_t* end = packet->end;
800
801 for (;;) {
802 int c;
803
804 if (p >= end) { /* should not happen */
805 XLOG("%s: INTERNAL_ERROR: read-overflow !!\n", __FUNCTION__);
806 break;
807 }
808
809 c = *p++;
810
811 if (c == 0)
812 break;
813
814 if (c >= 64) {
815 XLOG("%s: INTERNAL_ERROR: malformed domain !!\n", __FUNCTION__);
816 break;
817 }
818 if (p + c >= end) {
819 XLOG("%s: INTERNAL_ERROR: simple label read-overflow !!\n",
820 __FUNCTION__);
821 break;
822 }
823 while (c > 0) {
824 hash = hash*FNV_MULT ^ *p++;
825 c -= 1;
826 }
827 }
828 packet->cursor = p;
829 return hash;
830}
831
832static unsigned
833_dnsPacket_hashQR( DnsPacket* packet, unsigned hash )
834{
835 int len;
836
837 hash = _dnsPacket_hashQName(packet, hash);
838 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TYPE and CLASS */
839 return hash;
840}
841
842static unsigned
843_dnsPacket_hashQuery( DnsPacket* packet )
844{
845 unsigned hash = FNV_BASIS;
846 int count;
847 _dnsPacket_rewind(packet);
848
849 /* we ignore the TC bit for reasons explained in
850 * _dnsPacket_checkQuery().
851 *
852 * however we hash the RD bit to differentiate
853 * between answers for recursive and non-recursive
854 * queries.
855 */
856 hash = hash*FNV_MULT ^ (packet->base[2] & 1);
857
858 /* assume: other flags are 0 */
859 _dnsPacket_skip(packet, 4);
860
861 /* read QDCOUNT */
862 count = _dnsPacket_readInt16(packet);
863
864 /* assume: ANcount, NScount, ARcount are 0 */
865 _dnsPacket_skip(packet, 6);
866
867 /* hash QDCOUNT QRs */
868 for ( ; count > 0; count-- )
869 hash = _dnsPacket_hashQR(packet, hash);
870
871 return hash;
872}
873
874
875/** QUERY COMPARISON
876 **
877 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKETS HAVE ALREADY
878 ** BEEN SUCCESFULLY CHECKED.
879 **/
880
881static int
882_dnsPacket_isEqualDomainName( DnsPacket* pack1, DnsPacket* pack2 )
883{
884 const uint8_t* p1 = pack1->cursor;
885 const uint8_t* end1 = pack1->end;
886 const uint8_t* p2 = pack2->cursor;
887 const uint8_t* end2 = pack2->end;
888
889 for (;;) {
890 int c1, c2;
891
892 if (p1 >= end1 || p2 >= end2) {
893 XLOG("%s: INTERNAL_ERROR: read-overflow !!\n", __FUNCTION__);
894 break;
895 }
896 c1 = *p1++;
897 c2 = *p2++;
898 if (c1 != c2)
899 break;
900
901 if (c1 == 0) {
902 pack1->cursor = p1;
903 pack2->cursor = p2;
904 return 1;
905 }
906 if (c1 >= 64) {
907 XLOG("%s: INTERNAL_ERROR: malformed domain !!\n", __FUNCTION__);
908 break;
909 }
910 if ((p1+c1 > end1) || (p2+c1 > end2)) {
911 XLOG("%s: INTERNAL_ERROR: simple label read-overflow !!\n",
912 __FUNCTION__);
913 break;
914 }
915 if (memcmp(p1, p2, c1) != 0)
916 break;
917 p1 += c1;
918 p2 += c1;
919 /* we rely on the bound checks at the start of the loop */
920 }
921 /* not the same, or one is malformed */
922 XLOG("different DN");
923 return 0;
924}
925
926static int
927_dnsPacket_isEqualBytes( DnsPacket* pack1, DnsPacket* pack2, int numBytes )
928{
929 const uint8_t* p1 = pack1->cursor;
930 const uint8_t* p2 = pack2->cursor;
931
932 if ( p1 + numBytes > pack1->end || p2 + numBytes > pack2->end )
933 return 0;
934
935 if ( memcmp(p1, p2, numBytes) != 0 )
936 return 0;
937
938 pack1->cursor += numBytes;
939 pack2->cursor += numBytes;
940 return 1;
941}
942
943static int
944_dnsPacket_isEqualQR( DnsPacket* pack1, DnsPacket* pack2 )
945{
946 /* compare domain name encoding + TYPE + CLASS */
947 if ( !_dnsPacket_isEqualDomainName(pack1, pack2) ||
948 !_dnsPacket_isEqualBytes(pack1, pack2, 2+2) )
949 return 0;
950
951 return 1;
952}
953
954static int
955_dnsPacket_isEqualQuery( DnsPacket* pack1, DnsPacket* pack2 )
956{
957 int count1, count2;
958
959 /* compare the headers, ignore most fields */
960 _dnsPacket_rewind(pack1);
961 _dnsPacket_rewind(pack2);
962
963 /* compare RD, ignore TC, see comment in _dnsPacket_checkQuery */
964 if ((pack1->base[2] & 1) != (pack2->base[2] & 1)) {
965 XLOG("different RD");
966 return 0;
967 }
968
969 /* assume: other flags are all 0 */
970 _dnsPacket_skip(pack1, 4);
971 _dnsPacket_skip(pack2, 4);
972
973 /* compare QDCOUNT */
974 count1 = _dnsPacket_readInt16(pack1);
975 count2 = _dnsPacket_readInt16(pack2);
976 if (count1 != count2 || count1 < 0) {
977 XLOG("different QDCOUNT");
978 return 0;
979 }
980
981 /* assume: ANcount, NScount and ARcount are all 0 */
982 _dnsPacket_skip(pack1, 6);
983 _dnsPacket_skip(pack2, 6);
984
985 /* compare the QDCOUNT QRs */
986 for ( ; count1 > 0; count1-- ) {
987 if (!_dnsPacket_isEqualQR(pack1, pack2)) {
988 XLOG("different QR");
989 return 0;
990 }
991 }
992 return 1;
993}
994
995/****************************************************************************/
996/****************************************************************************/
997/***** *****/
998/***** *****/
999/***** *****/
1000/****************************************************************************/
1001/****************************************************************************/
1002
1003/* cache entry. for simplicity, 'hash' and 'hlink' are inlined in this
1004 * structure though they are conceptually part of the hash table.
1005 *
1006 * similarly, mru_next and mru_prev are part of the global MRU list
1007 */
1008typedef struct Entry {
1009 unsigned int hash; /* hash value */
1010 struct Entry* hlink; /* next in collision chain */
1011 struct Entry* mru_prev;
1012 struct Entry* mru_next;
1013
1014 const uint8_t* query;
1015 int querylen;
1016 const uint8_t* answer;
1017 int answerlen;
Mattias Falk3e0c5102011-01-31 12:42:26 +01001018 time_t expires; /* time_t when the entry isn't valid any more */
1019 int id; /* for debugging purpose */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001020} Entry;
1021
Mattias Falk3e0c5102011-01-31 12:42:26 +01001022/**
1023 * Parse the answer records and find the smallest
1024 * TTL among the answer records.
1025 *
1026 * The returned TTL is the number of seconds to
1027 * keep the answer in the cache.
1028 *
1029 * In case of parse error zero (0) is returned which
1030 * indicates that the answer shall not be cached.
1031 */
1032static u_long
1033answer_getTTL(const void* answer, int answerlen)
1034{
1035 ns_msg handle;
1036 int ancount, n;
1037 u_long result, ttl;
1038 ns_rr rr;
1039
1040 result = 0;
1041 if (ns_initparse(answer, answerlen, &handle) >= 0) {
1042 // get number of answer records
1043 ancount = ns_msg_count(handle, ns_s_an);
1044 for (n = 0; n < ancount; n++) {
1045 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
1046 ttl = ns_rr_ttl(rr);
1047 if (n == 0 || ttl < result) {
1048 result = ttl;
1049 }
1050 } else {
1051 XLOG("ns_parserr failed ancount no = %d. errno = %s\n", n, strerror(errno));
1052 }
1053 }
1054 } else {
1055 XLOG("ns_parserr failed. %s\n", strerror(errno));
1056 }
1057
1058 XLOG("TTL = %d\n", result);
1059
1060 return result;
1061}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001062
1063static void
1064entry_free( Entry* e )
1065{
1066 /* everything is allocated in a single memory block */
1067 if (e) {
1068 free(e);
1069 }
1070}
1071
1072static __inline__ void
1073entry_mru_remove( Entry* e )
1074{
1075 e->mru_prev->mru_next = e->mru_next;
1076 e->mru_next->mru_prev = e->mru_prev;
1077}
1078
1079static __inline__ void
1080entry_mru_add( Entry* e, Entry* list )
1081{
1082 Entry* first = list->mru_next;
1083
1084 e->mru_next = first;
1085 e->mru_prev = list;
1086
1087 list->mru_next = e;
1088 first->mru_prev = e;
1089}
1090
1091/* compute the hash of a given entry, this is a hash of most
1092 * data in the query (key) */
1093static unsigned
1094entry_hash( const Entry* e )
1095{
1096 DnsPacket pack[1];
1097
1098 _dnsPacket_init(pack, e->query, e->querylen);
1099 return _dnsPacket_hashQuery(pack);
1100}
1101
1102/* initialize an Entry as a search key, this also checks the input query packet
1103 * returns 1 on success, or 0 in case of unsupported/malformed data */
1104static int
1105entry_init_key( Entry* e, const void* query, int querylen )
1106{
1107 DnsPacket pack[1];
1108
1109 memset(e, 0, sizeof(*e));
1110
1111 e->query = query;
1112 e->querylen = querylen;
1113 e->hash = entry_hash(e);
1114
1115 _dnsPacket_init(pack, query, querylen);
1116
1117 return _dnsPacket_checkQuery(pack);
1118}
1119
1120/* allocate a new entry as a cache node */
1121static Entry*
1122entry_alloc( const Entry* init, const void* answer, int answerlen )
1123{
1124 Entry* e;
1125 int size;
1126
1127 size = sizeof(*e) + init->querylen + answerlen;
1128 e = calloc(size, 1);
1129 if (e == NULL)
1130 return e;
1131
1132 e->hash = init->hash;
1133 e->query = (const uint8_t*)(e+1);
1134 e->querylen = init->querylen;
1135
1136 memcpy( (char*)e->query, init->query, e->querylen );
1137
1138 e->answer = e->query + e->querylen;
1139 e->answerlen = answerlen;
1140
1141 memcpy( (char*)e->answer, answer, e->answerlen );
1142
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001143 return e;
1144}
1145
1146static int
1147entry_equals( const Entry* e1, const Entry* e2 )
1148{
1149 DnsPacket pack1[1], pack2[1];
1150
1151 if (e1->querylen != e2->querylen) {
1152 return 0;
1153 }
1154 _dnsPacket_init(pack1, e1->query, e1->querylen);
1155 _dnsPacket_init(pack2, e2->query, e2->querylen);
1156
1157 return _dnsPacket_isEqualQuery(pack1, pack2);
1158}
1159
1160/****************************************************************************/
1161/****************************************************************************/
1162/***** *****/
1163/***** *****/
1164/***** *****/
1165/****************************************************************************/
1166/****************************************************************************/
1167
1168/* We use a simple hash table with external collision lists
1169 * for simplicity, the hash-table fields 'hash' and 'hlink' are
1170 * inlined in the Entry structure.
1171 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001172
Mattias Falka59cfcf2011-09-06 15:15:06 +02001173/* Maximum time for a thread to wait for an pending request */
1174#define PENDING_REQUEST_TIMEOUT 20;
1175
1176typedef struct pending_req_info {
1177 unsigned int hash;
1178 pthread_cond_t cond;
1179 struct pending_req_info* next;
1180} PendingReqInfo;
1181
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001182typedef struct resolv_cache {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001183 int max_entries;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001184 int num_entries;
1185 Entry mru_list;
1186 pthread_mutex_t lock;
1187 unsigned generation;
1188 int last_id;
Mattias Falk3a4910c2011-02-14 12:41:11 +01001189 Entry* entries;
Mattias Falka59cfcf2011-09-06 15:15:06 +02001190 PendingReqInfo pending_requests;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001191} Cache;
1192
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001193typedef struct resolv_cache_info {
1194 char ifname[IF_NAMESIZE + 1];
1195 struct in_addr ifaddr;
1196 Cache* cache;
1197 struct resolv_cache_info* next;
1198 char* nameservers[MAXNS +1];
1199 struct addrinfo* nsaddrinfo[MAXNS + 1];
Robert Greenwalt6f3222e2012-11-13 11:50:57 -08001200 char* domains;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001201} CacheInfo;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001202
1203#define HTABLE_VALID(x) ((x) != NULL && (x) != HTABLE_DELETED)
1204
1205static void
Mattias Falka59cfcf2011-09-06 15:15:06 +02001206_cache_flush_pending_requests_locked( struct resolv_cache* cache )
1207{
1208 struct pending_req_info *ri, *tmp;
1209 if (cache) {
1210 ri = cache->pending_requests.next;
1211
1212 while (ri) {
1213 tmp = ri;
1214 ri = ri->next;
1215 pthread_cond_broadcast(&tmp->cond);
1216
1217 pthread_cond_destroy(&tmp->cond);
1218 free(tmp);
1219 }
1220
1221 cache->pending_requests.next = NULL;
1222 }
1223}
1224
1225/* return 0 if no pending request is found matching the key
1226 * if a matching request is found the calling thread will wait
1227 * and return 1 when released */
1228static int
1229_cache_check_pending_request_locked( struct resolv_cache* cache, Entry* key )
1230{
1231 struct pending_req_info *ri, *prev;
1232 int exist = 0;
1233
1234 if (cache && key) {
1235 ri = cache->pending_requests.next;
1236 prev = &cache->pending_requests;
1237 while (ri) {
1238 if (ri->hash == key->hash) {
1239 exist = 1;
1240 break;
1241 }
1242 prev = ri;
1243 ri = ri->next;
1244 }
1245
1246 if (!exist) {
1247 ri = calloc(1, sizeof(struct pending_req_info));
1248 if (ri) {
1249 ri->hash = key->hash;
1250 pthread_cond_init(&ri->cond, NULL);
1251 prev->next = ri;
1252 }
1253 } else {
1254 struct timespec ts = {0,0};
1255 ts.tv_sec = _time_now() + PENDING_REQUEST_TIMEOUT;
1256 int rv = pthread_cond_timedwait(&ri->cond, &cache->lock, &ts);
1257 }
1258 }
1259
1260 return exist;
1261}
1262
1263/* notify any waiting thread that waiting on a request
1264 * matching the key has been added to the cache */
1265static void
1266_cache_notify_waiting_tid_locked( struct resolv_cache* cache, Entry* key )
1267{
1268 struct pending_req_info *ri, *prev;
1269
1270 if (cache && key) {
1271 ri = cache->pending_requests.next;
1272 prev = &cache->pending_requests;
1273 while (ri) {
1274 if (ri->hash == key->hash) {
1275 pthread_cond_broadcast(&ri->cond);
1276 break;
1277 }
1278 prev = ri;
1279 ri = ri->next;
1280 }
1281
1282 // remove item from list and destroy
1283 if (ri) {
1284 prev->next = ri->next;
1285 pthread_cond_destroy(&ri->cond);
1286 free(ri);
1287 }
1288 }
1289}
1290
1291/* notify the cache that the query failed */
1292void
1293_resolv_cache_query_failed( struct resolv_cache* cache,
1294 const void* query,
1295 int querylen)
1296{
1297 Entry key[1];
1298
1299 if (cache && entry_init_key(key, query, querylen)) {
1300 pthread_mutex_lock(&cache->lock);
1301 _cache_notify_waiting_tid_locked(cache, key);
1302 pthread_mutex_unlock(&cache->lock);
1303 }
1304}
1305
1306static void
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001307_cache_flush_locked( Cache* cache )
1308{
1309 int nn;
1310 time_t now = _time_now();
1311
Mattias Falk3a4910c2011-02-14 12:41:11 +01001312 for (nn = 0; nn < cache->max_entries; nn++)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001313 {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001314 Entry** pnode = (Entry**) &cache->entries[nn];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001315
1316 while (*pnode != NULL) {
1317 Entry* node = *pnode;
1318 *pnode = node->hlink;
1319 entry_free(node);
1320 }
1321 }
1322
Mattias Falka59cfcf2011-09-06 15:15:06 +02001323 // flush pending request
1324 _cache_flush_pending_requests_locked(cache);
1325
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001326 cache->mru_list.mru_next = cache->mru_list.mru_prev = &cache->mru_list;
1327 cache->num_entries = 0;
1328 cache->last_id = 0;
1329
1330 XLOG("*************************\n"
1331 "*** DNS CACHE FLUSHED ***\n"
1332 "*************************");
1333}
1334
Mattias Falk3a4910c2011-02-14 12:41:11 +01001335/* Return max number of entries allowed in the cache,
1336 * i.e. cache size. The cache size is either defined
1337 * by system property ro.net.dns_cache_size or by
1338 * CONFIG_MAX_ENTRIES if system property not set
1339 * or set to invalid value. */
1340static int
1341_res_cache_get_max_entries( void )
1342{
1343 int result = -1;
1344 char cache_size[PROP_VALUE_MAX];
1345
Robert Greenwalt52764f52012-01-25 15:16:03 -08001346 const char* cache_mode = getenv("ANDROID_DNS_MODE");
1347
1348 if (cache_mode == NULL || strcmp(cache_mode, "local") != 0) {
1349 // Don't use the cache in local mode. This is used by the
1350 // proxy itself.
1351 // TODO - change this to 0 when all dns stuff uses proxy (5918973)
1352 XLOG("setup cache for non-cache process. size=1");
1353 return 1;
1354 }
1355
Mattias Falk3a4910c2011-02-14 12:41:11 +01001356 if (__system_property_get(DNS_CACHE_SIZE_PROP_NAME, cache_size) > 0) {
1357 result = atoi(cache_size);
1358 }
1359
1360 // ro.net.dns_cache_size not set or set to negative value
1361 if (result <= 0) {
1362 result = CONFIG_MAX_ENTRIES;
1363 }
1364
1365 XLOG("cache size: %d", result);
1366 return result;
1367}
1368
Jim Huang7cc56662010-10-15 02:02:57 +08001369static struct resolv_cache*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001370_resolv_cache_create( void )
1371{
1372 struct resolv_cache* cache;
1373
1374 cache = calloc(sizeof(*cache), 1);
1375 if (cache) {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001376 cache->max_entries = _res_cache_get_max_entries();
1377 cache->entries = calloc(sizeof(*cache->entries), cache->max_entries);
1378 if (cache->entries) {
1379 cache->generation = ~0U;
1380 pthread_mutex_init( &cache->lock, NULL );
1381 cache->mru_list.mru_prev = cache->mru_list.mru_next = &cache->mru_list;
1382 XLOG("%s: cache created\n", __FUNCTION__);
1383 } else {
1384 free(cache);
1385 cache = NULL;
1386 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001387 }
1388 return cache;
1389}
1390
1391
1392#if DEBUG
1393static void
1394_dump_query( const uint8_t* query, int querylen )
1395{
1396 char temp[256], *p=temp, *end=p+sizeof(temp);
1397 DnsPacket pack[1];
1398
1399 _dnsPacket_init(pack, query, querylen);
1400 p = _dnsPacket_bprintQuery(pack, p, end);
1401 XLOG("QUERY: %s", temp);
1402}
1403
1404static void
1405_cache_dump_mru( Cache* cache )
1406{
1407 char temp[512], *p=temp, *end=p+sizeof(temp);
1408 Entry* e;
1409
1410 p = _bprint(temp, end, "MRU LIST (%2d): ", cache->num_entries);
1411 for (e = cache->mru_list.mru_next; e != &cache->mru_list; e = e->mru_next)
1412 p = _bprint(p, end, " %d", e->id);
1413
1414 XLOG("%s", temp);
1415}
Mattias Falk3e0c5102011-01-31 12:42:26 +01001416
1417static void
1418_dump_answer(const void* answer, int answerlen)
1419{
1420 res_state statep;
1421 FILE* fp;
1422 char* buf;
1423 int fileLen;
1424
1425 fp = fopen("/data/reslog.txt", "w+");
1426 if (fp != NULL) {
1427 statep = __res_get_state();
1428
1429 res_pquery(statep, answer, answerlen, fp);
1430
1431 //Get file length
1432 fseek(fp, 0, SEEK_END);
1433 fileLen=ftell(fp);
1434 fseek(fp, 0, SEEK_SET);
1435 buf = (char *)malloc(fileLen+1);
1436 if (buf != NULL) {
1437 //Read file contents into buffer
1438 fread(buf, fileLen, 1, fp);
1439 XLOG("%s\n", buf);
1440 free(buf);
1441 }
1442 fclose(fp);
1443 remove("/data/reslog.txt");
1444 }
1445 else {
1446 XLOG("_dump_answer: can't open file\n");
1447 }
1448}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001449#endif
1450
1451#if DEBUG
1452# define XLOG_QUERY(q,len) _dump_query((q), (len))
Mattias Falk3e0c5102011-01-31 12:42:26 +01001453# define XLOG_ANSWER(a, len) _dump_answer((a), (len))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001454#else
1455# define XLOG_QUERY(q,len) ((void)0)
Mattias Falk3e0c5102011-01-31 12:42:26 +01001456# define XLOG_ANSWER(a,len) ((void)0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001457#endif
1458
1459/* This function tries to find a key within the hash table
1460 * In case of success, it will return a *pointer* to the hashed key.
1461 * In case of failure, it will return a *pointer* to NULL
1462 *
1463 * So, the caller must check '*result' to check for success/failure.
1464 *
1465 * The main idea is that the result can later be used directly in
1466 * calls to _resolv_cache_add or _resolv_cache_remove as the 'lookup'
1467 * parameter. This makes the code simpler and avoids re-searching
1468 * for the key position in the htable.
1469 *
1470 * The result of a lookup_p is only valid until you alter the hash
1471 * table.
1472 */
1473static Entry**
1474_cache_lookup_p( Cache* cache,
1475 Entry* key )
1476{
Mattias Falk3a4910c2011-02-14 12:41:11 +01001477 int index = key->hash % cache->max_entries;
1478 Entry** pnode = (Entry**) &cache->entries[ index ];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001479
1480 while (*pnode != NULL) {
1481 Entry* node = *pnode;
1482
1483 if (node == NULL)
1484 break;
1485
1486 if (node->hash == key->hash && entry_equals(node, key))
1487 break;
1488
1489 pnode = &node->hlink;
1490 }
1491 return pnode;
1492}
1493
1494/* Add a new entry to the hash table. 'lookup' must be the
1495 * result of an immediate previous failed _lookup_p() call
1496 * (i.e. with *lookup == NULL), and 'e' is the pointer to the
1497 * newly created entry
1498 */
1499static void
1500_cache_add_p( Cache* cache,
1501 Entry** lookup,
1502 Entry* e )
1503{
1504 *lookup = e;
1505 e->id = ++cache->last_id;
1506 entry_mru_add(e, &cache->mru_list);
1507 cache->num_entries += 1;
1508
1509 XLOG("%s: entry %d added (count=%d)", __FUNCTION__,
1510 e->id, cache->num_entries);
1511}
1512
1513/* Remove an existing entry from the hash table,
1514 * 'lookup' must be the result of an immediate previous
1515 * and succesful _lookup_p() call.
1516 */
1517static void
1518_cache_remove_p( Cache* cache,
1519 Entry** lookup )
1520{
1521 Entry* e = *lookup;
1522
1523 XLOG("%s: entry %d removed (count=%d)", __FUNCTION__,
1524 e->id, cache->num_entries-1);
1525
1526 entry_mru_remove(e);
1527 *lookup = e->hlink;
1528 entry_free(e);
1529 cache->num_entries -= 1;
1530}
1531
1532/* Remove the oldest entry from the hash table.
1533 */
1534static void
1535_cache_remove_oldest( Cache* cache )
1536{
1537 Entry* oldest = cache->mru_list.mru_prev;
1538 Entry** lookup = _cache_lookup_p(cache, oldest);
1539
1540 if (*lookup == NULL) { /* should not happen */
1541 XLOG("%s: OLDEST NOT IN HTABLE ?", __FUNCTION__);
1542 return;
1543 }
Robert Greenwalt7f84da62011-09-02 07:44:36 -07001544 if (DEBUG) {
1545 XLOG("Cache full - removing oldest");
1546 XLOG_QUERY(oldest->query, oldest->querylen);
1547 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001548 _cache_remove_p(cache, lookup);
1549}
1550
Anders Fredlunddd161822011-05-20 08:12:37 +02001551/* Remove all expired entries from the hash table.
1552 */
1553static void _cache_remove_expired(Cache* cache) {
1554 Entry* e;
1555 time_t now = _time_now();
1556
1557 for (e = cache->mru_list.mru_next; e != &cache->mru_list;) {
1558 // Entry is old, remove
1559 if (now >= e->expires) {
1560 Entry** lookup = _cache_lookup_p(cache, e);
1561 if (*lookup == NULL) { /* should not happen */
1562 XLOG("%s: ENTRY NOT IN HTABLE ?", __FUNCTION__);
1563 return;
1564 }
1565 e = e->mru_next;
1566 _cache_remove_p(cache, lookup);
1567 } else {
1568 e = e->mru_next;
1569 }
1570 }
1571}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001572
1573ResolvCacheStatus
1574_resolv_cache_lookup( struct resolv_cache* cache,
1575 const void* query,
1576 int querylen,
1577 void* answer,
1578 int answersize,
1579 int *answerlen )
1580{
1581 DnsPacket pack[1];
1582 Entry key[1];
1583 int index;
1584 Entry** lookup;
1585 Entry* e;
1586 time_t now;
1587
1588 ResolvCacheStatus result = RESOLV_CACHE_NOTFOUND;
1589
1590 XLOG("%s: lookup", __FUNCTION__);
1591 XLOG_QUERY(query, querylen);
1592
1593 /* we don't cache malformed queries */
1594 if (!entry_init_key(key, query, querylen)) {
1595 XLOG("%s: unsupported query", __FUNCTION__);
1596 return RESOLV_CACHE_UNSUPPORTED;
1597 }
1598 /* lookup cache */
1599 pthread_mutex_lock( &cache->lock );
1600
1601 /* see the description of _lookup_p to understand this.
1602 * the function always return a non-NULL pointer.
1603 */
1604 lookup = _cache_lookup_p(cache, key);
1605 e = *lookup;
1606
1607 if (e == NULL) {
1608 XLOG( "NOT IN CACHE");
Mattias Falka59cfcf2011-09-06 15:15:06 +02001609 // calling thread will wait if an outstanding request is found
1610 // that matching this query
1611 if (!_cache_check_pending_request_locked(cache, key)) {
1612 goto Exit;
1613 } else {
1614 lookup = _cache_lookup_p(cache, key);
1615 e = *lookup;
1616 if (e == NULL) {
1617 goto Exit;
1618 }
1619 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001620 }
1621
1622 now = _time_now();
1623
1624 /* remove stale entries here */
Mattias Falk3e0c5102011-01-31 12:42:26 +01001625 if (now >= e->expires) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001626 XLOG( " NOT IN CACHE (STALE ENTRY %p DISCARDED)", *lookup );
Robert Greenwalt7f84da62011-09-02 07:44:36 -07001627 XLOG_QUERY(e->query, e->querylen);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001628 _cache_remove_p(cache, lookup);
1629 goto Exit;
1630 }
1631
1632 *answerlen = e->answerlen;
1633 if (e->answerlen > answersize) {
1634 /* NOTE: we return UNSUPPORTED if the answer buffer is too short */
1635 result = RESOLV_CACHE_UNSUPPORTED;
1636 XLOG(" ANSWER TOO LONG");
1637 goto Exit;
1638 }
1639
1640 memcpy( answer, e->answer, e->answerlen );
1641
1642 /* bump up this entry to the top of the MRU list */
1643 if (e != cache->mru_list.mru_next) {
1644 entry_mru_remove( e );
1645 entry_mru_add( e, &cache->mru_list );
1646 }
1647
1648 XLOG( "FOUND IN CACHE entry=%p", e );
1649 result = RESOLV_CACHE_FOUND;
1650
1651Exit:
1652 pthread_mutex_unlock( &cache->lock );
1653 return result;
1654}
1655
1656
1657void
1658_resolv_cache_add( struct resolv_cache* cache,
1659 const void* query,
1660 int querylen,
1661 const void* answer,
1662 int answerlen )
1663{
1664 Entry key[1];
1665 Entry* e;
1666 Entry** lookup;
Mattias Falk3e0c5102011-01-31 12:42:26 +01001667 u_long ttl;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001668
1669 /* don't assume that the query has already been cached
1670 */
1671 if (!entry_init_key( key, query, querylen )) {
1672 XLOG( "%s: passed invalid query ?", __FUNCTION__);
1673 return;
1674 }
1675
1676 pthread_mutex_lock( &cache->lock );
1677
1678 XLOG( "%s: query:", __FUNCTION__ );
1679 XLOG_QUERY(query,querylen);
Mattias Falk3e0c5102011-01-31 12:42:26 +01001680 XLOG_ANSWER(answer, answerlen);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001681#if DEBUG_DATA
1682 XLOG( "answer:");
1683 XLOG_BYTES(answer,answerlen);
1684#endif
1685
1686 lookup = _cache_lookup_p(cache, key);
1687 e = *lookup;
1688
1689 if (e != NULL) { /* should not happen */
1690 XLOG("%s: ALREADY IN CACHE (%p) ? IGNORING ADD",
1691 __FUNCTION__, e);
1692 goto Exit;
1693 }
1694
Mattias Falk3a4910c2011-02-14 12:41:11 +01001695 if (cache->num_entries >= cache->max_entries) {
Anders Fredlunddd161822011-05-20 08:12:37 +02001696 _cache_remove_expired(cache);
1697 if (cache->num_entries >= cache->max_entries) {
1698 _cache_remove_oldest(cache);
1699 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001700 /* need to lookup again */
1701 lookup = _cache_lookup_p(cache, key);
1702 e = *lookup;
1703 if (e != NULL) {
1704 XLOG("%s: ALREADY IN CACHE (%p) ? IGNORING ADD",
1705 __FUNCTION__, e);
1706 goto Exit;
1707 }
1708 }
1709
Mattias Falk3e0c5102011-01-31 12:42:26 +01001710 ttl = answer_getTTL(answer, answerlen);
1711 if (ttl > 0) {
1712 e = entry_alloc(key, answer, answerlen);
1713 if (e != NULL) {
1714 e->expires = ttl + _time_now();
1715 _cache_add_p(cache, lookup, e);
1716 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001717 }
1718#if DEBUG
1719 _cache_dump_mru(cache);
1720#endif
1721Exit:
Mattias Falka59cfcf2011-09-06 15:15:06 +02001722 _cache_notify_waiting_tid_locked(cache, key);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001723 pthread_mutex_unlock( &cache->lock );
1724}
1725
1726/****************************************************************************/
1727/****************************************************************************/
1728/***** *****/
1729/***** *****/
1730/***** *****/
1731/****************************************************************************/
1732/****************************************************************************/
1733
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001734static pthread_once_t _res_cache_once;
1735
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001736// Head of the list of caches. Protected by _res_cache_list_lock.
1737static struct resolv_cache_info _res_cache_list;
1738
1739// name of the current default inteface
1740static char _res_default_ifname[IF_NAMESIZE + 1];
1741
1742// lock protecting everything in the _resolve_cache_info structs (next ptr, etc)
1743static pthread_mutex_t _res_cache_list_lock;
1744
1745
1746/* lookup the default interface name */
1747static char *_get_default_iface_locked();
1748/* insert resolv_cache_info into the list of resolv_cache_infos */
1749static void _insert_cache_info_locked(struct resolv_cache_info* cache_info);
1750/* creates a resolv_cache_info */
1751static struct resolv_cache_info* _create_cache_info( void );
1752/* gets cache associated with an interface name, or NULL if none exists */
1753static struct resolv_cache* _find_named_cache_locked(const char* ifname);
1754/* gets a resolv_cache_info associated with an interface name, or NULL if not found */
1755static struct resolv_cache_info* _find_cache_info_locked(const char* ifname);
1756/* free dns name server list of a resolv_cache_info structure */
1757static void _free_nameservers(struct resolv_cache_info* cache_info);
1758/* look up the named cache, and creates one if needed */
1759static struct resolv_cache* _get_res_cache_for_iface_locked(const char* ifname);
1760/* empty the named cache */
1761static void _flush_cache_for_iface_locked(const char* ifname);
1762/* empty the nameservers set for the named cache */
1763static void _free_nameservers_locked(struct resolv_cache_info* cache_info);
1764/* lookup the namserver for the name interface */
1765static int _get_nameserver_locked(const char* ifname, int n, char* addr, int addrLen);
1766/* lookup the addr of the nameserver for the named interface */
1767static struct addrinfo* _get_nameserver_addr_locked(const char* ifname, int n);
1768/* lookup the inteface's address */
1769static struct in_addr* _get_addr_locked(const char * ifname);
1770
1771
1772
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001773static void
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001774_res_cache_init(void)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001775{
1776 const char* env = getenv(CONFIG_ENV);
1777
1778 if (env && atoi(env) == 0) {
1779 /* the cache is disabled */
1780 return;
1781 }
1782
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001783 memset(&_res_default_ifname, 0, sizeof(_res_default_ifname));
1784 memset(&_res_cache_list, 0, sizeof(_res_cache_list));
1785 pthread_mutex_init(&_res_cache_list_lock, NULL);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001786}
1787
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001788struct resolv_cache*
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001789__get_res_cache(void)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001790{
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001791 struct resolv_cache *cache;
1792
1793 pthread_once(&_res_cache_once, _res_cache_init);
1794
1795 pthread_mutex_lock(&_res_cache_list_lock);
1796
1797 char* ifname = _get_default_iface_locked();
1798
1799 // if default interface not set then use the first cache
1800 // associated with an interface as the default one.
1801 if (ifname[0] == '\0') {
1802 struct resolv_cache_info* cache_info = _res_cache_list.next;
1803 while (cache_info) {
1804 if (cache_info->ifname[0] != '\0') {
1805 ifname = cache_info->ifname;
Robert Greenwalt9363d912011-07-25 12:30:17 -07001806 break;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001807 }
1808
1809 cache_info = cache_info->next;
1810 }
1811 }
1812 cache = _get_res_cache_for_iface_locked(ifname);
1813
1814 pthread_mutex_unlock(&_res_cache_list_lock);
1815 XLOG("_get_res_cache. default_ifname = %s\n", ifname);
1816 return cache;
1817}
1818
1819static struct resolv_cache*
1820_get_res_cache_for_iface_locked(const char* ifname)
1821{
1822 if (ifname == NULL)
1823 return NULL;
1824
1825 struct resolv_cache* cache = _find_named_cache_locked(ifname);
1826 if (!cache) {
1827 struct resolv_cache_info* cache_info = _create_cache_info();
1828 if (cache_info) {
1829 cache = _resolv_cache_create();
1830 if (cache) {
1831 int len = sizeof(cache_info->ifname);
1832 cache_info->cache = cache;
1833 strncpy(cache_info->ifname, ifname, len - 1);
1834 cache_info->ifname[len - 1] = '\0';
1835
1836 _insert_cache_info_locked(cache_info);
1837 } else {
1838 free(cache_info);
1839 }
1840 }
1841 }
1842 return cache;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001843}
1844
1845void
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001846_resolv_cache_reset(unsigned generation)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001847{
1848 XLOG("%s: generation=%d", __FUNCTION__, generation);
1849
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001850 pthread_once(&_res_cache_once, _res_cache_init);
1851 pthread_mutex_lock(&_res_cache_list_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001852
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001853 char* ifname = _get_default_iface_locked();
1854 // if default interface not set then use the first cache
1855 // associated with an interface as the default one.
1856 // Note: Copied the code from __get_res_cache since this
1857 // method will be deleted/obsolete when cache per interface
1858 // implemented all over
1859 if (ifname[0] == '\0') {
1860 struct resolv_cache_info* cache_info = _res_cache_list.next;
1861 while (cache_info) {
1862 if (cache_info->ifname[0] != '\0') {
1863 ifname = cache_info->ifname;
Robert Greenwalt9363d912011-07-25 12:30:17 -07001864 break;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001865 }
1866
1867 cache_info = cache_info->next;
1868 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001869 }
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001870 struct resolv_cache* cache = _get_res_cache_for_iface_locked(ifname);
1871
Robert Greenwalt9363d912011-07-25 12:30:17 -07001872 if (cache != NULL) {
1873 pthread_mutex_lock( &cache->lock );
1874 if (cache->generation != generation) {
1875 _cache_flush_locked(cache);
1876 cache->generation = generation;
1877 }
1878 pthread_mutex_unlock( &cache->lock );
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001879 }
1880
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001881 pthread_mutex_unlock(&_res_cache_list_lock);
1882}
1883
1884void
1885_resolv_flush_cache_for_default_iface(void)
1886{
1887 char* ifname;
1888
1889 pthread_once(&_res_cache_once, _res_cache_init);
1890 pthread_mutex_lock(&_res_cache_list_lock);
1891
1892 ifname = _get_default_iface_locked();
1893 _flush_cache_for_iface_locked(ifname);
1894
1895 pthread_mutex_unlock(&_res_cache_list_lock);
1896}
1897
1898void
1899_resolv_flush_cache_for_iface(const char* ifname)
1900{
1901 pthread_once(&_res_cache_once, _res_cache_init);
1902 pthread_mutex_lock(&_res_cache_list_lock);
1903
1904 _flush_cache_for_iface_locked(ifname);
1905
1906 pthread_mutex_unlock(&_res_cache_list_lock);
1907}
1908
1909static void
1910_flush_cache_for_iface_locked(const char* ifname)
1911{
1912 struct resolv_cache* cache = _find_named_cache_locked(ifname);
1913 if (cache) {
1914 pthread_mutex_lock(&cache->lock);
1915 _cache_flush_locked(cache);
1916 pthread_mutex_unlock(&cache->lock);
1917 }
1918}
1919
1920static struct resolv_cache_info*
1921_create_cache_info(void)
1922{
1923 struct resolv_cache_info* cache_info;
1924
1925 cache_info = calloc(sizeof(*cache_info), 1);
1926 return cache_info;
1927}
1928
1929static void
1930_insert_cache_info_locked(struct resolv_cache_info* cache_info)
1931{
1932 struct resolv_cache_info* last;
1933
1934 for (last = &_res_cache_list; last->next; last = last->next);
1935
1936 last->next = cache_info;
1937
1938}
1939
1940static struct resolv_cache*
1941_find_named_cache_locked(const char* ifname) {
1942
1943 struct resolv_cache_info* info = _find_cache_info_locked(ifname);
1944
1945 if (info != NULL) return info->cache;
1946
1947 return NULL;
1948}
1949
1950static struct resolv_cache_info*
1951_find_cache_info_locked(const char* ifname)
1952{
1953 if (ifname == NULL)
1954 return NULL;
1955
1956 struct resolv_cache_info* cache_info = _res_cache_list.next;
1957
1958 while (cache_info) {
1959 if (strcmp(cache_info->ifname, ifname) == 0) {
1960 break;
1961 }
1962
1963 cache_info = cache_info->next;
1964 }
1965 return cache_info;
1966}
1967
1968static char*
1969_get_default_iface_locked(void)
1970{
1971 char* iface = _res_default_ifname;
1972
1973 return iface;
1974}
1975
1976void
1977_resolv_set_default_iface(const char* ifname)
1978{
1979 XLOG("_resolv_set_default_if ifname %s\n",ifname);
1980
1981 pthread_once(&_res_cache_once, _res_cache_init);
1982 pthread_mutex_lock(&_res_cache_list_lock);
1983
1984 int size = sizeof(_res_default_ifname);
1985 memset(_res_default_ifname, 0, size);
1986 strncpy(_res_default_ifname, ifname, size - 1);
1987 _res_default_ifname[size - 1] = '\0';
1988
1989 pthread_mutex_unlock(&_res_cache_list_lock);
1990}
1991
1992void
Robert Greenwalt6f3222e2012-11-13 11:50:57 -08001993_resolv_set_nameservers_for_iface(const char* ifname, char** servers, int numservers,
1994 const char *domains)
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001995{
1996 int i, rt, index;
1997 struct addrinfo hints;
1998 char sbuf[NI_MAXSERV];
1999
2000 pthread_once(&_res_cache_once, _res_cache_init);
2001
2002 pthread_mutex_lock(&_res_cache_list_lock);
2003 // creates the cache if not created
2004 _get_res_cache_for_iface_locked(ifname);
2005
2006 struct resolv_cache_info* cache_info = _find_cache_info_locked(ifname);
2007
2008 if (cache_info != NULL) {
2009 // free current before adding new
2010 _free_nameservers_locked(cache_info);
2011
2012 memset(&hints, 0, sizeof(hints));
2013 hints.ai_family = PF_UNSPEC;
2014 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
2015 hints.ai_flags = AI_NUMERICHOST;
2016 sprintf(sbuf, "%u", NAMESERVER_PORT);
2017
2018 index = 0;
2019 for (i = 0; i < numservers && i < MAXNS; i++) {
2020 rt = getaddrinfo(servers[i], sbuf, &hints, &cache_info->nsaddrinfo[index]);
2021 if (rt == 0) {
2022 cache_info->nameservers[index] = strdup(servers[i]);
2023 index++;
2024 } else {
2025 cache_info->nsaddrinfo[index] = NULL;
2026 }
2027 }
Robert Greenwalt6f3222e2012-11-13 11:50:57 -08002028 cache_info->domains = strdup(domains);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002029 }
2030 pthread_mutex_unlock(&_res_cache_list_lock);
2031}
2032
2033static void
2034_free_nameservers_locked(struct resolv_cache_info* cache_info)
2035{
2036 int i;
2037 for (i = 0; i <= MAXNS; i++) {
2038 free(cache_info->nameservers[i]);
2039 cache_info->nameservers[i] = NULL;
Robert Greenwalt9363d912011-07-25 12:30:17 -07002040 if (cache_info->nsaddrinfo[i] != NULL) {
2041 freeaddrinfo(cache_info->nsaddrinfo[i]);
2042 cache_info->nsaddrinfo[i] = NULL;
2043 }
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002044 }
2045}
2046
2047int
2048_resolv_cache_get_nameserver(int n, char* addr, int addrLen)
2049{
2050 char *ifname;
2051 int result = 0;
2052
2053 pthread_once(&_res_cache_once, _res_cache_init);
2054 pthread_mutex_lock(&_res_cache_list_lock);
2055
2056 ifname = _get_default_iface_locked();
2057 result = _get_nameserver_locked(ifname, n, addr, addrLen);
2058
2059 pthread_mutex_unlock(&_res_cache_list_lock);
2060 return result;
2061}
2062
2063static int
2064_get_nameserver_locked(const char* ifname, int n, char* addr, int addrLen)
2065{
2066 int len = 0;
2067 char* ns;
2068 struct resolv_cache_info* cache_info;
2069
2070 if (n < 1 || n > MAXNS || !addr)
2071 return 0;
2072
2073 cache_info = _find_cache_info_locked(ifname);
2074 if (cache_info) {
2075 ns = cache_info->nameservers[n - 1];
2076 if (ns) {
2077 len = strlen(ns);
2078 if (len < addrLen) {
2079 strncpy(addr, ns, len);
2080 addr[len] = '\0';
2081 } else {
2082 len = 0;
2083 }
2084 }
2085 }
2086
2087 return len;
2088}
2089
2090struct addrinfo*
2091_cache_get_nameserver_addr(int n)
2092{
2093 struct addrinfo *result;
2094 char* ifname;
2095
2096 pthread_once(&_res_cache_once, _res_cache_init);
2097 pthread_mutex_lock(&_res_cache_list_lock);
2098
2099 ifname = _get_default_iface_locked();
2100
2101 result = _get_nameserver_addr_locked(ifname, n);
2102 pthread_mutex_unlock(&_res_cache_list_lock);
2103 return result;
2104}
2105
2106static struct addrinfo*
2107_get_nameserver_addr_locked(const char* ifname, int n)
2108{
2109 struct addrinfo* ai = NULL;
2110 struct resolv_cache_info* cache_info;
2111
2112 if (n < 1 || n > MAXNS)
2113 return NULL;
2114
2115 cache_info = _find_cache_info_locked(ifname);
2116 if (cache_info) {
2117 ai = cache_info->nsaddrinfo[n - 1];
2118 }
2119 return ai;
2120}
2121
2122void
2123_resolv_set_addr_of_iface(const char* ifname, struct in_addr* addr)
2124{
2125 pthread_once(&_res_cache_once, _res_cache_init);
2126 pthread_mutex_lock(&_res_cache_list_lock);
2127 struct resolv_cache_info* cache_info = _find_cache_info_locked(ifname);
2128 if (cache_info) {
2129 memcpy(&cache_info->ifaddr, addr, sizeof(*addr));
2130
2131 if (DEBUG) {
2132 char* addr_s = inet_ntoa(cache_info->ifaddr);
2133 XLOG("address of interface %s is %s\n", ifname, addr_s);
2134 }
2135 }
2136 pthread_mutex_unlock(&_res_cache_list_lock);
2137}
2138
2139struct in_addr*
2140_resolv_get_addr_of_default_iface(void)
2141{
2142 struct in_addr* ai = NULL;
2143 char* ifname;
2144
2145 pthread_once(&_res_cache_once, _res_cache_init);
2146 pthread_mutex_lock(&_res_cache_list_lock);
2147 ifname = _get_default_iface_locked();
2148 ai = _get_addr_locked(ifname);
2149 pthread_mutex_unlock(&_res_cache_list_lock);
2150
2151 return ai;
2152}
2153
2154struct in_addr*
2155_resolv_get_addr_of_iface(const char* ifname)
2156{
2157 struct in_addr* ai = NULL;
2158
2159 pthread_once(&_res_cache_once, _res_cache_init);
2160 pthread_mutex_lock(&_res_cache_list_lock);
2161 ai =_get_addr_locked(ifname);
2162 pthread_mutex_unlock(&_res_cache_list_lock);
2163 return ai;
2164}
2165
2166static struct in_addr*
2167_get_addr_locked(const char * ifname)
2168{
2169 struct resolv_cache_info* cache_info = _find_cache_info_locked(ifname);
2170 if (cache_info) {
2171 return &cache_info->ifaddr;
2172 }
2173 return NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002174}