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