Imported Upstream version 2.88
[platform/upstream/dnsmasq.git] / src / cache.c
1 /* dnsmasq is Copyright (c) 2000-2022 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 #ifdef HAVE_DHCP
21 static struct crec *dhcp_spare = NULL;
22 #endif
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;
27
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);
31
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 */
34 static const struct {
35   unsigned int type;
36   const char * const name;
37 } typestr[] = {
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] */
127 };
128
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);
134
135 void next_uid(struct crec *crecp)
136 {
137   static unsigned int uid = 0;
138
139   if (crecp->uid == UID_NONE)
140     {
141       uid++;
142   
143       /* uid == 0 used to indicate CNAME to interface name. */
144       if (uid == UID_NONE)
145         uid++;
146       
147       crecp->uid = uid;
148     }
149 }
150
151 void cache_init(void)
152 {
153   struct crec *crecp;
154   int i;
155  
156   bignames_left = daemon->cachesize/10;
157   
158   if (daemon->cachesize > 0)
159     {
160       crecp = safe_malloc(daemon->cachesize*sizeof(struct crec));
161       
162       for (i=0; i < daemon->cachesize; i++, crecp++)
163         {
164           cache_link(crecp);
165           crecp->flags = 0;
166           crecp->uid = UID_NONE;
167         }
168     }
169   
170   /* create initial hash table*/
171   rehash(daemon->cachesize);
172 }
173
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
177    expand the table. */
178 static void rehash(int size)
179 {
180   struct crec **new, **old, *p, *tmp;
181   int i, new_size, old_size;
182
183   /* hash_size is a power of two. */
184   for (new_size = 64; new_size < size/10; new_size = new_size << 1);
185   
186   /* must succeed in getting first instance, failure later is non-fatal */
187   if (!hash_table)
188     new = safe_malloc(new_size * sizeof(struct crec *));
189   else if (new_size <= hash_size || !(new = whine_malloc(new_size * sizeof(struct crec *))))
190     return;
191
192   for (i = 0; i < new_size; i++)
193     new[i] = NULL;
194
195   old = hash_table;
196   old_size = hash_size;
197   hash_table = new;
198   hash_size = new_size;
199   
200   if (old)
201     {
202       for (i = 0; i < old_size; i++)
203         for (p = old[i]; p ; p = tmp)
204           {
205             tmp = p->hash_next;
206             cache_hash(p);
207           }
208       free(old);
209     }
210 }
211   
212 static struct crec **hash_bucket(char *name)
213 {
214   unsigned int c, val = 017465; /* Barker code - minimum self-correlation in cyclic shift */
215   const unsigned char *mix_tab = (const unsigned char*)typestr; 
216
217   while((c = (unsigned char) *name++))
218     {
219       /* don't use tolower and friends here - they may be messed up by LOCALE */
220       if (c >= 'A' && c <= 'Z')
221         c += 'a' - 'A';
222       val = ((val << 7) | (val >> (32 - 7))) + (mix_tab[(val + c) & 0x3F] ^ c);
223     } 
224   
225   /* hash_size is a power of two */
226   return hash_table + ((val ^ (val >> 16)) & (hash_size - 1));
227 }
228
229 static void cache_hash(struct crec *crecp)
230 {
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 */
235
236   char *name = cache_get_name(crecp);
237   struct crec **up = hash_bucket(name);
238
239   if (!(crecp->flags & F_REVERSE))
240     {
241       while (*up && ((*up)->flags & F_REVERSE))
242         up = &((*up)->hash_next); 
243       
244       if (crecp->flags & F_IMMORTAL)
245         while (*up && !((*up)->flags & F_IMMORTAL))
246           up = &((*up)->hash_next);
247     }
248
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);
252   
253   crecp->hash_next = *up;
254   *up = crecp;
255 }
256
257 static void cache_blockdata_free(struct crec *crecp)
258 {
259   if (!(crecp->flags & F_NEG))
260     {
261       if (crecp->flags & F_SRV)
262         blockdata_free(crecp->addr.srv.target);
263 #ifdef HAVE_DNSSEC
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);
268 #endif
269     }
270 }
271
272 static void cache_free(struct crec *crecp)
273 {
274   crecp->flags &= ~F_FORWARD;
275   crecp->flags &= ~F_REVERSE;
276   crecp->uid = UID_NONE; /* invalidate CNAMES pointing to this. */
277
278   if (cache_tail)
279     cache_tail->next = crecp;
280   else
281     cache_head = crecp;
282   crecp->prev = cache_tail;
283   crecp->next = NULL;
284   cache_tail = crecp;
285   
286   /* retrieve big name for further use. */
287   if (crecp->flags & F_BIGNAME)
288     {
289       crecp->name.bname->next = big_free;
290       big_free = crecp->name.bname;
291       crecp->flags &= ~F_BIGNAME;
292     }
293
294   cache_blockdata_free(crecp);
295 }    
296
297 /* insert a new cache entry at the head of the list (youngest entry) */
298 static void cache_link(struct crec *crecp)
299 {
300   if (cache_head) /* check needed for init code */
301     cache_head->prev = crecp;
302   crecp->next = cache_head;
303   crecp->prev = NULL;
304   cache_head = crecp;
305   if (!cache_tail)
306     cache_tail = crecp;
307 }
308
309 /* remove an arbitrary cache entry for promotion */ 
310 static void cache_unlink (struct crec *crecp)
311 {
312   if (crecp->prev)
313     crecp->prev->next = crecp->next;
314   else
315     cache_head = crecp->next;
316
317   if (crecp->next)
318     crecp->next->prev = crecp->prev;
319   else
320     cache_tail = crecp->prev;
321 }
322
323 char *cache_get_name(struct crec *crecp)
324 {
325   if (crecp->flags & F_BIGNAME)
326     return crecp->name.bname->name;
327   else if (crecp->flags & F_NAMEP) 
328     return crecp->name.namep;
329   
330   return crecp->name.sname;
331 }
332
333 char *cache_get_cname_target(struct crec *crecp)
334 {
335   if (crecp->addr.cname.is_name_ptr)
336      return crecp->addr.cname.target.name;
337   else
338     return cache_get_name(crecp->addr.cname.target.cache);
339 }
340
341
342
343 struct crec *cache_enumerate(int init)
344 {
345   static int bucket;
346   static struct crec *cache;
347
348   if (init)
349     {
350       bucket = 0;
351       cache = NULL;
352     }
353   else if (cache && cache->hash_next)
354     cache = cache->hash_next;
355   else
356     {
357        cache = NULL; 
358        while (bucket < hash_size)
359          if ((cache = hash_table[bucket++]))
360            break;
361     }
362   
363   return cache;
364 }
365
366 static int is_outdated_cname_pointer(struct crec *crecp)
367 {
368   if (!(crecp->flags & F_CNAME) || crecp->addr.cname.is_name_ptr)
369     return 0;
370   
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)
376     return 0;
377   
378   return 1;
379 }
380
381 static int is_expired(time_t now, struct crec *crecp)
382 {
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)))
394     return 0;
395
396   if (crecp->flags & F_IMMORTAL)
397     return 0;
398
399   if (difftime(now, crecp->ttd) < 0)
400     return 0;
401   
402   return 1;
403 }
404
405 /* Remove entries with a given UID from the cache */
406 unsigned int cache_remove_uid(const unsigned int uid)
407 {
408   int i;
409   unsigned int removed = 0;
410   struct crec *crecp, **up;
411
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)
415         {
416           *up = crecp->hash_next;
417           free(crecp);
418           removed++;
419         }
420       else
421         up = &crecp->hash_next;
422   
423   return removed;
424 }
425
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)
428 {
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. 
435
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)
438
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. 
441
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. */
444  
445   struct crec *crecp, **up;
446
447   (void)class;
448   
449   if (flags & F_FORWARD)
450     {
451       for (up = hash_bucket(name), crecp = *up; crecp; crecp = crecp->hash_next)
452         {
453           if ((crecp->flags & F_FORWARD) && hostname_isequal(cache_get_name(crecp), name))
454             {
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))))
458                 {
459                   if (crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG))
460                     return crecp;
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)
466                     {
467                       if (target_crec)
468                         *target_crec = crecp;
469                       if (target_uid)
470                         *target_uid = crecp->uid;
471                     }
472                   cache_unlink(crecp);
473                   cache_free(crecp);
474                   continue;
475                 }
476               
477 #ifdef HAVE_DNSSEC
478               /* Deletion has to be class-sensitive for DS and DNSKEY */
479               if ((flags & crecp->flags & (F_DNSKEY | F_DS)) && crecp->uid == class)
480                 {
481                   if (crecp->flags & F_CONFIG)
482                     return crecp;
483                   *up = crecp->hash_next;
484                   cache_unlink(crecp);
485                   cache_free(crecp);
486                   continue;
487                 }
488 #endif
489             }
490
491           if (is_expired(now, crecp) || is_outdated_cname_pointer(crecp))
492             { 
493               *up = crecp->hash_next;
494               if (!(crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG)))
495                 {
496                   cache_unlink(crecp);
497                   cache_free(crecp);
498                 }
499               continue;
500             } 
501           
502           up = &crecp->hash_next;
503         }
504     }
505   else
506     {
507       int i;
508       int addrlen = (flags & F_IPV6) ? IN6ADDRSZ : INADDRSZ;
509
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))
515             {
516               *up = crecp->hash_next;
517               if (!(crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG)))
518                 { 
519                   cache_unlink(crecp);
520                   cache_free(crecp);
521                 }
522             }
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)
527             {
528               *up = crecp->hash_next;
529               cache_unlink(crecp);
530               cache_free(crecp);
531             }
532           else
533             up = &crecp->hash_next;
534     }
535   
536   return NULL;
537 }
538
539 /* Note: The normal calling sequence is
540    cache_start_insert
541    cache_insert * n
542    cache_end_insert
543
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. */
546
547 void cache_start_insert(void)
548 {
549   /* Free any entries which didn't get committed during the last
550      insert due to error.
551   */
552   while (new_chain)
553     {
554       struct crec *tmp = new_chain->next;
555       cache_free(new_chain);
556       new_chain = tmp;
557     }
558   new_chain = NULL;
559   insert_error = 0;
560 }
561
562 struct crec *cache_insert(char *name, union all_addr *addr, unsigned short class,
563                           time_t now,  unsigned long ttl, unsigned int flags)
564 {
565 #ifdef HAVE_DNSSEC
566   if (flags & (F_DNSKEY | F_DS)) 
567     {
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;
577     }
578   else
579 #endif
580     {
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;
585     }   
586   
587   return really_insert(name, addr, class, now, ttl, flags);
588 }
589
590
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)
593 {
594   struct crec *new, *target_crec = NULL;
595   union bigname *big_name = NULL;
596   int freed_all = (flags & F_REVERSE);
597   int free_avail = 0;
598   unsigned int target_uid;
599   
600   /* if previous insertion failed give up now. */
601   if (insert_error)
602     return NULL;
603
604   /* we don't cache zero-TTL records. */
605   if (ttl == 0)
606     {
607       insert_error = 1;
608       return NULL;
609     }
610   
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)))
614     {
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)
621         {
622           if ((flags & F_IPV4) && (new->flags & F_IPV4) &&
623               new->addr.addr4.s_addr == addr->addr4.s_addr)
624             return new;
625           else if ((flags & F_IPV6) && (new->flags & F_IPV6) &&
626                    IN6_ARE_ADDR_EQUAL(&new->addr.addr6, &addr->addr6))
627             return new;
628         }
629
630       insert_error = 1;
631       return NULL;
632     }
633   
634   /* Now get a cache entry from the end of the LRU list */
635   if (!target_crec)
636     while (1) {
637       if (!(new = cache_tail)) /* no entries left - cache is too small, bail */
638         {
639           insert_error = 1;
640           return NULL;
641         }
642       
643       /* Free entry at end of LRU list, use it. */
644       if (!(new->flags & (F_FORWARD | F_REVERSE)))
645         break;
646
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. */
650       
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. */
655       if (free_avail)
656         {
657           static int warned = 0;
658           if (!warned)
659             {
660               my_syslog(LOG_ERR, _("Internal error in cache."));
661               warned = 1;
662             }
663           insert_error = 1;
664           return NULL;
665         }
666       
667       if (freed_all)
668         {
669           /* For DNSSEC records, uid holds class. */
670           free_avail = 1; /* Must be free space now. */
671           
672           /* condition valid when stale-caching */
673           if (difftime(now, new->ttd) < 0)
674             daemon->metrics[METRIC_DNS_CACHE_LIVE_FREED]++;
675           
676           cache_scan_free(cache_get_name(new), &new->addr, new->uid, now, new->flags, NULL, NULL);
677         }
678       else
679         {
680           cache_scan_free(NULL, NULL, class, now, 0, NULL, NULL);
681           freed_all = 1;
682         }
683     }
684       
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))
688     {
689       if (big_free)
690         { 
691           big_name = big_free;
692           big_free = big_free->next;
693         }
694       else if ((bignames_left == 0 && !(flags & (F_DS | F_DNSKEY))) ||
695                !(big_name = (union bigname *)whine_malloc(sizeof(union bigname))))
696         {
697           insert_error = 1;
698           return NULL;
699         }
700       else if (bignames_left != 0)
701         bignames_left--;
702       
703     }
704
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. */
707   if (target_crec)
708     {
709       new = target_crec;
710       new->uid = target_uid;
711     }
712   
713   /* Got the rest: finally grab entry. */
714   cache_unlink(new);
715   
716   new->flags = flags;
717   if (big_name)
718     {
719       new->name.bname = big_name;
720       new->flags |= F_BIGNAME;
721     }
722
723   if (name)
724     strcpy(cache_get_name(new), name);
725   else
726     *cache_get_name(new) = 0;
727
728 #ifdef HAVE_DNSSEC
729   if (flags & (F_DS | F_DNSKEY))
730     new->uid = class;
731 #endif
732
733   if (addr)
734     new->addr = *addr;  
735
736   new->ttd = now + (time_t)ttl;
737   new->next = new_chain;
738   new_chain = new;
739   
740   return new;
741 }
742
743 /* after end of insertion, commit the new entries */
744 void cache_end_insert(void)
745 {
746   if (insert_error)
747     return;
748   
749   while (new_chain)
750     { 
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);
755       else
756         {
757           cache_hash(new_chain);
758           cache_link(new_chain);
759           daemon->metrics[METRIC_DNS_CACHE_INSERTED]++;
760
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)
764             {
765               char *name = cache_get_name(new_chain);
766               ssize_t m = strlen(name);
767               unsigned int flags = new_chain->flags;
768 #ifdef HAVE_DNSSEC
769               u16 class = new_chain->uid;
770 #endif
771               
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);
776
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);
779               if (flags & F_SRV)
780                 {
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);
784                 }
785 #ifdef HAVE_DNSSEC
786               if (flags & F_DNSKEY)
787                 {
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);
790                 }
791               else if (flags & F_DS)
792                 {
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);
797                 }
798 #endif
799             }
800         }
801       
802       new_chain = tmp;
803     }
804
805   /* signal end of cache insert in master process */
806   if (daemon->pipe_to_parent != -1)
807     {
808       ssize_t m = -1;
809       read_write(daemon->pipe_to_parent, (unsigned char *)&m, sizeof(m), 0);
810     }
811       
812   new_chain = NULL;
813 }
814
815
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)
818 {
819   ssize_t m;
820   union all_addr addr;
821   unsigned long ttl;
822   time_t ttd;
823   unsigned int flags;
824   struct crec *crecp = NULL;
825   
826   cache_start_insert();
827   
828   while(1)
829     {
830  
831       if (!read_write(fd, (unsigned char *)&m, sizeof(m), 1))
832         return 0;
833       
834       if (m == -1)
835         {
836           cache_end_insert();
837           return 1;
838         }
839
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))
843         return 0;
844
845       daemon->namebuff[m] = 0;
846
847       ttl = difftime(ttd, now);
848       
849       if (flags & (F_IPV4 | F_IPV6 | F_DNSKEY | F_DS | F_SRV))
850         {
851           unsigned short class = C_IN;
852
853           if (!read_write(fd, (unsigned char *)&addr, sizeof(addr), 1))
854             return 0;
855
856           if ((flags & F_SRV) && !(flags & F_NEG) && !(addr.srv.target = blockdata_read(fd, addr.srv.targetlen)))
857             return 0;
858         
859 #ifdef HAVE_DNSSEC
860            if (flags & F_DNSKEY)
861              {
862                if (!read_write(fd, (unsigned char *)&class, sizeof(class), 1) ||
863                    !(addr.key.keydata = blockdata_read(fd, addr.key.keylen)))
864                  return 0;
865              }
866            else  if (flags & F_DS)
867              {
868                 if (!read_write(fd, (unsigned char *)&class, sizeof(class), 1) ||
869                     (!(flags & F_NEG) && !(addr.key.keydata = blockdata_read(fd, addr.key.keylen))))
870                   return 0;
871              }
872 #endif
873                
874           crecp = really_insert(daemon->namebuff, &addr, class, now, ttl, flags);
875         }
876       else if (flags & F_CNAME)
877         {
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. */
882           if (newc)
883             {
884                newc->addr.cname.is_name_ptr = 0;
885                
886                if (!crecp)
887                  newc->addr.cname.target.cache = NULL;
888                else
889                 {
890                   next_uid(crecp);
891                   newc->addr.cname.target.cache = crecp;
892                   newc->addr.cname.uid = crecp->uid;
893                 }
894             }
895         }
896     }
897 }
898         
899 int cache_find_non_terminal(char *name, time_t now)
900 {
901   struct crec *crecp;
902
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)))
909       return 1;
910
911   return 0;
912 }
913
914 struct crec *cache_find_by_name(struct crec *crecp, char *name, time_t now, unsigned int prot)
915 {
916   struct crec *ans;
917   int no_rr = (prot & F_NO_RR) || option_bool(OPT_NORR);
918
919   prot &= ~F_NO_RR;
920   
921   if (crecp) /* iterating */
922     ans = crecp->next;
923   else
924     {
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;
929       
930       for (up = hash_bucket(name), crecp = *up; crecp; crecp = next)
931         {
932           next = crecp->hash_next;
933           
934           if (!is_expired(now, crecp) && !is_outdated_cname_pointer(crecp))
935             {
936               if ((crecp->flags & F_FORWARD) && 
937                   (crecp->flags & prot) &&
938                   hostname_isequal(cache_get_name(crecp), name))
939                 {
940                   if (crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG))
941                     {
942                       *chainp = crecp;
943                       chainp = &crecp->next;
944                     }
945                   else
946                     {
947                       cache_unlink(crecp);
948                       cache_link(crecp);
949                     }
950                       
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
954                      order invariants. 
955                   */
956                   if (insert && (crecp->flags & (F_REVERSE | F_IMMORTAL)) == ins_flags)
957                     {
958                       *up = crecp->hash_next;
959                       crecp->hash_next = *insert;
960                       *insert = crecp;
961                       insert = &crecp->hash_next;
962                     }
963                   else
964                     {
965                       if (!insert && !no_rr)
966                         {
967                           insert = up;
968                           ins_flags = crecp->flags & (F_REVERSE | F_IMMORTAL);
969                         }
970                       up = &crecp->hash_next; 
971                     }
972                 }
973               else
974                 /* case : not expired, incorrect entry. */
975                 up = &crecp->hash_next; 
976             }
977           else
978             {
979               /* expired entry, free it */
980               *up = crecp->hash_next;
981               if (!(crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG)))
982                 { 
983                   cache_unlink(crecp);
984                   cache_free(crecp);
985                 }
986             }
987         }
988           
989       *chainp = cache_head;
990     }
991
992   if (ans && 
993       (ans->flags & F_FORWARD) &&
994       (ans->flags & prot) &&     
995       hostname_isequal(cache_get_name(ans), name))
996     return ans;
997   
998   return NULL;
999 }
1000
1001 struct crec *cache_find_by_addr(struct crec *crecp, union all_addr *addr, 
1002                                 time_t now, unsigned int prot)
1003 {
1004   struct crec *ans;
1005   int addrlen = (prot == F_IPV6) ? IN6ADDRSZ : INADDRSZ;
1006   
1007   if (crecp) /* iterating */
1008     ans = crecp->next;
1009   else
1010     {  
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 
1014          non-REVERSE one.  */
1015        int i;
1016        struct crec **up, **chainp = &ans;
1017        
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))
1023              {      
1024                if ((crecp->flags & prot) &&
1025                    memcmp(&crecp->addr, addr, addrlen) == 0)
1026                  {          
1027                    if (crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG))
1028                      {
1029                        *chainp = crecp;
1030                        chainp = &crecp->next;
1031                      }
1032                    else
1033                      {
1034                        cache_unlink(crecp);
1035                        cache_link(crecp);
1036                      }
1037                  }
1038                up = &crecp->hash_next;
1039              }
1040            else
1041              {
1042                *up = crecp->hash_next;
1043                if (!(crecp->flags & (F_HOSTS | F_DHCP | F_CONFIG)))
1044                  {
1045                    cache_unlink(crecp);
1046                    cache_free(crecp);
1047                  }
1048              }
1049        
1050        *chainp = cache_head;
1051     }
1052   
1053   if (ans && 
1054       (ans->flags & F_REVERSE) &&
1055       (ans->flags & prot) &&
1056       memcmp(&ans->addr, addr, addrlen) == 0)
1057     return ans;
1058   
1059   return NULL;
1060 }
1061
1062 static void add_hosts_entry(struct crec *cache, union all_addr *addr, int addrlen, 
1063                             unsigned int index, struct crec **rhash, int hashsz)
1064 {
1065   int i;
1066   unsigned int j; 
1067   struct crec *lookup = NULL;
1068
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)
1072       {
1073         free(cache);
1074         return;
1075       }
1076     
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. 
1083
1084      Only insert each unique address once into this hashing structure.
1085
1086      This complexity avoids O(n^2) divergent CPU use whilst reading
1087      large (10000 entry) hosts files. 
1088
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
1091      instead.
1092   */
1093   
1094   if (rhash)
1095     {
1096       /* hash address */
1097       for (j = 0, i = 0; i < addrlen; i++)
1098         j = (j*2 +((unsigned char *)addr)[i]) % hashsz;
1099       
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)
1103           {
1104             cache->flags &= ~F_REVERSE;
1105             break;
1106           }
1107       
1108       /* maintain address hash chain, insert new unique address */
1109       if (!lookup)
1110         {
1111           cache->next = rhash[j];
1112           rhash[j] = cache;
1113         }
1114     }
1115   else
1116     {
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;
1121     }
1122
1123   cache->uid = index;
1124   memcpy(&cache->addr, addr, addrlen);  
1125   cache_hash(cache);
1126   make_non_terminals(cache);
1127 }
1128
1129 static int eatspace(FILE *f)
1130 {
1131   int c, nl = 0;
1132
1133   while (1)
1134     {
1135       if ((c = getc(f)) == '#')
1136         while (c != '\n' && c != EOF)
1137           c = getc(f);
1138       
1139       if (c == EOF)
1140         return 1;
1141
1142       if (!isspace(c))
1143         {
1144           ungetc(c, f);
1145           return nl;
1146         }
1147
1148       if (c == '\n')
1149         nl++;
1150     }
1151 }
1152          
1153 static int gettok(FILE *f, char *token)
1154 {
1155   int c, count = 0;
1156  
1157   while (1)
1158     {
1159       if ((c = getc(f)) == EOF)
1160         return (count == 0) ? -1 : 1;
1161
1162       if (isspace(c) || c == '#')
1163         {
1164           ungetc(c, f);
1165           return eatspace(f);
1166         }
1167       
1168       if (count < (MAXDNAME - 1))
1169         {
1170           token[count++] = c;
1171           token[count] = 0;
1172         }
1173     }
1174 }
1175
1176 int read_hostsfile(char *filename, unsigned int index, int cache_size, struct crec **rhash, int hashsz)
1177 {  
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;
1184
1185   if (!f)
1186     {
1187       my_syslog(LOG_ERR, _("failed to load names from %s: %s"), filename, strerror(errno));
1188       return cache_size;
1189     }
1190   
1191   lineno += eatspace(f);
1192   
1193   while ((atnl = gettok(f, token)) != -1)
1194     {
1195       if (inet_pton(AF_INET, token, &addr) > 0)
1196         {
1197           flags = F_HOSTS | F_IMMORTAL | F_FORWARD | F_REVERSE | F_IPV4;
1198           addrlen = INADDRSZ;
1199           domain_suffix = get_domain(addr.addr4);
1200         }
1201       else if (inet_pton(AF_INET6, token, &addr) > 0)
1202         {
1203           flags = F_HOSTS | F_IMMORTAL | F_FORWARD | F_REVERSE | F_IPV6;
1204           addrlen = IN6ADDRSZ;
1205           domain_suffix = get_domain6(&addr.addr6);
1206         }
1207       else
1208         {
1209           my_syslog(LOG_ERR, _("bad address at %s line %d"), filename, lineno); 
1210           while (atnl == 0)
1211             atnl = gettok(f, token);
1212           lineno += atnl;
1213           continue;
1214         }
1215       
1216       /* rehash every 1000 names. */
1217       if (rhash && ((name_count - cache_size) > 1000))
1218         {
1219           rehash(name_count);
1220           cache_size = name_count;
1221         } 
1222       
1223       while (atnl == 0)
1224         {
1225           struct crec *cache;
1226           int fqdn, nomem;
1227           char *canon;
1228           
1229           if ((atnl = gettok(f, token)) == -1)
1230             break;
1231
1232           fqdn = !!strchr(token, '.');
1233
1234           if ((canon = canonicalise(token, &nomem)))
1235             {
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))))
1239                 {
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);
1246                   name_count++;
1247                   names_done++;
1248                 }
1249               if ((cache = whine_malloc(SIZEOF_BARE_CREC + strlen(canon) + 1)))
1250                 {
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);
1255                   name_count++;
1256                   names_done++;
1257                 }
1258               free(canon);
1259               
1260             }
1261           else if (!nomem)
1262             my_syslog(LOG_ERR, _("bad name at %s line %d"), filename, lineno); 
1263         }
1264
1265       lineno += atnl;
1266     } 
1267
1268   fclose(f);
1269   
1270   if (rhash)
1271     rehash(name_count); 
1272   
1273   my_syslog(LOG_INFO, _("read %s - %d names"), filename, names_done);
1274   
1275   return name_count;
1276 }
1277             
1278 void cache_reload(void)
1279 {
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;
1285   struct cname *a;
1286   struct crec lrec;
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;
1292 #ifdef HAVE_DNSSEC
1293   struct ds_config *ds;
1294 #endif
1295
1296   daemon->metrics[METRIC_DNS_CACHE_INSERTED] = 0;
1297   daemon->metrics[METRIC_DNS_CACHE_LIVE_FREED] = 0;
1298   
1299   for (i=0; i<hash_size; i++)
1300     for (cache = hash_table[i], up = &hash_table[i]; cache; cache = tmp)
1301       {
1302         cache_blockdata_free(cache);
1303
1304         tmp = cache->hash_next;
1305         if (cache->flags & (F_HOSTS | F_CONFIG))
1306           {
1307             *up = cache->hash_next;
1308             free(cache);
1309           }
1310         else if (!(cache->flags & F_DHCP))
1311           {
1312             *up = cache->hash_next;
1313             if (cache->flags & F_BIGNAME)
1314               {
1315                 cache->name.bname->next = big_free;
1316                 big_free = cache->name.bname;
1317               }
1318             cache->flags = 0;
1319           }
1320         else
1321           up = &cache->hash_next;
1322       }
1323   
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))))
1328       {
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;
1335         cache_hash(cache);
1336         make_non_terminals(cache);
1337       }
1338   
1339 #ifdef HAVE_DNSSEC
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)))
1343       {
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;
1352         cache_hash(cache);
1353         make_non_terminals(cache);
1354       }
1355 #endif
1356   
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;
1362
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)
1366       {
1367         if ((hr->flags & HR_4) &&
1368             (cache = whine_malloc(SIZEOF_POINTER_CREC)))
1369           {
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);
1374           }
1375
1376         if ((hr->flags & HR_6) &&
1377             (cache = whine_malloc(SIZEOF_POINTER_CREC)))
1378           {
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);
1383           }
1384       }
1385         
1386   if (option_bool(OPT_NO_HOSTS) && !daemon->addn_hosts)
1387     {
1388       if (daemon->cachesize > 0)
1389         my_syslog(LOG_INFO, _("cleared cache"));
1390     }
1391   else
1392     {
1393       if (!option_bool(OPT_NO_HOSTS))
1394         total_size = read_hostsfile(HOSTSFILE, SRC_HOSTS, total_size, (struct crec **)daemon->packet, revhashsz);
1395       
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);
1400     }
1401   
1402   /* Make non-terminal records for all locally-define RRs */
1403   lrec.flags = F_FORWARD | F_CONFIG | F_NAMEP | F_IMMORTAL;
1404   
1405   for (txt = daemon->txt; txt; txt = txt->next)
1406     {
1407       lrec.name.namep = txt->name;
1408       make_non_terminals(&lrec);
1409     }
1410
1411   for (naptr = daemon->naptr; naptr; naptr = naptr->next)
1412     {
1413       lrec.name.namep = naptr->name;
1414       make_non_terminals(&lrec);
1415     }
1416
1417   for (mx = daemon->mxnames; mx; mx = mx->next)
1418     {
1419       lrec.name.namep = mx->name;
1420       make_non_terminals(&lrec);
1421     }
1422
1423   for (intr = daemon->int_names; intr; intr = intr->next)
1424     {
1425       lrec.name.namep = intr->name;
1426       make_non_terminals(&lrec);
1427     }
1428   
1429   for (ptr = daemon->ptr; ptr; ptr = ptr->next)
1430     {
1431       lrec.name.namep = ptr->name;
1432       make_non_terminals(&lrec);
1433     }
1434   
1435 #ifdef HAVE_INOTIFY
1436   set_dynamic_inotify(AH_HOSTS, total_size, (struct crec **)daemon->packet, revhashsz);
1437 #endif
1438   
1439
1440
1441 #ifdef HAVE_DHCP
1442 struct in_addr a_record_from_hosts(char *name, time_t now)
1443 {
1444   struct crec *crecp = NULL;
1445   struct in_addr ret;
1446   
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;
1452   
1453   my_syslog(MS_DHCP | LOG_WARNING, _("No IPv4 address found for %s"), name);
1454   
1455   ret.s_addr = 0;
1456   return ret;
1457 }
1458
1459 void cache_unhash_dhcp(void)
1460 {
1461   struct crec *cache, **up;
1462   int i;
1463
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)
1467         {
1468           *up = cache->hash_next;
1469           cache->next = dhcp_spare;
1470           dhcp_spare = cache;
1471         }
1472       else
1473         up = &cache->hash_next;
1474 }
1475
1476 void cache_add_dhcp_entry(char *host_name, int prot,
1477                           union all_addr *host_address, time_t ttd) 
1478 {
1479   struct crec *crec = NULL, *fail_crec = NULL;
1480   unsigned int flags = F_IPV4;
1481   int in_hosts = 0;
1482   size_t addrlen = sizeof(struct in_addr);
1483
1484   if (prot == AF_INET6)
1485     {
1486       flags = F_IPV6;
1487       addrlen = sizeof(struct in6_addr);
1488     }
1489   
1490   inet_ntop(prot, host_address, daemon->addrbuff, ADDRSTRLEN);
1491   
1492   while ((crec = cache_find_by_name(crec, host_name, 0, flags | F_CNAME)))
1493     {
1494       /* check all addresses associated with name */
1495       if (crec->flags & (F_HOSTS | F_CONFIG))
1496         {
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)
1502             in_hosts = 1;
1503           else
1504             fail_crec = crec;
1505         }
1506       else if (!(crec->flags & F_DHCP))
1507         {
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 */
1510           break;
1511         }
1512     }
1513   
1514   /* if in hosts, don't need DHCP record */
1515   if (in_hosts)
1516     return;
1517   
1518   /* Name in hosts, address doesn't match */
1519   if (fail_crec)
1520     {
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);
1527       return;
1528     }     
1529   
1530   if ((crec = cache_find_by_addr(NULL, (union all_addr *)host_address, 0, flags)))
1531     {
1532       if (crec->flags & F_NEG)
1533         {
1534           flags |= F_REVERSE;
1535           cache_scan_free(NULL, (union all_addr *)host_address, C_IN, 0, flags, NULL, NULL);
1536         }
1537     }
1538   else
1539     flags |= F_REVERSE;
1540   
1541   if ((crec = dhcp_spare))
1542     dhcp_spare = dhcp_spare->next;
1543   else /* need new one */
1544     crec = whine_malloc(SIZEOF_POINTER_CREC);
1545   
1546   if (crec) /* malloc may fail */
1547     {
1548       crec->flags = flags | F_NAMEP | F_DHCP | F_FORWARD;
1549       if (ttd == 0)
1550         crec->flags |= F_IMMORTAL;
1551       else
1552         crec->ttd = ttd;
1553       crec->addr = *host_address;
1554       crec->name.namep = host_name;
1555       crec->uid = UID_NONE;
1556       cache_hash(crec);
1557       make_non_terminals(crec);
1558     }
1559 }
1560 #endif
1561
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)
1568 {
1569   char *name = cache_get_name(source);
1570   struct crec *crecp, *tmp, **up;
1571   int type = F_HOSTS | F_CONFIG;
1572 #ifdef HAVE_DHCP
1573   if (source->flags & F_DHCP)
1574     type = F_DHCP;
1575 #endif
1576   
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)
1583     {
1584       tmp = crecp->hash_next;
1585
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)))
1591         {
1592           *up = crecp->hash_next;
1593 #ifdef HAVE_DHCP
1594           if (type & F_DHCP)
1595             {
1596               crecp->next = dhcp_spare;
1597               dhcp_spare = crecp;
1598             }
1599           else
1600 #endif
1601             free(crecp);
1602           break;
1603         }
1604       else
1605          up = &crecp->hash_next;
1606     }
1607      
1608   while ((name = strchr(name, '.')))
1609     {
1610       name++;
1611
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)))
1618           break;
1619       
1620       if (crecp)
1621         {
1622           /* If the new name expires later, transfer that time to
1623              empty non-terminal entry. */
1624           if (!(crecp->flags & F_IMMORTAL))
1625             {
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;
1630             }
1631           continue;
1632         }
1633       
1634 #ifdef HAVE_DHCP
1635       if ((source->flags & F_DHCP) && dhcp_spare)
1636         {
1637           crecp = dhcp_spare;
1638           dhcp_spare = dhcp_spare->next;
1639         }
1640       else
1641 #endif
1642         crecp = whine_malloc(SIZEOF_POINTER_CREC);
1643
1644       if (crecp)
1645         {
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;
1650           
1651           cache_hash(crecp);
1652         }
1653     }
1654 }
1655
1656 #ifndef NO_ID
1657 int cache_make_stat(struct txt_record *t)
1658
1659   static char *buff = NULL;
1660   static int bufflen = 60;
1661   int len;
1662   struct server *serv, *serv1;
1663   char *p;
1664
1665   if (!buff && !(buff = whine_malloc(60)))
1666     return 0;
1667
1668   p = buff;
1669   
1670   switch (t->stat)
1671     {
1672     case TXT_STAT_CACHESIZE:
1673       sprintf(buff+1, "%d", daemon->cachesize);
1674       break;
1675
1676     case TXT_STAT_INSERTS:
1677       sprintf(buff+1, "%d", daemon->metrics[METRIC_DNS_CACHE_INSERTED]);
1678       break;
1679
1680     case TXT_STAT_EVICTIONS:
1681       sprintf(buff+1, "%d", daemon->metrics[METRIC_DNS_CACHE_LIVE_FREED]);
1682       break;
1683
1684     case TXT_STAT_MISSES:
1685       sprintf(buff+1, "%u", daemon->metrics[METRIC_DNS_QUERIES_FORWARDED]);
1686       break;
1687
1688     case TXT_STAT_HITS:
1689       sprintf(buff+1, "%u", daemon->metrics[METRIC_DNS_LOCAL_ANSWERED]);
1690       break;
1691
1692 #ifdef HAVE_AUTH
1693     case TXT_STAT_AUTH:
1694       sprintf(buff+1, "%u", daemon->metrics[METRIC_DNS_AUTH_ANSWERED]);
1695       break;
1696 #endif
1697
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;
1702       
1703       for (serv = daemon->servers; serv; serv = serv->next)
1704         if (!(serv->flags & SERV_MARK))
1705           {
1706             char *new, *lenp;
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))
1711                 {
1712                   serv1->flags |= SERV_MARK;
1713                   queries += serv1->queries;
1714                   failed_queries += serv1->failed_queries;
1715                 }
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)
1721               {
1722                 /* expand buffer if necessary */
1723                 newlen = bytes_needed + 1 + bufflen - bytes_avail;
1724                 if (!(new = whine_realloc(buff, newlen)))
1725                   return 0;
1726                 p = new + (p - buff);
1727                 lenp = p - 1;
1728                 buff = new;
1729                 bufflen = newlen;
1730                 bytes_avail =  bufflen - (p - buff );
1731                 bytes_needed = snprintf(p, bytes_avail, "%s#%d %u %u", daemon->addrbuff, port, queries, failed_queries);
1732               }
1733             *lenp = bytes_needed;
1734             p += bytes_needed;
1735           }
1736       t->txt = (unsigned char *)buff;
1737       t->len = p - buff;
1738
1739       return 1;
1740     }
1741   
1742   len = strlen(buff+1);
1743   t->txt = (unsigned char *)buff;
1744   t->len = len + 1;
1745   *buff = len;
1746   return 1;
1747 }
1748 #endif
1749
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)
1753 {
1754   unsigned char *r;
1755   if (name)
1756     for (r = (unsigned char *)name; *r; r++)
1757       if (!isprint((int)*r))
1758         return "<name unprintable>";
1759
1760   return name;
1761 }
1762
1763
1764 void dump_cache(time_t now)
1765 {
1766   struct server *serv, *serv1;
1767
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]);
1775 #ifdef HAVE_AUTH
1776   my_syslog(LOG_INFO, _("queries for authoritative zones %u"), daemon->metrics[METRIC_DNS_AUTH_ANSWERED]);
1777 #endif
1778
1779   blockdata_report();
1780
1781   /* sum counts from different records for same server */
1782   for (serv = daemon->servers; serv; serv = serv->next)
1783     serv->flags &= ~SERV_MARK;
1784   
1785   for (serv = daemon->servers; serv; serv = serv->next)
1786     if (!(serv->flags & SERV_MARK))
1787       {
1788         int port;
1789         unsigned int queries = 0, failed_queries = 0, nxdomain_replies = 0, retrys = 0;
1790         unsigned int sigma_latency = 0, count_latency = 0;
1791
1792         for (serv1 = serv; serv1; serv1 = serv1->next)
1793           if (!(serv1->flags & SERV_MARK) && sockaddr_isequal(&serv->addr, &serv1->addr))
1794             {
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;
1801               count_latency++;
1802             }
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);
1806       }
1807
1808   if (option_bool(OPT_DEBUG) || option_bool(OPT_LOG))
1809     {
1810       struct crec *cache ;
1811       int i;
1812       my_syslog(LOG_INFO, "Host                           Address                                  Flags      Expires                  Source");
1813       my_syslog(LOG_INFO, "------------------------------ ---------------------------------------- ---------- ------------------------ ------------");
1814     
1815       for (i=0; i<hash_size; i++)
1816         for (cache = hash_table[i]; cache; cache = cache->hash_next)
1817           {
1818             char *t = " ";
1819             char *a = daemon->addrbuff, *p = daemon->namebuff, *n = cache_get_name(cache);
1820             *a = 0;
1821             if (strlen(n) == 0 && !(cache->flags & F_REVERSE))
1822               n = "<Root>";
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))
1827               {
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);
1831
1832                 if (targetlen > (40 - len))
1833                   targetlen = 40 - len;
1834                 blockdata_retrieve(cache->addr.srv.target, targetlen, a + len);
1835                 a[len + targetlen] = 0;         
1836               }
1837 #ifdef HAVE_DNSSEC
1838             else if (cache->flags & F_DS)
1839               {
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);
1843               }
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);
1847 #endif
1848             else if (!(cache->flags & F_NEG) || !(cache->flags & F_FORWARD))
1849               { 
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);
1855               }
1856
1857             if (cache->flags & F_IPV4)
1858               t = "4";
1859             else if (cache->flags & F_IPV6)
1860               t = "6";
1861             else if (cache->flags & F_CNAME)
1862               t = "C";
1863             else if (cache->flags & F_SRV)
1864               t = "V";
1865 #ifdef HAVE_DNSSEC
1866             else if (cache->flags & F_DS)
1867               t = "S";
1868             else if (cache->flags & F_DNSKEY)
1869               t = "K";
1870 #endif
1871             else /* non-terminal */
1872               t = "!";
1873
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));
1886 #else
1887             p += sprintf(p, "%-24.24s", cache->flags & F_IMMORTAL ? "" : ctime(&(cache->ttd)));
1888 #endif
1889             if(cache->flags & (F_HOSTS | F_CONFIG) && cache->uid > 0)
1890                 p += sprintf(p, " %s", record_source(cache->uid));
1891
1892             my_syslog(LOG_INFO, "%s", daemon->namebuff);
1893           }
1894     }
1895 }
1896
1897 char *record_source(unsigned int index)
1898 {
1899   struct hostsfile *ah;
1900 #ifdef HAVE_INOTIFY
1901   struct dyndir *dd;
1902 #endif
1903   
1904   if (index == SRC_CONFIG)
1905     return "config";
1906   else if (index == SRC_HOSTS)
1907     return HOSTSFILE;
1908
1909   for (ah = daemon->addn_hosts; ah; ah = ah->next)
1910     if (ah->index == index)
1911       return ah->fname;
1912
1913 #ifdef HAVE_INOTIFY
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)
1918         return ah->fname;
1919 #endif
1920
1921   return "<unknown>";
1922 }
1923
1924 static char *querystr(char *desc, unsigned short type)
1925 {
1926   unsigned int i;
1927   int len = 10; /* strlen("type=xxxxx") */
1928   const char *types = NULL;
1929   static char *buff = NULL;
1930   static int bufflen = 0;
1931
1932   for (i = 0; i < (sizeof(typestr)/sizeof(typestr[0])); i++)
1933     if (typestr[i].type == type)
1934       {
1935         types = typestr[i].name;
1936         len = strlen(types);
1937         break;
1938       }
1939
1940   if (desc)
1941     {
1942        len += 2; /* braces */
1943        len += strlen(desc);
1944     }
1945   len++; /* terminator */
1946   
1947   if (!buff || bufflen < len)
1948     {
1949       if (buff)
1950         free(buff);
1951       else if (len < 20)
1952         len = 20;
1953       
1954       buff = whine_malloc(len);
1955       bufflen = len;
1956     }
1957
1958   if (buff)
1959     {
1960       if (desc)
1961         {
1962           if (types)
1963             sprintf(buff, "%s[%s]", desc, types);
1964           else
1965             sprintf(buff, "%s[type=%d]", desc, type);
1966         }
1967       else
1968         {
1969           if (types)
1970             sprintf(buff, "<%s>", types);
1971           else
1972             sprintf(buff, "<type=%d>", type);
1973         }
1974     }
1975   
1976   return buff ? buff : "";
1977 }
1978
1979 static char *edestr(int ede)
1980 {
1981   switch (ede)
1982     {
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";
2009     }
2010 }
2011
2012 void log_query(unsigned int flags, char *name, union all_addr *addr, char *arg, unsigned short type)
2013 {
2014   char *source, *dest = arg;
2015   char *verb = "is";
2016   char *extra = "";
2017   char portstring[7]; /* space for #<portnum> */
2018   
2019   if (!option_bool(OPT_LOG))
2020     return;
2021
2022   /* build query type string if requested */
2023   if (!(flags & (F_SERVER | F_IPSET)) && type > 0)
2024     arg = querystr(arg, type);
2025
2026 #ifdef HAVE_DNSSEC
2027   if ((flags & F_DNSSECOK) && option_bool(OPT_EXTRALOG))
2028     extra = " (DNSSEC signed)";
2029 #endif
2030
2031   name = sanitise(name);
2032
2033   if (addr)
2034     {
2035       dest = daemon->addrbuff;
2036
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)
2040         {
2041           unsigned int rcode = addr->log.rcode;
2042
2043           if (rcode == SERVFAIL)
2044             dest = "SERVFAIL";
2045           else if (rcode == REFUSED)
2046             dest = "REFUSED";
2047           else if (rcode == NOTIMP)
2048             dest = "not implemented";
2049           else
2050             sprintf(daemon->addrbuff, "%u", rcode);
2051
2052           if (addr->log.ede != EDE_UNSET)
2053             {
2054               extra = daemon->addrbuff;
2055               sprintf(extra, " (EDE: %s)", edestr(addr->log.ede));
2056             }
2057         }
2058       else if (flags & (F_IPV4 | F_IPV6))
2059         {
2060           inet_ntop(flags & F_IPV4 ? AF_INET : AF_INET6,
2061                     addr, daemon->addrbuff, ADDRSTRLEN);
2062           if ((flags & F_SERVER) && type != NAMESERVER_PORT)
2063             {
2064               extra = portstring;
2065               sprintf(portstring, "#%u", type);
2066             }
2067         }
2068       else
2069         dest = arg;
2070     }
2071
2072   if (flags & F_REVERSE)
2073     {
2074       dest = name;
2075       name = daemon->addrbuff;
2076     }
2077   
2078   if (flags & F_NEG)
2079     {
2080       if (flags & F_NXDOMAIN)
2081         dest = "NXDOMAIN";
2082       else
2083         {      
2084           if (flags & F_IPV4)
2085             dest = "NODATA-IPv4";
2086           else if (flags & F_IPV6)
2087             dest = "NODATA-IPv6";
2088           else
2089             dest = "NODATA";
2090         }
2091     }
2092   else if (flags & F_CNAME)
2093     dest = "<CNAME>";
2094   else if (flags & F_SRV)
2095     dest = "<SRV>";
2096   else if (flags & F_RRNAME)
2097     dest = arg;
2098     
2099   if (flags & F_CONFIG)
2100     source = "config";
2101   else if (flags & F_DHCP)
2102     source = "DHCP";
2103   else if (flags & F_HOSTS)
2104     source = arg;
2105   else if (flags & F_UPSTREAM)
2106     source = "reply";
2107   else if (flags & F_SECSTAT)
2108     {
2109       if (addr && addr->log.ede != EDE_UNSET && option_bool(OPT_EXTRALOG))
2110         {
2111           extra = daemon->addrbuff;
2112           sprintf(extra, " (EDE: %s)", edestr(addr->log.ede));
2113         }
2114       source = "validation";
2115       dest = arg;
2116     }
2117   else if (flags & F_AUTH)
2118     source = "auth";
2119    else if (flags & F_DNSSEC)
2120     {
2121       source = arg;
2122       verb = "to";
2123     }
2124    else if (flags & F_SERVER)
2125     {
2126       source = "forwarded";
2127       verb = "to";
2128     }
2129   else if (flags & F_QUERY)
2130     {
2131       source = arg;
2132       verb = "from";
2133     }
2134   else if (flags & F_IPSET)
2135     {
2136       source = type ? "ipset add" : "nftset add";
2137       dest = name;
2138       name = arg;
2139       verb = daemon->addrbuff;
2140     }
2141   else if (flags & F_STALE)
2142     source = "cached-stale";
2143   else
2144     source = "cached";
2145   
2146   if (name && !name[0])
2147     name = ".";
2148
2149   if (option_bool(OPT_EXTRALOG))
2150     {
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);
2153       else
2154         {
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);
2157         }
2158     }
2159   else
2160     my_syslog(LOG_INFO, "%s %s %s %s%s", source, name, verb, dest, extra);
2161 }