autotrust.c revision 291767
138061Smsmith/*
255939Snsouch * validator/autotrust.c - RFC5011 trust anchor management for unbound.
370608Snsouch *
438061Smsmith * Copyright (c) 2009, NLnet Labs. All rights reserved.
538061Smsmith *
638061Smsmith * This software is open source.
738061Smsmith *
838061Smsmith * Redistribution and use in source and binary forms, with or without
938061Smsmith * modification, are permitted provided that the following conditions
1038061Smsmith * are met:
1138061Smsmith *
1238061Smsmith * Redistributions of source code must retain the above copyright notice,
1338061Smsmith * this list of conditions and the following disclaimer.
1438061Smsmith *
1538061Smsmith * Redistributions in binary form must reproduce the above copyright notice,
1638061Smsmith * this list of conditions and the following disclaimer in the documentation
1738061Smsmith * and/or other materials provided with the distribution.
1838061Smsmith *
1938061Smsmith * Neither the name of the NLNET LABS nor the names of its contributors may
2038061Smsmith * be used to endorse or promote products derived from this software without
2138061Smsmith * specific prior written permission.
2238061Smsmith *
2338061Smsmith * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2438061Smsmith * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2538061Smsmith * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2638061Smsmith * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2738061Smsmith * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2838061Smsmith * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
2938061Smsmith * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30119418Sobrien * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31119418Sobrien * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32119418Sobrien * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
3355205Speter * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3438061Smsmith */
3538061Smsmith
3655939Snsouch/**
3755939Snsouch * \file
3838061Smsmith *
3938061Smsmith * Contains autotrust implementation. The implementation was taken from
4038061Smsmith * the autotrust daemon (BSD licensed), written by Matthijs Mekking.
4155205Speter * It was modified to fit into unbound. The state table process is the same.
4238061Smsmith */
4342475Snsouch#include "config.h"
4442475Snsouch#include "validator/autotrust.h"
4555939Snsouch#include "validator/val_anchor.h"
4638061Smsmith#include "validator/val_utils.h"
4738061Smsmith#include "validator/val_sigcrypt.h"
4838061Smsmith#include "util/data/dname.h"
4938061Smsmith#include "util/data/packed_rrset.h"
5055939Snsouch#include "util/log.h"
5155939Snsouch#include "util/module.h"
5238061Smsmith#include "util/net_help.h"
5338061Smsmith#include "util/config_file.h"
5438061Smsmith#include "util/regional.h"
5538061Smsmith#include "util/random.h"
5638061Smsmith#include "util/data/msgparse.h"
5738061Smsmith#include "services/mesh.h"
5838061Smsmith#include "services/cache/rrset.h"
5938061Smsmith#include "validator/val_kcache.h"
6038061Smsmith#include "sldns/sbuffer.h"
6138061Smsmith#include "sldns/wire2str.h"
6238061Smsmith#include "sldns/str2wire.h"
6338061Smsmith#include "sldns/keyraw.h"
6438061Smsmith#include "sldns/rrdef.h"
6538061Smsmith#include <stdarg.h>
6638061Smsmith#include <ctype.h>
6738061Smsmith
6838061Smsmith/** number of times a key must be seen before it can become valid */
6938061Smsmith#define MIN_PENDINGCOUNT 2
7038061Smsmith
7138061Smsmith/** Event: Revoked */
7238061Smsmithstatic void do_revoked(struct module_env* env, struct autr_ta* anchor, int* c);
7338061Smsmith
7438061Smsmithstruct autr_global_data* autr_global_create(void)
7538061Smsmith{
7638061Smsmith	struct autr_global_data* global;
7738061Smsmith	global = (struct autr_global_data*)malloc(sizeof(*global));
7838061Smsmith	if(!global)
7938061Smsmith		return NULL;
8038061Smsmith	rbtree_init(&global->probe, &probetree_cmp);
8138061Smsmith	return global;
8238061Smsmith}
8338061Smsmith
8439134Snsouchvoid autr_global_delete(struct autr_global_data* global)
8539134Snsouch{
8638061Smsmith	if(!global)
8738061Smsmith		return;
8838061Smsmith	/* elements deleted by parent */
8938061Smsmith	memset(global, 0, sizeof(*global));
9038061Smsmith	free(global);
9138061Smsmith}
9238061Smsmith
9338061Smsmithint probetree_cmp(const void* x, const void* y)
9438061Smsmith{
9538061Smsmith	struct trust_anchor* a = (struct trust_anchor*)x;
9638061Smsmith	struct trust_anchor* b = (struct trust_anchor*)y;
9738061Smsmith	log_assert(a->autr && b->autr);
9838061Smsmith	if(a->autr->next_probe_time < b->autr->next_probe_time)
9978645Snsouch		return -1;
10078645Snsouch	if(a->autr->next_probe_time > b->autr->next_probe_time)
10178645Snsouch		return 1;
10278645Snsouch	/* time is equal, sort on trust point identity */
10378645Snsouch	return anchor_cmp(x, y);
10478645Snsouch}
10578645Snsouch
10678645Snsouchsize_t
10778645Snsouchautr_get_num_anchors(struct val_anchors* anchors)
10878645Snsouch{
10978645Snsouch	size_t res = 0;
11078645Snsouch	if(!anchors)
11178645Snsouch		return 0;
11278645Snsouch	lock_basic_lock(&anchors->lock);
11378645Snsouch	if(anchors->autr)
11439134Snsouch		res = anchors->autr->probe.count;
11539134Snsouch	lock_basic_unlock(&anchors->lock);
11639134Snsouch	return res;
11739134Snsouch}
11845342Speter
11939134Snsouch/** Position in string */
12045342Speterstatic int
12139134Snsouchposition_in_string(char *str, const char* sub)
12239134Snsouch{
12339134Snsouch	char* pos = strstr(str, sub);
12439134Snsouch	if(pos)
12539134Snsouch		return (int)(pos-str)+(int)strlen(sub);
12638061Smsmith	return -1;
12738061Smsmith}
12838061Smsmith
12938061Smsmith/** Debug routine to print pretty key information */
13038061Smsmithstatic void
13138061Smsmithverbose_key(struct autr_ta* ta, enum verbosity_value level,
13238061Smsmith	const char* format, ...) ATTR_FORMAT(printf, 3, 4);
13339134Snsouch
13439134Snsouch/**
13538061Smsmith * Implementation of debug pretty key print
13638061Smsmith * @param ta: trust anchor key with DNSKEY data.
13738061Smsmith * @param level: verbosity level to print at.
13838061Smsmith * @param format: printf style format string.
13938061Smsmith */
14038061Smsmithstatic void
14138061Smsmithverbose_key(struct autr_ta* ta, enum verbosity_value level,
14239134Snsouch	const char* format, ...)
14338061Smsmith{
14438061Smsmith	va_list args;
14538061Smsmith	va_start(args, format);
14638061Smsmith	if(verbosity >= level) {
14739134Snsouch		char* str = sldns_wire2str_dname(ta->rr, ta->dname_len);
14838061Smsmith		int keytag = (int)sldns_calc_keytag_raw(sldns_wirerr_get_rdata(
14938061Smsmith			ta->rr, ta->rr_len, ta->dname_len),
15038061Smsmith			sldns_wirerr_get_rdatalen(ta->rr, ta->rr_len,
15138061Smsmith			ta->dname_len));
15239134Snsouch		char msg[MAXSYSLOGMSGLEN];
15338061Smsmith		vsnprintf(msg, sizeof(msg), format, args);
15438061Smsmith		verbose(level, "%s key %d %s", str?str:"??", keytag, msg);
15538061Smsmith		free(str);
15638061Smsmith	}
15738061Smsmith	va_end(args);
15838061Smsmith}
15938061Smsmith
16038061Smsmith/**
16138061Smsmith * Parse comments
16238061Smsmith * @param str: to parse
16338061Smsmith * @param ta: trust key autotrust metadata
16438061Smsmith * @return false on failure.
16538061Smsmith */
16638061Smsmithstatic int
16738061Smsmithparse_comments(char* str, struct autr_ta* ta)
16838061Smsmith{
16938061Smsmith        int len = (int)strlen(str), pos = 0, timestamp = 0;
17038061Smsmith        char* comment = (char*) malloc(sizeof(char)*len+1);
17138061Smsmith        char* comments = comment;
17238061Smsmith	if(!comment) {
17378645Snsouch		log_err("malloc failure in parse");
17478645Snsouch                return 0;
17578645Snsouch	}
17678645Snsouch	/* skip over whitespace and data at start of line */
17738061Smsmith        while (*str != '\0' && *str != ';')
17838061Smsmith                str++;
17938061Smsmith        if (*str == ';')
18038061Smsmith                str++;
18138061Smsmith        /* copy comments */
18238061Smsmith        while (*str != '\0')
18338061Smsmith        {
18478645Snsouch                *comments = *str;
18578645Snsouch                comments++;
18678645Snsouch                str++;
18778645Snsouch        }
18878645Snsouch        *comments = '\0';
18978645Snsouch
19078645Snsouch        comments = comment;
19178645Snsouch
19278645Snsouch        /* read state */
19378645Snsouch        pos = position_in_string(comments, "state=");
19478645Snsouch        if (pos >= (int) strlen(comments))
19578645Snsouch        {
19678645Snsouch		log_err("parse error");
19778645Snsouch                free(comment);
19838061Smsmith                return 0;
19938061Smsmith        }
20038061Smsmith        if (pos <= 0)
20138061Smsmith                ta->s = AUTR_STATE_VALID;
20239134Snsouch        else
20338061Smsmith        {
20438061Smsmith                int s = (int) comments[pos] - '0';
20538061Smsmith                switch(s)
20638061Smsmith                {
20738061Smsmith                        case AUTR_STATE_START:
20838061Smsmith                        case AUTR_STATE_ADDPEND:
20943433Snsouch                        case AUTR_STATE_VALID:
21038061Smsmith                        case AUTR_STATE_MISSING:
21138061Smsmith                        case AUTR_STATE_REVOKED:
21238061Smsmith                        case AUTR_STATE_REMOVED:
21338061Smsmith                                ta->s = s;
21438061Smsmith                                break;
21538061Smsmith                        default:
21638061Smsmith				verbose_key(ta, VERB_OPS, "has undefined "
21738061Smsmith					"state, considered NewKey");
21839134Snsouch                                ta->s = AUTR_STATE_START;
21938061Smsmith                                break;
22038061Smsmith                }
221185003Sjhb        }
22238061Smsmith        /* read pending count */
22338061Smsmith        pos = position_in_string(comments, "count=");
22438061Smsmith        if (pos >= (int) strlen(comments))
22543433Snsouch        {
22638061Smsmith		log_err("parse error");
22738061Smsmith                free(comment);
22838061Smsmith                return 0;
22938061Smsmith        }
23038061Smsmith        if (pos <= 0)
23138061Smsmith                ta->pending_count = 0;
23239134Snsouch        else
23338061Smsmith        {
23438061Smsmith                comments += pos;
23538061Smsmith                ta->pending_count = (uint8_t)atoi(comments);
236185003Sjhb        }
23743433Snsouch
23843433Snsouch        /* read last change */
23938061Smsmith        pos = position_in_string(comments, "lastchange=");
24038061Smsmith        if (pos >= (int) strlen(comments))
24138061Smsmith        {
24238061Smsmith		log_err("parse error");
24338061Smsmith                free(comment);
24438061Smsmith                return 0;
24538061Smsmith        }
24638061Smsmith        if (pos >= 0)
24739134Snsouch        {
24838061Smsmith                comments += pos;
24938061Smsmith                timestamp = atoi(comments);
25038061Smsmith        }
251185003Sjhb        if (pos < 0 || !timestamp)
25243433Snsouch		ta->last_change = 0;
25343433Snsouch        else
25438061Smsmith                ta->last_change = (time_t)timestamp;
25538061Smsmith
25638061Smsmith        free(comment);
25738061Smsmith        return 1;
25838061Smsmith}
25938061Smsmith
26038061Smsmith/** Check if a line contains data (besides comments) */
26138061Smsmithstatic int
26239134Snsouchstr_contains_data(char* str, char comment)
26339134Snsouch{
26439134Snsouch        while (*str != '\0') {
26539134Snsouch                if (*str == comment || *str == '\n')
26643433Snsouch                        return 0;
26739134Snsouch                if (*str != ' ' && *str != '\t')
26843433Snsouch                        return 1;
26939134Snsouch                str++;
27039520Snsouch        }
27139134Snsouch        return 0;
27239520Snsouch}
27339134Snsouch
27439134Snsouch/** Get DNSKEY flags
27538061Smsmith * rdata without rdatalen in front of it. */
27638061Smsmithstatic int
27738061Smsmithdnskey_flags(uint16_t t, uint8_t* rdata, size_t len)
27855939Snsouch{
27938061Smsmith	uint16_t f;
28038061Smsmith	if(t != LDNS_RR_TYPE_DNSKEY)
28155939Snsouch		return 0;
28255939Snsouch	if(len < 2)
28338061Smsmith		return 0;
28438061Smsmith	memmove(&f, rdata, 2);
28538061Smsmith	f = ntohs(f);
28638061Smsmith	return (int)f;
28738061Smsmith}
28838061Smsmith
28938061Smsmith/** Check if KSK DNSKEY.
29038061Smsmith * pass rdata without rdatalen in front of it */
29155939Snsouchstatic int
29238061Smsmithrr_is_dnskey_sep(uint16_t t, uint8_t* rdata, size_t len)
29338061Smsmith{
29438061Smsmith	return (dnskey_flags(t, rdata, len)&DNSKEY_BIT_SEP);
29555939Snsouch}
29642475Snsouch
29742475Snsouch/** Check if TA is KSK DNSKEY */
29887599Sobrienstatic int
29942475Snsouchta_is_dnskey_sep(struct autr_ta* ta)
300185003Sjhb{
30142475Snsouch	return (dnskey_flags(
30238061Smsmith		sldns_wirerr_get_type(ta->rr, ta->rr_len, ta->dname_len),
30355939Snsouch		sldns_wirerr_get_rdata(ta->rr, ta->rr_len, ta->dname_len),
30455939Snsouch		sldns_wirerr_get_rdatalen(ta->rr, ta->rr_len, ta->dname_len)
30538061Smsmith		) & DNSKEY_BIT_SEP);
30655939Snsouch}
30738061Smsmith
30838061Smsmith/** Check if REVOKED DNSKEY
30938061Smsmith * pass rdata without rdatalen in front of it */
31038061Smsmithstatic int
31138061Smsmithrr_is_dnskey_revoked(uint16_t t, uint8_t* rdata, size_t len)
31239134Snsouch{
31338061Smsmith	return (dnskey_flags(t, rdata, len)&LDNS_KEY_REVOKE_KEY);
31439134Snsouch}
31538061Smsmith
31639134Snsouch/** create ta */
317185003Sjhbstatic struct autr_ta*
31838061Smsmithautr_ta_create(uint8_t* rr, size_t rr_len, size_t dname_len)
31955939Snsouch{
32039134Snsouch	struct autr_ta* ta = (struct autr_ta*)calloc(1, sizeof(*ta));
32138061Smsmith	if(!ta) {
32239134Snsouch		free(rr);
32338061Smsmith		return NULL;
32439134Snsouch	}
32538061Smsmith	ta->rr = rr;
32639134Snsouch	ta->rr_len = rr_len;
32739134Snsouch	ta->dname_len = dname_len;
32839134Snsouch	return ta;
32939134Snsouch}
33039134Snsouch
33139134Snsouch/** create tp */
33238061Smsmithstatic struct trust_anchor*
33339134Snsouchautr_tp_create(struct val_anchors* anchors, uint8_t* own, size_t own_len,
33455939Snsouch	uint16_t dc)
33539134Snsouch{
33639134Snsouch	struct trust_anchor* tp = (struct trust_anchor*)calloc(1, sizeof(*tp));
33738061Smsmith	if(!tp) return NULL;
33838061Smsmith	tp->name = memdup(own, own_len);
33938061Smsmith	if(!tp->name) {
34039134Snsouch		free(tp);
34138061Smsmith		return NULL;
34239134Snsouch	}
34339134Snsouch	tp->namelen = own_len;
34438061Smsmith	tp->namelabs = dname_count_labels(tp->name);
34555939Snsouch	tp->node.key = tp;
34639134Snsouch	tp->dclass = dc;
34738061Smsmith	tp->autr = (struct autr_point_data*)calloc(1, sizeof(*tp->autr));
34855939Snsouch	if(!tp->autr) {
34938061Smsmith		free(tp->name);
35039134Snsouch		free(tp);
35138061Smsmith		return NULL;
35238061Smsmith	}
35338061Smsmith	tp->autr->pnode.key = tp;
35438061Smsmith
35538061Smsmith	lock_basic_lock(&anchors->lock);
35638061Smsmith	if(!rbtree_insert(anchors->tree, &tp->node)) {
35738061Smsmith		lock_basic_unlock(&anchors->lock);
35839134Snsouch		log_err("trust anchor presented twice");
35938061Smsmith		free(tp->name);
36038061Smsmith		free(tp->autr);
36155939Snsouch		free(tp);
36239520Snsouch		return NULL;
36338061Smsmith	}
36439520Snsouch	if(!rbtree_insert(&anchors->autr->probe, &tp->autr->pnode)) {
36555939Snsouch		(void)rbtree_delete(anchors->tree, tp);
366185003Sjhb		lock_basic_unlock(&anchors->lock);
36739520Snsouch		log_err("trust anchor in probetree twice");
36878645Snsouch		free(tp->name);
36955939Snsouch		free(tp->autr);
37039520Snsouch		free(tp);
37170608Snsouch		return NULL;
37270608Snsouch	}
37370608Snsouch	lock_basic_unlock(&anchors->lock);
37470608Snsouch	lock_basic_init(&tp->lock);
37555939Snsouch	lock_protect(&tp->lock, tp, sizeof(*tp));
37670608Snsouch	lock_protect(&tp->lock, tp->autr, sizeof(*tp->autr));
37739520Snsouch	return tp;
37870608Snsouch}
37970608Snsouch
38070608Snsouch/** delete assembled rrsets */
38139520Snsouchstatic void
38270608Snsouchautr_rrset_delete(struct ub_packed_rrset_key* r)
38370608Snsouch{
38470608Snsouch	if(r) {
385298955Spfg		free(r->rk.dname);
38670608Snsouch		free(r->entry.data);
38739520Snsouch		free(r);
38870608Snsouch	}
38970608Snsouch}
39070608Snsouch
39170608Snsouchvoid autr_point_delete(struct trust_anchor* tp)
39270608Snsouch{
39370608Snsouch	if(!tp)
39470608Snsouch		return;
39570608Snsouch	lock_unprotect(&tp->lock, tp);
39670608Snsouch	lock_unprotect(&tp->lock, tp->autr);
39770608Snsouch	lock_basic_destroy(&tp->lock);
39855939Snsouch	autr_rrset_delete(tp->ds_rrset);
39970608Snsouch	autr_rrset_delete(tp->dnskey_rrset);
40070608Snsouch	if(tp->autr) {
40139520Snsouch		struct autr_ta* p = tp->autr->keys, *np;
402184130Sjhb		while(p) {
403184130Sjhb			np = p->next;
40439520Snsouch			free(p->rr);
40539520Snsouch			free(p);
40655939Snsouch			p = np;
40739520Snsouch		}
40839520Snsouch		free(tp->autr->file);
40939520Snsouch		free(tp->autr);
41070608Snsouch	}
41170608Snsouch	free(tp->name);
41238061Smsmith	free(tp);
41338061Smsmith}
41438061Smsmith
41538061Smsmith/** find or add a new trust point for autotrust */
41638061Smsmithstatic struct trust_anchor*
41755939Snsouchfind_add_tp(struct val_anchors* anchors, uint8_t* rr, size_t rr_len,
41838061Smsmith	size_t dname_len)
419185003Sjhb{
42039134Snsouch	struct trust_anchor* tp;
42170608Snsouch	tp = anchor_find(anchors, rr, dname_count_labels(rr), dname_len,
42239520Snsouch		sldns_wirerr_get_class(rr, rr_len, dname_len));
423184130Sjhb	if(tp) {
424184130Sjhb		if(!tp->autr) {
42539520Snsouch			log_err("anchor cannot be with and without autotrust");
42639520Snsouch			lock_basic_unlock(&tp->lock);
42738061Smsmith			return NULL;
42855939Snsouch		}
42938061Smsmith		return tp;
43039520Snsouch	}
43139520Snsouch	tp = autr_tp_create(anchors, rr, dname_len, sldns_wirerr_get_class(rr,
43255939Snsouch		rr_len, dname_len));
43339520Snsouch	lock_basic_lock(&tp->lock);
43438061Smsmith	return tp;
43538061Smsmith}
43638061Smsmith
43738061Smsmith/** Add trust anchor from RR */
43838061Smsmithstatic struct autr_ta*
43938061Smsmithadd_trustanchor_frm_rr(struct val_anchors* anchors, uint8_t* rr, size_t rr_len,
44038061Smsmith        size_t dname_len, struct trust_anchor** tp)
44138061Smsmith{
44255939Snsouch	struct autr_ta* ta = autr_ta_create(rr, rr_len, dname_len);
44338061Smsmith	if(!ta)
44438061Smsmith		return NULL;
44555939Snsouch	*tp = find_add_tp(anchors, rr, rr_len, dname_len);
44645342Speter	if(!*tp) {
44738061Smsmith		free(ta->rr);
44855939Snsouch		free(ta);
44938061Smsmith		return NULL;
45038061Smsmith	}
45138061Smsmith	/* add ta to tp */
45238061Smsmith	ta->next = (*tp)->autr->keys;
45338061Smsmith	(*tp)->autr->keys = ta;
45438061Smsmith	lock_basic_unlock(&(*tp)->lock);
45538061Smsmith	return ta;
45638061Smsmith}
45738061Smsmith
45838061Smsmith/**
45955939Snsouch * Add new trust anchor from a string in file.
46038061Smsmith * @param anchors: all anchors
46138061Smsmith * @param str: string with anchor and comments, if any comments.
46255939Snsouch * @param tp: trust point returned.
46345342Speter * @param origin: what to use for @
46438061Smsmith * @param origin_len: length of origin
46555939Snsouch * @param prev: previous rr name
46638061Smsmith * @param prev_len: length of prev
46738061Smsmith * @param skip: if true, the result is NULL, but not an error, skip it.
46838061Smsmith * @return new key in trust point.
46938061Smsmith */
47038061Smsmithstatic struct autr_ta*
47138061Smsmithadd_trustanchor_frm_str(struct val_anchors* anchors, char* str,
47238061Smsmith	struct trust_anchor** tp, uint8_t* origin, size_t origin_len,
47355939Snsouch	uint8_t** prev, size_t* prev_len, int* skip)
47438061Smsmith{
47538061Smsmith	uint8_t rr[LDNS_RR_BUF_SIZE];
47638061Smsmith	size_t rr_len = sizeof(rr), dname_len;
47738061Smsmith	uint8_t* drr;
47838061Smsmith	int lstatus;
47938061Smsmith        if (!str_contains_data(str, ';')) {
48038061Smsmith		*skip = 1;
48138061Smsmith                return NULL; /* empty line */
48238061Smsmith	}
48338061Smsmith	if(0 != (lstatus = sldns_str2wire_rr_buf(str, rr, &rr_len, &dname_len,
48438061Smsmith		0, origin, origin_len, *prev, *prev_len)))
48538061Smsmith	{
48638061Smsmith		log_err("ldns error while converting string to RR at%d: %s: %s",
48738061Smsmith			LDNS_WIREPARSE_OFFSET(lstatus),
48838061Smsmith			sldns_get_errorstr_parse(lstatus), str);
48938061Smsmith		return NULL;
49038061Smsmith	}
49138061Smsmith	free(*prev);
49243433Snsouch	*prev = memdup(rr, dname_len);
49343433Snsouch	*prev_len = dname_len;
49438061Smsmith	if(!*prev) {
49538061Smsmith		log_err("malloc failure in add_trustanchor");
49638061Smsmith		return NULL;
49738061Smsmith	}
49838061Smsmith	if(sldns_wirerr_get_type(rr, rr_len, dname_len)!=LDNS_RR_TYPE_DNSKEY &&
49938061Smsmith		sldns_wirerr_get_type(rr, rr_len, dname_len)!=LDNS_RR_TYPE_DS) {
50038061Smsmith		*skip = 1;
50138061Smsmith		return NULL; /* only DS and DNSKEY allowed */
502185003Sjhb	}
50355939Snsouch	drr = memdup(rr, rr_len);
50438061Smsmith	if(!drr) {
50538061Smsmith		log_err("malloc failure in add trustanchor");
50638061Smsmith		return NULL;
50738061Smsmith	}
50838061Smsmith	return add_trustanchor_frm_rr(anchors, drr, rr_len, dname_len, tp);
50938061Smsmith}
51038061Smsmith
51138061Smsmith/**
51238061Smsmith * Load single anchor
51338061Smsmith * @param anchors: all points.
51438061Smsmith * @param str: comments line
51538061Smsmith * @param fname: filename
51638061Smsmith * @param origin: the $ORIGIN.
51738061Smsmith * @param origin_len: length of origin
51838061Smsmith * @param prev: passed to ldns.
51938061Smsmith * @param prev_len: length of prev
52038061Smsmith * @param skip: if true, the result is NULL, but not an error, skip it.
52178645Snsouch * @return false on failure, otherwise the tp read.
52278645Snsouch */
52355939Snsouchstatic struct trust_anchor*
52478645Snsouchload_trustanchor(struct val_anchors* anchors, char* str, const char* fname,
52538061Smsmith	uint8_t* origin, size_t origin_len, uint8_t** prev, size_t* prev_len,
52638061Smsmith	int* skip)
52755939Snsouch{
52838061Smsmith	struct autr_ta* ta = NULL;
52938061Smsmith	struct trust_anchor* tp = NULL;
53055939Snsouch
53138061Smsmith	ta = add_trustanchor_frm_str(anchors, str, &tp, origin, origin_len,
53238061Smsmith		prev, prev_len, skip);
53338061Smsmith	if(!ta)
53438061Smsmith		return NULL;
53538061Smsmith	lock_basic_lock(&tp->lock);
53638061Smsmith	if(!parse_comments(str, ta)) {
53738061Smsmith		lock_basic_unlock(&tp->lock);
53838061Smsmith		return NULL;
53938061Smsmith	}
54038061Smsmith	if(!tp->autr->file) {
54178645Snsouch		tp->autr->file = strdup(fname);
54278645Snsouch		if(!tp->autr->file) {
54378645Snsouch			lock_basic_unlock(&tp->lock);
54478645Snsouch			log_err("malloc failure");
54578645Snsouch			return NULL;
54678645Snsouch		}
54778645Snsouch	}
548185003Sjhb	lock_basic_unlock(&tp->lock);
54978645Snsouch        return tp;
55078645Snsouch}
55138061Smsmith
55238061Smsmith/** iterator for DSes from keylist. return true if a next element exists */
55338061Smsmithstatic int
55438061Smsmithassemble_iterate_ds(struct autr_ta** list, uint8_t** rr, size_t* rr_len,
55538061Smsmith	size_t* dname_len)
55638061Smsmith{
55738061Smsmith	while(*list) {
55838061Smsmith		if(sldns_wirerr_get_type((*list)->rr, (*list)->rr_len,
55955939Snsouch			(*list)->dname_len) == LDNS_RR_TYPE_DS) {
56055939Snsouch			*rr = (*list)->rr;
56138061Smsmith			*rr_len = (*list)->rr_len;
56255939Snsouch			*dname_len = (*list)->dname_len;
56338061Smsmith			*list = (*list)->next;
56438061Smsmith			return 1;
56555939Snsouch		}
56638061Smsmith		*list = (*list)->next;
56739134Snsouch	}
56839134Snsouch	return 0;
56939134Snsouch}
57039134Snsouch
57139134Snsouch/** iterator for DNSKEYs from keylist. return true if a next element exists */
57238061Smsmithstatic int
57355939Snsouchassemble_iterate_dnskey(struct autr_ta** list, uint8_t** rr, size_t* rr_len,
57455939Snsouch	size_t* dname_len)
57538061Smsmith{
57638061Smsmith	while(*list) {
57755939Snsouch		if(sldns_wirerr_get_type((*list)->rr, (*list)->rr_len,
57838061Smsmith		   (*list)->dname_len) != LDNS_RR_TYPE_DS &&
57938061Smsmith			((*list)->s == AUTR_STATE_VALID ||
58038061Smsmith			 (*list)->s == AUTR_STATE_MISSING)) {
58138061Smsmith			*rr = (*list)->rr;
58238061Smsmith			*rr_len = (*list)->rr_len;
58338061Smsmith			*dname_len = (*list)->dname_len;
58438061Smsmith			*list = (*list)->next;
58538061Smsmith			return 1;
58638061Smsmith		}
58738061Smsmith		*list = (*list)->next;
58838061Smsmith	}
589185003Sjhb	return 0;
59055939Snsouch}
59170608Snsouch
59238061Smsmith/** see if iterator-list has any elements in it, or it is empty */
59338061Smsmithstatic int
59438061Smsmithassemble_iterate_hasfirst(int iter(struct autr_ta**, uint8_t**, size_t*,
59538061Smsmith	size_t*), struct autr_ta* list)
59638061Smsmith{
59755939Snsouch	uint8_t* rr = NULL;
59838061Smsmith	size_t rr_len = 0, dname_len = 0;
59938061Smsmith	return iter(&list, &rr, &rr_len, &dname_len);
60038061Smsmith}
60138061Smsmith
60238061Smsmith/** number of elements in iterator list */
60378645Snsouchstatic size_t
60478645Snsouchassemble_iterate_count(int iter(struct autr_ta**, uint8_t**, size_t*,
60578645Snsouch	size_t*), struct autr_ta* list)
60678645Snsouch{
607185003Sjhb	uint8_t* rr = NULL;
60838061Smsmith	size_t i = 0, rr_len = 0, dname_len = 0;
60938061Smsmith	while(iter(&list, &rr, &rr_len, &dname_len)) {
61038061Smsmith		i++;
61138061Smsmith	}
612187576Sjhb	return i;
61370608Snsouch}
61470608Snsouch
61538061Smsmith/**
61670608Snsouch * Create a ub_packed_rrset_key allocated on the heap.
61770608Snsouch * It therefore does not have the correct ID value, and cannot be used
61870608Snsouch * inside the cache.  It can be used in storage outside of the cache.
61970608Snsouch * Keys for the cache have to be obtained from alloc.h .
62070608Snsouch * @param iter: iterator over the elements in the list.  It filters elements.
621184130Sjhb * @param list: the list.
62270608Snsouch * @return key allocated or NULL on failure.
62370608Snsouch */
62455939Snsouchstatic struct ub_packed_rrset_key*
62555939Snsouchub_packed_rrset_heap_key(int iter(struct autr_ta**, uint8_t**, size_t*,
626184130Sjhb	size_t*), struct autr_ta* list)
62770608Snsouch{
62870608Snsouch	uint8_t* rr = NULL;
62970608Snsouch	size_t rr_len = 0, dname_len = 0;
63070608Snsouch	struct ub_packed_rrset_key* k;
631184130Sjhb	if(!iter(&list, &rr, &rr_len, &dname_len))
63270608Snsouch		return NULL;
63370608Snsouch	k = (struct ub_packed_rrset_key*)calloc(1, sizeof(*k));
63470608Snsouch	if(!k)
63538061Smsmith		return NULL;
63638061Smsmith	k->rk.type = htons(sldns_wirerr_get_type(rr, rr_len, dname_len));
63755939Snsouch	k->rk.rrset_class = htons(sldns_wirerr_get_class(rr, rr_len, dname_len));
63838061Smsmith	k->rk.dname_len = dname_len;
63970608Snsouch	k->rk.dname = memdup(rr, dname_len);
640187576Sjhb	if(!k->rk.dname) {
64170608Snsouch		free(k);
64238061Smsmith		return NULL;
64338061Smsmith	}
64438061Smsmith	return k;
64538061Smsmith}
64638061Smsmith
64738061Smsmith/**
64838061Smsmith * Create packed_rrset data on the heap.
64938061Smsmith * @param iter: iterator over the elements in the list.  It filters elements.
65038061Smsmith * @param list: the list.
65138061Smsmith * @return data allocated or NULL on failure.
65239520Snsouch */
65342475Snsouchstatic struct packed_rrset_data*
65442475Snsouchpacked_rrset_heap_data(int iter(struct autr_ta**, uint8_t**, size_t*,
65587599Sobrien	size_t*), struct autr_ta* list)
65642475Snsouch{
65738061Smsmith	uint8_t* rr = NULL;
65838061Smsmith	size_t rr_len = 0, dname_len = 0;
65938061Smsmith	struct packed_rrset_data* data;
66038061Smsmith	size_t count=0, rrsig_count=0, len=0, i, total;
66138061Smsmith	uint8_t* nextrdata;
66238061Smsmith	struct autr_ta* list_i;
66338061Smsmith	time_t ttl = 0;
66438061Smsmith
66538061Smsmith	list_i = list;
66638061Smsmith	while(iter(&list_i, &rr, &rr_len, &dname_len)) {
66738061Smsmith		if(sldns_wirerr_get_type(rr, rr_len, dname_len) ==
66838061Smsmith			LDNS_RR_TYPE_RRSIG)
66938061Smsmith			rrsig_count++;
67038061Smsmith		else	count++;
67138061Smsmith		/* sizeof the rdlength + rdatalen */
67238061Smsmith		len += 2 + sldns_wirerr_get_rdatalen(rr, rr_len, dname_len);
67338061Smsmith		ttl = (time_t)sldns_wirerr_get_ttl(rr, rr_len, dname_len);
67438061Smsmith	}
67538061Smsmith	if(count == 0 && rrsig_count == 0)
67638061Smsmith		return NULL;
677185003Sjhb
67838061Smsmith	/* allocate */
67938061Smsmith	total = count + rrsig_count;
68038061Smsmith	len += sizeof(*data) + total*(sizeof(size_t) + sizeof(time_t) +
68138061Smsmith		sizeof(uint8_t*));
68255939Snsouch	data = (struct packed_rrset_data*)calloc(1, len);
68338061Smsmith	if(!data)
68438061Smsmith		return NULL;
68538061Smsmith
68638061Smsmith	/* fill it */
68738061Smsmith	data->ttl = ttl;
68838061Smsmith	data->count = count;
68938061Smsmith	data->rrsig_count = rrsig_count;
69038061Smsmith	data->rr_len = (size_t*)((uint8_t*)data +
69138061Smsmith		sizeof(struct packed_rrset_data));
69238061Smsmith	data->rr_data = (uint8_t**)&(data->rr_len[total]);
69338061Smsmith	data->rr_ttl = (time_t*)&(data->rr_data[total]);
69438061Smsmith	nextrdata = (uint8_t*)&(data->rr_ttl[total]);
69538061Smsmith
69638061Smsmith	/* fill out len, ttl, fields */
69738061Smsmith	list_i = list;
69838061Smsmith	i = 0;
69939520Snsouch	while(iter(&list_i, &rr, &rr_len, &dname_len)) {
700185003Sjhb		data->rr_ttl[i] = (time_t)sldns_wirerr_get_ttl(rr, rr_len,
701185003Sjhb			dname_len);
70238061Smsmith		if(data->rr_ttl[i] < data->ttl)
70338061Smsmith			data->ttl = data->rr_ttl[i];
70438061Smsmith		data->rr_len[i] = 2 /* the rdlength */ +
70538061Smsmith			sldns_wirerr_get_rdatalen(rr, rr_len, dname_len);
70638061Smsmith		i++;
70738061Smsmith	}
70838061Smsmith
70938061Smsmith	/* fixup rest of ptrs */
71038061Smsmith	for(i=0; i<total; i++) {
71138061Smsmith		data->rr_data[i] = nextrdata;
71255939Snsouch		nextrdata += data->rr_len[i];
71338061Smsmith	}
71438061Smsmith
71538061Smsmith	/* copy data in there */
71638061Smsmith	list_i = list;
71738061Smsmith	i = 0;
71838061Smsmith	while(iter(&list_i, &rr, &rr_len, &dname_len)) {
71938061Smsmith		memmove(data->rr_data[i],
72038061Smsmith			sldns_wirerr_get_rdatawl(rr, rr_len, dname_len),
72138061Smsmith			data->rr_len[i]);
72238061Smsmith		i++;
72338061Smsmith	}
72438061Smsmith
725185003Sjhb	if(data->rrsig_count && data->count == 0) {
726185003Sjhb		data->count = data->rrsig_count; /* rrset type is RRSIG */
72738061Smsmith		data->rrsig_count = 0;
72838061Smsmith	}
72938061Smsmith	return data;
73038061Smsmith}
73138061Smsmith
73238061Smsmith/**
733185003Sjhb * Assemble the trust anchors into DS and DNSKEY packed rrsets.
734185003Sjhb * Uses only VALID and MISSING DNSKEYs.
73538061Smsmith * Read the sldns_rrs and builds packed rrsets
73638061Smsmith * @param tp: the trust point. Must be locked.
73738061Smsmith * @return false on malloc failure.
73838061Smsmith */
73938061Smsmithstatic int
74038061Smsmithautr_assemble(struct trust_anchor* tp)
74138061Smsmith{
74238061Smsmith	struct ub_packed_rrset_key* ubds=NULL, *ubdnskey=NULL;
74338061Smsmith
74438061Smsmith	/* make packed rrset keys - malloced with no ID number, they
74538061Smsmith	 * are not in the cache */
74639520Snsouch	/* make packed rrset data (if there is a key) */
74739520Snsouch	if(assemble_iterate_hasfirst(assemble_iterate_ds, tp->autr->keys)) {
74839520Snsouch		ubds = ub_packed_rrset_heap_key(
74955939Snsouch			assemble_iterate_ds, tp->autr->keys);
75039520Snsouch		if(!ubds)
75139520Snsouch			goto error_cleanup;
75239520Snsouch		ubds->entry.data = packed_rrset_heap_data(
75339520Snsouch			assemble_iterate_ds, tp->autr->keys);
75439520Snsouch		if(!ubds->entry.data)
75538061Smsmith			goto error_cleanup;
75638061Smsmith	}
75738061Smsmith
75838061Smsmith	/* make packed DNSKEY data */
75938061Smsmith	if(assemble_iterate_hasfirst(assemble_iterate_dnskey, tp->autr->keys)) {
76038061Smsmith		ubdnskey = ub_packed_rrset_heap_key(
76138061Smsmith			assemble_iterate_dnskey, tp->autr->keys);
76238061Smsmith		if(!ubdnskey)
76338061Smsmith			goto error_cleanup;
76438061Smsmith		ubdnskey->entry.data = packed_rrset_heap_data(
76538061Smsmith			assemble_iterate_dnskey, tp->autr->keys);
76638061Smsmith		if(!ubdnskey->entry.data) {
76738061Smsmith		error_cleanup:
76838061Smsmith			autr_rrset_delete(ubds);
76938061Smsmith			autr_rrset_delete(ubdnskey);
770185003Sjhb			return 0;
771185003Sjhb		}
77238061Smsmith	}
77338061Smsmith
77438061Smsmith	/* we have prepared the new keys so nothing can go wrong any more.
77538061Smsmith	 * And we are sure we cannot be left without trustanchor after
77638061Smsmith	 * any errors. Put in the new keys and remove old ones. */
777185003Sjhb
778185003Sjhb	/* free the old data */
77938061Smsmith	autr_rrset_delete(tp->ds_rrset);
78038061Smsmith	autr_rrset_delete(tp->dnskey_rrset);
78138061Smsmith
78238061Smsmith	/* assign the data to replace the old */
78338061Smsmith	tp->ds_rrset = ubds;
78438061Smsmith	tp->dnskey_rrset = ubdnskey;
78538061Smsmith	tp->numDS = assemble_iterate_count(assemble_iterate_ds,
78638061Smsmith		tp->autr->keys);
78738061Smsmith	tp->numDNSKEY = assemble_iterate_count(assemble_iterate_dnskey,
788		tp->autr->keys);
789	return 1;
790}
791
792/** parse integer */
793static unsigned int
794parse_int(char* line, int* ret)
795{
796	char *e;
797	unsigned int x = (unsigned int)strtol(line, &e, 10);
798	if(line == e) {
799		*ret = -1; /* parse error */
800		return 0;
801	}
802	*ret = 1; /* matched */
803	return x;
804}
805
806/** parse id sequence for anchor */
807static struct trust_anchor*
808parse_id(struct val_anchors* anchors, char* line)
809{
810	struct trust_anchor *tp;
811	int r;
812	uint16_t dclass;
813	uint8_t* dname;
814	size_t dname_len;
815	/* read the owner name */
816	char* next = strchr(line, ' ');
817	if(!next)
818		return NULL;
819	next[0] = 0;
820	dname = sldns_str2wire_dname(line, &dname_len);
821	if(!dname)
822		return NULL;
823
824	/* read the class */
825	dclass = parse_int(next+1, &r);
826	if(r == -1) {
827		free(dname);
828		return NULL;
829	}
830
831	/* find the trust point */
832	tp = autr_tp_create(anchors, dname, dname_len, dclass);
833	free(dname);
834	return tp;
835}
836
837/**
838 * Parse variable from trustanchor header
839 * @param line: to parse
840 * @param anchors: the anchor is added to this, if "id:" is seen.
841 * @param anchor: the anchor as result value or previously returned anchor
842 * 	value to read the variable lines into.
843 * @return: 0 no match, -1 failed syntax error, +1 success line read.
844 * 	+2 revoked trust anchor file.
845 */
846static int
847parse_var_line(char* line, struct val_anchors* anchors,
848	struct trust_anchor** anchor)
849{
850	struct trust_anchor* tp = *anchor;
851	int r = 0;
852	if(strncmp(line, ";;id: ", 6) == 0) {
853		*anchor = parse_id(anchors, line+6);
854		if(!*anchor) return -1;
855		else return 1;
856	} else if(strncmp(line, ";;REVOKED", 9) == 0) {
857		if(tp) {
858			log_err("REVOKED statement must be at start of file");
859			return -1;
860		}
861		return 2;
862	} else if(strncmp(line, ";;last_queried: ", 16) == 0) {
863		if(!tp) return -1;
864		lock_basic_lock(&tp->lock);
865		tp->autr->last_queried = (time_t)parse_int(line+16, &r);
866		lock_basic_unlock(&tp->lock);
867	} else if(strncmp(line, ";;last_success: ", 16) == 0) {
868		if(!tp) return -1;
869		lock_basic_lock(&tp->lock);
870		tp->autr->last_success = (time_t)parse_int(line+16, &r);
871		lock_basic_unlock(&tp->lock);
872	} else if(strncmp(line, ";;next_probe_time: ", 19) == 0) {
873		if(!tp) return -1;
874		lock_basic_lock(&anchors->lock);
875		lock_basic_lock(&tp->lock);
876		(void)rbtree_delete(&anchors->autr->probe, tp);
877		tp->autr->next_probe_time = (time_t)parse_int(line+19, &r);
878		(void)rbtree_insert(&anchors->autr->probe, &tp->autr->pnode);
879		lock_basic_unlock(&tp->lock);
880		lock_basic_unlock(&anchors->lock);
881	} else if(strncmp(line, ";;query_failed: ", 16) == 0) {
882		if(!tp) return -1;
883		lock_basic_lock(&tp->lock);
884		tp->autr->query_failed = (uint8_t)parse_int(line+16, &r);
885		lock_basic_unlock(&tp->lock);
886	} else if(strncmp(line, ";;query_interval: ", 18) == 0) {
887		if(!tp) return -1;
888		lock_basic_lock(&tp->lock);
889		tp->autr->query_interval = (time_t)parse_int(line+18, &r);
890		lock_basic_unlock(&tp->lock);
891	} else if(strncmp(line, ";;retry_time: ", 14) == 0) {
892		if(!tp) return -1;
893		lock_basic_lock(&tp->lock);
894		tp->autr->retry_time = (time_t)parse_int(line+14, &r);
895		lock_basic_unlock(&tp->lock);
896	}
897	return r;
898}
899
900/** handle origin lines */
901static int
902handle_origin(char* line, uint8_t** origin, size_t* origin_len)
903{
904	size_t len = 0;
905	while(isspace((unsigned char)*line))
906		line++;
907	if(strncmp(line, "$ORIGIN", 7) != 0)
908		return 0;
909	free(*origin);
910	line += 7;
911	while(isspace((unsigned char)*line))
912		line++;
913	*origin = sldns_str2wire_dname(line, &len);
914	*origin_len = len;
915	if(!*origin)
916		log_warn("malloc failure or parse error in $ORIGIN");
917	return 1;
918}
919
920/** Read one line and put multiline RRs onto one line string */
921static int
922read_multiline(char* buf, size_t len, FILE* in, int* linenr)
923{
924	char* pos = buf;
925	size_t left = len;
926	int depth = 0;
927	buf[len-1] = 0;
928	while(left > 0 && fgets(pos, (int)left, in) != NULL) {
929		size_t i, poslen = strlen(pos);
930		(*linenr)++;
931
932		/* check what the new depth is after the line */
933		/* this routine cannot handle braces inside quotes,
934		   say for TXT records, but this routine only has to read keys */
935		for(i=0; i<poslen; i++) {
936			if(pos[i] == '(') {
937				depth++;
938			} else if(pos[i] == ')') {
939				if(depth == 0) {
940					log_err("mismatch: too many ')'");
941					return -1;
942				}
943				depth--;
944			} else if(pos[i] == ';') {
945				break;
946			}
947		}
948
949		/* normal oneline or last line: keeps newline and comments */
950		if(depth == 0) {
951			return 1;
952		}
953
954		/* more lines expected, snip off comments and newline */
955		if(poslen>0)
956			pos[poslen-1] = 0; /* strip newline */
957		if(strchr(pos, ';'))
958			strchr(pos, ';')[0] = 0; /* strip comments */
959
960		/* move to paste other lines behind this one */
961		poslen = strlen(pos);
962		pos += poslen;
963		left -= poslen;
964		/* the newline is changed into a space */
965		if(left <= 2 /* space and eos */) {
966			log_err("line too long");
967			return -1;
968		}
969		pos[0] = ' ';
970		pos[1] = 0;
971		pos += 1;
972		left -= 1;
973	}
974	if(depth != 0) {
975		log_err("mismatch: too many '('");
976		return -1;
977	}
978	if(pos != buf)
979		return 1;
980	return 0;
981}
982
983int autr_read_file(struct val_anchors* anchors, const char* nm)
984{
985        /* the file descriptor */
986        FILE* fd;
987        /* keep track of line numbers */
988        int line_nr = 0;
989        /* single line */
990        char line[10240];
991	/* trust point being read */
992	struct trust_anchor *tp = NULL, *tp2;
993	int r;
994	/* for $ORIGIN parsing */
995	uint8_t *origin=NULL, *prev=NULL;
996	size_t origin_len=0, prev_len=0;
997
998        if (!(fd = fopen(nm, "r"))) {
999                log_err("unable to open %s for reading: %s",
1000			nm, strerror(errno));
1001                return 0;
1002        }
1003        verbose(VERB_ALGO, "reading autotrust anchor file %s", nm);
1004        while ( (r=read_multiline(line, sizeof(line), fd, &line_nr)) != 0) {
1005		if(r == -1 || (r = parse_var_line(line, anchors, &tp)) == -1) {
1006			log_err("could not parse auto-trust-anchor-file "
1007				"%s line %d", nm, line_nr);
1008			fclose(fd);
1009			free(origin);
1010			free(prev);
1011			return 0;
1012		} else if(r == 1) {
1013			continue;
1014		} else if(r == 2) {
1015			log_warn("trust anchor %s has been revoked", nm);
1016			fclose(fd);
1017			free(origin);
1018			free(prev);
1019			return 1;
1020		}
1021        	if (!str_contains_data(line, ';'))
1022                	continue; /* empty lines allowed */
1023 		if(handle_origin(line, &origin, &origin_len))
1024			continue;
1025		r = 0;
1026                if(!(tp2=load_trustanchor(anchors, line, nm, origin,
1027			origin_len, &prev, &prev_len, &r))) {
1028			if(!r) log_err("failed to load trust anchor from %s "
1029				"at line %i, skipping", nm, line_nr);
1030                        /* try to do the rest */
1031			continue;
1032                }
1033		if(tp && tp != tp2) {
1034			log_err("file %s has mismatching data inside: "
1035				"the file may only contain keys for one name, "
1036				"remove keys for other domain names", nm);
1037        		fclose(fd);
1038			free(origin);
1039			free(prev);
1040			return 0;
1041		}
1042		tp = tp2;
1043        }
1044        fclose(fd);
1045	free(origin);
1046	free(prev);
1047	if(!tp) {
1048		log_err("failed to read %s", nm);
1049		return 0;
1050	}
1051
1052	/* now assemble the data into DNSKEY and DS packed rrsets */
1053	lock_basic_lock(&tp->lock);
1054	if(!autr_assemble(tp)) {
1055		lock_basic_unlock(&tp->lock);
1056		log_err("malloc failure assembling %s", nm);
1057		return 0;
1058	}
1059	lock_basic_unlock(&tp->lock);
1060	return 1;
1061}
1062
1063/** string for a trustanchor state */
1064static const char*
1065trustanchor_state2str(autr_state_t s)
1066{
1067        switch (s) {
1068                case AUTR_STATE_START:       return "  START  ";
1069                case AUTR_STATE_ADDPEND:     return " ADDPEND ";
1070                case AUTR_STATE_VALID:       return "  VALID  ";
1071                case AUTR_STATE_MISSING:     return " MISSING ";
1072                case AUTR_STATE_REVOKED:     return " REVOKED ";
1073                case AUTR_STATE_REMOVED:     return " REMOVED ";
1074        }
1075        return " UNKNOWN ";
1076}
1077
1078/** print ID to file */
1079static int
1080print_id(FILE* out, char* fname, uint8_t* nm, size_t nmlen, uint16_t dclass)
1081{
1082	char* s = sldns_wire2str_dname(nm, nmlen);
1083	if(!s) {
1084		log_err("malloc failure in write to %s", fname);
1085		return 0;
1086	}
1087	if(fprintf(out, ";;id: %s %d\n", s, (int)dclass) < 0) {
1088		log_err("could not write to %s: %s", fname, strerror(errno));
1089		free(s);
1090		return 0;
1091	}
1092	free(s);
1093	return 1;
1094}
1095
1096static int
1097autr_write_contents(FILE* out, char* fn, struct trust_anchor* tp)
1098{
1099	char tmi[32];
1100	struct autr_ta* ta;
1101	char* str;
1102
1103	/* write pretty header */
1104	if(fprintf(out, "; autotrust trust anchor file\n") < 0) {
1105		log_err("could not write to %s: %s", fn, strerror(errno));
1106		return 0;
1107	}
1108	if(tp->autr->revoked) {
1109		if(fprintf(out, ";;REVOKED\n") < 0 ||
1110		   fprintf(out, "; The zone has all keys revoked, and is\n"
1111			"; considered as if it has no trust anchors.\n"
1112			"; the remainder of the file is the last probe.\n"
1113			"; to restart the trust anchor, overwrite this file.\n"
1114			"; with one containing valid DNSKEYs or DSes.\n") < 0) {
1115		   log_err("could not write to %s: %s", fn, strerror(errno));
1116		   return 0;
1117		}
1118	}
1119	if(!print_id(out, fn, tp->name, tp->namelen, tp->dclass)) {
1120		return 0;
1121	}
1122	if(fprintf(out, ";;last_queried: %u ;;%s",
1123		(unsigned int)tp->autr->last_queried,
1124		ctime_r(&(tp->autr->last_queried), tmi)) < 0 ||
1125	   fprintf(out, ";;last_success: %u ;;%s",
1126		(unsigned int)tp->autr->last_success,
1127		ctime_r(&(tp->autr->last_success), tmi)) < 0 ||
1128	   fprintf(out, ";;next_probe_time: %u ;;%s",
1129		(unsigned int)tp->autr->next_probe_time,
1130		ctime_r(&(tp->autr->next_probe_time), tmi)) < 0 ||
1131	   fprintf(out, ";;query_failed: %d\n", (int)tp->autr->query_failed)<0
1132	   || fprintf(out, ";;query_interval: %d\n",
1133	   (int)tp->autr->query_interval) < 0 ||
1134	   fprintf(out, ";;retry_time: %d\n", (int)tp->autr->retry_time) < 0) {
1135		log_err("could not write to %s: %s", fn, strerror(errno));
1136		return 0;
1137	}
1138
1139	/* write anchors */
1140	for(ta=tp->autr->keys; ta; ta=ta->next) {
1141		/* by default do not store START and REMOVED keys */
1142		if(ta->s == AUTR_STATE_START)
1143			continue;
1144		if(ta->s == AUTR_STATE_REMOVED)
1145			continue;
1146		/* only store keys */
1147		if(sldns_wirerr_get_type(ta->rr, ta->rr_len, ta->dname_len)
1148			!= LDNS_RR_TYPE_DNSKEY)
1149			continue;
1150		str = sldns_wire2str_rr(ta->rr, ta->rr_len);
1151		if(!str || !str[0]) {
1152			free(str);
1153			log_err("malloc failure writing %s", fn);
1154			return 0;
1155		}
1156		str[strlen(str)-1] = 0; /* remove newline */
1157		if(fprintf(out, "%s ;;state=%d [%s] ;;count=%d "
1158			";;lastchange=%u ;;%s", str, (int)ta->s,
1159			trustanchor_state2str(ta->s), (int)ta->pending_count,
1160			(unsigned int)ta->last_change,
1161			ctime_r(&(ta->last_change), tmi)) < 0) {
1162		   log_err("could not write to %s: %s", fn, strerror(errno));
1163		   free(str);
1164		   return 0;
1165		}
1166		free(str);
1167	}
1168	return 1;
1169}
1170
1171void autr_write_file(struct module_env* env, struct trust_anchor* tp)
1172{
1173	FILE* out;
1174	char* fname = tp->autr->file;
1175	char tempf[2048];
1176	log_assert(tp->autr);
1177	if(!env) {
1178		log_err("autr_write_file: Module environment is NULL.");
1179		return;
1180	}
1181	/* unique name with pid number and thread number */
1182	snprintf(tempf, sizeof(tempf), "%s.%d-%d", fname, (int)getpid(),
1183		env->worker?*(int*)env->worker:0);
1184	verbose(VERB_ALGO, "autotrust: write to disk: %s", tempf);
1185	out = fopen(tempf, "w");
1186	if(!out) {
1187		fatal_exit("could not open autotrust file for writing, %s: %s",
1188			tempf, strerror(errno));
1189		return;
1190	}
1191	if(!autr_write_contents(out, tempf, tp)) {
1192		/* failed to write contents (completely) */
1193		fclose(out);
1194		unlink(tempf);
1195		fatal_exit("could not completely write: %s", fname);
1196		return;
1197	}
1198	if(fclose(out) != 0) {
1199		fatal_exit("could not complete write: %s: %s",
1200			fname, strerror(errno));
1201		unlink(tempf);
1202		return;
1203	}
1204	/* success; overwrite actual file */
1205	verbose(VERB_ALGO, "autotrust: replaced %s", fname);
1206#ifdef UB_ON_WINDOWS
1207	(void)unlink(fname); /* windows does not replace file with rename() */
1208#endif
1209	if(rename(tempf, fname) < 0) {
1210		fatal_exit("rename(%s to %s): %s", tempf, fname, strerror(errno));
1211	}
1212}
1213
1214/**
1215 * Verify if dnskey works for trust point
1216 * @param env: environment (with time) for verification
1217 * @param ve: validator environment (with options) for verification.
1218 * @param tp: trust point to verify with
1219 * @param rrset: DNSKEY rrset to verify.
1220 * @return false on failure, true if verification successful.
1221 */
1222static int
1223verify_dnskey(struct module_env* env, struct val_env* ve,
1224        struct trust_anchor* tp, struct ub_packed_rrset_key* rrset)
1225{
1226	char* reason = NULL;
1227	uint8_t sigalg[ALGO_NEEDS_MAX+1];
1228	int downprot = env->cfg->harden_algo_downgrade;
1229	enum sec_status sec = val_verify_DNSKEY_with_TA(env, ve, rrset,
1230		tp->ds_rrset, tp->dnskey_rrset, downprot?sigalg:NULL, &reason);
1231	/* sigalg is ignored, it returns algorithms signalled to exist, but
1232	 * in 5011 there are no other rrsets to check.  if downprot is
1233	 * enabled, then it checks that the DNSKEY is signed with all
1234	 * algorithms available in the trust store. */
1235	verbose(VERB_ALGO, "autotrust: validate DNSKEY with anchor: %s",
1236		sec_status_to_string(sec));
1237	return sec == sec_status_secure;
1238}
1239
1240static int32_t
1241rrsig_get_expiry(uint8_t* d, size_t len)
1242{
1243	/* rrsig: 2(rdlen), 2(type) 1(alg) 1(v) 4(origttl), then 4(expi), (4)incep) */
1244	if(len < 2+8+4)
1245		return 0;
1246	return sldns_read_uint32(d+2+8);
1247}
1248
1249/** Find minimum expiration interval from signatures */
1250static time_t
1251min_expiry(struct module_env* env, struct packed_rrset_data* dd)
1252{
1253	size_t i;
1254	int32_t t, r = 15 * 24 * 3600; /* 15 days max */
1255	for(i=dd->count; i<dd->count+dd->rrsig_count; i++) {
1256		t = rrsig_get_expiry(dd->rr_data[i], dd->rr_len[i]);
1257		if((int32_t)t - (int32_t)*env->now > 0) {
1258			t -= (int32_t)*env->now;
1259			if(t < r)
1260				r = t;
1261		}
1262	}
1263	return (time_t)r;
1264}
1265
1266/** Is rr self-signed revoked key */
1267static int
1268rr_is_selfsigned_revoked(struct module_env* env, struct val_env* ve,
1269	struct ub_packed_rrset_key* dnskey_rrset, size_t i)
1270{
1271	enum sec_status sec;
1272	char* reason = NULL;
1273	verbose(VERB_ALGO, "seen REVOKE flag, check self-signed, rr %d",
1274		(int)i);
1275	/* no algorithm downgrade protection necessary, if it is selfsigned
1276	 * revoked it can be removed. */
1277	sec = dnskey_verify_rrset(env, ve, dnskey_rrset, dnskey_rrset, i,
1278		&reason);
1279	return (sec == sec_status_secure);
1280}
1281
1282/** Set fetched value */
1283static void
1284seen_trustanchor(struct autr_ta* ta, uint8_t seen)
1285{
1286	ta->fetched = seen;
1287	if(ta->pending_count < 250) /* no numerical overflow, please */
1288		ta->pending_count++;
1289}
1290
1291/** set revoked value */
1292static void
1293seen_revoked_trustanchor(struct autr_ta* ta, uint8_t revoked)
1294{
1295	ta->revoked = revoked;
1296}
1297
1298/** revoke a trust anchor */
1299static void
1300revoke_dnskey(struct autr_ta* ta, int off)
1301{
1302	uint16_t flags;
1303	uint8_t* data;
1304	if(sldns_wirerr_get_type(ta->rr, ta->rr_len, ta->dname_len) !=
1305		LDNS_RR_TYPE_DNSKEY)
1306		return;
1307	if(sldns_wirerr_get_rdatalen(ta->rr, ta->rr_len, ta->dname_len) < 2)
1308		return;
1309	data = sldns_wirerr_get_rdata(ta->rr, ta->rr_len, ta->dname_len);
1310	flags = sldns_read_uint16(data);
1311	if (off && (flags&LDNS_KEY_REVOKE_KEY))
1312		flags ^= LDNS_KEY_REVOKE_KEY; /* flip */
1313	else
1314		flags |= LDNS_KEY_REVOKE_KEY;
1315	sldns_write_uint16(data, flags);
1316}
1317
1318/** Compare two RRs skipping the REVOKED bit. Pass rdata(no len) */
1319static int
1320dnskey_compare_skip_revbit(uint8_t* a, size_t a_len, uint8_t* b, size_t b_len)
1321{
1322	size_t i;
1323	if(a_len != b_len)
1324		return -1;
1325	/* compare RRs RDATA byte for byte. */
1326	for(i = 0; i < a_len; i++)
1327	{
1328		uint8_t rdf1, rdf2;
1329		rdf1 = a[i];
1330		rdf2 = b[i];
1331		if(i==1) {
1332			/* this is the second part of the flags field */
1333			rdf1 |= LDNS_KEY_REVOKE_KEY;
1334			rdf2 |= LDNS_KEY_REVOKE_KEY;
1335		}
1336		if (rdf1 < rdf2)	return -1;
1337		else if (rdf1 > rdf2)	return 1;
1338        }
1339	return 0;
1340}
1341
1342
1343/** compare trust anchor with rdata, 0 if equal. Pass rdata(no len) */
1344static int
1345ta_compare(struct autr_ta* a, uint16_t t, uint8_t* b, size_t b_len)
1346{
1347	if(!a) return -1;
1348	else if(!b) return -1;
1349	else if(sldns_wirerr_get_type(a->rr, a->rr_len, a->dname_len) != t)
1350		return (int)sldns_wirerr_get_type(a->rr, a->rr_len,
1351			a->dname_len) - (int)t;
1352	else if(t == LDNS_RR_TYPE_DNSKEY) {
1353		return dnskey_compare_skip_revbit(
1354			sldns_wirerr_get_rdata(a->rr, a->rr_len, a->dname_len),
1355			sldns_wirerr_get_rdatalen(a->rr, a->rr_len,
1356			a->dname_len), b, b_len);
1357	}
1358	else if(t == LDNS_RR_TYPE_DS) {
1359		if(sldns_wirerr_get_rdatalen(a->rr, a->rr_len, a->dname_len) !=
1360			b_len)
1361			return -1;
1362		return memcmp(sldns_wirerr_get_rdata(a->rr,
1363			a->rr_len, a->dname_len), b, b_len);
1364	}
1365	return -1;
1366}
1367
1368/**
1369 * Find key
1370 * @param tp: to search in
1371 * @param t: rr type of the rdata.
1372 * @param rdata: to look for  (no rdatalen in it)
1373 * @param rdata_len: length of rdata
1374 * @param result: returns NULL or the ta key looked for.
1375 * @return false on malloc failure during search. if true examine result.
1376 */
1377static int
1378find_key(struct trust_anchor* tp, uint16_t t, uint8_t* rdata, size_t rdata_len,
1379	struct autr_ta** result)
1380{
1381	struct autr_ta* ta;
1382	if(!tp || !rdata) {
1383		*result = NULL;
1384		return 0;
1385	}
1386	for(ta=tp->autr->keys; ta; ta=ta->next) {
1387		if(ta_compare(ta, t, rdata, rdata_len) == 0) {
1388			*result = ta;
1389			return 1;
1390		}
1391	}
1392	*result = NULL;
1393	return 1;
1394}
1395
1396/** add key and clone RR and tp already locked. rdata without rdlen. */
1397static struct autr_ta*
1398add_key(struct trust_anchor* tp, uint32_t ttl, uint8_t* rdata, size_t rdata_len)
1399{
1400	struct autr_ta* ta;
1401	uint8_t* rr;
1402	size_t rr_len, dname_len;
1403	uint16_t rrtype = htons(LDNS_RR_TYPE_DNSKEY);
1404	uint16_t rrclass = htons(LDNS_RR_CLASS_IN);
1405	uint16_t rdlen = htons(rdata_len);
1406	dname_len = tp->namelen;
1407	ttl = htonl(ttl);
1408	rr_len = dname_len + 10 /* type,class,ttl,rdatalen */ + rdata_len;
1409	rr = (uint8_t*)malloc(rr_len);
1410	if(!rr) return NULL;
1411	memmove(rr, tp->name, tp->namelen);
1412	memmove(rr+dname_len, &rrtype, 2);
1413	memmove(rr+dname_len+2, &rrclass, 2);
1414	memmove(rr+dname_len+4, &ttl, 4);
1415	memmove(rr+dname_len+8, &rdlen, 2);
1416	memmove(rr+dname_len+10, rdata, rdata_len);
1417	ta = autr_ta_create(rr, rr_len, dname_len);
1418	if(!ta) {
1419		/* rr freed in autr_ta_create */
1420		return NULL;
1421	}
1422	/* link in, tp already locked */
1423	ta->next = tp->autr->keys;
1424	tp->autr->keys = ta;
1425	return ta;
1426}
1427
1428/** get TTL from DNSKEY rrset */
1429static time_t
1430key_ttl(struct ub_packed_rrset_key* k)
1431{
1432	struct packed_rrset_data* d = (struct packed_rrset_data*)k->entry.data;
1433	return d->ttl;
1434}
1435
1436/** update the time values for the trustpoint */
1437static void
1438set_tp_times(struct trust_anchor* tp, time_t rrsig_exp_interval,
1439	time_t origttl, int* changed)
1440{
1441	time_t x, qi = tp->autr->query_interval, rt = tp->autr->retry_time;
1442
1443	/* x = MIN(15days, ttl/2, expire/2) */
1444	x = 15 * 24 * 3600;
1445	if(origttl/2 < x)
1446		x = origttl/2;
1447	if(rrsig_exp_interval/2 < x)
1448		x = rrsig_exp_interval/2;
1449	/* MAX(1hr, x) */
1450	if(!autr_permit_small_holddown) {
1451		if(x < 3600)
1452			tp->autr->query_interval = 3600;
1453		else	tp->autr->query_interval = x;
1454	}	else    tp->autr->query_interval = x;
1455
1456	/* x= MIN(1day, ttl/10, expire/10) */
1457	x = 24 * 3600;
1458	if(origttl/10 < x)
1459		x = origttl/10;
1460	if(rrsig_exp_interval/10 < x)
1461		x = rrsig_exp_interval/10;
1462	/* MAX(1hr, x) */
1463	if(!autr_permit_small_holddown) {
1464		if(x < 3600)
1465			tp->autr->retry_time = 3600;
1466		else	tp->autr->retry_time = x;
1467	}	else    tp->autr->retry_time = x;
1468
1469	if(qi != tp->autr->query_interval || rt != tp->autr->retry_time) {
1470		*changed = 1;
1471		verbose(VERB_ALGO, "orig_ttl is %d", (int)origttl);
1472		verbose(VERB_ALGO, "rrsig_exp_interval is %d",
1473			(int)rrsig_exp_interval);
1474		verbose(VERB_ALGO, "query_interval: %d, retry_time: %d",
1475			(int)tp->autr->query_interval,
1476			(int)tp->autr->retry_time);
1477	}
1478}
1479
1480/** init events to zero */
1481static void
1482init_events(struct trust_anchor* tp)
1483{
1484	struct autr_ta* ta;
1485	for(ta=tp->autr->keys; ta; ta=ta->next) {
1486		ta->fetched = 0;
1487	}
1488}
1489
1490/** check for revoked keys without trusting any other information */
1491static void
1492check_contains_revoked(struct module_env* env, struct val_env* ve,
1493	struct trust_anchor* tp, struct ub_packed_rrset_key* dnskey_rrset,
1494	int* changed)
1495{
1496	struct packed_rrset_data* dd = (struct packed_rrset_data*)
1497		dnskey_rrset->entry.data;
1498	size_t i;
1499	log_assert(ntohs(dnskey_rrset->rk.type) == LDNS_RR_TYPE_DNSKEY);
1500	for(i=0; i<dd->count; i++) {
1501		struct autr_ta* ta = NULL;
1502		if(!rr_is_dnskey_sep(ntohs(dnskey_rrset->rk.type),
1503			dd->rr_data[i]+2, dd->rr_len[i]-2) ||
1504			!rr_is_dnskey_revoked(ntohs(dnskey_rrset->rk.type),
1505			dd->rr_data[i]+2, dd->rr_len[i]-2))
1506			continue; /* not a revoked KSK */
1507		if(!find_key(tp, ntohs(dnskey_rrset->rk.type),
1508			dd->rr_data[i]+2, dd->rr_len[i]-2, &ta)) {
1509			log_err("malloc failure");
1510			continue; /* malloc fail in compare*/
1511		}
1512		if(!ta)
1513			continue; /* key not found */
1514		if(rr_is_selfsigned_revoked(env, ve, dnskey_rrset, i)) {
1515			/* checked if there is an rrsig signed by this key. */
1516			/* same keytag, but stored can be revoked already, so
1517			 * compare keytags, with +0 or +128(REVOKE flag) */
1518			log_assert(dnskey_calc_keytag(dnskey_rrset, i)-128 ==
1519				sldns_calc_keytag_raw(sldns_wirerr_get_rdata(
1520				ta->rr, ta->rr_len, ta->dname_len),
1521				sldns_wirerr_get_rdatalen(ta->rr, ta->rr_len,
1522				ta->dname_len)) ||
1523				dnskey_calc_keytag(dnskey_rrset, i) ==
1524				sldns_calc_keytag_raw(sldns_wirerr_get_rdata(
1525				ta->rr, ta->rr_len, ta->dname_len),
1526				sldns_wirerr_get_rdatalen(ta->rr, ta->rr_len,
1527				ta->dname_len))); /* checks conversion*/
1528			verbose_key(ta, VERB_ALGO, "is self-signed revoked");
1529			if(!ta->revoked)
1530				*changed = 1;
1531			seen_revoked_trustanchor(ta, 1);
1532			do_revoked(env, ta, changed);
1533		}
1534	}
1535}
1536
1537/** See if a DNSKEY is verified by one of the DSes */
1538static int
1539key_matches_a_ds(struct module_env* env, struct val_env* ve,
1540	struct ub_packed_rrset_key* dnskey_rrset, size_t key_idx,
1541	struct ub_packed_rrset_key* ds_rrset)
1542{
1543	struct packed_rrset_data* dd = (struct packed_rrset_data*)
1544	                ds_rrset->entry.data;
1545	size_t ds_idx, num = dd->count;
1546	int d = val_favorite_ds_algo(ds_rrset);
1547	char* reason = "";
1548	for(ds_idx=0; ds_idx<num; ds_idx++) {
1549		if(!ds_digest_algo_is_supported(ds_rrset, ds_idx) ||
1550			!ds_key_algo_is_supported(ds_rrset, ds_idx) ||
1551			ds_get_digest_algo(ds_rrset, ds_idx) != d)
1552			continue;
1553		if(ds_get_key_algo(ds_rrset, ds_idx)
1554		   != dnskey_get_algo(dnskey_rrset, key_idx)
1555		   || dnskey_calc_keytag(dnskey_rrset, key_idx)
1556		   != ds_get_keytag(ds_rrset, ds_idx)) {
1557			continue;
1558		}
1559		if(!ds_digest_match_dnskey(env, dnskey_rrset, key_idx,
1560			ds_rrset, ds_idx)) {
1561			verbose(VERB_ALGO, "DS match attempt failed");
1562			continue;
1563		}
1564		if(dnskey_verify_rrset(env, ve, dnskey_rrset,
1565			dnskey_rrset, key_idx, &reason) == sec_status_secure) {
1566			return 1;
1567		} else {
1568			verbose(VERB_ALGO, "DS match failed because the key "
1569				"does not verify the keyset: %s", reason);
1570		}
1571	}
1572	return 0;
1573}
1574
1575/** Set update events */
1576static int
1577update_events(struct module_env* env, struct val_env* ve,
1578	struct trust_anchor* tp, struct ub_packed_rrset_key* dnskey_rrset,
1579	int* changed)
1580{
1581	struct packed_rrset_data* dd = (struct packed_rrset_data*)
1582		dnskey_rrset->entry.data;
1583	size_t i;
1584	log_assert(ntohs(dnskey_rrset->rk.type) == LDNS_RR_TYPE_DNSKEY);
1585	init_events(tp);
1586	for(i=0; i<dd->count; i++) {
1587		struct autr_ta* ta = NULL;
1588		if(!rr_is_dnskey_sep(ntohs(dnskey_rrset->rk.type),
1589			dd->rr_data[i]+2, dd->rr_len[i]-2))
1590			continue;
1591		if(rr_is_dnskey_revoked(ntohs(dnskey_rrset->rk.type),
1592			dd->rr_data[i]+2, dd->rr_len[i]-2)) {
1593			/* self-signed revoked keys already detected before,
1594			 * other revoked keys are not 'added' again */
1595			continue;
1596		}
1597		/* is a key of this type supported?. Note rr_list and
1598		 * packed_rrset are in the same order. */
1599		if(!dnskey_algo_is_supported(dnskey_rrset, i)) {
1600			/* skip unknown algorithm key, it is useless to us */
1601			log_nametypeclass(VERB_DETAIL, "trust point has "
1602				"unsupported algorithm at",
1603				tp->name, LDNS_RR_TYPE_DNSKEY, tp->dclass);
1604			continue;
1605		}
1606
1607		/* is it new? if revocation bit set, find the unrevoked key */
1608		if(!find_key(tp, ntohs(dnskey_rrset->rk.type),
1609			dd->rr_data[i]+2, dd->rr_len[i]-2, &ta)) {
1610			return 0;
1611		}
1612		if(!ta) {
1613			ta = add_key(tp, (uint32_t)dd->rr_ttl[i],
1614				dd->rr_data[i]+2, dd->rr_len[i]-2);
1615			*changed = 1;
1616			/* first time seen, do we have DSes? if match: VALID */
1617			if(ta && tp->ds_rrset && key_matches_a_ds(env, ve,
1618				dnskey_rrset, i, tp->ds_rrset)) {
1619				verbose_key(ta, VERB_ALGO, "verified by DS");
1620				ta->s = AUTR_STATE_VALID;
1621			}
1622		}
1623		if(!ta) {
1624			return 0;
1625		}
1626		seen_trustanchor(ta, 1);
1627		verbose_key(ta, VERB_ALGO, "in DNS response");
1628	}
1629	set_tp_times(tp, min_expiry(env, dd), key_ttl(dnskey_rrset), changed);
1630	return 1;
1631}
1632
1633/**
1634 * Check if the holddown time has already exceeded
1635 * setting: add-holddown: add holddown timer
1636 * setting: del-holddown: del holddown timer
1637 * @param env: environment with current time
1638 * @param ta: trust anchor to check for.
1639 * @param holddown: the timer value
1640 * @return number of seconds the holddown has passed.
1641 */
1642static time_t
1643check_holddown(struct module_env* env, struct autr_ta* ta,
1644	unsigned int holddown)
1645{
1646        time_t elapsed;
1647	if(*env->now < ta->last_change) {
1648		log_warn("time goes backwards. delaying key holddown");
1649		return 0;
1650	}
1651	elapsed = *env->now - ta->last_change;
1652        if (elapsed > (time_t)holddown) {
1653                return elapsed-(time_t)holddown;
1654        }
1655	verbose_key(ta, VERB_ALGO, "holddown time " ARG_LL "d seconds to go",
1656		(long long) ((time_t)holddown-elapsed));
1657        return 0;
1658}
1659
1660
1661/** Set last_change to now */
1662static void
1663reset_holddown(struct module_env* env, struct autr_ta* ta, int* changed)
1664{
1665	ta->last_change = *env->now;
1666	*changed = 1;
1667}
1668
1669/** Set the state for this trust anchor */
1670static void
1671set_trustanchor_state(struct module_env* env, struct autr_ta* ta, int* changed,
1672	autr_state_t s)
1673{
1674	verbose_key(ta, VERB_ALGO, "update: %s to %s",
1675		trustanchor_state2str(ta->s), trustanchor_state2str(s));
1676	ta->s = s;
1677	reset_holddown(env, ta, changed);
1678}
1679
1680
1681/** Event: NewKey */
1682static void
1683do_newkey(struct module_env* env, struct autr_ta* anchor, int* c)
1684{
1685	if (anchor->s == AUTR_STATE_START)
1686		set_trustanchor_state(env, anchor, c, AUTR_STATE_ADDPEND);
1687}
1688
1689/** Event: AddTime */
1690static void
1691do_addtime(struct module_env* env, struct autr_ta* anchor, int* c)
1692{
1693	/* This not according to RFC, this is 30 days, but the RFC demands
1694	 * MAX(30days, TTL expire time of first DNSKEY set with this key),
1695	 * The value may be too small if a very large TTL was used. */
1696	time_t exceeded = check_holddown(env, anchor, env->cfg->add_holddown);
1697	if (exceeded && anchor->s == AUTR_STATE_ADDPEND) {
1698		verbose_key(anchor, VERB_ALGO, "add-holddown time exceeded "
1699			ARG_LL "d seconds ago, and pending-count %d",
1700			(long long)exceeded, anchor->pending_count);
1701		if(anchor->pending_count >= MIN_PENDINGCOUNT) {
1702			set_trustanchor_state(env, anchor, c, AUTR_STATE_VALID);
1703			anchor->pending_count = 0;
1704			return;
1705		}
1706		verbose_key(anchor, VERB_ALGO, "add-holddown time sanity check "
1707			"failed (pending count: %d)", anchor->pending_count);
1708	}
1709}
1710
1711/** Event: RemTime */
1712static void
1713do_remtime(struct module_env* env, struct autr_ta* anchor, int* c)
1714{
1715	time_t exceeded = check_holddown(env, anchor, env->cfg->del_holddown);
1716	if(exceeded && anchor->s == AUTR_STATE_REVOKED) {
1717		verbose_key(anchor, VERB_ALGO, "del-holddown time exceeded "
1718			ARG_LL "d seconds ago", (long long)exceeded);
1719		set_trustanchor_state(env, anchor, c, AUTR_STATE_REMOVED);
1720	}
1721}
1722
1723/** Event: KeyRem */
1724static void
1725do_keyrem(struct module_env* env, struct autr_ta* anchor, int* c)
1726{
1727	if(anchor->s == AUTR_STATE_ADDPEND) {
1728		set_trustanchor_state(env, anchor, c, AUTR_STATE_START);
1729		anchor->pending_count = 0;
1730	} else if(anchor->s == AUTR_STATE_VALID)
1731		set_trustanchor_state(env, anchor, c, AUTR_STATE_MISSING);
1732}
1733
1734/** Event: KeyPres */
1735static void
1736do_keypres(struct module_env* env, struct autr_ta* anchor, int* c)
1737{
1738	if(anchor->s == AUTR_STATE_MISSING)
1739		set_trustanchor_state(env, anchor, c, AUTR_STATE_VALID);
1740}
1741
1742/* Event: Revoked */
1743static void
1744do_revoked(struct module_env* env, struct autr_ta* anchor, int* c)
1745{
1746	if(anchor->s == AUTR_STATE_VALID || anchor->s == AUTR_STATE_MISSING) {
1747                set_trustanchor_state(env, anchor, c, AUTR_STATE_REVOKED);
1748		verbose_key(anchor, VERB_ALGO, "old id, prior to revocation");
1749                revoke_dnskey(anchor, 0);
1750		verbose_key(anchor, VERB_ALGO, "new id, after revocation");
1751	}
1752}
1753
1754/** Do statestable transition matrix for anchor */
1755static void
1756anchor_state_update(struct module_env* env, struct autr_ta* anchor, int* c)
1757{
1758	log_assert(anchor);
1759	switch(anchor->s) {
1760	/* START */
1761	case AUTR_STATE_START:
1762		/* NewKey: ADDPEND */
1763		if (anchor->fetched)
1764			do_newkey(env, anchor, c);
1765		break;
1766	/* ADDPEND */
1767	case AUTR_STATE_ADDPEND:
1768		/* KeyRem: START */
1769		if (!anchor->fetched)
1770			do_keyrem(env, anchor, c);
1771		/* AddTime: VALID */
1772		else	do_addtime(env, anchor, c);
1773		break;
1774	/* VALID */
1775	case AUTR_STATE_VALID:
1776		/* RevBit: REVOKED */
1777		if (anchor->revoked)
1778			do_revoked(env, anchor, c);
1779		/* KeyRem: MISSING */
1780		else if (!anchor->fetched)
1781			do_keyrem(env, anchor, c);
1782		else if(!anchor->last_change) {
1783			verbose_key(anchor, VERB_ALGO, "first seen");
1784			reset_holddown(env, anchor, c);
1785		}
1786		break;
1787	/* MISSING */
1788	case AUTR_STATE_MISSING:
1789		/* RevBit: REVOKED */
1790		if (anchor->revoked)
1791			do_revoked(env, anchor, c);
1792		/* KeyPres */
1793		else if (anchor->fetched)
1794			do_keypres(env, anchor, c);
1795		break;
1796	/* REVOKED */
1797	case AUTR_STATE_REVOKED:
1798		if (anchor->fetched)
1799			reset_holddown(env, anchor, c);
1800		/* RemTime: REMOVED */
1801		else	do_remtime(env, anchor, c);
1802		break;
1803	/* REMOVED */
1804	case AUTR_STATE_REMOVED:
1805	default:
1806		break;
1807	}
1808}
1809
1810/** if ZSK init then trust KSKs */
1811static int
1812init_zsk_to_ksk(struct module_env* env, struct trust_anchor* tp, int* changed)
1813{
1814	/* search for VALID ZSKs */
1815	struct autr_ta* anchor;
1816	int validzsk = 0;
1817	int validksk = 0;
1818	for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
1819		/* last_change test makes sure it was manually configured */
1820		if(sldns_wirerr_get_type(anchor->rr, anchor->rr_len,
1821			anchor->dname_len) == LDNS_RR_TYPE_DNSKEY &&
1822			anchor->last_change == 0 &&
1823			!ta_is_dnskey_sep(anchor) &&
1824			anchor->s == AUTR_STATE_VALID)
1825                        validzsk++;
1826	}
1827	if(validzsk == 0)
1828		return 0;
1829	for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
1830                if (ta_is_dnskey_sep(anchor) &&
1831			anchor->s == AUTR_STATE_ADDPEND) {
1832			verbose_key(anchor, VERB_ALGO, "trust KSK from "
1833				"ZSK(config)");
1834			set_trustanchor_state(env, anchor, changed,
1835				AUTR_STATE_VALID);
1836			validksk++;
1837		}
1838	}
1839	return validksk;
1840}
1841
1842/** Remove missing trustanchors so the list does not grow forever */
1843static void
1844remove_missing_trustanchors(struct module_env* env, struct trust_anchor* tp,
1845	int* changed)
1846{
1847	struct autr_ta* anchor;
1848	time_t exceeded;
1849	int valid = 0;
1850	/* see if we have anchors that are valid */
1851	for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
1852		/* Only do KSKs */
1853                if (!ta_is_dnskey_sep(anchor))
1854                        continue;
1855                if (anchor->s == AUTR_STATE_VALID)
1856                        valid++;
1857	}
1858	/* if there are no SEP Valid anchors, see if we started out with
1859	 * a ZSK (last-change=0) anchor, which is VALID and there are KSKs
1860	 * now that can be made valid.  Do this immediately because there
1861	 * is no guarantee that the ZSKs get announced long enough.  Usually
1862	 * this is immediately after init with a ZSK trusted, unless the domain
1863	 * was not advertising any KSKs at all.  In which case we perfectly
1864	 * track the zero number of KSKs. */
1865	if(valid == 0) {
1866		valid = init_zsk_to_ksk(env, tp, changed);
1867		if(valid == 0)
1868			return;
1869	}
1870
1871	for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
1872		/* ignore ZSKs if newly added */
1873		if(anchor->s == AUTR_STATE_START)
1874			continue;
1875		/* remove ZSKs if a KSK is present */
1876                if (!ta_is_dnskey_sep(anchor)) {
1877			if(valid > 0) {
1878				verbose_key(anchor, VERB_ALGO, "remove ZSK "
1879					"[%d key(s) VALID]", valid);
1880				set_trustanchor_state(env, anchor, changed,
1881					AUTR_STATE_REMOVED);
1882			}
1883                        continue;
1884		}
1885                /* Only do MISSING keys */
1886                if (anchor->s != AUTR_STATE_MISSING)
1887                        continue;
1888		if(env->cfg->keep_missing == 0)
1889			continue; /* keep forever */
1890
1891		exceeded = check_holddown(env, anchor, env->cfg->keep_missing);
1892		/* If keep_missing has exceeded and we still have more than
1893		 * one valid KSK: remove missing trust anchor */
1894                if (exceeded && valid > 0) {
1895			verbose_key(anchor, VERB_ALGO, "keep-missing time "
1896				"exceeded " ARG_LL "d seconds ago, [%d key(s) VALID]",
1897				(long long)exceeded, valid);
1898			set_trustanchor_state(env, anchor, changed,
1899				AUTR_STATE_REMOVED);
1900		}
1901	}
1902}
1903
1904/** Do the statetable from RFC5011 transition matrix */
1905static int
1906do_statetable(struct module_env* env, struct trust_anchor* tp, int* changed)
1907{
1908	struct autr_ta* anchor;
1909	for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
1910		/* Only do KSKs */
1911		if(!ta_is_dnskey_sep(anchor))
1912			continue;
1913		anchor_state_update(env, anchor, changed);
1914	}
1915	remove_missing_trustanchors(env, tp, changed);
1916	return 1;
1917}
1918
1919/** See if time alone makes ADDPEND to VALID transition */
1920static void
1921autr_holddown_exceed(struct module_env* env, struct trust_anchor* tp, int* c)
1922{
1923	struct autr_ta* anchor;
1924	for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
1925		if(ta_is_dnskey_sep(anchor) &&
1926			anchor->s == AUTR_STATE_ADDPEND)
1927			do_addtime(env, anchor, c);
1928	}
1929}
1930
1931/** cleanup key list */
1932static void
1933autr_cleanup_keys(struct trust_anchor* tp)
1934{
1935	struct autr_ta* p, **prevp;
1936	prevp = &tp->autr->keys;
1937	p = tp->autr->keys;
1938	while(p) {
1939		/* do we want to remove this key? */
1940		if(p->s == AUTR_STATE_START || p->s == AUTR_STATE_REMOVED ||
1941			sldns_wirerr_get_type(p->rr, p->rr_len, p->dname_len)
1942			!= LDNS_RR_TYPE_DNSKEY) {
1943			struct autr_ta* np = p->next;
1944			/* remove */
1945			free(p->rr);
1946			free(p);
1947			/* snip and go to next item */
1948			*prevp = np;
1949			p = np;
1950			continue;
1951		}
1952		/* remove pending counts if no longer pending */
1953		if(p->s != AUTR_STATE_ADDPEND)
1954			p->pending_count = 0;
1955		prevp = &p->next;
1956		p = p->next;
1957	}
1958}
1959
1960/** calculate next probe time */
1961static time_t
1962calc_next_probe(struct module_env* env, time_t wait)
1963{
1964	/* make it random, 90-100% */
1965	time_t rnd, rest;
1966	if(!autr_permit_small_holddown) {
1967		if(wait < 3600)
1968			wait = 3600;
1969	} else {
1970		if(wait == 0) wait = 1;
1971	}
1972	rnd = wait/10;
1973	rest = wait-rnd;
1974	rnd = (time_t)ub_random_max(env->rnd, (long int)rnd);
1975	return (time_t)(*env->now + rest + rnd);
1976}
1977
1978/** what is first probe time (anchors must be locked) */
1979static time_t
1980wait_probe_time(struct val_anchors* anchors)
1981{
1982	rbnode_t* t = rbtree_first(&anchors->autr->probe);
1983	if(t != RBTREE_NULL)
1984		return ((struct trust_anchor*)t->key)->autr->next_probe_time;
1985	return 0;
1986}
1987
1988/** reset worker timer */
1989static void
1990reset_worker_timer(struct module_env* env)
1991{
1992	struct timeval tv;
1993#ifndef S_SPLINT_S
1994	time_t next = (time_t)wait_probe_time(env->anchors);
1995	/* in case this is libunbound, no timer */
1996	if(!env->probe_timer)
1997		return;
1998	if(next > *env->now)
1999		tv.tv_sec = (time_t)(next - *env->now);
2000	else	tv.tv_sec = 0;
2001#endif
2002	tv.tv_usec = 0;
2003	comm_timer_set(env->probe_timer, &tv);
2004	verbose(VERB_ALGO, "scheduled next probe in " ARG_LL "d sec", (long long)tv.tv_sec);
2005}
2006
2007/** set next probe for trust anchor */
2008static int
2009set_next_probe(struct module_env* env, struct trust_anchor* tp,
2010	struct ub_packed_rrset_key* dnskey_rrset)
2011{
2012	struct trust_anchor key, *tp2;
2013	time_t mold, mnew;
2014	/* use memory allocated in rrset for temporary name storage */
2015	key.node.key = &key;
2016	key.name = dnskey_rrset->rk.dname;
2017	key.namelen = dnskey_rrset->rk.dname_len;
2018	key.namelabs = dname_count_labels(key.name);
2019	key.dclass = tp->dclass;
2020	lock_basic_unlock(&tp->lock);
2021
2022	/* fetch tp again and lock anchors, so that we can modify the trees */
2023	lock_basic_lock(&env->anchors->lock);
2024	tp2 = (struct trust_anchor*)rbtree_search(env->anchors->tree, &key);
2025	if(!tp2) {
2026		verbose(VERB_ALGO, "trustpoint was deleted in set_next_probe");
2027		lock_basic_unlock(&env->anchors->lock);
2028		return 0;
2029	}
2030	log_assert(tp == tp2);
2031	lock_basic_lock(&tp->lock);
2032
2033	/* schedule */
2034	mold = wait_probe_time(env->anchors);
2035	(void)rbtree_delete(&env->anchors->autr->probe, tp);
2036	tp->autr->next_probe_time = calc_next_probe(env,
2037		tp->autr->query_interval);
2038	(void)rbtree_insert(&env->anchors->autr->probe, &tp->autr->pnode);
2039	mnew = wait_probe_time(env->anchors);
2040
2041	lock_basic_unlock(&env->anchors->lock);
2042	verbose(VERB_ALGO, "next probe set in %d seconds",
2043		(int)tp->autr->next_probe_time - (int)*env->now);
2044	if(mold != mnew) {
2045		reset_worker_timer(env);
2046	}
2047	return 1;
2048}
2049
2050/** Revoke and Delete a trust point */
2051static void
2052autr_tp_remove(struct module_env* env, struct trust_anchor* tp,
2053	struct ub_packed_rrset_key* dnskey_rrset)
2054{
2055	struct trust_anchor* del_tp;
2056	struct trust_anchor key;
2057	struct autr_point_data pd;
2058	time_t mold, mnew;
2059
2060	log_nametypeclass(VERB_OPS, "trust point was revoked",
2061		tp->name, LDNS_RR_TYPE_DNSKEY, tp->dclass);
2062	tp->autr->revoked = 1;
2063
2064	/* use space allocated for dnskey_rrset to save name of anchor */
2065	memset(&key, 0, sizeof(key));
2066	memset(&pd, 0, sizeof(pd));
2067	key.autr = &pd;
2068	key.node.key = &key;
2069	pd.pnode.key = &key;
2070	pd.next_probe_time = tp->autr->next_probe_time;
2071	key.name = dnskey_rrset->rk.dname;
2072	key.namelen = tp->namelen;
2073	key.namelabs = tp->namelabs;
2074	key.dclass = tp->dclass;
2075
2076	/* unlock */
2077	lock_basic_unlock(&tp->lock);
2078
2079	/* take from tree. It could be deleted by someone else,hence (void). */
2080	lock_basic_lock(&env->anchors->lock);
2081	del_tp = (struct trust_anchor*)rbtree_delete(env->anchors->tree, &key);
2082	mold = wait_probe_time(env->anchors);
2083	(void)rbtree_delete(&env->anchors->autr->probe, &key);
2084	mnew = wait_probe_time(env->anchors);
2085	anchors_init_parents_locked(env->anchors);
2086	lock_basic_unlock(&env->anchors->lock);
2087
2088	/* if !del_tp then the trust point is no longer present in the tree,
2089	 * it was deleted by someone else, who will write the zonefile and
2090	 * clean up the structure */
2091	if(del_tp) {
2092		/* save on disk */
2093		del_tp->autr->next_probe_time = 0; /* no more probing for it */
2094		autr_write_file(env, del_tp);
2095
2096		/* delete */
2097		autr_point_delete(del_tp);
2098	}
2099	if(mold != mnew) {
2100		reset_worker_timer(env);
2101	}
2102}
2103
2104int autr_process_prime(struct module_env* env, struct val_env* ve,
2105	struct trust_anchor* tp, struct ub_packed_rrset_key* dnskey_rrset)
2106{
2107	int changed = 0;
2108	log_assert(tp && tp->autr);
2109	/* autotrust update trust anchors */
2110	/* the tp is locked, and stays locked unless it is deleted */
2111
2112	/* we could just catch the anchor here while another thread
2113	 * is busy deleting it. Just unlock and let the other do its job */
2114	if(tp->autr->revoked) {
2115		log_nametypeclass(VERB_ALGO, "autotrust not processed, "
2116			"trust point revoked", tp->name,
2117			LDNS_RR_TYPE_DNSKEY, tp->dclass);
2118		lock_basic_unlock(&tp->lock);
2119		return 0; /* it is revoked */
2120	}
2121
2122	/* query_dnskeys(): */
2123	tp->autr->last_queried = *env->now;
2124
2125	log_nametypeclass(VERB_ALGO, "autotrust process for",
2126		tp->name, LDNS_RR_TYPE_DNSKEY, tp->dclass);
2127	/* see if time alone makes some keys valid */
2128	autr_holddown_exceed(env, tp, &changed);
2129	if(changed) {
2130		verbose(VERB_ALGO, "autotrust: morekeys, reassemble");
2131		if(!autr_assemble(tp)) {
2132			log_err("malloc failure assembling autotrust keys");
2133			return 1; /* unchanged */
2134		}
2135	}
2136	/* did we get any data? */
2137	if(!dnskey_rrset) {
2138		verbose(VERB_ALGO, "autotrust: no dnskey rrset");
2139		/* no update of query_failed, because then we would have
2140		 * to write to disk. But we cannot because we maybe are
2141		 * still 'initialising' with DS records, that we cannot write
2142		 * in the full format (which only contains KSKs). */
2143		return 1; /* trust point exists */
2144	}
2145	/* check for revoked keys to remove immediately */
2146	check_contains_revoked(env, ve, tp, dnskey_rrset, &changed);
2147	if(changed) {
2148		verbose(VERB_ALGO, "autotrust: revokedkeys, reassemble");
2149		if(!autr_assemble(tp)) {
2150			log_err("malloc failure assembling autotrust keys");
2151			return 1; /* unchanged */
2152		}
2153		if(!tp->ds_rrset && !tp->dnskey_rrset) {
2154			/* no more keys, all are revoked */
2155			/* this is a success for this probe attempt */
2156			tp->autr->last_success = *env->now;
2157			autr_tp_remove(env, tp, dnskey_rrset);
2158			return 0; /* trust point removed */
2159		}
2160	}
2161	/* verify the dnskey rrset and see if it is valid. */
2162	if(!verify_dnskey(env, ve, tp, dnskey_rrset)) {
2163		verbose(VERB_ALGO, "autotrust: dnskey did not verify.");
2164		/* only increase failure count if this is not the first prime,
2165		 * this means there was a previous succesful probe */
2166		if(tp->autr->last_success) {
2167			tp->autr->query_failed += 1;
2168			autr_write_file(env, tp);
2169		}
2170		return 1; /* trust point exists */
2171	}
2172
2173	tp->autr->last_success = *env->now;
2174	tp->autr->query_failed = 0;
2175
2176	/* Add new trust anchors to the data structure
2177	 * - note which trust anchors are seen this probe.
2178	 * Set trustpoint query_interval and retry_time.
2179	 * - find minimum rrsig expiration interval
2180	 */
2181	if(!update_events(env, ve, tp, dnskey_rrset, &changed)) {
2182		log_err("malloc failure in autotrust update_events. "
2183			"trust point unchanged.");
2184		return 1; /* trust point unchanged, so exists */
2185	}
2186
2187	/* - for every SEP key do the 5011 statetable.
2188	 * - remove missing trustanchors (if veryold and we have new anchors).
2189	 */
2190	if(!do_statetable(env, tp, &changed)) {
2191		log_err("malloc failure in autotrust do_statetable. "
2192			"trust point unchanged.");
2193		return 1; /* trust point unchanged, so exists */
2194	}
2195
2196	autr_cleanup_keys(tp);
2197	if(!set_next_probe(env, tp, dnskey_rrset))
2198		return 0; /* trust point does not exist */
2199	autr_write_file(env, tp);
2200	if(changed) {
2201		verbose(VERB_ALGO, "autotrust: changed, reassemble");
2202		if(!autr_assemble(tp)) {
2203			log_err("malloc failure assembling autotrust keys");
2204			return 1; /* unchanged */
2205		}
2206		if(!tp->ds_rrset && !tp->dnskey_rrset) {
2207			/* no more keys, all are revoked */
2208			autr_tp_remove(env, tp, dnskey_rrset);
2209			return 0; /* trust point removed */
2210		}
2211	} else verbose(VERB_ALGO, "autotrust: no changes");
2212
2213	return 1; /* trust point exists */
2214}
2215
2216/** debug print a trust anchor key */
2217static void
2218autr_debug_print_ta(struct autr_ta* ta)
2219{
2220	char buf[32];
2221	char* str = sldns_wire2str_rr(ta->rr, ta->rr_len);
2222	if(!str) {
2223		log_info("out of memory in debug_print_ta");
2224		return;
2225	}
2226	if(str && str[0]) str[strlen(str)-1]=0; /* remove newline */
2227	ctime_r(&ta->last_change, buf);
2228	if(buf[0]) buf[strlen(buf)-1]=0; /* remove newline */
2229	log_info("[%s] %s ;;state:%d ;;pending_count:%d%s%s last:%s",
2230		trustanchor_state2str(ta->s), str, ta->s, ta->pending_count,
2231		ta->fetched?" fetched":"", ta->revoked?" revoked":"", buf);
2232	free(str);
2233}
2234
2235/** debug print a trust point */
2236static void
2237autr_debug_print_tp(struct trust_anchor* tp)
2238{
2239	struct autr_ta* ta;
2240	char buf[257];
2241	if(!tp->autr)
2242		return;
2243	dname_str(tp->name, buf);
2244	log_info("trust point %s : %d", buf, (int)tp->dclass);
2245	log_info("assembled %d DS and %d DNSKEYs",
2246		(int)tp->numDS, (int)tp->numDNSKEY);
2247	if(tp->ds_rrset) {
2248		log_packed_rrset(0, "DS:", tp->ds_rrset);
2249	}
2250	if(tp->dnskey_rrset) {
2251		log_packed_rrset(0, "DNSKEY:", tp->dnskey_rrset);
2252	}
2253	log_info("file %s", tp->autr->file);
2254	ctime_r(&tp->autr->last_queried, buf);
2255	if(buf[0]) buf[strlen(buf)-1]=0; /* remove newline */
2256	log_info("last_queried: %u %s", (unsigned)tp->autr->last_queried, buf);
2257	ctime_r(&tp->autr->last_success, buf);
2258	if(buf[0]) buf[strlen(buf)-1]=0; /* remove newline */
2259	log_info("last_success: %u %s", (unsigned)tp->autr->last_success, buf);
2260	ctime_r(&tp->autr->next_probe_time, buf);
2261	if(buf[0]) buf[strlen(buf)-1]=0; /* remove newline */
2262	log_info("next_probe_time: %u %s", (unsigned)tp->autr->next_probe_time,
2263		buf);
2264	log_info("query_interval: %u", (unsigned)tp->autr->query_interval);
2265	log_info("retry_time: %u", (unsigned)tp->autr->retry_time);
2266	log_info("query_failed: %u", (unsigned)tp->autr->query_failed);
2267
2268	for(ta=tp->autr->keys; ta; ta=ta->next) {
2269		autr_debug_print_ta(ta);
2270	}
2271}
2272
2273void
2274autr_debug_print(struct val_anchors* anchors)
2275{
2276	struct trust_anchor* tp;
2277	lock_basic_lock(&anchors->lock);
2278	RBTREE_FOR(tp, struct trust_anchor*, anchors->tree) {
2279		lock_basic_lock(&tp->lock);
2280		autr_debug_print_tp(tp);
2281		lock_basic_unlock(&tp->lock);
2282	}
2283	lock_basic_unlock(&anchors->lock);
2284}
2285
2286void probe_answer_cb(void* arg, int ATTR_UNUSED(rcode),
2287	sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(sec),
2288	char* ATTR_UNUSED(why_bogus))
2289{
2290	/* retry was set before the query was done,
2291	 * re-querytime is set when query succeeded, but that may not
2292	 * have reset this timer because the query could have been
2293	 * handled by another thread. In that case, this callback would
2294	 * get called after the original timeout is done.
2295	 * By not resetting the timer, it may probe more often, but not
2296	 * less often.
2297	 * Unless the new lookup resulted in smaller TTLs and thus smaller
2298	 * timeout values. In that case one old TTL could be mistakenly done.
2299	 */
2300	struct module_env* env = (struct module_env*)arg;
2301	verbose(VERB_ALGO, "autotrust probe answer cb");
2302	reset_worker_timer(env);
2303}
2304
2305/** probe a trust anchor DNSKEY and unlocks tp */
2306static void
2307probe_anchor(struct module_env* env, struct trust_anchor* tp)
2308{
2309	struct query_info qinfo;
2310	uint16_t qflags = BIT_RD;
2311	struct edns_data edns;
2312	sldns_buffer* buf = env->scratch_buffer;
2313	qinfo.qname = regional_alloc_init(env->scratch, tp->name, tp->namelen);
2314	if(!qinfo.qname) {
2315		log_err("out of memory making 5011 probe");
2316		return;
2317	}
2318	qinfo.qname_len = tp->namelen;
2319	qinfo.qtype = LDNS_RR_TYPE_DNSKEY;
2320	qinfo.qclass = tp->dclass;
2321	log_query_info(VERB_ALGO, "autotrust probe", &qinfo);
2322	verbose(VERB_ALGO, "retry probe set in %d seconds",
2323		(int)tp->autr->next_probe_time - (int)*env->now);
2324	edns.edns_present = 1;
2325	edns.ext_rcode = 0;
2326	edns.edns_version = 0;
2327	edns.bits = EDNS_DO;
2328	if(sldns_buffer_capacity(buf) < 65535)
2329		edns.udp_size = (uint16_t)sldns_buffer_capacity(buf);
2330	else	edns.udp_size = 65535;
2331
2332	/* can't hold the lock while mesh_run is processing */
2333	lock_basic_unlock(&tp->lock);
2334
2335	/* delete the DNSKEY from rrset and key cache so an active probe
2336	 * is done. First the rrset so another thread does not use it
2337	 * to recreate the key entry in a race condition. */
2338	rrset_cache_remove(env->rrset_cache, qinfo.qname, qinfo.qname_len,
2339		qinfo.qtype, qinfo.qclass, 0);
2340	key_cache_remove(env->key_cache, qinfo.qname, qinfo.qname_len,
2341		qinfo.qclass);
2342
2343	if(!mesh_new_callback(env->mesh, &qinfo, qflags, &edns, buf, 0,
2344		&probe_answer_cb, env)) {
2345		log_err("out of memory making 5011 probe");
2346	}
2347}
2348
2349/** fetch first to-probe trust-anchor and lock it and set retrytime */
2350static struct trust_anchor*
2351todo_probe(struct module_env* env, time_t* next)
2352{
2353	struct trust_anchor* tp;
2354	rbnode_t* el;
2355	/* get first one */
2356	lock_basic_lock(&env->anchors->lock);
2357	if( (el=rbtree_first(&env->anchors->autr->probe)) == RBTREE_NULL) {
2358		/* in case of revoked anchors */
2359		lock_basic_unlock(&env->anchors->lock);
2360		/* signal that there are no anchors to probe */
2361		*next = 0;
2362		return NULL;
2363	}
2364	tp = (struct trust_anchor*)el->key;
2365	lock_basic_lock(&tp->lock);
2366
2367	/* is it eligible? */
2368	if((time_t)tp->autr->next_probe_time > *env->now) {
2369		/* no more to probe */
2370		*next = (time_t)tp->autr->next_probe_time - *env->now;
2371		lock_basic_unlock(&tp->lock);
2372		lock_basic_unlock(&env->anchors->lock);
2373		return NULL;
2374	}
2375
2376	/* reset its next probe time */
2377	(void)rbtree_delete(&env->anchors->autr->probe, tp);
2378	tp->autr->next_probe_time = calc_next_probe(env, tp->autr->retry_time);
2379	(void)rbtree_insert(&env->anchors->autr->probe, &tp->autr->pnode);
2380	lock_basic_unlock(&env->anchors->lock);
2381
2382	return tp;
2383}
2384
2385time_t
2386autr_probe_timer(struct module_env* env)
2387{
2388	struct trust_anchor* tp;
2389	time_t next_probe = 3600;
2390	int num = 0;
2391	if(autr_permit_small_holddown) next_probe = 1;
2392	verbose(VERB_ALGO, "autotrust probe timer callback");
2393	/* while there are still anchors to probe */
2394	while( (tp = todo_probe(env, &next_probe)) ) {
2395		/* make a probe for this anchor */
2396		probe_anchor(env, tp);
2397		num++;
2398	}
2399	regional_free_all(env->scratch);
2400	if(next_probe == 0)
2401		return 0; /* no trust points to probe */
2402	verbose(VERB_ALGO, "autotrust probe timer %d callbacks done", num);
2403	return next_probe;
2404}
2405