]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - validator/autotrust.c
import unbound 1.4.21
[FreeBSD/FreeBSD.git] / validator / autotrust.c
1 /*
2  * validator/autotrust.c - RFC5011 trust anchor management for unbound.
3  *
4  * Copyright (c) 2009, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  * 
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  * 
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  * 
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  * 
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
25  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
27  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGE.
34  */
35
36 /**
37  * \file
38  *
39  * Contains autotrust implementation. The implementation was taken from 
40  * the autotrust daemon (BSD licensed), written by Matthijs Mekking.
41  * It was modified to fit into unbound. The state table process is the same.
42  */
43 #include "config.h"
44 #include <ldns/ldns.h>
45 #include "validator/autotrust.h"
46 #include "validator/val_anchor.h"
47 #include "validator/val_utils.h"
48 #include "validator/val_sigcrypt.h"
49 #include "util/data/dname.h"
50 #include "util/data/packed_rrset.h"
51 #include "util/log.h"
52 #include "util/module.h"
53 #include "util/net_help.h"
54 #include "util/config_file.h"
55 #include "util/regional.h"
56 #include "util/random.h"
57 #include "util/data/msgparse.h"
58 #include "services/mesh.h"
59 #include "services/cache/rrset.h"
60 #include "validator/val_kcache.h"
61
62 /** number of times a key must be seen before it can become valid */
63 #define MIN_PENDINGCOUNT 2
64
65 /** Event: Revoked */
66 static void do_revoked(struct module_env* env, struct autr_ta* anchor, int* c);
67
68 struct autr_global_data* autr_global_create(void)
69 {
70         struct autr_global_data* global;
71         global = (struct autr_global_data*)malloc(sizeof(*global));
72         if(!global) 
73                 return NULL;
74         rbtree_init(&global->probe, &probetree_cmp);
75         return global;
76 }
77
78 void autr_global_delete(struct autr_global_data* global)
79 {
80         if(!global)
81                 return;
82         /* elements deleted by parent */
83         memset(global, 0, sizeof(*global));
84         free(global);
85 }
86
87 int probetree_cmp(const void* x, const void* y)
88 {
89         struct trust_anchor* a = (struct trust_anchor*)x;
90         struct trust_anchor* b = (struct trust_anchor*)y;
91         log_assert(a->autr && b->autr);
92         if(a->autr->next_probe_time < b->autr->next_probe_time)
93                 return -1;
94         if(a->autr->next_probe_time > b->autr->next_probe_time)
95                 return 1;
96         /* time is equal, sort on trust point identity */
97         return anchor_cmp(x, y);
98 }
99
100 size_t 
101 autr_get_num_anchors(struct val_anchors* anchors)
102 {
103         size_t res = 0;
104         if(!anchors)
105                 return 0;
106         lock_basic_lock(&anchors->lock);
107         if(anchors->autr)
108                 res = anchors->autr->probe.count;
109         lock_basic_unlock(&anchors->lock);
110         return res;
111 }
112
113 /** Position in string */
114 static int
115 position_in_string(char *str, const char* sub)
116 {
117         char* pos = strstr(str, sub);
118         if(pos)
119                 return (int)(pos-str)+(int)strlen(sub);
120         return -1;
121 }
122
123 /** Debug routine to print pretty key information */
124 static void
125 verbose_key(struct autr_ta* ta, enum verbosity_value level, 
126         const char* format, ...) ATTR_FORMAT(printf, 3, 4);
127
128 /** 
129  * Implementation of debug pretty key print 
130  * @param ta: trust anchor key with DNSKEY data.
131  * @param level: verbosity level to print at.
132  * @param format: printf style format string.
133  */
134 static void
135 verbose_key(struct autr_ta* ta, enum verbosity_value level, 
136         const char* format, ...) 
137 {
138         va_list args;
139         va_start(args, format);
140         if(verbosity >= level) {
141                 char* str = ldns_rdf2str(ldns_rr_owner(ta->rr));
142                 int keytag = (int)ldns_calc_keytag(ta->rr);
143                 char msg[MAXSYSLOGMSGLEN];
144                 vsnprintf(msg, sizeof(msg), format, args);
145                 verbose(level, "%s key %d %s", str?str:"??", keytag, msg);
146                 free(str);
147         }
148         va_end(args);
149 }
150
151 /** 
152  * Parse comments 
153  * @param str: to parse
154  * @param ta: trust key autotrust metadata
155  * @return false on failure.
156  */
157 static int
158 parse_comments(char* str, struct autr_ta* ta)
159 {
160         int len = (int)strlen(str), pos = 0, timestamp = 0;
161         char* comment = (char*) malloc(sizeof(char)*len+1);
162         char* comments = comment;
163         if(!comment) {
164                 log_err("malloc failure in parse");
165                 return 0;
166         }
167         /* skip over whitespace and data at start of line */
168         while (*str != '\0' && *str != ';')
169                 str++;
170         if (*str == ';')
171                 str++;
172         /* copy comments */
173         while (*str != '\0')
174         {
175                 *comments = *str;
176                 comments++;
177                 str++;
178         }
179         *comments = '\0';
180
181         comments = comment;
182
183         /* read state */
184         pos = position_in_string(comments, "state=");
185         if (pos >= (int) strlen(comments))
186         {
187                 log_err("parse error");
188                 free(comment);
189                 return 0;
190         }
191         if (pos <= 0)
192                 ta->s = AUTR_STATE_VALID;
193         else
194         {
195                 int s = (int) comments[pos] - '0';
196                 switch(s)
197                 {
198                         case AUTR_STATE_START:
199                         case AUTR_STATE_ADDPEND:
200                         case AUTR_STATE_VALID:
201                         case AUTR_STATE_MISSING:
202                         case AUTR_STATE_REVOKED:
203                         case AUTR_STATE_REMOVED:
204                                 ta->s = s;
205                                 break;
206                         default:
207                                 verbose_key(ta, VERB_OPS, "has undefined "
208                                         "state, considered NewKey");
209                                 ta->s = AUTR_STATE_START;
210                                 break;
211                 }
212         }
213         /* read pending count */
214         pos = position_in_string(comments, "count=");
215         if (pos >= (int) strlen(comments))
216         {
217                 log_err("parse error");
218                 free(comment);
219                 return 0;
220         }
221         if (pos <= 0)
222                 ta->pending_count = 0;
223         else
224         {
225                 comments += pos;
226                 ta->pending_count = (uint8_t)atoi(comments);
227         }
228
229         /* read last change */
230         pos = position_in_string(comments, "lastchange=");
231         if (pos >= (int) strlen(comments))
232         {
233                 log_err("parse error");
234                 free(comment);
235                 return 0;
236         }
237         if (pos >= 0)
238         {
239                 comments += pos;
240                 timestamp = atoi(comments);
241         }
242         if (pos < 0 || !timestamp)
243                 ta->last_change = 0;
244         else
245                 ta->last_change = (time_t)timestamp;
246
247         free(comment);
248         return 1;
249 }
250
251 /** Check if a line contains data (besides comments) */
252 static int
253 str_contains_data(char* str, char comment)
254 {
255         while (*str != '\0') {
256                 if (*str == comment || *str == '\n')
257                         return 0;
258                 if (*str != ' ' && *str != '\t')
259                         return 1;
260                 str++;
261         }
262         return 0;
263 }
264
265 /** Get DNSKEY flags */
266 static int
267 dnskey_flags(ldns_rr* rr)
268 {
269         if(ldns_rr_get_type(rr) != LDNS_RR_TYPE_DNSKEY)
270                 return 0;
271         return (int)ldns_read_uint16(ldns_rdf_data(ldns_rr_dnskey_flags(rr)));
272 }
273
274
275 /** Check if KSK DNSKEY */
276 static int
277 rr_is_dnskey_sep(ldns_rr* rr)
278 {
279         return (dnskey_flags(rr)&DNSKEY_BIT_SEP);
280 }
281
282 /** Check if REVOKED DNSKEY */
283 static int
284 rr_is_dnskey_revoked(ldns_rr* rr)
285 {
286         return (dnskey_flags(rr)&LDNS_KEY_REVOKE_KEY);
287 }
288
289 /** create ta */
290 static struct autr_ta*
291 autr_ta_create(ldns_rr* rr)
292 {
293         struct autr_ta* ta = (struct autr_ta*)calloc(1, sizeof(*ta));
294         if(!ta) {
295                 ldns_rr_free(rr);
296                 return NULL;
297         }
298         ta->rr = rr;
299         return ta;
300 }
301
302 /** create tp */
303 static struct trust_anchor*
304 autr_tp_create(struct val_anchors* anchors, ldns_rdf* own, uint16_t dc)
305 {
306         struct trust_anchor* tp = (struct trust_anchor*)calloc(1, sizeof(*tp));
307         if(!tp) return NULL;
308         tp->name = memdup(ldns_rdf_data(own), ldns_rdf_size(own));
309         if(!tp->name) {
310                 free(tp);
311                 return NULL;
312         }
313         tp->namelen = ldns_rdf_size(own);
314         tp->namelabs = dname_count_labels(tp->name);
315         tp->node.key = tp;
316         tp->dclass = dc;
317         tp->autr = (struct autr_point_data*)calloc(1, sizeof(*tp->autr));
318         if(!tp->autr) {
319                 free(tp->name);
320                 free(tp);
321                 return NULL;
322         }
323         tp->autr->pnode.key = tp;
324
325         lock_basic_lock(&anchors->lock);
326         if(!rbtree_insert(anchors->tree, &tp->node)) {
327                 lock_basic_unlock(&anchors->lock);
328                 log_err("trust anchor presented twice");
329                 free(tp->name);
330                 free(tp->autr);
331                 free(tp);
332                 return NULL;
333         }
334         if(!rbtree_insert(&anchors->autr->probe, &tp->autr->pnode)) {
335                 (void)rbtree_delete(anchors->tree, tp);
336                 lock_basic_unlock(&anchors->lock);
337                 log_err("trust anchor in probetree twice");
338                 free(tp->name);
339                 free(tp->autr);
340                 free(tp);
341                 return NULL;
342         }
343         lock_basic_unlock(&anchors->lock);
344         lock_basic_init(&tp->lock);
345         lock_protect(&tp->lock, tp, sizeof(*tp));
346         lock_protect(&tp->lock, tp->autr, sizeof(*tp->autr));
347         return tp;
348 }
349
350 /** delete assembled rrsets */
351 static void
352 autr_rrset_delete(struct ub_packed_rrset_key* r)
353 {
354         if(r) {
355                 free(r->rk.dname);
356                 free(r->entry.data);
357                 free(r);
358         }
359 }
360
361 void autr_point_delete(struct trust_anchor* tp)
362 {
363         if(!tp)
364                 return;
365         lock_unprotect(&tp->lock, tp);
366         lock_unprotect(&tp->lock, tp->autr);
367         lock_basic_destroy(&tp->lock);
368         autr_rrset_delete(tp->ds_rrset);
369         autr_rrset_delete(tp->dnskey_rrset);
370         if(tp->autr) {
371                 struct autr_ta* p = tp->autr->keys, *np;
372                 while(p) {
373                         np = p->next;
374                         ldns_rr_free(p->rr);
375                         free(p);
376                         p = np;
377                 }
378                 free(tp->autr->file);
379                 free(tp->autr);
380         }
381         free(tp->name);
382         free(tp);
383 }
384
385 /** find or add a new trust point for autotrust */
386 static struct trust_anchor*
387 find_add_tp(struct val_anchors* anchors, ldns_rr* rr)
388 {
389         struct trust_anchor* tp;
390         ldns_rdf* own = ldns_rr_owner(rr);
391         tp = anchor_find(anchors, ldns_rdf_data(own), 
392                 dname_count_labels(ldns_rdf_data(own)),
393                 ldns_rdf_size(own), ldns_rr_get_class(rr));
394         if(tp) {
395                 if(!tp->autr) {
396                         log_err("anchor cannot be with and without autotrust");
397                         lock_basic_unlock(&tp->lock);
398                         return NULL;
399                 }
400                 return tp;
401         }
402         tp = autr_tp_create(anchors, ldns_rr_owner(rr), ldns_rr_get_class(rr));
403         lock_basic_lock(&tp->lock);
404         return tp;
405 }
406
407 /** Add trust anchor from RR */
408 static struct autr_ta*
409 add_trustanchor_frm_rr(struct val_anchors* anchors, ldns_rr* rr, 
410         struct trust_anchor** tp)
411 {
412         struct autr_ta* ta = autr_ta_create(rr);
413         if(!ta) 
414                 return NULL;
415         *tp = find_add_tp(anchors, rr);
416         if(!*tp) {
417                 ldns_rr_free(ta->rr);
418                 free(ta);
419                 return NULL;
420         }
421         /* add ta to tp */
422         ta->next = (*tp)->autr->keys;
423         (*tp)->autr->keys = ta;
424         lock_basic_unlock(&(*tp)->lock);
425         return ta;
426 }
427
428 /**
429  * Add new trust anchor from a string in file.
430  * @param anchors: all anchors
431  * @param str: string with anchor and comments, if any comments.
432  * @param tp: trust point returned.
433  * @param origin: what to use for @
434  * @param prev: previous rr name
435  * @param skip: if true, the result is NULL, but not an error, skip it.
436  * @return new key in trust point.
437  */
438 static struct autr_ta*
439 add_trustanchor_frm_str(struct val_anchors* anchors, char* str, 
440         struct trust_anchor** tp, ldns_rdf* origin, ldns_rdf** prev, int* skip)
441 {
442         ldns_rr* rr;
443         ldns_status lstatus;
444         if (!str_contains_data(str, ';')) {
445                 *skip = 1;
446                 return NULL; /* empty line */
447         }
448         if (LDNS_STATUS_OK !=
449                 (lstatus = ldns_rr_new_frm_str(&rr, str, 0, origin, prev)))
450         {
451                 log_err("ldns error while converting string to RR: %s",
452                         ldns_get_errorstr_by_id(lstatus));
453                 return NULL;
454         }
455         if(ldns_rr_get_type(rr) != LDNS_RR_TYPE_DNSKEY &&
456                 ldns_rr_get_type(rr) != LDNS_RR_TYPE_DS) {
457                 ldns_rr_free(rr);
458                 *skip = 1;
459                 return NULL; /* only DS and DNSKEY allowed */
460         }
461         return add_trustanchor_frm_rr(anchors, rr, tp);
462 }
463
464 /** 
465  * Load single anchor 
466  * @param anchors: all points.
467  * @param str: comments line
468  * @param fname: filename
469  * @param origin: the $ORIGIN.
470  * @param prev: passed to ldns.
471  * @param skip: if true, the result is NULL, but not an error, skip it.
472  * @return false on failure, otherwise the tp read.
473  */
474 static struct trust_anchor*
475 load_trustanchor(struct val_anchors* anchors, char* str, const char* fname,
476         ldns_rdf* origin, ldns_rdf** prev, int* skip)
477 {
478         struct autr_ta* ta = NULL;
479         struct trust_anchor* tp = NULL;
480
481         ta = add_trustanchor_frm_str(anchors, str, &tp, origin, prev, skip);
482         if(!ta)
483                 return NULL;
484         lock_basic_lock(&tp->lock);
485         if(!parse_comments(str, ta)) {
486                 lock_basic_unlock(&tp->lock);
487                 return NULL;
488         }
489         if(!tp->autr->file) {
490                 tp->autr->file = strdup(fname);
491                 if(!tp->autr->file) {
492                         lock_basic_unlock(&tp->lock);
493                         log_err("malloc failure");
494                         return NULL;
495                 }
496         }
497         lock_basic_unlock(&tp->lock);
498         return tp;
499 }
500
501 /**
502  * Assemble the trust anchors into DS and DNSKEY packed rrsets.
503  * Uses only VALID and MISSING DNSKEYs.
504  * Read the ldns_rrs and builds packed rrsets
505  * @param tp: the trust point. Must be locked.
506  * @return false on malloc failure.
507  */
508 static int 
509 autr_assemble(struct trust_anchor* tp)
510 {
511         ldns_rr_list* ds, *dnskey;
512         struct autr_ta* ta;
513         struct ub_packed_rrset_key* ubds=NULL, *ubdnskey=NULL;
514
515         ds = ldns_rr_list_new();
516         dnskey = ldns_rr_list_new();
517         if(!ds || !dnskey) {
518                 ldns_rr_list_free(ds);
519                 ldns_rr_list_free(dnskey);
520                 return 0;
521         }
522         for(ta = tp->autr->keys; ta; ta = ta->next) {
523                 if(ldns_rr_get_type(ta->rr) == LDNS_RR_TYPE_DS) {
524                         if(!ldns_rr_list_push_rr(ds, ta->rr)) {
525                                 ldns_rr_list_free(ds);
526                                 ldns_rr_list_free(dnskey);
527                                 return 0;
528                         }
529                 } else if(ta->s == AUTR_STATE_VALID || 
530                         ta->s == AUTR_STATE_MISSING) {
531                         if(!ldns_rr_list_push_rr(dnskey, ta->rr)) {
532                                 ldns_rr_list_free(ds);
533                                 ldns_rr_list_free(dnskey);
534                                 return 0;
535                         }
536                 }
537         }
538
539         /* make packed rrset keys - malloced with no ID number, they
540          * are not in the cache */
541         /* make packed rrset data (if there is a key) */
542
543         if(ldns_rr_list_rr_count(ds) > 0) {
544                 ubds = ub_packed_rrset_heap_key(ds);
545                 if(!ubds) 
546                         goto error_cleanup;
547                 ubds->entry.data = packed_rrset_heap_data(ds);
548                 if(!ubds->entry.data)
549                         goto error_cleanup;
550         }
551         if(ldns_rr_list_rr_count(dnskey) > 0) {
552                 ubdnskey = ub_packed_rrset_heap_key(dnskey);
553                 if(!ubdnskey)
554                         goto error_cleanup;
555                 ubdnskey->entry.data = packed_rrset_heap_data(dnskey);
556                 if(!ubdnskey->entry.data) {
557                 error_cleanup:
558                         autr_rrset_delete(ubds);
559                         autr_rrset_delete(ubdnskey);
560                         ldns_rr_list_free(ds);
561                         ldns_rr_list_free(dnskey);
562                         return 0;
563                 }
564         }
565         /* we have prepared the new keys so nothing can go wrong any more.
566          * And we are sure we cannot be left without trustanchor after
567          * any errors. Put in the new keys and remove old ones. */
568
569         /* free the old data */
570         autr_rrset_delete(tp->ds_rrset);
571         autr_rrset_delete(tp->dnskey_rrset);
572
573         /* assign the data to replace the old */
574         tp->ds_rrset = ubds;
575         tp->dnskey_rrset = ubdnskey;
576         tp->numDS = ldns_rr_list_rr_count(ds);
577         tp->numDNSKEY = ldns_rr_list_rr_count(dnskey);
578
579         ldns_rr_list_free(ds);
580         ldns_rr_list_free(dnskey);
581         return 1;
582 }
583
584 /** parse integer */
585 static unsigned int
586 parse_int(char* line, int* ret)
587 {
588         char *e;
589         unsigned int x = (unsigned int)strtol(line, &e, 10);
590         if(line == e) {
591                 *ret = -1; /* parse error */
592                 return 0; 
593         }
594         *ret = 1; /* matched */
595         return x;
596 }
597
598 /** parse id sequence for anchor */
599 static struct trust_anchor*
600 parse_id(struct val_anchors* anchors, char* line)
601 {
602         struct trust_anchor *tp;
603         int r;
604         ldns_rdf* rdf;
605         uint16_t dclass;
606         /* read the owner name */
607         char* next = strchr(line, ' ');
608         if(!next)
609                 return NULL;
610         next[0] = 0;
611         rdf = ldns_dname_new_frm_str(line);
612         if(!rdf)
613                 return NULL;
614
615         /* read the class */
616         dclass = parse_int(next+1, &r);
617         if(r == -1) {
618                 ldns_rdf_deep_free(rdf);
619                 return NULL;
620         }
621
622         /* find the trust point */
623         tp = autr_tp_create(anchors, rdf, dclass);
624         ldns_rdf_deep_free(rdf);
625         return tp;
626 }
627
628 /** 
629  * Parse variable from trustanchor header 
630  * @param line: to parse
631  * @param anchors: the anchor is added to this, if "id:" is seen.
632  * @param anchor: the anchor as result value or previously returned anchor
633  *      value to read the variable lines into.
634  * @return: 0 no match, -1 failed syntax error, +1 success line read.
635  *      +2 revoked trust anchor file.
636  */
637 static int
638 parse_var_line(char* line, struct val_anchors* anchors, 
639         struct trust_anchor** anchor)
640 {
641         struct trust_anchor* tp = *anchor;
642         int r = 0;
643         if(strncmp(line, ";;id: ", 6) == 0) {
644                 *anchor = parse_id(anchors, line+6);
645                 if(!*anchor) return -1;
646                 else return 1;
647         } else if(strncmp(line, ";;REVOKED", 9) == 0) {
648                 if(tp) {
649                         log_err("REVOKED statement must be at start of file");
650                         return -1;
651                 }
652                 return 2;
653         } else if(strncmp(line, ";;last_queried: ", 16) == 0) {
654                 if(!tp) return -1;
655                 lock_basic_lock(&tp->lock);
656                 tp->autr->last_queried = (time_t)parse_int(line+16, &r);
657                 lock_basic_unlock(&tp->lock);
658         } else if(strncmp(line, ";;last_success: ", 16) == 0) {
659                 if(!tp) return -1;
660                 lock_basic_lock(&tp->lock);
661                 tp->autr->last_success = (time_t)parse_int(line+16, &r);
662                 lock_basic_unlock(&tp->lock);
663         } else if(strncmp(line, ";;next_probe_time: ", 19) == 0) {
664                 if(!tp) return -1;
665                 lock_basic_lock(&anchors->lock);
666                 lock_basic_lock(&tp->lock);
667                 (void)rbtree_delete(&anchors->autr->probe, tp);
668                 tp->autr->next_probe_time = (time_t)parse_int(line+19, &r);
669                 (void)rbtree_insert(&anchors->autr->probe, &tp->autr->pnode);
670                 lock_basic_unlock(&tp->lock);
671                 lock_basic_unlock(&anchors->lock);
672         } else if(strncmp(line, ";;query_failed: ", 16) == 0) {
673                 if(!tp) return -1;
674                 lock_basic_lock(&tp->lock);
675                 tp->autr->query_failed = (uint8_t)parse_int(line+16, &r);
676                 lock_basic_unlock(&tp->lock);
677         } else if(strncmp(line, ";;query_interval: ", 18) == 0) {
678                 if(!tp) return -1;
679                 lock_basic_lock(&tp->lock);
680                 tp->autr->query_interval = (time_t)parse_int(line+18, &r);
681                 lock_basic_unlock(&tp->lock);
682         } else if(strncmp(line, ";;retry_time: ", 14) == 0) {
683                 if(!tp) return -1;
684                 lock_basic_lock(&tp->lock);
685                 tp->autr->retry_time = (time_t)parse_int(line+14, &r);
686                 lock_basic_unlock(&tp->lock);
687         }
688         return r;
689 }
690
691 /** handle origin lines */
692 static int
693 handle_origin(char* line, ldns_rdf** origin)
694 {
695         while(isspace((int)*line))
696                 line++;
697         if(strncmp(line, "$ORIGIN", 7) != 0)
698                 return 0;
699         ldns_rdf_deep_free(*origin);
700         line += 7;
701         while(isspace((int)*line))
702                 line++;
703         *origin = ldns_dname_new_frm_str(line);
704         if(!*origin)
705                 log_warn("malloc failure or parse error in $ORIGIN");
706         return 1;
707 }
708
709 /** Read one line and put multiline RRs onto one line string */
710 static int
711 read_multiline(char* buf, size_t len, FILE* in, int* linenr)
712 {
713         char* pos = buf;
714         size_t left = len;
715         int depth = 0;
716         buf[len-1] = 0;
717         while(left > 0 && fgets(pos, (int)left, in) != NULL) {
718                 size_t i, poslen = strlen(pos);
719                 (*linenr)++;
720
721                 /* check what the new depth is after the line */
722                 /* this routine cannot handle braces inside quotes,
723                    say for TXT records, but this routine only has to read keys */
724                 for(i=0; i<poslen; i++) {
725                         if(pos[i] == '(') {
726                                 depth++;
727                         } else if(pos[i] == ')') {
728                                 if(depth == 0) {
729                                         log_err("mismatch: too many ')'");
730                                         return -1;
731                                 }
732                                 depth--;
733                         } else if(pos[i] == ';') {
734                                 break;
735                         }
736                 }
737
738                 /* normal oneline or last line: keeps newline and comments */
739                 if(depth == 0) {
740                         return 1;
741                 }
742
743                 /* more lines expected, snip off comments and newline */
744                 if(poslen>0) 
745                         pos[poslen-1] = 0; /* strip newline */
746                 if(strchr(pos, ';')) 
747                         strchr(pos, ';')[0] = 0; /* strip comments */
748
749                 /* move to paste other lines behind this one */
750                 poslen = strlen(pos);
751                 pos += poslen;
752                 left -= poslen;
753                 /* the newline is changed into a space */
754                 if(left <= 2 /* space and eos */) {
755                         log_err("line too long");
756                         return -1;
757                 }
758                 pos[0] = ' ';
759                 pos[1] = 0;
760                 pos += 1;
761                 left -= 1;
762         }
763         if(depth != 0) {
764                 log_err("mismatch: too many '('");
765                 return -1;
766         }
767         if(pos != buf)
768                 return 1;
769         return 0;
770 }
771
772 int autr_read_file(struct val_anchors* anchors, const char* nm)
773 {
774         /* the file descriptor */
775         FILE* fd;
776         /* keep track of line numbers */
777         int line_nr = 0;
778         /* single line */
779         char line[10240];
780         /* trust point being read */
781         struct trust_anchor *tp = NULL, *tp2;
782         int r;
783         /* for $ORIGIN parsing */
784         ldns_rdf *origin=NULL, *prev=NULL;
785
786         if (!(fd = fopen(nm, "r"))) {
787                 log_err("unable to open %s for reading: %s", 
788                         nm, strerror(errno));
789                 return 0;
790         }
791         verbose(VERB_ALGO, "reading autotrust anchor file %s", nm);
792         while ( (r=read_multiline(line, sizeof(line), fd, &line_nr)) != 0) {
793                 if(r == -1 || (r = parse_var_line(line, anchors, &tp)) == -1) {
794                         log_err("could not parse auto-trust-anchor-file "
795                                 "%s line %d", nm, line_nr);
796                         fclose(fd);
797                         ldns_rdf_deep_free(origin);
798                         ldns_rdf_deep_free(prev);
799                         return 0;
800                 } else if(r == 1) {
801                         continue;
802                 } else if(r == 2) {
803                         log_warn("trust anchor %s has been revoked", nm);
804                         fclose(fd);
805                         ldns_rdf_deep_free(origin);
806                         ldns_rdf_deep_free(prev);
807                         return 1;
808                 }
809                 if (!str_contains_data(line, ';'))
810                         continue; /* empty lines allowed */
811                 if(handle_origin(line, &origin))
812                         continue;
813                 r = 0;
814                 if(!(tp2=load_trustanchor(anchors, line, nm, origin, &prev, 
815                         &r))) {
816                         if(!r) log_err("failed to load trust anchor from %s "
817                                 "at line %i, skipping", nm, line_nr);
818                         /* try to do the rest */
819                         continue;
820                 }
821                 if(tp && tp != tp2) {
822                         log_err("file %s has mismatching data inside: "
823                                 "the file may only contain keys for one name, "
824                                 "remove keys for other domain names", nm);
825                         fclose(fd);
826                         ldns_rdf_deep_free(origin);
827                         ldns_rdf_deep_free(prev);
828                         return 0;
829                 }
830                 tp = tp2;
831         }
832         fclose(fd);
833         ldns_rdf_deep_free(origin);
834         ldns_rdf_deep_free(prev);
835         if(!tp) {
836                 log_err("failed to read %s", nm);
837                 return 0;
838         }
839
840         /* now assemble the data into DNSKEY and DS packed rrsets */
841         lock_basic_lock(&tp->lock);
842         if(!autr_assemble(tp)) {
843                 lock_basic_unlock(&tp->lock);
844                 log_err("malloc failure assembling %s", nm);
845                 return 0;
846         }
847         lock_basic_unlock(&tp->lock);
848         return 1;
849 }
850
851 /** string for a trustanchor state */
852 static const char*
853 trustanchor_state2str(autr_state_t s)
854 {
855         switch (s) {
856                 case AUTR_STATE_START:       return "  START  ";
857                 case AUTR_STATE_ADDPEND:     return " ADDPEND ";
858                 case AUTR_STATE_VALID:       return "  VALID  ";
859                 case AUTR_STATE_MISSING:     return " MISSING ";
860                 case AUTR_STATE_REVOKED:     return " REVOKED ";
861                 case AUTR_STATE_REMOVED:     return " REMOVED ";
862         }
863         return " UNKNOWN ";
864 }
865
866 /** print ID to file */
867 static int
868 print_id(FILE* out, char* fname, struct module_env* env, 
869         uint8_t* nm, size_t nmlen, uint16_t dclass)
870 {
871         ldns_rdf rdf;
872 #ifdef UNBOUND_DEBUG
873         ldns_status s;
874 #endif
875
876         memset(&rdf, 0, sizeof(rdf));
877         ldns_rdf_set_data(&rdf, nm);
878         ldns_rdf_set_size(&rdf, nmlen);
879         ldns_rdf_set_type(&rdf, LDNS_RDF_TYPE_DNAME);
880
881         ldns_buffer_clear(env->scratch_buffer);
882 #ifdef UNBOUND_DEBUG
883         s =
884 #else
885         (void)
886 #endif
887         ldns_rdf2buffer_str_dname(env->scratch_buffer, &rdf);
888         log_assert(s == LDNS_STATUS_OK);
889         ldns_buffer_write_u8(env->scratch_buffer, 0);
890         ldns_buffer_flip(env->scratch_buffer);
891         if(fprintf(out, ";;id: %s %d\n", 
892                 (char*)ldns_buffer_begin(env->scratch_buffer),
893                 (int)dclass) < 0) {
894                 log_err("could not write to %s: %s", fname, strerror(errno));
895                 return 0;
896         }
897         return 1;
898 }
899
900 static int
901 autr_write_contents(FILE* out, char* fn, struct module_env* env,
902         struct trust_anchor* tp)
903 {
904         char tmi[32];
905         struct autr_ta* ta;
906         char* str;
907
908         /* write pretty header */
909         if(fprintf(out, "; autotrust trust anchor file\n") < 0) {
910                 log_err("could not write to %s: %s", fn, strerror(errno));
911                 return 0;
912         }
913         if(tp->autr->revoked) {
914                 if(fprintf(out, ";;REVOKED\n") < 0 ||
915                    fprintf(out, "; The zone has all keys revoked, and is\n"
916                         "; considered as if it has no trust anchors.\n"
917                         "; the remainder of the file is the last probe.\n"
918                         "; to restart the trust anchor, overwrite this file.\n"
919                         "; with one containing valid DNSKEYs or DSes.\n") < 0) {
920                    log_err("could not write to %s: %s", fn, strerror(errno));
921                    return 0;
922                 }
923         }
924         if(!print_id(out, fn, env, tp->name, tp->namelen, tp->dclass)) {
925                 return 0;
926         }
927         if(fprintf(out, ";;last_queried: %u ;;%s", 
928                 (unsigned int)tp->autr->last_queried, 
929                 ctime_r(&(tp->autr->last_queried), tmi)) < 0 ||
930            fprintf(out, ";;last_success: %u ;;%s", 
931                 (unsigned int)tp->autr->last_success,
932                 ctime_r(&(tp->autr->last_success), tmi)) < 0 ||
933            fprintf(out, ";;next_probe_time: %u ;;%s", 
934                 (unsigned int)tp->autr->next_probe_time,
935                 ctime_r(&(tp->autr->next_probe_time), tmi)) < 0 ||
936            fprintf(out, ";;query_failed: %d\n", (int)tp->autr->query_failed)<0
937            || fprintf(out, ";;query_interval: %d\n", 
938            (int)tp->autr->query_interval) < 0 ||
939            fprintf(out, ";;retry_time: %d\n", (int)tp->autr->retry_time) < 0) {
940                 log_err("could not write to %s: %s", fn, strerror(errno));
941                 return 0;
942         }
943
944         /* write anchors */
945         for(ta=tp->autr->keys; ta; ta=ta->next) {
946                 /* by default do not store START and REMOVED keys */
947                 if(ta->s == AUTR_STATE_START)
948                         continue;
949                 if(ta->s == AUTR_STATE_REMOVED)
950                         continue;
951                 /* only store keys */
952                 if(ldns_rr_get_type(ta->rr) != LDNS_RR_TYPE_DNSKEY)
953                         continue;
954                 str = ldns_rr2str(ta->rr);
955                 if(!str || !str[0]) {
956                         free(str);
957                         log_err("malloc failure writing %s", fn);
958                         return 0;
959                 }
960                 str[strlen(str)-1] = 0; /* remove newline */
961                 if(fprintf(out, "%s ;;state=%d [%s] ;;count=%d "
962                         ";;lastchange=%u ;;%s", str, (int)ta->s, 
963                         trustanchor_state2str(ta->s), (int)ta->pending_count,
964                         (unsigned int)ta->last_change, 
965                         ctime_r(&(ta->last_change), tmi)) < 0) {
966                    log_err("could not write to %s: %s", fn, strerror(errno));
967                    free(str);
968                    return 0;
969                 }
970                 free(str);
971         }
972         return 1;
973 }
974
975 void autr_write_file(struct module_env* env, struct trust_anchor* tp)
976 {
977         FILE* out;
978         char* fname = tp->autr->file;
979         char tempf[2048];
980         log_assert(tp->autr);
981         if(!env) {
982                 log_err("autr_write_file: Module environment is NULL.");
983                 return;
984         }
985         /* unique name with pid number and thread number */
986         snprintf(tempf, sizeof(tempf), "%s.%d-%d", fname, (int)getpid(),
987                 env->worker?*(int*)env->worker:0);
988         verbose(VERB_ALGO, "autotrust: write to disk: %s", tempf);
989         out = fopen(tempf, "w");
990         if(!out) {
991                 log_err("could not open autotrust file for writing, %s: %s",
992                         tempf, strerror(errno));
993                 return;
994         }
995         if(!autr_write_contents(out, tempf, env, tp)) {
996                 /* failed to write contents (completely) */
997                 fclose(out);
998                 unlink(tempf);
999                 log_err("could not completely write: %s", fname);
1000                 return;
1001         }
1002         /* success; overwrite actual file */
1003         fclose(out);
1004         verbose(VERB_ALGO, "autotrust: replaced %s", fname);
1005 #ifdef UB_ON_WINDOWS
1006         (void)unlink(fname); /* windows does not replace file with rename() */
1007 #endif
1008         if(rename(tempf, fname) < 0) {
1009                 log_err("rename(%s to %s): %s", tempf, fname, strerror(errno));
1010         }
1011 }
1012
1013 /** 
1014  * Verify if dnskey works for trust point 
1015  * @param env: environment (with time) for verification
1016  * @param ve: validator environment (with options) for verification.
1017  * @param tp: trust point to verify with
1018  * @param rrset: DNSKEY rrset to verify.
1019  * @return false on failure, true if verification successful.
1020  */
1021 static int
1022 verify_dnskey(struct module_env* env, struct val_env* ve,
1023         struct trust_anchor* tp, struct ub_packed_rrset_key* rrset)
1024 {
1025         char* reason = NULL;
1026         uint8_t sigalg[ALGO_NEEDS_MAX+1];
1027         int downprot = 1;
1028         enum sec_status sec = val_verify_DNSKEY_with_TA(env, ve, rrset,
1029                 tp->ds_rrset, tp->dnskey_rrset, downprot?sigalg:NULL, &reason);
1030         /* sigalg is ignored, it returns algorithms signalled to exist, but
1031          * in 5011 there are no other rrsets to check.  if downprot is
1032          * enabled, then it checks that the DNSKEY is signed with all
1033          * algorithms available in the trust store. */
1034         verbose(VERB_ALGO, "autotrust: validate DNSKEY with anchor: %s",
1035                 sec_status_to_string(sec));
1036         return sec == sec_status_secure;
1037 }
1038
1039 /** Find minimum expiration interval from signatures */
1040 static time_t
1041 min_expiry(struct module_env* env, ldns_rr_list* rrset)
1042 {
1043         size_t i;
1044         int32_t t, r = 15 * 24 * 3600; /* 15 days max */
1045         for(i=0; i<ldns_rr_list_rr_count(rrset); i++) {
1046                 ldns_rr* rr = ldns_rr_list_rr(rrset, i);
1047                 if(ldns_rr_get_type(rr) != LDNS_RR_TYPE_RRSIG)
1048                         continue;
1049                 t = ldns_rdf2native_int32(ldns_rr_rrsig_expiration(rr));
1050                 if((int32_t)t - (int32_t)*env->now > 0) {
1051                         t -= *env->now;
1052                         if(t < r)
1053                                 r = t;
1054                 }
1055         }
1056         return (time_t)r;
1057 }
1058
1059 /** Is rr self-signed revoked key */
1060 static int
1061 rr_is_selfsigned_revoked(struct module_env* env, struct val_env* ve,
1062         struct ub_packed_rrset_key* dnskey_rrset, size_t i)
1063 {
1064         enum sec_status sec;
1065         char* reason = NULL;
1066         verbose(VERB_ALGO, "seen REVOKE flag, check self-signed, rr %d",
1067                 (int)i);
1068         /* no algorithm downgrade protection necessary, if it is selfsigned
1069          * revoked it can be removed. */
1070         sec = dnskey_verify_rrset(env, ve, dnskey_rrset, dnskey_rrset, i, 
1071                 &reason);
1072         return (sec == sec_status_secure);
1073 }
1074
1075 /** Set fetched value */
1076 static void
1077 seen_trustanchor(struct autr_ta* ta, uint8_t seen)
1078 {
1079         ta->fetched = seen;
1080         if(ta->pending_count < 250) /* no numerical overflow, please */
1081                 ta->pending_count++;
1082 }
1083
1084 /** set revoked value */
1085 static void
1086 seen_revoked_trustanchor(struct autr_ta* ta, uint8_t revoked)
1087 {
1088         ta->revoked = revoked;
1089 }
1090
1091 /** revoke a trust anchor */
1092 static void
1093 revoke_dnskey(struct autr_ta* ta, int off)
1094 {
1095         ldns_rdf* rdf;
1096         uint16_t flags;
1097         log_assert(ta && ta->rr);
1098         if(ldns_rr_get_type(ta->rr) != LDNS_RR_TYPE_DNSKEY)
1099                 return;
1100         rdf = ldns_rr_dnskey_flags(ta->rr);
1101         flags = ldns_read_uint16(ldns_rdf_data(rdf));
1102
1103         if (off && (flags&LDNS_KEY_REVOKE_KEY))
1104                 flags ^= LDNS_KEY_REVOKE_KEY; /* flip */
1105         else
1106                 flags |= LDNS_KEY_REVOKE_KEY;
1107         ldns_write_uint16(ldns_rdf_data(rdf), flags);
1108 }
1109
1110 /** Compare two RR buffers skipping the REVOKED bit */
1111 static int
1112 ldns_rr_compare_wire_skip_revbit(ldns_buffer* rr1_buf, ldns_buffer* rr2_buf)
1113 {
1114         size_t rr1_len, rr2_len, min_len, i, offset;
1115         rr1_len = ldns_buffer_capacity(rr1_buf);
1116         rr2_len = ldns_buffer_capacity(rr2_buf);
1117         /* jump past dname (checked in earlier part) and especially past TTL */
1118         offset = 0;
1119         while (offset < rr1_len && *ldns_buffer_at(rr1_buf, offset) != 0)
1120                 offset += *ldns_buffer_at(rr1_buf, offset) + 1;
1121         /* jump to rdata section (PAST the rdata length field) */
1122         offset += 11; /* 0-dname-end + type + class + ttl + rdatalen */
1123         min_len = (rr1_len < rr2_len) ? rr1_len : rr2_len;
1124         /* compare RRs RDATA byte for byte. */
1125         for(i = offset; i < min_len; i++)
1126         {
1127                 uint8_t *rdf1, *rdf2;
1128                 rdf1 = ldns_buffer_at(rr1_buf, i);
1129                 rdf2 = ldns_buffer_at(rr2_buf, i);
1130                 if (i==(offset+1))
1131                 {
1132                         /* this is the second part of the flags field */
1133                         *rdf1 = *rdf1 | LDNS_KEY_REVOKE_KEY;
1134                         *rdf2 = *rdf2 | LDNS_KEY_REVOKE_KEY;
1135                 }
1136                 if (*rdf1 < *rdf2)      return -1;
1137                 else if (*rdf1 > *rdf2) return 1;
1138         }
1139         return 0;
1140 }
1141
1142 /** Compare two RRs skipping the REVOKED bit */
1143 static int
1144 ldns_rr_compare_skip_revbit(const ldns_rr* rr1, const ldns_rr* rr2, int* result)
1145 {
1146         size_t rr1_len, rr2_len;
1147         ldns_buffer* rr1_buf;
1148         ldns_buffer* rr2_buf;
1149
1150         *result = ldns_rr_compare_no_rdata(rr1, rr2);
1151         if (*result == 0)
1152         {
1153                 rr1_len = ldns_rr_uncompressed_size(rr1);
1154                 rr2_len = ldns_rr_uncompressed_size(rr2);
1155                 rr1_buf = ldns_buffer_new(rr1_len);
1156                 rr2_buf = ldns_buffer_new(rr2_len);
1157                 if(!rr1_buf || !rr2_buf) {
1158                         ldns_buffer_free(rr1_buf);
1159                         ldns_buffer_free(rr2_buf);
1160                         return 0;
1161                 }
1162                 if (ldns_rr2buffer_wire_canonical(rr1_buf, rr1,
1163                         LDNS_SECTION_ANY) != LDNS_STATUS_OK)
1164                 {
1165                         ldns_buffer_free(rr1_buf);
1166                         ldns_buffer_free(rr2_buf);
1167                         return 0;
1168                 }
1169                 if (ldns_rr2buffer_wire_canonical(rr2_buf, rr2,
1170                         LDNS_SECTION_ANY) != LDNS_STATUS_OK) {
1171                         ldns_buffer_free(rr1_buf);
1172                         ldns_buffer_free(rr2_buf);
1173                         return 0;
1174                 }
1175                 *result = ldns_rr_compare_wire_skip_revbit(rr1_buf, rr2_buf);
1176                 ldns_buffer_free(rr1_buf);
1177                 ldns_buffer_free(rr2_buf);
1178         }
1179         return 1;
1180 }
1181
1182
1183 /** compare two trust anchors */
1184 static int
1185 ta_compare(ldns_rr* a, ldns_rr* b, int* result)
1186 {
1187         if (!a && !b)   *result = 0;
1188         else if (!a)    *result = -1;
1189         else if (!b)    *result = 1;
1190         else if (ldns_rr_get_type(a) != ldns_rr_get_type(b))
1191                 *result = (int)ldns_rr_get_type(a) - (int)ldns_rr_get_type(b);
1192         else if (ldns_rr_get_type(a) == LDNS_RR_TYPE_DNSKEY) {
1193                 if(!ldns_rr_compare_skip_revbit(a, b, result))
1194                         return 0;
1195         }
1196         else if (ldns_rr_get_type(a) == LDNS_RR_TYPE_DS)
1197                 *result = ldns_rr_compare(a, b);
1198         else    *result = -1;
1199         return 1;
1200 }
1201
1202 /** 
1203  * Find key
1204  * @param tp: to search in
1205  * @param rr: to look for
1206  * @param result: returns NULL or the ta key looked for.
1207  * @return false on malloc failure during search. if true examine result.
1208  */
1209 static int
1210 find_key(struct trust_anchor* tp, ldns_rr* rr, struct autr_ta** result)
1211 {
1212         struct autr_ta* ta;
1213         int ret;
1214         if(!tp || !rr)
1215                 return 0;
1216         for(ta=tp->autr->keys; ta; ta=ta->next) {
1217                 if(!ta_compare(ta->rr, rr, &ret))
1218                         return 0;
1219                 if(ret == 0) {
1220                         *result = ta;
1221                         return 1;
1222                 }
1223         }
1224         *result = NULL;
1225         return 1;
1226 }
1227
1228 /** add key and clone RR and tp already locked */
1229 static struct autr_ta*
1230 add_key(struct trust_anchor* tp, ldns_rr* rr)
1231 {
1232         ldns_rr* c;
1233         struct autr_ta* ta;
1234         c = ldns_rr_clone(rr);
1235         if(!c) return NULL;
1236         ta = autr_ta_create(c);
1237         if(!ta) {
1238                 ldns_rr_free(c);
1239                 return NULL;
1240         }
1241         /* link in, tp already locked */
1242         ta->next = tp->autr->keys;
1243         tp->autr->keys = ta;
1244         return ta;
1245 }
1246
1247 /** get TTL from DNSKEY rrset */
1248 static time_t
1249 key_ttl(struct ub_packed_rrset_key* k)
1250 {
1251         struct packed_rrset_data* d = (struct packed_rrset_data*)k->entry.data;
1252         return d->ttl;
1253 }
1254
1255 /** update the time values for the trustpoint */
1256 static void
1257 set_tp_times(struct trust_anchor* tp, time_t rrsig_exp_interval, 
1258         time_t origttl, int* changed)
1259 {
1260         time_t x, qi = tp->autr->query_interval, rt = tp->autr->retry_time;
1261         
1262         /* x = MIN(15days, ttl/2, expire/2) */
1263         x = 15 * 24 * 3600;
1264         if(origttl/2 < x)
1265                 x = origttl/2;
1266         if(rrsig_exp_interval/2 < x)
1267                 x = rrsig_exp_interval/2;
1268         /* MAX(1hr, x) */
1269         if(x < 3600)
1270                 tp->autr->query_interval = 3600;
1271         else    tp->autr->query_interval = x;
1272
1273         /* x= MIN(1day, ttl/10, expire/10) */
1274         x = 24 * 3600;
1275         if(origttl/10 < x)
1276                 x = origttl/10;
1277         if(rrsig_exp_interval/10 < x)
1278                 x = rrsig_exp_interval/10;
1279         /* MAX(1hr, x) */
1280         if(x < 3600)
1281                 tp->autr->retry_time = 3600;
1282         else    tp->autr->retry_time = x;
1283
1284         if(qi != tp->autr->query_interval || rt != tp->autr->retry_time) {
1285                 *changed = 1;
1286                 verbose(VERB_ALGO, "orig_ttl is %d", (int)origttl);
1287                 verbose(VERB_ALGO, "rrsig_exp_interval is %d", 
1288                         (int)rrsig_exp_interval);
1289                 verbose(VERB_ALGO, "query_interval: %d, retry_time: %d",
1290                         (int)tp->autr->query_interval, 
1291                         (int)tp->autr->retry_time);
1292         }
1293 }
1294
1295 /** init events to zero */
1296 static void
1297 init_events(struct trust_anchor* tp)
1298 {
1299         struct autr_ta* ta;
1300         for(ta=tp->autr->keys; ta; ta=ta->next) {
1301                 ta->fetched = 0;
1302         }
1303 }
1304
1305 /** check for revoked keys without trusting any other information */
1306 static void
1307 check_contains_revoked(struct module_env* env, struct val_env* ve,
1308         struct trust_anchor* tp, struct ub_packed_rrset_key* dnskey_rrset,
1309         int* changed)
1310 {
1311         ldns_rr_list* r = packed_rrset_to_rr_list(dnskey_rrset, 
1312                 env->scratch_buffer);
1313         size_t i;
1314         if(!r) {
1315                 log_err("malloc failure");
1316                 return;
1317         }
1318         for(i=0; i<ldns_rr_list_rr_count(r); i++) {
1319                 ldns_rr* rr = ldns_rr_list_rr(r, i);
1320                 struct autr_ta* ta = NULL;
1321                 if(ldns_rr_get_type(rr) != LDNS_RR_TYPE_DNSKEY)
1322                         continue;
1323                 if(!rr_is_dnskey_sep(rr) || !rr_is_dnskey_revoked(rr))
1324                         continue; /* not a revoked KSK */
1325                 if(!find_key(tp, rr, &ta)) {
1326                         log_err("malloc failure");
1327                         continue; /* malloc fail in compare*/
1328                 }
1329                 if(!ta)
1330                         continue; /* key not found */
1331                 if(rr_is_selfsigned_revoked(env, ve, dnskey_rrset, i)) {
1332                         /* checked if there is an rrsig signed by this key. */
1333                         log_assert(dnskey_calc_keytag(dnskey_rrset, i) ==
1334                                 ldns_calc_keytag(rr)); /* checks conversion*/
1335                         verbose_key(ta, VERB_ALGO, "is self-signed revoked");
1336                         if(!ta->revoked) 
1337                                 *changed = 1;
1338                         seen_revoked_trustanchor(ta, 1);
1339                         do_revoked(env, ta, changed);
1340                 }
1341         }
1342         ldns_rr_list_deep_free(r);
1343 }
1344
1345 /** See if a DNSKEY is verified by one of the DSes */
1346 static int
1347 key_matches_a_ds(struct module_env* env, struct val_env* ve,
1348         struct ub_packed_rrset_key* dnskey_rrset, size_t key_idx,
1349         struct ub_packed_rrset_key* ds_rrset)
1350 {
1351         struct packed_rrset_data* dd = (struct packed_rrset_data*)
1352                         ds_rrset->entry.data;
1353         size_t ds_idx, num = dd->count;
1354         int d = val_favorite_ds_algo(ds_rrset);
1355         char* reason = "";
1356         for(ds_idx=0; ds_idx<num; ds_idx++) {
1357                 if(!ds_digest_algo_is_supported(ds_rrset, ds_idx) ||
1358                         !ds_key_algo_is_supported(ds_rrset, ds_idx) ||
1359                         ds_get_digest_algo(ds_rrset, ds_idx) != d)
1360                         continue;
1361                 if(ds_get_key_algo(ds_rrset, ds_idx)
1362                    != dnskey_get_algo(dnskey_rrset, key_idx)
1363                    || dnskey_calc_keytag(dnskey_rrset, key_idx)
1364                    != ds_get_keytag(ds_rrset, ds_idx)) {
1365                         continue;
1366                 }
1367                 if(!ds_digest_match_dnskey(env, dnskey_rrset, key_idx,
1368                         ds_rrset, ds_idx)) {
1369                         verbose(VERB_ALGO, "DS match attempt failed");
1370                         continue;
1371                 }
1372                 if(dnskey_verify_rrset(env, ve, dnskey_rrset, 
1373                         dnskey_rrset, key_idx, &reason) == sec_status_secure) {
1374                         return 1;
1375                 } else {
1376                         verbose(VERB_ALGO, "DS match failed because the key "
1377                                 "does not verify the keyset: %s", reason);
1378                 }
1379         }
1380         return 0;
1381 }
1382
1383 /** Set update events */
1384 static int
1385 update_events(struct module_env* env, struct val_env* ve, 
1386         struct trust_anchor* tp, struct ub_packed_rrset_key* dnskey_rrset, 
1387         int* changed)
1388 {
1389         ldns_rr_list* r = packed_rrset_to_rr_list(dnskey_rrset, 
1390                 env->scratch_buffer);
1391         size_t i;
1392         if(!r) 
1393                 return 0;
1394         init_events(tp);
1395         for(i=0; i<ldns_rr_list_rr_count(r); i++) {
1396                 ldns_rr* rr = ldns_rr_list_rr(r, i);
1397                 struct autr_ta* ta = NULL;
1398                 if(ldns_rr_get_type(rr) != LDNS_RR_TYPE_DNSKEY)
1399                         continue;
1400                 if(!rr_is_dnskey_sep(rr))
1401                         continue;
1402                 if(rr_is_dnskey_revoked(rr)) {
1403                         /* self-signed revoked keys already detected before,
1404                          * other revoked keys are not 'added' again */
1405                         continue;
1406                 }
1407                 /* is a key of this type supported?. Note rr_list and
1408                  * packed_rrset are in the same order. */
1409                 if(!dnskey_algo_is_supported(dnskey_rrset, i)) {
1410                         /* skip unknown algorithm key, it is useless to us */
1411                         log_nametypeclass(VERB_DETAIL, "trust point has "
1412                                 "unsupported algorithm at", 
1413                                 tp->name, LDNS_RR_TYPE_DNSKEY, tp->dclass);
1414                         continue;
1415                 }
1416
1417                 /* is it new? if revocation bit set, find the unrevoked key */
1418                 if(!find_key(tp, rr, &ta)) {
1419                         ldns_rr_list_deep_free(r); /* malloc fail in compare*/
1420                         return 0;
1421                 }
1422                 if(!ta) {
1423                         ta = add_key(tp, rr);
1424                         *changed = 1;
1425                         /* first time seen, do we have DSes? if match: VALID */
1426                         if(ta && tp->ds_rrset && key_matches_a_ds(env, ve,
1427                                 dnskey_rrset, i, tp->ds_rrset)) {
1428                                 verbose_key(ta, VERB_ALGO, "verified by DS");
1429                                 ta->s = AUTR_STATE_VALID;
1430                         }
1431                 }
1432                 if(!ta) {
1433                         ldns_rr_list_deep_free(r);
1434                         return 0;
1435                 }
1436                 seen_trustanchor(ta, 1);
1437                 verbose_key(ta, VERB_ALGO, "in DNS response");
1438         }
1439         set_tp_times(tp, min_expiry(env, r), key_ttl(dnskey_rrset), changed);
1440         ldns_rr_list_deep_free(r);
1441         return 1;
1442 }
1443
1444 /**
1445  * Check if the holddown time has already exceeded
1446  * setting: add-holddown: add holddown timer
1447  * setting: del-holddown: del holddown timer
1448  * @param env: environment with current time
1449  * @param ta: trust anchor to check for.
1450  * @param holddown: the timer value
1451  * @return number of seconds the holddown has passed.
1452  */
1453 static time_t
1454 check_holddown(struct module_env* env, struct autr_ta* ta,
1455         unsigned int holddown)
1456 {
1457         time_t elapsed;
1458         if(*env->now < ta->last_change) {
1459                 log_warn("time goes backwards. delaying key holddown");
1460                 return 0;
1461         }
1462         elapsed = *env->now - ta->last_change;
1463         if (elapsed > (time_t)holddown) {
1464                 return elapsed-(time_t)holddown;
1465         }
1466         verbose_key(ta, VERB_ALGO, "holddown time %lld seconds to go",
1467                 (long long) ((time_t)holddown-elapsed));
1468         return 0;
1469 }
1470
1471
1472 /** Set last_change to now */
1473 static void
1474 reset_holddown(struct module_env* env, struct autr_ta* ta, int* changed)
1475 {
1476         ta->last_change = *env->now;
1477         *changed = 1;
1478 }
1479
1480 /** Set the state for this trust anchor */
1481 static void
1482 set_trustanchor_state(struct module_env* env, struct autr_ta* ta, int* changed,
1483         autr_state_t s)
1484 {
1485         verbose_key(ta, VERB_ALGO, "update: %s to %s",
1486                 trustanchor_state2str(ta->s), trustanchor_state2str(s));
1487         ta->s = s;
1488         reset_holddown(env, ta, changed);
1489 }
1490
1491
1492 /** Event: NewKey */
1493 static void
1494 do_newkey(struct module_env* env, struct autr_ta* anchor, int* c)
1495 {
1496         if (anchor->s == AUTR_STATE_START)
1497                 set_trustanchor_state(env, anchor, c, AUTR_STATE_ADDPEND);
1498 }
1499
1500 /** Event: AddTime */
1501 static void
1502 do_addtime(struct module_env* env, struct autr_ta* anchor, int* c)
1503 {
1504         /* This not according to RFC, this is 30 days, but the RFC demands 
1505          * MAX(30days, TTL expire time of first DNSKEY set with this key),
1506          * The value may be too small if a very large TTL was used. */
1507         time_t exceeded = check_holddown(env, anchor, env->cfg->add_holddown);
1508         if (exceeded && anchor->s == AUTR_STATE_ADDPEND) {
1509                 verbose_key(anchor, VERB_ALGO, "add-holddown time exceeded "
1510                         "%lld seconds ago, and pending-count %d",
1511                         (long long)exceeded, anchor->pending_count);
1512                 if(anchor->pending_count >= MIN_PENDINGCOUNT) {
1513                         set_trustanchor_state(env, anchor, c, AUTR_STATE_VALID);
1514                         anchor->pending_count = 0;
1515                         return;
1516                 }
1517                 verbose_key(anchor, VERB_ALGO, "add-holddown time sanity check "
1518                         "failed (pending count: %d)", anchor->pending_count);
1519         }
1520 }
1521
1522 /** Event: RemTime */
1523 static void
1524 do_remtime(struct module_env* env, struct autr_ta* anchor, int* c)
1525 {
1526         time_t exceeded = check_holddown(env, anchor, env->cfg->del_holddown);
1527         if(exceeded && anchor->s == AUTR_STATE_REVOKED) {
1528                 verbose_key(anchor, VERB_ALGO, "del-holddown time exceeded "
1529                         "%lld seconds ago", (long long)exceeded);
1530                 set_trustanchor_state(env, anchor, c, AUTR_STATE_REMOVED);
1531         }
1532 }
1533
1534 /** Event: KeyRem */
1535 static void
1536 do_keyrem(struct module_env* env, struct autr_ta* anchor, int* c)
1537 {
1538         if(anchor->s == AUTR_STATE_ADDPEND) {
1539                 set_trustanchor_state(env, anchor, c, AUTR_STATE_START);
1540                 anchor->pending_count = 0;
1541         } else if(anchor->s == AUTR_STATE_VALID)
1542                 set_trustanchor_state(env, anchor, c, AUTR_STATE_MISSING);
1543 }
1544
1545 /** Event: KeyPres */
1546 static void
1547 do_keypres(struct module_env* env, struct autr_ta* anchor, int* c)
1548 {
1549         if(anchor->s == AUTR_STATE_MISSING)
1550                 set_trustanchor_state(env, anchor, c, AUTR_STATE_VALID);
1551 }
1552
1553 /* Event: Revoked */
1554 static void
1555 do_revoked(struct module_env* env, struct autr_ta* anchor, int* c)
1556 {
1557         if(anchor->s == AUTR_STATE_VALID || anchor->s == AUTR_STATE_MISSING) {
1558                 set_trustanchor_state(env, anchor, c, AUTR_STATE_REVOKED);
1559                 verbose_key(anchor, VERB_ALGO, "old id, prior to revocation");
1560                 revoke_dnskey(anchor, 0);
1561                 verbose_key(anchor, VERB_ALGO, "new id, after revocation");
1562         }
1563 }
1564
1565 /** Do statestable transition matrix for anchor */
1566 static void
1567 anchor_state_update(struct module_env* env, struct autr_ta* anchor, int* c)
1568 {
1569         log_assert(anchor);
1570         switch(anchor->s) {
1571         /* START */
1572         case AUTR_STATE_START:
1573                 /* NewKey: ADDPEND */
1574                 if (anchor->fetched)
1575                         do_newkey(env, anchor, c);
1576                 break;
1577         /* ADDPEND */
1578         case AUTR_STATE_ADDPEND:
1579                 /* KeyRem: START */
1580                 if (!anchor->fetched)
1581                         do_keyrem(env, anchor, c);
1582                 /* AddTime: VALID */
1583                 else    do_addtime(env, anchor, c);
1584                 break;
1585         /* VALID */
1586         case AUTR_STATE_VALID:
1587                 /* RevBit: REVOKED */
1588                 if (anchor->revoked)
1589                         do_revoked(env, anchor, c);
1590                 /* KeyRem: MISSING */
1591                 else if (!anchor->fetched)
1592                         do_keyrem(env, anchor, c);
1593                 else if(!anchor->last_change) {
1594                         verbose_key(anchor, VERB_ALGO, "first seen");
1595                         reset_holddown(env, anchor, c);
1596                 }
1597                 break;
1598         /* MISSING */
1599         case AUTR_STATE_MISSING:
1600                 /* RevBit: REVOKED */
1601                 if (anchor->revoked)
1602                         do_revoked(env, anchor, c);
1603                 /* KeyPres */
1604                 else if (anchor->fetched)
1605                         do_keypres(env, anchor, c);
1606                 break;
1607         /* REVOKED */
1608         case AUTR_STATE_REVOKED:
1609                 if (anchor->fetched)
1610                         reset_holddown(env, anchor, c);
1611                 /* RemTime: REMOVED */
1612                 else    do_remtime(env, anchor, c);
1613                 break;
1614         /* REMOVED */
1615         case AUTR_STATE_REMOVED:
1616         default:
1617                 break;
1618         }
1619 }
1620
1621 /** if ZSK init then trust KSKs */
1622 static int
1623 init_zsk_to_ksk(struct module_env* env, struct trust_anchor* tp, int* changed)
1624 {
1625         /* search for VALID ZSKs */
1626         struct autr_ta* anchor;
1627         int validzsk = 0;
1628         int validksk = 0;
1629         for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
1630                 /* last_change test makes sure it was manually configured */
1631                 if (ldns_rr_get_type(anchor->rr) == LDNS_RR_TYPE_DNSKEY &&
1632                         anchor->last_change == 0 && 
1633                         !rr_is_dnskey_sep(anchor->rr) &&
1634                         anchor->s == AUTR_STATE_VALID)
1635                         validzsk++;
1636         }
1637         if(validzsk == 0)
1638                 return 0;
1639         for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
1640                 if (rr_is_dnskey_sep(anchor->rr) && 
1641                         anchor->s == AUTR_STATE_ADDPEND) {
1642                         verbose_key(anchor, VERB_ALGO, "trust KSK from "
1643                                 "ZSK(config)");
1644                         set_trustanchor_state(env, anchor, changed, 
1645                                 AUTR_STATE_VALID);
1646                         validksk++;
1647                 }
1648         }
1649         return validksk;
1650 }
1651
1652 /** Remove missing trustanchors so the list does not grow forever */
1653 static void
1654 remove_missing_trustanchors(struct module_env* env, struct trust_anchor* tp,
1655         int* changed)
1656 {
1657         struct autr_ta* anchor;
1658         time_t exceeded;
1659         int valid = 0;
1660         /* see if we have anchors that are valid */
1661         for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
1662                 /* Only do KSKs */
1663                 if (!rr_is_dnskey_sep(anchor->rr))
1664                         continue;
1665                 if (anchor->s == AUTR_STATE_VALID)
1666                         valid++;
1667         }
1668         /* if there are no SEP Valid anchors, see if we started out with
1669          * a ZSK (last-change=0) anchor, which is VALID and there are KSKs
1670          * now that can be made valid.  Do this immediately because there
1671          * is no guarantee that the ZSKs get announced long enough.  Usually
1672          * this is immediately after init with a ZSK trusted, unless the domain
1673          * was not advertising any KSKs at all.  In which case we perfectly
1674          * track the zero number of KSKs. */
1675         if(valid == 0) {
1676                 valid = init_zsk_to_ksk(env, tp, changed);
1677                 if(valid == 0)
1678                         return;
1679         }
1680         
1681         for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
1682                 /* ignore ZSKs if newly added */
1683                 if(anchor->s == AUTR_STATE_START)
1684                         continue;
1685                 /* remove ZSKs if a KSK is present */
1686                 if (!rr_is_dnskey_sep(anchor->rr)) {
1687                         if(valid > 0) {
1688                                 verbose_key(anchor, VERB_ALGO, "remove ZSK "
1689                                         "[%d key(s) VALID]", valid);
1690                                 set_trustanchor_state(env, anchor, changed, 
1691                                         AUTR_STATE_REMOVED);
1692                         }
1693                         continue;
1694                 }
1695                 /* Only do MISSING keys */
1696                 if (anchor->s != AUTR_STATE_MISSING)
1697                         continue;
1698                 if(env->cfg->keep_missing == 0)
1699                         continue; /* keep forever */
1700
1701                 exceeded = check_holddown(env, anchor, env->cfg->keep_missing);
1702                 /* If keep_missing has exceeded and we still have more than 
1703                  * one valid KSK: remove missing trust anchor */
1704                 if (exceeded && valid > 0) {
1705                         verbose_key(anchor, VERB_ALGO, "keep-missing time "
1706                                 "exceeded %lld seconds ago, [%d key(s) VALID]",
1707                                 (long long)exceeded, valid);
1708                         set_trustanchor_state(env, anchor, changed, 
1709                                 AUTR_STATE_REMOVED);
1710                 }
1711         }
1712 }
1713
1714 /** Do the statetable from RFC5011 transition matrix */
1715 static int
1716 do_statetable(struct module_env* env, struct trust_anchor* tp, int* changed)
1717 {
1718         struct autr_ta* anchor;
1719         for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
1720                 /* Only do KSKs */
1721                 if(!rr_is_dnskey_sep(anchor->rr))
1722                         continue;
1723                 anchor_state_update(env, anchor, changed);
1724         }
1725         remove_missing_trustanchors(env, tp, changed);
1726         return 1;
1727 }
1728
1729 /** See if time alone makes ADDPEND to VALID transition */
1730 static void
1731 autr_holddown_exceed(struct module_env* env, struct trust_anchor* tp, int* c)
1732 {
1733         struct autr_ta* anchor;
1734         for(anchor = tp->autr->keys; anchor; anchor = anchor->next) {
1735                 if(rr_is_dnskey_sep(anchor->rr) && 
1736                         anchor->s == AUTR_STATE_ADDPEND)
1737                         do_addtime(env, anchor, c);
1738         }
1739 }
1740
1741 /** cleanup key list */
1742 static void
1743 autr_cleanup_keys(struct trust_anchor* tp)
1744 {
1745         struct autr_ta* p, **prevp;
1746         prevp = &tp->autr->keys;
1747         p = tp->autr->keys;
1748         while(p) {
1749                 /* do we want to remove this key? */
1750                 if(p->s == AUTR_STATE_START || p->s == AUTR_STATE_REMOVED ||
1751                         ldns_rr_get_type(p->rr) != LDNS_RR_TYPE_DNSKEY) {
1752                         struct autr_ta* np = p->next;
1753                         /* remove */
1754                         ldns_rr_free(p->rr);
1755                         free(p);
1756                         /* snip and go to next item */
1757                         *prevp = np;
1758                         p = np;
1759                         continue;
1760                 }
1761                 /* remove pending counts if no longer pending */
1762                 if(p->s != AUTR_STATE_ADDPEND)
1763                         p->pending_count = 0;
1764                 prevp = &p->next;
1765                 p = p->next;
1766         }
1767 }
1768
1769 /** calculate next probe time */
1770 static time_t
1771 calc_next_probe(struct module_env* env, time_t wait)
1772 {
1773         /* make it random, 90-100% */
1774         time_t rnd, rest;
1775         if(wait < 3600)
1776                 wait = 3600;
1777         rnd = wait/10;
1778         rest = wait-rnd;
1779         rnd = (time_t)ub_random_max(env->rnd, (long int)rnd);
1780         return (time_t)(*env->now + rest + rnd);
1781 }
1782
1783 /** what is first probe time (anchors must be locked) */
1784 static time_t
1785 wait_probe_time(struct val_anchors* anchors)
1786 {
1787         rbnode_t* t = rbtree_first(&anchors->autr->probe);
1788         if(t != RBTREE_NULL) 
1789                 return ((struct trust_anchor*)t->key)->autr->next_probe_time;
1790         return 0;
1791 }
1792
1793 /** reset worker timer */
1794 static void
1795 reset_worker_timer(struct module_env* env)
1796 {
1797         struct timeval tv;
1798 #ifndef S_SPLINT_S
1799         time_t next = (time_t)wait_probe_time(env->anchors);
1800         /* in case this is libunbound, no timer */
1801         if(!env->probe_timer)
1802                 return;
1803         if(next > *env->now)
1804                 tv.tv_sec = (time_t)(next - *env->now);
1805         else    tv.tv_sec = 0;
1806 #endif
1807         tv.tv_usec = 0;
1808         comm_timer_set(env->probe_timer, &tv);
1809         verbose(VERB_ALGO, "scheduled next probe in %lld sec", (long long)tv.tv_sec);
1810 }
1811
1812 /** set next probe for trust anchor */
1813 static int
1814 set_next_probe(struct module_env* env, struct trust_anchor* tp,
1815         struct ub_packed_rrset_key* dnskey_rrset)
1816 {
1817         struct trust_anchor key, *tp2;
1818         time_t mold, mnew;
1819         /* use memory allocated in rrset for temporary name storage */
1820         key.node.key = &key;
1821         key.name = dnskey_rrset->rk.dname;
1822         key.namelen = dnskey_rrset->rk.dname_len;
1823         key.namelabs = dname_count_labels(key.name);
1824         key.dclass = tp->dclass;
1825         lock_basic_unlock(&tp->lock);
1826
1827         /* fetch tp again and lock anchors, so that we can modify the trees */
1828         lock_basic_lock(&env->anchors->lock);
1829         tp2 = (struct trust_anchor*)rbtree_search(env->anchors->tree, &key);
1830         if(!tp2) {
1831                 verbose(VERB_ALGO, "trustpoint was deleted in set_next_probe");
1832                 lock_basic_unlock(&env->anchors->lock);
1833                 return 0;
1834         }
1835         log_assert(tp == tp2);
1836         lock_basic_lock(&tp->lock);
1837
1838         /* schedule */
1839         mold = wait_probe_time(env->anchors);
1840         (void)rbtree_delete(&env->anchors->autr->probe, tp);
1841         tp->autr->next_probe_time = calc_next_probe(env, 
1842                 tp->autr->query_interval);
1843         (void)rbtree_insert(&env->anchors->autr->probe, &tp->autr->pnode);
1844         mnew = wait_probe_time(env->anchors);
1845
1846         lock_basic_unlock(&env->anchors->lock);
1847         verbose(VERB_ALGO, "next probe set in %d seconds", 
1848                 (int)tp->autr->next_probe_time - (int)*env->now);
1849         if(mold != mnew) {
1850                 reset_worker_timer(env);
1851         }
1852         return 1;
1853 }
1854
1855 /** Revoke and Delete a trust point */
1856 static void
1857 autr_tp_remove(struct module_env* env, struct trust_anchor* tp,
1858         struct ub_packed_rrset_key* dnskey_rrset)
1859 {
1860         struct trust_anchor* del_tp;
1861         struct trust_anchor key;
1862         struct autr_point_data pd;
1863         time_t mold, mnew;
1864
1865         log_nametypeclass(VERB_OPS, "trust point was revoked",
1866                 tp->name, LDNS_RR_TYPE_DNSKEY, tp->dclass);
1867         tp->autr->revoked = 1;
1868
1869         /* use space allocated for dnskey_rrset to save name of anchor */
1870         memset(&key, 0, sizeof(key));
1871         memset(&pd, 0, sizeof(pd));
1872         key.autr = &pd;
1873         key.node.key = &key;
1874         pd.pnode.key = &key;
1875         pd.next_probe_time = tp->autr->next_probe_time;
1876         key.name = dnskey_rrset->rk.dname;
1877         key.namelen = tp->namelen;
1878         key.namelabs = tp->namelabs;
1879         key.dclass = tp->dclass;
1880
1881         /* unlock */
1882         lock_basic_unlock(&tp->lock);
1883
1884         /* take from tree. It could be deleted by someone else,hence (void). */
1885         lock_basic_lock(&env->anchors->lock);
1886         del_tp = (struct trust_anchor*)rbtree_delete(env->anchors->tree, &key);
1887         mold = wait_probe_time(env->anchors);
1888         (void)rbtree_delete(&env->anchors->autr->probe, &key);
1889         mnew = wait_probe_time(env->anchors);
1890         anchors_init_parents_locked(env->anchors);
1891         lock_basic_unlock(&env->anchors->lock);
1892
1893         /* if !del_tp then the trust point is no longer present in the tree,
1894          * it was deleted by someone else, who will write the zonefile and
1895          * clean up the structure */
1896         if(del_tp) {
1897                 /* save on disk */
1898                 del_tp->autr->next_probe_time = 0; /* no more probing for it */
1899                 autr_write_file(env, del_tp);
1900
1901                 /* delete */
1902                 autr_point_delete(del_tp);
1903         }
1904         if(mold != mnew) {
1905                 reset_worker_timer(env);
1906         }
1907 }
1908
1909 int autr_process_prime(struct module_env* env, struct val_env* ve,
1910         struct trust_anchor* tp, struct ub_packed_rrset_key* dnskey_rrset)
1911 {
1912         int changed = 0;
1913         log_assert(tp && tp->autr);
1914         /* autotrust update trust anchors */
1915         /* the tp is locked, and stays locked unless it is deleted */
1916
1917         /* we could just catch the anchor here while another thread
1918          * is busy deleting it. Just unlock and let the other do its job */
1919         if(tp->autr->revoked) {
1920                 log_nametypeclass(VERB_ALGO, "autotrust not processed, "
1921                         "trust point revoked", tp->name, 
1922                         LDNS_RR_TYPE_DNSKEY, tp->dclass);
1923                 lock_basic_unlock(&tp->lock);
1924                 return 0; /* it is revoked */
1925         }
1926
1927         /* query_dnskeys(): */
1928         tp->autr->last_queried = *env->now;
1929
1930         log_nametypeclass(VERB_ALGO, "autotrust process for",
1931                 tp->name, LDNS_RR_TYPE_DNSKEY, tp->dclass);
1932         /* see if time alone makes some keys valid */
1933         autr_holddown_exceed(env, tp, &changed);
1934         if(changed) {
1935                 verbose(VERB_ALGO, "autotrust: morekeys, reassemble");
1936                 if(!autr_assemble(tp)) {
1937                         log_err("malloc failure assembling autotrust keys");
1938                         return 1; /* unchanged */
1939                 }
1940         }
1941         /* did we get any data? */
1942         if(!dnskey_rrset) {
1943                 verbose(VERB_ALGO, "autotrust: no dnskey rrset");
1944                 /* no update of query_failed, because then we would have
1945                  * to write to disk. But we cannot because we maybe are
1946                  * still 'initialising' with DS records, that we cannot write
1947                  * in the full format (which only contains KSKs). */
1948                 return 1; /* trust point exists */
1949         }
1950         /* check for revoked keys to remove immediately */
1951         check_contains_revoked(env, ve, tp, dnskey_rrset, &changed);
1952         if(changed) {
1953                 verbose(VERB_ALGO, "autotrust: revokedkeys, reassemble");
1954                 if(!autr_assemble(tp)) {
1955                         log_err("malloc failure assembling autotrust keys");
1956                         return 1; /* unchanged */
1957                 }
1958                 if(!tp->ds_rrset && !tp->dnskey_rrset) {
1959                         /* no more keys, all are revoked */
1960                         /* this is a success for this probe attempt */
1961                         tp->autr->last_success = *env->now;
1962                         autr_tp_remove(env, tp, dnskey_rrset);
1963                         return 0; /* trust point removed */
1964                 }
1965         }
1966         /* verify the dnskey rrset and see if it is valid. */
1967         if(!verify_dnskey(env, ve, tp, dnskey_rrset)) {
1968                 verbose(VERB_ALGO, "autotrust: dnskey did not verify.");
1969                 /* only increase failure count if this is not the first prime,
1970                  * this means there was a previous succesful probe */
1971                 if(tp->autr->last_success) {
1972                         tp->autr->query_failed += 1;
1973                         autr_write_file(env, tp);
1974                 }
1975                 return 1; /* trust point exists */
1976         }
1977
1978         tp->autr->last_success = *env->now;
1979         tp->autr->query_failed = 0;
1980
1981         /* Add new trust anchors to the data structure
1982          * - note which trust anchors are seen this probe.
1983          * Set trustpoint query_interval and retry_time.
1984          * - find minimum rrsig expiration interval
1985          */
1986         if(!update_events(env, ve, tp, dnskey_rrset, &changed)) {
1987                 log_err("malloc failure in autotrust update_events. "
1988                         "trust point unchanged.");
1989                 return 1; /* trust point unchanged, so exists */
1990         }
1991
1992         /* - for every SEP key do the 5011 statetable.
1993          * - remove missing trustanchors (if veryold and we have new anchors).
1994          */
1995         if(!do_statetable(env, tp, &changed)) {
1996                 log_err("malloc failure in autotrust do_statetable. "
1997                         "trust point unchanged.");
1998                 return 1; /* trust point unchanged, so exists */
1999         }
2000
2001         autr_cleanup_keys(tp);
2002         if(!set_next_probe(env, tp, dnskey_rrset))
2003                 return 0; /* trust point does not exist */
2004         autr_write_file(env, tp);
2005         if(changed) {
2006                 verbose(VERB_ALGO, "autotrust: changed, reassemble");
2007                 if(!autr_assemble(tp)) {
2008                         log_err("malloc failure assembling autotrust keys");
2009                         return 1; /* unchanged */
2010                 }
2011                 if(!tp->ds_rrset && !tp->dnskey_rrset) {
2012                         /* no more keys, all are revoked */
2013                         autr_tp_remove(env, tp, dnskey_rrset);
2014                         return 0; /* trust point removed */
2015                 }
2016         } else verbose(VERB_ALGO, "autotrust: no changes");
2017         
2018         return 1; /* trust point exists */
2019 }
2020
2021 /** debug print a trust anchor key */
2022 static void 
2023 autr_debug_print_ta(struct autr_ta* ta)
2024 {
2025         char buf[32];
2026         char* str = ldns_rr2str(ta->rr);
2027         if(!str) {
2028                 log_info("out of memory in debug_print_ta");
2029                 return;
2030         }
2031         if(str && str[0]) str[strlen(str)-1]=0; /* remove newline */
2032         ctime_r(&ta->last_change, buf);
2033         if(buf[0]) buf[strlen(buf)-1]=0; /* remove newline */
2034         log_info("[%s] %s ;;state:%d ;;pending_count:%d%s%s last:%s",
2035                 trustanchor_state2str(ta->s), str, ta->s, ta->pending_count,
2036                 ta->fetched?" fetched":"", ta->revoked?" revoked":"", buf);
2037         free(str);
2038 }
2039
2040 /** debug print a trust point */
2041 static void 
2042 autr_debug_print_tp(struct trust_anchor* tp)
2043 {
2044         struct autr_ta* ta;
2045         char buf[257];
2046         if(!tp->autr)
2047                 return;
2048         dname_str(tp->name, buf);
2049         log_info("trust point %s : %d", buf, (int)tp->dclass);
2050         log_info("assembled %d DS and %d DNSKEYs", 
2051                 (int)tp->numDS, (int)tp->numDNSKEY);
2052         if(0) { /* turned off because it prints to stderr */
2053                 ldns_buffer* bf = ldns_buffer_new(70000);
2054                 ldns_rr_list* list;
2055                 if(tp->ds_rrset) {
2056                         list = packed_rrset_to_rr_list(tp->ds_rrset, bf);
2057                         ldns_rr_list_print(stderr, list);
2058                         ldns_rr_list_deep_free(list);
2059                 }
2060                 if(tp->dnskey_rrset) {
2061                         list = packed_rrset_to_rr_list(tp->dnskey_rrset, bf);
2062                         ldns_rr_list_print(stderr, list);
2063                         ldns_rr_list_deep_free(list);
2064                 }
2065                 ldns_buffer_free(bf);
2066         }
2067         log_info("file %s", tp->autr->file);
2068         ctime_r(&tp->autr->last_queried, buf);
2069         if(buf[0]) buf[strlen(buf)-1]=0; /* remove newline */
2070         log_info("last_queried: %u %s", (unsigned)tp->autr->last_queried, buf);
2071         ctime_r(&tp->autr->last_success, buf);
2072         if(buf[0]) buf[strlen(buf)-1]=0; /* remove newline */
2073         log_info("last_success: %u %s", (unsigned)tp->autr->last_success, buf);
2074         ctime_r(&tp->autr->next_probe_time, buf);
2075         if(buf[0]) buf[strlen(buf)-1]=0; /* remove newline */
2076         log_info("next_probe_time: %u %s", (unsigned)tp->autr->next_probe_time,
2077                 buf);
2078         log_info("query_interval: %u", (unsigned)tp->autr->query_interval);
2079         log_info("retry_time: %u", (unsigned)tp->autr->retry_time);
2080         log_info("query_failed: %u", (unsigned)tp->autr->query_failed);
2081                 
2082         for(ta=tp->autr->keys; ta; ta=ta->next) {
2083                 autr_debug_print_ta(ta);
2084         }
2085 }
2086
2087 void 
2088 autr_debug_print(struct val_anchors* anchors)
2089 {
2090         struct trust_anchor* tp;
2091         lock_basic_lock(&anchors->lock);
2092         RBTREE_FOR(tp, struct trust_anchor*, anchors->tree) {
2093                 lock_basic_lock(&tp->lock);
2094                 autr_debug_print_tp(tp);
2095                 lock_basic_unlock(&tp->lock);
2096         }
2097         lock_basic_unlock(&anchors->lock);
2098 }
2099
2100 void probe_answer_cb(void* arg, int ATTR_UNUSED(rcode), 
2101         ldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(sec),
2102         char* ATTR_UNUSED(why_bogus))
2103 {
2104         /* retry was set before the query was done,
2105          * re-querytime is set when query succeeded, but that may not
2106          * have reset this timer because the query could have been
2107          * handled by another thread. In that case, this callback would
2108          * get called after the original timeout is done. 
2109          * By not resetting the timer, it may probe more often, but not
2110          * less often.
2111          * Unless the new lookup resulted in smaller TTLs and thus smaller
2112          * timeout values. In that case one old TTL could be mistakenly done.
2113          */
2114         struct module_env* env = (struct module_env*)arg;
2115         verbose(VERB_ALGO, "autotrust probe answer cb");
2116         reset_worker_timer(env);
2117 }
2118
2119 /** probe a trust anchor DNSKEY and unlocks tp */
2120 static void
2121 probe_anchor(struct module_env* env, struct trust_anchor* tp)
2122 {
2123         struct query_info qinfo;
2124         uint16_t qflags = BIT_RD;
2125         struct edns_data edns;
2126         ldns_buffer* buf = env->scratch_buffer;
2127         qinfo.qname = regional_alloc_init(env->scratch, tp->name, tp->namelen);
2128         if(!qinfo.qname) {
2129                 log_err("out of memory making 5011 probe");
2130                 return;
2131         }
2132         qinfo.qname_len = tp->namelen;
2133         qinfo.qtype = LDNS_RR_TYPE_DNSKEY;
2134         qinfo.qclass = tp->dclass;
2135         log_query_info(VERB_ALGO, "autotrust probe", &qinfo);
2136         verbose(VERB_ALGO, "retry probe set in %d seconds", 
2137                 (int)tp->autr->next_probe_time - (int)*env->now);
2138         edns.edns_present = 1;
2139         edns.ext_rcode = 0;
2140         edns.edns_version = 0;
2141         edns.bits = EDNS_DO;
2142         if(ldns_buffer_capacity(buf) < 65535)
2143                 edns.udp_size = (uint16_t)ldns_buffer_capacity(buf);
2144         else    edns.udp_size = 65535;
2145
2146         /* can't hold the lock while mesh_run is processing */
2147         lock_basic_unlock(&tp->lock);
2148
2149         /* delete the DNSKEY from rrset and key cache so an active probe
2150          * is done. First the rrset so another thread does not use it
2151          * to recreate the key entry in a race condition. */
2152         rrset_cache_remove(env->rrset_cache, qinfo.qname, qinfo.qname_len,
2153                 qinfo.qtype, qinfo.qclass, 0);
2154         key_cache_remove(env->key_cache, qinfo.qname, qinfo.qname_len, 
2155                 qinfo.qclass);
2156
2157         if(!mesh_new_callback(env->mesh, &qinfo, qflags, &edns, buf, 0, 
2158                 &probe_answer_cb, env)) {
2159                 log_err("out of memory making 5011 probe");
2160         }
2161 }
2162
2163 /** fetch first to-probe trust-anchor and lock it and set retrytime */
2164 static struct trust_anchor*
2165 todo_probe(struct module_env* env, time_t* next)
2166 {
2167         struct trust_anchor* tp;
2168         rbnode_t* el;
2169         /* get first one */
2170         lock_basic_lock(&env->anchors->lock);
2171         if( (el=rbtree_first(&env->anchors->autr->probe)) == RBTREE_NULL) {
2172                 /* in case of revoked anchors */
2173                 lock_basic_unlock(&env->anchors->lock);
2174                 return NULL;
2175         }
2176         tp = (struct trust_anchor*)el->key;
2177         lock_basic_lock(&tp->lock);
2178
2179         /* is it eligible? */
2180         if((time_t)tp->autr->next_probe_time > *env->now) {
2181                 /* no more to probe */
2182                 *next = (time_t)tp->autr->next_probe_time - *env->now;
2183                 lock_basic_unlock(&tp->lock);
2184                 lock_basic_unlock(&env->anchors->lock);
2185                 return NULL;
2186         }
2187
2188         /* reset its next probe time */
2189         (void)rbtree_delete(&env->anchors->autr->probe, tp);
2190         tp->autr->next_probe_time = calc_next_probe(env, tp->autr->retry_time);
2191         (void)rbtree_insert(&env->anchors->autr->probe, &tp->autr->pnode);
2192         lock_basic_unlock(&env->anchors->lock);
2193
2194         return tp;
2195 }
2196
2197 time_t 
2198 autr_probe_timer(struct module_env* env)
2199 {
2200         struct trust_anchor* tp;
2201         time_t next_probe = 3600;
2202         int num = 0;
2203         verbose(VERB_ALGO, "autotrust probe timer callback");
2204         /* while there are still anchors to probe */
2205         while( (tp = todo_probe(env, &next_probe)) ) {
2206                 /* make a probe for this anchor */
2207                 probe_anchor(env, tp);
2208                 num++;
2209         }
2210         regional_free_all(env->scratch);
2211         if(num == 0)
2212                 return 0; /* no trust points to probe */
2213         verbose(VERB_ALGO, "autotrust probe timer %d callbacks done", num);
2214         return next_probe;
2215 }