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