xref: /freebsd/contrib/unbound/cachedb/cachedb.c (revision 5c1d97100348ef19878fa14671a9b70f3d963ed4)
1 /*
2  * cachedb/cachedb.c - cache from a database external to the program module
3  *
4  * Copyright (c) 2016, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 /**
37  * \file
38  *
39  * This file contains a module that uses an external database to cache
40  * dns responses.
41  */
42 
43 #include "config.h"
44 #ifdef USE_CACHEDB
45 #include "cachedb/cachedb.h"
46 #include "cachedb/redis.h"
47 #include "util/regional.h"
48 #include "util/net_help.h"
49 #include "util/config_file.h"
50 #include "util/data/msgreply.h"
51 #include "util/data/msgencode.h"
52 #include "services/cache/dns.h"
53 #include "validator/val_neg.h"
54 #include "validator/val_secalgo.h"
55 #include "iterator/iter_utils.h"
56 #include "sldns/parseutil.h"
57 #include "sldns/wire2str.h"
58 #include "sldns/sbuffer.h"
59 
60 /* header file for htobe64 */
61 #ifdef HAVE_ENDIAN_H
62 #  include <endian.h>
63 #endif
64 #ifdef HAVE_SYS_ENDIAN_H
65 #  include <sys/endian.h>
66 #endif
67 #ifdef HAVE_LIBKERN_OSBYTEORDER_H
68 /* In practice this is specific to MacOS X.  We assume it doesn't have
69 * htobe64/be64toh but has alternatives with a different name. */
70 #  include <libkern/OSByteOrder.h>
71 #  define htobe64(x) OSSwapHostToBigInt64(x)
72 #  define be64toh(x) OSSwapBigToHostInt64(x)
73 #endif
74 
75 /* Some compilers do not define __BYTE_ORDER__, like IBM XLC on AIX */
76 #ifndef be64toh
77 #if defined(__sun) || defined(_AIX)
78 #  if __BIG_ENDIAN__
79 #    define be64toh(n) (n)
80 #    define htobe64(n) (n)
81 #  else
82 #    define be64toh(n) (((uint64_t)htonl((n) & 0xFFFFFFFF) << 32) | htonl((n) >> 32))
83 #    define htobe64(n) (((uint64_t)htonl((n) & 0xFFFFFFFF) << 32) | htonl((n) >> 32))
84 #  endif
85 #endif
86 #endif /* be64toh */
87 
88 /** the unit test testframe for cachedb, its module state contains
89  * a cache for a couple queries (in memory). */
90 struct testframe_moddata {
91 	/** lock for mutex */
92 	lock_basic_type lock;
93 	/** key for single stored data element, NULL if none */
94 	char* stored_key;
95 	/** data for single stored data element, NULL if none */
96 	uint8_t* stored_data;
97 	/** length of stored data */
98 	size_t stored_datalen;
99 };
100 
101 static int
102 testframe_init(struct module_env* env, struct cachedb_env* cachedb_env)
103 {
104 	struct testframe_moddata* d;
105 	(void)env;
106 	verbose(VERB_ALGO, "testframe_init");
107 	d = (struct testframe_moddata*)calloc(1,
108 		sizeof(struct testframe_moddata));
109 	cachedb_env->backend_data = (void*)d;
110 	if(!cachedb_env->backend_data) {
111 		log_err("out of memory");
112 		return 0;
113 	}
114 	lock_basic_init(&d->lock);
115 	lock_protect(&d->lock, d, sizeof(*d));
116 	return 1;
117 }
118 
119 static void
120 testframe_deinit(struct module_env* env, struct cachedb_env* cachedb_env)
121 {
122 	struct testframe_moddata* d = (struct testframe_moddata*)
123 		cachedb_env->backend_data;
124 	(void)env;
125 	verbose(VERB_ALGO, "testframe_deinit");
126 	if(!d)
127 		return;
128 	lock_basic_destroy(&d->lock);
129 	free(d->stored_key);
130 	free(d->stored_data);
131 	free(d);
132 }
133 
134 static int
135 testframe_lookup(struct module_env* env, struct cachedb_env* cachedb_env,
136 	char* key, struct sldns_buffer* result_buffer)
137 {
138 	struct testframe_moddata* d = (struct testframe_moddata*)
139 		cachedb_env->backend_data;
140 	(void)env;
141 	verbose(VERB_ALGO, "testframe_lookup of %s", key);
142 	lock_basic_lock(&d->lock);
143 	if(d->stored_key && strcmp(d->stored_key, key) == 0) {
144 		if(d->stored_datalen > sldns_buffer_capacity(result_buffer)) {
145 			lock_basic_unlock(&d->lock);
146 			return 0; /* too large */
147 		}
148 		verbose(VERB_ALGO, "testframe_lookup found %d bytes",
149 			(int)d->stored_datalen);
150 		sldns_buffer_clear(result_buffer);
151 		sldns_buffer_write(result_buffer, d->stored_data,
152 			d->stored_datalen);
153 		sldns_buffer_flip(result_buffer);
154 		lock_basic_unlock(&d->lock);
155 		return 1;
156 	}
157 	lock_basic_unlock(&d->lock);
158 	return 0;
159 }
160 
161 static void
162 testframe_store(struct module_env* env, struct cachedb_env* cachedb_env,
163 	char* key, uint8_t* data, size_t data_len)
164 {
165 	struct testframe_moddata* d = (struct testframe_moddata*)
166 		cachedb_env->backend_data;
167 	(void)env;
168 	lock_basic_lock(&d->lock);
169 	verbose(VERB_ALGO, "testframe_store %s (%d bytes)", key, (int)data_len);
170 
171 	/* free old data element (if any) */
172 	free(d->stored_key);
173 	d->stored_key = NULL;
174 	free(d->stored_data);
175 	d->stored_data = NULL;
176 	d->stored_datalen = 0;
177 
178 	d->stored_data = memdup(data, data_len);
179 	if(!d->stored_data) {
180 		lock_basic_unlock(&d->lock);
181 		log_err("out of memory");
182 		return;
183 	}
184 	d->stored_datalen = data_len;
185 	d->stored_key = strdup(key);
186 	if(!d->stored_key) {
187 		free(d->stored_data);
188 		d->stored_data = NULL;
189 		d->stored_datalen = 0;
190 		lock_basic_unlock(&d->lock);
191 		return;
192 	}
193 	lock_basic_unlock(&d->lock);
194 	/* (key,data) successfully stored */
195 }
196 
197 /** The testframe backend is for unit tests */
198 static struct cachedb_backend testframe_backend = { "testframe",
199 	testframe_init, testframe_deinit, testframe_lookup, testframe_store
200 };
201 
202 /** find a particular backend from possible backends */
203 static struct cachedb_backend*
204 cachedb_find_backend(const char* str)
205 {
206 #ifdef USE_REDIS
207 	if(strcmp(str, redis_backend.name) == 0)
208 		return &redis_backend;
209 #endif
210 	if(strcmp(str, testframe_backend.name) == 0)
211 		return &testframe_backend;
212 	/* TODO add more backends here */
213 	return NULL;
214 }
215 
216 /** apply configuration to cachedb module 'global' state */
217 static int
218 cachedb_apply_cfg(struct cachedb_env* cachedb_env, struct config_file* cfg)
219 {
220 	const char* backend_str = cfg->cachedb_backend;
221 
222 	/* If unspecified we use the in-memory test DB. */
223 	if(!backend_str)
224 		backend_str = "testframe";
225 	cachedb_env->backend = cachedb_find_backend(backend_str);
226 	if(!cachedb_env->backend) {
227 		log_err("cachedb: cannot find backend name '%s'", backend_str);
228 		return 0;
229 	}
230 
231 	/* TODO see if more configuration needs to be applied or not */
232 	return 1;
233 }
234 
235 int
236 cachedb_init(struct module_env* env, int id)
237 {
238 	struct cachedb_env* cachedb_env = (struct cachedb_env*)calloc(1,
239 		sizeof(struct cachedb_env));
240 	if(!cachedb_env) {
241 		log_err("malloc failure");
242 		return 0;
243 	}
244 	env->modinfo[id] = (void*)cachedb_env;
245 	if(!cachedb_apply_cfg(cachedb_env, env->cfg)) {
246 		log_err("cachedb: could not apply configuration settings.");
247 		return 0;
248 	}
249 	/* see if a backend is selected */
250 	if(!cachedb_env->backend || !cachedb_env->backend->name)
251 		return 1;
252 	if(!(*cachedb_env->backend->init)(env, cachedb_env)) {
253 		log_err("cachedb: could not init %s backend",
254 			cachedb_env->backend->name);
255 		return 0;
256 	}
257 	cachedb_env->enabled = 1;
258 	return 1;
259 }
260 
261 void
262 cachedb_deinit(struct module_env* env, int id)
263 {
264 	struct cachedb_env* cachedb_env;
265 	if(!env || !env->modinfo[id])
266 		return;
267 	cachedb_env = (struct cachedb_env*)env->modinfo[id];
268 	/* free contents */
269 	/* TODO */
270 	if(cachedb_env->enabled) {
271 		(*cachedb_env->backend->deinit)(env, cachedb_env);
272 	}
273 
274 	free(cachedb_env);
275 	env->modinfo[id] = NULL;
276 }
277 
278 /** new query for cachedb */
279 static int
280 cachedb_new(struct module_qstate* qstate, int id)
281 {
282 	struct cachedb_qstate* iq = (struct cachedb_qstate*)regional_alloc(
283 		qstate->region, sizeof(struct cachedb_qstate));
284 	qstate->minfo[id] = iq;
285 	if(!iq)
286 		return 0;
287 	memset(iq, 0, sizeof(*iq));
288 	/* initialise it */
289 	/* TODO */
290 
291 	return 1;
292 }
293 
294 /**
295  * Return an error
296  * @param qstate: our query state
297  * @param id: module id
298  * @param rcode: error code (DNS errcode).
299  * @return: 0 for use by caller, to make notation easy, like:
300  * 	return error_response(..).
301  */
302 static int
303 error_response(struct module_qstate* qstate, int id, int rcode)
304 {
305 	verbose(VERB_QUERY, "return error response %s",
306 		sldns_lookup_by_id(sldns_rcodes, rcode)?
307 		sldns_lookup_by_id(sldns_rcodes, rcode)->name:"??");
308 	qstate->return_rcode = rcode;
309 	qstate->return_msg = NULL;
310 	qstate->ext_state[id] = module_finished;
311 	return 0;
312 }
313 
314 /**
315  * Hash the query name, type, class and dbacess-secret into lookup buffer.
316  * @param qstate: query state with query info
317  * 	and env->cfg with secret.
318  * @param buf: returned buffer with hash to lookup
319  * @param len: length of the buffer.
320  */
321 static void
322 calc_hash(struct module_qstate* qstate, char* buf, size_t len)
323 {
324 	uint8_t clear[1024];
325 	size_t clen = 0;
326 	uint8_t hash[CACHEDB_HASHSIZE/8];
327 	const char* hex = "0123456789ABCDEF";
328 	const char* secret = qstate->env->cfg->cachedb_secret ?
329 		qstate->env->cfg->cachedb_secret : "default";
330 	size_t i;
331 
332 	/* copy the hash info into the clear buffer */
333 	if(clen + qstate->qinfo.qname_len < sizeof(clear)) {
334 		memmove(clear+clen, qstate->qinfo.qname,
335 			qstate->qinfo.qname_len);
336 		clen += qstate->qinfo.qname_len;
337 	}
338 	if(clen + 4 < sizeof(clear)) {
339 		uint16_t t = htons(qstate->qinfo.qtype);
340 		uint16_t c = htons(qstate->qinfo.qclass);
341 		memmove(clear+clen, &t, 2);
342 		memmove(clear+clen+2, &c, 2);
343 		clen += 4;
344 	}
345 	if(secret && secret[0] && clen + strlen(secret) < sizeof(clear)) {
346 		memmove(clear+clen, secret, strlen(secret));
347 		clen += strlen(secret);
348 	}
349 
350 	/* hash the buffer */
351 	secalgo_hash_sha256(clear, clen, hash);
352 	memset(clear, 0, clen);
353 
354 	/* hex encode output for portability (some online dbs need
355 	 * no nulls, no control characters, and so on) */
356 	log_assert(len >= sizeof(hash)*2 + 1);
357 	(void)len;
358 	for(i=0; i<sizeof(hash); i++) {
359 		buf[i*2] = hex[(hash[i]&0xf0)>>4];
360 		buf[i*2+1] = hex[hash[i]&0x0f];
361 	}
362 	buf[sizeof(hash)*2] = 0;
363 }
364 
365 /** convert data from return_msg into the data buffer */
366 static int
367 prep_data(struct module_qstate* qstate, struct sldns_buffer* buf)
368 {
369 	uint64_t timestamp, expiry;
370 	size_t oldlim;
371 	struct edns_data edns;
372 	memset(&edns, 0, sizeof(edns));
373 	edns.edns_present = 1;
374 	edns.bits = EDNS_DO;
375 	edns.ext_rcode = 0;
376 	edns.edns_version = EDNS_ADVERTISED_VERSION;
377 	edns.udp_size = EDNS_ADVERTISED_SIZE;
378 
379 	if(!qstate->return_msg || !qstate->return_msg->rep)
380 		return 0;
381 	/* We don't store the reply if its TTL is 0 unless serve-expired is
382 	 * enabled.  Such a reply won't be reusable and simply be a waste for
383 	 * the backend.  It's also compatible with the default behavior of
384 	 * dns_cache_store_msg(). */
385 	if(qstate->return_msg->rep->ttl == 0 &&
386 		!qstate->env->cfg->serve_expired)
387 		return 0;
388 	if(verbosity >= VERB_ALGO)
389 		log_dns_msg("cachedb encoding", &qstate->return_msg->qinfo,
390 	                qstate->return_msg->rep);
391 	if(!reply_info_answer_encode(&qstate->return_msg->qinfo,
392 		qstate->return_msg->rep, 0, qstate->query_flags,
393 		buf, 0, 1, qstate->env->scratch, 65535, &edns, 1, 0))
394 		return 0;
395 
396 	/* TTLs in the return_msg are relative to time(0) so we have to
397 	 * store that, we also store the smallest ttl in the packet+time(0)
398 	 * as the packet expiry time */
399 	/* qstate->return_msg->rep->ttl contains that relative shortest ttl */
400 	timestamp = (uint64_t)*qstate->env->now;
401 	expiry = timestamp + (uint64_t)qstate->return_msg->rep->ttl;
402 	timestamp = htobe64(timestamp);
403 	expiry = htobe64(expiry);
404 	oldlim = sldns_buffer_limit(buf);
405 	if(oldlim + sizeof(timestamp)+sizeof(expiry) >=
406 		sldns_buffer_capacity(buf))
407 		return 0; /* doesn't fit. */
408 	sldns_buffer_set_limit(buf, oldlim + sizeof(timestamp)+sizeof(expiry));
409 	sldns_buffer_write_at(buf, oldlim, &timestamp, sizeof(timestamp));
410 	sldns_buffer_write_at(buf, oldlim+sizeof(timestamp), &expiry,
411 		sizeof(expiry));
412 
413 	return 1;
414 }
415 
416 /** check expiry, return true if matches OK */
417 static int
418 good_expiry_and_qinfo(struct module_qstate* qstate, struct sldns_buffer* buf)
419 {
420 	uint64_t expiry;
421 	/* the expiry time is the last bytes of the buffer */
422 	if(sldns_buffer_limit(buf) < sizeof(expiry))
423 		return 0;
424 	sldns_buffer_read_at(buf, sldns_buffer_limit(buf)-sizeof(expiry),
425 		&expiry, sizeof(expiry));
426 	expiry = be64toh(expiry);
427 
428 	if((time_t)expiry < *qstate->env->now &&
429 		!qstate->env->cfg->serve_expired)
430 		return 0;
431 
432 	return 1;
433 }
434 
435 /* Adjust the TTL of the given RRset by 'subtract'.  If 'subtract' is
436  * negative, set the TTL to 0. */
437 static void
438 packed_rrset_ttl_subtract(struct packed_rrset_data* data, time_t subtract)
439 {
440         size_t i;
441         size_t total = data->count + data->rrsig_count;
442 	if(subtract >= 0 && data->ttl > subtract)
443 		data->ttl -= subtract;
444 	else	data->ttl = 0;
445         for(i=0; i<total; i++) {
446 		if(subtract >= 0 && data->rr_ttl[i] > subtract)
447                 	data->rr_ttl[i] -= subtract;
448                 else	data->rr_ttl[i] = 0;
449 	}
450 }
451 
452 /* Adjust the TTL of a DNS message and its RRs by 'adjust'.  If 'adjust' is
453  * negative, set the TTLs to 0. */
454 static void
455 adjust_msg_ttl(struct dns_msg* msg, time_t adjust)
456 {
457 	size_t i;
458 	if(adjust >= 0 && msg->rep->ttl > adjust)
459 		msg->rep->ttl -= adjust;
460 	else	msg->rep->ttl = 0;
461 	msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
462 	msg->rep->serve_expired_ttl = msg->rep->ttl + SERVE_EXPIRED_TTL;
463 
464 	for(i=0; i<msg->rep->rrset_count; i++) {
465 		packed_rrset_ttl_subtract((struct packed_rrset_data*)msg->
466 			rep->rrsets[i]->entry.data, adjust);
467 	}
468 }
469 
470 /** convert dns message in buffer to return_msg */
471 static int
472 parse_data(struct module_qstate* qstate, struct sldns_buffer* buf)
473 {
474 	struct msg_parse* prs;
475 	struct edns_data edns;
476 	uint64_t timestamp, expiry;
477 	time_t adjust;
478 	size_t lim = sldns_buffer_limit(buf);
479 	if(lim < LDNS_HEADER_SIZE+sizeof(timestamp)+sizeof(expiry))
480 		return 0; /* too short */
481 
482 	/* remove timestamp and expiry from end */
483 	sldns_buffer_read_at(buf, lim-sizeof(expiry), &expiry, sizeof(expiry));
484 	sldns_buffer_read_at(buf, lim-sizeof(expiry)-sizeof(timestamp),
485 		&timestamp, sizeof(timestamp));
486 	expiry = be64toh(expiry);
487 	timestamp = be64toh(timestamp);
488 
489 	/* parse DNS packet */
490 	regional_free_all(qstate->env->scratch);
491 	prs = (struct msg_parse*)regional_alloc(qstate->env->scratch,
492 		sizeof(struct msg_parse));
493 	if(!prs)
494 		return 0; /* out of memory */
495 	memset(prs, 0, sizeof(*prs));
496 	memset(&edns, 0, sizeof(edns));
497 	sldns_buffer_set_limit(buf, lim - sizeof(expiry)-sizeof(timestamp));
498 	if(parse_packet(buf, prs, qstate->env->scratch) != LDNS_RCODE_NOERROR) {
499 		sldns_buffer_set_limit(buf, lim);
500 		return 0;
501 	}
502 	if(parse_extract_edns(prs, &edns, qstate->env->scratch) !=
503 		LDNS_RCODE_NOERROR) {
504 		sldns_buffer_set_limit(buf, lim);
505 		return 0;
506 	}
507 
508 	qstate->return_msg = dns_alloc_msg(buf, prs, qstate->region);
509 	sldns_buffer_set_limit(buf, lim);
510 	if(!qstate->return_msg)
511 		return 0;
512 
513 	qstate->return_rcode = LDNS_RCODE_NOERROR;
514 
515 	/* see how much of the TTL expired, and remove it */
516 	if(*qstate->env->now <= (time_t)timestamp) {
517 		verbose(VERB_ALGO, "cachedb msg adjust by zero");
518 		return 1; /* message from the future (clock skew?) */
519 	}
520 	adjust = *qstate->env->now - (time_t)timestamp;
521 	if(qstate->return_msg->rep->ttl < adjust) {
522 		verbose(VERB_ALGO, "cachedb msg expired");
523 		/* If serve-expired is enabled, we still use an expired message
524 		 * setting the TTL to 0. */
525 		if(qstate->env->cfg->serve_expired)
526 			adjust = -1;
527 		else
528 			return 0; /* message expired */
529 	}
530 	verbose(VERB_ALGO, "cachedb msg adjusted down by %d", (int)adjust);
531 	adjust_msg_ttl(qstate->return_msg, adjust);
532 
533 	/* Similar to the unbound worker, if serve-expired is enabled and
534 	 * the msg would be considered to be expired, mark the state so a
535 	 * refetch will be scheduled.  The comparison between 'expiry' and
536 	 * 'now' should be redundant given how these values were calculated,
537 	 * but we check it just in case as does good_expiry_and_qinfo(). */
538 	if(qstate->env->cfg->serve_expired &&
539 		(adjust == -1 || (time_t)expiry < *qstate->env->now)) {
540 		qstate->need_refetch = 1;
541 	}
542 
543 	return 1;
544 }
545 
546 /**
547  * Lookup the qstate.qinfo in extcache, store in qstate.return_msg.
548  * return true if lookup was successful.
549  */
550 static int
551 cachedb_extcache_lookup(struct module_qstate* qstate, struct cachedb_env* ie)
552 {
553 	char key[(CACHEDB_HASHSIZE/8)*2+1];
554 	calc_hash(qstate, key, sizeof(key));
555 
556 	/* call backend to fetch data for key into scratch buffer */
557 	if( !(*ie->backend->lookup)(qstate->env, ie, key,
558 		qstate->env->scratch_buffer)) {
559 		return 0;
560 	}
561 
562 	/* check expiry date and check if query-data matches */
563 	if( !good_expiry_and_qinfo(qstate, qstate->env->scratch_buffer) ) {
564 		return 0;
565 	}
566 
567 	/* parse dns message into return_msg */
568 	if( !parse_data(qstate, qstate->env->scratch_buffer) ) {
569 		return 0;
570 	}
571 	return 1;
572 }
573 
574 /**
575  * Store the qstate.return_msg in extcache for key qstate.info
576  */
577 static void
578 cachedb_extcache_store(struct module_qstate* qstate, struct cachedb_env* ie)
579 {
580 	char key[(CACHEDB_HASHSIZE/8)*2+1];
581 	calc_hash(qstate, key, sizeof(key));
582 
583 	/* prepare data in scratch buffer */
584 	if(!prep_data(qstate, qstate->env->scratch_buffer))
585 		return;
586 
587 	/* call backend */
588 	(*ie->backend->store)(qstate->env, ie, key,
589 		sldns_buffer_begin(qstate->env->scratch_buffer),
590 		sldns_buffer_limit(qstate->env->scratch_buffer));
591 }
592 
593 /**
594  * See if unbound's internal cache can answer the query
595  */
596 static int
597 cachedb_intcache_lookup(struct module_qstate* qstate)
598 {
599 	struct dns_msg* msg;
600 	msg = dns_cache_lookup(qstate->env, qstate->qinfo.qname,
601 		qstate->qinfo.qname_len, qstate->qinfo.qtype,
602 		qstate->qinfo.qclass, qstate->query_flags,
603 		qstate->region, qstate->env->scratch,
604 		1 /* no partial messages with only a CNAME */
605 		);
606 	if(!msg && qstate->env->neg_cache &&
607 		iter_qname_indicates_dnssec(qstate->env, &qstate->qinfo)) {
608 		/* lookup in negative cache; may result in
609 		 * NOERROR/NODATA or NXDOMAIN answers that need validation */
610 		msg = val_neg_getmsg(qstate->env->neg_cache, &qstate->qinfo,
611 			qstate->region, qstate->env->rrset_cache,
612 			qstate->env->scratch_buffer,
613 			*qstate->env->now, 1/*add SOA*/, NULL,
614 			qstate->env->cfg);
615 	}
616 	if(!msg)
617 		return 0;
618 	/* this is the returned msg */
619 	qstate->return_rcode = LDNS_RCODE_NOERROR;
620 	qstate->return_msg = msg;
621 	return 1;
622 }
623 
624 /**
625  * Store query into the internal cache of unbound.
626  */
627 static void
628 cachedb_intcache_store(struct module_qstate* qstate)
629 {
630 	uint32_t store_flags = qstate->query_flags;
631 
632 	if(qstate->env->cfg->serve_expired)
633 		store_flags |= DNSCACHE_STORE_ZEROTTL;
634 	if(!qstate->return_msg)
635 		return;
636 	(void)dns_cache_store(qstate->env, &qstate->qinfo,
637 		qstate->return_msg->rep, 0, qstate->prefetch_leeway, 0,
638 		qstate->region, store_flags);
639 }
640 
641 /**
642  * Handle a cachedb module event with a query
643  * @param qstate: query state (from the mesh), passed between modules.
644  * 	contains qstate->env module environment with global caches and so on.
645  * @param iq: query state specific for this module.  per-query.
646  * @param ie: environment specific for this module.  global.
647  * @param id: module id.
648  */
649 static void
650 cachedb_handle_query(struct module_qstate* qstate,
651 	struct cachedb_qstate* ATTR_UNUSED(iq),
652 	struct cachedb_env* ie, int id)
653 {
654 	/* check if we are enabled, and skip if so */
655 	if(!ie->enabled) {
656 		/* pass request to next module */
657 		qstate->ext_state[id] = module_wait_module;
658 		return;
659 	}
660 
661 	if(qstate->blacklist || qstate->no_cache_lookup) {
662 		/* cache is blacklisted or we are instructed from edns to not look */
663 		/* pass request to next module */
664 		qstate->ext_state[id] = module_wait_module;
665 		return;
666 	}
667 
668 	/* lookup inside unbound's internal cache */
669 	if(cachedb_intcache_lookup(qstate)) {
670 		if(verbosity >= VERB_ALGO) {
671 			if(qstate->return_msg->rep)
672 				log_dns_msg("cachedb internal cache lookup",
673 					&qstate->return_msg->qinfo,
674 					qstate->return_msg->rep);
675 			else log_info("cachedb internal cache lookup: rcode %s",
676 				sldns_lookup_by_id(sldns_rcodes, qstate->return_rcode)?
677 				sldns_lookup_by_id(sldns_rcodes, qstate->return_rcode)->name:"??");
678 		}
679 		/* we are done with the query */
680 		qstate->ext_state[id] = module_finished;
681 		return;
682 	}
683 
684 	/* ask backend cache to see if we have data */
685 	if(cachedb_extcache_lookup(qstate, ie)) {
686 		if(verbosity >= VERB_ALGO)
687 			log_dns_msg(ie->backend->name,
688 				&qstate->return_msg->qinfo,
689 				qstate->return_msg->rep);
690 		/* store this result in internal cache */
691 		cachedb_intcache_store(qstate);
692 		/* we are done with the query */
693 		qstate->ext_state[id] = module_finished;
694 		return;
695 	}
696 
697 	/* no cache fetches */
698 	/* pass request to next module */
699 	qstate->ext_state[id] = module_wait_module;
700 }
701 
702 /**
703  * Handle a cachedb module event with a response from the iterator.
704  * @param qstate: query state (from the mesh), passed between modules.
705  * 	contains qstate->env module environment with global caches and so on.
706  * @param iq: query state specific for this module.  per-query.
707  * @param ie: environment specific for this module.  global.
708  * @param id: module id.
709  */
710 static void
711 cachedb_handle_response(struct module_qstate* qstate,
712 	struct cachedb_qstate* ATTR_UNUSED(iq), struct cachedb_env* ie, int id)
713 {
714 	/* check if we are not enabled or instructed to not cache, and skip */
715 	if(!ie->enabled || qstate->no_cache_store) {
716 		/* we are done with the query */
717 		qstate->ext_state[id] = module_finished;
718 		return;
719 	}
720 
721 	/* store the item into the backend cache */
722 	cachedb_extcache_store(qstate, ie);
723 
724 	/* we are done with the query */
725 	qstate->ext_state[id] = module_finished;
726 }
727 
728 void
729 cachedb_operate(struct module_qstate* qstate, enum module_ev event, int id,
730 	struct outbound_entry* outbound)
731 {
732 	struct cachedb_env* ie = (struct cachedb_env*)qstate->env->modinfo[id];
733 	struct cachedb_qstate* iq = (struct cachedb_qstate*)qstate->minfo[id];
734 	verbose(VERB_QUERY, "cachedb[module %d] operate: extstate:%s event:%s",
735 		id, strextstate(qstate->ext_state[id]), strmodulevent(event));
736 	if(iq) log_query_info(VERB_QUERY, "cachedb operate: query",
737 		&qstate->qinfo);
738 
739 	/* perform cachedb state machine */
740 	if((event == module_event_new || event == module_event_pass) &&
741 		iq == NULL) {
742 		if(!cachedb_new(qstate, id)) {
743 			(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
744 			return;
745 		}
746 		iq = (struct cachedb_qstate*)qstate->minfo[id];
747 	}
748 	if(iq && (event == module_event_pass || event == module_event_new)) {
749 		cachedb_handle_query(qstate, iq, ie, id);
750 		return;
751 	}
752 	if(iq && (event == module_event_moddone)) {
753 		cachedb_handle_response(qstate, iq, ie, id);
754 		return;
755 	}
756 	if(iq && outbound) {
757 		/* cachedb does not need to process responses at this time
758 		 * ignore it.
759 		cachedb_process_response(qstate, iq, ie, id, outbound, event);
760 		*/
761 		return;
762 	}
763 	if(event == module_event_error) {
764 		verbose(VERB_ALGO, "got called with event error, giving up");
765 		(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
766 		return;
767 	}
768 	if(!iq && (event == module_event_moddone)) {
769 		/* during priming, module done but we never started */
770 		qstate->ext_state[id] = module_finished;
771 		return;
772 	}
773 
774 	log_err("bad event for cachedb");
775 	(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
776 }
777 
778 void
779 cachedb_inform_super(struct module_qstate* ATTR_UNUSED(qstate),
780 	int ATTR_UNUSED(id), struct module_qstate* ATTR_UNUSED(super))
781 {
782 	/* cachedb does not use subordinate requests at this time */
783 	verbose(VERB_ALGO, "cachedb inform_super was called");
784 }
785 
786 void
787 cachedb_clear(struct module_qstate* qstate, int id)
788 {
789 	struct cachedb_qstate* iq;
790 	if(!qstate)
791 		return;
792 	iq = (struct cachedb_qstate*)qstate->minfo[id];
793 	if(iq) {
794 		/* free contents of iq */
795 		/* TODO */
796 	}
797 	qstate->minfo[id] = NULL;
798 }
799 
800 size_t
801 cachedb_get_mem(struct module_env* env, int id)
802 {
803 	struct cachedb_env* ie = (struct cachedb_env*)env->modinfo[id];
804 	if(!ie)
805 		return 0;
806 	return sizeof(*ie); /* TODO - more mem */
807 }
808 
809 /**
810  * The cachedb function block
811  */
812 static struct module_func_block cachedb_block = {
813 	"cachedb",
814 	&cachedb_init, &cachedb_deinit, &cachedb_operate,
815 	&cachedb_inform_super, &cachedb_clear, &cachedb_get_mem
816 };
817 
818 struct module_func_block*
819 cachedb_get_funcblock(void)
820 {
821 	return &cachedb_block;
822 }
823 #endif /* USE_CACHEDB */
824