xref: /freebsd/contrib/unbound/cachedb/cachedb.c (revision ebacd8013fe5f7fdf9f6a5b286f6680dd2891036)
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 
68 #ifndef HAVE_HTOBE64
69 #  ifdef HAVE_LIBKERN_OSBYTEORDER_H
70      /* In practice this is specific to MacOS X.  We assume it doesn't have
71       * htobe64/be64toh but has alternatives with a different name. */
72 #    include <libkern/OSByteOrder.h>
73 #    define htobe64(x) OSSwapHostToBigInt64(x)
74 #    define be64toh(x) OSSwapBigToHostInt64(x)
75 #  else
76      /* not OSX */
77      /* Some compilers do not define __BYTE_ORDER__, like IBM XLC on 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 /* _ENDIAN */
85 #  endif /* HAVE_LIBKERN_OSBYTEORDER_H */
86 #endif /* HAVE_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, time_t ATTR_UNUSED(ttl))
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 	cachedb_env->backend = cachedb_find_backend(backend_str);
222 	if(!cachedb_env->backend) {
223 		log_err("cachedb: cannot find backend name '%s'", backend_str);
224 		return 0;
225 	}
226 
227 	/* TODO see if more configuration needs to be applied or not */
228 	return 1;
229 }
230 
231 int
232 cachedb_init(struct module_env* env, int id)
233 {
234 	struct cachedb_env* cachedb_env = (struct cachedb_env*)calloc(1,
235 		sizeof(struct cachedb_env));
236 	if(!cachedb_env) {
237 		log_err("malloc failure");
238 		return 0;
239 	}
240 	env->modinfo[id] = (void*)cachedb_env;
241 	if(!cachedb_apply_cfg(cachedb_env, env->cfg)) {
242 		log_err("cachedb: could not apply configuration settings.");
243 		free(cachedb_env);
244 		env->modinfo[id] = NULL;
245 		return 0;
246 	}
247 	/* see if a backend is selected */
248 	if(!cachedb_env->backend || !cachedb_env->backend->name)
249 		return 1;
250 	if(!(*cachedb_env->backend->init)(env, cachedb_env)) {
251 		log_err("cachedb: could not init %s backend",
252 			cachedb_env->backend->name);
253 		free(cachedb_env);
254 		env->modinfo[id] = NULL;
255 		return 0;
256 	}
257 	cachedb_env->enabled = 1;
258 	if(env->cfg->serve_expired_reply_ttl)
259 		log_warn(
260 			"cachedb: serve-expired-reply-ttl is set but not working for data "
261 			"originating from the external cache; 0 TLL is used for those.");
262 	if(env->cfg->serve_expired_client_timeout)
263 		log_warn(
264 			"cachedb: serve-expired-client-timeout is set but not working for "
265 			"data originating from the external cache; expired data are used "
266 			"in the reply without first trying to refresh the data.");
267 	return 1;
268 }
269 
270 void
271 cachedb_deinit(struct module_env* env, int id)
272 {
273 	struct cachedb_env* cachedb_env;
274 	if(!env || !env->modinfo[id])
275 		return;
276 	cachedb_env = (struct cachedb_env*)env->modinfo[id];
277 	/* free contents */
278 	/* TODO */
279 	if(cachedb_env->enabled) {
280 		(*cachedb_env->backend->deinit)(env, cachedb_env);
281 	}
282 
283 	free(cachedb_env);
284 	env->modinfo[id] = NULL;
285 }
286 
287 /** new query for cachedb */
288 static int
289 cachedb_new(struct module_qstate* qstate, int id)
290 {
291 	struct cachedb_qstate* iq = (struct cachedb_qstate*)regional_alloc(
292 		qstate->region, sizeof(struct cachedb_qstate));
293 	qstate->minfo[id] = iq;
294 	if(!iq)
295 		return 0;
296 	memset(iq, 0, sizeof(*iq));
297 	/* initialise it */
298 	/* TODO */
299 
300 	return 1;
301 }
302 
303 /**
304  * Return an error
305  * @param qstate: our query state
306  * @param id: module id
307  * @param rcode: error code (DNS errcode).
308  * @return: 0 for use by caller, to make notation easy, like:
309  * 	return error_response(..).
310  */
311 static int
312 error_response(struct module_qstate* qstate, int id, int rcode)
313 {
314 	verbose(VERB_QUERY, "return error response %s",
315 		sldns_lookup_by_id(sldns_rcodes, rcode)?
316 		sldns_lookup_by_id(sldns_rcodes, rcode)->name:"??");
317 	qstate->return_rcode = rcode;
318 	qstate->return_msg = NULL;
319 	qstate->ext_state[id] = module_finished;
320 	return 0;
321 }
322 
323 /**
324  * Hash the query name, type, class and dbacess-secret into lookup buffer.
325  * @param qstate: query state with query info
326  * 	and env->cfg with secret.
327  * @param buf: returned buffer with hash to lookup
328  * @param len: length of the buffer.
329  */
330 static void
331 calc_hash(struct module_qstate* qstate, char* buf, size_t len)
332 {
333 	uint8_t clear[1024];
334 	size_t clen = 0;
335 	uint8_t hash[CACHEDB_HASHSIZE/8];
336 	const char* hex = "0123456789ABCDEF";
337 	const char* secret = qstate->env->cfg->cachedb_secret;
338 	size_t i;
339 
340 	/* copy the hash info into the clear buffer */
341 	if(clen + qstate->qinfo.qname_len < sizeof(clear)) {
342 		memmove(clear+clen, qstate->qinfo.qname,
343 			qstate->qinfo.qname_len);
344 		clen += qstate->qinfo.qname_len;
345 	}
346 	if(clen + 4 < sizeof(clear)) {
347 		uint16_t t = htons(qstate->qinfo.qtype);
348 		uint16_t c = htons(qstate->qinfo.qclass);
349 		memmove(clear+clen, &t, 2);
350 		memmove(clear+clen+2, &c, 2);
351 		clen += 4;
352 	}
353 	if(secret && secret[0] && clen + strlen(secret) < sizeof(clear)) {
354 		memmove(clear+clen, secret, strlen(secret));
355 		clen += strlen(secret);
356 	}
357 
358 	/* hash the buffer */
359 	secalgo_hash_sha256(clear, clen, hash);
360 #ifdef HAVE_EXPLICIT_BZERO
361 	explicit_bzero(clear, clen);
362 #else
363 	memset(clear, 0, clen);
364 #endif
365 
366 	/* hex encode output for portability (some online dbs need
367 	 * no nulls, no control characters, and so on) */
368 	log_assert(len >= sizeof(hash)*2 + 1);
369 	(void)len;
370 	for(i=0; i<sizeof(hash); i++) {
371 		buf[i*2] = hex[(hash[i]&0xf0)>>4];
372 		buf[i*2+1] = hex[hash[i]&0x0f];
373 	}
374 	buf[sizeof(hash)*2] = 0;
375 }
376 
377 /** convert data from return_msg into the data buffer */
378 static int
379 prep_data(struct module_qstate* qstate, struct sldns_buffer* buf)
380 {
381 	uint64_t timestamp, expiry;
382 	size_t oldlim;
383 	struct edns_data edns;
384 	memset(&edns, 0, sizeof(edns));
385 	edns.edns_present = 1;
386 	edns.bits = EDNS_DO;
387 	edns.ext_rcode = 0;
388 	edns.edns_version = EDNS_ADVERTISED_VERSION;
389 	edns.udp_size = EDNS_ADVERTISED_SIZE;
390 
391 	if(!qstate->return_msg || !qstate->return_msg->rep)
392 		return 0;
393 	/* do not store failures like SERVFAIL in the cachedb, this avoids
394 	 * overwriting expired, valid, content with broken content. */
395 	if(FLAGS_GET_RCODE(qstate->return_msg->rep->flags) !=
396 		LDNS_RCODE_NOERROR &&
397 	   FLAGS_GET_RCODE(qstate->return_msg->rep->flags) !=
398 		LDNS_RCODE_NXDOMAIN &&
399 	   FLAGS_GET_RCODE(qstate->return_msg->rep->flags) !=
400 		LDNS_RCODE_YXDOMAIN)
401 		return 0;
402 	/* We don't store the reply if its TTL is 0 unless serve-expired is
403 	 * enabled.  Such a reply won't be reusable and simply be a waste for
404 	 * the backend.  It's also compatible with the default behavior of
405 	 * dns_cache_store_msg(). */
406 	if(qstate->return_msg->rep->ttl == 0 &&
407 		!qstate->env->cfg->serve_expired)
408 		return 0;
409 	if(verbosity >= VERB_ALGO)
410 		log_dns_msg("cachedb encoding", &qstate->return_msg->qinfo,
411 	                qstate->return_msg->rep);
412 	if(!reply_info_answer_encode(&qstate->return_msg->qinfo,
413 		qstate->return_msg->rep, 0, qstate->query_flags,
414 		buf, 0, 1, qstate->env->scratch, 65535, &edns, 1, 0))
415 		return 0;
416 
417 	/* TTLs in the return_msg are relative to time(0) so we have to
418 	 * store that, we also store the smallest ttl in the packet+time(0)
419 	 * as the packet expiry time */
420 	/* qstate->return_msg->rep->ttl contains that relative shortest ttl */
421 	timestamp = (uint64_t)*qstate->env->now;
422 	expiry = timestamp + (uint64_t)qstate->return_msg->rep->ttl;
423 	timestamp = htobe64(timestamp);
424 	expiry = htobe64(expiry);
425 	oldlim = sldns_buffer_limit(buf);
426 	if(oldlim + sizeof(timestamp)+sizeof(expiry) >=
427 		sldns_buffer_capacity(buf))
428 		return 0; /* doesn't fit. */
429 	sldns_buffer_set_limit(buf, oldlim + sizeof(timestamp)+sizeof(expiry));
430 	sldns_buffer_write_at(buf, oldlim, &timestamp, sizeof(timestamp));
431 	sldns_buffer_write_at(buf, oldlim+sizeof(timestamp), &expiry,
432 		sizeof(expiry));
433 
434 	return 1;
435 }
436 
437 /** check expiry, return true if matches OK */
438 static int
439 good_expiry_and_qinfo(struct module_qstate* qstate, struct sldns_buffer* buf)
440 {
441 	uint64_t expiry;
442 	/* the expiry time is the last bytes of the buffer */
443 	if(sldns_buffer_limit(buf) < sizeof(expiry))
444 		return 0;
445 	sldns_buffer_read_at(buf, sldns_buffer_limit(buf)-sizeof(expiry),
446 		&expiry, sizeof(expiry));
447 	expiry = be64toh(expiry);
448 
449 	/* Check if we are allowed to return expired entries:
450 	 * - serve_expired needs to be set
451 	 * - if SERVE_EXPIRED_TTL is set make sure that the record is not older
452 	 *   than that. */
453 	if((time_t)expiry < *qstate->env->now &&
454 		(!qstate->env->cfg->serve_expired ||
455 			(SERVE_EXPIRED_TTL &&
456 			*qstate->env->now - (time_t)expiry > SERVE_EXPIRED_TTL)))
457 		return 0;
458 
459 	return 1;
460 }
461 
462 /* Adjust the TTL of the given RRset by 'subtract'.  If 'subtract' is
463  * negative, set the TTL to 0. */
464 static void
465 packed_rrset_ttl_subtract(struct packed_rrset_data* data, time_t subtract)
466 {
467 	size_t i;
468 	size_t total = data->count + data->rrsig_count;
469 	if(subtract >= 0 && data->ttl > subtract)
470 		data->ttl -= subtract;
471 	else	data->ttl = 0;
472 	for(i=0; i<total; i++) {
473 		if(subtract >= 0 && data->rr_ttl[i] > subtract)
474 			data->rr_ttl[i] -= subtract;
475 		else	data->rr_ttl[i] = 0;
476 	}
477 	data->ttl_add = (subtract < data->ttl_add) ? (data->ttl_add - subtract) : 0;
478 }
479 
480 /* Adjust the TTL of a DNS message and its RRs by 'adjust'.  If 'adjust' is
481  * negative, set the TTLs to 0. */
482 static void
483 adjust_msg_ttl(struct dns_msg* msg, time_t adjust)
484 {
485 	size_t i;
486 	if(adjust >= 0 && msg->rep->ttl > adjust)
487 		msg->rep->ttl -= adjust;
488 	else
489 		msg->rep->ttl = 0;
490 	msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
491 	msg->rep->serve_expired_ttl = msg->rep->ttl + SERVE_EXPIRED_TTL;
492 
493 	for(i=0; i<msg->rep->rrset_count; i++) {
494 		packed_rrset_ttl_subtract((struct packed_rrset_data*)msg->
495 			rep->rrsets[i]->entry.data, adjust);
496 	}
497 }
498 
499 /** convert dns message in buffer to return_msg */
500 static int
501 parse_data(struct module_qstate* qstate, struct sldns_buffer* buf)
502 {
503 	struct msg_parse* prs;
504 	struct edns_data edns;
505 	uint64_t timestamp, expiry;
506 	time_t adjust;
507 	size_t lim = sldns_buffer_limit(buf);
508 	if(lim < LDNS_HEADER_SIZE+sizeof(timestamp)+sizeof(expiry))
509 		return 0; /* too short */
510 
511 	/* remove timestamp and expiry from end */
512 	sldns_buffer_read_at(buf, lim-sizeof(expiry), &expiry, sizeof(expiry));
513 	sldns_buffer_read_at(buf, lim-sizeof(expiry)-sizeof(timestamp),
514 		&timestamp, sizeof(timestamp));
515 	expiry = be64toh(expiry);
516 	timestamp = be64toh(timestamp);
517 
518 	/* parse DNS packet */
519 	regional_free_all(qstate->env->scratch);
520 	prs = (struct msg_parse*)regional_alloc(qstate->env->scratch,
521 		sizeof(struct msg_parse));
522 	if(!prs)
523 		return 0; /* out of memory */
524 	memset(prs, 0, sizeof(*prs));
525 	memset(&edns, 0, sizeof(edns));
526 	sldns_buffer_set_limit(buf, lim - sizeof(expiry)-sizeof(timestamp));
527 	if(parse_packet(buf, prs, qstate->env->scratch) != LDNS_RCODE_NOERROR) {
528 		sldns_buffer_set_limit(buf, lim);
529 		return 0;
530 	}
531 	if(parse_extract_edns_from_response_msg(prs, &edns, qstate->env->scratch) !=
532 		LDNS_RCODE_NOERROR) {
533 		sldns_buffer_set_limit(buf, lim);
534 		return 0;
535 	}
536 
537 	qstate->return_msg = dns_alloc_msg(buf, prs, qstate->region);
538 	sldns_buffer_set_limit(buf, lim);
539 	if(!qstate->return_msg)
540 		return 0;
541 
542 	qstate->return_rcode = LDNS_RCODE_NOERROR;
543 
544 	/* see how much of the TTL expired, and remove it */
545 	if(*qstate->env->now <= (time_t)timestamp) {
546 		verbose(VERB_ALGO, "cachedb msg adjust by zero");
547 		return 1; /* message from the future (clock skew?) */
548 	}
549 	adjust = *qstate->env->now - (time_t)timestamp;
550 	if(qstate->return_msg->rep->ttl < adjust) {
551 		verbose(VERB_ALGO, "cachedb msg expired");
552 		/* If serve-expired is enabled, we still use an expired message
553 		 * setting the TTL to 0. */
554 		if(!qstate->env->cfg->serve_expired ||
555 			(FLAGS_GET_RCODE(qstate->return_msg->rep->flags)
556 			!= LDNS_RCODE_NOERROR &&
557 			FLAGS_GET_RCODE(qstate->return_msg->rep->flags)
558 			!= LDNS_RCODE_NXDOMAIN &&
559 			FLAGS_GET_RCODE(qstate->return_msg->rep->flags)
560 			!= LDNS_RCODE_YXDOMAIN))
561 			return 0; /* message expired */
562 		else
563 			adjust = -1;
564 	}
565 	verbose(VERB_ALGO, "cachedb msg adjusted down by %d", (int)adjust);
566 	adjust_msg_ttl(qstate->return_msg, adjust);
567 
568 	/* Similar to the unbound worker, if serve-expired is enabled and
569 	 * the msg would be considered to be expired, mark the state so a
570 	 * refetch will be scheduled.  The comparison between 'expiry' and
571 	 * 'now' should be redundant given how these values were calculated,
572 	 * but we check it just in case as does good_expiry_and_qinfo(). */
573 	if(qstate->env->cfg->serve_expired &&
574 		(adjust == -1 || (time_t)expiry < *qstate->env->now)) {
575 		qstate->need_refetch = 1;
576 	}
577 
578 	return 1;
579 }
580 
581 /**
582  * Lookup the qstate.qinfo in extcache, store in qstate.return_msg.
583  * return true if lookup was successful.
584  */
585 static int
586 cachedb_extcache_lookup(struct module_qstate* qstate, struct cachedb_env* ie)
587 {
588 	char key[(CACHEDB_HASHSIZE/8)*2+1];
589 	calc_hash(qstate, key, sizeof(key));
590 
591 	/* call backend to fetch data for key into scratch buffer */
592 	if( !(*ie->backend->lookup)(qstate->env, ie, key,
593 		qstate->env->scratch_buffer)) {
594 		return 0;
595 	}
596 
597 	/* check expiry date and check if query-data matches */
598 	if( !good_expiry_and_qinfo(qstate, qstate->env->scratch_buffer) ) {
599 		return 0;
600 	}
601 
602 	/* parse dns message into return_msg */
603 	if( !parse_data(qstate, qstate->env->scratch_buffer) ) {
604 		return 0;
605 	}
606 	return 1;
607 }
608 
609 /**
610  * Store the qstate.return_msg in extcache for key qstate.info
611  */
612 static void
613 cachedb_extcache_store(struct module_qstate* qstate, struct cachedb_env* ie)
614 {
615 	char key[(CACHEDB_HASHSIZE/8)*2+1];
616 	calc_hash(qstate, key, sizeof(key));
617 
618 	/* prepare data in scratch buffer */
619 	if(!prep_data(qstate, qstate->env->scratch_buffer))
620 		return;
621 
622 	/* call backend */
623 	(*ie->backend->store)(qstate->env, ie, key,
624 		sldns_buffer_begin(qstate->env->scratch_buffer),
625 		sldns_buffer_limit(qstate->env->scratch_buffer),
626 		qstate->return_msg->rep->ttl);
627 }
628 
629 /**
630  * See if unbound's internal cache can answer the query
631  */
632 static int
633 cachedb_intcache_lookup(struct module_qstate* qstate)
634 {
635 	uint8_t* dpname=NULL;
636 	size_t dpnamelen=0;
637 	struct dns_msg* msg;
638 	if(iter_stub_fwd_no_cache(qstate, &qstate->qinfo,
639 		&dpname, &dpnamelen))
640 		return 0; /* no cache for these queries */
641 	msg = dns_cache_lookup(qstate->env, qstate->qinfo.qname,
642 		qstate->qinfo.qname_len, qstate->qinfo.qtype,
643 		qstate->qinfo.qclass, qstate->query_flags,
644 		qstate->region, qstate->env->scratch,
645 		1, /* no partial messages with only a CNAME */
646 		dpname, dpnamelen
647 		);
648 	if(!msg && qstate->env->neg_cache &&
649 		iter_qname_indicates_dnssec(qstate->env, &qstate->qinfo)) {
650 		/* lookup in negative cache; may result in
651 		 * NOERROR/NODATA or NXDOMAIN answers that need validation */
652 		msg = val_neg_getmsg(qstate->env->neg_cache, &qstate->qinfo,
653 			qstate->region, qstate->env->rrset_cache,
654 			qstate->env->scratch_buffer,
655 			*qstate->env->now, 1/*add SOA*/, NULL,
656 			qstate->env->cfg);
657 	}
658 	if(!msg)
659 		return 0;
660 	/* this is the returned msg */
661 	qstate->return_rcode = LDNS_RCODE_NOERROR;
662 	qstate->return_msg = msg;
663 	return 1;
664 }
665 
666 /**
667  * Store query into the internal cache of unbound.
668  */
669 static void
670 cachedb_intcache_store(struct module_qstate* qstate)
671 {
672 	uint32_t store_flags = qstate->query_flags;
673 
674 	if(qstate->env->cfg->serve_expired)
675 		store_flags |= DNSCACHE_STORE_ZEROTTL;
676 	if(!qstate->return_msg)
677 		return;
678 	(void)dns_cache_store(qstate->env, &qstate->qinfo,
679 		qstate->return_msg->rep, 0, qstate->prefetch_leeway, 0,
680 		qstate->region, store_flags, qstate->qstarttime);
681 }
682 
683 /**
684  * Handle a cachedb module event with a query
685  * @param qstate: query state (from the mesh), passed between modules.
686  * 	contains qstate->env module environment with global caches and so on.
687  * @param iq: query state specific for this module.  per-query.
688  * @param ie: environment specific for this module.  global.
689  * @param id: module id.
690  */
691 static void
692 cachedb_handle_query(struct module_qstate* qstate,
693 	struct cachedb_qstate* ATTR_UNUSED(iq),
694 	struct cachedb_env* ie, int id)
695 {
696 	/* check if we are enabled, and skip if so */
697 	if(!ie->enabled) {
698 		/* pass request to next module */
699 		qstate->ext_state[id] = module_wait_module;
700 		return;
701 	}
702 
703 	if(qstate->blacklist || qstate->no_cache_lookup) {
704 		/* cache is blacklisted or we are instructed from edns to not look */
705 		/* pass request to next module */
706 		qstate->ext_state[id] = module_wait_module;
707 		return;
708 	}
709 
710 	/* lookup inside unbound's internal cache.
711 	 * This does not look for expired entries. */
712 	if(cachedb_intcache_lookup(qstate)) {
713 		if(verbosity >= VERB_ALGO) {
714 			if(qstate->return_msg->rep)
715 				log_dns_msg("cachedb internal cache lookup",
716 					&qstate->return_msg->qinfo,
717 					qstate->return_msg->rep);
718 			else log_info("cachedb internal cache lookup: rcode %s",
719 				sldns_lookup_by_id(sldns_rcodes, qstate->return_rcode)
720 				?sldns_lookup_by_id(sldns_rcodes, qstate->return_rcode)->name
721 				:"??");
722 		}
723 		/* we are done with the query */
724 		qstate->ext_state[id] = module_finished;
725 		return;
726 	}
727 
728 	/* ask backend cache to see if we have data */
729 	if(cachedb_extcache_lookup(qstate, ie)) {
730 		if(verbosity >= VERB_ALGO)
731 			log_dns_msg(ie->backend->name,
732 				&qstate->return_msg->qinfo,
733 				qstate->return_msg->rep);
734 		/* store this result in internal cache */
735 		cachedb_intcache_store(qstate);
736 		/* In case we have expired data but there is a client timer for expired
737 		 * answers, pass execution to next module in order to try updating the
738 		 * data first.
739 		 * TODO: this needs revisit. The expired data stored from cachedb has
740 		 * 0 TTL which is picked up by iterator later when looking in the cache.
741 		 * Document that ext cachedb does not work properly with
742 		 * serve_stale_reply_ttl yet. */
743 		if(qstate->need_refetch && qstate->serve_expired_data &&
744 			qstate->serve_expired_data->timer) {
745 				qstate->return_msg = NULL;
746 				qstate->ext_state[id] = module_wait_module;
747 				return;
748 		}
749 		/* we are done with the query */
750 		qstate->ext_state[id] = module_finished;
751 		return;
752 	}
753 
754 	/* no cache fetches */
755 	/* pass request to next module */
756 	qstate->ext_state[id] = module_wait_module;
757 }
758 
759 /**
760  * Handle a cachedb module event with a response from the iterator.
761  * @param qstate: query state (from the mesh), passed between modules.
762  * 	contains qstate->env module environment with global caches and so on.
763  * @param iq: query state specific for this module.  per-query.
764  * @param ie: environment specific for this module.  global.
765  * @param id: module id.
766  */
767 static void
768 cachedb_handle_response(struct module_qstate* qstate,
769 	struct cachedb_qstate* ATTR_UNUSED(iq), struct cachedb_env* ie, int id)
770 {
771 	/* check if we are not enabled or instructed to not cache, and skip */
772 	if(!ie->enabled || qstate->no_cache_store) {
773 		/* we are done with the query */
774 		qstate->ext_state[id] = module_finished;
775 		return;
776 	}
777 
778 	/* store the item into the backend cache */
779 	cachedb_extcache_store(qstate, ie);
780 
781 	/* we are done with the query */
782 	qstate->ext_state[id] = module_finished;
783 }
784 
785 void
786 cachedb_operate(struct module_qstate* qstate, enum module_ev event, int id,
787 	struct outbound_entry* outbound)
788 {
789 	struct cachedb_env* ie = (struct cachedb_env*)qstate->env->modinfo[id];
790 	struct cachedb_qstate* iq = (struct cachedb_qstate*)qstate->minfo[id];
791 	verbose(VERB_QUERY, "cachedb[module %d] operate: extstate:%s event:%s",
792 		id, strextstate(qstate->ext_state[id]), strmodulevent(event));
793 	if(iq) log_query_info(VERB_QUERY, "cachedb operate: query",
794 		&qstate->qinfo);
795 
796 	/* perform cachedb state machine */
797 	if((event == module_event_new || event == module_event_pass) &&
798 		iq == NULL) {
799 		if(!cachedb_new(qstate, id)) {
800 			(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
801 			return;
802 		}
803 		iq = (struct cachedb_qstate*)qstate->minfo[id];
804 	}
805 	if(iq && (event == module_event_pass || event == module_event_new)) {
806 		cachedb_handle_query(qstate, iq, ie, id);
807 		return;
808 	}
809 	if(iq && (event == module_event_moddone)) {
810 		cachedb_handle_response(qstate, iq, ie, id);
811 		return;
812 	}
813 	if(iq && outbound) {
814 		/* cachedb does not need to process responses at this time
815 		 * ignore it.
816 		cachedb_process_response(qstate, iq, ie, id, outbound, event);
817 		*/
818 		return;
819 	}
820 	if(event == module_event_error) {
821 		verbose(VERB_ALGO, "got called with event error, giving up");
822 		(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
823 		return;
824 	}
825 	if(!iq && (event == module_event_moddone)) {
826 		/* during priming, module done but we never started */
827 		qstate->ext_state[id] = module_finished;
828 		return;
829 	}
830 
831 	log_err("bad event for cachedb");
832 	(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
833 }
834 
835 void
836 cachedb_inform_super(struct module_qstate* ATTR_UNUSED(qstate),
837 	int ATTR_UNUSED(id), struct module_qstate* ATTR_UNUSED(super))
838 {
839 	/* cachedb does not use subordinate requests at this time */
840 	verbose(VERB_ALGO, "cachedb inform_super was called");
841 }
842 
843 void
844 cachedb_clear(struct module_qstate* qstate, int id)
845 {
846 	struct cachedb_qstate* iq;
847 	if(!qstate)
848 		return;
849 	iq = (struct cachedb_qstate*)qstate->minfo[id];
850 	if(iq) {
851 		/* free contents of iq */
852 		/* TODO */
853 	}
854 	qstate->minfo[id] = NULL;
855 }
856 
857 size_t
858 cachedb_get_mem(struct module_env* env, int id)
859 {
860 	struct cachedb_env* ie = (struct cachedb_env*)env->modinfo[id];
861 	if(!ie)
862 		return 0;
863 	return sizeof(*ie); /* TODO - more mem */
864 }
865 
866 /**
867  * The cachedb function block
868  */
869 static struct module_func_block cachedb_block = {
870 	"cachedb",
871 	&cachedb_init, &cachedb_deinit, &cachedb_operate,
872 	&cachedb_inform_super, &cachedb_clear, &cachedb_get_mem
873 };
874 
875 struct module_func_block*
876 cachedb_get_funcblock(void)
877 {
878 	return &cachedb_block;
879 }
880 #endif /* USE_CACHEDB */
881