blob: d0673ef47cf2c359db28dd32b982d5fb7ec254e6 [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"
Pierre Imai97c9d732016-04-18 12:00:12 +090030
Mattias Falk23d3e6b2011-04-04 16:12:35 +020031#include <resolv.h>
Lorenzo Colitti616344d2014-11-28 11:47:13 +090032#include <stdarg.h>
33#include <stdio.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080034#include <stdlib.h>
35#include <string.h>
36#include <time.h>
37#include "pthread.h"
38
Mattias Falk3e0c5102011-01-31 12:42:26 +010039#include <errno.h>
Calin Juravle569fb982014-03-04 15:01:29 +000040#include <arpa/nameser.h>
Mattias Falk23d3e6b2011-04-04 16:12:35 +020041#include <net/if.h>
42#include <netdb.h>
43#include <linux/if.h>
44
45#include <arpa/inet.h>
46#include "resolv_private.h"
Szymon Jakubczakea9bf672014-02-14 17:07:23 -050047#include "resolv_netid.h"
Mattias Falkc63e5902011-08-23 14:34:14 +020048#include "res_private.h"
Mattias Falk3e0c5102011-01-31 12:42:26 +010049
Christopher Ferris7a3681e2017-04-24 17:48:32 -070050#include <async_safe/log.h>
Lorenzo Colitti616344d2014-11-28 11:47:13 +090051
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080052/* This code implements a small and *simple* DNS resolver cache.
53 *
Mattias Falk3e0c5102011-01-31 12:42:26 +010054 * It is only used to cache DNS answers for a time defined by the smallest TTL
55 * among the answer records in order to reduce DNS traffic. It is not supposed
56 * to be a full DNS cache, since we plan to implement that in the future in a
57 * dedicated process running on the system.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080058 *
59 * Note that its design is kept simple very intentionally, i.e.:
60 *
61 * - it takes raw DNS query packet data as input, and returns raw DNS
62 * answer packet data as output
63 *
64 * (this means that two similar queries that encode the DNS name
65 * differently will be treated distinctly).
66 *
Mattias Falk3e0c5102011-01-31 12:42:26 +010067 * the smallest TTL value among the answer records are used as the time
68 * to keep an answer in the cache.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080069 *
70 * this is bad, but we absolutely want to avoid parsing the answer packets
71 * (and should be solved by the later full DNS cache process).
72 *
73 * - the implementation is just a (query-data) => (answer-data) hash table
74 * with a trivial least-recently-used expiration policy.
75 *
76 * Doing this keeps the code simple and avoids to deal with a lot of things
77 * that a full DNS cache is expected to do.
78 *
79 * The API is also very simple:
80 *
81 * - the client calls _resolv_cache_get() to obtain a handle to the cache.
82 * this will initialize the cache on first usage. the result can be NULL
83 * if the cache is disabled.
84 *
85 * - the client calls _resolv_cache_lookup() before performing a query
86 *
87 * if the function returns RESOLV_CACHE_FOUND, a copy of the answer data
88 * has been copied into the client-provided answer buffer.
89 *
90 * if the function returns RESOLV_CACHE_NOTFOUND, the client should perform
91 * a request normally, *then* call _resolv_cache_add() to add the received
92 * answer to the cache.
93 *
94 * if the function returns RESOLV_CACHE_UNSUPPORTED, the client should
95 * perform a request normally, and *not* call _resolv_cache_add()
96 *
97 * note that RESOLV_CACHE_UNSUPPORTED is also returned if the answer buffer
98 * is too short to accomodate the cached result.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080099 */
100
Mattias Falk3a4910c2011-02-14 12:41:11 +0100101/* default number of entries kept in the cache. This value has been
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800102 * determined by browsing through various sites and counting the number
103 * of corresponding requests. Keep in mind that our framework is currently
104 * performing two requests per name lookup (one for IPv4, the other for IPv6)
105 *
106 * www.google.com 4
107 * www.ysearch.com 6
108 * www.amazon.com 8
109 * www.nytimes.com 22
110 * www.espn.com 28
111 * www.msn.com 28
112 * www.lemonde.fr 35
113 *
114 * (determined in 2009-2-17 from Paris, France, results may vary depending
115 * on location)
116 *
117 * most high-level websites use lots of media/ad servers with different names
118 * but these are generally reused when browsing through the site.
119 *
Mattias Falk3a4910c2011-02-14 12:41:11 +0100120 * As such, a value of 64 should be relatively comfortable at the moment.
121 *
Robert Greenwalt52764f52012-01-25 15:16:03 -0800122 * ******************************************
123 * * NOTE - this has changed.
124 * * 1) we've added IPv6 support so each dns query results in 2 responses
125 * * 2) we've made this a system-wide cache, so the cost is less (it's not
126 * * duplicated in each process) and the need is greater (more processes
127 * * making different requests).
128 * * Upping by 2x for IPv6
129 * * Upping by another 5x for the centralized nature
130 * *****************************************
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800131 */
Robert Greenwalt52764f52012-01-25 15:16:03 -0800132#define CONFIG_MAX_ENTRIES 64 * 2 * 5
Mattias Falk3a4910c2011-02-14 12:41:11 +0100133
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800134/****************************************************************************/
135/****************************************************************************/
136/***** *****/
137/***** *****/
138/***** *****/
139/****************************************************************************/
140/****************************************************************************/
141
142/* set to 1 to debug cache operations */
143#define DEBUG 0
144
145/* set to 1 to debug query data */
146#define DEBUG_DATA 0
147
148#if DEBUG
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900149#define __DEBUG__
150#else
151#define __DEBUG__ __attribute__((unused))
152#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800153
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900154#undef XLOG
155
156#define XLOG(...) ({ \
157 if (DEBUG) { \
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700158 async_safe_format_log(ANDROID_LOG_DEBUG,"libc",__VA_ARGS__); \
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900159 } else { \
160 ((void)0); \
161 } \
162})
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800163
164/** BOUNDED BUFFER FORMATTING
165 **/
166
167/* technical note:
168 *
169 * the following debugging routines are used to append data to a bounded
170 * buffer they take two parameters that are:
171 *
172 * - p : a pointer to the current cursor position in the buffer
173 * this value is initially set to the buffer's address.
174 *
175 * - end : the address of the buffer's limit, i.e. of the first byte
176 * after the buffer. this address should never be touched.
177 *
178 * IMPORTANT: it is assumed that end > buffer_address, i.e.
179 * that the buffer is at least one byte.
180 *
181 * the _bprint_() functions return the new value of 'p' after the data
182 * has been appended, and also ensure the following:
183 *
184 * - the returned value will never be strictly greater than 'end'
185 *
186 * - a return value equal to 'end' means that truncation occured
187 * (in which case, end[-1] will be set to 0)
188 *
189 * - after returning from a _bprint_() function, the content of the buffer
190 * is always 0-terminated, even in the event of truncation.
191 *
192 * these conventions allow you to call _bprint_ functions multiple times and
193 * only check for truncation at the end of the sequence, as in:
194 *
195 * char buff[1000], *p = buff, *end = p + sizeof(buff);
196 *
197 * p = _bprint_c(p, end, '"');
198 * p = _bprint_s(p, end, my_string);
199 * p = _bprint_c(p, end, '"');
200 *
201 * if (p >= end) {
202 * // buffer was too small
203 * }
204 *
205 * printf( "%s", buff );
206 */
207
208/* add a char to a bounded buffer */
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900209char*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800210_bprint_c( char* p, char* end, int c )
211{
212 if (p < end) {
213 if (p+1 == end)
214 *p++ = 0;
215 else {
216 *p++ = (char) c;
217 *p = 0;
218 }
219 }
220 return p;
221}
222
223/* add a sequence of bytes to a bounded buffer */
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900224char*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800225_bprint_b( char* p, char* end, const char* buf, int len )
226{
227 int avail = end - p;
228
229 if (avail <= 0 || len <= 0)
230 return p;
231
232 if (avail > len)
233 avail = len;
234
235 memcpy( p, buf, avail );
236 p += avail;
237
238 if (p < end)
239 p[0] = 0;
240 else
241 end[-1] = 0;
242
243 return p;
244}
245
246/* add a string to a bounded buffer */
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900247char*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800248_bprint_s( char* p, char* end, const char* str )
249{
250 return _bprint_b(p, end, str, strlen(str));
251}
252
253/* add a formatted string to a bounded buffer */
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900254char* _bprint( char* p, char* end, const char* format, ... ) __DEBUG__;
255char* _bprint( char* p, char* end, const char* format, ... )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800256{
257 int avail, n;
258 va_list args;
259
260 avail = end - p;
261
262 if (avail <= 0)
263 return p;
264
265 va_start(args, format);
David 'Digit' Turnerd378c682010-03-08 15:13:04 -0800266 n = vsnprintf( p, avail, format, args);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800267 va_end(args);
268
269 /* certain C libraries return -1 in case of truncation */
270 if (n < 0 || n > avail)
271 n = avail;
272
273 p += n;
274 /* certain C libraries do not zero-terminate in case of truncation */
275 if (p == end)
276 p[-1] = 0;
277
278 return p;
279}
280
281/* add a hex value to a bounded buffer, up to 8 digits */
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900282char*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800283_bprint_hex( char* p, char* end, unsigned value, int numDigits )
284{
285 char text[sizeof(unsigned)*2];
286 int nn = 0;
287
288 while (numDigits-- > 0) {
289 text[nn++] = "0123456789abcdef"[(value >> (numDigits*4)) & 15];
290 }
291 return _bprint_b(p, end, text, nn);
292}
293
294/* add the hexadecimal dump of some memory area to a bounded buffer */
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900295char*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800296_bprint_hexdump( char* p, char* end, const uint8_t* data, int datalen )
297{
298 int lineSize = 16;
299
300 while (datalen > 0) {
301 int avail = datalen;
302 int nn;
303
304 if (avail > lineSize)
305 avail = lineSize;
306
307 for (nn = 0; nn < avail; nn++) {
308 if (nn > 0)
309 p = _bprint_c(p, end, ' ');
310 p = _bprint_hex(p, end, data[nn], 2);
311 }
312 for ( ; nn < lineSize; nn++ ) {
313 p = _bprint_s(p, end, " ");
314 }
315 p = _bprint_s(p, end, " ");
316
317 for (nn = 0; nn < avail; nn++) {
318 int c = data[nn];
319
320 if (c < 32 || c > 127)
321 c = '.';
322
323 p = _bprint_c(p, end, c);
324 }
325 p = _bprint_c(p, end, '\n');
326
327 data += avail;
328 datalen -= avail;
329 }
330 return p;
331}
332
333/* dump the content of a query of packet to the log */
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900334void XLOG_BYTES( const void* base, int len ) __DEBUG__;
335void XLOG_BYTES( const void* base, int len )
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800336{
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900337 if (DEBUG_DATA) {
338 char buff[1024];
339 char* p = buff, *end = p + sizeof(buff);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800340
Lorenzo Colitti616344d2014-11-28 11:47:13 +0900341 p = _bprint_hexdump(p, end, base, len);
342 XLOG("%s",buff);
343 }
344} __DEBUG__
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800345
346static time_t
347_time_now( void )
348{
349 struct timeval tv;
350
351 gettimeofday( &tv, NULL );
352 return tv.tv_sec;
353}
354
355/* reminder: the general format of a DNS packet is the following:
356 *
357 * HEADER (12 bytes)
358 * QUESTION (variable)
359 * ANSWER (variable)
360 * AUTHORITY (variable)
361 * ADDITIONNAL (variable)
362 *
363 * the HEADER is made of:
364 *
365 * ID : 16 : 16-bit unique query identification field
366 *
367 * QR : 1 : set to 0 for queries, and 1 for responses
368 * Opcode : 4 : set to 0 for queries
369 * AA : 1 : set to 0 for queries
370 * TC : 1 : truncation flag, will be set to 0 in queries
371 * RD : 1 : recursion desired
372 *
373 * RA : 1 : recursion available (0 in queries)
374 * Z : 3 : three reserved zero bits
375 * RCODE : 4 : response code (always 0=NOERROR in queries)
376 *
377 * QDCount: 16 : question count
378 * ANCount: 16 : Answer count (0 in queries)
379 * NSCount: 16: Authority Record count (0 in queries)
380 * ARCount: 16: Additionnal Record count (0 in queries)
381 *
382 * the QUESTION is made of QDCount Question Record (QRs)
383 * the ANSWER is made of ANCount RRs
384 * the AUTHORITY is made of NSCount RRs
385 * the ADDITIONNAL is made of ARCount RRs
386 *
387 * Each Question Record (QR) is made of:
388 *
389 * QNAME : variable : Query DNS NAME
390 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
391 * CLASS : 16 : class of query (IN=1)
392 *
393 * Each Resource Record (RR) is made of:
394 *
395 * NAME : variable : DNS NAME
396 * TYPE : 16 : type of query (A=1, PTR=12, MX=15, AAAA=28, ALL=255)
397 * CLASS : 16 : class of query (IN=1)
398 * TTL : 32 : seconds to cache this RR (0=none)
399 * RDLENGTH: 16 : size of RDDATA in bytes
400 * RDDATA : variable : RR data (depends on TYPE)
401 *
402 * Each QNAME contains a domain name encoded as a sequence of 'labels'
403 * terminated by a zero. Each label has the following format:
404 *
405 * LEN : 8 : lenght of label (MUST be < 64)
406 * NAME : 8*LEN : label length (must exclude dots)
407 *
408 * A value of 0 in the encoding is interpreted as the 'root' domain and
409 * terminates the encoding. So 'www.android.com' will be encoded as:
410 *
411 * <3>www<7>android<3>com<0>
412 *
413 * Where <n> represents the byte with value 'n'
414 *
415 * Each NAME reflects the QNAME of the question, but has a slightly more
416 * complex encoding in order to provide message compression. This is achieved
417 * by using a 2-byte pointer, with format:
418 *
419 * TYPE : 2 : 0b11 to indicate a pointer, 0b01 and 0b10 are reserved
420 * OFFSET : 14 : offset to another part of the DNS packet
421 *
422 * The offset is relative to the start of the DNS packet and must point
423 * A pointer terminates the encoding.
424 *
425 * The NAME can be encoded in one of the following formats:
426 *
427 * - a sequence of simple labels terminated by 0 (like QNAMEs)
428 * - a single pointer
429 * - a sequence of simple labels terminated by a pointer
430 *
431 * A pointer shall always point to either a pointer of a sequence of
432 * labels (which can themselves be terminated by either a 0 or a pointer)
433 *
434 * The expanded length of a given domain name should not exceed 255 bytes.
435 *
436 * NOTE: we don't parse the answer packets, so don't need to deal with NAME
437 * records, only QNAMEs.
438 */
439
440#define DNS_HEADER_SIZE 12
441
442#define DNS_TYPE_A "\00\01" /* big-endian decimal 1 */
443#define DNS_TYPE_PTR "\00\014" /* big-endian decimal 12 */
444#define DNS_TYPE_MX "\00\017" /* big-endian decimal 15 */
445#define DNS_TYPE_AAAA "\00\034" /* big-endian decimal 28 */
446#define DNS_TYPE_ALL "\00\0377" /* big-endian decimal 255 */
447
448#define DNS_CLASS_IN "\00\01" /* big-endian decimal 1 */
449
450typedef struct {
451 const uint8_t* base;
452 const uint8_t* end;
453 const uint8_t* cursor;
454} DnsPacket;
455
456static void
457_dnsPacket_init( DnsPacket* packet, const uint8_t* buff, int bufflen )
458{
459 packet->base = buff;
460 packet->end = buff + bufflen;
461 packet->cursor = buff;
462}
463
464static void
465_dnsPacket_rewind( DnsPacket* packet )
466{
467 packet->cursor = packet->base;
468}
469
470static void
471_dnsPacket_skip( DnsPacket* packet, int count )
472{
473 const uint8_t* p = packet->cursor + count;
474
475 if (p > packet->end)
476 p = packet->end;
477
478 packet->cursor = p;
479}
480
481static int
482_dnsPacket_readInt16( DnsPacket* packet )
483{
484 const uint8_t* p = packet->cursor;
485
486 if (p+2 > packet->end)
487 return -1;
488
489 packet->cursor = p+2;
490 return (p[0]<< 8) | p[1];
491}
492
493/** QUERY CHECKING
494 **/
495
496/* check bytes in a dns packet. returns 1 on success, 0 on failure.
497 * the cursor is only advanced in the case of success
498 */
499static int
500_dnsPacket_checkBytes( DnsPacket* packet, int numBytes, const void* bytes )
501{
502 const uint8_t* p = packet->cursor;
503
504 if (p + numBytes > packet->end)
505 return 0;
506
507 if (memcmp(p, bytes, numBytes) != 0)
508 return 0;
509
510 packet->cursor = p + numBytes;
511 return 1;
512}
513
514/* parse and skip a given QNAME stored in a query packet,
515 * from the current cursor position. returns 1 on success,
516 * or 0 for malformed data.
517 */
518static int
519_dnsPacket_checkQName( DnsPacket* packet )
520{
521 const uint8_t* p = packet->cursor;
522 const uint8_t* end = packet->end;
523
524 for (;;) {
525 int c;
526
527 if (p >= end)
528 break;
529
530 c = *p++;
531
532 if (c == 0) {
533 packet->cursor = p;
534 return 1;
535 }
536
537 /* we don't expect label compression in QNAMEs */
538 if (c >= 64)
539 break;
540
541 p += c;
542 /* we rely on the bound check at the start
543 * of the loop here */
544 }
545 /* malformed data */
546 XLOG("malformed QNAME");
547 return 0;
548}
549
550/* parse and skip a given QR stored in a packet.
551 * returns 1 on success, and 0 on failure
552 */
553static int
554_dnsPacket_checkQR( DnsPacket* packet )
555{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800556 if (!_dnsPacket_checkQName(packet))
557 return 0;
558
559 /* TYPE must be one of the things we support */
560 if (!_dnsPacket_checkBytes(packet, 2, DNS_TYPE_A) &&
561 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_PTR) &&
562 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_MX) &&
563 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_AAAA) &&
564 !_dnsPacket_checkBytes(packet, 2, DNS_TYPE_ALL))
565 {
566 XLOG("unsupported TYPE");
567 return 0;
568 }
569 /* CLASS must be IN */
570 if (!_dnsPacket_checkBytes(packet, 2, DNS_CLASS_IN)) {
571 XLOG("unsupported CLASS");
572 return 0;
573 }
574
575 return 1;
576}
577
578/* check the header of a DNS Query packet, return 1 if it is one
579 * type of query we can cache, or 0 otherwise
580 */
581static int
582_dnsPacket_checkQuery( DnsPacket* packet )
583{
584 const uint8_t* p = packet->base;
585 int qdCount, anCount, dnCount, arCount;
586
587 if (p + DNS_HEADER_SIZE > packet->end) {
588 XLOG("query packet too small");
589 return 0;
590 }
591
592 /* QR must be set to 0, opcode must be 0 and AA must be 0 */
593 /* RA, Z, and RCODE must be 0 */
Ben Schwartz6eed8e12017-10-02 12:26:05 -0400594 if ((p[2] & 0xFC) != 0 || (p[3] & 0xCF) != 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800595 XLOG("query packet flags unsupported");
596 return 0;
597 }
598
Ben Schwartz6eed8e12017-10-02 12:26:05 -0400599 /* Note that we ignore the TC, RD, CD, and AD bits here for the
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800600 * following reasons:
601 *
602 * - there is no point for a query packet sent to a server
603 * to have the TC bit set, but the implementation might
604 * set the bit in the query buffer for its own needs
605 * between a _resolv_cache_lookup and a
606 * _resolv_cache_add. We should not freak out if this
607 * is the case.
608 *
Ben Schwartz6eed8e12017-10-02 12:26:05 -0400609 * - we consider that the result from a query might depend on
610 * the RD, AD, and CD bits, so these bits
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800611 * should be used to differentiate cached result.
612 *
Ben Schwartz6eed8e12017-10-02 12:26:05 -0400613 * this implies that these bits are checked when hashing or
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800614 * comparing query packets, but not TC
615 */
616
617 /* ANCOUNT, DNCOUNT and ARCOUNT must be 0 */
618 qdCount = (p[4] << 8) | p[5];
619 anCount = (p[6] << 8) | p[7];
620 dnCount = (p[8] << 8) | p[9];
621 arCount = (p[10]<< 8) | p[11];
622
Ben Schwartz6eed8e12017-10-02 12:26:05 -0400623 if (anCount != 0 || dnCount != 0 || arCount > 1) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800624 XLOG("query packet contains non-query records");
625 return 0;
626 }
627
628 if (qdCount == 0) {
629 XLOG("query packet doesn't contain query record");
630 return 0;
631 }
632
633 /* Check QDCOUNT QRs */
634 packet->cursor = p + DNS_HEADER_SIZE;
635
636 for (;qdCount > 0; qdCount--)
637 if (!_dnsPacket_checkQR(packet))
638 return 0;
639
640 return 1;
641}
642
643/** QUERY DEBUGGING
644 **/
645#if DEBUG
646static char*
647_dnsPacket_bprintQName(DnsPacket* packet, char* bp, char* bend)
648{
649 const uint8_t* p = packet->cursor;
650 const uint8_t* end = packet->end;
651 int first = 1;
652
653 for (;;) {
654 int c;
655
656 if (p >= end)
657 break;
658
659 c = *p++;
660
661 if (c == 0) {
662 packet->cursor = p;
663 return bp;
664 }
665
666 /* we don't expect label compression in QNAMEs */
667 if (c >= 64)
668 break;
669
670 if (first)
671 first = 0;
672 else
673 bp = _bprint_c(bp, bend, '.');
674
675 bp = _bprint_b(bp, bend, (const char*)p, c);
676
677 p += c;
678 /* we rely on the bound check at the start
679 * of the loop here */
680 }
681 /* malformed data */
682 bp = _bprint_s(bp, bend, "<MALFORMED>");
683 return bp;
684}
685
686static char*
687_dnsPacket_bprintQR(DnsPacket* packet, char* p, char* end)
688{
689#define QQ(x) { DNS_TYPE_##x, #x }
Elliott Hughes8f2a5a02013-03-15 15:30:25 -0700690 static const struct {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800691 const char* typeBytes;
Elliott Hughes8f2a5a02013-03-15 15:30:25 -0700692 const char* typeString;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800693 } qTypes[] =
694 {
695 QQ(A), QQ(PTR), QQ(MX), QQ(AAAA), QQ(ALL),
696 { NULL, NULL }
697 };
698 int nn;
699 const char* typeString = NULL;
700
701 /* dump QNAME */
702 p = _dnsPacket_bprintQName(packet, p, end);
703
704 /* dump TYPE */
705 p = _bprint_s(p, end, " (");
706
707 for (nn = 0; qTypes[nn].typeBytes != NULL; nn++) {
708 if (_dnsPacket_checkBytes(packet, 2, qTypes[nn].typeBytes)) {
709 typeString = qTypes[nn].typeString;
710 break;
711 }
712 }
713
714 if (typeString != NULL)
715 p = _bprint_s(p, end, typeString);
716 else {
717 int typeCode = _dnsPacket_readInt16(packet);
718 p = _bprint(p, end, "UNKNOWN-%d", typeCode);
719 }
720
721 p = _bprint_c(p, end, ')');
722
723 /* skip CLASS */
724 _dnsPacket_skip(packet, 2);
725 return p;
726}
727
728/* this function assumes the packet has already been checked */
729static char*
730_dnsPacket_bprintQuery( DnsPacket* packet, char* p, char* end )
731{
732 int qdCount;
733
734 if (packet->base[2] & 0x1) {
735 p = _bprint_s(p, end, "RECURSIVE ");
736 }
737
738 _dnsPacket_skip(packet, 4);
739 qdCount = _dnsPacket_readInt16(packet);
740 _dnsPacket_skip(packet, 6);
741
742 for ( ; qdCount > 0; qdCount-- ) {
743 p = _dnsPacket_bprintQR(packet, p, end);
744 }
745 return p;
746}
747#endif
748
749
750/** QUERY HASHING SUPPORT
751 **
752 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKET HAS ALREADY
753 ** BEEN SUCCESFULLY CHECKED.
754 **/
755
756/* use 32-bit FNV hash function */
757#define FNV_MULT 16777619U
758#define FNV_BASIS 2166136261U
759
760static unsigned
761_dnsPacket_hashBytes( DnsPacket* packet, int numBytes, unsigned hash )
762{
763 const uint8_t* p = packet->cursor;
764 const uint8_t* end = packet->end;
765
766 while (numBytes > 0 && p < end) {
767 hash = hash*FNV_MULT ^ *p++;
768 }
769 packet->cursor = p;
770 return hash;
771}
772
773
774static unsigned
775_dnsPacket_hashQName( DnsPacket* packet, unsigned hash )
776{
777 const uint8_t* p = packet->cursor;
778 const uint8_t* end = packet->end;
779
780 for (;;) {
781 int c;
782
783 if (p >= end) { /* should not happen */
784 XLOG("%s: INTERNAL_ERROR: read-overflow !!\n", __FUNCTION__);
785 break;
786 }
787
788 c = *p++;
789
790 if (c == 0)
791 break;
792
793 if (c >= 64) {
794 XLOG("%s: INTERNAL_ERROR: malformed domain !!\n", __FUNCTION__);
795 break;
796 }
797 if (p + c >= end) {
798 XLOG("%s: INTERNAL_ERROR: simple label read-overflow !!\n",
799 __FUNCTION__);
800 break;
801 }
802 while (c > 0) {
803 hash = hash*FNV_MULT ^ *p++;
804 c -= 1;
805 }
806 }
807 packet->cursor = p;
808 return hash;
809}
810
811static unsigned
812_dnsPacket_hashQR( DnsPacket* packet, unsigned hash )
813{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800814 hash = _dnsPacket_hashQName(packet, hash);
815 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TYPE and CLASS */
816 return hash;
817}
818
819static unsigned
Ben Schwartz6eed8e12017-10-02 12:26:05 -0400820_dnsPacket_hashRR( DnsPacket* packet, unsigned hash )
821{
822 int rdlength;
823 hash = _dnsPacket_hashQR(packet, hash);
824 hash = _dnsPacket_hashBytes(packet, 4, hash); /* TTL */
825 rdlength = _dnsPacket_readInt16(packet);
826 hash = _dnsPacket_hashBytes(packet, rdlength, hash); /* RDATA */
827 return hash;
828}
829
830static unsigned
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800831_dnsPacket_hashQuery( DnsPacket* packet )
832{
833 unsigned hash = FNV_BASIS;
Ben Schwartz6eed8e12017-10-02 12:26:05 -0400834 int count, arcount;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800835 _dnsPacket_rewind(packet);
836
Ben Schwartz6eed8e12017-10-02 12:26:05 -0400837 /* ignore the ID */
838 _dnsPacket_skip(packet, 2);
839
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800840 /* we ignore the TC bit for reasons explained in
841 * _dnsPacket_checkQuery().
842 *
843 * however we hash the RD bit to differentiate
844 * between answers for recursive and non-recursive
845 * queries.
846 */
847 hash = hash*FNV_MULT ^ (packet->base[2] & 1);
848
Ben Schwartz6eed8e12017-10-02 12:26:05 -0400849 /* mark the first header byte as processed */
850 _dnsPacket_skip(packet, 1);
851
852 /* process the second header byte */
853 hash = _dnsPacket_hashBytes(packet, 1, hash);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800854
855 /* read QDCOUNT */
856 count = _dnsPacket_readInt16(packet);
857
Ben Schwartz6eed8e12017-10-02 12:26:05 -0400858 /* assume: ANcount and NScount are 0 */
859 _dnsPacket_skip(packet, 4);
860
861 /* read ARCOUNT */
862 arcount = _dnsPacket_readInt16(packet);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800863
864 /* hash QDCOUNT QRs */
865 for ( ; count > 0; count-- )
866 hash = _dnsPacket_hashQR(packet, hash);
867
Ben Schwartz6eed8e12017-10-02 12:26:05 -0400868 /* hash ARCOUNT RRs */
869 for ( ; arcount > 0; arcount-- )
870 hash = _dnsPacket_hashRR(packet, hash);
871
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800872 return hash;
873}
874
875
876/** QUERY COMPARISON
877 **
878 ** THE FOLLOWING CODE ASSUMES THAT THE INPUT PACKETS HAVE ALREADY
879 ** BEEN SUCCESFULLY CHECKED.
880 **/
881
882static int
883_dnsPacket_isEqualDomainName( DnsPacket* pack1, DnsPacket* pack2 )
884{
885 const uint8_t* p1 = pack1->cursor;
886 const uint8_t* end1 = pack1->end;
887 const uint8_t* p2 = pack2->cursor;
888 const uint8_t* end2 = pack2->end;
889
890 for (;;) {
891 int c1, c2;
892
893 if (p1 >= end1 || p2 >= end2) {
894 XLOG("%s: INTERNAL_ERROR: read-overflow !!\n", __FUNCTION__);
895 break;
896 }
897 c1 = *p1++;
898 c2 = *p2++;
899 if (c1 != c2)
900 break;
901
902 if (c1 == 0) {
903 pack1->cursor = p1;
904 pack2->cursor = p2;
905 return 1;
906 }
907 if (c1 >= 64) {
908 XLOG("%s: INTERNAL_ERROR: malformed domain !!\n", __FUNCTION__);
909 break;
910 }
911 if ((p1+c1 > end1) || (p2+c1 > end2)) {
912 XLOG("%s: INTERNAL_ERROR: simple label read-overflow !!\n",
913 __FUNCTION__);
914 break;
915 }
916 if (memcmp(p1, p2, c1) != 0)
917 break;
918 p1 += c1;
919 p2 += c1;
920 /* we rely on the bound checks at the start of the loop */
921 }
922 /* not the same, or one is malformed */
923 XLOG("different DN");
924 return 0;
925}
926
927static int
928_dnsPacket_isEqualBytes( DnsPacket* pack1, DnsPacket* pack2, int numBytes )
929{
930 const uint8_t* p1 = pack1->cursor;
931 const uint8_t* p2 = pack2->cursor;
932
933 if ( p1 + numBytes > pack1->end || p2 + numBytes > pack2->end )
934 return 0;
935
936 if ( memcmp(p1, p2, numBytes) != 0 )
937 return 0;
938
939 pack1->cursor += numBytes;
940 pack2->cursor += numBytes;
941 return 1;
942}
943
944static int
945_dnsPacket_isEqualQR( DnsPacket* pack1, DnsPacket* pack2 )
946{
947 /* compare domain name encoding + TYPE + CLASS */
948 if ( !_dnsPacket_isEqualDomainName(pack1, pack2) ||
949 !_dnsPacket_isEqualBytes(pack1, pack2, 2+2) )
950 return 0;
951
952 return 1;
953}
954
955static int
Ben Schwartz6eed8e12017-10-02 12:26:05 -0400956_dnsPacket_isEqualRR( DnsPacket* pack1, DnsPacket* pack2 )
957{
958 int rdlength1, rdlength2;
959 /* compare query + TTL */
960 if ( !_dnsPacket_isEqualQR(pack1, pack2) ||
961 !_dnsPacket_isEqualBytes(pack1, pack2, 4) )
962 return 0;
963
964 /* compare RDATA */
965 rdlength1 = _dnsPacket_readInt16(pack1);
966 rdlength2 = _dnsPacket_readInt16(pack2);
967 if ( rdlength1 != rdlength2 ||
968 !_dnsPacket_isEqualBytes(pack1, pack2, rdlength1) )
969 return 0;
970
971 return 1;
972}
973
974static int
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800975_dnsPacket_isEqualQuery( DnsPacket* pack1, DnsPacket* pack2 )
976{
Ben Schwartz6eed8e12017-10-02 12:26:05 -0400977 int count1, count2, arcount1, arcount2;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800978
979 /* compare the headers, ignore most fields */
980 _dnsPacket_rewind(pack1);
981 _dnsPacket_rewind(pack2);
982
983 /* compare RD, ignore TC, see comment in _dnsPacket_checkQuery */
984 if ((pack1->base[2] & 1) != (pack2->base[2] & 1)) {
985 XLOG("different RD");
986 return 0;
987 }
988
Ben Schwartz6eed8e12017-10-02 12:26:05 -0400989 if (pack1->base[3] != pack2->base[3]) {
990 XLOG("different CD or AD");
991 return 0;
992 }
993
994 /* mark ID and header bytes as compared */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800995 _dnsPacket_skip(pack1, 4);
996 _dnsPacket_skip(pack2, 4);
997
998 /* compare QDCOUNT */
999 count1 = _dnsPacket_readInt16(pack1);
1000 count2 = _dnsPacket_readInt16(pack2);
1001 if (count1 != count2 || count1 < 0) {
1002 XLOG("different QDCOUNT");
1003 return 0;
1004 }
1005
Ben Schwartz6eed8e12017-10-02 12:26:05 -04001006 /* assume: ANcount and NScount are 0 */
1007 _dnsPacket_skip(pack1, 4);
1008 _dnsPacket_skip(pack2, 4);
1009
1010 /* compare ARCOUNT */
1011 arcount1 = _dnsPacket_readInt16(pack1);
1012 arcount2 = _dnsPacket_readInt16(pack2);
1013 if (arcount1 != arcount2 || arcount1 < 0) {
1014 XLOG("different ARCOUNT");
1015 return 0;
1016 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001017
1018 /* compare the QDCOUNT QRs */
1019 for ( ; count1 > 0; count1-- ) {
1020 if (!_dnsPacket_isEqualQR(pack1, pack2)) {
1021 XLOG("different QR");
1022 return 0;
1023 }
1024 }
Ben Schwartz6eed8e12017-10-02 12:26:05 -04001025
1026 /* compare the ARCOUNT RRs */
1027 for ( ; arcount1 > 0; arcount1-- ) {
1028 if (!_dnsPacket_isEqualRR(pack1, pack2)) {
1029 XLOG("different additional RR");
1030 return 0;
1031 }
1032 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001033 return 1;
1034}
1035
1036/****************************************************************************/
1037/****************************************************************************/
1038/***** *****/
1039/***** *****/
1040/***** *****/
1041/****************************************************************************/
1042/****************************************************************************/
1043
1044/* cache entry. for simplicity, 'hash' and 'hlink' are inlined in this
1045 * structure though they are conceptually part of the hash table.
1046 *
1047 * similarly, mru_next and mru_prev are part of the global MRU list
1048 */
1049typedef struct Entry {
1050 unsigned int hash; /* hash value */
1051 struct Entry* hlink; /* next in collision chain */
1052 struct Entry* mru_prev;
1053 struct Entry* mru_next;
1054
1055 const uint8_t* query;
1056 int querylen;
1057 const uint8_t* answer;
1058 int answerlen;
Mattias Falk3e0c5102011-01-31 12:42:26 +01001059 time_t expires; /* time_t when the entry isn't valid any more */
1060 int id; /* for debugging purpose */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001061} Entry;
1062
Mattias Falk3e0c5102011-01-31 12:42:26 +01001063/**
Robert Greenwalt78851f12013-01-07 12:10:06 -08001064 * Find the TTL for a negative DNS result. This is defined as the minimum
1065 * of the SOA records TTL and the MINIMUM-TTL field (RFC-2308).
1066 *
1067 * Return 0 if not found.
1068 */
1069static u_long
1070answer_getNegativeTTL(ns_msg handle) {
1071 int n, nscount;
1072 u_long result = 0;
1073 ns_rr rr;
1074
1075 nscount = ns_msg_count(handle, ns_s_ns);
1076 for (n = 0; n < nscount; n++) {
1077 if ((ns_parserr(&handle, ns_s_ns, n, &rr) == 0) && (ns_rr_type(rr) == ns_t_soa)) {
1078 const u_char *rdata = ns_rr_rdata(rr); // find the data
1079 const u_char *edata = rdata + ns_rr_rdlen(rr); // add the len to find the end
1080 int len;
1081 u_long ttl, rec_result = ns_rr_ttl(rr);
1082
1083 // find the MINIMUM-TTL field from the blob of binary data for this record
1084 // skip the server name
1085 len = dn_skipname(rdata, edata);
1086 if (len == -1) continue; // error skipping
1087 rdata += len;
1088
1089 // skip the admin name
1090 len = dn_skipname(rdata, edata);
1091 if (len == -1) continue; // error skipping
1092 rdata += len;
1093
1094 if (edata - rdata != 5*NS_INT32SZ) continue;
1095 // skip: serial number + refresh interval + retry interval + expiry
1096 rdata += NS_INT32SZ * 4;
1097 // finally read the MINIMUM TTL
1098 ttl = ns_get32(rdata);
1099 if (ttl < rec_result) {
1100 rec_result = ttl;
1101 }
1102 // Now that the record is read successfully, apply the new min TTL
1103 if (n == 0 || rec_result < result) {
1104 result = rec_result;
1105 }
1106 }
1107 }
1108 return result;
1109}
1110
1111/**
1112 * Parse the answer records and find the appropriate
1113 * smallest TTL among the records. This might be from
1114 * the answer records if found or from the SOA record
1115 * if it's a negative result.
Mattias Falk3e0c5102011-01-31 12:42:26 +01001116 *
1117 * The returned TTL is the number of seconds to
1118 * keep the answer in the cache.
1119 *
1120 * In case of parse error zero (0) is returned which
1121 * indicates that the answer shall not be cached.
1122 */
1123static u_long
1124answer_getTTL(const void* answer, int answerlen)
1125{
1126 ns_msg handle;
1127 int ancount, n;
1128 u_long result, ttl;
1129 ns_rr rr;
1130
1131 result = 0;
1132 if (ns_initparse(answer, answerlen, &handle) >= 0) {
1133 // get number of answer records
1134 ancount = ns_msg_count(handle, ns_s_an);
Robert Greenwalt78851f12013-01-07 12:10:06 -08001135
1136 if (ancount == 0) {
1137 // a response with no answers? Cache this negative result.
1138 result = answer_getNegativeTTL(handle);
1139 } else {
1140 for (n = 0; n < ancount; n++) {
1141 if (ns_parserr(&handle, ns_s_an, n, &rr) == 0) {
1142 ttl = ns_rr_ttl(rr);
1143 if (n == 0 || ttl < result) {
1144 result = ttl;
1145 }
1146 } else {
1147 XLOG("ns_parserr failed ancount no = %d. errno = %s\n", n, strerror(errno));
Mattias Falk3e0c5102011-01-31 12:42:26 +01001148 }
Mattias Falk3e0c5102011-01-31 12:42:26 +01001149 }
1150 }
1151 } else {
1152 XLOG("ns_parserr failed. %s\n", strerror(errno));
1153 }
1154
Patrick Tjina6a09492015-01-20 16:02:04 -08001155 XLOG("TTL = %lu\n", result);
Mattias Falk3e0c5102011-01-31 12:42:26 +01001156
1157 return result;
1158}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001159
1160static void
1161entry_free( Entry* e )
1162{
1163 /* everything is allocated in a single memory block */
1164 if (e) {
1165 free(e);
1166 }
1167}
1168
1169static __inline__ void
1170entry_mru_remove( Entry* e )
1171{
1172 e->mru_prev->mru_next = e->mru_next;
1173 e->mru_next->mru_prev = e->mru_prev;
1174}
1175
1176static __inline__ void
1177entry_mru_add( Entry* e, Entry* list )
1178{
1179 Entry* first = list->mru_next;
1180
1181 e->mru_next = first;
1182 e->mru_prev = list;
1183
1184 list->mru_next = e;
1185 first->mru_prev = e;
1186}
1187
1188/* compute the hash of a given entry, this is a hash of most
1189 * data in the query (key) */
1190static unsigned
1191entry_hash( const Entry* e )
1192{
1193 DnsPacket pack[1];
1194
1195 _dnsPacket_init(pack, e->query, e->querylen);
1196 return _dnsPacket_hashQuery(pack);
1197}
1198
1199/* initialize an Entry as a search key, this also checks the input query packet
1200 * returns 1 on success, or 0 in case of unsupported/malformed data */
1201static int
1202entry_init_key( Entry* e, const void* query, int querylen )
1203{
1204 DnsPacket pack[1];
1205
1206 memset(e, 0, sizeof(*e));
1207
1208 e->query = query;
1209 e->querylen = querylen;
1210 e->hash = entry_hash(e);
1211
1212 _dnsPacket_init(pack, query, querylen);
1213
1214 return _dnsPacket_checkQuery(pack);
1215}
1216
1217/* allocate a new entry as a cache node */
1218static Entry*
1219entry_alloc( const Entry* init, const void* answer, int answerlen )
1220{
1221 Entry* e;
1222 int size;
1223
1224 size = sizeof(*e) + init->querylen + answerlen;
1225 e = calloc(size, 1);
1226 if (e == NULL)
1227 return e;
1228
1229 e->hash = init->hash;
1230 e->query = (const uint8_t*)(e+1);
1231 e->querylen = init->querylen;
1232
1233 memcpy( (char*)e->query, init->query, e->querylen );
1234
1235 e->answer = e->query + e->querylen;
1236 e->answerlen = answerlen;
1237
1238 memcpy( (char*)e->answer, answer, e->answerlen );
1239
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001240 return e;
1241}
1242
1243static int
1244entry_equals( const Entry* e1, const Entry* e2 )
1245{
1246 DnsPacket pack1[1], pack2[1];
1247
1248 if (e1->querylen != e2->querylen) {
1249 return 0;
1250 }
1251 _dnsPacket_init(pack1, e1->query, e1->querylen);
1252 _dnsPacket_init(pack2, e2->query, e2->querylen);
1253
1254 return _dnsPacket_isEqualQuery(pack1, pack2);
1255}
1256
1257/****************************************************************************/
1258/****************************************************************************/
1259/***** *****/
1260/***** *****/
1261/***** *****/
1262/****************************************************************************/
1263/****************************************************************************/
1264
1265/* We use a simple hash table with external collision lists
1266 * for simplicity, the hash-table fields 'hash' and 'hlink' are
1267 * inlined in the Entry structure.
1268 */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001269
Mattias Falka59cfcf2011-09-06 15:15:06 +02001270/* Maximum time for a thread to wait for an pending request */
1271#define PENDING_REQUEST_TIMEOUT 20;
1272
1273typedef struct pending_req_info {
1274 unsigned int hash;
1275 pthread_cond_t cond;
1276 struct pending_req_info* next;
1277} PendingReqInfo;
1278
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001279typedef struct resolv_cache {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001280 int max_entries;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001281 int num_entries;
1282 Entry mru_list;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001283 int last_id;
Mattias Falk3a4910c2011-02-14 12:41:11 +01001284 Entry* entries;
Mattias Falka59cfcf2011-09-06 15:15:06 +02001285 PendingReqInfo pending_requests;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001286} Cache;
1287
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001288struct resolv_cache_info {
1289 unsigned netid;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001290 Cache* cache;
1291 struct resolv_cache_info* next;
Pierre Imaifff35672016-04-18 11:42:14 +09001292 int nscount;
1293 char* nameservers[MAXNS];
1294 struct addrinfo* nsaddrinfo[MAXNS];
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001295 int revision_id; // # times the nameservers have been replaced
1296 struct __res_params params;
Pierre Imaifff35672016-04-18 11:42:14 +09001297 struct __res_stats nsstats[MAXNS];
Pierre Imai97c9d732016-04-18 12:00:12 +09001298 char defdname[MAXDNSRCHPATH];
Mattias Falkc63e5902011-08-23 14:34:14 +02001299 int dnsrch_offset[MAXDNSRCH+1]; // offsets into defdname
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001300};
Mattias Falkc63e5902011-08-23 14:34:14 +02001301
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001302#define HTABLE_VALID(x) ((x) != NULL && (x) != HTABLE_DELETED)
1303
Paul Jensen41d9a502014-04-08 15:43:41 -04001304static pthread_once_t _res_cache_once = PTHREAD_ONCE_INIT;
1305static void _res_cache_init(void);
1306
1307// lock protecting everything in the _resolve_cache_info structs (next ptr, etc)
1308static pthread_mutex_t _res_cache_list_lock;
1309
1310/* gets cache associated with a network, or NULL if none exists */
1311static struct resolv_cache* _find_named_cache_locked(unsigned netid);
1312
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001313static void
Mattias Falka59cfcf2011-09-06 15:15:06 +02001314_cache_flush_pending_requests_locked( struct resolv_cache* cache )
1315{
1316 struct pending_req_info *ri, *tmp;
1317 if (cache) {
1318 ri = cache->pending_requests.next;
1319
1320 while (ri) {
1321 tmp = ri;
1322 ri = ri->next;
1323 pthread_cond_broadcast(&tmp->cond);
1324
1325 pthread_cond_destroy(&tmp->cond);
1326 free(tmp);
1327 }
1328
1329 cache->pending_requests.next = NULL;
1330 }
1331}
1332
Paul Jensen41d9a502014-04-08 15:43:41 -04001333/* Return 0 if no pending request is found matching the key.
1334 * If a matching request is found the calling thread will wait until
1335 * the matching request completes, then update *cache and return 1. */
Mattias Falka59cfcf2011-09-06 15:15:06 +02001336static int
Paul Jensen41d9a502014-04-08 15:43:41 -04001337_cache_check_pending_request_locked( struct resolv_cache** cache, Entry* key, unsigned netid )
Mattias Falka59cfcf2011-09-06 15:15:06 +02001338{
1339 struct pending_req_info *ri, *prev;
1340 int exist = 0;
1341
Paul Jensen41d9a502014-04-08 15:43:41 -04001342 if (*cache && key) {
1343 ri = (*cache)->pending_requests.next;
1344 prev = &(*cache)->pending_requests;
Mattias Falka59cfcf2011-09-06 15:15:06 +02001345 while (ri) {
1346 if (ri->hash == key->hash) {
1347 exist = 1;
1348 break;
1349 }
1350 prev = ri;
1351 ri = ri->next;
1352 }
1353
1354 if (!exist) {
1355 ri = calloc(1, sizeof(struct pending_req_info));
1356 if (ri) {
1357 ri->hash = key->hash;
1358 pthread_cond_init(&ri->cond, NULL);
1359 prev->next = ri;
1360 }
1361 } else {
1362 struct timespec ts = {0,0};
Mattias Falkc63e5902011-08-23 14:34:14 +02001363 XLOG("Waiting for previous request");
Mattias Falka59cfcf2011-09-06 15:15:06 +02001364 ts.tv_sec = _time_now() + PENDING_REQUEST_TIMEOUT;
Paul Jensen41d9a502014-04-08 15:43:41 -04001365 pthread_cond_timedwait(&ri->cond, &_res_cache_list_lock, &ts);
1366 /* Must update *cache as it could have been deleted. */
1367 *cache = _find_named_cache_locked(netid);
Mattias Falka59cfcf2011-09-06 15:15:06 +02001368 }
1369 }
1370
1371 return exist;
1372}
1373
1374/* notify any waiting thread that waiting on a request
1375 * matching the key has been added to the cache */
1376static void
1377_cache_notify_waiting_tid_locked( struct resolv_cache* cache, Entry* key )
1378{
1379 struct pending_req_info *ri, *prev;
1380
1381 if (cache && key) {
1382 ri = cache->pending_requests.next;
1383 prev = &cache->pending_requests;
1384 while (ri) {
1385 if (ri->hash == key->hash) {
1386 pthread_cond_broadcast(&ri->cond);
1387 break;
1388 }
1389 prev = ri;
1390 ri = ri->next;
1391 }
1392
1393 // remove item from list and destroy
1394 if (ri) {
1395 prev->next = ri->next;
1396 pthread_cond_destroy(&ri->cond);
1397 free(ri);
1398 }
1399 }
1400}
1401
1402/* notify the cache that the query failed */
1403void
Paul Jensen41d9a502014-04-08 15:43:41 -04001404_resolv_cache_query_failed( unsigned netid,
Mattias Falka59cfcf2011-09-06 15:15:06 +02001405 const void* query,
1406 int querylen)
1407{
1408 Entry key[1];
Paul Jensen41d9a502014-04-08 15:43:41 -04001409 Cache* cache;
Mattias Falka59cfcf2011-09-06 15:15:06 +02001410
Paul Jensen41d9a502014-04-08 15:43:41 -04001411 if (!entry_init_key(key, query, querylen))
1412 return;
1413
1414 pthread_mutex_lock(&_res_cache_list_lock);
1415
1416 cache = _find_named_cache_locked(netid);
1417
1418 if (cache) {
Mattias Falka59cfcf2011-09-06 15:15:06 +02001419 _cache_notify_waiting_tid_locked(cache, key);
Mattias Falka59cfcf2011-09-06 15:15:06 +02001420 }
Paul Jensen41d9a502014-04-08 15:43:41 -04001421
1422 pthread_mutex_unlock(&_res_cache_list_lock);
Mattias Falka59cfcf2011-09-06 15:15:06 +02001423}
1424
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001425static struct resolv_cache_info* _find_cache_info_locked(unsigned netid);
1426
Mattias Falka59cfcf2011-09-06 15:15:06 +02001427static void
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001428_cache_flush_locked( Cache* cache )
1429{
1430 int nn;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001431
Mattias Falk3a4910c2011-02-14 12:41:11 +01001432 for (nn = 0; nn < cache->max_entries; nn++)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001433 {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001434 Entry** pnode = (Entry**) &cache->entries[nn];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001435
1436 while (*pnode != NULL) {
1437 Entry* node = *pnode;
1438 *pnode = node->hlink;
1439 entry_free(node);
1440 }
1441 }
1442
Mattias Falka59cfcf2011-09-06 15:15:06 +02001443 // flush pending request
1444 _cache_flush_pending_requests_locked(cache);
1445
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001446 cache->mru_list.mru_next = cache->mru_list.mru_prev = &cache->mru_list;
1447 cache->num_entries = 0;
1448 cache->last_id = 0;
1449
1450 XLOG("*************************\n"
1451 "*** DNS CACHE FLUSHED ***\n"
1452 "*************************");
1453}
1454
Mattias Falk3a4910c2011-02-14 12:41:11 +01001455static int
1456_res_cache_get_max_entries( void )
1457{
Elliott Hughes908e8c22014-01-28 14:54:11 -08001458 int cache_size = CONFIG_MAX_ENTRIES;
Mattias Falk3a4910c2011-02-14 12:41:11 +01001459
Robert Greenwalt52764f52012-01-25 15:16:03 -08001460 const char* cache_mode = getenv("ANDROID_DNS_MODE");
Robert Greenwalt52764f52012-01-25 15:16:03 -08001461 if (cache_mode == NULL || strcmp(cache_mode, "local") != 0) {
Elliott Hughes908e8c22014-01-28 14:54:11 -08001462 // Don't use the cache in local mode. This is used by the proxy itself.
1463 cache_size = 0;
Robert Greenwalt52764f52012-01-25 15:16:03 -08001464 }
1465
Elliott Hughes908e8c22014-01-28 14:54:11 -08001466 XLOG("cache size: %d", cache_size);
1467 return cache_size;
Mattias Falk3a4910c2011-02-14 12:41:11 +01001468}
1469
Jim Huang7cc56662010-10-15 02:02:57 +08001470static struct resolv_cache*
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001471_resolv_cache_create( void )
1472{
1473 struct resolv_cache* cache;
1474
1475 cache = calloc(sizeof(*cache), 1);
1476 if (cache) {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001477 cache->max_entries = _res_cache_get_max_entries();
1478 cache->entries = calloc(sizeof(*cache->entries), cache->max_entries);
1479 if (cache->entries) {
Mattias Falk3a4910c2011-02-14 12:41:11 +01001480 cache->mru_list.mru_prev = cache->mru_list.mru_next = &cache->mru_list;
1481 XLOG("%s: cache created\n", __FUNCTION__);
1482 } else {
1483 free(cache);
1484 cache = NULL;
1485 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001486 }
1487 return cache;
1488}
1489
1490
1491#if DEBUG
1492static void
1493_dump_query( const uint8_t* query, int querylen )
1494{
1495 char temp[256], *p=temp, *end=p+sizeof(temp);
1496 DnsPacket pack[1];
1497
1498 _dnsPacket_init(pack, query, querylen);
1499 p = _dnsPacket_bprintQuery(pack, p, end);
1500 XLOG("QUERY: %s", temp);
1501}
1502
1503static void
1504_cache_dump_mru( Cache* cache )
1505{
1506 char temp[512], *p=temp, *end=p+sizeof(temp);
1507 Entry* e;
1508
1509 p = _bprint(temp, end, "MRU LIST (%2d): ", cache->num_entries);
1510 for (e = cache->mru_list.mru_next; e != &cache->mru_list; e = e->mru_next)
1511 p = _bprint(p, end, " %d", e->id);
1512
1513 XLOG("%s", temp);
1514}
Mattias Falk3e0c5102011-01-31 12:42:26 +01001515
1516static void
1517_dump_answer(const void* answer, int answerlen)
1518{
1519 res_state statep;
1520 FILE* fp;
1521 char* buf;
1522 int fileLen;
1523
Elliott Hughesc674edb2014-08-26 15:56:54 -07001524 fp = fopen("/data/reslog.txt", "w+e");
Mattias Falk3e0c5102011-01-31 12:42:26 +01001525 if (fp != NULL) {
1526 statep = __res_get_state();
1527
1528 res_pquery(statep, answer, answerlen, fp);
1529
1530 //Get file length
1531 fseek(fp, 0, SEEK_END);
1532 fileLen=ftell(fp);
1533 fseek(fp, 0, SEEK_SET);
1534 buf = (char *)malloc(fileLen+1);
1535 if (buf != NULL) {
1536 //Read file contents into buffer
1537 fread(buf, fileLen, 1, fp);
1538 XLOG("%s\n", buf);
1539 free(buf);
1540 }
1541 fclose(fp);
1542 remove("/data/reslog.txt");
1543 }
1544 else {
Robert Greenwalt78851f12013-01-07 12:10:06 -08001545 errno = 0; // else debug is introducing error signals
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001546 XLOG("%s: can't open file\n", __FUNCTION__);
Mattias Falk3e0c5102011-01-31 12:42:26 +01001547 }
1548}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001549#endif
1550
1551#if DEBUG
1552# define XLOG_QUERY(q,len) _dump_query((q), (len))
Mattias Falk3e0c5102011-01-31 12:42:26 +01001553# define XLOG_ANSWER(a, len) _dump_answer((a), (len))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001554#else
1555# define XLOG_QUERY(q,len) ((void)0)
Mattias Falk3e0c5102011-01-31 12:42:26 +01001556# define XLOG_ANSWER(a,len) ((void)0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001557#endif
1558
1559/* This function tries to find a key within the hash table
1560 * In case of success, it will return a *pointer* to the hashed key.
1561 * In case of failure, it will return a *pointer* to NULL
1562 *
1563 * So, the caller must check '*result' to check for success/failure.
1564 *
1565 * The main idea is that the result can later be used directly in
1566 * calls to _resolv_cache_add or _resolv_cache_remove as the 'lookup'
1567 * parameter. This makes the code simpler and avoids re-searching
1568 * for the key position in the htable.
1569 *
1570 * The result of a lookup_p is only valid until you alter the hash
1571 * table.
1572 */
1573static Entry**
1574_cache_lookup_p( Cache* cache,
1575 Entry* key )
1576{
Mattias Falk3a4910c2011-02-14 12:41:11 +01001577 int index = key->hash % cache->max_entries;
1578 Entry** pnode = (Entry**) &cache->entries[ index ];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001579
1580 while (*pnode != NULL) {
1581 Entry* node = *pnode;
1582
1583 if (node == NULL)
1584 break;
1585
1586 if (node->hash == key->hash && entry_equals(node, key))
1587 break;
1588
1589 pnode = &node->hlink;
1590 }
Mattias Falkc63e5902011-08-23 14:34:14 +02001591 return pnode;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001592}
1593
1594/* Add a new entry to the hash table. 'lookup' must be the
1595 * result of an immediate previous failed _lookup_p() call
1596 * (i.e. with *lookup == NULL), and 'e' is the pointer to the
1597 * newly created entry
1598 */
1599static void
1600_cache_add_p( Cache* cache,
1601 Entry** lookup,
1602 Entry* e )
1603{
1604 *lookup = e;
1605 e->id = ++cache->last_id;
1606 entry_mru_add(e, &cache->mru_list);
1607 cache->num_entries += 1;
1608
1609 XLOG("%s: entry %d added (count=%d)", __FUNCTION__,
1610 e->id, cache->num_entries);
1611}
1612
1613/* Remove an existing entry from the hash table,
1614 * 'lookup' must be the result of an immediate previous
1615 * and succesful _lookup_p() call.
1616 */
1617static void
1618_cache_remove_p( Cache* cache,
1619 Entry** lookup )
1620{
1621 Entry* e = *lookup;
1622
1623 XLOG("%s: entry %d removed (count=%d)", __FUNCTION__,
1624 e->id, cache->num_entries-1);
1625
1626 entry_mru_remove(e);
1627 *lookup = e->hlink;
1628 entry_free(e);
1629 cache->num_entries -= 1;
1630}
1631
1632/* Remove the oldest entry from the hash table.
1633 */
1634static void
1635_cache_remove_oldest( Cache* cache )
1636{
1637 Entry* oldest = cache->mru_list.mru_prev;
1638 Entry** lookup = _cache_lookup_p(cache, oldest);
1639
1640 if (*lookup == NULL) { /* should not happen */
1641 XLOG("%s: OLDEST NOT IN HTABLE ?", __FUNCTION__);
1642 return;
1643 }
Robert Greenwalt7f84da62011-09-02 07:44:36 -07001644 if (DEBUG) {
1645 XLOG("Cache full - removing oldest");
1646 XLOG_QUERY(oldest->query, oldest->querylen);
1647 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001648 _cache_remove_p(cache, lookup);
1649}
1650
Anders Fredlunddd161822011-05-20 08:12:37 +02001651/* Remove all expired entries from the hash table.
1652 */
1653static void _cache_remove_expired(Cache* cache) {
1654 Entry* e;
1655 time_t now = _time_now();
1656
1657 for (e = cache->mru_list.mru_next; e != &cache->mru_list;) {
1658 // Entry is old, remove
1659 if (now >= e->expires) {
1660 Entry** lookup = _cache_lookup_p(cache, e);
1661 if (*lookup == NULL) { /* should not happen */
1662 XLOG("%s: ENTRY NOT IN HTABLE ?", __FUNCTION__);
1663 return;
1664 }
1665 e = e->mru_next;
1666 _cache_remove_p(cache, lookup);
1667 } else {
1668 e = e->mru_next;
1669 }
1670 }
1671}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001672
1673ResolvCacheStatus
Paul Jensen41d9a502014-04-08 15:43:41 -04001674_resolv_cache_lookup( unsigned netid,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001675 const void* query,
1676 int querylen,
1677 void* answer,
1678 int answersize,
1679 int *answerlen )
1680{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001681 Entry key[1];
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001682 Entry** lookup;
1683 Entry* e;
1684 time_t now;
Paul Jensen41d9a502014-04-08 15:43:41 -04001685 Cache* cache;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001686
1687 ResolvCacheStatus result = RESOLV_CACHE_NOTFOUND;
1688
1689 XLOG("%s: lookup", __FUNCTION__);
1690 XLOG_QUERY(query, querylen);
1691
1692 /* we don't cache malformed queries */
1693 if (!entry_init_key(key, query, querylen)) {
1694 XLOG("%s: unsupported query", __FUNCTION__);
1695 return RESOLV_CACHE_UNSUPPORTED;
1696 }
1697 /* lookup cache */
Paul Jensen41d9a502014-04-08 15:43:41 -04001698 pthread_once(&_res_cache_once, _res_cache_init);
1699 pthread_mutex_lock(&_res_cache_list_lock);
1700
1701 cache = _find_named_cache_locked(netid);
1702 if (cache == NULL) {
1703 result = RESOLV_CACHE_UNSUPPORTED;
1704 goto Exit;
1705 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001706
1707 /* see the description of _lookup_p to understand this.
1708 * the function always return a non-NULL pointer.
1709 */
1710 lookup = _cache_lookup_p(cache, key);
1711 e = *lookup;
1712
1713 if (e == NULL) {
1714 XLOG( "NOT IN CACHE");
Mattias Falka59cfcf2011-09-06 15:15:06 +02001715 // calling thread will wait if an outstanding request is found
1716 // that matching this query
Paul Jensen41d9a502014-04-08 15:43:41 -04001717 if (!_cache_check_pending_request_locked(&cache, key, netid) || cache == NULL) {
Mattias Falka59cfcf2011-09-06 15:15:06 +02001718 goto Exit;
1719 } else {
1720 lookup = _cache_lookup_p(cache, key);
1721 e = *lookup;
1722 if (e == NULL) {
1723 goto Exit;
1724 }
1725 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001726 }
1727
1728 now = _time_now();
1729
1730 /* remove stale entries here */
Mattias Falk3e0c5102011-01-31 12:42:26 +01001731 if (now >= e->expires) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001732 XLOG( " NOT IN CACHE (STALE ENTRY %p DISCARDED)", *lookup );
Robert Greenwalt7f84da62011-09-02 07:44:36 -07001733 XLOG_QUERY(e->query, e->querylen);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001734 _cache_remove_p(cache, lookup);
1735 goto Exit;
1736 }
1737
1738 *answerlen = e->answerlen;
1739 if (e->answerlen > answersize) {
1740 /* NOTE: we return UNSUPPORTED if the answer buffer is too short */
1741 result = RESOLV_CACHE_UNSUPPORTED;
1742 XLOG(" ANSWER TOO LONG");
1743 goto Exit;
1744 }
1745
1746 memcpy( answer, e->answer, e->answerlen );
1747
1748 /* bump up this entry to the top of the MRU list */
1749 if (e != cache->mru_list.mru_next) {
1750 entry_mru_remove( e );
1751 entry_mru_add( e, &cache->mru_list );
1752 }
1753
1754 XLOG( "FOUND IN CACHE entry=%p", e );
1755 result = RESOLV_CACHE_FOUND;
1756
1757Exit:
Paul Jensen41d9a502014-04-08 15:43:41 -04001758 pthread_mutex_unlock(&_res_cache_list_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001759 return result;
1760}
1761
1762
1763void
Paul Jensen41d9a502014-04-08 15:43:41 -04001764_resolv_cache_add( unsigned netid,
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001765 const void* query,
1766 int querylen,
1767 const void* answer,
1768 int answerlen )
1769{
1770 Entry key[1];
1771 Entry* e;
1772 Entry** lookup;
Mattias Falk3e0c5102011-01-31 12:42:26 +01001773 u_long ttl;
Paul Jensen41d9a502014-04-08 15:43:41 -04001774 Cache* cache = NULL;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001775
1776 /* don't assume that the query has already been cached
1777 */
1778 if (!entry_init_key( key, query, querylen )) {
1779 XLOG( "%s: passed invalid query ?", __FUNCTION__);
1780 return;
1781 }
1782
Paul Jensen41d9a502014-04-08 15:43:41 -04001783 pthread_mutex_lock(&_res_cache_list_lock);
1784
1785 cache = _find_named_cache_locked(netid);
1786 if (cache == NULL) {
1787 goto Exit;
1788 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001789
1790 XLOG( "%s: query:", __FUNCTION__ );
1791 XLOG_QUERY(query,querylen);
Mattias Falk3e0c5102011-01-31 12:42:26 +01001792 XLOG_ANSWER(answer, answerlen);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001793#if DEBUG_DATA
1794 XLOG( "answer:");
1795 XLOG_BYTES(answer,answerlen);
1796#endif
1797
1798 lookup = _cache_lookup_p(cache, key);
1799 e = *lookup;
1800
1801 if (e != NULL) { /* should not happen */
1802 XLOG("%s: ALREADY IN CACHE (%p) ? IGNORING ADD",
1803 __FUNCTION__, e);
1804 goto Exit;
1805 }
1806
Mattias Falk3a4910c2011-02-14 12:41:11 +01001807 if (cache->num_entries >= cache->max_entries) {
Anders Fredlunddd161822011-05-20 08:12:37 +02001808 _cache_remove_expired(cache);
1809 if (cache->num_entries >= cache->max_entries) {
1810 _cache_remove_oldest(cache);
1811 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001812 /* need to lookup again */
1813 lookup = _cache_lookup_p(cache, key);
1814 e = *lookup;
1815 if (e != NULL) {
1816 XLOG("%s: ALREADY IN CACHE (%p) ? IGNORING ADD",
1817 __FUNCTION__, e);
1818 goto Exit;
1819 }
1820 }
1821
Mattias Falk3e0c5102011-01-31 12:42:26 +01001822 ttl = answer_getTTL(answer, answerlen);
1823 if (ttl > 0) {
1824 e = entry_alloc(key, answer, answerlen);
1825 if (e != NULL) {
1826 e->expires = ttl + _time_now();
1827 _cache_add_p(cache, lookup, e);
1828 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001829 }
1830#if DEBUG
1831 _cache_dump_mru(cache);
1832#endif
1833Exit:
Paul Jensen41d9a502014-04-08 15:43:41 -04001834 if (cache != NULL) {
1835 _cache_notify_waiting_tid_locked(cache, key);
1836 }
1837 pthread_mutex_unlock(&_res_cache_list_lock);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001838}
1839
1840/****************************************************************************/
1841/****************************************************************************/
1842/***** *****/
1843/***** *****/
1844/***** *****/
1845/****************************************************************************/
1846/****************************************************************************/
1847
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001848// Head of the list of caches. Protected by _res_cache_list_lock.
1849static struct resolv_cache_info _res_cache_list;
1850
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001851/* insert resolv_cache_info into the list of resolv_cache_infos */
1852static void _insert_cache_info_locked(struct resolv_cache_info* cache_info);
1853/* creates a resolv_cache_info */
1854static struct resolv_cache_info* _create_cache_info( void );
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001855/* gets a resolv_cache_info associated with a network, or NULL if not found */
1856static struct resolv_cache_info* _find_cache_info_locked(unsigned netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001857/* look up the named cache, and creates one if needed */
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001858static struct resolv_cache* _get_res_cache_for_net_locked(unsigned netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001859/* empty the named cache */
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001860static void _flush_cache_for_net_locked(unsigned netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001861/* empty the nameservers set for the named cache */
1862static void _free_nameservers_locked(struct resolv_cache_info* cache_info);
Mattias Falkc63e5902011-08-23 14:34:14 +02001863/* return 1 if the provided list of name servers differs from the list of name servers
1864 * currently attached to the provided cache_info */
1865static int _resolv_is_nameservers_equal_locked(struct resolv_cache_info* cache_info,
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08001866 const char** servers, int numservers);
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001867/* clears the stats samples contained withing the given cache_info */
1868static void _res_cache_clear_stats_locked(struct resolv_cache_info* cache_info);
Chad Brubaker0c9bb492013-05-30 13:37:02 -07001869
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001870static void
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001871_res_cache_init(void)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001872{
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001873 memset(&_res_cache_list, 0, sizeof(_res_cache_list));
1874 pthread_mutex_init(&_res_cache_list_lock, NULL);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001875}
1876
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001877static struct resolv_cache*
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001878_get_res_cache_for_net_locked(unsigned netid)
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001879{
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001880 struct resolv_cache* cache = _find_named_cache_locked(netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001881 if (!cache) {
1882 struct resolv_cache_info* cache_info = _create_cache_info();
1883 if (cache_info) {
1884 cache = _resolv_cache_create();
1885 if (cache) {
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001886 cache_info->cache = cache;
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001887 cache_info->netid = netid;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001888 _insert_cache_info_locked(cache_info);
1889 } else {
1890 free(cache_info);
1891 }
1892 }
1893 }
1894 return cache;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001895}
1896
Paul Jensen1544eae2014-08-06 17:34:22 +00001897void
1898_resolv_flush_cache_for_net(unsigned netid)
1899{
1900 pthread_once(&_res_cache_once, _res_cache_init);
1901 pthread_mutex_lock(&_res_cache_list_lock);
1902
1903 _flush_cache_for_net_locked(netid);
1904
1905 pthread_mutex_unlock(&_res_cache_list_lock);
1906}
1907
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001908static void
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001909_flush_cache_for_net_locked(unsigned netid)
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001910{
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001911 struct resolv_cache* cache = _find_named_cache_locked(netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001912 if (cache) {
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001913 _cache_flush_locked(cache);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001914 }
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001915
1916 // Also clear the NS statistics.
1917 struct resolv_cache_info* cache_info = _find_cache_info_locked(netid);
1918 _res_cache_clear_stats_locked(cache_info);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001919}
1920
Paul Jensen41d9a502014-04-08 15:43:41 -04001921void _resolv_delete_cache_for_net(unsigned netid)
1922{
1923 pthread_once(&_res_cache_once, _res_cache_init);
1924 pthread_mutex_lock(&_res_cache_list_lock);
1925
1926 struct resolv_cache_info* prev_cache_info = &_res_cache_list;
1927
1928 while (prev_cache_info->next) {
1929 struct resolv_cache_info* cache_info = prev_cache_info->next;
1930
1931 if (cache_info->netid == netid) {
1932 prev_cache_info->next = cache_info->next;
1933 _cache_flush_locked(cache_info->cache);
1934 free(cache_info->cache->entries);
1935 free(cache_info->cache);
1936 _free_nameservers_locked(cache_info);
1937 free(cache_info);
1938 break;
1939 }
1940
1941 prev_cache_info = prev_cache_info->next;
1942 }
1943
1944 pthread_mutex_unlock(&_res_cache_list_lock);
1945}
1946
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001947static struct resolv_cache_info*
1948_create_cache_info(void)
1949{
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001950 struct resolv_cache_info* cache_info;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001951
1952 cache_info = calloc(sizeof(*cache_info), 1);
1953 return cache_info;
1954}
1955
1956static void
1957_insert_cache_info_locked(struct resolv_cache_info* cache_info)
1958{
1959 struct resolv_cache_info* last;
1960
1961 for (last = &_res_cache_list; last->next; last = last->next);
1962
1963 last->next = cache_info;
1964
1965}
1966
1967static struct resolv_cache*
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001968_find_named_cache_locked(unsigned netid) {
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001969
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001970 struct resolv_cache_info* info = _find_cache_info_locked(netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001971
1972 if (info != NULL) return info->cache;
1973
1974 return NULL;
1975}
1976
1977static struct resolv_cache_info*
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001978_find_cache_info_locked(unsigned netid)
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001979{
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001980 struct resolv_cache_info* cache_info = _res_cache_list.next;
1981
1982 while (cache_info) {
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001983 if (cache_info->netid == netid) {
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001984 break;
1985 }
1986
1987 cache_info = cache_info->next;
1988 }
1989 return cache_info;
1990}
1991
Mattias Falk23d3e6b2011-04-04 16:12:35 +02001992void
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001993_resolv_set_default_params(struct __res_params* params) {
1994 params->sample_validity = NSSAMPLE_VALIDITY;
1995 params->success_threshold = SUCCESS_THRESHOLD;
1996 params->min_samples = 0;
1997 params->max_samples = 0;
Bernie Innocenti96c619f2018-08-09 17:32:15 +09001998 params->base_timeout_msec = 0; // 0 = legacy algorithm
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001999}
2000
Pierre Imaifff35672016-04-18 11:42:14 +09002001int
2002_resolv_set_nameservers_for_net(unsigned netid, const char** servers, unsigned numservers,
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002003 const char *domains, const struct __res_params* params)
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002004{
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002005 char sbuf[NI_MAXSERV];
Mattias Falkc63e5902011-08-23 14:34:14 +02002006 register char *cp;
2007 int *offset;
Pierre Imaifff35672016-04-18 11:42:14 +09002008 struct addrinfo* nsaddrinfo[MAXNS];
2009
2010 if (numservers > MAXNS) {
2011 XLOG("%s: numservers=%u, MAXNS=%u", __FUNCTION__, numservers, MAXNS);
2012 return E2BIG;
2013 }
2014
2015 // Parse the addresses before actually locking or changing any state, in case there is an error.
2016 // As a side effect this also reduces the time the lock is kept.
2017 struct addrinfo hints = {
2018 .ai_family = AF_UNSPEC,
2019 .ai_socktype = SOCK_DGRAM,
2020 .ai_flags = AI_NUMERICHOST
2021 };
2022 snprintf(sbuf, sizeof(sbuf), "%u", NAMESERVER_PORT);
2023 for (unsigned i = 0; i < numservers; i++) {
2024 // The addrinfo structures allocated here are freed in _free_nameservers_locked().
2025 int rt = getaddrinfo(servers[i], sbuf, &hints, &nsaddrinfo[i]);
2026 if (rt != 0) {
2027 for (unsigned j = 0 ; j < i ; j++) {
2028 freeaddrinfo(nsaddrinfo[j]);
2029 nsaddrinfo[j] = NULL;
2030 }
2031 XLOG("%s: getaddrinfo(%s)=%s", __FUNCTION__, servers[i], gai_strerror(rt));
2032 return EINVAL;
2033 }
2034 }
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002035
2036 pthread_once(&_res_cache_once, _res_cache_init);
Robert Greenwaltb002a2f2013-01-19 00:40:24 +00002037 pthread_mutex_lock(&_res_cache_list_lock);
Mattias Falkc63e5902011-08-23 14:34:14 +02002038
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002039 // creates the cache if not created
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002040 _get_res_cache_for_net_locked(netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002041
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002042 struct resolv_cache_info* cache_info = _find_cache_info_locked(netid);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002043
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002044 if (cache_info != NULL) {
2045 uint8_t old_max_samples = cache_info->params.max_samples;
2046 if (params != NULL) {
2047 cache_info->params = *params;
2048 } else {
2049 _resolv_set_default_params(&cache_info->params);
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002050 }
Mattias Falkc63e5902011-08-23 14:34:14 +02002051
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002052 if (!_resolv_is_nameservers_equal_locked(cache_info, servers, numservers)) {
2053 // free current before adding new
2054 _free_nameservers_locked(cache_info);
Pierre Imaifff35672016-04-18 11:42:14 +09002055 unsigned i;
2056 for (i = 0; i < numservers; i++) {
2057 cache_info->nsaddrinfo[i] = nsaddrinfo[i];
2058 cache_info->nameservers[i] = strdup(servers[i]);
2059 XLOG("%s: netid = %u, addr = %s\n", __FUNCTION__, netid, servers[i]);
Mattias Falkc63e5902011-08-23 14:34:14 +02002060 }
Pierre Imaifff35672016-04-18 11:42:14 +09002061 cache_info->nscount = numservers;
Mattias Falkc63e5902011-08-23 14:34:14 +02002062
Erik Kline0e4cdff2016-11-08 18:06:57 +09002063 // Clear the NS statistics because the mapping to nameservers might have changed.
2064 _res_cache_clear_stats_locked(cache_info);
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002065
2066 // increment the revision id to ensure that sample state is not written back if the
2067 // servers change; in theory it would suffice to do so only if the servers or
2068 // max_samples actually change, in practice the overhead of checking is higher than the
2069 // cost, and overflows are unlikely
2070 ++cache_info->revision_id;
Pierre Imai06e22022016-05-06 17:56:57 +09002071 } else if (cache_info->params.max_samples != old_max_samples) {
2072 // If the maximum number of samples changes, the overhead of keeping the most recent
2073 // samples around is not considered worth the effort, so they are cleared instead. All
2074 // other parameters do not affect shared state: Changing these parameters does not
2075 // invalidate the samples, as they only affect aggregation and the conditions under
2076 // which servers are considered usable.
2077 _res_cache_clear_stats_locked(cache_info);
2078 ++cache_info->revision_id;
2079 }
2080
2081 // Always update the search paths, since determining whether they actually changed is
2082 // complex due to the zero-padding, and probably not worth the effort. Cache-flushing
2083 // however is not // necessary, since the stored cache entries do contain the domain, not
2084 // just the host name.
2085 // code moved from res_init.c, load_domain_search_list
2086 strlcpy(cache_info->defdname, domains, sizeof(cache_info->defdname));
2087 if ((cp = strchr(cache_info->defdname, '\n')) != NULL)
2088 *cp = '\0';
2089
2090 cp = cache_info->defdname;
2091 offset = cache_info->dnsrch_offset;
2092 while (offset < cache_info->dnsrch_offset + MAXDNSRCH) {
2093 while (*cp == ' ' || *cp == '\t') /* skip leading white space */
2094 cp++;
2095 if (*cp == '\0') /* stop if nothing more to do */
2096 break;
2097 *offset++ = cp - cache_info->defdname; /* record this search domain */
2098 while (*cp) { /* zero-terminate it */
2099 if (*cp == ' '|| *cp == '\t') {
2100 *cp++ = '\0';
2101 break;
2102 }
2103 cp++;
2104 }
2105 }
2106 *offset = -1; /* cache_info->dnsrch_offset has MAXDNSRCH+1 items */
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002107 }
Mattias Falkc63e5902011-08-23 14:34:14 +02002108
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002109 pthread_mutex_unlock(&_res_cache_list_lock);
Pierre Imaifff35672016-04-18 11:42:14 +09002110 return 0;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002111}
2112
Mattias Falkc63e5902011-08-23 14:34:14 +02002113static int
2114_resolv_is_nameservers_equal_locked(struct resolv_cache_info* cache_info,
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08002115 const char** servers, int numservers)
Mattias Falkc63e5902011-08-23 14:34:14 +02002116{
Pierre Imaifff35672016-04-18 11:42:14 +09002117 if (cache_info->nscount != numservers) {
Lorenzo Colittibce18c92014-09-08 18:09:43 +09002118 return 0;
Pierre Imaifff35672016-04-18 11:42:14 +09002119 }
Lorenzo Colittibce18c92014-09-08 18:09:43 +09002120
2121 // Compare each name server against current name servers.
2122 // TODO: this is incorrect if the list of current or previous nameservers
2123 // contains duplicates. This does not really matter because the framework
2124 // filters out duplicates, but we should probably fix it. It's also
2125 // insensitive to the order of the nameservers; we should probably fix that
2126 // too.
Pierre Imaifff35672016-04-18 11:42:14 +09002127 for (int i = 0; i < numservers; i++) {
2128 for (int j = 0 ; ; j++) {
2129 if (j >= numservers) {
2130 return 0;
2131 }
2132 if (strcmp(cache_info->nameservers[i], servers[j]) == 0) {
Mattias Falkc63e5902011-08-23 14:34:14 +02002133 break;
2134 }
Mattias Falkc63e5902011-08-23 14:34:14 +02002135 }
2136 }
2137
Pierre Imaifff35672016-04-18 11:42:14 +09002138 return 1;
Mattias Falkc63e5902011-08-23 14:34:14 +02002139}
2140
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002141static void
2142_free_nameservers_locked(struct resolv_cache_info* cache_info)
2143{
2144 int i;
Pierre Imaifff35672016-04-18 11:42:14 +09002145 for (i = 0; i < cache_info->nscount; i++) {
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002146 free(cache_info->nameservers[i]);
2147 cache_info->nameservers[i] = NULL;
Robert Greenwalt9363d912011-07-25 12:30:17 -07002148 if (cache_info->nsaddrinfo[i] != NULL) {
2149 freeaddrinfo(cache_info->nsaddrinfo[i]);
2150 cache_info->nsaddrinfo[i] = NULL;
2151 }
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002152 cache_info->nsstats[i].sample_count =
2153 cache_info->nsstats[i].sample_next = 0;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002154 }
Pierre Imaifff35672016-04-18 11:42:14 +09002155 cache_info->nscount = 0;
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002156 _res_cache_clear_stats_locked(cache_info);
2157 ++cache_info->revision_id;
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002158}
2159
Mattias Falk23d3e6b2011-04-04 16:12:35 +02002160void
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002161_resolv_populate_res_for_net(res_state statp)
Mattias Falkc63e5902011-08-23 14:34:14 +02002162{
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08002163 if (statp == NULL) {
2164 return;
2165 }
Mattias Falkc63e5902011-08-23 14:34:14 +02002166
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08002167 pthread_once(&_res_cache_once, _res_cache_init);
2168 pthread_mutex_lock(&_res_cache_list_lock);
2169
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002170 struct resolv_cache_info* info = _find_cache_info_locked(statp->netid);
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08002171 if (info != NULL) {
2172 int nserv;
Mattias Falkc63e5902011-08-23 14:34:14 +02002173 struct addrinfo* ai;
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002174 XLOG("%s: %u\n", __FUNCTION__, statp->netid);
Mattias Falkc63e5902011-08-23 14:34:14 +02002175 for (nserv = 0; nserv < MAXNS; nserv++) {
2176 ai = info->nsaddrinfo[nserv];
2177 if (ai == NULL) {
2178 break;
2179 }
2180
2181 if ((size_t) ai->ai_addrlen <= sizeof(statp->_u._ext.ext->nsaddrs[0])) {
2182 if (statp->_u._ext.ext != NULL) {
2183 memcpy(&statp->_u._ext.ext->nsaddrs[nserv], ai->ai_addr, ai->ai_addrlen);
2184 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
2185 } else {
2186 if ((size_t) ai->ai_addrlen
2187 <= sizeof(statp->nsaddr_list[0])) {
2188 memcpy(&statp->nsaddr_list[nserv], ai->ai_addr,
2189 ai->ai_addrlen);
2190 } else {
2191 statp->nsaddr_list[nserv].sin_family = AF_UNSPEC;
2192 }
2193 }
2194 } else {
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002195 XLOG("%s: found too long addrlen", __FUNCTION__);
Mattias Falkc63e5902011-08-23 14:34:14 +02002196 }
2197 }
2198 statp->nscount = nserv;
2199 // now do search domains. Note that we cache the offsets as this code runs alot
2200 // but the setting/offset-computer only runs when set/changed
Pierre Imai0967fc72016-02-29 16:31:55 +09002201 // WARNING: Don't use str*cpy() here, this string contains zeroes.
2202 memcpy(statp->defdname, info->defdname, sizeof(statp->defdname));
Mattias Falkc63e5902011-08-23 14:34:14 +02002203 register char **pp = statp->dnsrch;
2204 register int *p = info->dnsrch_offset;
2205 while (pp < statp->dnsrch + MAXDNSRCH && *p != -1) {
Elliott Hughes37b1b5b2014-07-02 16:27:20 -07002206 *pp++ = &statp->defdname[0] + *p++;
Mattias Falkc63e5902011-08-23 14:34:14 +02002207 }
Mattias Falkc63e5902011-08-23 14:34:14 +02002208 }
Sasha Levitskiyfbae9f32013-02-27 15:48:55 -08002209 pthread_mutex_unlock(&_res_cache_list_lock);
Mattias Falkc63e5902011-08-23 14:34:14 +02002210}
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002211
2212/* Resolver reachability statistics. */
2213
2214static void
2215_res_cache_add_stats_sample_locked(struct __res_stats* stats, const struct __res_sample* sample,
2216 int max_samples) {
2217 // Note: This function expects max_samples > 0, otherwise a (harmless) modification of the
2218 // allocated but supposedly unused memory for samples[0] will happen
2219 XLOG("%s: adding sample to stats, next = %d, count = %d", __FUNCTION__,
2220 stats->sample_next, stats->sample_count);
2221 stats->samples[stats->sample_next] = *sample;
2222 if (stats->sample_count < max_samples) {
2223 ++stats->sample_count;
2224 }
2225 if (++stats->sample_next >= max_samples) {
2226 stats->sample_next = 0;
2227 }
2228}
2229
2230static void
2231_res_cache_clear_stats_locked(struct resolv_cache_info* cache_info) {
2232 if (cache_info) {
2233 for (int i = 0 ; i < MAXNS ; ++i) {
2234 cache_info->nsstats->sample_count = cache_info->nsstats->sample_next = 0;
2235 }
2236 }
2237}
2238
2239int
Pierre Imai97c9d732016-04-18 12:00:12 +09002240android_net_res_stats_get_info_for_net(unsigned netid, int* nscount,
2241 struct sockaddr_storage servers[MAXNS], int* dcount, char domains[MAXDNSRCH][MAXDNSRCHPATH],
2242 struct __res_params* params, struct __res_stats stats[MAXNS]) {
2243 int revision_id = -1;
2244 pthread_mutex_lock(&_res_cache_list_lock);
2245
2246 struct resolv_cache_info* info = _find_cache_info_locked(netid);
2247 if (info) {
2248 if (info->nscount > MAXNS) {
2249 pthread_mutex_unlock(&_res_cache_list_lock);
2250 XLOG("%s: nscount %d > MAXNS %d", __FUNCTION__, info->nscount, MAXNS);
2251 errno = EFAULT;
2252 return -1;
2253 }
2254 int i;
2255 for (i = 0; i < info->nscount; i++) {
2256 // Verify that the following assumptions are held, failure indicates corruption:
2257 // - getaddrinfo() may never return a sockaddr > sockaddr_storage
2258 // - all addresses are valid
2259 // - there is only one address per addrinfo thanks to numeric resolution
2260 int addrlen = info->nsaddrinfo[i]->ai_addrlen;
2261 if (addrlen < (int) sizeof(struct sockaddr) ||
2262 addrlen > (int) sizeof(servers[0])) {
2263 pthread_mutex_unlock(&_res_cache_list_lock);
2264 XLOG("%s: nsaddrinfo[%d].ai_addrlen == %d", __FUNCTION__, i, addrlen);
2265 errno = EMSGSIZE;
2266 return -1;
2267 }
2268 if (info->nsaddrinfo[i]->ai_addr == NULL) {
2269 pthread_mutex_unlock(&_res_cache_list_lock);
2270 XLOG("%s: nsaddrinfo[%d].ai_addr == NULL", __FUNCTION__, i);
2271 errno = ENOENT;
2272 return -1;
2273 }
2274 if (info->nsaddrinfo[i]->ai_next != NULL) {
2275 pthread_mutex_unlock(&_res_cache_list_lock);
2276 XLOG("%s: nsaddrinfo[%d].ai_next != NULL", __FUNCTION__, i);
2277 errno = ENOTUNIQ;
2278 return -1;
2279 }
2280 }
2281 *nscount = info->nscount;
2282 for (i = 0; i < info->nscount; i++) {
2283 memcpy(&servers[i], info->nsaddrinfo[i]->ai_addr, info->nsaddrinfo[i]->ai_addrlen);
2284 stats[i] = info->nsstats[i];
2285 }
2286 for (i = 0; i < MAXDNSRCH; i++) {
Pierre Imai1b069a92016-04-26 22:08:40 +09002287 const char* cur_domain = info->defdname + info->dnsrch_offset[i];
2288 // dnsrch_offset[i] can either be -1 or point to an empty string to indicate the end
2289 // of the search offsets. Checking for < 0 is not strictly necessary, but safer.
2290 // TODO: Pass in a search domain array instead of a string to
2291 // _resolv_set_nameservers_for_net() and make this double check unnecessary.
2292 if (info->dnsrch_offset[i] < 0 ||
2293 ((size_t)info->dnsrch_offset[i]) >= sizeof(info->defdname) || !cur_domain[0]) {
Pierre Imai97c9d732016-04-18 12:00:12 +09002294 break;
2295 }
Pierre Imai1b069a92016-04-26 22:08:40 +09002296 strlcpy(domains[i], cur_domain, MAXDNSRCHPATH);
Pierre Imai97c9d732016-04-18 12:00:12 +09002297 }
2298 *dcount = i;
2299 *params = info->params;
2300 revision_id = info->revision_id;
2301 }
2302
2303 pthread_mutex_unlock(&_res_cache_list_lock);
2304 return revision_id;
2305}
2306
2307int
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002308_resolv_cache_get_resolver_stats( unsigned netid, struct __res_params* params,
2309 struct __res_stats stats[MAXNS]) {
Pierre Imai6b3f0d62016-02-22 17:50:41 +09002310 int revision_id = -1;
2311 pthread_mutex_lock(&_res_cache_list_lock);
2312
2313 struct resolv_cache_info* info = _find_cache_info_locked(netid);
2314 if (info) {
2315 memcpy(stats, info->nsstats, sizeof(info->nsstats));
2316 *params = info->params;
2317 revision_id = info->revision_id;
2318 }
2319
2320 pthread_mutex_unlock(&_res_cache_list_lock);
2321 return revision_id;
2322}
2323
2324void
2325_resolv_cache_add_resolver_stats_sample( unsigned netid, int revision_id, int ns,
2326 const struct __res_sample* sample, int max_samples) {
2327 if (max_samples <= 0) return;
2328
2329 pthread_mutex_lock(&_res_cache_list_lock);
2330
2331 struct resolv_cache_info* info = _find_cache_info_locked(netid);
2332
2333 if (info && info->revision_id == revision_id) {
2334 _res_cache_add_stats_sample_locked(&info->nsstats[ns], sample, max_samples);
2335 }
2336
2337 pthread_mutex_unlock(&_res_cache_list_lock);
2338}