blob: f0c51abe21e903d3a9cc1ccc36f961e514e64e2f [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"
30#include <stdlib.h>
31#include <string.h>
32#include <time.h>
33#include "pthread.h"
34
Mattias Falk3e0c5102011-01-31 12:42:26 +010035#include <errno.h>
36#include "arpa_nameser.h"
37
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080038/* This code implements a small and *simple* DNS resolver cache.
39 *
Mattias Falk3e0c5102011-01-31 12:42:26 +010040 * It is only used to cache DNS answers for a time defined by the smallest TTL
41 * among the answer records in order to reduce DNS traffic. It is not supposed
42 * to be a full DNS cache, since we plan to implement that in the future in a
43 * dedicated process running on the system.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080044 *
45 * Note that its design is kept simple very intentionally, i.e.:
46 *
47 * - it takes raw DNS query packet data as input, and returns raw DNS
48 * answer packet data as output
49 *
50 * (this means that two similar queries that encode the DNS name
51 * differently will be treated distinctly).
52 *
Mattias Falk3e0c5102011-01-31 12:42:26 +010053 * the smallest TTL value among the answer records are used as the time
54 * to keep an answer in the cache.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080055 *
56 * this is bad, but we absolutely want to avoid parsing the answer packets
57 * (and should be solved by the later full DNS cache process).
58 *
59 * - the implementation is just a (query-data) => (answer-data) hash table
60 * with a trivial least-recently-used expiration policy.
61 *
62 * Doing this keeps the code simple and avoids to deal with a lot of things
63 * that a full DNS cache is expected to do.
64 *
65 * The API is also very simple:
66 *
67 * - the client calls _resolv_cache_get() to obtain a handle to the cache.
68 * this will initialize the cache on first usage. the result can be NULL
69 * if the cache is disabled.
70 *
71 * - the client calls _resolv_cache_lookup() before performing a query
72 *
73 * if the function returns RESOLV_CACHE_FOUND, a copy of the answer data
74 * has been copied into the client-provided answer buffer.
75 *
76 * if the function returns RESOLV_CACHE_NOTFOUND, the client should perform
77 * a request normally, *then* call _resolv_cache_add() to add the received
78 * answer to the cache.
79 *
80 * if the function returns RESOLV_CACHE_UNSUPPORTED, the client should
81 * perform a request normally, and *not* call _resolv_cache_add()
82 *
83 * note that RESOLV_CACHE_UNSUPPORTED is also returned if the answer buffer
84 * is too short to accomodate the cached result.
85 *
86 * - when network settings change, the cache must be flushed since the list
87 * of DNS servers probably changed. this is done by calling
88 * _resolv_cache_reset()
89 *
90 * the parameter to this function must be an ever-increasing generation
91 * number corresponding to the current network settings state.
92 *
93 * This is done because several threads could detect the same network
94 * settings change (but at different times) and will all end up calling the
95 * same function. Comparing with the last used generation number ensures
96 * that the cache is only flushed once per network change.
97 */
98
99/* the name of an environment variable that will be checked the first time
100 * this code is called if its value is "0", then the resolver cache is
101 * disabled.
102 */
103#define CONFIG_ENV "BIONIC_DNSCACHE"
104
105/* entries older than CONFIG_SECONDS seconds are always discarded.
106 */
107#define CONFIG_SECONDS (60*10) /* 10 minutes */
108
109/* maximum number of entries kept in the cache. This value has been
110 * determined by browsing through various sites and counting the number
111 * of corresponding requests. Keep in mind that our framework is currently
112 * performing two requests per name lookup (one for IPv4, the other for IPv6)
113 *
114 * www.google.com 4
115 * www.ysearch.com 6
116 * www.amazon.com 8
117 * www.nytimes.com 22
118 * www.espn.com 28
119 * www.msn.com 28
120 * www.lemonde.fr 35
121 *
122 * (determined in 2009-2-17 from Paris, France, results may vary depending
123 * on location)
124 *
125 * most high-level websites use lots of media/ad servers with different names
126 * but these are generally reused when browsing through the site.
127 *
128 * As such, a valud of 64 should be relatively conformtable at the moment.
129 */
130#define CONFIG_MAX_ENTRIES 64
131
132/****************************************************************************/
133/****************************************************************************/
134/***** *****/
135/***** *****/
136/***** *****/
137/****************************************************************************/
138/****************************************************************************/
139
140/* set to 1 to debug cache operations */
141#define DEBUG 0
142
143/* set to 1 to debug query data */
144#define DEBUG_DATA 0
145
Mattias Falk3e0c5102011-01-31 12:42:26 +0100146#undef XLOG
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800147#if DEBUG
148# include <logd.h>
149# define XLOG(...) \
150 __libc_android_log_print(ANDROID_LOG_DEBUG,"libc",__VA_ARGS__)
151
152#include <stdio.h>
153#include <stdarg.h>
154
Mattias Falk3e0c5102011-01-31 12:42:26 +0100155#include <arpa/inet.h>
156#include "resolv_private.h"
157
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800158/** BOUNDED BUFFER FORMATTING
159 **/
160
161/* technical note:
162 *
163 * the following debugging routines are used to append data to a bounded
164 * buffer they take two parameters that are:
165 *
166 * - p : a pointer to the current cursor position in the buffer
167 * this value is initially set to the buffer's address.
168 *
169 * - end : the address of the buffer's limit, i.e. of the first byte
170 * after the buffer. this address should never be touched.
171 *
172 * IMPORTANT: it is assumed that end > buffer_address, i.e.
173 * that the buffer is at least one byte.
174 *
175 * the _bprint_() functions return the new value of 'p' after the data
176 * has been appended, and also ensure the following:
177 *
178 * - the returned value will never be strictly greater than 'end'
179 *
180 * - a return value equal to 'end' means that truncation occured
181 * (in which case, end[-1] will be set to 0)
182 *
183 * - after returning from a _bprint_() function, the content of the buffer
184 * is always 0-terminated, even in the event of truncation.
185 *
186 * these conventions allow you to call _bprint_ functions multiple times and
187 * only check for truncation at the end of the sequence, as in:
188 *
189 * char buff[1000], *p = buff, *end = p + sizeof(buff);
190 *
191 * p = _bprint_c(p, end, '"');
192 * p = _bprint_s(p, end, my_string);
193 * p = _bprint_c(p, end, '"');
194 *
195 * if (p >= end) {
196 * // buffer was too small
197 * }
198 *
199 * printf( "%s", buff );
200 */
201
202/* add a char to a bounded buffer */
203static char*
204_bprint_c( char* p, char* end, int c )
205{
206 if (p < end) {
207 if (p+1 == end)
208 *p++ = 0;
209 else {
210 *p++ = (char) c;
211 *p = 0;
212 }
213 }
214 return p;
215}
216
217/* add a sequence of bytes to a bounded buffer */
218static char*
219_bprint_b( char* p, char* end, const char* buf, int len )
220{
221 int avail = end - p;
222
223 if (avail <= 0 || len <= 0)
224 return p;
225
226 if (avail > len)
227 avail = len;
228
229 memcpy( p, buf, avail );
230 p += avail;
231
232 if (p < end)
233 p[0] = 0;
234 else
235 end[-1] = 0;
236
237 return p;
238}
239
240/* add a string to a bounded buffer */
241static char*
242_bprint_s( char* p, char* end, const char* str )
243{
244 return _bprint_b(p, end, str, strlen(str));
245}
246
247/* add a formatted string to a bounded buffer */
248static char*
249_bprint( char* p, char* end, const char* format, ... )
250{
251 int avail, n;
252 va_list args;
253
254 avail = end - p;
255
256 if (avail <= 0)
257 return p;
258
259 va_start(args, format);
David 'Digit' Turnerd378c682010-03-08 15:13:04 -0800260 n = vsnprintf( p, avail, format, args);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800261 va_end(args);
262
263 /* certain C libraries return -1 in case of truncation */
264 if (n < 0 || n > avail)
265 n = avail;
266
267 p += n;
268 /* certain C libraries do not zero-terminate in case of truncation */
269 if (p == end)
270 p[-1] = 0;
271
272 return p;
273}
274
275/* add a hex value to a bounded buffer, up to 8 digits */
276static char*
277_bprint_hex( char* p, char* end, unsigned value, int numDigits )
278{
279 char text[sizeof(unsigned)*2];
280 int nn = 0;
281
282 while (numDigits-- > 0) {
283 text[nn++] = "0123456789abcdef"[(value >> (numDigits*4)) & 15];
284 }
285 return _bprint_b(p, end, text, nn);
286}
287
288/* add the hexadecimal dump of some memory area to a bounded buffer */
289static char*
290_bprint_hexdump( char* p, char* end, const uint8_t* data, int datalen )
291{
292 int lineSize = 16;
293
294 while (datalen > 0) {
295 int avail = datalen;
296 int nn;
297
298 if (avail > lineSize)
299 avail = lineSize;
300
301 for (nn = 0; nn < avail; nn++) {
302 if (nn > 0)
303 p = _bprint_c(p, end, ' ');
304 p = _bprint_hex(p, end, data[nn], 2);
305 }
306 for ( ; nn < lineSize; nn++ ) {
307 p = _bprint_s(p, end, " ");
308 }
309 p = _bprint_s(p, end, " ");
310
311 for (nn = 0; nn < avail; nn++) {
312 int c = data[nn];
313
314 if (c < 32 || c > 127)
315 c = '.';
316
317 p = _bprint_c(p, end, c);
318 }
319 p = _bprint_c(p, end, '\n');
320
321 data += avail;
322 datalen -= avail;
323 }
324 return p;
325}
326
327/* dump the content of a query of packet to the log */
328static void
329XLOG_BYTES( const void* base, int len )
330{
331 char buff[1024];
332 char* p = buff, *end = p + sizeof(buff);
333
334 p = _bprint_hexdump(p, end, base, len);
335 XLOG("%s",buff);
336}
337
338#else /* !DEBUG */
339# define XLOG(...) ((void)0)
340# define XLOG_BYTES(a,b) ((void)0)
341#endif
342
343static time_t
344_time_now( void )
345{
346 struct timeval tv;
347
348 gettimeofday( &tv, NULL );
349 return tv.tv_sec;
350}
351
352/* reminder: the general format of a DNS packet is the following:
353 *
354 * HEADER (12 bytes)
355 * QUESTION (variable)
356 * ANSWER (variable)
357 * AUTHORITY (variable)
358 * ADDITIONNAL (variable)
359 *
360 * the HEADER is made of:
361 *
362 * ID : 16 : 16-bit unique query identification field
363 *
364 * QR : 1 : set to 0 for queries, and 1 for responses
365 * Opcode : 4 : set to 0 for queries
366 * AA : 1 : set to 0 for queries
367 * TC : 1 : truncation flag, will be set to 0 in queries
368 * RD : 1 : recursion desired
369 *
370 * RA : 1 : recursion available (0 in queries)
371 * Z : 3 : three reserved zero bits
372 * RCODE : 4 : response code (always 0=NOERROR in queries)
373 *
374 * QDCount: 16 : question count
375 * ANCount: 16 : Answer count (0 in queries)
376 * NSCount: 16: Authority Record count (0 in queries)
377 * ARCount: 16: Additionnal Record count (0 in queries)
378 *
379 * the QUESTION is made of QDCount Question Record (QRs)
380 * the ANSWER is made of ANCount RRs
381 * the AUTHORITY is made of NSCount RRs
382 * the ADDITIONNAL is made of ARCount RRs
383 *
384 * Each Question Record (QR) is made of:
385 *
386 * QNAME : variable : Query DNS NAME
387 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
388 * CLASS : 16 : class of query (IN=1)
389 *
390 * Each Resource Record (RR) is made of:
391 *
392 * NAME : variable : DNS NAME
393 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
394 * CLASS : 16 : class of query (IN=1)
395 * TTL : 32 : seconds to cache this RR (0=none)
396 * RDLENGTH: 16 : size of RDDATA in bytes
397 * RDDATA : variable : RR data (depends on TYPE)
398 *
399 * Each QNAME contains a domain name encoded as a sequence of 'labels'
400 * terminated by a zero. Each label has the following format:
401 *
402 * LEN : 8 : lenght of label (MUST be < 64)
403 * NAME : 8*LEN : label length (must exclude dots)
404 *
405 * A value of 0 in the encoding is interpreted as the 'root' domain and
406 * terminates the encoding. So 'www.android.com' will be encoded as:
407 *
408 * <3>www<7>android<3>com<0>
409 *
410 * Where <n> represents the byte with value 'n'
411 *
412 * Each NAME reflects the QNAME of the question, but has a slightly more
413 * complex encoding in order to provide message compression. This is achieved
414 * by using a 2-byte pointer, with format:
415 *
416 * TYPE : 2 : 0b11 to indicate a pointer, 0b01 and 0b10 are reserved
417 * OFFSET : 14 : offset to another part of the DNS packet
418 *
419 * The offset is relative to the start of the DNS packet and must point
420 * A pointer terminates the encoding.
421 *
422 * The NAME can be encoded in one of the following formats:
423 *
424 * - a sequence of simple labels terminated by 0 (like QNAMEs)
425 * - a single pointer
426 * - a sequence of simple labels terminated by a pointer
427 *
428 * A pointer shall always point to either a pointer of a sequence of
429 * labels (which can themselves be terminated by either a 0 or a pointer)
430 *
431 * The expanded length of a given domain name should not exceed 255 bytes.
432 *
433 * NOTE: we don't parse the answer packets, so don't need to deal with NAME
434 * records, only QNAMEs.
435 */
436
437#define DNS_HEADER_SIZE 12
438
439#define DNS_TYPE_A "\00\01" /* big-endian decimal 1 */
440#define DNS_TYPE_PTR "\00\014" /* big-endian decimal 12 */
441#define DNS_TYPE_MX "\00\017" /* big-endian decimal 15 */
442#define DNS_TYPE_AAAA "\00\034" /* big-endian decimal 28 */
443#define DNS_TYPE_ALL "\00\0377" /* big-endian decimal 255 */
444
445#define DNS_CLASS_IN "\00\01" /* big-endian decimal 1 */
446
447typedef struct {
448 const uint8_t* base;
449 const uint8_t* end;
450 const uint8_t* cursor;
451} DnsPacket;
452
453static void
454_dnsPacket_init( DnsPacket* packet, const uint8_t* buff, int bufflen )
455{
456 packet->base = buff;
457 packet->end = buff + bufflen;
458 packet->cursor = buff;
459}
460
461static void
462_dnsPacket_rewind( DnsPacket* packet )
463{
464 packet->cursor = packet->base;
465}
466
467static void
468_dnsPacket_skip( DnsPacket* packet, int count )
469{
470 const uint8_t* p = packet->cursor + count;
471
472 if (p > packet->end)
473 p = packet->end;
474
475 packet->cursor = p;
476}
477
478static int
479_dnsPacket_readInt16( DnsPacket* packet )
480{
481 const uint8_t* p = packet->cursor;
482
483 if (p+2 > packet->end)
484 return -1;
485
486 packet->cursor = p+2;
487 return (p[0]<< 8) | p[1];
488}
489
490/** QUERY CHECKING
491 **/
492
493/* check bytes in a dns packet. returns 1 on success, 0 on failure.
494 * the cursor is only advanced in the case of success
495 */
496static int
497_dnsPacket_checkBytes( DnsPacket* packet, int numBytes, const void* bytes )
498{
499 const uint8_t* p = packet->cursor;
500
501 if (p + numBytes > packet->end)
502 return 0;
503
504 if (memcmp(p, bytes, numBytes) != 0)
505 return 0;
506
507 packet->cursor = p + numBytes;
508 return 1;
509}
510
511/* parse and skip a given QNAME stored in a query packet,
512 * from the current cursor position. returns 1 on success,
513 * or 0 for malformed data.
514 */
515static int
516_dnsPacket_checkQName( DnsPacket* packet )
517{
518 const uint8_t* p = packet->cursor;
519 const uint8_t* end = packet->end;
520
521 for (;;) {
522 int c;
523
524 if (p >= end)
525 break;
526
527 c = *p++;
528
529 if (c == 0) {
530 packet->cursor = p;
531 return 1;
532 }
533
534 /* we don't expect label compression in QNAMEs */
535 if (c >= 64)
536 break;
537
538 p += c;
539 /* we rely on the bound check at the start
540 * of the loop here */
541 }
542 /* malformed data */
543 XLOG("malformed QNAME");
544 return 0;
545}
546
547/* parse and skip a given QR stored in a packet.
548 * returns 1 on success, and 0 on failure
549 */
550static int
551_dnsPacket_checkQR( DnsPacket* packet )
552{
553 int len;
554
555 if (!_dnsPacket_checkQName(packet))
556 return 0;
557
558 /* TYPE must be one of the things we support */
559 if (!_dnsPacket_checkBytes(packet, 2, DNS_TYPE_A) &&
560 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_PTR) &&
561 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_MX) &&
562 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_AAAA) &&
563 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_ALL))
564 {
565 XLOG("unsupported TYPE");
566 return 0;
567 }
568 /* CLASS must be IN */
569 if (!_dnsPacket_checkBytes(packet, 2, DNS_CLASS_IN)) {
570 XLOG("unsupported CLASS");
571 return 0;
572 }
573
574 return 1;
575}
576
577/* check the header of a DNS Query packet, return 1 if it is one
578 * type of query we can cache, or 0 otherwise
579 */
580static int
581_dnsPacket_checkQuery( DnsPacket* packet )
582{
583 const uint8_t* p = packet->base;
584 int qdCount, anCount, dnCount, arCount;
585
586 if (p + DNS_HEADER_SIZE > packet->end) {
587 XLOG("query packet too small");
588 return 0;
589 }
590
591 /* QR must be set to 0, opcode must be 0 and AA must be 0 */
592 /* RA, Z, and RCODE must be 0 */
593 if ((p[2] & 0xFC) != 0 || p[3] != 0) {
594 XLOG("query packet flags unsupported");
595 return 0;
596 }
597
598 /* Note that we ignore the TC and RD bits here for the
599 * following reasons:
600 *
601 * - there is no point for a query packet sent to a server
602 * to have the TC bit set, but the implementation might
603 * set the bit in the query buffer for its own needs
604 * between a _resolv_cache_lookup and a
605 * _resolv_cache_add. We should not freak out if this
606 * is the case.
607 *
608 * - we consider that the result from a RD=0 or a RD=1
609 * query might be different, hence that the RD bit
610 * should be used to differentiate cached result.
611 *
612 * this implies that RD is checked when hashing or
613 * comparing query packets, but not TC
614 */
615
616 /* ANCOUNT, DNCOUNT and ARCOUNT must be 0 */
617 qdCount = (p[4] << 8) | p[5];
618 anCount = (p[6] << 8) | p[7];
619 dnCount = (p[8] << 8) | p[9];
620 arCount = (p[10]<< 8) | p[11];
621
622 if (anCount != 0 || dnCount != 0 || arCount != 0) {
623 XLOG("query packet contains non-query records");
624 return 0;
625 }
626
627 if (qdCount == 0) {
628 XLOG("query packet doesn't contain query record");
629 return 0;
630 }
631
632 /* Check QDCOUNT QRs */
633 packet->cursor = p + DNS_HEADER_SIZE;
634
635 for (;qdCount > 0; qdCount--)
636 if (!_dnsPacket_checkQR(packet))
637 return 0;
638
639 return 1;
640}
641
642/** QUERY DEBUGGING
643 **/
644#if DEBUG
645static char*
646_dnsPacket_bprintQName(DnsPacket* packet, char* bp, char* bend)
647{
648 const uint8_t* p = packet->cursor;
649 const uint8_t* end = packet->end;
650 int first = 1;
651
652 for (;;) {
653 int c;
654
655 if (p >= end)
656 break;
657
658 c = *p++;
659
660 if (c == 0) {
661 packet->cursor = p;
662 return bp;
663 }
664
665 /* we don't expect label compression in QNAMEs */
666 if (c >= 64)
667 break;
668
669 if (first)
670 first = 0;
671 else
672 bp = _bprint_c(bp, bend, '.');
673
674 bp = _bprint_b(bp, bend, (const char*)p, c);
675
676 p += c;
677 /* we rely on the bound check at the start
678 * of the loop here */
679 }
680 /* malformed data */
681 bp = _bprint_s(bp, bend, "<MALFORMED>");
682 return bp;
683}
684
685static char*
686_dnsPacket_bprintQR(DnsPacket* packet, char* p, char* end)
687{
688#define QQ(x) { DNS_TYPE_##x, #x }
689 static const struct {
690 const char* typeBytes;
691 const char* typeString;
692 } qTypes[] =
693 {
694 QQ(A), QQ(PTR), QQ(MX), QQ(AAAA), QQ(ALL),
695 { NULL, NULL }
696 };
697 int nn;
698 const char* typeString = NULL;
699
700 /* dump QNAME */
701 p = _dnsPacket_bprintQName(packet, p, end);
702
703 /* dump TYPE */
704 p = _bprint_s(p, end, " (");
705
706 for (nn = 0; qTypes[nn].typeBytes != NULL; nn++) {
707 if (_dnsPacket_checkBytes(packet, 2, qTypes[nn].typeBytes)) {
708 typeString = qTypes[nn].typeString;
709 break;
710 }
711 }
712
713 if (typeString != NULL)
714 p = _bprint_s(p, end, typeString);
715 else {
716 int typeCode = _dnsPacket_readInt16(packet);
717 p = _bprint(p, end, "UNKNOWN-%d", typeCode);
718 }
719
720 p = _bprint_c(p, end, ')');
721
722 /* skip CLASS */
723 _dnsPacket_skip(packet, 2);
724 return p;
725}
726
727/* this function assumes the packet has already been checked */
728static char*
729_dnsPacket_bprintQuery( DnsPacket* packet, char* p, char* end )
730{
731 int qdCount;
732
733 if (packet->base[2] & 0x1) {
734 p = _bprint_s(p, end, "RECURSIVE ");
735 }
736
737 _dnsPacket_skip(packet, 4);
738 qdCount = _dnsPacket_readInt16(packet);
739 _dnsPacket_skip(packet, 6);
740
741 for ( ; qdCount > 0; qdCount-- ) {
742 p = _dnsPacket_bprintQR(packet, p, end);
743 }
744 return p;
745}
746#endif
747
748
749/** QUERY HASHING SUPPORT
750 **
751 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKET HAS ALREADY
752 ** BEEN SUCCESFULLY CHECKED.
753 **/
754
755/* use 32-bit FNV hash function */
756#define FNV_MULT 16777619U
757#define FNV_BASIS 2166136261U
758
759static unsigned
760_dnsPacket_hashBytes( DnsPacket* packet, int numBytes, unsigned hash )
761{
762 const uint8_t* p = packet->cursor;
763 const uint8_t* end = packet->end;
764
765 while (numBytes > 0 && p < end) {
766 hash = hash*FNV_MULT ^ *p++;
767 }
768 packet->cursor = p;
769 return hash;
770}
771
772
773static unsigned
774_dnsPacket_hashQName( DnsPacket* packet, unsigned hash )
775{
776 const uint8_t* p = packet->cursor;
777 const uint8_t* end = packet->end;
778
779 for (;;) {
780 int c;
781
782 if (p >= end) { /* should not happen */
783 XLOG("%s: INTERNAL_ERROR: read-overflow !!\n", __FUNCTION__);
784 break;
785 }
786
787 c = *p++;
788
789 if (c == 0)
790 break;
791
792 if (c >= 64) {
793 XLOG("%s: INTERNAL_ERROR: malformed domain !!\n", __FUNCTION__);
794 break;
795 }
796 if (p + c >= end) {
797 XLOG("%s: INTERNAL_ERROR: simple label read-overflow !!\n",
798 __FUNCTION__);
799 break;
800 }
801 while (c > 0) {
802 hash = hash*FNV_MULT ^ *p++;
803 c -= 1;
804 }
805 }
806 packet->cursor = p;
807 return hash;
808}
809
810static unsigned
811_dnsPacket_hashQR( DnsPacket* packet, unsigned hash )
812{
813 int len;
814
815 hash = _dnsPacket_hashQName(packet, hash);
816 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TYPE and CLASS */
817 return hash;
818}
819
820static unsigned
821_dnsPacket_hashQuery( DnsPacket* packet )
822{
823 unsigned hash = FNV_BASIS;
824 int count;
825 _dnsPacket_rewind(packet);
826
827 /* we ignore the TC bit for reasons explained in
828 * _dnsPacket_checkQuery().
829 *
830 * however we hash the RD bit to differentiate
831 * between answers for recursive and non-recursive
832 * queries.
833 */
834 hash = hash*FNV_MULT ^ (packet->base[2] & 1);
835
836 /* assume: other flags are 0 */
837 _dnsPacket_skip(packet, 4);
838
839 /* read QDCOUNT */
840 count = _dnsPacket_readInt16(packet);
841
842 /* assume: ANcount, NScount, ARcount are 0 */
843 _dnsPacket_skip(packet, 6);
844
845 /* hash QDCOUNT QRs */
846 for ( ; count > 0; count-- )
847 hash = _dnsPacket_hashQR(packet, hash);
848
849 return hash;
850}
851
852
853/** QUERY COMPARISON
854 **
855 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKETS HAVE ALREADY
856 ** BEEN SUCCESFULLY CHECKED.
857 **/
858
859static int
860_dnsPacket_isEqualDomainName( DnsPacket* pack1, DnsPacket* pack2 )
861{
862 const uint8_t* p1 = pack1->cursor;
863 const uint8_t* end1 = pack1->end;
864 const uint8_t* p2 = pack2->cursor;
865 const uint8_t* end2 = pack2->end;
866
867 for (;;) {
868 int c1, c2;
869
870 if (p1 >= end1 || p2 >= end2) {
871 XLOG("%s: INTERNAL_ERROR: read-overflow !!\n", __FUNCTION__);
872 break;
873 }
874 c1 = *p1++;
875 c2 = *p2++;
876 if (c1 != c2)
877 break;
878
879 if (c1 == 0) {
880 pack1->cursor = p1;
881 pack2->cursor = p2;
882 return 1;
883 }
884 if (c1 >= 64) {
885 XLOG("%s: INTERNAL_ERROR: malformed domain !!\n", __FUNCTION__);
886 break;
887 }
888 if ((p1+c1 > end1) || (p2+c1 > end2)) {
889 XLOG("%s: INTERNAL_ERROR: simple label read-overflow !!\n",
890 __FUNCTION__);
891 break;
892 }
893 if (memcmp(p1, p2, c1) != 0)
894 break;
895 p1 += c1;
896 p2 += c1;
897 /* we rely on the bound checks at the start of the loop */
898 }
899 /* not the same, or one is malformed */
900 XLOG("different DN");
901 return 0;
902}
903
904static int
905_dnsPacket_isEqualBytes( DnsPacket* pack1, DnsPacket* pack2, int numBytes )
906{
907 const uint8_t* p1 = pack1->cursor;
908 const uint8_t* p2 = pack2->cursor;
909
910 if ( p1 + numBytes > pack1->end || p2 + numBytes > pack2->end )
911 return 0;
912
913 if ( memcmp(p1, p2, numBytes) != 0 )
914 return 0;
915
916 pack1->cursor += numBytes;
917 pack2->cursor += numBytes;
918 return 1;
919}
920
921static int
922_dnsPacket_isEqualQR( DnsPacket* pack1, DnsPacket* pack2 )
923{
924 /* compare domain name encoding + TYPE + CLASS */
925 if ( !_dnsPacket_isEqualDomainName(pack1, pack2) ||
926 !_dnsPacket_isEqualBytes(pack1, pack2, 2+2) )
927 return 0;
928
929 return 1;
930}
931
932static int
933_dnsPacket_isEqualQuery( DnsPacket* pack1, DnsPacket* pack2 )
934{
935 int count1, count2;
936
937 /* compare the headers, ignore most fields */
938 _dnsPacket_rewind(pack1);
939 _dnsPacket_rewind(pack2);
940
941 /* compare RD, ignore TC, see comment in _dnsPacket_checkQuery */
942 if ((pack1->base[2] & 1) != (pack2->base[2] & 1)) {
943 XLOG("different RD");
944 return 0;
945 }
946
947 /* assume: other flags are all 0 */
948 _dnsPacket_skip(pack1, 4);
949 _dnsPacket_skip(pack2, 4);
950
951 /* compare QDCOUNT */
952 count1 = _dnsPacket_readInt16(pack1);
953 count2 = _dnsPacket_readInt16(pack2);
954 if (count1 != count2 || count1 < 0) {
955 XLOG("different QDCOUNT");
956 return 0;
957 }
958
959 /* assume: ANcount, NScount and ARcount are all 0 */
960 _dnsPacket_skip(pack1, 6);
961 _dnsPacket_skip(pack2, 6);
962
963 /* compare the QDCOUNT QRs */
964 for ( ; count1 > 0; count1-- ) {
965 if (!_dnsPacket_isEqualQR(pack1, pack2)) {
966 XLOG("different QR");
967 return 0;
968 }
969 }
970 return 1;
971}
972
973/****************************************************************************/
974/****************************************************************************/
975/***** *****/
976/***** *****/
977/***** *****/
978/****************************************************************************/
979/****************************************************************************/
980
981/* cache entry. for simplicity, 'hash' and 'hlink' are inlined in this
982 * structure though they are conceptually part of the hash table.
983 *
984 * similarly, mru_next and mru_prev are part of the global MRU list
985 */
986typedef struct Entry {
987 unsigned int hash; /* hash value */
988 struct Entry* hlink; /* next in collision chain */
989 struct Entry* mru_prev;
990 struct Entry* mru_next;
991
992 const uint8_t* query;
993 int querylen;
994 const uint8_t* answer;
995 int answerlen;
Mattias Falk3e0c5102011-01-31 12:42:26 +0100996 time_t expires; /* time_t when the entry isn't valid any more */
997 int id; /* for debugging purpose */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800998} Entry;
999
Mattias Falk3e0c5102011-01-31 12:42:26 +01001000/**
1001 * Parse the answer records and find the smallest
1002 * TTL among the answer records.
1003 *
1004 * The returned TTL is the number of seconds to
1005 * keep the answer in the cache.
1006 *
1007 * In case of parse error zero (0) is returned which
1008 * indicates that the answer shall not be cached.
1009 */
1010static u_long
1011answer_getTTL(const void* answer, int answerlen)
1012{
1013 ns_msg handle;
1014 int ancount, n;
1015 u_long result, ttl;
1016 ns_rr rr;
1017
1018 result = 0;
1019 if (ns_initparse(answer, answerlen, &handle) >= 0) {
1020 // get number of answer records
1021 ancount = ns_msg_count(handle, ns_s_an);
1022 for (n = 0; n < ancount; n++) {
1023 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
1024 ttl = ns_rr_ttl(rr);
1025 if (n == 0 || ttl < result) {
1026 result = ttl;
1027 }
1028 } else {
1029 XLOG("ns_parserr failed ancount no = %d. errno = %s\n", n, strerror(errno));
1030 }
1031 }
1032 } else {
1033 XLOG("ns_parserr failed. %s\n", strerror(errno));
1034 }
1035
1036 XLOG("TTL = %d\n", result);
1037
1038 return result;
1039}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001040
1041static void
1042entry_free( Entry* e )
1043{
1044 /* everything is allocated in a single memory block */
1045 if (e) {
1046 free(e);
1047 }
1048}
1049
1050static __inline__ void
1051entry_mru_remove( Entry* e )
1052{
1053 e->mru_prev->mru_next = e->mru_next;
1054 e->mru_next->mru_prev = e->mru_prev;
1055}
1056
1057static __inline__ void
1058entry_mru_add( Entry* e, Entry* list )
1059{
1060 Entry* first = list->mru_next;
1061
1062 e->mru_next = first;
1063 e->mru_prev = list;
1064
1065 list->mru_next = e;
1066 first->mru_prev = e;
1067}
1068
1069/* compute the hash of a given entry, this is a hash of most
1070 * data in the query (key) */
1071static unsigned
1072entry_hash( const Entry* e )
1073{
1074 DnsPacket pack[1];
1075
1076 _dnsPacket_init(pack, e->query, e->querylen);
1077 return _dnsPacket_hashQuery(pack);
1078}
1079
1080/* initialize an Entry as a search key, this also checks the input query packet
1081 * returns 1 on success, or 0 in case of unsupported/malformed data */
1082static int
1083entry_init_key( Entry* e, const void* query, int querylen )
1084{
1085 DnsPacket pack[1];
1086
1087 memset(e, 0, sizeof(*e));
1088
1089 e->query = query;
1090 e->querylen = querylen;
1091 e->hash = entry_hash(e);
1092
1093 _dnsPacket_init(pack, query, querylen);
1094
1095 return _dnsPacket_checkQuery(pack);
1096}
1097
1098/* allocate a new entry as a cache node */
1099static Entry*
1100entry_alloc( const Entry* init, const void* answer, int answerlen )
1101{
1102 Entry* e;
1103 int size;
1104
1105 size = sizeof(*e) + init->querylen + answerlen;
1106 e = calloc(size, 1);
1107 if (e == NULL)
1108 return e;
1109
1110 e->hash = init->hash;
1111 e->query = (const uint8_t*)(e+1);
1112 e->querylen = init->querylen;
1113
1114 memcpy( (char*)e->query, init->query, e->querylen );
1115
1116 e->answer = e->query + e->querylen;
1117 e->answerlen = answerlen;
1118
1119 memcpy( (char*)e->answer, answer, e->answerlen );
1120
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001121 return e;
1122}
1123
1124static int
1125entry_equals( const Entry* e1, const Entry* e2 )
1126{
1127 DnsPacket pack1[1], pack2[1];
1128
1129 if (e1->querylen != e2->querylen) {
1130 return 0;
1131 }
1132 _dnsPacket_init(pack1, e1->query, e1->querylen);
1133 _dnsPacket_init(pack2, e2->query, e2->querylen);
1134
1135 return _dnsPacket_isEqualQuery(pack1, pack2);
1136}
1137
1138/****************************************************************************/
1139/****************************************************************************/
1140/***** *****/
1141/***** *****/
1142/***** *****/
1143/****************************************************************************/
1144/****************************************************************************/
1145
1146/* We use a simple hash table with external collision lists
1147 * for simplicity, the hash-table fields 'hash' and 'hlink' are
1148 * inlined in the Entry structure.
1149 */
1150#define MAX_HASH_ENTRIES (2*CONFIG_MAX_ENTRIES)
1151
1152typedef struct resolv_cache {
1153 int num_entries;
1154 Entry mru_list;
1155 pthread_mutex_t lock;
1156 unsigned generation;
1157 int last_id;
1158 Entry* entries[ MAX_HASH_ENTRIES ];
1159} Cache;
1160
1161
1162#define HTABLE_VALID(x) ((x) != NULL && (x) != HTABLE_DELETED)
1163
1164static void
1165_cache_flush_locked( Cache* cache )
1166{
1167 int nn;
1168 time_t now = _time_now();
1169
1170 for (nn = 0; nn < MAX_HASH_ENTRIES; nn++)
1171 {
1172 Entry** pnode = &cache->entries[nn];
1173
1174 while (*pnode != NULL) {
1175 Entry* node = *pnode;
1176 *pnode = node->hlink;
1177 entry_free(node);
1178 }
1179 }
1180
1181 cache->mru_list.mru_next = cache->mru_list.mru_prev = &cache->mru_list;
1182 cache->num_entries = 0;
1183 cache->last_id = 0;
1184
1185 XLOG("*************************\n"
1186 "*** DNS CACHE FLUSHED ***\n"
1187 "*************************");
1188}
1189
Jim Huang7cc56662010-10-15 02:02:57 +08001190static struct resolv_cache*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001191_resolv_cache_create( void )
1192{
1193 struct resolv_cache* cache;
1194
1195 cache = calloc(sizeof(*cache), 1);
1196 if (cache) {
1197 cache->generation = ~0U;
1198 pthread_mutex_init( &cache->lock, NULL );
1199 cache->mru_list.mru_prev = cache->mru_list.mru_next = &cache->mru_list;
1200 XLOG("%s: cache created\n", __FUNCTION__);
1201 }
1202 return cache;
1203}
1204
1205
1206#if DEBUG
1207static void
1208_dump_query( const uint8_t* query, int querylen )
1209{
1210 char temp[256], *p=temp, *end=p+sizeof(temp);
1211 DnsPacket pack[1];
1212
1213 _dnsPacket_init(pack, query, querylen);
1214 p = _dnsPacket_bprintQuery(pack, p, end);
1215 XLOG("QUERY: %s", temp);
1216}
1217
1218static void
1219_cache_dump_mru( Cache* cache )
1220{
1221 char temp[512], *p=temp, *end=p+sizeof(temp);
1222 Entry* e;
1223
1224 p = _bprint(temp, end, "MRU LIST (%2d): ", cache->num_entries);
1225 for (e = cache->mru_list.mru_next; e != &cache->mru_list; e = e->mru_next)
1226 p = _bprint(p, end, " %d", e->id);
1227
1228 XLOG("%s", temp);
1229}
Mattias Falk3e0c5102011-01-31 12:42:26 +01001230
1231static void
1232_dump_answer(const void* answer, int answerlen)
1233{
1234 res_state statep;
1235 FILE* fp;
1236 char* buf;
1237 int fileLen;
1238
1239 fp = fopen("/data/reslog.txt", "w+");
1240 if (fp != NULL) {
1241 statep = __res_get_state();
1242
1243 res_pquery(statep, answer, answerlen, fp);
1244
1245 //Get file length
1246 fseek(fp, 0, SEEK_END);
1247 fileLen=ftell(fp);
1248 fseek(fp, 0, SEEK_SET);
1249 buf = (char *)malloc(fileLen+1);
1250 if (buf != NULL) {
1251 //Read file contents into buffer
1252 fread(buf, fileLen, 1, fp);
1253 XLOG("%s\n", buf);
1254 free(buf);
1255 }
1256 fclose(fp);
1257 remove("/data/reslog.txt");
1258 }
1259 else {
1260 XLOG("_dump_answer: can't open file\n");
1261 }
1262}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001263#endif
1264
1265#if DEBUG
1266# define XLOG_QUERY(q,len) _dump_query((q), (len))
Mattias Falk3e0c5102011-01-31 12:42:26 +01001267# define XLOG_ANSWER(a, len) _dump_answer((a), (len))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001268#else
1269# define XLOG_QUERY(q,len) ((void)0)
Mattias Falk3e0c5102011-01-31 12:42:26 +01001270# define XLOG_ANSWER(a,len) ((void)0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001271#endif
1272
1273/* This function tries to find a key within the hash table
1274 * In case of success, it will return a *pointer* to the hashed key.
1275 * In case of failure, it will return a *pointer* to NULL
1276 *
1277 * So, the caller must check '*result' to check for success/failure.
1278 *
1279 * The main idea is that the result can later be used directly in
1280 * calls to _resolv_cache_add or _resolv_cache_remove as the 'lookup'
1281 * parameter. This makes the code simpler and avoids re-searching
1282 * for the key position in the htable.
1283 *
1284 * The result of a lookup_p is only valid until you alter the hash
1285 * table.
1286 */
1287static Entry**
1288_cache_lookup_p( Cache* cache,
1289 Entry* key )
1290{
1291 int index = key->hash % MAX_HASH_ENTRIES;
1292 Entry** pnode = &cache->entries[ key->hash % MAX_HASH_ENTRIES ];
1293
1294 while (*pnode != NULL) {
1295 Entry* node = *pnode;
1296
1297 if (node == NULL)
1298 break;
1299
1300 if (node->hash == key->hash && entry_equals(node, key))
1301 break;
1302
1303 pnode = &node->hlink;
1304 }
1305 return pnode;
1306}
1307
1308/* Add a new entry to the hash table. 'lookup' must be the
1309 * result of an immediate previous failed _lookup_p() call
1310 * (i.e. with *lookup == NULL), and 'e' is the pointer to the
1311 * newly created entry
1312 */
1313static void
1314_cache_add_p( Cache* cache,
1315 Entry** lookup,
1316 Entry* e )
1317{
1318 *lookup = e;
1319 e->id = ++cache->last_id;
1320 entry_mru_add(e, &cache->mru_list);
1321 cache->num_entries += 1;
1322
1323 XLOG("%s: entry %d added (count=%d)", __FUNCTION__,
1324 e->id, cache->num_entries);
1325}
1326
1327/* Remove an existing entry from the hash table,
1328 * 'lookup' must be the result of an immediate previous
1329 * and succesful _lookup_p() call.
1330 */
1331static void
1332_cache_remove_p( Cache* cache,
1333 Entry** lookup )
1334{
1335 Entry* e = *lookup;
1336
1337 XLOG("%s: entry %d removed (count=%d)", __FUNCTION__,
1338 e->id, cache->num_entries-1);
1339
1340 entry_mru_remove(e);
1341 *lookup = e->hlink;
1342 entry_free(e);
1343 cache->num_entries -= 1;
1344}
1345
1346/* Remove the oldest entry from the hash table.
1347 */
1348static void
1349_cache_remove_oldest( Cache* cache )
1350{
1351 Entry* oldest = cache->mru_list.mru_prev;
1352 Entry** lookup = _cache_lookup_p(cache, oldest);
1353
1354 if (*lookup == NULL) { /* should not happen */
1355 XLOG("%s: OLDEST NOT IN HTABLE ?", __FUNCTION__);
1356 return;
1357 }
1358 _cache_remove_p(cache, lookup);
1359}
1360
1361
1362ResolvCacheStatus
1363_resolv_cache_lookup( struct resolv_cache* cache,
1364 const void* query,
1365 int querylen,
1366 void* answer,
1367 int answersize,
1368 int *answerlen )
1369{
1370 DnsPacket pack[1];
1371 Entry key[1];
1372 int index;
1373 Entry** lookup;
1374 Entry* e;
1375 time_t now;
1376
1377 ResolvCacheStatus result = RESOLV_CACHE_NOTFOUND;
1378
1379 XLOG("%s: lookup", __FUNCTION__);
1380 XLOG_QUERY(query, querylen);
1381
1382 /* we don't cache malformed queries */
1383 if (!entry_init_key(key, query, querylen)) {
1384 XLOG("%s: unsupported query", __FUNCTION__);
1385 return RESOLV_CACHE_UNSUPPORTED;
1386 }
1387 /* lookup cache */
1388 pthread_mutex_lock( &cache->lock );
1389
1390 /* see the description of _lookup_p to understand this.
1391 * the function always return a non-NULL pointer.
1392 */
1393 lookup = _cache_lookup_p(cache, key);
1394 e = *lookup;
1395
1396 if (e == NULL) {
1397 XLOG( "NOT IN CACHE");
1398 goto Exit;
1399 }
1400
1401 now = _time_now();
1402
1403 /* remove stale entries here */
Mattias Falk3e0c5102011-01-31 12:42:26 +01001404 if (now >= e->expires) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001405 XLOG( " NOT IN CACHE (STALE ENTRY %p DISCARDED)", *lookup );
1406 _cache_remove_p(cache, lookup);
1407 goto Exit;
1408 }
1409
1410 *answerlen = e->answerlen;
1411 if (e->answerlen > answersize) {
1412 /* NOTE: we return UNSUPPORTED if the answer buffer is too short */
1413 result = RESOLV_CACHE_UNSUPPORTED;
1414 XLOG(" ANSWER TOO LONG");
1415 goto Exit;
1416 }
1417
1418 memcpy( answer, e->answer, e->answerlen );
1419
1420 /* bump up this entry to the top of the MRU list */
1421 if (e != cache->mru_list.mru_next) {
1422 entry_mru_remove( e );
1423 entry_mru_add( e, &cache->mru_list );
1424 }
1425
1426 XLOG( "FOUND IN CACHE entry=%p", e );
1427 result = RESOLV_CACHE_FOUND;
1428
1429Exit:
1430 pthread_mutex_unlock( &cache->lock );
1431 return result;
1432}
1433
1434
1435void
1436_resolv_cache_add( struct resolv_cache* cache,
1437 const void* query,
1438 int querylen,
1439 const void* answer,
1440 int answerlen )
1441{
1442 Entry key[1];
1443 Entry* e;
1444 Entry** lookup;
Mattias Falk3e0c5102011-01-31 12:42:26 +01001445 u_long ttl;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001446
1447 /* don't assume that the query has already been cached
1448 */
1449 if (!entry_init_key( key, query, querylen )) {
1450 XLOG( "%s: passed invalid query ?", __FUNCTION__);
1451 return;
1452 }
1453
1454 pthread_mutex_lock( &cache->lock );
1455
1456 XLOG( "%s: query:", __FUNCTION__ );
1457 XLOG_QUERY(query,querylen);
Mattias Falk3e0c5102011-01-31 12:42:26 +01001458 XLOG_ANSWER(answer, answerlen);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001459#if DEBUG_DATA
1460 XLOG( "answer:");
1461 XLOG_BYTES(answer,answerlen);
1462#endif
1463
1464 lookup = _cache_lookup_p(cache, key);
1465 e = *lookup;
1466
1467 if (e != NULL) { /* should not happen */
1468 XLOG("%s: ALREADY IN CACHE (%p) ? IGNORING ADD",
1469 __FUNCTION__, e);
1470 goto Exit;
1471 }
1472
1473 if (cache->num_entries >= CONFIG_MAX_ENTRIES) {
1474 _cache_remove_oldest(cache);
1475 /* need to lookup again */
1476 lookup = _cache_lookup_p(cache, key);
1477 e = *lookup;
1478 if (e != NULL) {
1479 XLOG("%s: ALREADY IN CACHE (%p) ? IGNORING ADD",
1480 __FUNCTION__, e);
1481 goto Exit;
1482 }
1483 }
1484
Mattias Falk3e0c5102011-01-31 12:42:26 +01001485 ttl = answer_getTTL(answer, answerlen);
1486 if (ttl > 0) {
1487 e = entry_alloc(key, answer, answerlen);
1488 if (e != NULL) {
1489 e->expires = ttl + _time_now();
1490 _cache_add_p(cache, lookup, e);
1491 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001492 }
1493#if DEBUG
1494 _cache_dump_mru(cache);
1495#endif
1496Exit:
1497 pthread_mutex_unlock( &cache->lock );
1498}
1499
1500/****************************************************************************/
1501/****************************************************************************/
1502/***** *****/
1503/***** *****/
1504/***** *****/
1505/****************************************************************************/
1506/****************************************************************************/
1507
1508static struct resolv_cache* _res_cache;
1509static pthread_once_t _res_cache_once;
1510
1511static void
1512_res_cache_init( void )
1513{
1514 const char* env = getenv(CONFIG_ENV);
1515
1516 if (env && atoi(env) == 0) {
1517 /* the cache is disabled */
1518 return;
1519 }
1520
1521 _res_cache = _resolv_cache_create();
1522}
1523
1524
1525struct resolv_cache*
1526__get_res_cache( void )
1527{
1528 pthread_once( &_res_cache_once, _res_cache_init );
1529 return _res_cache;
1530}
1531
1532void
1533_resolv_cache_reset( unsigned generation )
1534{
1535 XLOG("%s: generation=%d", __FUNCTION__, generation);
1536
1537 if (_res_cache == NULL)
1538 return;
1539
1540 pthread_mutex_lock( &_res_cache->lock );
1541 if (_res_cache->generation != generation) {
1542 _cache_flush_locked(_res_cache);
1543 _res_cache->generation = generation;
1544 }
1545 pthread_mutex_unlock( &_res_cache->lock );
1546}