1 /* dnsmasq is Copyright (c) 2000-2022 Simon Kelley
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License as published by
5 the Free Software Foundation; version 2 dated June, 1991, or
6 (at your option) version 3 dated 29 June, 2007.
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
13 You should have received a copy of the GNU General Public License
14 along with this program. If not, see <http://www.gnu.org/licenses/>.
19 static struct crec *cache_head = NULL, *cache_tail = NULL, **hash_table = NULL;
21 static struct crec *dhcp_spare = NULL;
23 static struct crec *new_chain = NULL;
24 static int insert_error;
25 static union bigname *big_free = NULL;
26 static int bignames_left, hash_size;
28 static void make_non_terminals(struct crec *source);
29 static struct crec *really_insert(char *name, union all_addr *addr, unsigned short class,
30 time_t now, unsigned long ttl, unsigned int flags);
32 /* type->string mapping: this is also used by the name-hash function as a mixing table. */
33 /* taken from https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml */
36 const char * const name;
38 { 1, "A" }, /* a host address [RFC1035] */
39 { 2, "NS" }, /* an authoritative name server [RFC1035] */
40 { 3, "MD" }, /* a mail destination (OBSOLETE - use MX) [RFC1035] */
41 { 4, "MF" }, /* a mail forwarder (OBSOLETE - use MX) [RFC1035] */
42 { 5, "CNAME" }, /* the canonical name for an alias [RFC1035] */
43 { 6, "SOA" }, /* marks the start of a zone of authority [RFC1035] */
44 { 7, "MB" }, /* a mailbox domain name (EXPERIMENTAL) [RFC1035] */
45 { 8, "MG" }, /* a mail group member (EXPERIMENTAL) [RFC1035] */
46 { 9, "MR" }, /* a mail rename domain name (EXPERIMENTAL) [RFC1035] */
47 { 10, "NULL" }, /* a null RR (EXPERIMENTAL) [RFC1035] */
48 { 11, "WKS" }, /* a well known service description [RFC1035] */
49 { 12, "PTR" }, /* a domain name pointer [RFC1035] */
50 { 13, "HINFO" }, /* host information [RFC1035] */
51 { 14, "MINFO" }, /* mailbox or mail list information [RFC1035] */
52 { 15, "MX" }, /* mail exchange [RFC1035] */
53 { 16, "TXT" }, /* text strings [RFC1035] */
54 { 17, "RP" }, /* for Responsible Person [RFC1183] */
55 { 18, "AFSDB" }, /* for AFS Data Base location [RFC1183][RFC5864] */
56 { 19, "X25" }, /* for X.25 PSDN address [RFC1183] */
57 { 20, "ISDN" }, /* for ISDN address [RFC1183] */
58 { 21, "RT" }, /* for Route Through [RFC1183] */
59 { 22, "NSAP" }, /* for NSAP address, NSAP style A record [RFC1706] */
60 { 23, "NSAP_PTR" }, /* for domain name pointer, NSAP style [RFC1348][RFC1637][RFC1706] */
61 { 24, "SIG" }, /* for security signature [RFC2535][RFC2536][RFC2537][RFC2931][RFC3008][RFC3110][RFC3755][RFC4034] */
62 { 25, "KEY" }, /* for security key [RFC2535][RFC2536][RFC2537][RFC2539][RFC3008][RFC3110][RFC3755][RFC4034] */
63 { 26, "PX" }, /* X.400 mail mapping information [RFC2163] */
64 { 27, "GPOS" }, /* Geographical Position [RFC1712] */
65 { 28, "AAAA" }, /* IP6 Address [RFC3596] */
66 { 29, "LOC" }, /* Location Information [RFC1876] */
67 { 30, "NXT" }, /* Next Domain (OBSOLETE) [RFC2535][RFC3755] */
68 { 31, "EID" }, /* Endpoint Identifier [Michael_Patton][http://ana-3.lcs.mit.edu/~jnc/nimrod/dns.txt] 1995-06*/
69 { 32, "NIMLOC" }, /* Nimrod Locator [1][Michael_Patton][http://ana-3.lcs.mit.edu/~jnc/nimrod/dns.txt] 1995-06*/
70 { 33, "SRV" }, /* Server Selection [1][RFC2782] */
71 { 34, "ATMA" }, /* ATM Address [ ATM Forum Technical Committee, "ATM Name System, V2.0", Doc ID: AF-DANS-0152.000, July 2000. Available from and held in escrow by IANA.] */
72 { 35, "NAPTR" }, /* Naming Authority Pointer [RFC2168][RFC2915][RFC3403] */
73 { 36, "KX" }, /* Key Exchanger [RFC2230] */
74 { 37, "CERT" }, /* CERT [RFC4398] */
75 { 38, "A6" }, /* A6 (OBSOLETE - use AAAA) [RFC2874][RFC3226][RFC6563] */
76 { 39, "DNAME" }, /* DNAME [RFC6672] */
77 { 40, "SINK" }, /* SINK [Donald_E_Eastlake][http://tools.ietf.org/html/draft-eastlake-kitchen-sink] 1997-11*/
78 { 41, "OPT" }, /* OPT [RFC3225][RFC6891] */
79 { 42, "APL" }, /* APL [RFC3123] */
80 { 43, "DS" }, /* Delegation Signer [RFC3658][RFC4034] */
81 { 44, "SSHFP" }, /* SSH Key Fingerprint [RFC4255] */
82 { 45, "IPSECKEY" }, /* IPSECKEY [RFC4025] */
83 { 46, "RRSIG" }, /* RRSIG [RFC3755][RFC4034] */
84 { 47, "NSEC" }, /* NSEC [RFC3755][RFC4034][RFC9077] */
85 { 48, "DNSKEY" }, /* DNSKEY [RFC3755][RFC4034] */
86 { 49, "DHCID" }, /* DHCID [RFC4701] */
87 { 50, "NSEC3" }, /* NSEC3 [RFC5155][RFC9077] */
88 { 51, "NSEC3PARAM" }, /* NSEC3PARAM [RFC5155] */
89 { 52, "TLSA" }, /* TLSA [RFC6698] */
90 { 53, "SMIMEA" }, /* S/MIME cert association [RFC8162] SMIMEA/smimea-completed-template 2015-12-01*/
91 { 55, "HIP" }, /* Host Identity Protocol [RFC8005] */
92 { 56, "NINFO" }, /* NINFO [Jim_Reid] NINFO/ninfo-completed-template 2008-01-21*/
93 { 57, "RKEY" }, /* RKEY [Jim_Reid] RKEY/rkey-completed-template 2008-01-21*/
94 { 58, "TALINK" }, /* Trust Anchor LINK [Wouter_Wijngaards] TALINK/talink-completed-template 2010-02-17*/
95 { 59, "CDS" }, /* Child DS [RFC7344] CDS/cds-completed-template 2011-06-06*/
96 { 60, "CDNSKEY" }, /* DNSKEY(s) the Child wants reflected in DS [RFC7344] 2014-06-16*/
97 { 61, "OPENPGPKEY" }, /* OpenPGP Key [RFC7929] OPENPGPKEY/openpgpkey-completed-template 2014-08-12*/
98 { 62, "CSYNC" }, /* Child-To-Parent Synchronization [RFC7477] 2015-01-27*/
99 { 63, "ZONEMD" }, /* Message Digest Over Zone Data [RFC8976] ZONEMD/zonemd-completed-template 2018-12-12*/
100 { 64, "SVCB" }, /* Service Binding [draft-ietf-dnsop-svcb-https-00] SVCB/svcb-completed-template 2020-06-30*/
101 { 65, "HTTPS" }, /* HTTPS Binding [draft-ietf-dnsop-svcb-https-00] HTTPS/https-completed-template 2020-06-30*/
102 { 99, "SPF" }, /* [RFC7208] */
103 { 100, "UINFO" }, /* [IANA-Reserved] */
104 { 101, "UID" }, /* [IANA-Reserved] */
105 { 102, "GID" }, /* [IANA-Reserved] */
106 { 103, "UNSPEC" }, /* [IANA-Reserved] */
107 { 104, "NID" }, /* [RFC6742] ILNP/nid-completed-template */
108 { 105, "L32" }, /* [RFC6742] ILNP/l32-completed-template */
109 { 106, "L64" }, /* [RFC6742] ILNP/l64-completed-template */
110 { 107, "LP" }, /* [RFC6742] ILNP/lp-completed-template */
111 { 108, "EUI48" }, /* an EUI-48 address [RFC7043] EUI48/eui48-completed-template 2013-03-27*/
112 { 109, "EUI64" }, /* an EUI-64 address [RFC7043] EUI64/eui64-completed-template 2013-03-27*/
113 { 249, "TKEY" }, /* Transaction Key [RFC2930] */
114 { 250, "TSIG" }, /* Transaction Signature [RFC8945] */
115 { 251, "IXFR" }, /* incremental transfer [RFC1995] */
116 { 252, "AXFR" }, /* transfer of an entire zone [RFC1035][RFC5936] */
117 { 253, "MAILB" }, /* mailbox-related RRs (MB, MG or MR) [RFC1035] */
118 { 254, "MAILA" }, /* mail agent RRs (OBSOLETE - see MX) [RFC1035] */
119 { 255, "ANY" }, /* A request for some or all records the server has available [RFC1035][RFC6895][RFC8482] */
120 { 256, "URI" }, /* URI [RFC7553] URI/uri-completed-template 2011-02-22*/
121 { 257, "CAA" }, /* Certification Authority Restriction [RFC8659] CAA/caa-completed-template 2011-04-07*/
122 { 258, "AVC" }, /* Application Visibility and Control [Wolfgang_Riedel] AVC/avc-completed-template 2016-02-26*/
123 { 259, "DOA" }, /* Digital Object Architecture [draft-durand-doa-over-dns] DOA/doa-completed-template 2017-08-30*/
124 { 260, "AMTRELAY" }, /* Automatic Multicast Tunneling Relay [RFC8777] AMTRELAY/amtrelay-completed-template 2019-02-06*/
125 { 32768, "TA" }, /* DNSSEC Trust Authorities [Sam_Weiler][http://cameo.library.cmu.edu/][ Deploying DNSSEC Without a Signed Root. Technical Report 1999-19, Information Networking Institute, Carnegie Mellon University, April 2004.] 2005-12-13*/
126 { 32769, "DLV" }, /* DNSSEC Lookaside Validation (OBSOLETE) [RFC8749][RFC4431] */
129 static void cache_free(struct crec *crecp);
130 static void cache_unlink(struct crec *crecp);
131 static void cache_link(struct crec *crecp);
132 static void rehash(int size);
133 static void cache_hash(struct crec *crecp);
135 void next_uid(struct crec *crecp)
137 static unsigned int uid = 0;
139 if (crecp->uid == UID_NONE)
143 /* uid == 0 used to indicate CNAME to interface name. */
151 void cache_init(void)
156 bignames_left = daemon->cachesize/10;
158 if (daemon->cachesize > 0)
160 crecp = safe_malloc(daemon->cachesize*sizeof(struct crec));
162 for (i=0; i < daemon->cachesize; i++, crecp++)
166 crecp->uid = UID_NONE;
170 /* create initial hash table*/
171 rehash(daemon->cachesize);
174 /* In most cases, we create the hash table once here by calling this with (hash_table == NULL)
175 but if the hosts file(s) are big (some people have 50000 ad-block entries), the table
176 will be much too small, so the hosts reading code calls rehash every 1000 addresses, to
178 static void rehash(int size)
180 struct crec **new, **old, *p, *tmp;
181 int i, new_size, old_size;
183 /* hash_size is a power of two. */
184 for (new_size = 64; new_size < size/10; new_size = new_size << 1);
186 /* must succeed in getting first instance, failure later is non-fatal */
188 new = safe_malloc(new_size * sizeof(struct crec *));
189 else if (new_size <= hash_size || !(new = whine_malloc(new_size * sizeof(struct crec *))))
192 for (i = 0; i < new_size; i++)
196 old_size = hash_size;
198 hash_size = new_size;
202 for (i = 0; i < old_size; i++)
203 for (p = old[i]; p ; p = tmp)
212 static struct crec **hash_bucket(char *name)
214 unsigned int c, val = 017465; /* Barker code - minimum self-correlation in cyclic shift */
215 const unsigned char *mix_tab = (const unsigned char*)typestr;
217 while((c = (unsigned char) *name++))
219 /* don't use tolower and friends here - they may be messed up by LOCALE */
220 if (c >= 'A' && c <= 'Z')
222 val = ((val << 7) | (val >> (32 - 7))) + (mix_tab[(val + c) & 0x3F] ^ c);
225 /* hash_size is a power of two */
226 return hash_table + ((val ^ (val >> 16)) & (hash_size - 1));
229 static void cache_hash(struct crec *crecp)
231 /* maintain an invariant that all entries with F_REVERSE set
232 are at the start of the hash-chain and all non-reverse
233 immortal entries are at the end of the hash-chain.
234 This allows reverse searches and garbage collection to be optimised */
236 char *name = cache_get_name(crecp);
237 struct crec **up = hash_bucket(name);
239 if (!(crecp->flags & F_REVERSE))
241 while (*up && ((*up)->flags & F_REVERSE))
242 up = &((*up)->hash_next);
244 if (crecp->flags & F_IMMORTAL)
245 while (*up && !((*up)->flags & F_IMMORTAL))
246 up = &((*up)->hash_next);
249 /* Preserve order when inserting the same name multiple times. */
250 while (*up && hostname_isequal(cache_get_name(*up), name))
251 up = &((*up)->hash_next);
253 crecp->hash_next = *up;
257 static void cache_blockdata_free(struct crec *crecp)
259 if (!(crecp->flags & F_NEG))
261 if (crecp->flags & F_SRV)
262 blockdata_free(crecp->addr.srv.target);
264 else if (crecp->flags & F_DNSKEY)
265 blockdata_free(crecp->addr.key.keydata);
266 else if (crecp->flags & F_DS)
267 blockdata_free(crecp->addr.ds.keydata);
272 static void cache_free(struct crec *crecp)
274 crecp->flags &= ~F_FORWARD;
275 crecp->flags &= ~F_REVERSE;
276 crecp->uid = UID_NONE; /* invalidate CNAMES pointing to this. */
279 cache_tail->next = crecp;
282 crecp->prev = cache_tail;
286 /* retrieve big name for further use. */
287 if (crecp->flags & F_BIGNAME)
289 crecp->name.bname->next = big_free;
290 big_free = crecp->name.bname;
291 crecp->flags &= ~F_BIGNAME;
294 cache_blockdata_free(crecp);
297 /* insert a new cache entry at the head of the list (youngest entry) */
298 static void cache_link(struct crec *crecp)
300 if (cache_head) /* check needed for init code */
301 cache_head->prev = crecp;
302 crecp->next = cache_head;
309 /* remove an arbitrary cache entry for promotion */
310 static void cache_unlink (struct crec *crecp)
313 crecp->prev->next = crecp->next;
315 cache_head = crecp->next;
318 crecp->next->prev = crecp->prev;
320 cache_tail = crecp->prev;
323 char *cache_get_name(struct crec *crecp)
325 if (crecp->flags & F_BIGNAME)
326 return crecp->name.bname->name;
327 else if (crecp->flags & F_NAMEP)
328 return crecp->name.namep;
330 return crecp->name.sname;
333 char *cache_get_cname_target(struct crec *crecp)
335 if (crecp->addr.cname.is_name_ptr)
336 return crecp->addr.cname.target.name;
338 return cache_get_name(crecp->addr.cname.target.cache);
343 struct crec *cache_enumerate(int init)
346 static struct crec *cache;
353 else if (cache && cache->hash_next)
354 cache = cache->hash_next;
358 while (bucket < hash_size)
359 if ((cache = hash_table[bucket++]))
366 static int is_outdated_cname_pointer(struct crec *crecp)
368 if (!(crecp->flags & F_CNAME) || crecp->addr.cname.is_name_ptr)
371 /* NB. record may be reused as DS or DNSKEY, where uid is
372 overloaded for something completely different */
373 if (crecp->addr.cname.target.cache &&
374 !(crecp->addr.cname.target.cache->flags & (F_DNSKEY | F_DS)) &&
375 crecp->addr.cname.uid == crecp->addr.cname.target.cache->uid)
381 static int is_expired(time_t now, struct crec *crecp)
383 /* Don't dump expired entries if they are within the accepted timeout range.
384 The cache becomes approx. LRU. Never use expired DS or DNSKEY entries.
385 Possible values for daemon->cache_max_expiry:
386 -1 == serve cached content regardless how long ago it expired
387 0 == the option is disabled, expired content isn't served
388 <n> == serve cached content only if it expire less than <n> seconds
389 ago (where n is a positive integer) */
390 if (daemon->cache_max_expiry != 0 &&
391 (daemon->cache_max_expiry == -1 ||
392 difftime(now, crecp->ttd) < daemon->cache_max_expiry) &&
393 !(crecp->flags & (F_DS | F_DNSKEY)))
396 if (crecp->flags & F_IMMORTAL)
399 if (difftime(now, crecp->ttd) < 0)
405 /* Remove entries with a given UID from the cache */
406 unsigned int cache_remove_uid(const unsigned int uid)
409 unsigned int removed = 0;
410 struct crec *crecp, **up;
412 for (i = 0; i < hash_size; i++)
413 for (crecp = hash_table[i], up = &hash_table[i]; crecp; crecp = crecp->hash_next)
414 if ((crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG)) && crecp->uid == uid)
416 *up = crecp->hash_next;
421 up = &crecp->hash_next;
426 static struct crec *cache_scan_free(char *name, union all_addr *addr, unsigned short class, time_t now,
427 unsigned int flags, struct crec **target_crec, unsigned int *target_uid)
429 /* Scan and remove old entries.
430 If (flags & F_FORWARD) then remove any forward entries for name and any expired
431 entries but only in the same hash bucket as name.
432 If (flags & F_REVERSE) then remove any reverse entries for addr and any expired
433 entries in the whole cache.
434 If (flags == 0) remove any expired entries in the whole cache.
436 In the flags & F_FORWARD case, the return code is valid, and returns a non-NULL pointer
437 to a cache entry if the name exists in the cache as a HOSTS or DHCP entry (these are never deleted)
439 We take advantage of the fact that hash chains have stuff in the order <reverse>,<other>,<immortal>
440 so that when we hit an entry which isn't reverse and is immortal, we're done.
442 If we free a crec which is a CNAME target, return the entry and uid in target_crec and target_uid.
443 This entry will get re-used with the same name, to preserve CNAMEs. */
445 struct crec *crecp, **up;
449 if (flags & F_FORWARD)
451 for (up = hash_bucket(name), crecp = *up; crecp; crecp = crecp->hash_next)
453 if ((crecp->flags & F_FORWARD) && hostname_isequal(cache_get_name(crecp), name))
455 /* Don't delete DNSSEC in favour of a CNAME, they can co-exist */
456 if ((flags & crecp->flags & (F_IPV4 | F_IPV6 | F_SRV | F_NXDOMAIN)) ||
457 (((crecp->flags | flags) & F_CNAME) && !(crecp->flags & (F_DNSKEY | F_DS))))
459 if (crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG))
461 *up = crecp->hash_next;
462 /* If this record is for the name we're inserting and is the target
463 of a CNAME record. Make the new record for the same name, in the same
464 crec, with the same uid to avoid breaking the existing CNAME. */
465 if (crecp->uid != UID_NONE)
468 *target_crec = crecp;
470 *target_uid = crecp->uid;
478 /* Deletion has to be class-sensitive for DS and DNSKEY */
479 if ((flags & crecp->flags & (F_DNSKEY | F_DS)) && crecp->uid == class)
481 if (crecp->flags & F_CONFIG)
483 *up = crecp->hash_next;
491 if (is_expired(now, crecp) || is_outdated_cname_pointer(crecp))
493 *up = crecp->hash_next;
494 if (!(crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG)))
502 up = &crecp->hash_next;
508 int addrlen = (flags & F_IPV6) ? IN6ADDRSZ : INADDRSZ;
510 for (i = 0; i < hash_size; i++)
511 for (crecp = hash_table[i], up = &hash_table[i];
512 crecp && ((crecp->flags & F_REVERSE) || !(crecp->flags & F_IMMORTAL));
513 crecp = crecp->hash_next)
514 if (is_expired(now, crecp))
516 *up = crecp->hash_next;
517 if (!(crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG)))
523 else if (!(crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG)) &&
524 (flags & crecp->flags & F_REVERSE) &&
525 (flags & crecp->flags & (F_IPV4 | F_IPV6)) &&
526 addr && memcmp(&crecp->addr, addr, addrlen) == 0)
528 *up = crecp->hash_next;
533 up = &crecp->hash_next;
539 /* Note: The normal calling sequence is
544 but an abort can cause the cache_end_insert to be missed
545 in which can the next cache_start_insert cleans things up. */
547 void cache_start_insert(void)
549 /* Free any entries which didn't get committed during the last
554 struct crec *tmp = new_chain->next;
555 cache_free(new_chain);
562 struct crec *cache_insert(char *name, union all_addr *addr, unsigned short class,
563 time_t now, unsigned long ttl, unsigned int flags)
566 if (flags & (F_DNSKEY | F_DS))
568 /* The DNSSEC validation process works by getting needed records into the
569 cache, then retrying the validation until they are all in place.
570 This can be messed up by very short TTLs, and _really_ messed up by
571 zero TTLs, so we force the TTL to be at least long enough to do a validation.
572 Ideally, we should use some kind of reference counting so that records are
573 locked until the validation that asked for them is complete, but this
574 is much easier, and just as effective. */
575 if (ttl < DNSSEC_MIN_TTL)
576 ttl = DNSSEC_MIN_TTL;
581 if (daemon->max_cache_ttl != 0 && daemon->max_cache_ttl < ttl)
582 ttl = daemon->max_cache_ttl;
583 if (daemon->min_cache_ttl != 0 && daemon->min_cache_ttl > ttl)
584 ttl = daemon->min_cache_ttl;
587 return really_insert(name, addr, class, now, ttl, flags);
591 static struct crec *really_insert(char *name, union all_addr *addr, unsigned short class,
592 time_t now, unsigned long ttl, unsigned int flags)
594 struct crec *new, *target_crec = NULL;
595 union bigname *big_name = NULL;
596 int freed_all = (flags & F_REVERSE);
598 unsigned int target_uid;
600 /* if previous insertion failed give up now. */
604 /* we don't cache zero-TTL records. */
611 /* First remove any expired entries and entries for the name/address we
612 are currently inserting. */
613 if ((new = cache_scan_free(name, addr, class, now, flags, &target_crec, &target_uid)))
615 /* We're trying to insert a record over one from
616 /etc/hosts or DHCP, or other config. If the
617 existing record is for an A or AAAA or CNAME and
618 the record we're trying to insert is the same,
619 just drop the insert, but don't error the whole process. */
620 if ((flags & (F_IPV4 | F_IPV6)) && (flags & F_FORWARD) && addr)
622 if ((flags & F_IPV4) && (new->flags & F_IPV4) &&
623 new->addr.addr4.s_addr == addr->addr4.s_addr)
625 else if ((flags & F_IPV6) && (new->flags & F_IPV6) &&
626 IN6_ARE_ADDR_EQUAL(&new->addr.addr6, &addr->addr6))
634 /* Now get a cache entry from the end of the LRU list */
637 if (!(new = cache_tail)) /* no entries left - cache is too small, bail */
643 /* Free entry at end of LRU list, use it. */
644 if (!(new->flags & (F_FORWARD | F_REVERSE)))
647 /* End of LRU list is still in use: if we didn't scan all the hash
648 chains for expired entries do that now. If we already tried that
649 then it's time to start spilling things. */
651 /* If free_avail set, we believe that an entry has been freed.
652 Bugs have been known to make this not true, resulting in
653 a tight loop here. If that happens, abandon the
654 insert. Once in this state, all inserts will probably fail. */
657 static int warned = 0;
660 my_syslog(LOG_ERR, _("Internal error in cache."));
669 /* For DNSSEC records, uid holds class. */
670 free_avail = 1; /* Must be free space now. */
672 /* condition valid when stale-caching */
673 if (difftime(now, new->ttd) < 0)
674 daemon->metrics[METRIC_DNS_CACHE_LIVE_FREED]++;
676 cache_scan_free(cache_get_name(new), &new->addr, new->uid, now, new->flags, NULL, NULL);
680 cache_scan_free(NULL, NULL, class, now, 0, NULL, NULL);
685 /* Check if we need to and can allocate extra memory for a long name.
686 If that fails, give up now, always succeed for DNSSEC records. */
687 if (name && (strlen(name) > SMALLDNAME-1))
692 big_free = big_free->next;
694 else if ((bignames_left == 0 && !(flags & (F_DS | F_DNSKEY))) ||
695 !(big_name = (union bigname *)whine_malloc(sizeof(union bigname))))
700 else if (bignames_left != 0)
705 /* If we freed a cache entry for our name which was a CNAME target, use that.
706 and preserve the uid, so that existing CNAMES are not broken. */
710 new->uid = target_uid;
713 /* Got the rest: finally grab entry. */
719 new->name.bname = big_name;
720 new->flags |= F_BIGNAME;
724 strcpy(cache_get_name(new), name);
726 *cache_get_name(new) = 0;
729 if (flags & (F_DS | F_DNSKEY))
736 new->ttd = now + (time_t)ttl;
737 new->next = new_chain;
743 /* after end of insertion, commit the new entries */
744 void cache_end_insert(void)
751 struct crec *tmp = new_chain->next;
752 /* drop CNAMEs which didn't find a target. */
753 if (is_outdated_cname_pointer(new_chain))
754 cache_free(new_chain);
757 cache_hash(new_chain);
758 cache_link(new_chain);
759 daemon->metrics[METRIC_DNS_CACHE_INSERTED]++;
761 /* If we're a child process, send this cache entry up the pipe to the master.
762 The marshalling process is rather nasty. */
763 if (daemon->pipe_to_parent != -1)
765 char *name = cache_get_name(new_chain);
766 ssize_t m = strlen(name);
767 unsigned int flags = new_chain->flags;
769 u16 class = new_chain->uid;
772 read_write(daemon->pipe_to_parent, (unsigned char *)&m, sizeof(m), 0);
773 read_write(daemon->pipe_to_parent, (unsigned char *)name, m, 0);
774 read_write(daemon->pipe_to_parent, (unsigned char *)&new_chain->ttd, sizeof(new_chain->ttd), 0);
775 read_write(daemon->pipe_to_parent, (unsigned char *)&flags, sizeof(flags), 0);
777 if (flags & (F_IPV4 | F_IPV6 | F_DNSKEY | F_DS | F_SRV))
778 read_write(daemon->pipe_to_parent, (unsigned char *)&new_chain->addr, sizeof(new_chain->addr), 0);
781 /* A negative SRV entry is possible and has no data, obviously. */
782 if (!(flags & F_NEG))
783 blockdata_write(new_chain->addr.srv.target, new_chain->addr.srv.targetlen, daemon->pipe_to_parent);
786 if (flags & F_DNSKEY)
788 read_write(daemon->pipe_to_parent, (unsigned char *)&class, sizeof(class), 0);
789 blockdata_write(new_chain->addr.key.keydata, new_chain->addr.key.keylen, daemon->pipe_to_parent);
791 else if (flags & F_DS)
793 read_write(daemon->pipe_to_parent, (unsigned char *)&class, sizeof(class), 0);
794 /* A negative DS entry is possible and has no data, obviously. */
795 if (!(flags & F_NEG))
796 blockdata_write(new_chain->addr.ds.keydata, new_chain->addr.ds.keylen, daemon->pipe_to_parent);
805 /* signal end of cache insert in master process */
806 if (daemon->pipe_to_parent != -1)
809 read_write(daemon->pipe_to_parent, (unsigned char *)&m, sizeof(m), 0);
816 /* A marshalled cache entry arrives on fd, read, unmarshall and insert into cache of master process. */
817 int cache_recv_insert(time_t now, int fd)
824 struct crec *crecp = NULL;
826 cache_start_insert();
831 if (!read_write(fd, (unsigned char *)&m, sizeof(m), 1))
840 if (!read_write(fd, (unsigned char *)daemon->namebuff, m, 1) ||
841 !read_write(fd, (unsigned char *)&ttd, sizeof(ttd), 1) ||
842 !read_write(fd, (unsigned char *)&flags, sizeof(flags), 1))
845 daemon->namebuff[m] = 0;
847 ttl = difftime(ttd, now);
849 if (flags & (F_IPV4 | F_IPV6 | F_DNSKEY | F_DS | F_SRV))
851 unsigned short class = C_IN;
853 if (!read_write(fd, (unsigned char *)&addr, sizeof(addr), 1))
856 if ((flags & F_SRV) && !(flags & F_NEG) && !(addr.srv.target = blockdata_read(fd, addr.srv.targetlen)))
860 if (flags & F_DNSKEY)
862 if (!read_write(fd, (unsigned char *)&class, sizeof(class), 1) ||
863 !(addr.key.keydata = blockdata_read(fd, addr.key.keylen)))
866 else if (flags & F_DS)
868 if (!read_write(fd, (unsigned char *)&class, sizeof(class), 1) ||
869 (!(flags & F_NEG) && !(addr.key.keydata = blockdata_read(fd, addr.key.keylen))))
874 crecp = really_insert(daemon->namebuff, &addr, class, now, ttl, flags);
876 else if (flags & F_CNAME)
878 struct crec *newc = really_insert(daemon->namebuff, NULL, C_IN, now, ttl, flags);
879 /* This relies on the fact that the target of a CNAME immediately precedes
880 it because of the order of extraction in extract_addresses, and
881 the order reversal on the new_chain. */
884 newc->addr.cname.is_name_ptr = 0;
887 newc->addr.cname.target.cache = NULL;
891 newc->addr.cname.target.cache = crecp;
892 newc->addr.cname.uid = crecp->uid;
899 int cache_find_non_terminal(char *name, time_t now)
903 for (crecp = *hash_bucket(name); crecp; crecp = crecp->hash_next)
904 if (!is_outdated_cname_pointer(crecp) &&
905 !is_expired(now, crecp) &&
906 (crecp->flags & F_FORWARD) &&
907 !(crecp->flags & F_NXDOMAIN) &&
908 hostname_isequal(name, cache_get_name(crecp)))
914 struct crec *cache_find_by_name(struct crec *crecp, char *name, time_t now, unsigned int prot)
917 int no_rr = (prot & F_NO_RR) || option_bool(OPT_NORR);
921 if (crecp) /* iterating */
925 /* first search, look for relevant entries and push to top of list
926 also free anything which has expired */
927 struct crec *next, **up, **insert = NULL, **chainp = &ans;
928 unsigned int ins_flags = 0;
930 for (up = hash_bucket(name), crecp = *up; crecp; crecp = next)
932 next = crecp->hash_next;
934 if (!is_expired(now, crecp) && !is_outdated_cname_pointer(crecp))
936 if ((crecp->flags & F_FORWARD) &&
937 (crecp->flags & prot) &&
938 hostname_isequal(cache_get_name(crecp), name))
940 if (crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG))
943 chainp = &crecp->next;
951 /* Move all but the first entry up the hash chain
952 this implements round-robin.
953 Make sure that re-ordering doesn't break the hash-chain
956 if (insert && (crecp->flags & (F_REVERSE | F_IMMORTAL)) == ins_flags)
958 *up = crecp->hash_next;
959 crecp->hash_next = *insert;
961 insert = &crecp->hash_next;
965 if (!insert && !no_rr)
968 ins_flags = crecp->flags & (F_REVERSE | F_IMMORTAL);
970 up = &crecp->hash_next;
974 /* case : not expired, incorrect entry. */
975 up = &crecp->hash_next;
979 /* expired entry, free it */
980 *up = crecp->hash_next;
981 if (!(crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG)))
989 *chainp = cache_head;
993 (ans->flags & F_FORWARD) &&
994 (ans->flags & prot) &&
995 hostname_isequal(cache_get_name(ans), name))
1001 struct crec *cache_find_by_addr(struct crec *crecp, union all_addr *addr,
1002 time_t now, unsigned int prot)
1005 int addrlen = (prot == F_IPV6) ? IN6ADDRSZ : INADDRSZ;
1007 if (crecp) /* iterating */
1011 /* first search, look for relevant entries and push to top of list
1012 also free anything which has expired. All the reverse entries are at the
1013 start of the hash chain, so we can give up when we find the first
1016 struct crec **up, **chainp = &ans;
1018 for (i=0; i<hash_size; i++)
1019 for (crecp = hash_table[i], up = &hash_table[i];
1020 crecp && (crecp->flags & F_REVERSE);
1021 crecp = crecp->hash_next)
1022 if (!is_expired(now, crecp))
1024 if ((crecp->flags & prot) &&
1025 memcmp(&crecp->addr, addr, addrlen) == 0)
1027 if (crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG))
1030 chainp = &crecp->next;
1034 cache_unlink(crecp);
1038 up = &crecp->hash_next;
1042 *up = crecp->hash_next;
1043 if (!(crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG)))
1045 cache_unlink(crecp);
1050 *chainp = cache_head;
1054 (ans->flags & F_REVERSE) &&
1055 (ans->flags & prot) &&
1056 memcmp(&ans->addr, addr, addrlen) == 0)
1062 static void add_hosts_entry(struct crec *cache, union all_addr *addr, int addrlen,
1063 unsigned int index, struct crec **rhash, int hashsz)
1067 struct crec *lookup = NULL;
1069 /* Remove duplicates in hosts files. */
1070 while ((lookup = cache_find_by_name(lookup, cache_get_name(cache), 0, cache->flags & (F_IPV4 | F_IPV6))))
1071 if ((lookup->flags & F_HOSTS) && memcmp(&lookup->addr, addr, addrlen) == 0)
1077 /* Ensure there is only one address -> name mapping (first one trumps)
1078 We do this by steam here, The entries are kept in hash chains, linked
1079 by ->next (which is unused at this point) held in hash buckets in
1080 the array rhash, hashed on address. Note that rhash and the values
1081 in ->next are only valid whilst reading hosts files: the buckets are
1082 then freed, and the ->next pointer used for other things.
1084 Only insert each unique address once into this hashing structure.
1086 This complexity avoids O(n^2) divergent CPU use whilst reading
1087 large (10000 entry) hosts files.
1089 Note that we only do this process when bulk-reading hosts files,
1090 for incremental reads, rhash is NULL, and we use cache lookups
1097 for (j = 0, i = 0; i < addrlen; i++)
1098 j = (j*2 +((unsigned char *)addr)[i]) % hashsz;
1100 for (lookup = rhash[j]; lookup; lookup = lookup->next)
1101 if ((lookup->flags & cache->flags & (F_IPV4 | F_IPV6)) &&
1102 memcmp(&lookup->addr, addr, addrlen) == 0)
1104 cache->flags &= ~F_REVERSE;
1108 /* maintain address hash chain, insert new unique address */
1111 cache->next = rhash[j];
1117 /* incremental read, lookup in cache */
1118 lookup = cache_find_by_addr(NULL, addr, 0, cache->flags & (F_IPV4 | F_IPV6));
1119 if (lookup && lookup->flags & F_HOSTS)
1120 cache->flags &= ~F_REVERSE;
1124 memcpy(&cache->addr, addr, addrlen);
1126 make_non_terminals(cache);
1129 static int eatspace(FILE *f)
1135 if ((c = getc(f)) == '#')
1136 while (c != '\n' && c != EOF)
1153 static int gettok(FILE *f, char *token)
1159 if ((c = getc(f)) == EOF)
1160 return (count == 0) ? -1 : 1;
1162 if (isspace(c) || c == '#')
1168 if (count < (MAXDNAME - 1))
1176 int read_hostsfile(char *filename, unsigned int index, int cache_size, struct crec **rhash, int hashsz)
1178 FILE *f = fopen(filename, "r");
1179 char *token = daemon->namebuff, *domain_suffix = NULL;
1180 int names_done = 0, name_count = cache_size, lineno = 1;
1181 unsigned int flags = 0;
1182 union all_addr addr;
1183 int atnl, addrlen = 0;
1187 my_syslog(LOG_ERR, _("failed to load names from %s: %s"), filename, strerror(errno));
1191 lineno += eatspace(f);
1193 while ((atnl = gettok(f, token)) != -1)
1195 if (inet_pton(AF_INET, token, &addr) > 0)
1197 flags = F_HOSTS | F_IMMORTAL | F_FORWARD | F_REVERSE | F_IPV4;
1199 domain_suffix = get_domain(addr.addr4);
1201 else if (inet_pton(AF_INET6, token, &addr) > 0)
1203 flags = F_HOSTS | F_IMMORTAL | F_FORWARD | F_REVERSE | F_IPV6;
1204 addrlen = IN6ADDRSZ;
1205 domain_suffix = get_domain6(&addr.addr6);
1209 my_syslog(LOG_ERR, _("bad address at %s line %d"), filename, lineno);
1211 atnl = gettok(f, token);
1216 /* rehash every 1000 names. */
1217 if (rhash && ((name_count - cache_size) > 1000))
1220 cache_size = name_count;
1229 if ((atnl = gettok(f, token)) == -1)
1232 fqdn = !!strchr(token, '.');
1234 if ((canon = canonicalise(token, &nomem)))
1236 /* If set, add a version of the name with a default domain appended */
1237 if (option_bool(OPT_EXPAND) && domain_suffix && !fqdn &&
1238 (cache = whine_malloc(SIZEOF_BARE_CREC + strlen(canon) + 2 + strlen(domain_suffix))))
1240 strcpy(cache->name.sname, canon);
1241 strcat(cache->name.sname, ".");
1242 strcat(cache->name.sname, domain_suffix);
1243 cache->flags = flags;
1244 cache->ttd = daemon->local_ttl;
1245 add_hosts_entry(cache, &addr, addrlen, index, rhash, hashsz);
1249 if ((cache = whine_malloc(SIZEOF_BARE_CREC + strlen(canon) + 1)))
1251 strcpy(cache->name.sname, canon);
1252 cache->flags = flags;
1253 cache->ttd = daemon->local_ttl;
1254 add_hosts_entry(cache, &addr, addrlen, index, rhash, hashsz);
1262 my_syslog(LOG_ERR, _("bad name at %s line %d"), filename, lineno);
1273 my_syslog(LOG_INFO, _("read %s - %d names"), filename, names_done);
1278 void cache_reload(void)
1280 struct crec *cache, **up, *tmp;
1281 int revhashsz, i, total_size = daemon->cachesize;
1282 struct hostsfile *ah;
1283 struct host_record *hr;
1284 struct name_list *nl;
1287 struct mx_srv_record *mx;
1288 struct txt_record *txt;
1289 struct interface_name *intr;
1290 struct ptr_record *ptr;
1291 struct naptr *naptr;
1293 struct ds_config *ds;
1296 daemon->metrics[METRIC_DNS_CACHE_INSERTED] = 0;
1297 daemon->metrics[METRIC_DNS_CACHE_LIVE_FREED] = 0;
1299 for (i=0; i<hash_size; i++)
1300 for (cache = hash_table[i], up = &hash_table[i]; cache; cache = tmp)
1302 cache_blockdata_free(cache);
1304 tmp = cache->hash_next;
1305 if (cache->flags & (F_HOSTS | F_CONFIG))
1307 *up = cache->hash_next;
1310 else if (!(cache->flags & F_DHCP))
1312 *up = cache->hash_next;
1313 if (cache->flags & F_BIGNAME)
1315 cache->name.bname->next = big_free;
1316 big_free = cache->name.bname;
1321 up = &cache->hash_next;
1324 /* Add locally-configured CNAMEs to the cache */
1325 for (a = daemon->cnames; a; a = a->next)
1326 if (a->alias[1] != '*' &&
1327 ((cache = whine_malloc(SIZEOF_POINTER_CREC))))
1329 cache->flags = F_FORWARD | F_NAMEP | F_CNAME | F_IMMORTAL | F_CONFIG;
1330 cache->ttd = a->ttl;
1331 cache->name.namep = a->alias;
1332 cache->addr.cname.target.name = a->target;
1333 cache->addr.cname.is_name_ptr = 1;
1334 cache->uid = UID_NONE;
1336 make_non_terminals(cache);
1340 for (ds = daemon->ds; ds; ds = ds->next)
1341 if ((cache = whine_malloc(SIZEOF_POINTER_CREC)) &&
1342 (cache->addr.ds.keydata = blockdata_alloc(ds->digest, ds->digestlen)))
1344 cache->flags = F_FORWARD | F_IMMORTAL | F_DS | F_CONFIG | F_NAMEP;
1345 cache->ttd = daemon->local_ttl;
1346 cache->name.namep = ds->name;
1347 cache->addr.ds.keylen = ds->digestlen;
1348 cache->addr.ds.algo = ds->algo;
1349 cache->addr.ds.keytag = ds->keytag;
1350 cache->addr.ds.digest = ds->digest_type;
1351 cache->uid = ds->class;
1353 make_non_terminals(cache);
1357 /* borrow the packet buffer for a temporary by-address hash */
1358 memset(daemon->packet, 0, daemon->packet_buff_sz);
1359 revhashsz = daemon->packet_buff_sz / sizeof(struct crec *);
1360 /* we overwrote the buffer... */
1361 daemon->srv_save = NULL;
1363 /* Do host_records in config. */
1364 for (hr = daemon->host_records; hr; hr = hr->next)
1365 for (nl = hr->names; nl; nl = nl->next)
1367 if ((hr->flags & HR_4) &&
1368 (cache = whine_malloc(SIZEOF_POINTER_CREC)))
1370 cache->name.namep = nl->name;
1371 cache->ttd = hr->ttl;
1372 cache->flags = F_HOSTS | F_IMMORTAL | F_FORWARD | F_REVERSE | F_IPV4 | F_NAMEP | F_CONFIG;
1373 add_hosts_entry(cache, (union all_addr *)&hr->addr, INADDRSZ, SRC_CONFIG, (struct crec **)daemon->packet, revhashsz);
1376 if ((hr->flags & HR_6) &&
1377 (cache = whine_malloc(SIZEOF_POINTER_CREC)))
1379 cache->name.namep = nl->name;
1380 cache->ttd = hr->ttl;
1381 cache->flags = F_HOSTS | F_IMMORTAL | F_FORWARD | F_REVERSE | F_IPV6 | F_NAMEP | F_CONFIG;
1382 add_hosts_entry(cache, (union all_addr *)&hr->addr6, IN6ADDRSZ, SRC_CONFIG, (struct crec **)daemon->packet, revhashsz);
1386 if (option_bool(OPT_NO_HOSTS) && !daemon->addn_hosts)
1388 if (daemon->cachesize > 0)
1389 my_syslog(LOG_INFO, _("cleared cache"));
1393 if (!option_bool(OPT_NO_HOSTS))
1394 total_size = read_hostsfile(HOSTSFILE, SRC_HOSTS, total_size, (struct crec **)daemon->packet, revhashsz);
1396 daemon->addn_hosts = expand_filelist(daemon->addn_hosts);
1397 for (ah = daemon->addn_hosts; ah; ah = ah->next)
1398 if (!(ah->flags & AH_INACTIVE))
1399 total_size = read_hostsfile(ah->fname, ah->index, total_size, (struct crec **)daemon->packet, revhashsz);
1402 /* Make non-terminal records for all locally-define RRs */
1403 lrec.flags = F_FORWARD | F_CONFIG | F_NAMEP | F_IMMORTAL;
1405 for (txt = daemon->txt; txt; txt = txt->next)
1407 lrec.name.namep = txt->name;
1408 make_non_terminals(&lrec);
1411 for (naptr = daemon->naptr; naptr; naptr = naptr->next)
1413 lrec.name.namep = naptr->name;
1414 make_non_terminals(&lrec);
1417 for (mx = daemon->mxnames; mx; mx = mx->next)
1419 lrec.name.namep = mx->name;
1420 make_non_terminals(&lrec);
1423 for (intr = daemon->int_names; intr; intr = intr->next)
1425 lrec.name.namep = intr->name;
1426 make_non_terminals(&lrec);
1429 for (ptr = daemon->ptr; ptr; ptr = ptr->next)
1431 lrec.name.namep = ptr->name;
1432 make_non_terminals(&lrec);
1436 set_dynamic_inotify(AH_HOSTS, total_size, (struct crec **)daemon->packet, revhashsz);
1442 struct in_addr a_record_from_hosts(char *name, time_t now)
1444 struct crec *crecp = NULL;
1447 /* If no DNS service, cache not initialised. */
1448 if (daemon->port != 0)
1449 while ((crecp = cache_find_by_name(crecp, name, now, F_IPV4)))
1450 if (crecp->flags & F_HOSTS)
1451 return crecp->addr.addr4;
1453 my_syslog(MS_DHCP | LOG_WARNING, _("No IPv4 address found for %s"), name);
1459 void cache_unhash_dhcp(void)
1461 struct crec *cache, **up;
1464 for (i=0; i<hash_size; i++)
1465 for (cache = hash_table[i], up = &hash_table[i]; cache; cache = cache->hash_next)
1466 if (cache->flags & F_DHCP)
1468 *up = cache->hash_next;
1469 cache->next = dhcp_spare;
1473 up = &cache->hash_next;
1476 void cache_add_dhcp_entry(char *host_name, int prot,
1477 union all_addr *host_address, time_t ttd)
1479 struct crec *crec = NULL, *fail_crec = NULL;
1480 unsigned int flags = F_IPV4;
1482 size_t addrlen = sizeof(struct in_addr);
1484 if (prot == AF_INET6)
1487 addrlen = sizeof(struct in6_addr);
1490 inet_ntop(prot, host_address, daemon->addrbuff, ADDRSTRLEN);
1492 while ((crec = cache_find_by_name(crec, host_name, 0, flags | F_CNAME)))
1494 /* check all addresses associated with name */
1495 if (crec->flags & (F_HOSTS | F_CONFIG))
1497 if (crec->flags & F_CNAME)
1498 my_syslog(MS_DHCP | LOG_WARNING,
1499 _("%s is a CNAME, not giving it to the DHCP lease of %s"),
1500 host_name, daemon->addrbuff);
1501 else if (memcmp(&crec->addr, host_address, addrlen) == 0)
1506 else if (!(crec->flags & F_DHCP))
1508 cache_scan_free(host_name, NULL, C_IN, 0, crec->flags & (flags | F_CNAME | F_FORWARD), NULL, NULL);
1509 /* scan_free deletes all addresses associated with name */
1514 /* if in hosts, don't need DHCP record */
1518 /* Name in hosts, address doesn't match */
1521 inet_ntop(prot, &fail_crec->addr, daemon->namebuff, MAXDNAME);
1522 my_syslog(MS_DHCP | LOG_WARNING,
1523 _("not giving name %s to the DHCP lease of %s because "
1524 "the name exists in %s with address %s"),
1525 host_name, daemon->addrbuff,
1526 record_source(fail_crec->uid), daemon->namebuff);
1530 if ((crec = cache_find_by_addr(NULL, (union all_addr *)host_address, 0, flags)))
1532 if (crec->flags & F_NEG)
1535 cache_scan_free(NULL, (union all_addr *)host_address, C_IN, 0, flags, NULL, NULL);
1541 if ((crec = dhcp_spare))
1542 dhcp_spare = dhcp_spare->next;
1543 else /* need new one */
1544 crec = whine_malloc(SIZEOF_POINTER_CREC);
1546 if (crec) /* malloc may fail */
1548 crec->flags = flags | F_NAMEP | F_DHCP | F_FORWARD;
1550 crec->flags |= F_IMMORTAL;
1553 crec->addr = *host_address;
1554 crec->name.namep = host_name;
1555 crec->uid = UID_NONE;
1557 make_non_terminals(crec);
1562 /* Called when we put a local or DHCP name into the cache.
1563 Creates empty cache entries for subnames (ie,
1564 for three.two.one, for two.one and one), without
1565 F_IPV4 or F_IPV6 or F_CNAME set. These convert
1566 NXDOMAIN answers to NoData ones. */
1567 static void make_non_terminals(struct crec *source)
1569 char *name = cache_get_name(source);
1570 struct crec *crecp, *tmp, **up;
1571 int type = F_HOSTS | F_CONFIG;
1573 if (source->flags & F_DHCP)
1577 /* First delete any empty entries for our new real name. Note that
1578 we only delete empty entries deriving from DHCP for a new DHCP-derived
1579 entry and vice-versa for HOSTS and CONFIG. This ensures that
1580 non-terminals from DHCP go when we reload DHCP and
1581 for HOSTS/CONFIG when we re-read. */
1582 for (up = hash_bucket(name), crecp = *up; crecp; crecp = tmp)
1584 tmp = crecp->hash_next;
1586 if (!is_outdated_cname_pointer(crecp) &&
1587 (crecp->flags & F_FORWARD) &&
1588 (crecp->flags & type) &&
1589 !(crecp->flags & (F_IPV4 | F_IPV6 | F_CNAME | F_SRV | F_DNSKEY | F_DS)) &&
1590 hostname_isequal(name, cache_get_name(crecp)))
1592 *up = crecp->hash_next;
1596 crecp->next = dhcp_spare;
1605 up = &crecp->hash_next;
1608 while ((name = strchr(name, '.')))
1612 /* Look for one existing, don't need another */
1613 for (crecp = *hash_bucket(name); crecp; crecp = crecp->hash_next)
1614 if (!is_outdated_cname_pointer(crecp) &&
1615 (crecp->flags & F_FORWARD) &&
1616 (crecp->flags & type) &&
1617 hostname_isequal(name, cache_get_name(crecp)))
1622 /* If the new name expires later, transfer that time to
1623 empty non-terminal entry. */
1624 if (!(crecp->flags & F_IMMORTAL))
1626 if (source->flags & F_IMMORTAL)
1627 crecp->flags |= F_IMMORTAL;
1628 else if (difftime(crecp->ttd, source->ttd) < 0)
1629 crecp->ttd = source->ttd;
1635 if ((source->flags & F_DHCP) && dhcp_spare)
1638 dhcp_spare = dhcp_spare->next;
1642 crecp = whine_malloc(SIZEOF_POINTER_CREC);
1646 crecp->flags = (source->flags | F_NAMEP) & ~(F_IPV4 | F_IPV6 | F_CNAME | F_SRV | F_DNSKEY | F_DS | F_REVERSE);
1647 if (!(crecp->flags & F_IMMORTAL))
1648 crecp->ttd = source->ttd;
1649 crecp->name.namep = name;
1657 int cache_make_stat(struct txt_record *t)
1659 static char *buff = NULL;
1660 static int bufflen = 60;
1662 struct server *serv, *serv1;
1665 if (!buff && !(buff = whine_malloc(60)))
1672 case TXT_STAT_CACHESIZE:
1673 sprintf(buff+1, "%d", daemon->cachesize);
1676 case TXT_STAT_INSERTS:
1677 sprintf(buff+1, "%d", daemon->metrics[METRIC_DNS_CACHE_INSERTED]);
1680 case TXT_STAT_EVICTIONS:
1681 sprintf(buff+1, "%d", daemon->metrics[METRIC_DNS_CACHE_LIVE_FREED]);
1684 case TXT_STAT_MISSES:
1685 sprintf(buff+1, "%u", daemon->metrics[METRIC_DNS_QUERIES_FORWARDED]);
1689 sprintf(buff+1, "%u", daemon->metrics[METRIC_DNS_LOCAL_ANSWERED]);
1694 sprintf(buff+1, "%u", daemon->metrics[METRIC_DNS_AUTH_ANSWERED]);
1698 case TXT_STAT_SERVERS:
1699 /* sum counts from different records for same server */
1700 for (serv = daemon->servers; serv; serv = serv->next)
1701 serv->flags &= ~SERV_MARK;
1703 for (serv = daemon->servers; serv; serv = serv->next)
1704 if (!(serv->flags & SERV_MARK))
1707 int port, newlen, bytes_avail, bytes_needed;
1708 unsigned int queries = 0, failed_queries = 0;
1709 for (serv1 = serv; serv1; serv1 = serv1->next)
1710 if (!(serv1->flags & SERV_MARK) && sockaddr_isequal(&serv->addr, &serv1->addr))
1712 serv1->flags |= SERV_MARK;
1713 queries += serv1->queries;
1714 failed_queries += serv1->failed_queries;
1716 port = prettyprint_addr(&serv->addr, daemon->addrbuff);
1717 lenp = p++; /* length */
1718 bytes_avail = bufflen - (p - buff );
1719 bytes_needed = snprintf(p, bytes_avail, "%s#%d %u %u", daemon->addrbuff, port, queries, failed_queries);
1720 if (bytes_needed >= bytes_avail)
1722 /* expand buffer if necessary */
1723 newlen = bytes_needed + 1 + bufflen - bytes_avail;
1724 if (!(new = whine_realloc(buff, newlen)))
1726 p = new + (p - buff);
1730 bytes_avail = bufflen - (p - buff );
1731 bytes_needed = snprintf(p, bytes_avail, "%s#%d %u %u", daemon->addrbuff, port, queries, failed_queries);
1733 *lenp = bytes_needed;
1736 t->txt = (unsigned char *)buff;
1742 len = strlen(buff+1);
1743 t->txt = (unsigned char *)buff;
1750 /* There can be names in the cache containing control chars, don't
1751 mess up logging or open security holes. */
1752 static char *sanitise(char *name)
1756 for (r = (unsigned char *)name; *r; r++)
1757 if (!isprint((int)*r))
1758 return "<name unprintable>";
1764 void dump_cache(time_t now)
1766 struct server *serv, *serv1;
1768 my_syslog(LOG_INFO, _("time %lu"), (unsigned long)now);
1769 my_syslog(LOG_INFO, _("cache size %d, %d/%d cache insertions re-used unexpired cache entries."),
1770 daemon->cachesize, daemon->metrics[METRIC_DNS_CACHE_LIVE_FREED], daemon->metrics[METRIC_DNS_CACHE_INSERTED]);
1771 my_syslog(LOG_INFO, _("queries forwarded %u, queries answered locally %u"),
1772 daemon->metrics[METRIC_DNS_QUERIES_FORWARDED], daemon->metrics[METRIC_DNS_LOCAL_ANSWERED]);
1773 if (daemon->cache_max_expiry != 0)
1774 my_syslog(LOG_INFO, _("queries answered from stale cache %u"), daemon->metrics[METRIC_DNS_STALE_ANSWERED]);
1776 my_syslog(LOG_INFO, _("queries for authoritative zones %u"), daemon->metrics[METRIC_DNS_AUTH_ANSWERED]);
1781 /* sum counts from different records for same server */
1782 for (serv = daemon->servers; serv; serv = serv->next)
1783 serv->flags &= ~SERV_MARK;
1785 for (serv = daemon->servers; serv; serv = serv->next)
1786 if (!(serv->flags & SERV_MARK))
1789 unsigned int queries = 0, failed_queries = 0, nxdomain_replies = 0, retrys = 0;
1790 unsigned int sigma_latency = 0, count_latency = 0;
1792 for (serv1 = serv; serv1; serv1 = serv1->next)
1793 if (!(serv1->flags & SERV_MARK) && sockaddr_isequal(&serv->addr, &serv1->addr))
1795 serv1->flags |= SERV_MARK;
1796 queries += serv1->queries;
1797 failed_queries += serv1->failed_queries;
1798 nxdomain_replies += serv1->nxdomain_replies;
1799 retrys += serv1->retrys;
1800 sigma_latency += serv1->query_latency;
1803 port = prettyprint_addr(&serv->addr, daemon->addrbuff);
1804 my_syslog(LOG_INFO, _("server %s#%d: queries sent %u, retried %u, failed %u, nxdomain replies %u, avg. latency %ums"),
1805 daemon->addrbuff, port, queries, retrys, failed_queries, nxdomain_replies, sigma_latency/count_latency);
1808 if (option_bool(OPT_DEBUG) || option_bool(OPT_LOG))
1810 struct crec *cache ;
1812 my_syslog(LOG_INFO, "Host Address Flags Expires Source");
1813 my_syslog(LOG_INFO, "------------------------------ ---------------------------------------- ---------- ------------------------ ------------");
1815 for (i=0; i<hash_size; i++)
1816 for (cache = hash_table[i]; cache; cache = cache->hash_next)
1819 char *a = daemon->addrbuff, *p = daemon->namebuff, *n = cache_get_name(cache);
1821 if (strlen(n) == 0 && !(cache->flags & F_REVERSE))
1823 p += sprintf(p, "%-30.30s ", sanitise(n));
1824 if ((cache->flags & F_CNAME) && !is_outdated_cname_pointer(cache))
1825 a = sanitise(cache_get_cname_target(cache));
1826 else if ((cache->flags & F_SRV) && !(cache->flags & F_NEG))
1828 int targetlen = cache->addr.srv.targetlen;
1829 ssize_t len = sprintf(a, "%u %u %u ", cache->addr.srv.priority,
1830 cache->addr.srv.weight, cache->addr.srv.srvport);
1832 if (targetlen > (40 - len))
1833 targetlen = 40 - len;
1834 blockdata_retrieve(cache->addr.srv.target, targetlen, a + len);
1835 a[len + targetlen] = 0;
1838 else if (cache->flags & F_DS)
1840 if (!(cache->flags & F_NEG))
1841 sprintf(a, "%5u %3u %3u", cache->addr.ds.keytag,
1842 cache->addr.ds.algo, cache->addr.ds.digest);
1844 else if (cache->flags & F_DNSKEY)
1845 sprintf(a, "%5u %3u %3u", cache->addr.key.keytag,
1846 cache->addr.key.algo, cache->addr.key.flags);
1848 else if (!(cache->flags & F_NEG) || !(cache->flags & F_FORWARD))
1850 a = daemon->addrbuff;
1851 if (cache->flags & F_IPV4)
1852 inet_ntop(AF_INET, &cache->addr, a, ADDRSTRLEN);
1853 else if (cache->flags & F_IPV6)
1854 inet_ntop(AF_INET6, &cache->addr, a, ADDRSTRLEN);
1857 if (cache->flags & F_IPV4)
1859 else if (cache->flags & F_IPV6)
1861 else if (cache->flags & F_CNAME)
1863 else if (cache->flags & F_SRV)
1866 else if (cache->flags & F_DS)
1868 else if (cache->flags & F_DNSKEY)
1871 else /* non-terminal */
1874 p += sprintf(p, "%-40.40s %s%s%s%s%s%s%s%s%s%s ", a, t,
1875 cache->flags & F_FORWARD ? "F" : " ",
1876 cache->flags & F_REVERSE ? "R" : " ",
1877 cache->flags & F_IMMORTAL ? "I" : " ",
1878 cache->flags & F_DHCP ? "D" : " ",
1879 cache->flags & F_NEG ? "N" : " ",
1880 cache->flags & F_NXDOMAIN ? "X" : " ",
1881 cache->flags & F_HOSTS ? "H" : " ",
1882 cache->flags & F_CONFIG ? "C" : " ",
1883 cache->flags & F_DNSSECOK ? "V" : " ");
1884 #ifdef HAVE_BROKEN_RTC
1885 p += sprintf(p, "%-24lu", cache->flags & F_IMMORTAL ? 0: (unsigned long)(cache->ttd - now));
1887 p += sprintf(p, "%-24.24s", cache->flags & F_IMMORTAL ? "" : ctime(&(cache->ttd)));
1889 if(cache->flags & (F_HOSTS | F_CONFIG) && cache->uid > 0)
1890 p += sprintf(p, " %s", record_source(cache->uid));
1892 my_syslog(LOG_INFO, "%s", daemon->namebuff);
1897 char *record_source(unsigned int index)
1899 struct hostsfile *ah;
1904 if (index == SRC_CONFIG)
1906 else if (index == SRC_HOSTS)
1909 for (ah = daemon->addn_hosts; ah; ah = ah->next)
1910 if (ah->index == index)
1914 /* Dynamic directories contain multiple files */
1915 for (dd = daemon->dynamic_dirs; dd; dd = dd->next)
1916 for (ah = dd->files; ah; ah = ah->next)
1917 if (ah->index == index)
1924 static char *querystr(char *desc, unsigned short type)
1927 int len = 10; /* strlen("type=xxxxx") */
1928 const char *types = NULL;
1929 static char *buff = NULL;
1930 static int bufflen = 0;
1932 for (i = 0; i < (sizeof(typestr)/sizeof(typestr[0])); i++)
1933 if (typestr[i].type == type)
1935 types = typestr[i].name;
1936 len = strlen(types);
1942 len += 2; /* braces */
1943 len += strlen(desc);
1945 len++; /* terminator */
1947 if (!buff || bufflen < len)
1954 buff = whine_malloc(len);
1963 sprintf(buff, "%s[%s]", desc, types);
1965 sprintf(buff, "%s[type=%d]", desc, type);
1970 sprintf(buff, "<%s>", types);
1972 sprintf(buff, "<type=%d>", type);
1976 return buff ? buff : "";
1979 static char *edestr(int ede)
1983 case EDE_OTHER: return "other";
1984 case EDE_USUPDNSKEY: return "unsupported DNSKEY algorithm";
1985 case EDE_USUPDS: return "unsupported DS digest";
1986 case EDE_STALE: return "stale answer";
1987 case EDE_FORGED: return "forged";
1988 case EDE_DNSSEC_IND: return "DNSSEC indeterminate";
1989 case EDE_DNSSEC_BOGUS: return "DNSSEC bogus";
1990 case EDE_SIG_EXP: return "DNSSEC signature expired";
1991 case EDE_SIG_NYV: return "DNSSEC sig not yet valid";
1992 case EDE_NO_DNSKEY: return "DNSKEY missing";
1993 case EDE_NO_RRSIG: return "RRSIG missing";
1994 case EDE_NO_ZONEKEY: return "no zone key bit set";
1995 case EDE_NO_NSEC: return "NSEC(3) missing";
1996 case EDE_CACHED_ERR: return "cached error";
1997 case EDE_NOT_READY: return "not ready";
1998 case EDE_BLOCKED: return "blocked";
1999 case EDE_CENSORED: return "censored";
2000 case EDE_FILTERED: return "filtered";
2001 case EDE_PROHIBITED: return "prohibited";
2002 case EDE_STALE_NXD: return "stale NXDOMAIN";
2003 case EDE_NOT_AUTH: return "not authoritative";
2004 case EDE_NOT_SUP: return "not supported";
2005 case EDE_NO_AUTH: return "no reachable authority";
2006 case EDE_NETERR: return "network error";
2007 case EDE_INVALID_DATA: return "invalid data";
2008 default: return "unknown";
2012 void log_query(unsigned int flags, char *name, union all_addr *addr, char *arg, unsigned short type)
2014 char *source, *dest = arg;
2017 char portstring[7]; /* space for #<portnum> */
2019 if (!option_bool(OPT_LOG))
2022 /* build query type string if requested */
2023 if (!(flags & (F_SERVER | F_IPSET)) && type > 0)
2024 arg = querystr(arg, type);
2027 if ((flags & F_DNSSECOK) && option_bool(OPT_EXTRALOG))
2028 extra = " (DNSSEC signed)";
2031 name = sanitise(name);
2035 dest = daemon->addrbuff;
2037 if (flags & F_KEYTAG)
2038 sprintf(daemon->addrbuff, arg, addr->log.keytag, addr->log.algo, addr->log.digest);
2039 else if (flags & F_RCODE)
2041 unsigned int rcode = addr->log.rcode;
2043 if (rcode == SERVFAIL)
2045 else if (rcode == REFUSED)
2047 else if (rcode == NOTIMP)
2048 dest = "not implemented";
2050 sprintf(daemon->addrbuff, "%u", rcode);
2052 if (addr->log.ede != EDE_UNSET)
2054 extra = daemon->addrbuff;
2055 sprintf(extra, " (EDE: %s)", edestr(addr->log.ede));
2058 else if (flags & (F_IPV4 | F_IPV6))
2060 inet_ntop(flags & F_IPV4 ? AF_INET : AF_INET6,
2061 addr, daemon->addrbuff, ADDRSTRLEN);
2062 if ((flags & F_SERVER) && type != NAMESERVER_PORT)
2065 sprintf(portstring, "#%u", type);
2072 if (flags & F_REVERSE)
2075 name = daemon->addrbuff;
2080 if (flags & F_NXDOMAIN)
2085 dest = "NODATA-IPv4";
2086 else if (flags & F_IPV6)
2087 dest = "NODATA-IPv6";
2092 else if (flags & F_CNAME)
2094 else if (flags & F_SRV)
2096 else if (flags & F_RRNAME)
2099 if (flags & F_CONFIG)
2101 else if (flags & F_DHCP)
2103 else if (flags & F_HOSTS)
2105 else if (flags & F_UPSTREAM)
2107 else if (flags & F_SECSTAT)
2109 if (addr && addr->log.ede != EDE_UNSET && option_bool(OPT_EXTRALOG))
2111 extra = daemon->addrbuff;
2112 sprintf(extra, " (EDE: %s)", edestr(addr->log.ede));
2114 source = "validation";
2117 else if (flags & F_AUTH)
2119 else if (flags & F_DNSSEC)
2124 else if (flags & F_SERVER)
2126 source = "forwarded";
2129 else if (flags & F_QUERY)
2134 else if (flags & F_IPSET)
2136 source = type ? "ipset add" : "nftset add";
2139 verb = daemon->addrbuff;
2141 else if (flags & F_STALE)
2142 source = "cached-stale";
2146 if (name && !name[0])
2149 if (option_bool(OPT_EXTRALOG))
2151 if (flags & F_NOEXTRA)
2152 my_syslog(LOG_INFO, "%u %s %s %s %s%s", daemon->log_display_id, source, name, verb, dest, extra);
2155 int port = prettyprint_addr(daemon->log_source_addr, daemon->addrbuff2);
2156 my_syslog(LOG_INFO, "%u %s/%u %s %s %s %s%s", daemon->log_display_id, daemon->addrbuff2, port, source, name, verb, dest, extra);
2160 my_syslog(LOG_INFO, "%s %s %s %s%s", source, name, verb, dest, extra);