Debian Codegraph @

src/cache.c

raw
1 /* dnsmasq is Copyright (c) 2000-2026 Simon Kelley
2
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.
7
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.
12
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/>.
15 */
16
17 #include "dnsmasq.h"
18
19 static struct crec *cache_head = NULL, *cache_tail = NULL, **hash_table = NULL;
20 static struct crec *config_spare = NULL;
21 static struct crec *new_chain = NULL;
22 static int insert_error;
23 static union bigname *big_free = NULL;
24 static int bignames_left, hash_size;
25
26 struct nameblock {
27 struct nameblock *next;
28 unsigned int last, index;
29 char data[NAMEBLOCK_CHARS];
30 } *hostblocks = NULL;
31
32 static void make_non_terminals(struct crec *source);
33 static struct crec *really_insert(char *name, union all_addr *addr, unsigned short class,
34 time_t now, unsigned long ttl, unsigned int flags);
35 static void dump_cache_entry(struct crec *cache, time_t now);
36 static char *querystr(char *desc, unsigned short type);
37
38 /* type->string mapping: this is also used by the name-hash function as a mixing table. */
39 /* taken from https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml */
40 static const struct {
41 unsigned int type;
42 const char * const name;
43 } typestr[] = {
44 { 1, "A" }, /* a host address [RFC1035] */
45 { 2, "NS" }, /* an authoritative name server [RFC1035] */
46 { 3, "MD" }, /* a mail destination (OBSOLETE - use MX) [RFC1035] */
47 { 4, "MF" }, /* a mail forwarder (OBSOLETE - use MX) [RFC1035] */
48 { 5, "CNAME" }, /* the canonical name for an alias [RFC1035] */
49 { 6, "SOA" }, /* marks the start of a zone of authority [RFC1035] */
50 { 7, "MB" }, /* a mailbox domain name (EXPERIMENTAL) [RFC1035] */
51 { 8, "MG" }, /* a mail group member (EXPERIMENTAL) [RFC1035] */
52 { 9, "MR" }, /* a mail rename domain name (EXPERIMENTAL) [RFC1035] */
53 { 10, "NULL" }, /* a null RR (EXPERIMENTAL) [RFC1035] */
54 { 11, "WKS" }, /* a well known service description [RFC1035] */
55 { 12, "PTR" }, /* a domain name pointer [RFC1035] */
56 { 13, "HINFO" }, /* host information [RFC1035] */
57 { 14, "MINFO" }, /* mailbox or mail list information [RFC1035] */
58 { 15, "MX" }, /* mail exchange [RFC1035] */
59 { 16, "TXT" }, /* text strings [RFC1035] */
60 { 17, "RP" }, /* for Responsible Person [RFC1183] */
61 { 18, "AFSDB" }, /* for AFS Data Base location [RFC1183][RFC5864] */
62 { 19, "X25" }, /* for X.25 PSDN address [RFC1183] */
63 { 20, "ISDN" }, /* for ISDN address [RFC1183] */
64 { 21, "RT" }, /* for Route Through [RFC1183] */
65 { 22, "NSAP" }, /* for NSAP address, NSAP style A record [RFC1706] */
66 { 23, "NSAP_PTR" }, /* for domain name pointer, NSAP style [RFC1348][RFC1637][RFC1706] */
67 { 24, "SIG" }, /* for security signature [RFC2535][RFC2536][RFC2537][RFC2931][RFC3008][RFC3110][RFC3755][RFC4034] */
68 { 25, "KEY" }, /* for security key [RFC2535][RFC2536][RFC2537][RFC2539][RFC3008][RFC3110][RFC3755][RFC4034] */
69 { 26, "PX" }, /* X.400 mail mapping information [RFC2163] */
70 { 27, "GPOS" }, /* Geographical Position [RFC1712] */
71 { 28, "AAAA" }, /* IP6 Address [RFC3596] */
72 { 29, "LOC" }, /* Location Information [RFC1876] */
73 { 30, "NXT" }, /* Next Domain (OBSOLETE) [RFC2535][RFC3755] */
74 { 31, "EID" }, /* Endpoint Identifier [Michael_Patton][http://ana-3.lcs.mit.edu/~jnc/nimrod/dns.txt] 1995-06*/
75 { 32, "NIMLOC" }, /* Nimrod Locator [1][Michael_Patton][http://ana-3.lcs.mit.edu/~jnc/nimrod/dns.txt] 1995-06*/
76 { 33, "SRV" }, /* Server Selection [1][RFC2782] */
77 { 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.] */
78 { 35, "NAPTR" }, /* Naming Authority Pointer [RFC2168][RFC2915][RFC3403] */
79 { 36, "KX" }, /* Key Exchanger [RFC2230] */
80 { 37, "CERT" }, /* CERT [RFC4398] */
81 { 38, "A6" }, /* A6 (OBSOLETE - use AAAA) [RFC2874][RFC3226][RFC6563] */
82 { 39, "DNAME" }, /* DNAME [RFC6672] */
83 { 40, "SINK" }, /* SINK [Donald_E_Eastlake][http://tools.ietf.org/html/draft-eastlake-kitchen-sink] 1997-11*/
84 { 41, "OPT" }, /* OPT [RFC3225][RFC6891] */
85 { 42, "APL" }, /* APL [RFC3123] */
86 { 43, "DS" }, /* Delegation Signer [RFC3658][RFC4034] */
87 { 44, "SSHFP" }, /* SSH Key Fingerprint [RFC4255] */
88 { 45, "IPSECKEY" }, /* IPSECKEY [RFC4025] */
89 { 46, "RRSIG" }, /* RRSIG [RFC3755][RFC4034] */
90 { 47, "NSEC" }, /* NSEC [RFC3755][RFC4034][RFC9077] */
91 { 48, "DNSKEY" }, /* DNSKEY [RFC3755][RFC4034] */
92 { 49, "DHCID" }, /* DHCID [RFC4701] */
93 { 50, "NSEC3" }, /* NSEC3 [RFC5155][RFC9077] */
94 { 51, "NSEC3PARAM" }, /* NSEC3PARAM [RFC5155] */
95 { 52, "TLSA" }, /* TLSA [RFC6698] */
96 { 53, "SMIMEA" }, /* S/MIME cert association [RFC8162] SMIMEA/smimea-completed-template 2015-12-01*/
97 { 55, "HIP" }, /* Host Identity Protocol [RFC8005] */
98 { 56, "NINFO" }, /* NINFO [Jim_Reid] NINFO/ninfo-completed-template 2008-01-21*/
99 { 57, "RKEY" }, /* RKEY [Jim_Reid] RKEY/rkey-completed-template 2008-01-21*/
100 { 58, "TALINK" }, /* Trust Anchor LINK [Wouter_Wijngaards] TALINK/talink-completed-template 2010-02-17*/
101 { 59, "CDS" }, /* Child DS [RFC7344] CDS/cds-completed-template 2011-06-06*/
102 { 60, "CDNSKEY" }, /* DNSKEY(s) the Child wants reflected in DS [RFC7344] 2014-06-16*/
103 { 61, "OPENPGPKEY" }, /* OpenPGP Key [RFC7929] OPENPGPKEY/openpgpkey-completed-template 2014-08-12*/
104 { 62, "CSYNC" }, /* Child-To-Parent Synchronization [RFC7477] 2015-01-27*/
105 { 63, "ZONEMD" }, /* Message Digest Over Zone Data [RFC8976] ZONEMD/zonemd-completed-template 2018-12-12*/
106 { 64, "SVCB" }, /* Service Binding [draft-ietf-dnsop-svcb-https-00] SVCB/svcb-completed-template 2020-06-30*/
107 { 65, "HTTPS" }, /* HTTPS Binding [draft-ietf-dnsop-svcb-https-00] HTTPS/https-completed-template 2020-06-30*/
108 { 66, "DSYNC" }, /* Endpoint discovery for delegation synchronization [draft-ietf-dnsop-generalized-notify-03] DSYNC/dsync-completed-template 2024-12-10 */
109 { 67, "HHIT" }, /* [draft-ietf-drip-registries-28] */
110 { 68, "BRID" }, /* [draft-ietf-drip-registries-28] */
111 { 99, "SPF" }, /* [RFC7208] */
112 { 100, "UINFO" }, /* [IANA-Reserved] */
113 { 101, "UID" }, /* [IANA-Reserved] */
114 { 102, "GID" }, /* [IANA-Reserved] */
115 { 103, "UNSPEC" }, /* [IANA-Reserved] */
116 { 104, "NID" }, /* [RFC6742] ILNP/nid-completed-template */
117 { 105, "L32" }, /* [RFC6742] ILNP/l32-completed-template */
118 { 106, "L64" }, /* [RFC6742] ILNP/l64-completed-template */
119 { 107, "LP" }, /* [RFC6742] ILNP/lp-completed-template */
120 { 108, "EUI48" }, /* an EUI-48 address [RFC7043] EUI48/eui48-completed-template 2013-03-27*/
121 { 109, "EUI64" }, /* an EUI-64 address [RFC7043] EUI64/eui64-completed-template 2013-03-27*/
122 { 128, "NXNAME" }, /* NXDOMAIN indicator for Compact Denial of Existence https://www.iana.org/go/draft-ietf-dnsop-compact-denial-of-existence-04 */
123 { 249, "TKEY" }, /* Transaction Key [RFC2930] */
124 { 250, "TSIG" }, /* Transaction Signature [RFC8945] */
125 { 251, "IXFR" }, /* incremental transfer [RFC1995] */
126 { 252, "AXFR" }, /* transfer of an entire zone [RFC1035][RFC5936] */
127 { 253, "MAILB" }, /* mailbox-related RRs (MB, MG or MR) [RFC1035] */
128 { 254, "MAILA" }, /* mail agent RRs (OBSOLETE - see MX) [RFC1035] */
129 { 255, "ANY" }, /* A request for some or all records the server has available [RFC1035][RFC6895][RFC8482] */
130 { 256, "URI" }, /* URI [RFC7553] URI/uri-completed-template 2011-02-22*/
131 { 257, "CAA" }, /* Certification Authority Restriction [RFC8659] CAA/caa-completed-template 2011-04-07*/
132 { 258, "AVC" }, /* Application Visibility and Control [Wolfgang_Riedel] AVC/avc-completed-template 2016-02-26*/
133 { 259, "DOA" }, /* Digital Object Architecture [draft-durand-doa-over-dns] DOA/doa-completed-template 2017-08-30*/
134 { 260, "AMTRELAY" }, /* Automatic Multicast Tunneling Relay [RFC8777] AMTRELAY/amtrelay-completed-template 2019-02-06*/
135 { 261, "RESINFO" }, /* Resolver Information as Key/Value Pairs https://datatracker.ietf.org/doc/draft-ietf-add-resolver-info/06/ */
136 { 262, "WALLET" }, /* Public wallet address https://www.iana.org/assignments/dns-parameters/WALLET/wallet-completed-template */
137 { 263, "CLA" }, /* BP Convergence Layer Adapter https://www.iana.org/go/draft-johnson-dns-ipn-cla-07 */
138 { 264, "IPN" }, /* BP Node Number https://www.iana.org/go/draft-johnson-dns-ipn-cla-07 */
139 { 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*/
140 { 32769, "DLV" }, /* DNSSEC Lookaside Validation (OBSOLETE) [RFC8749][RFC4431] */
141 };
142
143 static void cache_free(struct crec *crecp);
144 static void cache_unlink(struct crec *crecp);
145 static void cache_link(struct crec *crecp);
146 static void rehash(int size);
147 static void cache_hash(struct crec *crecp);
148
149 unsigned short rrtype(char *in)
150 {
151 unsigned int i;
152
153 for (i = 0; i < (sizeof(typestr)/sizeof(typestr[0])); i++)
154 if (strcasecmp(in, typestr[i].name) == 0)
155 return typestr[i].type;
156
157 return 0;
158 }
159
160 void next_uid(struct crec *crecp)
161 {
162 static unsigned int uid = 0;
163
164 if (crecp->uid == UID_NONE)
165 {
166 uid++;
167
168 /* uid == 0 used to indicate CNAME to interface name. */
169 if (uid == UID_NONE)
170 uid++;
171
172 crecp->uid = uid;
173 }
174 }
175
176 void cache_init(void)
177 {
178 struct crec *crecp;
179 int i;
180
181 bignames_left = daemon->cachesize/10;
182
183 if (daemon->cachesize > 0)
184 {
185 crecp = safe_malloc(daemon->cachesize*sizeof(struct crec));
186
187 for (i=0; i < daemon->cachesize; i++, crecp++)
188 {
189 cache_link(crecp);
190 crecp->flags = 0;
191 crecp->uid = UID_NONE;
192 }
193 }
194
195 /* create initial hash table*/
196 rehash(daemon->cachesize);
197 }
198
199 static struct crec *get_config_crec(void)
200 {
201 struct crec *ret;
202
203 if (config_spare)
204 {
205 ret = config_spare;
206 config_spare = config_spare->next;
207 }
208 else
209 ret = whine_malloc(SIZEOF_POINTER_CREC);
210
211 return ret;
212 }
213
214 static void free_config_crec(struct crec *p)
215 {
216 p->next = config_spare;
217 config_spare = p;
218 }
219
220 static char *store_name(unsigned int namelen, unsigned int index)
221 {
222 struct nameblock *block;
223 char *ret = NULL;
224
225 if (namelen > NAMEBLOCK_CHARS)
226 return NULL;
227
228 for (block = hostblocks; block; block = block->next)
229 if (block->index == index && NAMEBLOCK_CHARS - block->last >= namelen)
230 break;
231
232 if (!block && ((block = whine_malloc(sizeof(struct nameblock)))))
233 {
234 block->next = hostblocks;
235 block->index = index;
236 hostblocks = block;
237 }
238
239 if (block && NAMEBLOCK_CHARS - block->last >= namelen)
240 {
241 ret = &block->data[block->last];
242 block->last += namelen;
243 }
244
245 return ret;
246 }
247
248 static void free_names(unsigned int index)
249 {
250 struct nameblock *block;
251
252 for (block = hostblocks; block; block = block->next)
253 if (index == UID_NONE || block->index == index)
254 block->last = 0;
255 }
256
257 /* In most cases, we create the hash table once here by calling this with (hash_table == NULL)
258 but if the hosts file(s) are big (some people have 50000 ad-block entries), the table
259 will be much too small, so the hosts reading code calls rehash every 1000 addresses, to
260 expand the table. */
261 static void rehash(int size)
262 {
263 struct crec **new, **old, *p, *tmp;
264 int i, new_size, old_size;
265
266 /* hash_size is a power of two. */
267 for (new_size = 64; new_size < size/10; new_size = new_size << 1);
268
269 /* must succeed in getting first instance, failure later is non-fatal */
270 if (!hash_table)
271 new = safe_malloc(new_size * sizeof(struct crec *));
272 else if (new_size <= hash_size || !(new = whine_malloc(new_size * sizeof(struct crec *))))
273 return;
274
275 for (i = 0; i < new_size; i++)
276 new[i] = NULL;
277
278 old = hash_table;
279 old_size = hash_size;
280 hash_table = new;
281 hash_size = new_size;
282
283 if (old)
284 {
285 for (i = 0; i < old_size; i++)
286 for (p = old[i]; p ; p = tmp)
287 {
288 tmp = p->hash_next;
289 cache_hash(p);
290 }
291 free(old);
292 }
293 }
294
295 static struct crec **hash_bucket(char *name)
296 {
297 unsigned int c, val = 017465; /* Barker code - minimum self-correlation in cyclic shift */
298 const unsigned char *mix_tab = (const unsigned char*)typestr;
299
300 while((c = (unsigned char) *name++))
301 {
302 /* don't use tolower and friends here - they may be messed up by LOCALE */
303 if (c >= 'A' && c <= 'Z')
304 c += 'a' - 'A';
305 val = ((val << 7) | (val >> (32 - 7))) + (mix_tab[(val + c) & 0x3F] ^ c);
306 }
307
308 /* hash_size is a power of two */
309 return hash_table + ((val ^ (val >> 16)) & (hash_size - 1));
310 }
311
312 static void cache_hash(struct crec *crecp)
313 {
314 /* maintain an invariant that all entries with F_REVERSE set
315 are at the start of the hash-chain and all non-reverse
316 immortal entries are at the end of the hash-chain.
317 This allows reverse searches and garbage collection to be optimised */
318
319 char *name = cache_get_name(crecp);
320 struct crec **up = hash_bucket(name);
321 unsigned int flags = crecp->flags & (F_IMMORTAL | F_REVERSE);
322
323 if (!(flags & F_REVERSE))
324 {
325 while (*up && ((*up)->flags & F_REVERSE))
326 up = &((*up)->hash_next);
327
328 if (flags & F_IMMORTAL)
329 while (*up && !((*up)->flags & F_IMMORTAL))
330 up = &((*up)->hash_next);
331 }
332
333 /* Preserve order when inserting the same name multiple times.
334 Do not mess up the flag invariants. */
335 while (*up &&
336 hostname_isequal(cache_get_name(*up), name) &&
337 flags == ((*up)->flags & (F_IMMORTAL | F_REVERSE)))
338 up = &((*up)->hash_next);
339
340 crecp->hash_next = *up;
341 *up = crecp;
342 }
343
344 static void cache_blockdata_free(struct crec *crecp)
345 {
346 if (!(crecp->flags & F_NEG))
347 {
348 if ((crecp->flags & F_RR) && (crecp->flags & F_KEYTAG))
349 blockdata_free(crecp->addr.rrblock.rrdata);
350 #ifdef HAVE_DNSSEC
351 else if (crecp->flags & F_DNSKEY)
352 blockdata_free(crecp->addr.key.keydata);
353 else if (crecp->flags & F_DS)
354 blockdata_free(crecp->addr.ds.keydata);
355 #endif
356 }
357 }
358
359 static void cache_free(struct crec *crecp)
360 {
361 crecp->flags &= ~F_FORWARD;
362 crecp->flags &= ~F_REVERSE;
363 crecp->uid = UID_NONE; /* invalidate CNAMES pointing to this. */
364
365 if (cache_tail)
366 cache_tail->next = crecp;
367 else
368 cache_head = crecp;
369 crecp->prev = cache_tail;
370 crecp->next = NULL;
371 cache_tail = crecp;
372
373 /* retrieve big name for further use. */
374 if (crecp->flags & F_BIGNAME)
375 {
376 crecp->name.bname->next = big_free;
377 big_free = crecp->name.bname;
378 crecp->flags &= ~F_BIGNAME;
379 }
380
381 cache_blockdata_free(crecp);
382 }
383
384 /* insert a new cache entry at the head of the list (youngest entry) */
385 static void cache_link(struct crec *crecp)
386 {
387 if (cache_head) /* check needed for init code */
388 cache_head->prev = crecp;
389 crecp->next = cache_head;
390 crecp->prev = NULL;
391 cache_head = crecp;
392 if (!cache_tail)
393 cache_tail = crecp;
394 }
395
396 /* remove an arbitrary cache entry for promotion */
397 static void cache_unlink (struct crec *crecp)
398 {
399 if (crecp->prev)
400 crecp->prev->next = crecp->next;
401 else
402 cache_head = crecp->next;
403
404 if (crecp->next)
405 crecp->next->prev = crecp->prev;
406 else
407 cache_tail = crecp->prev;
408 }
409
410 char *cache_get_name(struct crec *crecp)
411 {
412 if (crecp->flags & F_BIGNAME)
413 return crecp->name.bname->name;
414 else if (crecp->flags & F_NAMEP)
415 return crecp->name.namep;
416
417 return crecp->name.sname;
418 }
419
420 char *cache_get_cname_target(struct crec *crecp)
421 {
422 if (crecp->addr.cname.is_name_ptr)
423 return crecp->addr.cname.target.name;
424 else
425 return cache_get_name(crecp->addr.cname.target.cache);
426 }
427
428
429
430 struct crec *cache_enumerate(int init)
431 {
432 static int bucket;
433 static struct crec *cache;
434
435 if (init)
436 {
437 bucket = 0;
438 cache = NULL;
439 }
440 else if (cache && cache->hash_next)
441 cache = cache->hash_next;
442 else
443 {
444 cache = NULL;
445 while (bucket < hash_size)
446 if ((cache = hash_table[bucket++]))
447 break;
448 }
449
450 return cache;
451 }
452
453 static int is_outdated_cname_pointer(struct crec *crecp)
454 {
455 if (!(crecp->flags & F_CNAME) || crecp->addr.cname.is_name_ptr)
456 return 0;
457
458 /* NB. record may be reused as DS or DNSKEY, where uid is
459 overloaded for something completely different */
460 if (crecp->addr.cname.target.cache &&
461 !(crecp->addr.cname.target.cache->flags & (F_DNSKEY | F_DS)) &&
462 crecp->addr.cname.uid == crecp->addr.cname.target.cache->uid)
463 return 0;
464
465 return 1;
466 }
467
468 static int is_expired(time_t now, struct crec *crecp)
469 {
470 /* Don't dump expired entries if they are within the accepted timeout range.
471 The cache becomes approx. LRU. Never use expired DS or DNSKEY entries.
472 Possible values for daemon->cache_max_expiry:
473 -1 == serve cached content regardless how long ago it expired
474 0 == the option is disabled, expired content isn't served
475 <n> == serve cached content only if it expire less than <n> seconds
476 ago (where n is a positive integer) */
477 if (daemon->cache_max_expiry != 0 &&
478 (daemon->cache_max_expiry == -1 ||
479 difftime(now, crecp->ttd) < daemon->cache_max_expiry) &&
480 !(crecp->flags & (F_DS | F_DNSKEY)))
481 return 0;
482
483 if (crecp->flags & F_IMMORTAL)
484 return 0;
485
486 if (difftime(now, crecp->ttd) < 0)
487 return 0;
488
489 return 1;
490 }
491
492 /* Remove entries with a given UID from the cache */
493 unsigned int cache_remove_uid(const unsigned int uid)
494 {
495 int i;
496 unsigned int removed = 0;
497 struct crec *crecp, *tmp, **up;
498
499 for (i = 0; i < hash_size; i++)
500 for (crecp = hash_table[i], up = &hash_table[i]; crecp; crecp = tmp)
501 {
502 tmp = crecp->hash_next;
503 if ((crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG)) && crecp->uid == uid)
504 {
505 *up = tmp;
506 free_config_crec(crecp);
507 removed++;
508 }
509 else
510 up = &crecp->hash_next;
511 }
512
513 free_names(uid);
514
515 return removed;
516 }
517
518 static struct crec *cache_scan_free(char *name, union all_addr *addr, unsigned short class, time_t now,
519 unsigned int flags, struct crec **target_crec, unsigned int *target_uid)
520 {
521 /* Scan and remove old entries.
522 If (flags & F_FORWARD) then remove any forward entries for name and any expired
523 entries but only in the same hash bucket as name.
524 If (flags & F_REVERSE) then remove any reverse entries for addr and any expired
525 entries in the whole cache.
526 If (flags == 0) remove any expired entries in the whole cache.
527
528 In the flags & F_FORWARD case, the return code is valid, and returns a non-NULL pointer
529 to a cache entry if the name exists in the cache as a HOSTS or DHCP entry (these are never deleted)
530
531 We take advantage of the fact that hash chains have stuff in the order <reverse>,<other>,<immortal>
532 so that when we hit an entry which isn't reverse and is immortal, we're done.
533
534 If we free a crec which is a CNAME target, return the entry and uid in target_crec and target_uid.
535 This entry will get re-used with the same name, to preserve CNAMEs. */
536
537 struct crec *crecp, **up;
538
539 (void)class;
540
541 if (flags & F_FORWARD)
542 {
543 for (up = hash_bucket(name), crecp = *up; crecp; crecp = crecp->hash_next)
544 {
545 if ((crecp->flags & F_FORWARD) && hostname_isequal(cache_get_name(crecp), name))
546 {
547 int rrmatch = 0;
548 if (addr && (crecp->flags & flags & F_RR))
549 {
550 unsigned short rrc = (crecp->flags & F_KEYTAG) ? crecp->addr.rrblock.rrtype : crecp->addr.rrdata.rrtype;
551 unsigned short rra = (flags & F_KEYTAG) ? addr->rrblock.rrtype : addr->rrdata.rrtype;
552
553 if (rrc == rra)
554 rrmatch = 1;
555 }
556
557 /* Don't delete DNSSEC in favour of a CNAME, they can co-exist */
558 if ((flags & crecp->flags & (F_IPV4 | F_IPV6 | F_NXDOMAIN)) ||
559 (((crecp->flags | flags) & F_CNAME) && !(crecp->flags & (F_DNSKEY | F_DS))) ||
560 rrmatch)
561 {
562 if (crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG))
563 return crecp;
564 *up = crecp->hash_next;
565 /* If this record is for the name we're inserting and is the target
566 of a CNAME record. Make the new record for the same name, in the same
567 crec, with the same uid to avoid breaking the existing CNAME. */
568 if (crecp->uid != UID_NONE)
569 {
570 if (target_crec)
571 *target_crec = crecp;
572 if (target_uid)
573 *target_uid = crecp->uid;
574 }
575 cache_unlink(crecp);
576 cache_free(crecp);
577 continue;
578 }
579
580 #ifdef HAVE_DNSSEC
581 /* Deletion has to be class-sensitive for DS and DNSKEY */
582 if ((flags & crecp->flags & (F_DNSKEY | F_DS)) && crecp->uid == class)
583 {
584 if (crecp->flags & F_CONFIG)
585 return crecp;
586 *up = crecp->hash_next;
587 cache_unlink(crecp);
588 cache_free(crecp);
589 continue;
590 }
591 #endif
592 }
593
594 if (is_expired(now, crecp) || is_outdated_cname_pointer(crecp))
595 {
596 *up = crecp->hash_next;
597 if (!(crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG)))
598 {
599 cache_unlink(crecp);
600 cache_free(crecp);
601 }
602 continue;
603 }
604
605 up = &crecp->hash_next;
606 }
607 }
608 else
609 {
610 int i;
611 int addrlen = (flags & F_IPV6) ? IN6ADDRSZ : INADDRSZ;
612
613 for (i = 0; i < hash_size; i++)
614 for (crecp = hash_table[i], up = &hash_table[i];
615 crecp && ((crecp->flags & F_REVERSE) || !(crecp->flags & F_IMMORTAL));
616 crecp = crecp->hash_next)
617 if (is_expired(now, crecp))
618 {
619 *up = crecp->hash_next;
620 if (!(crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG)))
621 {
622 cache_unlink(crecp);
623 cache_free(crecp);
624 }
625 }
626 else if (!(crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG)) &&
627 (flags & crecp->flags & F_REVERSE) &&
628 (flags & crecp->flags & (F_IPV4 | F_IPV6)) &&
629 addr && memcmp(&crecp->addr, addr, addrlen) == 0)
630 {
631 *up = crecp->hash_next;
632 cache_unlink(crecp);
633 cache_free(crecp);
634 }
635 else
636 up = &crecp->hash_next;
637 }
638
639 return NULL;
640 }
641
642 /* Note: The normal calling sequence is
643 cache_start_insert
644 cache_insert * n
645 cache_end_insert
646
647 but an abort can cause the cache_end_insert to be missed
648 in which can the next cache_start_insert cleans things up. */
649
650 void cache_start_insert(void)
651 {
652 /* Free any entries which didn't get committed during the last
653 insert due to error.
654 */
655 while (new_chain)
656 {
657 struct crec *tmp = new_chain->next;
658 cache_free(new_chain);
659 new_chain = tmp;
660 }
661 new_chain = NULL;
662 insert_error = 0;
663 }
664
665 struct crec *cache_insert(char *name, union all_addr *addr, unsigned short class,
666 time_t now, unsigned long ttl, unsigned int flags)
667 {
668 #ifdef HAVE_DNSSEC
669 if (flags & (F_DNSKEY | F_DS))
670 {
671 /* The DNSSEC validation process works by getting needed records into the
672 cache, then retrying the validation until they are all in place.
673 This can be messed up by very short TTLs, and _really_ messed up by
674 zero TTLs, so we force the TTL to be at least long enough to do a validation.
675 Ideally, we should use some kind of reference counting so that records are
676 locked until the validation that asked for them is complete, but this
677 is much easier, and just as effective. */
678 if (ttl < DNSSEC_MIN_TTL)
679 ttl = DNSSEC_MIN_TTL;
680 }
681 else
682 #endif
683 {
684 if (daemon->max_cache_ttl != 0 && daemon->max_cache_ttl < ttl)
685 ttl = daemon->max_cache_ttl;
686 if (daemon->min_cache_ttl != 0 && daemon->min_cache_ttl > ttl)
687 ttl = daemon->min_cache_ttl;
688 }
689
690 return really_insert(name, addr, class, now, ttl, flags);
691 }
692
693
694 static struct crec *really_insert(char *name, union all_addr *addr, unsigned short class,
695 time_t now, unsigned long ttl, unsigned int flags)
696 {
697 struct crec *new, *target_crec = NULL;
698 union bigname *big_name = NULL;
699 int freed_all = (flags & F_REVERSE);
700 struct crec *free_avail = NULL;
701 unsigned int target_uid;
702
703 /* if previous insertion failed give up now. */
704 if (insert_error)
705 return NULL;
706
707 /* we don't cache zero-TTL records unless we're doing stale-caching. */
708 if (daemon->cache_max_expiry == 0 && ttl == 0)
709 {
710 insert_error = 1;
711 return NULL;
712 }
713
714 /* First remove any expired entries and entries for the name/address we
715 are currently inserting. */
716 if ((new = cache_scan_free(name, addr, class, now, flags, &target_crec, &target_uid)))
717 {
718 /* We're trying to insert a record over one from
719 /etc/hosts or DHCP, or other config. If the
720 existing record is for an A or AAAA or CNAME and
721 the record we're trying to insert is the same,
722 just drop the insert, but don't error the whole process. */
723 if ((flags & (F_IPV4 | F_IPV6)) && (flags & F_FORWARD) && addr)
724 {
725 if ((flags & F_IPV4) && (new->flags & F_IPV4) &&
726 new->addr.addr4.s_addr == addr->addr4.s_addr)
727 return new;
728 else if ((flags & F_IPV6) && (new->flags & F_IPV6) &&
729 IN6_ARE_ADDR_EQUAL(&new->addr.addr6, &addr->addr6))
730 return new;
731 }
732
733 insert_error = 1;
734 return NULL;
735 }
736
737 /* Now get a cache entry from the end of the LRU list */
738 if (!target_crec)
739 while (1) {
740 if (!(new = cache_tail)) /* no entries left - cache is too small, bail */
741 {
742 insert_error = 1;
743 return NULL;
744 }
745
746 /* Free entry at end of LRU list, use it. */
747 if (!(new->flags & (F_FORWARD | F_REVERSE)))
748 break;
749
750 /* End of LRU list is still in use: if we didn't scan all the hash
751 chains for expired entries do that now. If we already tried that
752 then it's time to start spilling things. */
753
754 /* If free_avail set, we believe that an entry has been freed.
755 Bugs have been known to make this not true, resulting in
756 a tight loop here. If that happens, abandon the
757 insert. Once in this state, all inserts will probably fail. */
758 if (free_avail)
759 {
760 my_syslog(LOG_ERR, _("Internal error in cache."));
761 /* Log the entry we tried to delete. */
762 dump_cache_entry(free_avail, now);
763 insert_error = 1;
764 return NULL;
765 }
766
767 if (freed_all)
768 {
769 /* For DNSSEC records, uid holds class. */
770 free_avail = new; /* Must be free space now. */
771
772 /* condition valid when stale-caching */
773 if (difftime(now, new->ttd) < 0)
774 daemon->metrics[METRIC_DNS_CACHE_LIVE_FREED]++;
775
776 cache_scan_free(cache_get_name(new), &new->addr, new->uid, now, new->flags, NULL, NULL);
777 }
778 else
779 {
780 cache_scan_free(NULL, NULL, class, now, 0, NULL, NULL);
781 freed_all = 1;
782 }
783 }
784
785 /* Check if we need to and can allocate extra memory for a long name.
786 If that fails, give up now, always succeed for DNSSEC records. */
787 if (name && (strlen(name) > SMALLDNAME-1))
788 {
789 if (big_free)
790 {
791 big_name = big_free;
792 big_free = big_free->next;
793 }
794 else if ((bignames_left == 0 && !(flags & (F_DS | F_DNSKEY))) ||
795 !(big_name = (union bigname *)whine_malloc(sizeof(union bigname))))
796 {
797 insert_error = 1;
798 return NULL;
799 }
800 else if (bignames_left != 0)
801 bignames_left--;
802
803 }
804
805 /* If we freed a cache entry for our name which was a CNAME target, use that.
806 and preserve the uid, so that existing CNAMES are not broken. */
807 if (target_crec)
808 {
809 new = target_crec;
810 new->uid = target_uid;
811 }
812
813 /* Got the rest: finally grab entry. */
814 cache_unlink(new);
815
816 new->flags = flags;
817 if (big_name)
818 {
819 new->name.bname = big_name;
820 new->flags |= F_BIGNAME;
821 }
822
823 if (name)
824 strcpy(cache_get_name(new), name);
825 else
826 *cache_get_name(new) = 0;
827
828 #ifdef HAVE_DNSSEC
829 if (flags & (F_DS | F_DNSKEY))
830 new->uid = class;
831 #endif
832
833 if (addr)
834 new->addr = *addr;
835
836 new->ttd = now + (time_t)ttl;
837 new->next = new_chain;
838 new_chain = new;
839
840 return new;
841 }
842
843 /* after end of insertion, commit the new entries */
844 void cache_end_insert(void)
845 {
846 if (insert_error)
847 return;
848
849 /* signal start of cache insert transaction to master process */
850 if (daemon->pipe_to_parent != -1)
851 {
852 unsigned char op = PIPE_OP_INSERT;
853 read_write(daemon->pipe_to_parent, &op, sizeof(op), RW_WRITE);
854 }
855
856 while (new_chain)
857 {
858 struct crec *tmp = new_chain->next;
859 /* drop CNAMEs which didn't find a target. */
860 if (is_outdated_cname_pointer(new_chain))
861 cache_free(new_chain);
862 else
863 {
864 cache_hash(new_chain);
865 cache_link(new_chain);
866 daemon->metrics[METRIC_DNS_CACHE_INSERTED]++;
867
868 /* If we're a child process, send this cache entry up the pipe to the master.
869 The marshalling process is rather nasty. */
870 if (daemon->pipe_to_parent != -1)
871 {
872 char *name = cache_get_name(new_chain);
873 ssize_t m = strlen(name);
874 unsigned int flags = new_chain->flags;
875 #ifdef HAVE_DNSSEC
876 u16 class = new_chain->uid;
877 #endif
878
879 read_write(daemon->pipe_to_parent, (unsigned char *)&m, sizeof(m), RW_WRITE);
880 read_write(daemon->pipe_to_parent, (unsigned char *)name, m, RW_WRITE);
881 read_write(daemon->pipe_to_parent, (unsigned char *)&new_chain->ttd, sizeof(new_chain->ttd), RW_WRITE);
882 read_write(daemon->pipe_to_parent, (unsigned char *)&flags, sizeof(flags), RW_WRITE);
883 read_write(daemon->pipe_to_parent, (unsigned char *)&new_chain->addr, sizeof(new_chain->addr), RW_WRITE);
884
885 if (flags & F_RR)
886 {
887 /* A negative RR entry is possible and has no data, obviously. */
888 if (!(flags & F_NEG) && (flags & F_KEYTAG))
889 blockdata_write(new_chain->addr.rrblock.rrdata, new_chain->addr.rrblock.datalen, daemon->pipe_to_parent);
890 }
891 #ifdef HAVE_DNSSEC
892 else if (flags & F_DNSKEY)
893 {
894 read_write(daemon->pipe_to_parent, (unsigned char *)&class, sizeof(class), RW_WRITE);
895 blockdata_write(new_chain->addr.key.keydata, new_chain->addr.key.keylen, daemon->pipe_to_parent);
896 }
897 else if (flags & F_DS)
898 {
899 read_write(daemon->pipe_to_parent, (unsigned char *)&class, sizeof(class), RW_WRITE);
900 /* A negative DS entry is possible and has no data, obviously. */
901 if (!(flags & F_NEG))
902 blockdata_write(new_chain->addr.ds.keydata, new_chain->addr.ds.keylen, daemon->pipe_to_parent);
903 }
904 #endif
905 }
906 }
907
908 new_chain = tmp;
909 }
910
911 /* signal end of cache insert in master process */
912 if (daemon->pipe_to_parent != -1)
913 {
914 ssize_t m = -1;
915 read_write(daemon->pipe_to_parent, (unsigned char *)&m, sizeof(m), RW_WRITE);
916 }
917 }
918
919 #ifdef HAVE_DNSSEC
920 void cache_update_hwm(void)
921 {
922 /* Sneak out possibly updated crypto HWM values. */
923 unsigned char op = PIPE_OP_STATS;
924
925 read_write(daemon->pipe_to_parent, &op, sizeof(op), RW_WRITE);
926 read_write(daemon->pipe_to_parent,
927 (unsigned char *)&daemon->metrics[METRIC_CRYPTO_HWM],
928 sizeof(daemon->metrics[METRIC_CRYPTO_HWM]), RW_WRITE);
929 read_write(daemon->pipe_to_parent,
930 (unsigned char *)&daemon->metrics[METRIC_SIG_FAIL_HWM],
931 sizeof(daemon->metrics[METRIC_SIG_FAIL_HWM]), RW_WRITE);
932 read_write(daemon->pipe_to_parent,
933 (unsigned char *)&daemon->metrics[METRIC_WORK_HWM],
934 sizeof(daemon->metrics[METRIC_WORK_HWM]), RW_WRITE);
935 }
936 #endif
937
938 #if defined(HAVE_IPSET) || defined(HAVE_NFTSET)
939 void cache_send_ipset(unsigned char op, struct ipsets *sets, int flags, union all_addr *addr)
940 {
941 read_write(daemon->pipe_to_parent, &op, sizeof(op), RW_WRITE);
942 read_write(daemon->pipe_to_parent, (unsigned char *)&sets, sizeof(sets), RW_WRITE);
943 read_write(daemon->pipe_to_parent, (unsigned char *)&flags, sizeof(flags), RW_WRITE);
944 read_write(daemon->pipe_to_parent, (unsigned char *)addr, sizeof(*addr), RW_WRITE);
945 }
946 #endif
947
948 /* Retrieve and handle a result from child TCP-handler.
949 Return 0 when pipe is closed by far end. */
950 int cache_recv_insert(time_t now, int fd)
951 {
952 unsigned char op;
953
954 if (!read_write(fd, &op, sizeof(op), RW_READ))
955 return 0;
956
957 switch (op)
958 {
959 case PIPE_OP_INSERT:
960 {
961 /* A marshalled set if cache entries arrives on fd, read, unmarshall and insert into cache of master process. */
962 ssize_t m;
963 union all_addr addr;
964 unsigned long ttl;
965 time_t ttd;
966 unsigned int flags;
967 struct crec *crecp = NULL;
968
969 cache_start_insert();
970
971 /* loop reading RRs, since we don't want to go back to the poll() loop
972 and start processing other queries which might pollute the insertion
973 chain. The child will never block between the first OP_RR and the
974 minus-one length marking the end. */
975 while (1)
976 {
977 if (!read_write(fd, (unsigned char *)&m, sizeof(m), RW_READ))
978 return 0;
979
980 if (m == -1)
981 {
982 cache_end_insert();
983 return 1;
984 }
985
986 if (!read_write(fd, (unsigned char *)daemon->namebuff, m, RW_READ) ||
987 !read_write(fd, (unsigned char *)&ttd, sizeof(ttd), RW_READ) ||
988 !read_write(fd, (unsigned char *)&flags, sizeof(flags), RW_READ) ||
989 !read_write(fd, (unsigned char *)&addr, sizeof(addr), RW_READ))
990 return 0;
991
992 daemon->namebuff[m] = 0;
993
994 ttl = difftime(ttd, now);
995
996 if (flags & F_CNAME)
997 {
998 struct crec *newc = really_insert(daemon->namebuff, NULL, C_IN, now, ttl, flags);
999 /* This relies on the fact that the target of a CNAME immediately precedes
1000 it because of the order of extraction in extract_addresses, and
1001 the order reversal on the new_chain. */
1002 if (newc)
1003 {
1004 newc->addr.cname.is_name_ptr = 0;
1005 newc->addr.cname.target.cache = crecp;
1006
1007 if (crecp)
1008 {
1009 next_uid(crecp);
1010 newc->addr.cname.uid = crecp->uid;
1011 }
1012 crecp = newc;
1013 }
1014 }
1015 else
1016 {
1017 unsigned short class = C_IN;
1018 struct blockdata *block = NULL;
1019
1020 if ((flags & F_RR) && !(flags & F_NEG) && (flags & F_KEYTAG)
1021 && !(block = addr.rrblock.rrdata = blockdata_read(fd, addr.rrblock.datalen)))
1022 continue;
1023 #ifdef HAVE_DNSSEC
1024 else if (flags & F_DNSKEY)
1025 {
1026 if (!read_write(fd, (unsigned char *)&class, sizeof(class), RW_READ))
1027 return 0;
1028 if (!(block = addr.key.keydata = blockdata_read(fd, addr.key.keylen)))
1029 continue;
1030 }
1031 else if (flags & F_DS)
1032 {
1033 if (!read_write(fd, (unsigned char *)&class, sizeof(class), RW_READ))
1034 return 0;
1035 if (!(flags & F_NEG) && !(block = addr.ds.keydata = blockdata_read(fd, addr.ds.keylen)))
1036 continue;
1037 }
1038 #endif
1039 if (!(crecp = really_insert(daemon->namebuff, &addr, class, now, ttl, flags)))
1040 blockdata_free(block);
1041 }
1042 }
1043 }
1044
1045 #ifdef HAVE_DNSSEC
1046 case PIPE_OP_STATS:
1047 {
1048 /* Sneak in possibly updated crypto HWM. */
1049 unsigned int val;
1050
1051 if (!read_write(fd, (unsigned char *)&val, sizeof(val), RW_READ))
1052 return 0;
1053 if (val > daemon->metrics[METRIC_CRYPTO_HWM])
1054 daemon->metrics[METRIC_CRYPTO_HWM] = val;
1055 if (!read_write(fd, (unsigned char *)&val, sizeof(val), RW_READ))
1056 return 0;
1057 if (val > daemon->metrics[METRIC_SIG_FAIL_HWM])
1058 daemon->metrics[METRIC_SIG_FAIL_HWM] = val;
1059 if (!read_write(fd, (unsigned char *)&val, sizeof(val), RW_READ))
1060 return 0;
1061 if (val > daemon->metrics[METRIC_WORK_HWM])
1062 daemon->metrics[METRIC_WORK_HWM] = val;
1063 return 1;
1064 }
1065
1066 case PIPE_OP_RESULT:
1067 case PIPE_OP_KILLED:
1068 {
1069 /* UDP validation moved to TCP to avoid truncation.
1070 Restart UDP validation process with the returned result. */
1071 int status, uid, keycount, validatecount;
1072 int *keycountp, *validatecountp;
1073 size_t ret_len;
1074
1075 struct frec *forward;
1076
1077 if (!read_write(fd, (unsigned char *)&status, sizeof(status), RW_READ) ||
1078 !read_write(fd, (unsigned char *)&ret_len, sizeof(ret_len), RW_READ) ||
1079 !read_write(fd, (unsigned char *)daemon->packet, ret_len, RW_READ) ||
1080 !read_write(fd, (unsigned char *)&forward, sizeof(forward), RW_READ) ||
1081 !read_write(fd, (unsigned char *)&uid, sizeof(uid), RW_READ))
1082 return 0;
1083
1084 if (op == PIPE_OP_RESULT &&
1085 (!read_write(fd, (unsigned char *)&keycount, sizeof(keycount), RW_READ) ||
1086 !read_write(fd, (unsigned char *)&keycountp, sizeof(keycountp), RW_READ) ||
1087 !read_write(fd, (unsigned char *)&validatecount, sizeof(validatecount), RW_READ) ||
1088 !read_write(fd, (unsigned char *)&validatecountp, sizeof(validatecountp), RW_READ)))
1089 return 0;
1090
1091 if (op == PIPE_OP_KILLED)
1092 my_syslog(LOG_INFO, _("TCP process for DNSSEC validation timed out"));
1093
1094 /* There's a chance that the frec may have timed-out and been
1095 freed before the TCP process returns, so check that the
1096 frec is still marked in use. Even if it is in use, there's a tiny chance
1097 that the frec may have been freed and _reused_ before the TCP process returns.
1098 Detect that with the uid field which is unique modulo 2^32 for each use. */
1099 if (forward->sentto && uid == forward->uid)
1100 {
1101 if (op == PIPE_OP_RESULT)
1102 {
1103 /* repatriate the work counters from the child process. */
1104 *keycountp = keycount;
1105 *validatecountp = validatecount;
1106 }
1107
1108 if (!forward->dependent)
1109 return_reply(now, forward, (struct dns_header *)daemon->packet, ret_len, status);
1110 else
1111 pop_and_retry_query(forward, status, now);
1112 }
1113
1114 return 1;
1115 }
1116 #endif
1117
1118 #if defined(HAVE_IPSET) || defined(HAVE_NFTSET)
1119 case PIPE_OP_IPSET:
1120 case PIPE_OP_NFTSET:
1121 {
1122 struct ipsets *sets;
1123 char **sets_cur;
1124 unsigned int flags;
1125 union all_addr addr;
1126
1127 if (!read_write(fd, (unsigned char *)&sets, sizeof(sets), RW_READ) ||
1128 !read_write(fd, (unsigned char *)&flags, sizeof(flags), RW_READ) ||
1129 !read_write(fd, (unsigned char *)&addr, sizeof(addr), RW_READ))
1130 return 0;
1131
1132 for (sets_cur = sets->sets; *sets_cur; sets_cur++)
1133 {
1134 int rc = -1;
1135
1136 #ifdef HAVE_IPSET
1137 if (op == PIPE_OP_IPSET)
1138 rc = add_to_ipset(*sets_cur, &addr, flags, 0);
1139 #endif
1140
1141 #ifdef HAVE_NFTSET
1142 if (op == PIPE_OP_NFTSET)
1143 rc = add_to_nftset(*sets_cur, &addr, flags, 0);
1144 #endif
1145
1146 if (rc == 0)
1147 log_query((flags & (F_IPV4 | F_IPV6)) | F_IPSET, sets->domain, &addr, *sets_cur, op == PIPE_OP_IPSET);
1148 }
1149
1150 return 1;
1151 }
1152 #endif
1153
1154 }
1155
1156 return 0;
1157 }
1158
1159 int cache_find_non_terminal(char *name, time_t now)
1160 {
1161 struct crec *crecp;
1162
1163 for (crecp = *hash_bucket(name); crecp; crecp = crecp->hash_next)
1164 if (!is_outdated_cname_pointer(crecp) &&
1165 !is_expired(now, crecp) &&
1166 (crecp->flags & F_FORWARD) &&
1167 !(crecp->flags & F_NXDOMAIN) &&
1168 hostname_isequal(name, cache_get_name(crecp)))
1169 return 1;
1170
1171 return 0;
1172 }
1173
1174 struct crec *cache_find_by_name(struct crec *crecp, char *name, time_t now, unsigned int prot)
1175 {
1176 struct crec *ans;
1177 int no_rr = (prot & F_NO_RR) || option_bool(OPT_NORR);
1178
1179 prot &= ~F_NO_RR;
1180
1181 if (crecp) /* iterating */
1182 ans = crecp->next;
1183 else
1184 {
1185 /* first search, look for relevant entries and push to top of list
1186 also free anything which has expired */
1187 struct crec *next, **up, **insert = NULL, **chainp = &ans;
1188 unsigned int ins_flags = 0;
1189
1190 for (up = hash_bucket(name), crecp = *up; crecp; crecp = next)
1191 {
1192 next = crecp->hash_next;
1193
1194 if (!is_expired(now, crecp) && !is_outdated_cname_pointer(crecp))
1195 {
1196 if ((crecp->flags & F_FORWARD) &&
1197 (crecp->flags & prot) &&
1198 hostname_isequal(cache_get_name(crecp), name))
1199 {
1200 if (crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG))
1201 {
1202 *chainp = crecp;
1203 chainp = &crecp->next;
1204 }
1205 else
1206 {
1207 cache_unlink(crecp);
1208 cache_link(crecp);
1209 }
1210
1211 /* Move all but the first entry up the hash chain
1212 this implements round-robin.
1213 Make sure that re-ordering doesn't break the hash-chain
1214 order invariants.
1215 */
1216 if (insert && (crecp->flags & (F_REVERSE | F_IMMORTAL)) == ins_flags)
1217 {
1218 *up = crecp->hash_next;
1219 crecp->hash_next = *insert;
1220 *insert = crecp;
1221 insert = &crecp->hash_next;
1222 }
1223 else
1224 {
1225 if (!insert && !no_rr)
1226 {
1227 insert = up;
1228 ins_flags = crecp->flags & (F_REVERSE | F_IMMORTAL);
1229 }
1230 up = &crecp->hash_next;
1231 }
1232 }
1233 else
1234 /* case : not expired, incorrect entry. */
1235 up = &crecp->hash_next;
1236 }
1237 else
1238 {
1239 /* expired entry, free it */
1240 *up = crecp->hash_next;
1241 if (!(crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG)))
1242 {
1243 cache_unlink(crecp);
1244 cache_free(crecp);
1245 }
1246 }
1247 }
1248
1249 *chainp = cache_head;
1250 }
1251
1252 if (ans &&
1253 (ans->flags & F_FORWARD) &&
1254 (ans->flags & prot) &&
1255 hostname_isequal(cache_get_name(ans), name))
1256 return ans;
1257
1258 return NULL;
1259 }
1260
1261 struct crec *cache_find_by_addr(struct crec *crecp, union all_addr *addr,
1262 time_t now, unsigned int prot)
1263 {
1264 struct crec *ans;
1265 int addrlen = (prot == F_IPV6) ? IN6ADDRSZ : INADDRSZ;
1266
1267 if (crecp) /* iterating */
1268 ans = crecp->next;
1269 else
1270 {
1271 /* first search, look for relevant entries and push to top of list
1272 also free anything which has expired. All the reverse entries are at the
1273 start of the hash chain, so we can give up when we find the first
1274 non-REVERSE one. */
1275 int i;
1276 struct crec **up, **chainp = &ans;
1277
1278 for (i=0; i<hash_size; i++)
1279 for (crecp = hash_table[i], up = &hash_table[i];
1280 crecp && (crecp->flags & F_REVERSE);
1281 crecp = crecp->hash_next)
1282 if (!is_expired(now, crecp))
1283 {
1284 if ((crecp->flags & prot) &&
1285 memcmp(&crecp->addr, addr, addrlen) == 0)
1286 {
1287 if (crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG))
1288 {
1289 *chainp = crecp;
1290 chainp = &crecp->next;
1291 }
1292 else
1293 {
1294 cache_unlink(crecp);
1295 cache_link(crecp);
1296 }
1297 }
1298 up = &crecp->hash_next;
1299 }
1300 else
1301 {
1302 *up = crecp->hash_next;
1303 if (!(crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG)))
1304 {
1305 cache_unlink(crecp);
1306 cache_free(crecp);
1307 }
1308 }
1309
1310 *chainp = cache_head;
1311 }
1312
1313 if (ans &&
1314 (ans->flags & F_REVERSE) &&
1315 (ans->flags & prot) &&
1316 memcmp(&ans->addr, addr, addrlen) == 0)
1317 return ans;
1318
1319 return NULL;
1320 }
1321
1322 static void add_hosts_entry(struct crec *cache, union all_addr *addr, int addrlen,
1323 unsigned int index, struct crec **rhash, int hashsz)
1324 {
1325 int i;
1326 unsigned int j;
1327 struct crec *lookup = NULL;
1328
1329 /* Remove duplicates in hosts files. */
1330 while ((lookup = cache_find_by_name(lookup, cache_get_name(cache), 0, cache->flags & (F_IPV4 | F_IPV6))))
1331 if ((lookup->flags & F_HOSTS) && memcmp(&lookup->addr, addr, addrlen) == 0)
1332 {
1333 free_config_crec(cache);
1334 return;
1335 }
1336
1337 /* Ensure there is only one address -> name mapping (first one trumps)
1338 We do this by steam here, The entries are kept in hash chains, linked
1339 by ->next (which is unused at this point) held in hash buckets in
1340 the array rhash, hashed on address. Note that rhash and the values
1341 in ->next are only valid whilst reading hosts files: the buckets are
1342 then freed, and the ->next pointer used for other things.
1343 Only insert each unique address once into this hashing structure.
1344
1345 This complexity avoids O(n^2) divergent CPU use whilst reading
1346 large (10000 entry) hosts files.
1347
1348 Note that we only do this process when bulk-reading hosts files,
1349 for incremental reads, rhash is NULL, and we use cache lookups
1350 instead.
1351 */
1352
1353 if (rhash)
1354 {
1355 /* hash address */
1356 for (j = 0, i = 0; i < addrlen; i++)
1357 j = (j*2 +((unsigned char *)addr)[i]) % hashsz;
1358
1359 for (lookup = rhash[j]; lookup; lookup = lookup->next)
1360 if ((lookup->flags & cache->flags & (F_IPV4 | F_IPV6)) &&
1361 memcmp(&lookup->addr, addr, addrlen) == 0)
1362 {
1363 cache->flags &= ~F_REVERSE;
1364 break;
1365 }
1366
1367 /* maintain address hash chain, insert new unique address */
1368 if (!lookup)
1369 {
1370 cache->next = rhash[j];
1371 rhash[j] = cache;
1372 }
1373 }
1374 else
1375 {
1376 /* incremental read, lookup in cache */
1377 lookup = cache_find_by_addr(NULL, addr, 0, cache->flags & (F_IPV4 | F_IPV6));
1378 if (lookup && lookup->flags & F_HOSTS)
1379 cache->flags &= ~F_REVERSE;
1380 }
1381
1382 cache->uid = index;
1383 memcpy(&cache->addr, addr, addrlen);
1384 cache_hash(cache);
1385 make_non_terminals(cache);
1386 }
1387
1388 static int eatspace(FILE *f)
1389 {
1390 int c, nl = 0;
1391
1392 while (1)
1393 {
1394 if ((c = getc(f)) == '#')
1395 while (c != '\n' && c != EOF)
1396 c = getc(f);
1397
1398 if (c == EOF)
1399 return 1;
1400
1401 if (!isspace(c))
1402 {
1403 ungetc(c, f);
1404 return nl;
1405 }
1406
1407 if (c == '\n')
1408 nl++;
1409 }
1410 }
1411
1412 static int gettok(FILE *f, char *token, size_t buffsz)
1413 {
1414 int c;
1415 unsigned int count = 0;
1416
1417 while (1)
1418 {
1419 if ((c = getc(f)) == EOF)
1420 return (count == 0) ? -1 : 1;
1421
1422 if (isspace(c) || c == '#')
1423 {
1424 ungetc(c, f);
1425 return eatspace(f);
1426 }
1427
1428 if (count < (buffsz - 1))
1429 {
1430 token[count++] = c;
1431 token[count] = 0;
1432 }
1433 }
1434 }
1435
1436 int read_hostsfile(char *filename, unsigned int index, int cache_size, struct crec **rhash, int hashsz)
1437 {
1438 FILE *f = fopen(filename, "r");
1439 char *token = daemon->namebuff, *domain_suffix = NULL;
1440 int names_done = 0, name_count = cache_size, lineno = 1;
1441 unsigned int flags = 0;
1442 union all_addr addr;
1443 int atnl, addrlen = 0;
1444
1445 if (!f)
1446 {
1447 my_syslog(LOG_ERR, _("failed to load names from %s: %s"), filename, strerror(errno));
1448 return cache_size;
1449 }
1450
1451 lineno += eatspace(f);
1452
1453 while ((atnl = gettok(f, token, MAXDNAMESTR)) != -1)
1454 {
1455 if (inet_pton(AF_INET, token, &addr) > 0)
1456 {
1457 flags = F_NAMEP | F_HOSTS | F_IMMORTAL | F_FORWARD | F_REVERSE | F_IPV4;
1458 addrlen = INADDRSZ;
1459 domain_suffix = get_domain(addr.addr4);
1460 }
1461 else if (inet_pton(AF_INET6, token, &addr) > 0)
1462 {
1463 flags = F_NAMEP | F_HOSTS | F_IMMORTAL | F_FORWARD | F_REVERSE | F_IPV6;
1464 addrlen = IN6ADDRSZ;
1465 domain_suffix = get_domain6(&addr.addr6);
1466 }
1467 else
1468 {
1469 my_syslog(LOG_ERR, _("bad address at %s line %d"), filename, lineno);
1470 while (atnl == 0)
1471 atnl = gettok(f, token, MAXDNAMESTR);
1472 lineno += atnl;
1473 continue;
1474 }
1475
1476 /* rehash every 1000 names. */
1477 if (rhash && ((name_count - cache_size) > 1000))
1478 {
1479 rehash(name_count);
1480 cache_size = name_count;
1481 }
1482
1483 while (atnl == 0)
1484 {
1485 struct crec *cache;
1486 int fqdn, nomem;
1487 char *canon;
1488
1489 if ((atnl = gettok(f, token, MAXDNAMESTR)) == -1)
1490 break;
1491
1492 fqdn = !!strchr(token, '.');
1493
1494 if ((canon = canonicalise(token, &nomem)))
1495 {
1496 /* If set, add a version of the name with a default domain appended */
1497 if (option_bool(OPT_EXPAND) && domain_suffix && !fqdn && (cache = get_config_crec()))
1498 {
1499 if (!(cache->name.namep = store_name(strlen(canon) + 2 + strlen(domain_suffix), index)))
1500 free_config_crec(cache);
1501 else
1502 {
1503 strcpy(cache->name.namep, canon);
1504 strcat(cache->name.namep, ".");
1505 strcat(cache->name.namep, domain_suffix);
1506 cache->flags = flags;
1507 cache->ttd = daemon->local_ttl;
1508 add_hosts_entry(cache, &addr, addrlen, index, rhash, hashsz);
1509 name_count++;
1510 names_done++;
1511 }
1512 }
1513 if ((cache = get_config_crec()))
1514 {
1515 if (!(cache->name.namep = store_name(strlen(canon) + 1, index)))
1516 free_config_crec(cache);
1517 else
1518 {
1519 strcpy(cache->name.namep, canon);
1520 cache->flags = flags;
1521 cache->ttd = daemon->local_ttl;
1522 add_hosts_entry(cache, &addr, addrlen, index, rhash, hashsz);
1523 name_count++;
1524 names_done++;
1525 }
1526 }
1527
1528 free(canon);
1529
1530 }
1531 else if (!nomem)
1532 my_syslog(LOG_ERR, _("bad name at %s line %d"), filename, lineno);
1533 }
1534
1535 lineno += atnl;
1536 }
1537
1538 fclose(f);
1539
1540 if (rhash)
1541 rehash(name_count);
1542
1543 my_syslog(LOG_INFO, _("read %s - %d names"), filename, names_done);
1544
1545 return name_count;
1546 }
1547
1548 void cache_reload(void)
1549 {
1550 struct crec *cache, **up, *tmp;
1551 int revhashsz, i, total_size = daemon->cachesize;
1552 struct hostsfile *ah;
1553 struct host_record *hr;
1554 struct name_list *nl;
1555 struct cname *a;
1556 struct crec lrec;
1557 struct mx_srv_record *mx;
1558 struct txt_record *txt;
1559 struct interface_name *intr;
1560 struct ptr_record *ptr;
1561 struct naptr *naptr;
1562 #ifdef HAVE_DNSSEC
1563 struct ds_config *ds;
1564 #endif
1565
1566 daemon->metrics[METRIC_DNS_CACHE_INSERTED] = 0;
1567 daemon->metrics[METRIC_DNS_CACHE_LIVE_FREED] = 0;
1568
1569 for (i=0; i<hash_size; i++)
1570 for (cache = hash_table[i], up = &hash_table[i]; cache; cache = tmp)
1571 {
1572 cache_blockdata_free(cache);
1573
1574 tmp = cache->hash_next;
1575 if (cache->flags & (F_HOSTS | F_CONFIG))
1576 {
1577 *up = cache->hash_next;
1578 free_config_crec(cache);
1579 }
1580 else if (!(cache->flags & F_DHCP))
1581 {
1582 *up = cache->hash_next;
1583 if (cache->flags & F_BIGNAME)
1584 {
1585 cache->name.bname->next = big_free;
1586 big_free = cache->name.bname;
1587 }
1588 cache->flags = 0;
1589 }
1590 else
1591 up = &cache->hash_next;
1592 }
1593
1594 free_names(UID_NONE); /* free everything */
1595
1596 /* Add locally-configured CNAMEs to the cache */
1597 for (a = daemon->cnames; a; a = a->next)
1598 if (a->alias[1] != '*' &&
1599 ((cache = get_config_crec())))
1600 {
1601 cache->flags = F_FORWARD | F_NAMEP | F_CNAME | F_IMMORTAL | F_CONFIG;
1602 cache->ttd = a->ttl;
1603 cache->name.namep = a->alias;
1604 cache->addr.cname.target.name = a->target;
1605 cache->addr.cname.is_name_ptr = 1;
1606 cache->uid = UID_NONE;
1607 cache_hash(cache);
1608 make_non_terminals(cache);
1609 }
1610
1611 #ifdef HAVE_DNSSEC
1612 for (ds = daemon->ds; ds; ds = ds->next)
1613 if (ds->name && (cache = get_config_crec()))
1614 {
1615
1616 if (!(cache->addr.ds.keydata = blockdata_alloc(ds->digest, ds->digestlen)))
1617 free_config_crec(cache);
1618 else
1619 {
1620 cache->flags = F_FORWARD | F_IMMORTAL | F_DS | F_CONFIG | F_NAMEP;
1621 cache->ttd = daemon->local_ttl;
1622 cache->name.namep = ds->name;
1623 cache->uid = ds->class;
1624 if (ds->digestlen != 0)
1625 {
1626 cache->addr.ds.keylen = ds->digestlen;
1627 cache->addr.ds.algo = ds->algo;
1628 cache->addr.ds.keytag = ds->keytag;
1629 cache->addr.ds.digest = ds->digest_type;
1630 }
1631 else
1632 cache->flags |= F_NEG | F_DNSSECOK | F_NO_RR;
1633
1634 cache_hash(cache);
1635 make_non_terminals(cache);
1636 }
1637 }
1638 #endif
1639
1640 /* borrow the packet buffer for a temporary by-address hash */
1641 memset(daemon->packet, 0, daemon->packet_buff_sz);
1642 revhashsz = daemon->packet_buff_sz / sizeof(struct crec *);
1643 /* we overwrote the buffer... */
1644 daemon->srv_save = NULL;
1645
1646 /* Do host_records in config. */
1647 for (hr = daemon->host_records; hr; hr = hr->next)
1648 for (nl = hr->names; nl; nl = nl->next)
1649 {
1650 if ((hr->flags & HR_4) &&
1651 (cache = get_config_crec()))
1652 {
1653 cache->name.namep = nl->name;
1654 cache->ttd = hr->ttl;
1655 cache->flags = F_HOSTS | F_IMMORTAL | F_FORWARD | F_REVERSE | F_IPV4 | F_NAMEP | F_CONFIG;
1656 add_hosts_entry(cache, (union all_addr *)&hr->addr, INADDRSZ, SRC_CONFIG, (struct crec **)daemon->packet, revhashsz);
1657 }
1658
1659 if ((hr->flags & HR_6) &&
1660 (cache = get_config_crec()))
1661 {
1662 cache->name.namep = nl->name;
1663 cache->ttd = hr->ttl;
1664 cache->flags = F_HOSTS | F_IMMORTAL | F_FORWARD | F_REVERSE | F_IPV6 | F_NAMEP | F_CONFIG;
1665 add_hosts_entry(cache, (union all_addr *)&hr->addr6, IN6ADDRSZ, SRC_CONFIG, (struct crec **)daemon->packet, revhashsz);
1666 }
1667 }
1668
1669 if (option_bool(OPT_NO_HOSTS) && !daemon->addn_hosts)
1670 {
1671 if (daemon->cachesize > 0)
1672 my_syslog(LOG_INFO, _("cleared cache"));
1673 }
1674 else
1675 {
1676 if (!option_bool(OPT_NO_HOSTS))
1677 total_size = read_hostsfile(HOSTSFILE, SRC_HOSTS, total_size, (struct crec **)daemon->packet, revhashsz);
1678
1679 daemon->addn_hosts = expand_filelist(daemon->addn_hosts);
1680 for (ah = daemon->addn_hosts; ah; ah = ah->next)
1681 if (!(ah->flags & AH_INACTIVE))
1682 total_size = read_hostsfile(ah->fname, ah->index, total_size, (struct crec **)daemon->packet, revhashsz);
1683 }
1684
1685 /* Make non-terminal records for all locally-define RRs */
1686 lrec.flags = F_FORWARD | F_CONFIG | F_NAMEP | F_IMMORTAL;
1687
1688 for (txt = daemon->txt; txt; txt = txt->next)
1689 {
1690 lrec.name.namep = txt->name;
1691 make_non_terminals(&lrec);
1692 }
1693
1694 for (naptr = daemon->naptr; naptr; naptr = naptr->next)
1695 {
1696 lrec.name.namep = naptr->name;
1697 make_non_terminals(&lrec);
1698 }
1699
1700 for (mx = daemon->mxnames; mx; mx = mx->next)
1701 {
1702 lrec.name.namep = mx->name;
1703 make_non_terminals(&lrec);
1704 }
1705
1706 for (intr = daemon->int_names; intr; intr = intr->next)
1707 {
1708 lrec.name.namep = intr->name;
1709 make_non_terminals(&lrec);
1710 }
1711
1712 for (ptr = daemon->ptr; ptr; ptr = ptr->next)
1713 {
1714 lrec.name.namep = ptr->name;
1715 make_non_terminals(&lrec);
1716 }
1717
1718 #ifdef HAVE_INOTIFY
1719 set_dynamic_inotify(AH_HOSTS, total_size, (struct crec **)daemon->packet, revhashsz);
1720 #endif
1721
1722 }
1723
1724 #ifdef HAVE_DHCP
1725 struct in_addr a_record_from_hosts(char *name, time_t now)
1726 {
1727 struct crec *crecp = NULL;
1728 struct in_addr ret;
1729
1730 /* If no DNS service, cache not initialised. */
1731 if (daemon->port != 0)
1732 while ((crecp = cache_find_by_name(crecp, name, now, F_IPV4)))
1733 if (crecp->flags & F_HOSTS)
1734 return crecp->addr.addr4;
1735
1736 my_syslog(MS_DHCP | LOG_WARNING, _("No IPv4 address found for %s"), name);
1737
1738 ret.s_addr = 0;
1739 return ret;
1740 }
1741
1742 void cache_unhash_dhcp(void)
1743 {
1744 struct crec *cache, **up;
1745 int i;
1746
1747 for (i=0; i<hash_size; i++)
1748 for (cache = hash_table[i], up = &hash_table[i]; cache; cache = cache->hash_next)
1749 if (cache->flags & F_DHCP)
1750 {
1751 *up = cache->hash_next;
1752 free_config_crec(cache);
1753 }
1754 else
1755 up = &cache->hash_next;
1756 }
1757
1758 void cache_add_dhcp_entry(char *host_name, int prot,
1759 union all_addr *host_address, time_t ttd)
1760 {
1761 struct crec *crec = NULL, *fail_crec = NULL;
1762 unsigned int flags = F_IPV4;
1763 int in_hosts = 0;
1764 size_t addrlen = sizeof(struct in_addr);
1765
1766 if (prot == AF_INET6)
1767 {
1768 flags = F_IPV6;
1769 addrlen = sizeof(struct in6_addr);
1770 }
1771
1772 inet_ntop(prot, host_address, daemon->addrbuff, ADDRSTRLEN);
1773
1774 while ((crec = cache_find_by_name(crec, host_name, 0, flags | F_CNAME)))
1775 {
1776 /* check all addresses associated with name */
1777 if (crec->flags & (F_HOSTS | F_CONFIG))
1778 {
1779 if (crec->flags & F_CNAME)
1780 my_syslog(MS_DHCP | LOG_WARNING,
1781 _("%s is a CNAME, not giving it to the DHCP lease of %s"),
1782 host_name, daemon->addrbuff);
1783 else if (memcmp(&crec->addr, host_address, addrlen) == 0)
1784 in_hosts = 1;
1785 else
1786 fail_crec = crec;
1787 }
1788 else if (!(crec->flags & F_DHCP))
1789 {
1790 cache_scan_free(host_name, NULL, C_IN, 0, crec->flags & (flags | F_CNAME | F_FORWARD), NULL, NULL);
1791 /* scan_free deletes all addresses associated with name */
1792 break;
1793 }
1794 }
1795
1796 /* if in hosts, don't need DHCP record */
1797 if (in_hosts)
1798 return;
1799
1800 /* Name in hosts, address doesn't match */
1801 if (fail_crec)
1802 {
1803 inet_ntop(prot, &fail_crec->addr, daemon->namebuff, MAXDNAMESTR);
1804 my_syslog(MS_DHCP | LOG_WARNING,
1805 _("not giving name %s to the DHCP lease of %s because "
1806 "the name exists in %s with address %s"),
1807 host_name, daemon->addrbuff,
1808 record_source(fail_crec->uid), daemon->namebuff);
1809 return;
1810 }
1811
1812 if ((crec = cache_find_by_addr(NULL, (union all_addr *)host_address, 0, flags)))
1813 {
1814 if (crec->flags & F_NEG)
1815 {
1816 flags |= F_REVERSE;
1817 cache_scan_free(NULL, (union all_addr *)host_address, C_IN, 0, flags, NULL, NULL);
1818 }
1819 }
1820 else
1821 flags |= F_REVERSE;
1822
1823 if ((crec = get_config_crec()))
1824 {
1825 crec->flags = flags | F_NAMEP | F_DHCP | F_FORWARD;
1826 if (ttd == 0)
1827 crec->flags |= F_IMMORTAL;
1828 else
1829 crec->ttd = ttd;
1830 crec->addr = *host_address;
1831 crec->name.namep = host_name;
1832 crec->uid = UID_NONE;
1833 cache_hash(crec);
1834 make_non_terminals(crec);
1835 }
1836 }
1837 #endif
1838
1839 /* Called when we put a local or DHCP name into the cache.
1840 Creates empty cache entries for subnames (ie,
1841 for three.two.one, for two.one and one), without
1842 F_IPV4 or F_IPV6 or F_CNAME set. These convert
1843 NXDOMAIN answers to NoData ones. */
1844 static void make_non_terminals(struct crec *source)
1845 {
1846 char *name = cache_get_name(source);
1847 struct crec *crecp, *tmp, **up;
1848 int type = F_HOSTS | F_CONFIG;
1849 #ifdef HAVE_DHCP
1850 if (source->flags & F_DHCP)
1851 type = F_DHCP;
1852 #endif
1853
1854 /* First delete any empty entries for our new real name. Note that
1855 we only delete empty entries deriving from DHCP for a new DHCP-derived
1856 entry and vice-versa for HOSTS and CONFIG. This ensures that
1857 non-terminals from DHCP go when we reload DHCP and
1858 for HOSTS/CONFIG when we re-read. */
1859 for (up = hash_bucket(name), crecp = *up; crecp; crecp = tmp)
1860 {
1861 tmp = crecp->hash_next;
1862
1863 if (!is_outdated_cname_pointer(crecp) &&
1864 (crecp->flags & F_FORWARD) &&
1865 (crecp->flags & type) &&
1866 !(crecp->flags & (F_IPV4 | F_IPV6 | F_CNAME | F_DNSKEY | F_DS | F_RR)) &&
1867 hostname_isequal(name, cache_get_name(crecp)))
1868 {
1869 *up = crecp->hash_next;
1870 free_config_crec(crecp);
1871 break;
1872 }
1873 else
1874 up = &crecp->hash_next;
1875 }
1876
1877 while ((name = strchr(name, '.')))
1878 {
1879 name++;
1880
1881 /* Look for one existing, don't need another */
1882 for (crecp = *hash_bucket(name); crecp; crecp = crecp->hash_next)
1883 if (!is_outdated_cname_pointer(crecp) &&
1884 (crecp->flags & F_FORWARD) &&
1885 (crecp->flags & type) &&
1886 hostname_isequal(name, cache_get_name(crecp)))
1887 break;
1888
1889 if (crecp)
1890 {
1891 /* If the new name expires later, transfer that time to
1892 empty non-terminal entry. */
1893 if (!(crecp->flags & F_IMMORTAL))
1894 {
1895 if (source->flags & F_IMMORTAL)
1896 crecp->flags |= F_IMMORTAL;
1897 else if (difftime(crecp->ttd, source->ttd) < 0)
1898 crecp->ttd = source->ttd;
1899 }
1900 continue;
1901 }
1902
1903 if ((crecp = get_config_crec()))
1904 {
1905 crecp->flags = (source->flags | F_NAMEP) & ~(F_IPV4 | F_IPV6 | F_CNAME | F_RR | F_DNSKEY | F_DS | F_REVERSE);
1906 if (!(crecp->flags & F_IMMORTAL))
1907 crecp->ttd = source->ttd;
1908 crecp->name.namep = name;
1909
1910 cache_hash(crecp);
1911 }
1912 }
1913 }
1914
1915 #ifndef NO_ID
1916 int cache_make_stat(struct txt_record *t)
1917 {
1918 static char *buff = NULL;
1919 static int bufflen = 60;
1920 int len;
1921 struct server *serv, *serv1;
1922 char *p;
1923
1924 if (!buff && !(buff = whine_malloc(60)))
1925 return 0;
1926
1927 p = buff;
1928
1929 switch (t->stat)
1930 {
1931 case TXT_STAT_CACHESIZE:
1932 sprintf(buff+1, "%d", daemon->cachesize);
1933 break;
1934
1935 case TXT_STAT_INSERTS:
1936 sprintf(buff+1, "%d", daemon->metrics[METRIC_DNS_CACHE_INSERTED]);
1937 break;
1938
1939 case TXT_STAT_EVICTIONS:
1940 sprintf(buff+1, "%d", daemon->metrics[METRIC_DNS_CACHE_LIVE_FREED]);
1941 break;
1942
1943 case TXT_STAT_MISSES:
1944 sprintf(buff+1, "%u", daemon->metrics[METRIC_DNS_QUERIES_FORWARDED]);
1945 break;
1946
1947 case TXT_STAT_HITS:
1948 sprintf(buff+1, "%u", daemon->metrics[METRIC_DNS_LOCAL_ANSWERED]);
1949 break;
1950
1951 #ifdef HAVE_AUTH
1952 case TXT_STAT_AUTH:
1953 sprintf(buff+1, "%u", daemon->metrics[METRIC_DNS_AUTH_ANSWERED]);
1954 break;
1955 #endif
1956
1957 case TXT_STAT_SERVERS:
1958 /* sum counts from different records for same server */
1959 for (serv = daemon->servers; serv; serv = serv->next)
1960 serv->flags &= ~SERV_MARK;
1961
1962 for (serv = daemon->servers; serv; serv = serv->next)
1963 if (!(serv->flags & SERV_MARK))
1964 {
1965 char *new, *lenp;
1966 int port, newlen, bytes_avail, bytes_needed;
1967 unsigned int queries = 0, failed_queries = 0;
1968 for (serv1 = serv; serv1; serv1 = serv1->next)
1969 if (!(serv1->flags & SERV_MARK) && sockaddr_isequal(&serv->addr, &serv1->addr))
1970 {
1971 serv1->flags |= SERV_MARK;
1972 queries += serv1->queries;
1973 failed_queries += serv1->failed_queries;
1974 }
1975 port = prettyprint_addr(&serv->addr, daemon->addrbuff);
1976 lenp = p++; /* length */
1977 bytes_avail = bufflen - (p - buff );
1978 bytes_needed = snprintf(p, bytes_avail, "%s#%d %u %u", daemon->addrbuff, port, queries, failed_queries);
1979 if (bytes_needed >= bytes_avail)
1980 {
1981 /* expand buffer if necessary */
1982 newlen = bytes_needed + 1 + bufflen - bytes_avail;
1983 if (!(new = whine_realloc(buff, newlen)))
1984 return 0;
1985 p = new + (p - buff);
1986 lenp = p - 1;
1987 buff = new;
1988 bufflen = newlen;
1989 bytes_avail = bufflen - (p - buff );
1990 bytes_needed = snprintf(p, bytes_avail, "%s#%d %u %u", daemon->addrbuff, port, queries, failed_queries);
1991 }
1992 *lenp = bytes_needed;
1993 p += bytes_needed;
1994 }
1995 t->txt = (unsigned char *)buff;
1996 t->len = p - buff;
1997
1998 return 1;
1999 }
2000
2001 len = strlen(buff+1);
2002 t->txt = (unsigned char *)buff;
2003 t->len = len + 1;
2004 *buff = len;
2005 return 1;
2006 }
2007 #endif
2008
2009 /* There can be names in the cache containing control chars, don't
2010 mess up logging or open security holes. Also convert to all-LC
2011 so that 0x20-encoding doesn't make logs look like ransom notes
2012 made out of letters cut from a newspaper.
2013 Overwrites daemon->workspacename */
2014 static char *sanitise(char *name)
2015 {
2016 unsigned char *r = (unsigned char *)name;
2017
2018 if (name)
2019 {
2020 char *d = name = daemon->workspacename;
2021
2022 for (; *r; r++, d++)
2023 if (!isprint((int)*r))
2024 return "<name unprintable>";
2025 else
2026 {
2027 unsigned char c = *r;
2028
2029 *d = (char)((c >= 'A' && c <= 'Z') ? c + 'a' - 'A' : c);
2030 }
2031
2032 *d = 0;
2033 }
2034
2035 return name;
2036 }
2037
2038 static void dump_cache_entry(struct crec *cache, time_t now)
2039 {
2040 (void)now;
2041 static char *buff = NULL;
2042
2043 char *p, *t = " ";
2044 char *a = daemon->addrbuff, *n = cache_get_name(cache);
2045
2046 /* String length is limited below */
2047 if (!buff && !(buff = whine_malloc(150)))
2048 return;
2049
2050 p = buff;
2051
2052 *a = 0;
2053
2054 if (cache->flags & F_REVERSE)
2055 {
2056 if ((cache->flags & F_NEG))
2057 n = "";
2058 }
2059 else
2060 {
2061 if (strlen(n) == 0)
2062 n = "<Root>";
2063 }
2064
2065 p += sprintf(p, "%-30.30s ", sanitise(n));
2066 if ((cache->flags & F_CNAME) && !is_outdated_cname_pointer(cache))
2067 a = sanitise(cache_get_cname_target(cache));
2068 else if (cache->flags & F_RR)
2069 {
2070 if (cache->flags & F_KEYTAG)
2071 sprintf(a, "%s", querystr(NULL, cache->addr.rrblock.rrtype));
2072 else
2073 sprintf(a, "%s", querystr(NULL, cache->addr.rrdata.rrtype));
2074 }
2075 #ifdef HAVE_DNSSEC
2076 else if (cache->flags & F_DS)
2077 {
2078 if (!(cache->flags & F_NEG))
2079 sprintf(a, "%5u %3u %3u", cache->addr.ds.keytag,
2080 cache->addr.ds.algo, cache->addr.ds.digest);
2081 }
2082 else if (cache->flags & F_DNSKEY)
2083 sprintf(a, "%5u %3u %3u", cache->addr.key.keytag,
2084 cache->addr.key.algo, cache->addr.key.flags);
2085 #endif
2086 else if (!(cache->flags & F_NEG) || !(cache->flags & F_FORWARD))
2087 {
2088 a = daemon->addrbuff;
2089 if (cache->flags & F_IPV4)
2090 inet_ntop(AF_INET, &cache->addr, a, ADDRSTRLEN);
2091 else if (cache->flags & F_IPV6)
2092 inet_ntop(AF_INET6, &cache->addr, a, ADDRSTRLEN);
2093 }
2094
2095 if (cache->flags & F_IPV4)
2096 t = "4";
2097 else if (cache->flags & F_IPV6)
2098 t = "6";
2099 else if (cache->flags & F_CNAME)
2100 t = "C";
2101 else if (cache->flags & F_RR)
2102 t = "T";
2103 #ifdef HAVE_DNSSEC
2104 else if (cache->flags & F_DS)
2105 t = "S";
2106 else if (cache->flags & F_DNSKEY)
2107 t = "K";
2108 #endif
2109 else if (!(cache->flags & F_NXDOMAIN)) /* non-terminal */
2110 t = "!";
2111
2112 p += sprintf(p, "%-40.40s %s%s%s%s%s%s%s%s%s%s ", a, t,
2113 cache->flags & F_FORWARD ? "F" : " ",
2114 cache->flags & F_REVERSE ? "R" : " ",
2115 cache->flags & F_IMMORTAL ? "I" : " ",
2116 cache->flags & F_DHCP ? "D" : " ",
2117 cache->flags & F_NEG ? "N" : " ",
2118 cache->flags & F_NXDOMAIN ? "X" : " ",
2119 cache->flags & F_HOSTS ? "H" : " ",
2120 cache->flags & F_CONFIG ? "C" : " ",
2121 cache->flags & F_DNSSECOK ? "V" : " ");
2122 #ifdef HAVE_BROKEN_RTC
2123 p += sprintf(p, "%-24lu", cache->flags & F_IMMORTAL ? 0: (unsigned long)(cache->ttd - now));
2124 #else
2125 p += sprintf(p, "%-24.24s", cache->flags & F_IMMORTAL ? "" : ctime(&(cache->ttd)));
2126 #endif
2127 if(cache->flags & (F_HOSTS | F_CONFIG) && cache->uid > 0)
2128 p += sprintf(p, " %-40.40s", record_source(cache->uid));
2129
2130 my_syslog(LOG_INFO, "%s", buff);
2131 }
2132
2133 void dump_cache(time_t now)
2134 {
2135 struct server *serv, *serv1;
2136
2137 my_syslog(LOG_INFO, _("time %lu"), (unsigned long)now);
2138 my_syslog(LOG_INFO, _("cache size %d, %d/%d cache insertions re-used unexpired cache entries."),
2139 daemon->cachesize, daemon->metrics[METRIC_DNS_CACHE_LIVE_FREED], daemon->metrics[METRIC_DNS_CACHE_INSERTED]);
2140 my_syslog(LOG_INFO, _("queries forwarded %u, queries answered locally %u"),
2141 daemon->metrics[METRIC_DNS_QUERIES_FORWARDED], daemon->metrics[METRIC_DNS_LOCAL_ANSWERED]);
2142 if (daemon->cache_max_expiry != 0)
2143 my_syslog(LOG_INFO, _("queries answered from stale cache %u"), daemon->metrics[METRIC_DNS_STALE_ANSWERED]);
2144 #ifdef HAVE_AUTH
2145 my_syslog(LOG_INFO, _("queries for authoritative zones %u"), daemon->metrics[METRIC_DNS_AUTH_ANSWERED]);
2146 #endif
2147 #ifdef HAVE_DNSSEC
2148 my_syslog(LOG_INFO, _("DNSSEC per-query subqueries HWM %u"), daemon->metrics[METRIC_WORK_HWM]);
2149 my_syslog(LOG_INFO, _("DNSSEC per-query crypto work HWM %u"), daemon->metrics[METRIC_CRYPTO_HWM]);
2150 my_syslog(LOG_INFO, _("DNSSEC per-RRSet signature fails HWM %u"), daemon->metrics[METRIC_SIG_FAIL_HWM]);
2151 #endif
2152
2153 blockdata_report();
2154 my_syslog(LOG_INFO, _("child processes for TCP requests: in use %zu, highest since last SIGUSR1 %zu, max allowed %zu."),
2155 daemon->metrics[METRIC_TCP_CONNECTIONS],
2156 daemon->max_procs_used,
2157 daemon->max_procs);
2158 daemon->max_procs_used = daemon->metrics[METRIC_TCP_CONNECTIONS];
2159
2160 /* sum counts from different records for same server */
2161 for (serv = daemon->servers; serv; serv = serv->next)
2162 serv->flags &= ~SERV_MARK;
2163
2164 for (serv = daemon->servers; serv; serv = serv->next)
2165 if (!(serv->flags & SERV_MARK))
2166 {
2167 int port;
2168 unsigned int queries = 0, failed_queries = 0, nxdomain_replies = 0, retrys = 0;
2169 unsigned int sigma_latency = 0, count_latency = 0;
2170
2171 for (serv1 = serv; serv1; serv1 = serv1->next)
2172 if (!(serv1->flags & SERV_MARK) && sockaddr_isequal(&serv->addr, &serv1->addr))
2173 {
2174 serv1->flags |= SERV_MARK;
2175 queries += serv1->queries;
2176 failed_queries += serv1->failed_queries;
2177 nxdomain_replies += serv1->nxdomain_replies;
2178 retrys += serv1->retrys;
2179 sigma_latency += serv1->query_latency;
2180 count_latency++;
2181 }
2182 port = prettyprint_addr(&serv->addr, daemon->addrbuff);
2183 my_syslog(LOG_INFO, _("server %s#%d: queries sent %u, retried %u, failed %u, nxdomain replies %u, avg. latency %ums"),
2184 daemon->addrbuff, port, queries, retrys, failed_queries, nxdomain_replies, sigma_latency/count_latency);
2185 }
2186
2187 if (option_bool(OPT_DEBUG) || option_bool(OPT_LOG))
2188 {
2189 struct crec *cache;
2190 int i;
2191 my_syslog(LOG_INFO, "Host Address Flags Expires Source");
2192 my_syslog(LOG_INFO, "------------------------------ ---------------------------------------- ---------- ------------------------ ------------");
2193
2194 for (i=0; i<hash_size; i++)
2195 for (cache = hash_table[i]; cache; cache = cache->hash_next)
2196 dump_cache_entry(cache, now);
2197 }
2198 }
2199
2200 char *record_source(unsigned int index)
2201 {
2202 struct hostsfile *ah;
2203 #ifdef HAVE_INOTIFY
2204 struct dyndir *dd;
2205 #endif
2206
2207 if (index == SRC_CONFIG)
2208 return "config";
2209 else if (index == SRC_HOSTS)
2210 return HOSTSFILE;
2211
2212 for (ah = daemon->addn_hosts; ah; ah = ah->next)
2213 if (ah->index == index)
2214 return ah->fname;
2215
2216 #ifdef HAVE_INOTIFY
2217 /* Dynamic directories contain multiple files */
2218 for (dd = daemon->dynamic_dirs; dd; dd = dd->next)
2219 for (ah = dd->files; ah; ah = ah->next)
2220 if (ah->index == index)
2221 return ah->fname;
2222 #endif
2223
2224 return "<unknown>";
2225 }
2226
2227 static char *querystr(char *desc, unsigned short type)
2228 {
2229 unsigned int i;
2230 int len = 10; /* strlen("type=xxxxx") */
2231 const char *types = NULL;
2232 static struct iovec buff = { NULL, 0 };
2233 char *buffp;
2234
2235 for (i = 0; i < (sizeof(typestr)/sizeof(typestr[0])); i++)
2236 if (typestr[i].type == type)
2237 {
2238 types = typestr[i].name;
2239 len = strlen(types);
2240 break;
2241 }
2242
2243 if (desc)
2244 {
2245 len += 2; /* braces */
2246 len += strlen(desc);
2247 }
2248 len++; /* terminator */
2249
2250 if (!expand_buf(&buff, len))
2251 return "";
2252
2253 buffp = buff.iov_base;
2254
2255 if (desc)
2256 {
2257 if (types)
2258 sprintf(buffp, "%s[%s]", desc, types);
2259 else
2260 sprintf(buffp, "%s[type=%d]", desc, type);
2261 }
2262 else
2263 {
2264 if (types)
2265 sprintf(buffp, "<%s>", types);
2266 else
2267 sprintf(buffp, "<type=%d>", type);
2268 }
2269
2270 return buffp;
2271 }
2272
2273 static char *edestr(int ede)
2274 {
2275 switch (ede)
2276 {
2277 case EDE_OTHER: return "other";
2278 case EDE_USUPDNSKEY: return "unsupported DNSKEY algorithm";
2279 case EDE_USUPDS: return "unsupported DS digest";
2280 case EDE_STALE: return "stale answer";
2281 case EDE_FORGED: return "forged";
2282 case EDE_DNSSEC_IND: return "DNSSEC indeterminate";
2283 case EDE_DNSSEC_BOGUS: return "DNSSEC bogus";
2284 case EDE_SIG_EXP: return "DNSSEC signature expired";
2285 case EDE_SIG_NYV: return "DNSSEC sig not yet valid";
2286 case EDE_NO_DNSKEY: return "DNSKEY missing";
2287 case EDE_NO_RRSIG: return "RRSIG missing";
2288 case EDE_NO_ZONEKEY: return "no zone key bit set";
2289 case EDE_NO_NSEC: return "NSEC(3) missing";
2290 case EDE_CACHED_ERR: return "cached error";
2291 case EDE_NOT_READY: return "not ready";
2292 case EDE_BLOCKED: return "blocked";
2293 case EDE_CENSORED: return "censored";
2294 case EDE_FILTERED: return "filtered";
2295 case EDE_PROHIBITED: return "prohibited";
2296 case EDE_STALE_NXD: return "stale NXDOMAIN";
2297 case EDE_NOT_AUTH: return "not authoritative";
2298 case EDE_NOT_SUP: return "not supported";
2299 case EDE_NO_AUTH: return "no reachable authority";
2300 case EDE_NETERR: return "network error";
2301 case EDE_INVALID_DATA: return "invalid data";
2302 case EDE_SIG_E_B_V: return "signature expired before valid";
2303 case EDE_TOO_EARLY: return "too early";
2304 case EDE_UNS_NS3_ITER: return "unsupported NSEC3 iterations value";
2305 case EDE_UNABLE_POLICY: return "uanble to conform to policy";
2306 case EDE_SYNTHESIZED: return "synthesized";
2307 case EDE_US_SERVFAIL: return "upstream returned SERVFAIL";
2308 default: return "unknown";
2309 }
2310 }
2311
2312 static int error_occured(unsigned int flags) {
2313 if (flags & F_RCODE)
2314 return 1;
2315 else if (flags & F_NEG)
2316 return 1;
2317 else
2318 return 0;
2319 }
2320
2321 void log_query(unsigned int flags, char *name, union all_addr *addr, char *arg, unsigned short type)
2322 {
2323 char *source, *dest;
2324 char *verb = "is";
2325 char *extra = "";
2326 char *gap = " ";
2327 char portstring[7]; /* space for #<portnum> */
2328 char opcodestring[3]; /* maximum is 15 */
2329
2330 if (!option_bool(OPT_LOG))
2331 return;
2332
2333 if(option_bool(OPT_LOG_ONLY_FAILED) && !error_occured(flags))
2334 return;
2335
2336 /* F_NOERR is reused here to indicate logs arrising from auth queries */
2337 if (!(flags & F_NOERR) && option_bool(OPT_AUTH_LOG))
2338 return;
2339
2340 /* build query type string if requested */
2341 if (!(flags & (F_SERVER | F_IPSET | F_QUERY | F_KEYTAG | F_RR)) && type > 0)
2342 arg = querystr(arg, type);
2343
2344 dest = arg;
2345
2346 #ifdef HAVE_DNSSEC
2347 if ((flags & F_DNSSECOK) && option_bool(OPT_EXTRALOG))
2348 extra = " (DNSSEC signed)";
2349 #endif
2350
2351 name = sanitise(name);
2352
2353 if (addr)
2354 {
2355 dest = daemon->addrbuff;
2356
2357 if (flags & F_RR)
2358 {
2359 if (flags & F_KEYTAG)
2360 dest = querystr(NULL, addr->rrblock.rrtype);
2361 else
2362 dest = querystr(NULL, addr->rrdata.rrtype);
2363 }
2364 #ifdef HAVE_DNSSEC
2365 else if (flags & F_KEYTAG)
2366 {
2367 snprintf(daemon->addrbuff, ADDRSTRLEN, arg, addr->log.keytag, addr->log.algo, addr->log.digest);
2368 if (type)
2369 extra = " (not supported)";
2370 }
2371 #endif
2372 else if (flags & F_RCODE)
2373 {
2374 unsigned int rcode = addr->log.rcode;
2375
2376 if (rcode == SERVFAIL)
2377 dest = "SERVFAIL";
2378 else if (rcode == REFUSED)
2379 dest = "REFUSED";
2380 else if (rcode == FORMERR)
2381 dest = "FORMERR";
2382 else if (rcode == NOTIMP)
2383 dest = "not implemented";
2384 else
2385 sprintf(daemon->addrbuff, "%u", rcode);
2386
2387 if (addr->log.ede != EDE_UNSET)
2388 {
2389 extra = daemon->addrbuff;
2390 sprintf(extra, " (EDE: %s)", edestr(addr->log.ede));
2391 }
2392 }
2393 else if (flags & (F_IPV4 | F_IPV6))
2394 {
2395 inet_ntop(flags & F_IPV4 ? AF_INET : AF_INET6,
2396 addr, daemon->addrbuff, ADDRSTRLEN);
2397 if ((flags & F_SERVER) && type != NAMESERVER_PORT)
2398 {
2399 extra = portstring;
2400 sprintf(portstring, "#%u", type);
2401 }
2402 }
2403 else
2404 dest = arg;
2405 }
2406
2407 if (flags & F_REVERSE)
2408 {
2409 dest = name;
2410 name = daemon->addrbuff;
2411 }
2412
2413 if (flags & F_NEG)
2414 {
2415 if (flags & F_NXDOMAIN)
2416 dest = "NXDOMAIN";
2417 else
2418 {
2419 if (flags & F_IPV4)
2420 dest = "NODATA-IPv4";
2421 else if (flags & F_IPV6)
2422 dest = "NODATA-IPv6";
2423 else
2424 dest = "NODATA";
2425 }
2426 }
2427 else if (flags & F_CNAME)
2428 dest = "<CNAME>";
2429 else if (flags & F_RRNAME)
2430 dest = arg;
2431
2432 if (flags & F_CONFIG)
2433 source = "config";
2434 else if (flags & F_DHCP)
2435 source = "DHCP";
2436 else if (flags & F_HOSTS)
2437 source = arg;
2438 else if (flags & F_UPSTREAM)
2439 source = "reply";
2440 else if (flags & F_AUTH)
2441 source = "auth";
2442 else if (flags & F_QUERY)
2443 source = "query";
2444 else if (flags & F_SECSTAT)
2445 {
2446 if (addr && addr->log.ede != EDE_UNSET && option_bool(OPT_EXTRALOG))
2447 {
2448 extra = daemon->addrbuff;
2449 sprintf(extra, " (EDE: %s)", edestr(addr->log.ede));
2450 }
2451 source = "validation";
2452 dest = arg;
2453 }
2454 else if (flags & F_DNSSEC)
2455 {
2456 source = arg;
2457 verb = "to";
2458 }
2459 else if (flags & F_SERVER)
2460 {
2461 source = "forwarded";
2462 verb = "to";
2463 }
2464 else if (flags & F_IPSET)
2465 {
2466 source = type ? "ipset add" : "nftset add";
2467 dest = name;
2468 name = arg;
2469 verb = daemon->addrbuff;
2470 }
2471 else if (flags & F_STALE)
2472 source = "cached-stale";
2473 else
2474 source = "cached";
2475
2476 if (flags & F_QUERY)
2477 {
2478 if (flags & F_CONFIG)
2479 {
2480 sprintf(opcodestring, "%u", type & 0xf);
2481 source = "non-query opcode";
2482 name = opcodestring;
2483 }
2484 else if (type > 0)
2485 source = querystr(source, type);
2486
2487 verb = "from";
2488 }
2489
2490 if (!name)
2491 gap = name = "";
2492 else if (!name[0])
2493 name = ".";
2494
2495 if (option_bool(OPT_EXTRALOG))
2496 {
2497 int display_id = daemon->log_display_id;
2498 char *proto = "";
2499
2500 if (option_bool(OPT_LOG_PROTO))
2501 proto = (display_id < 0) ? "TCP " : "UDP ";
2502
2503 if (display_id < 0)
2504 display_id = -display_id;
2505
2506 if (flags & F_NOEXTRA || !daemon->log_source_addr)
2507 my_syslog(LOG_INFO, "%s%u %s %s%s%s %s%s", proto, display_id, source, name, gap, verb, dest, extra);
2508 else
2509 {
2510 int port = prettyprint_addr(daemon->log_source_addr, daemon->addrbuff2);
2511 my_syslog(LOG_INFO, "%s%u %s/%u %s %s%s%s %s%s", proto, display_id, daemon->addrbuff2, port, source, name, gap, verb, dest, extra);
2512 }
2513 }
2514 else
2515 my_syslog(LOG_INFO, "%s %s%s%s %s%s", source, name, gap, verb, dest, extra);
2516 }