xref: /openbsd-src/usr.sbin/unbound/cachedb/cachedb.c (revision f763167468dba5339ed4b14b7ecaca2a397ab0f6)
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 "util/regional.h"
47 #include "util/net_help.h"
48 #include "util/config_file.h"
49 #include "util/data/msgreply.h"
50 #include "util/data/msgencode.h"
51 #include "services/cache/dns.h"
52 #include "validator/val_neg.h"
53 #include "validator/val_secalgo.h"
54 #include "iterator/iter_utils.h"
55 #include "sldns/parseutil.h"
56 #include "sldns/wire2str.h"
57 #include "sldns/sbuffer.h"
58 
59 #define CACHEDB_HASHSIZE 256 /* bit hash */
60 
61 /** the unit test testframe for cachedb, its module state contains
62  * a cache for a couple queries (in memory). */
63 struct testframe_moddata {
64 	/** lock for mutex */
65 	lock_basic_type lock;
66 	/** key for single stored data element, NULL if none */
67 	char* stored_key;
68 	/** data for single stored data element, NULL if none */
69 	uint8_t* stored_data;
70 	/** length of stored data */
71 	size_t stored_datalen;
72 };
73 
74 static int
75 testframe_init(struct module_env* env, struct cachedb_env* cachedb_env)
76 {
77 	struct testframe_moddata* d;
78 	(void)env;
79 	verbose(VERB_ALGO, "testframe_init");
80 	d = (struct testframe_moddata*)calloc(1,
81 		sizeof(struct testframe_moddata));
82 	cachedb_env->backend_data = (void*)d;
83 	if(!cachedb_env->backend_data) {
84 		log_err("out of memory");
85 		return 0;
86 	}
87 	lock_basic_init(&d->lock);
88 	lock_protect(&d->lock, d, sizeof(*d));
89 	return 1;
90 }
91 
92 static void
93 testframe_deinit(struct module_env* env, struct cachedb_env* cachedb_env)
94 {
95 	struct testframe_moddata* d = (struct testframe_moddata*)
96 		cachedb_env->backend_data;
97 	(void)env;
98 	verbose(VERB_ALGO, "testframe_deinit");
99 	if(!d)
100 		return;
101 	lock_basic_destroy(&d->lock);
102 	free(d->stored_key);
103 	free(d->stored_data);
104 	free(d);
105 }
106 
107 static int
108 testframe_lookup(struct module_env* env, struct cachedb_env* cachedb_env,
109 	char* key, struct sldns_buffer* result_buffer)
110 {
111 	struct testframe_moddata* d = (struct testframe_moddata*)
112 		cachedb_env->backend_data;
113 	(void)env;
114 	verbose(VERB_ALGO, "testframe_lookup of %s", key);
115 	lock_basic_lock(&d->lock);
116 	if(d->stored_key && strcmp(d->stored_key, key) == 0) {
117 		if(d->stored_datalen > sldns_buffer_capacity(result_buffer)) {
118 			lock_basic_unlock(&d->lock);
119 			return 0; /* too large */
120 		}
121 		verbose(VERB_ALGO, "testframe_lookup found %d bytes",
122 			(int)d->stored_datalen);
123 		sldns_buffer_clear(result_buffer);
124 		sldns_buffer_write(result_buffer, d->stored_data,
125 			d->stored_datalen);
126 		sldns_buffer_flip(result_buffer);
127 		lock_basic_unlock(&d->lock);
128 		return 1;
129 	}
130 	lock_basic_unlock(&d->lock);
131 	return 0;
132 }
133 
134 static void
135 testframe_store(struct module_env* env, struct cachedb_env* cachedb_env,
136 	char* key, uint8_t* data, size_t data_len)
137 {
138 	struct testframe_moddata* d = (struct testframe_moddata*)
139 		cachedb_env->backend_data;
140 	(void)env;
141 	lock_basic_lock(&d->lock);
142 	verbose(VERB_ALGO, "testframe_store %s (%d bytes)", key, (int)data_len);
143 
144 	/* free old data element (if any) */
145 	free(d->stored_key);
146 	d->stored_key = NULL;
147 	free(d->stored_data);
148 	d->stored_data = NULL;
149 	d->stored_datalen = 0;
150 
151 	d->stored_data = memdup(data, data_len);
152 	if(!d->stored_data) {
153 		lock_basic_unlock(&d->lock);
154 		log_err("out of memory");
155 		return;
156 	}
157 	d->stored_datalen = data_len;
158 	d->stored_key = strdup(key);
159 	if(!d->stored_key) {
160 		free(d->stored_data);
161 		d->stored_data = NULL;
162 		d->stored_datalen = 0;
163 		lock_basic_unlock(&d->lock);
164 		return;
165 	}
166 	lock_basic_unlock(&d->lock);
167 	/* (key,data) successfully stored */
168 }
169 
170 /** The testframe backend is for unit tests */
171 static struct cachedb_backend testframe_backend = { "testframe",
172 	testframe_init, testframe_deinit, testframe_lookup, testframe_store
173 };
174 
175 /** find a particular backend from possible backends */
176 static struct cachedb_backend*
177 cachedb_find_backend(const char* str)
178 {
179 	if(strcmp(str, testframe_backend.name) == 0)
180 		return &testframe_backend;
181 	/* TODO add more backends here */
182 	return NULL;
183 }
184 
185 /** apply configuration to cachedb module 'global' state */
186 static int
187 cachedb_apply_cfg(struct cachedb_env* cachedb_env, struct config_file* cfg)
188 {
189 	const char* backend_str = cfg->cachedb_backend;
190 
191 	/* If unspecified we use the in-memory test DB. */
192 	if(!backend_str)
193 		backend_str = "testframe";
194 	cachedb_env->backend = cachedb_find_backend(backend_str);
195 	if(!cachedb_env->backend) {
196 		log_err("cachedb: cannot find backend name '%s'", backend_str);
197 		return 0;
198 	}
199 
200 	/* TODO see if more configuration needs to be applied or not */
201 	return 1;
202 }
203 
204 int
205 cachedb_init(struct module_env* env, int id)
206 {
207 	struct cachedb_env* cachedb_env = (struct cachedb_env*)calloc(1,
208 		sizeof(struct cachedb_env));
209 	if(!cachedb_env) {
210 		log_err("malloc failure");
211 		return 0;
212 	}
213 	env->modinfo[id] = (void*)cachedb_env;
214 	if(!cachedb_apply_cfg(cachedb_env, env->cfg)) {
215 		log_err("cachedb: could not apply configuration settings.");
216 		return 0;
217 	}
218 	/* see if a backend is selected */
219 	if(!cachedb_env->backend || !cachedb_env->backend->name)
220 		return 1;
221 	if(!(*cachedb_env->backend->init)(env, cachedb_env)) {
222 		log_err("cachedb: could not init %s backend",
223 			cachedb_env->backend->name);
224 		return 0;
225 	}
226 	cachedb_env->enabled = 1;
227 	return 1;
228 }
229 
230 void
231 cachedb_deinit(struct module_env* env, int id)
232 {
233 	struct cachedb_env* cachedb_env;
234 	if(!env || !env->modinfo[id])
235 		return;
236 	cachedb_env = (struct cachedb_env*)env->modinfo[id];
237 	/* free contents */
238 	/* TODO */
239 	if(cachedb_env->enabled) {
240 		(*cachedb_env->backend->deinit)(env, cachedb_env);
241 	}
242 
243 	free(cachedb_env);
244 	env->modinfo[id] = NULL;
245 }
246 
247 /** new query for cachedb */
248 static int
249 cachedb_new(struct module_qstate* qstate, int id)
250 {
251 	struct cachedb_qstate* iq = (struct cachedb_qstate*)regional_alloc(
252 		qstate->region, sizeof(struct cachedb_qstate));
253 	qstate->minfo[id] = iq;
254 	if(!iq)
255 		return 0;
256 	memset(iq, 0, sizeof(*iq));
257 	/* initialise it */
258 	/* TODO */
259 
260 	return 1;
261 }
262 
263 /**
264  * Return an error
265  * @param qstate: our query state
266  * @param id: module id
267  * @param rcode: error code (DNS errcode).
268  * @return: 0 for use by caller, to make notation easy, like:
269  * 	return error_response(..).
270  */
271 static int
272 error_response(struct module_qstate* qstate, int id, int rcode)
273 {
274 	verbose(VERB_QUERY, "return error response %s",
275 		sldns_lookup_by_id(sldns_rcodes, rcode)?
276 		sldns_lookup_by_id(sldns_rcodes, rcode)->name:"??");
277 	qstate->return_rcode = rcode;
278 	qstate->return_msg = NULL;
279 	qstate->ext_state[id] = module_finished;
280 	return 0;
281 }
282 
283 /**
284  * Hash the query name, type, class and dbacess-secret into lookup buffer.
285  * @param qstate: query state with query info
286  * 	and env->cfg with secret.
287  * @param buf: returned buffer with hash to lookup
288  * @param len: length of the buffer.
289  */
290 static void
291 calc_hash(struct module_qstate* qstate, char* buf, size_t len)
292 {
293 	uint8_t clear[1024];
294 	size_t clen = 0;
295 	uint8_t hash[CACHEDB_HASHSIZE/8];
296 	const char* hex = "0123456789ABCDEF";
297 	const char* secret = qstate->env->cfg->cachedb_secret ?
298 		qstate->env->cfg->cachedb_secret : "default";
299 	size_t i;
300 
301 	/* copy the hash info into the clear buffer */
302 	if(clen + qstate->qinfo.qname_len < sizeof(clear)) {
303 		memmove(clear+clen, qstate->qinfo.qname,
304 			qstate->qinfo.qname_len);
305 		clen += qstate->qinfo.qname_len;
306 	}
307 	if(clen + 4 < sizeof(clear)) {
308 		uint16_t t = htons(qstate->qinfo.qtype);
309 		uint16_t c = htons(qstate->qinfo.qclass);
310 		memmove(clear+clen, &t, 2);
311 		memmove(clear+clen+2, &c, 2);
312 		clen += 4;
313 	}
314 	if(secret && secret[0] && clen + strlen(secret) < sizeof(clear)) {
315 		memmove(clear+clen, secret, strlen(secret));
316 		clen += strlen(secret);
317 	}
318 
319 	/* hash the buffer */
320 	secalgo_hash_sha256(clear, clen, hash);
321 	memset(clear, 0, clen);
322 
323 	/* hex encode output for portability (some online dbs need
324 	 * no nulls, no control characters, and so on) */
325 	log_assert(len >= sizeof(hash)*2 + 1);
326 	(void)len;
327 	for(i=0; i<sizeof(hash); i++) {
328 		buf[i*2] = hex[(hash[i]&0xf0)>>4];
329 		buf[i*2+1] = hex[hash[i]&0x0f];
330 	}
331 	buf[sizeof(hash)*2] = 0;
332 }
333 
334 /** convert data from return_msg into the data buffer */
335 static int
336 prep_data(struct module_qstate* qstate, struct sldns_buffer* buf)
337 {
338 	uint64_t timestamp, expiry;
339 	size_t oldlim;
340 	struct edns_data edns;
341 	memset(&edns, 0, sizeof(edns));
342 	edns.edns_present = 1;
343 	edns.bits = EDNS_DO;
344 	edns.ext_rcode = 0;
345 	edns.edns_version = EDNS_ADVERTISED_VERSION;
346 	edns.udp_size = EDNS_ADVERTISED_SIZE;
347 
348 	if(!qstate->return_msg || !qstate->return_msg->rep)
349 		return 0;
350 	if(verbosity >= VERB_ALGO)
351 		log_dns_msg("cachedb encoding", &qstate->return_msg->qinfo,
352 	                qstate->return_msg->rep);
353 	if(!reply_info_answer_encode(&qstate->return_msg->qinfo,
354 		qstate->return_msg->rep, 0, qstate->query_flags,
355 		buf, 0, 1, qstate->env->scratch, 65535, &edns, 1, 0))
356 		return 0;
357 
358 	/* TTLs in the return_msg are relative to time(0) so we have to
359 	 * store that, we also store the smallest ttl in the packet+time(0)
360 	 * as the packet expiry time */
361 	/* qstate->return_msg->rep->ttl contains that relative shortest ttl */
362 	timestamp = (uint64_t)*qstate->env->now;
363 	expiry = timestamp + (uint64_t)qstate->return_msg->rep->ttl;
364 	timestamp = htobe64(timestamp);
365 	expiry = htobe64(expiry);
366 	oldlim = sldns_buffer_limit(buf);
367 	if(oldlim + sizeof(timestamp)+sizeof(expiry) >=
368 		sldns_buffer_capacity(buf))
369 		return 0; /* doesn't fit. */
370 	sldns_buffer_set_limit(buf, oldlim + sizeof(timestamp)+sizeof(expiry));
371 	sldns_buffer_write_at(buf, oldlim, &timestamp, sizeof(timestamp));
372 	sldns_buffer_write_at(buf, oldlim+sizeof(timestamp), &expiry,
373 		sizeof(expiry));
374 
375 	return 1;
376 }
377 
378 /** check expiry, return true if matches OK */
379 static int
380 good_expiry_and_qinfo(struct module_qstate* qstate, struct sldns_buffer* buf)
381 {
382 	uint64_t expiry;
383 	/* the expiry time is the last bytes of the buffer */
384 	if(sldns_buffer_limit(buf) < sizeof(expiry))
385 		return 0;
386 	sldns_buffer_read_at(buf, sldns_buffer_limit(buf)-sizeof(expiry),
387 		&expiry, sizeof(expiry));
388 	expiry = be64toh(expiry);
389 
390 	if((time_t)expiry < *qstate->env->now)
391 		return 0;
392 
393 	return 1;
394 }
395 
396 static void
397 packed_rrset_ttl_subtract(struct packed_rrset_data* data, time_t subtract)
398 {
399         size_t i;
400         size_t total = data->count + data->rrsig_count;
401 	if(data->ttl > subtract)
402 		data->ttl -= subtract;
403 	else	data->ttl = 0;
404         for(i=0; i<total; i++) {
405 		if(data->rr_ttl[i] > subtract)
406                 	data->rr_ttl[i] -= subtract;
407                 else	data->rr_ttl[i] = 0;
408 	}
409 }
410 
411 static void
412 adjust_msg_ttl(struct dns_msg* msg, time_t adjust)
413 {
414 	size_t i;
415 	if(msg->rep->ttl > adjust)
416 		msg->rep->ttl -= adjust;
417 	else	msg->rep->ttl = 0;
418 	msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
419 
420 	for(i=0; i<msg->rep->rrset_count; i++) {
421 		packed_rrset_ttl_subtract((struct packed_rrset_data*)msg->
422 			rep->rrsets[i]->entry.data, adjust);
423 	}
424 }
425 
426 /** convert dns message in buffer to return_msg */
427 static int
428 parse_data(struct module_qstate* qstate, struct sldns_buffer* buf)
429 {
430 	struct msg_parse* prs;
431 	struct edns_data edns;
432 	uint64_t timestamp, expiry;
433 	time_t adjust;
434 	size_t lim = sldns_buffer_limit(buf);
435 	if(lim < LDNS_HEADER_SIZE+sizeof(timestamp)+sizeof(expiry))
436 		return 0; /* too short */
437 
438 	/* remove timestamp and expiry from end */
439 	sldns_buffer_read_at(buf, lim-sizeof(expiry), &expiry, sizeof(expiry));
440 	sldns_buffer_read_at(buf, lim-sizeof(expiry)-sizeof(timestamp),
441 		&timestamp, sizeof(timestamp));
442 	expiry = be64toh(expiry);
443 	timestamp = be64toh(timestamp);
444 
445 	/* parse DNS packet */
446 	regional_free_all(qstate->env->scratch);
447 	prs = (struct msg_parse*)regional_alloc(qstate->env->scratch,
448 		sizeof(struct msg_parse));
449 	if(!prs)
450 		return 0; /* out of memory */
451 	memset(prs, 0, sizeof(*prs));
452 	memset(&edns, 0, sizeof(edns));
453 	sldns_buffer_set_limit(buf, lim - sizeof(expiry)-sizeof(timestamp));
454 	if(parse_packet(buf, prs, qstate->env->scratch) != LDNS_RCODE_NOERROR) {
455 		sldns_buffer_set_limit(buf, lim);
456 		return 0;
457 	}
458 	if(parse_extract_edns(prs, &edns, qstate->env->scratch) !=
459 		LDNS_RCODE_NOERROR) {
460 		sldns_buffer_set_limit(buf, lim);
461 		return 0;
462 	}
463 
464 	qstate->return_msg = dns_alloc_msg(buf, prs, qstate->region);
465 	sldns_buffer_set_limit(buf, lim);
466 	if(!qstate->return_msg)
467 		return 0;
468 
469 	qstate->return_rcode = LDNS_RCODE_NOERROR;
470 
471 	/* see how much of the TTL expired, and remove it */
472 	if(*qstate->env->now <= (time_t)timestamp) {
473 		verbose(VERB_ALGO, "cachedb msg adjust by zero");
474 		return 1; /* message from the future (clock skew?) */
475 	}
476 	adjust = *qstate->env->now - (time_t)timestamp;
477 	if(qstate->return_msg->rep->ttl < adjust) {
478 		verbose(VERB_ALGO, "cachedb msg expired");
479 		return 0; /* message expired */
480 	}
481 	verbose(VERB_ALGO, "cachedb msg adjusted down by %d", (int)adjust);
482 	adjust_msg_ttl(qstate->return_msg, adjust);
483 	return 1;
484 }
485 
486 /**
487  * Lookup the qstate.qinfo in extcache, store in qstate.return_msg.
488  * return true if lookup was successful.
489  */
490 static int
491 cachedb_extcache_lookup(struct module_qstate* qstate, struct cachedb_env* ie)
492 {
493 	char key[(CACHEDB_HASHSIZE/8)*2+1];
494 	calc_hash(qstate, key, sizeof(key));
495 
496 	/* call backend to fetch data for key into scratch buffer */
497 	if( !(*ie->backend->lookup)(qstate->env, ie, key,
498 		qstate->env->scratch_buffer)) {
499 		return 0;
500 	}
501 
502 	/* check expiry date and check if query-data matches */
503 	if( !good_expiry_and_qinfo(qstate, qstate->env->scratch_buffer) ) {
504 		return 0;
505 	}
506 
507 	/* parse dns message into return_msg */
508 	if( !parse_data(qstate, qstate->env->scratch_buffer) ) {
509 		return 0;
510 	}
511 	return 1;
512 }
513 
514 /**
515  * Store the qstate.return_msg in extcache for key qstate.info
516  */
517 static void
518 cachedb_extcache_store(struct module_qstate* qstate, struct cachedb_env* ie)
519 {
520 	char key[(CACHEDB_HASHSIZE/8)*2+1];
521 	calc_hash(qstate, key, sizeof(key));
522 
523 	/* prepare data in scratch buffer */
524 	if(!prep_data(qstate, qstate->env->scratch_buffer))
525 		return;
526 
527 	/* call backend */
528 	(*ie->backend->store)(qstate->env, ie, key,
529 		sldns_buffer_begin(qstate->env->scratch_buffer),
530 		sldns_buffer_limit(qstate->env->scratch_buffer));
531 }
532 
533 /**
534  * See if unbound's internal cache can answer the query
535  */
536 static int
537 cachedb_intcache_lookup(struct module_qstate* qstate)
538 {
539 	struct dns_msg* msg;
540 	msg = dns_cache_lookup(qstate->env, qstate->qinfo.qname,
541 		qstate->qinfo.qname_len, qstate->qinfo.qtype,
542 		qstate->qinfo.qclass, qstate->query_flags,
543 		qstate->region, qstate->env->scratch);
544 	if(!msg && qstate->env->neg_cache) {
545 		/* lookup in negative cache; may result in
546 		 * NOERROR/NODATA or NXDOMAIN answers that need validation */
547 		msg = val_neg_getmsg(qstate->env->neg_cache, &qstate->qinfo,
548 			qstate->region, qstate->env->rrset_cache,
549 			qstate->env->scratch_buffer,
550 			*qstate->env->now, 1/*add SOA*/, NULL);
551 	}
552 	if(!msg)
553 		return 0;
554 	/* this is the returned msg */
555 	qstate->return_rcode = LDNS_RCODE_NOERROR;
556 	qstate->return_msg = msg;
557 	return 1;
558 }
559 
560 /**
561  * Store query into the internal cache of unbound.
562  */
563 static void
564 cachedb_intcache_store(struct module_qstate* qstate)
565 {
566 	if(!qstate->return_msg)
567 		return;
568 	(void)dns_cache_store(qstate->env, &qstate->qinfo,
569 		qstate->return_msg->rep, 0, qstate->prefetch_leeway, 0,
570 		qstate->region, qstate->query_flags);
571 }
572 
573 /**
574  * Handle a cachedb module event with a query
575  * @param qstate: query state (from the mesh), passed between modules.
576  * 	contains qstate->env module environment with global caches and so on.
577  * @param iq: query state specific for this module.  per-query.
578  * @param ie: environment specific for this module.  global.
579  * @param id: module id.
580  */
581 static void
582 cachedb_handle_query(struct module_qstate* qstate,
583 	struct cachedb_qstate* ATTR_UNUSED(iq),
584 	struct cachedb_env* ie, int id)
585 {
586 	/* check if we are enabled, and skip if so */
587 	if(!ie->enabled) {
588 		/* pass request to next module */
589 		qstate->ext_state[id] = module_wait_module;
590 		return;
591 	}
592 
593 	if(qstate->blacklist || qstate->no_cache_lookup) {
594 		/* cache is blacklisted or we are instructed from edns to not look */
595 		/* pass request to next module */
596 		qstate->ext_state[id] = module_wait_module;
597 		return;
598 	}
599 
600 	/* lookup inside unbound's internal cache */
601 	if(cachedb_intcache_lookup(qstate)) {
602 		if(verbosity >= VERB_ALGO) {
603 			if(qstate->return_msg->rep)
604 				log_dns_msg("cachedb internal cache lookup",
605 					&qstate->return_msg->qinfo,
606 					qstate->return_msg->rep);
607 			else log_info("cachedb internal cache lookup: rcode %s",
608 				sldns_lookup_by_id(sldns_rcodes, qstate->return_rcode)?
609 				sldns_lookup_by_id(sldns_rcodes, qstate->return_rcode)->name:"??");
610 		}
611 		/* we are done with the query */
612 		qstate->ext_state[id] = module_finished;
613 		return;
614 	}
615 
616 	/* ask backend cache to see if we have data */
617 	if(cachedb_extcache_lookup(qstate, ie)) {
618 		if(verbosity >= VERB_ALGO)
619 			log_dns_msg(ie->backend->name,
620 				&qstate->return_msg->qinfo,
621 				qstate->return_msg->rep);
622 		/* store this result in internal cache */
623 		cachedb_intcache_store(qstate);
624 		/* we are done with the query */
625 		qstate->ext_state[id] = module_finished;
626 		return;
627 	}
628 
629 	/* no cache fetches */
630 	/* pass request to next module */
631 	qstate->ext_state[id] = module_wait_module;
632 }
633 
634 /**
635  * Handle a cachedb module event with a response from the iterator.
636  * @param qstate: query state (from the mesh), passed between modules.
637  * 	contains qstate->env module environment with global caches and so on.
638  * @param iq: query state specific for this module.  per-query.
639  * @param ie: environment specific for this module.  global.
640  * @param id: module id.
641  */
642 static void
643 cachedb_handle_response(struct module_qstate* qstate,
644 	struct cachedb_qstate* ATTR_UNUSED(iq), struct cachedb_env* ie, int id)
645 {
646 	/* check if we are not enabled or instructed to not cache, and skip */
647 	if(!ie->enabled || qstate->no_cache_store) {
648 		/* we are done with the query */
649 		qstate->ext_state[id] = module_finished;
650 		return;
651 	}
652 
653 	/* store the item into the backend cache */
654 	cachedb_extcache_store(qstate, ie);
655 
656 	/* we are done with the query */
657 	qstate->ext_state[id] = module_finished;
658 }
659 
660 void
661 cachedb_operate(struct module_qstate* qstate, enum module_ev event, int id,
662 	struct outbound_entry* outbound)
663 {
664 	struct cachedb_env* ie = (struct cachedb_env*)qstate->env->modinfo[id];
665 	struct cachedb_qstate* iq = (struct cachedb_qstate*)qstate->minfo[id];
666 	verbose(VERB_QUERY, "cachedb[module %d] operate: extstate:%s event:%s",
667 		id, strextstate(qstate->ext_state[id]), strmodulevent(event));
668 	if(iq) log_query_info(VERB_QUERY, "cachedb operate: query",
669 		&qstate->qinfo);
670 
671 	/* perform cachedb state machine */
672 	if((event == module_event_new || event == module_event_pass) &&
673 		iq == NULL) {
674 		if(!cachedb_new(qstate, id)) {
675 			(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
676 			return;
677 		}
678 		iq = (struct cachedb_qstate*)qstate->minfo[id];
679 	}
680 	if(iq && (event == module_event_pass || event == module_event_new)) {
681 		cachedb_handle_query(qstate, iq, ie, id);
682 		return;
683 	}
684 	if(iq && (event == module_event_moddone)) {
685 		cachedb_handle_response(qstate, iq, ie, id);
686 		return;
687 	}
688 	if(iq && outbound) {
689 		/* cachedb does not need to process responses at this time
690 		 * ignore it.
691 		cachedb_process_response(qstate, iq, ie, id, outbound, event);
692 		*/
693 		return;
694 	}
695 	if(event == module_event_error) {
696 		verbose(VERB_ALGO, "got called with event error, giving up");
697 		(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
698 		return;
699 	}
700 	if(!iq && (event == module_event_moddone)) {
701 		/* during priming, module done but we never started */
702 		qstate->ext_state[id] = module_finished;
703 		return;
704 	}
705 
706 	log_err("bad event for cachedb");
707 	(void)error_response(qstate, id, LDNS_RCODE_SERVFAIL);
708 }
709 
710 void
711 cachedb_inform_super(struct module_qstate* ATTR_UNUSED(qstate),
712 	int ATTR_UNUSED(id), struct module_qstate* ATTR_UNUSED(super))
713 {
714 	/* cachedb does not use subordinate requests at this time */
715 	verbose(VERB_ALGO, "cachedb inform_super was called");
716 }
717 
718 void
719 cachedb_clear(struct module_qstate* qstate, int id)
720 {
721 	struct cachedb_qstate* iq;
722 	if(!qstate)
723 		return;
724 	iq = (struct cachedb_qstate*)qstate->minfo[id];
725 	if(iq) {
726 		/* free contents of iq */
727 		/* TODO */
728 	}
729 	qstate->minfo[id] = NULL;
730 }
731 
732 size_t
733 cachedb_get_mem(struct module_env* env, int id)
734 {
735 	struct cachedb_env* ie = (struct cachedb_env*)env->modinfo[id];
736 	if(!ie)
737 		return 0;
738 	return sizeof(*ie); /* TODO - more mem */
739 }
740 
741 /**
742  * The cachedb function block
743  */
744 static struct module_func_block cachedb_block = {
745 	"cachedb",
746 	&cachedb_init, &cachedb_deinit, &cachedb_operate,
747 	&cachedb_inform_super, &cachedb_clear, &cachedb_get_mem
748 };
749 
750 struct module_func_block*
751 cachedb_get_funcblock(void)
752 {
753 	return &cachedb_block;
754 }
755 #endif /* USE_CACHEDB */
756