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