]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/unbound/services/authzone.c
Update Apache Serf to 1.3.9 to support OpenSSL 1.1.1.
[FreeBSD/FreeBSD.git] / contrib / unbound / services / authzone.c
1 /*
2  * services/authzone.c - authoritative zone that is locally hosted.
3  *
4  * Copyright (c) 2017, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  * 
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  * 
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  * 
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  * 
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35
36 /**
37  * \file
38  *
39  * This file contains the functions for an authority zone.  This zone
40  * is queried by the iterator, just like a stub or forward zone, but then
41  * the data is locally held.
42  */
43
44 #include "config.h"
45 #include "services/authzone.h"
46 #include "util/data/dname.h"
47 #include "util/data/msgparse.h"
48 #include "util/data/msgreply.h"
49 #include "util/data/msgencode.h"
50 #include "util/data/packed_rrset.h"
51 #include "util/regional.h"
52 #include "util/net_help.h"
53 #include "util/netevent.h"
54 #include "util/config_file.h"
55 #include "util/log.h"
56 #include "util/module.h"
57 #include "util/random.h"
58 #include "services/cache/dns.h"
59 #include "services/outside_network.h"
60 #include "services/listen_dnsport.h"
61 #include "services/mesh.h"
62 #include "sldns/rrdef.h"
63 #include "sldns/pkthdr.h"
64 #include "sldns/sbuffer.h"
65 #include "sldns/str2wire.h"
66 #include "sldns/wire2str.h"
67 #include "sldns/parseutil.h"
68 #include "sldns/keyraw.h"
69 #include "validator/val_nsec3.h"
70 #include "validator/val_secalgo.h"
71 #include <ctype.h>
72
73 /** bytes to use for NSEC3 hash buffer. 20 for sha1 */
74 #define N3HASHBUFLEN 32
75 /** max number of CNAMEs we are willing to follow (in one answer) */
76 #define MAX_CNAME_CHAIN 8
77 /** timeout for probe packets for SOA */
78 #define AUTH_PROBE_TIMEOUT 100 /* msec */
79 /** when to stop with SOA probes (when exponential timeouts exceed this) */
80 #define AUTH_PROBE_TIMEOUT_STOP 1000 /* msec */
81 /* auth transfer timeout for TCP connections, in msec */
82 #define AUTH_TRANSFER_TIMEOUT 10000 /* msec */
83 /* auth transfer max backoff for failed tranfers and probes */
84 #define AUTH_TRANSFER_MAX_BACKOFF 86400 /* sec */
85 /* auth http port number */
86 #define AUTH_HTTP_PORT 80
87 /* auth https port number */
88 #define AUTH_HTTPS_PORT 443
89 /* max depth for nested $INCLUDEs */
90 #define MAX_INCLUDE_DEPTH 10
91
92 /** pick up nextprobe task to start waiting to perform transfer actions */
93 static void xfr_set_timeout(struct auth_xfer* xfr, struct module_env* env,
94         int failure, int lookup_only);
95 /** move to sending the probe packets, next if fails. task_probe */
96 static void xfr_probe_send_or_end(struct auth_xfer* xfr,
97         struct module_env* env);
98 /** pick up probe task with specified(or NULL) destination first,
99  * or transfer task if nothing to probe, or false if already in progress */
100 static int xfr_start_probe(struct auth_xfer* xfr, struct module_env* env,
101         struct auth_master* spec);
102 /** delete xfer structure (not its tree entry) */
103 static void auth_xfer_delete(struct auth_xfer* xfr);
104
105 /** create new dns_msg */
106 static struct dns_msg*
107 msg_create(struct regional* region, struct query_info* qinfo)
108 {
109         struct dns_msg* msg = (struct dns_msg*)regional_alloc(region,
110                 sizeof(struct dns_msg));
111         if(!msg)
112                 return NULL;
113         msg->qinfo.qname = regional_alloc_init(region, qinfo->qname,
114                 qinfo->qname_len);
115         if(!msg->qinfo.qname)
116                 return NULL;
117         msg->qinfo.qname_len = qinfo->qname_len;
118         msg->qinfo.qtype = qinfo->qtype;
119         msg->qinfo.qclass = qinfo->qclass;
120         msg->qinfo.local_alias = NULL;
121         /* non-packed reply_info, because it needs to grow the array */
122         msg->rep = (struct reply_info*)regional_alloc_zero(region,
123                 sizeof(struct reply_info)-sizeof(struct rrset_ref));
124         if(!msg->rep)
125                 return NULL;
126         msg->rep->flags = (uint16_t)(BIT_QR | BIT_AA);
127         msg->rep->authoritative = 1;
128         msg->rep->qdcount = 1;
129         /* rrsets is NULL, no rrsets yet */
130         return msg;
131 }
132
133 /** grow rrset array by one in msg */
134 static int
135 msg_grow_array(struct regional* region, struct dns_msg* msg)
136 {
137         if(msg->rep->rrsets == NULL) {
138                 msg->rep->rrsets = regional_alloc_zero(region,
139                         sizeof(struct ub_packed_rrset_key*)*(msg->rep->rrset_count+1));
140                 if(!msg->rep->rrsets)
141                         return 0;
142         } else {
143                 struct ub_packed_rrset_key** rrsets_old = msg->rep->rrsets;
144                 msg->rep->rrsets = regional_alloc_zero(region,
145                         sizeof(struct ub_packed_rrset_key*)*(msg->rep->rrset_count+1));
146                 if(!msg->rep->rrsets)
147                         return 0;
148                 memmove(msg->rep->rrsets, rrsets_old,
149                         sizeof(struct ub_packed_rrset_key*)*msg->rep->rrset_count);
150         }
151         return 1;
152 }
153
154 /** get ttl of rrset */
155 static time_t
156 get_rrset_ttl(struct ub_packed_rrset_key* k)
157 {
158         struct packed_rrset_data* d = (struct packed_rrset_data*)
159                 k->entry.data;
160         return d->ttl;
161 }
162
163 /** Copy rrset into region from domain-datanode and packet rrset */
164 static struct ub_packed_rrset_key*
165 auth_packed_rrset_copy_region(struct auth_zone* z, struct auth_data* node,
166         struct auth_rrset* rrset, struct regional* region, time_t adjust)
167 {
168         struct ub_packed_rrset_key key;
169         memset(&key, 0, sizeof(key));
170         key.entry.key = &key;
171         key.entry.data = rrset->data;
172         key.rk.dname = node->name;
173         key.rk.dname_len = node->namelen;
174         key.rk.type = htons(rrset->type);
175         key.rk.rrset_class = htons(z->dclass);
176         key.entry.hash = rrset_key_hash(&key.rk);
177         return packed_rrset_copy_region(&key, region, adjust);
178 }
179
180 /** fix up msg->rep TTL and prefetch ttl */
181 static void
182 msg_ttl(struct dns_msg* msg)
183 {
184         if(msg->rep->rrset_count == 0) return;
185         if(msg->rep->rrset_count == 1) {
186                 msg->rep->ttl = get_rrset_ttl(msg->rep->rrsets[0]);
187                 msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
188         } else if(get_rrset_ttl(msg->rep->rrsets[msg->rep->rrset_count-1]) <
189                 msg->rep->ttl) {
190                 msg->rep->ttl = get_rrset_ttl(msg->rep->rrsets[
191                         msg->rep->rrset_count-1]);
192                 msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
193         }
194 }
195
196 /** see if rrset is a duplicate in the answer message */
197 static int
198 msg_rrset_duplicate(struct dns_msg* msg, uint8_t* nm, size_t nmlen,
199         uint16_t type, uint16_t dclass)
200 {
201         size_t i;
202         for(i=0; i<msg->rep->rrset_count; i++) {
203                 struct ub_packed_rrset_key* k = msg->rep->rrsets[i];
204                 if(ntohs(k->rk.type) == type && k->rk.dname_len == nmlen &&
205                         ntohs(k->rk.rrset_class) == dclass &&
206                         query_dname_compare(k->rk.dname, nm) == 0)
207                         return 1;
208         }
209         return 0;
210 }
211
212 /** add rrset to answer section (no auth, add rrsets yet) */
213 static int
214 msg_add_rrset_an(struct auth_zone* z, struct regional* region,
215         struct dns_msg* msg, struct auth_data* node, struct auth_rrset* rrset)
216 {
217         log_assert(msg->rep->ns_numrrsets == 0);
218         log_assert(msg->rep->ar_numrrsets == 0);
219         if(!rrset)
220                 return 1;
221         if(msg_rrset_duplicate(msg, node->name, node->namelen, rrset->type,
222                 z->dclass))
223                 return 1;
224         /* grow array */
225         if(!msg_grow_array(region, msg))
226                 return 0;
227         /* copy it */
228         if(!(msg->rep->rrsets[msg->rep->rrset_count] =
229                 auth_packed_rrset_copy_region(z, node, rrset, region, 0)))
230                 return 0;
231         msg->rep->rrset_count++;
232         msg->rep->an_numrrsets++;
233         msg_ttl(msg);
234         return 1;
235 }
236
237 /** add rrset to authority section (no additonal section rrsets yet) */
238 static int
239 msg_add_rrset_ns(struct auth_zone* z, struct regional* region,
240         struct dns_msg* msg, struct auth_data* node, struct auth_rrset* rrset)
241 {
242         log_assert(msg->rep->ar_numrrsets == 0);
243         if(!rrset)
244                 return 1;
245         if(msg_rrset_duplicate(msg, node->name, node->namelen, rrset->type,
246                 z->dclass))
247                 return 1;
248         /* grow array */
249         if(!msg_grow_array(region, msg))
250                 return 0;
251         /* copy it */
252         if(!(msg->rep->rrsets[msg->rep->rrset_count] =
253                 auth_packed_rrset_copy_region(z, node, rrset, region, 0)))
254                 return 0;
255         msg->rep->rrset_count++;
256         msg->rep->ns_numrrsets++;
257         msg_ttl(msg);
258         return 1;
259 }
260
261 /** add rrset to additional section */
262 static int
263 msg_add_rrset_ar(struct auth_zone* z, struct regional* region,
264         struct dns_msg* msg, struct auth_data* node, struct auth_rrset* rrset)
265 {
266         if(!rrset)
267                 return 1;
268         if(msg_rrset_duplicate(msg, node->name, node->namelen, rrset->type,
269                 z->dclass))
270                 return 1;
271         /* grow array */
272         if(!msg_grow_array(region, msg))
273                 return 0;
274         /* copy it */
275         if(!(msg->rep->rrsets[msg->rep->rrset_count] =
276                 auth_packed_rrset_copy_region(z, node, rrset, region, 0)))
277                 return 0;
278         msg->rep->rrset_count++;
279         msg->rep->ar_numrrsets++;
280         msg_ttl(msg);
281         return 1;
282 }
283
284 struct auth_zones* auth_zones_create(void)
285 {
286         struct auth_zones* az = (struct auth_zones*)calloc(1, sizeof(*az));
287         if(!az) {
288                 log_err("out of memory");
289                 return NULL;
290         }
291         rbtree_init(&az->ztree, &auth_zone_cmp);
292         rbtree_init(&az->xtree, &auth_xfer_cmp);
293         lock_rw_init(&az->lock);
294         lock_protect(&az->lock, &az->ztree, sizeof(az->ztree));
295         lock_protect(&az->lock, &az->xtree, sizeof(az->xtree));
296         /* also lock protects the rbnode's in struct auth_zone, auth_xfer */
297         return az;
298 }
299
300 int auth_zone_cmp(const void* z1, const void* z2)
301 {
302         /* first sort on class, so that hierarchy can be maintained within
303          * a class */
304         struct auth_zone* a = (struct auth_zone*)z1;
305         struct auth_zone* b = (struct auth_zone*)z2;
306         int m;
307         if(a->dclass != b->dclass) {
308                 if(a->dclass < b->dclass)
309                         return -1;
310                 return 1;
311         }
312         /* sorted such that higher zones sort before lower zones (their
313          * contents) */
314         return dname_lab_cmp(a->name, a->namelabs, b->name, b->namelabs, &m);
315 }
316
317 int auth_data_cmp(const void* z1, const void* z2)
318 {
319         struct auth_data* a = (struct auth_data*)z1;
320         struct auth_data* b = (struct auth_data*)z2;
321         int m;
322         /* canonical sort, because DNSSEC needs that */
323         return dname_canon_lab_cmp(a->name, a->namelabs, b->name,
324                 b->namelabs, &m);
325 }
326
327 int auth_xfer_cmp(const void* z1, const void* z2)
328 {
329         /* first sort on class, so that hierarchy can be maintained within
330          * a class */
331         struct auth_xfer* a = (struct auth_xfer*)z1;
332         struct auth_xfer* b = (struct auth_xfer*)z2;
333         int m;
334         if(a->dclass != b->dclass) {
335                 if(a->dclass < b->dclass)
336                         return -1;
337                 return 1;
338         }
339         /* sorted such that higher zones sort before lower zones (their
340          * contents) */
341         return dname_lab_cmp(a->name, a->namelabs, b->name, b->namelabs, &m);
342 }
343
344 /** delete auth rrset node */
345 static void
346 auth_rrset_delete(struct auth_rrset* rrset)
347 {
348         if(!rrset) return;
349         free(rrset->data);
350         free(rrset);
351 }
352
353 /** delete auth data domain node */
354 static void
355 auth_data_delete(struct auth_data* n)
356 {
357         struct auth_rrset* p, *np;
358         if(!n) return;
359         p = n->rrsets;
360         while(p) {
361                 np = p->next;
362                 auth_rrset_delete(p);
363                 p = np;
364         }
365         free(n->name);
366         free(n);
367 }
368
369 /** helper traverse to delete zones */
370 static void
371 auth_data_del(rbnode_type* n, void* ATTR_UNUSED(arg))
372 {
373         struct auth_data* z = (struct auth_data*)n->key;
374         auth_data_delete(z);
375 }
376
377 /** delete an auth zone structure (tree remove must be done elsewhere) */
378 static void
379 auth_zone_delete(struct auth_zone* z)
380 {
381         if(!z) return;
382         lock_rw_destroy(&z->lock);
383         traverse_postorder(&z->data, auth_data_del, NULL);
384         free(z->name);
385         free(z->zonefile);
386         free(z);
387 }
388
389 struct auth_zone*
390 auth_zone_create(struct auth_zones* az, uint8_t* nm, size_t nmlen,
391         uint16_t dclass)
392 {
393         struct auth_zone* z = (struct auth_zone*)calloc(1, sizeof(*z));
394         if(!z) {
395                 return NULL;
396         }
397         z->node.key = z;
398         z->dclass = dclass;
399         z->namelen = nmlen;
400         z->namelabs = dname_count_labels(nm);
401         z->name = memdup(nm, nmlen);
402         if(!z->name) {
403                 free(z);
404                 return NULL;
405         }
406         rbtree_init(&z->data, &auth_data_cmp);
407         lock_rw_init(&z->lock);
408         lock_protect(&z->lock, &z->name, sizeof(*z)-sizeof(rbnode_type));
409         lock_rw_wrlock(&z->lock);
410         /* z lock protects all, except rbtree itself, which is az->lock */
411         if(!rbtree_insert(&az->ztree, &z->node)) {
412                 lock_rw_unlock(&z->lock);
413                 auth_zone_delete(z);
414                 log_warn("duplicate auth zone");
415                 return NULL;
416         }
417         return z;
418 }
419
420 struct auth_zone*
421 auth_zone_find(struct auth_zones* az, uint8_t* nm, size_t nmlen,
422         uint16_t dclass)
423 {
424         struct auth_zone key;
425         key.node.key = &key;
426         key.dclass = dclass;
427         key.name = nm;
428         key.namelen = nmlen;
429         key.namelabs = dname_count_labels(nm);
430         return (struct auth_zone*)rbtree_search(&az->ztree, &key);
431 }
432
433 struct auth_xfer*
434 auth_xfer_find(struct auth_zones* az, uint8_t* nm, size_t nmlen,
435         uint16_t dclass)
436 {
437         struct auth_xfer key;
438         key.node.key = &key;
439         key.dclass = dclass;
440         key.name = nm;
441         key.namelen = nmlen;
442         key.namelabs = dname_count_labels(nm);
443         return (struct auth_xfer*)rbtree_search(&az->xtree, &key);
444 }
445
446 /** find an auth zone or sorted less-or-equal, return true if exact */
447 static int
448 auth_zone_find_less_equal(struct auth_zones* az, uint8_t* nm, size_t nmlen,
449         uint16_t dclass, struct auth_zone** z)
450 {
451         struct auth_zone key;
452         key.node.key = &key;
453         key.dclass = dclass;
454         key.name = nm;
455         key.namelen = nmlen;
456         key.namelabs = dname_count_labels(nm);
457         return rbtree_find_less_equal(&az->ztree, &key, (rbnode_type**)z);
458 }
459
460
461 /** find the auth zone that is above the given name */
462 struct auth_zone*
463 auth_zones_find_zone(struct auth_zones* az, uint8_t* name, size_t name_len,
464         uint16_t dclass)
465 {
466         uint8_t* nm = name;
467         size_t nmlen = name_len;
468         struct auth_zone* z;
469         if(auth_zone_find_less_equal(az, nm, nmlen, dclass, &z)) {
470                 /* exact match */
471                 return z;
472         } else {
473                 /* less-or-nothing */
474                 if(!z) return NULL; /* nothing smaller, nothing above it */
475                 /* we found smaller name; smaller may be above the name,
476                  * but not below it. */
477                 nm = dname_get_shared_topdomain(z->name, name);
478                 dname_count_size_labels(nm, &nmlen);
479                 z = NULL;
480         }
481
482         /* search up */
483         while(!z) {
484                 z = auth_zone_find(az, nm, nmlen, dclass);
485                 if(z) return z;
486                 if(dname_is_root(nm)) break;
487                 dname_remove_label(&nm, &nmlen);
488         }
489         return NULL;
490 }
491
492 /** find or create zone with name str. caller must have lock on az. 
493  * returns a wrlocked zone */
494 static struct auth_zone*
495 auth_zones_find_or_add_zone(struct auth_zones* az, char* name)
496 {
497         uint8_t nm[LDNS_MAX_DOMAINLEN+1];
498         size_t nmlen = sizeof(nm);
499         struct auth_zone* z;
500
501         if(sldns_str2wire_dname_buf(name, nm, &nmlen) != 0) {
502                 log_err("cannot parse auth zone name: %s", name);
503                 return 0;
504         }
505         z = auth_zone_find(az, nm, nmlen, LDNS_RR_CLASS_IN);
506         if(!z) {
507                 /* not found, create the zone */
508                 z = auth_zone_create(az, nm, nmlen, LDNS_RR_CLASS_IN);
509         } else {
510                 lock_rw_wrlock(&z->lock);
511         }
512         return z;
513 }
514
515 /** find or create xfer zone with name str. caller must have lock on az. 
516  * returns a locked xfer */
517 static struct auth_xfer*
518 auth_zones_find_or_add_xfer(struct auth_zones* az, struct auth_zone* z)
519 {
520         struct auth_xfer* x;
521         x = auth_xfer_find(az, z->name, z->namelen, z->dclass);
522         if(!x) {
523                 /* not found, create the zone */
524                 x = auth_xfer_create(az, z);
525         } else {
526                 lock_basic_lock(&x->lock);
527         }
528         return x;
529 }
530
531 int
532 auth_zone_set_zonefile(struct auth_zone* z, char* zonefile)
533 {
534         if(z->zonefile) free(z->zonefile);
535         if(zonefile == NULL) {
536                 z->zonefile = NULL;
537         } else {
538                 z->zonefile = strdup(zonefile);
539                 if(!z->zonefile) {
540                         log_err("malloc failure");
541                         return 0;
542                 }
543         }
544         return 1;
545 }
546
547 /** set auth zone fallback. caller must have lock on zone */
548 int
549 auth_zone_set_fallback(struct auth_zone* z, char* fallbackstr)
550 {
551         if(strcmp(fallbackstr, "yes") != 0 && strcmp(fallbackstr, "no") != 0){
552                 log_err("auth zone fallback, expected yes or no, got %s",
553                         fallbackstr);
554                 return 0;
555         }
556         z->fallback_enabled = (strcmp(fallbackstr, "yes")==0);
557         return 1;
558 }
559
560 /** create domain with the given name */
561 static struct auth_data*
562 az_domain_create(struct auth_zone* z, uint8_t* nm, size_t nmlen)
563 {
564         struct auth_data* n = (struct auth_data*)malloc(sizeof(*n));
565         if(!n) return NULL;
566         memset(n, 0, sizeof(*n));
567         n->node.key = n;
568         n->name = memdup(nm, nmlen);
569         if(!n->name) {
570                 free(n);
571                 return NULL;
572         }
573         n->namelen = nmlen;
574         n->namelabs = dname_count_labels(nm);
575         if(!rbtree_insert(&z->data, &n->node)) {
576                 log_warn("duplicate auth domain name");
577                 free(n->name);
578                 free(n);
579                 return NULL;
580         }
581         return n;
582 }
583
584 /** find domain with exactly the given name */
585 static struct auth_data*
586 az_find_name(struct auth_zone* z, uint8_t* nm, size_t nmlen)
587 {
588         struct auth_zone key;
589         key.node.key = &key;
590         key.name = nm;
591         key.namelen = nmlen;
592         key.namelabs = dname_count_labels(nm);
593         return (struct auth_data*)rbtree_search(&z->data, &key);
594 }
595
596 /** Find domain name (or closest match) */
597 static void
598 az_find_domain(struct auth_zone* z, struct query_info* qinfo, int* node_exact,
599         struct auth_data** node)
600 {
601         struct auth_zone key;
602         key.node.key = &key;
603         key.name = qinfo->qname;
604         key.namelen = qinfo->qname_len;
605         key.namelabs = dname_count_labels(key.name);
606         *node_exact = rbtree_find_less_equal(&z->data, &key,
607                 (rbnode_type**)node);
608 }
609
610 /** find or create domain with name in zone */
611 static struct auth_data*
612 az_domain_find_or_create(struct auth_zone* z, uint8_t* dname,
613         size_t dname_len)
614 {
615         struct auth_data* n = az_find_name(z, dname, dname_len);
616         if(!n) {
617                 n = az_domain_create(z, dname, dname_len);
618         }
619         return n;
620 }
621
622 /** find rrset of given type in the domain */
623 static struct auth_rrset*
624 az_domain_rrset(struct auth_data* n, uint16_t t)
625 {
626         struct auth_rrset* rrset;
627         if(!n) return NULL;
628         rrset = n->rrsets;
629         while(rrset) {
630                 if(rrset->type == t)
631                         return rrset;
632                 rrset = rrset->next;
633         }
634         return NULL;
635 }
636
637 /** remove rrset of this type from domain */
638 static void
639 domain_remove_rrset(struct auth_data* node, uint16_t rr_type)
640 {
641         struct auth_rrset* rrset, *prev;
642         if(!node) return;
643         prev = NULL;
644         rrset = node->rrsets;
645         while(rrset) {
646                 if(rrset->type == rr_type) {
647                         /* found it, now delete it */
648                         if(prev) prev->next = rrset->next;
649                         else    node->rrsets = rrset->next;
650                         auth_rrset_delete(rrset);
651                         return;
652                 }
653                 prev = rrset;
654                 rrset = rrset->next;
655         }
656 }
657
658 /** find an rr index in the rrset.  returns true if found */
659 static int
660 az_rrset_find_rr(struct packed_rrset_data* d, uint8_t* rdata, size_t len,
661         size_t* index)
662 {
663         size_t i;
664         for(i=0; i<d->count; i++) {
665                 if(d->rr_len[i] != len)
666                         continue;
667                 if(memcmp(d->rr_data[i], rdata, len) == 0) {
668                         *index = i;
669                         return 1;
670                 }
671         }
672         return 0;
673 }
674
675 /** find an rrsig index in the rrset.  returns true if found */
676 static int
677 az_rrset_find_rrsig(struct packed_rrset_data* d, uint8_t* rdata, size_t len,
678         size_t* index)
679 {
680         size_t i;
681         for(i=d->count; i<d->count + d->rrsig_count; i++) {
682                 if(d->rr_len[i] != len)
683                         continue;
684                 if(memcmp(d->rr_data[i], rdata, len) == 0) {
685                         *index = i;
686                         return 1;
687                 }
688         }
689         return 0;
690 }
691
692 /** see if rdata is duplicate */
693 static int
694 rdata_duplicate(struct packed_rrset_data* d, uint8_t* rdata, size_t len)
695 {
696         size_t i;
697         for(i=0; i<d->count + d->rrsig_count; i++) {
698                 if(d->rr_len[i] != len)
699                         continue;
700                 if(memcmp(d->rr_data[i], rdata, len) == 0)
701                         return 1;
702         }
703         return 0;
704 }
705
706 /** get rrsig type covered from rdata.
707  * @param rdata: rdata in wireformat, starting with 16bit rdlength.
708  * @param rdatalen: length of rdata buffer.
709  * @return type covered (or 0).
710  */
711 static uint16_t
712 rrsig_rdata_get_type_covered(uint8_t* rdata, size_t rdatalen)
713 {
714         if(rdatalen < 4)
715                 return 0;
716         return sldns_read_uint16(rdata+2);
717 }
718
719 /** remove RR from existing RRset. Also sig, if it is a signature.
720  * reallocates the packed rrset for a new one, false on alloc failure */
721 static int
722 rrset_remove_rr(struct auth_rrset* rrset, size_t index)
723 {
724         struct packed_rrset_data* d, *old = rrset->data;
725         size_t i;
726         if(index >= old->count + old->rrsig_count)
727                 return 0; /* index out of bounds */
728         d = (struct packed_rrset_data*)calloc(1, packed_rrset_sizeof(old) - (
729                 sizeof(size_t) + sizeof(uint8_t*) + sizeof(time_t) +
730                 old->rr_len[index]));
731         if(!d) {
732                 log_err("malloc failure");
733                 return 0;
734         }
735         d->ttl = old->ttl;
736         d->count = old->count;
737         d->rrsig_count = old->rrsig_count;
738         if(index < d->count) d->count--;
739         else d->rrsig_count--;
740         d->trust = old->trust;
741         d->security = old->security;
742
743         /* set rr_len, needed for ptr_fixup */
744         d->rr_len = (size_t*)((uint8_t*)d +
745                 sizeof(struct packed_rrset_data));
746         if(index > 0)
747                 memmove(d->rr_len, old->rr_len, (index)*sizeof(size_t));
748         if(index+1 < old->count+old->rrsig_count)
749                 memmove(&d->rr_len[index], &old->rr_len[index+1],
750                 (old->count+old->rrsig_count - (index+1))*sizeof(size_t));
751         packed_rrset_ptr_fixup(d);
752
753         /* move over ttls */
754         if(index > 0)
755                 memmove(d->rr_ttl, old->rr_ttl, (index)*sizeof(time_t));
756         if(index+1 < old->count+old->rrsig_count)
757                 memmove(&d->rr_ttl[index], &old->rr_ttl[index+1],
758                 (old->count+old->rrsig_count - (index+1))*sizeof(time_t));
759         
760         /* move over rr_data */
761         for(i=0; i<d->count+d->rrsig_count; i++) {
762                 size_t oldi;
763                 if(i < index) oldi = i;
764                 else oldi = i+1;
765                 memmove(d->rr_data[i], old->rr_data[oldi], d->rr_len[i]);
766         }
767
768         /* recalc ttl (lowest of remaining RR ttls) */
769         if(d->count + d->rrsig_count > 0)
770                 d->ttl = d->rr_ttl[0];
771         for(i=0; i<d->count+d->rrsig_count; i++) {
772                 if(d->rr_ttl[i] < d->ttl)
773                         d->ttl = d->rr_ttl[i];
774         }
775
776         free(rrset->data);
777         rrset->data = d;
778         return 1;
779 }
780
781 /** add RR to existing RRset. If insert_sig is true, add to rrsigs. 
782  * This reallocates the packed rrset for a new one */
783 static int
784 rrset_add_rr(struct auth_rrset* rrset, uint32_t rr_ttl, uint8_t* rdata,
785         size_t rdatalen, int insert_sig)
786 {
787         struct packed_rrset_data* d, *old = rrset->data;
788         size_t total, old_total;
789
790         d = (struct packed_rrset_data*)calloc(1, packed_rrset_sizeof(old)
791                 + sizeof(size_t) + sizeof(uint8_t*) + sizeof(time_t)
792                 + rdatalen);
793         if(!d) {
794                 log_err("out of memory");
795                 return 0;
796         }
797         /* copy base values */
798         memcpy(d, old, sizeof(struct packed_rrset_data));
799         if(!insert_sig) {
800                 d->count++;
801         } else {
802                 d->rrsig_count++;
803         }
804         old_total = old->count + old->rrsig_count;
805         total = d->count + d->rrsig_count;
806         /* set rr_len, needed for ptr_fixup */
807         d->rr_len = (size_t*)((uint8_t*)d +
808                 sizeof(struct packed_rrset_data));
809         if(old->count != 0)
810                 memmove(d->rr_len, old->rr_len, old->count*sizeof(size_t));
811         if(old->rrsig_count != 0)
812                 memmove(d->rr_len+d->count, old->rr_len+old->count,
813                         old->rrsig_count*sizeof(size_t));
814         if(!insert_sig)
815                 d->rr_len[d->count-1] = rdatalen;
816         else    d->rr_len[total-1] = rdatalen;
817         packed_rrset_ptr_fixup(d);
818         if((time_t)rr_ttl < d->ttl)
819                 d->ttl = rr_ttl;
820
821         /* copy old values into new array */
822         if(old->count != 0) {
823                 memmove(d->rr_ttl, old->rr_ttl, old->count*sizeof(time_t));
824                 /* all the old rr pieces are allocated sequential, so we
825                  * can copy them in one go */
826                 memmove(d->rr_data[0], old->rr_data[0],
827                         (old->rr_data[old->count-1] - old->rr_data[0]) +
828                         old->rr_len[old->count-1]);
829         }
830         if(old->rrsig_count != 0) {
831                 memmove(d->rr_ttl+d->count, old->rr_ttl+old->count,
832                         old->rrsig_count*sizeof(time_t));
833                 memmove(d->rr_data[d->count], old->rr_data[old->count],
834                         (old->rr_data[old_total-1] - old->rr_data[old->count]) +
835                         old->rr_len[old_total-1]);
836         }
837
838         /* insert new value */
839         if(!insert_sig) {
840                 d->rr_ttl[d->count-1] = rr_ttl;
841                 memmove(d->rr_data[d->count-1], rdata, rdatalen);
842         } else {
843                 d->rr_ttl[total-1] = rr_ttl;
844                 memmove(d->rr_data[total-1], rdata, rdatalen);
845         }
846
847         rrset->data = d;
848         free(old);
849         return 1;
850 }
851
852 /** Create new rrset for node with packed rrset with one RR element */
853 static struct auth_rrset*
854 rrset_create(struct auth_data* node, uint16_t rr_type, uint32_t rr_ttl,
855         uint8_t* rdata, size_t rdatalen)
856 {
857         struct auth_rrset* rrset = (struct auth_rrset*)calloc(1,
858                 sizeof(*rrset));
859         struct auth_rrset* p, *prev;
860         struct packed_rrset_data* d;
861         if(!rrset) {
862                 log_err("out of memory");
863                 return NULL;
864         }
865         rrset->type = rr_type;
866
867         /* the rrset data structure, with one RR */
868         d = (struct packed_rrset_data*)calloc(1,
869                 sizeof(struct packed_rrset_data) + sizeof(size_t) +
870                 sizeof(uint8_t*) + sizeof(time_t) + rdatalen);
871         if(!d) {
872                 free(rrset);
873                 log_err("out of memory");
874                 return NULL;
875         }
876         rrset->data = d;
877         d->ttl = rr_ttl;
878         d->trust = rrset_trust_prim_noglue;
879         d->rr_len = (size_t*)((uint8_t*)d + sizeof(struct packed_rrset_data));
880         d->rr_data = (uint8_t**)&(d->rr_len[1]);
881         d->rr_ttl = (time_t*)&(d->rr_data[1]);
882         d->rr_data[0] = (uint8_t*)&(d->rr_ttl[1]);
883
884         /* insert the RR */
885         d->rr_len[0] = rdatalen;
886         d->rr_ttl[0] = rr_ttl;
887         memmove(d->rr_data[0], rdata, rdatalen);
888         d->count++;
889
890         /* insert rrset into linked list for domain */
891         /* find sorted place to link the rrset into the list */
892         prev = NULL;
893         p = node->rrsets;
894         while(p && p->type<=rr_type) {
895                 prev = p;
896                 p = p->next;
897         }
898         /* so, prev is smaller, and p is larger than rr_type */
899         rrset->next = p;
900         if(prev) prev->next = rrset;
901         else node->rrsets = rrset;
902         return rrset;
903 }
904
905 /** count number (and size) of rrsigs that cover a type */
906 static size_t
907 rrsig_num_that_cover(struct auth_rrset* rrsig, uint16_t rr_type, size_t* sigsz)
908 {
909         struct packed_rrset_data* d = rrsig->data;
910         size_t i, num = 0;
911         *sigsz = 0;
912         log_assert(d && rrsig->type == LDNS_RR_TYPE_RRSIG);
913         for(i=0; i<d->count+d->rrsig_count; i++) {
914                 if(rrsig_rdata_get_type_covered(d->rr_data[i],
915                         d->rr_len[i]) == rr_type) {
916                         num++;
917                         (*sigsz) += d->rr_len[i];
918                 }
919         }
920         return num;
921 }
922
923 /** See if rrsig set has covered sigs for rrset and move them over */
924 static int
925 rrset_moveover_rrsigs(struct auth_data* node, uint16_t rr_type,
926         struct auth_rrset* rrset, struct auth_rrset* rrsig)
927 {
928         size_t sigs, sigsz, i, j, total;
929         struct packed_rrset_data* sigold = rrsig->data;
930         struct packed_rrset_data* old = rrset->data;
931         struct packed_rrset_data* d, *sigd;
932
933         log_assert(rrset->type == rr_type);
934         log_assert(rrsig->type == LDNS_RR_TYPE_RRSIG);
935         sigs = rrsig_num_that_cover(rrsig, rr_type, &sigsz);
936         if(sigs == 0) {
937                 /* 0 rrsigs to move over, done */
938                 return 1;
939         }
940
941         /* allocate rrset sigsz larger for extra sigs elements, and
942          * allocate rrsig sigsz smaller for less sigs elements. */
943         d = (struct packed_rrset_data*)calloc(1, packed_rrset_sizeof(old)
944                 + sigs*(sizeof(size_t) + sizeof(uint8_t*) + sizeof(time_t))
945                 + sigsz);
946         if(!d) {
947                 log_err("out of memory");
948                 return 0;
949         }
950         /* copy base values */
951         total = old->count + old->rrsig_count;
952         memcpy(d, old, sizeof(struct packed_rrset_data));
953         d->rrsig_count += sigs;
954         /* setup rr_len */
955         d->rr_len = (size_t*)((uint8_t*)d +
956                 sizeof(struct packed_rrset_data));
957         if(total != 0)
958                 memmove(d->rr_len, old->rr_len, total*sizeof(size_t));
959         j = d->count+d->rrsig_count-sigs;
960         for(i=0; i<sigold->count+sigold->rrsig_count; i++) {
961                 if(rrsig_rdata_get_type_covered(sigold->rr_data[i],
962                         sigold->rr_len[i]) == rr_type) {
963                         d->rr_len[j] = sigold->rr_len[i];
964                         j++;
965                 }
966         }
967         packed_rrset_ptr_fixup(d);
968
969         /* copy old values into new array */
970         if(total != 0) {
971                 memmove(d->rr_ttl, old->rr_ttl, total*sizeof(time_t));
972                 /* all the old rr pieces are allocated sequential, so we
973                  * can copy them in one go */
974                 memmove(d->rr_data[0], old->rr_data[0],
975                         (old->rr_data[total-1] - old->rr_data[0]) +
976                         old->rr_len[total-1]);
977         }
978
979         /* move over the rrsigs to the larger rrset*/
980         j = d->count+d->rrsig_count-sigs;
981         for(i=0; i<sigold->count+sigold->rrsig_count; i++) {
982                 if(rrsig_rdata_get_type_covered(sigold->rr_data[i],
983                         sigold->rr_len[i]) == rr_type) {
984                         /* move this one over to location j */
985                         d->rr_ttl[j] = sigold->rr_ttl[i];
986                         memmove(d->rr_data[j], sigold->rr_data[i],
987                                 sigold->rr_len[i]);
988                         if(d->rr_ttl[j] < d->ttl)
989                                 d->ttl = d->rr_ttl[j];
990                         j++;
991                 }
992         }
993
994         /* put it in and deallocate the old rrset */
995         rrset->data = d;
996         free(old);
997
998         /* now make rrsig set smaller */
999         if(sigold->count+sigold->rrsig_count == sigs) {
1000                 /* remove all sigs from rrsig, remove it entirely */
1001                 domain_remove_rrset(node, LDNS_RR_TYPE_RRSIG);
1002                 return 1;
1003         }
1004         log_assert(packed_rrset_sizeof(sigold) > sigs*(sizeof(size_t) +
1005                 sizeof(uint8_t*) + sizeof(time_t)) + sigsz);
1006         sigd = (struct packed_rrset_data*)calloc(1, packed_rrset_sizeof(sigold)
1007                 - sigs*(sizeof(size_t) + sizeof(uint8_t*) + sizeof(time_t))
1008                 - sigsz);
1009         if(!sigd) {
1010                 /* no need to free up d, it has already been placed in the
1011                  * node->rrset structure */
1012                 log_err("out of memory");
1013                 return 0;
1014         }
1015         /* copy base values */
1016         memcpy(sigd, sigold, sizeof(struct packed_rrset_data));
1017         sigd->rrsig_count -= sigs;
1018         /* setup rr_len */
1019         sigd->rr_len = (size_t*)((uint8_t*)sigd +
1020                 sizeof(struct packed_rrset_data));
1021         j = 0;
1022         for(i=0; i<sigold->count+sigold->rrsig_count; i++) {
1023                 if(rrsig_rdata_get_type_covered(sigold->rr_data[i],
1024                         sigold->rr_len[i]) != rr_type) {
1025                         sigd->rr_len[j] = sigold->rr_len[i];
1026                         j++;
1027                 }
1028         }
1029         packed_rrset_ptr_fixup(sigd);
1030
1031         /* copy old values into new rrsig array */
1032         j = 0;
1033         for(i=0; i<sigold->count+sigold->rrsig_count; i++) {
1034                 if(rrsig_rdata_get_type_covered(sigold->rr_data[i],
1035                         sigold->rr_len[i]) != rr_type) {
1036                         /* move this one over to location j */
1037                         sigd->rr_ttl[j] = sigold->rr_ttl[i];
1038                         memmove(sigd->rr_data[j], sigold->rr_data[i],
1039                                 sigold->rr_len[i]);
1040                         if(j==0) sigd->ttl = sigd->rr_ttl[j];
1041                         else {
1042                                 if(sigd->rr_ttl[j] < sigd->ttl)
1043                                         sigd->ttl = sigd->rr_ttl[j];
1044                         }
1045                         j++;
1046                 }
1047         }
1048
1049         /* put it in and deallocate the old rrset */
1050         rrsig->data = sigd;
1051         free(sigold);
1052
1053         return 1;
1054 }
1055
1056 /** copy the rrsigs from the rrset to the rrsig rrset, because the rrset
1057  * is going to be deleted.  reallocates the RRSIG rrset data. */
1058 static int
1059 rrsigs_copy_from_rrset_to_rrsigset(struct auth_rrset* rrset,
1060         struct auth_rrset* rrsigset)
1061 {
1062         size_t i;
1063         if(rrset->data->rrsig_count == 0)
1064                 return 1;
1065
1066         /* move them over one by one, because there might be duplicates,
1067          * duplicates are ignored */
1068         for(i=rrset->data->count;
1069                 i<rrset->data->count+rrset->data->rrsig_count; i++) {
1070                 uint8_t* rdata = rrset->data->rr_data[i];
1071                 size_t rdatalen = rrset->data->rr_len[i];
1072                 time_t rr_ttl  = rrset->data->rr_ttl[i];
1073
1074                 if(rdata_duplicate(rrsigset->data, rdata, rdatalen)) {
1075                         continue;
1076                 }
1077                 if(!rrset_add_rr(rrsigset, rr_ttl, rdata, rdatalen, 0))
1078                         return 0;
1079         }
1080         return 1;
1081 }
1082
1083 /** Add rr to node, ignores duplicate RRs,
1084  * rdata points to buffer with rdatalen octets, starts with 2bytelength. */
1085 static int
1086 az_domain_add_rr(struct auth_data* node, uint16_t rr_type, uint32_t rr_ttl,
1087         uint8_t* rdata, size_t rdatalen, int* duplicate)
1088 {
1089         struct auth_rrset* rrset;
1090         /* packed rrsets have their rrsigs along with them, sort them out */
1091         if(rr_type == LDNS_RR_TYPE_RRSIG) {
1092                 uint16_t ctype = rrsig_rdata_get_type_covered(rdata, rdatalen);
1093                 if((rrset=az_domain_rrset(node, ctype))!= NULL) {
1094                         /* a node of the correct type exists, add the RRSIG
1095                          * to the rrset of the covered data type */
1096                         if(rdata_duplicate(rrset->data, rdata, rdatalen)) {
1097                                 if(duplicate) *duplicate = 1;
1098                                 return 1;
1099                         }
1100                         if(!rrset_add_rr(rrset, rr_ttl, rdata, rdatalen, 1))
1101                                 return 0;
1102                 } else if((rrset=az_domain_rrset(node, rr_type))!= NULL) {
1103                         /* add RRSIG to rrset of type RRSIG */
1104                         if(rdata_duplicate(rrset->data, rdata, rdatalen)) {
1105                                 if(duplicate) *duplicate = 1;
1106                                 return 1;
1107                         }
1108                         if(!rrset_add_rr(rrset, rr_ttl, rdata, rdatalen, 0))
1109                                 return 0;
1110                 } else {
1111                         /* create rrset of type RRSIG */
1112                         if(!rrset_create(node, rr_type, rr_ttl, rdata,
1113                                 rdatalen))
1114                                 return 0;
1115                 }
1116         } else {
1117                 /* normal RR type */
1118                 if((rrset=az_domain_rrset(node, rr_type))!= NULL) {
1119                         /* add data to existing node with data type */
1120                         if(rdata_duplicate(rrset->data, rdata, rdatalen)) {
1121                                 if(duplicate) *duplicate = 1;
1122                                 return 1;
1123                         }
1124                         if(!rrset_add_rr(rrset, rr_ttl, rdata, rdatalen, 0))
1125                                 return 0;
1126                 } else {
1127                         struct auth_rrset* rrsig;
1128                         /* create new node with data type */
1129                         if(!(rrset=rrset_create(node, rr_type, rr_ttl, rdata,
1130                                 rdatalen)))
1131                                 return 0;
1132
1133                         /* see if node of type RRSIG has signatures that
1134                          * cover the data type, and move them over */
1135                         /* and then make the RRSIG type smaller */
1136                         if((rrsig=az_domain_rrset(node, LDNS_RR_TYPE_RRSIG))
1137                                 != NULL) {
1138                                 if(!rrset_moveover_rrsigs(node, rr_type,
1139                                         rrset, rrsig))
1140                                         return 0;
1141                         }
1142                 }
1143         }
1144         return 1;
1145 }
1146
1147 /** insert RR into zone, ignore duplicates */
1148 static int
1149 az_insert_rr(struct auth_zone* z, uint8_t* rr, size_t rr_len,
1150         size_t dname_len, int* duplicate)
1151 {
1152         struct auth_data* node;
1153         uint8_t* dname = rr;
1154         uint16_t rr_type = sldns_wirerr_get_type(rr, rr_len, dname_len);
1155         uint16_t rr_class = sldns_wirerr_get_class(rr, rr_len, dname_len);
1156         uint32_t rr_ttl = sldns_wirerr_get_ttl(rr, rr_len, dname_len);
1157         size_t rdatalen = ((size_t)sldns_wirerr_get_rdatalen(rr, rr_len,
1158                 dname_len))+2;
1159         /* rdata points to rdata prefixed with uint16 rdatalength */
1160         uint8_t* rdata = sldns_wirerr_get_rdatawl(rr, rr_len, dname_len);
1161
1162         if(rr_class != z->dclass) {
1163                 log_err("wrong class for RR");
1164                 return 0;
1165         }
1166         if(!(node=az_domain_find_or_create(z, dname, dname_len))) {
1167                 log_err("cannot create domain");
1168                 return 0;
1169         }
1170         if(!az_domain_add_rr(node, rr_type, rr_ttl, rdata, rdatalen,
1171                 duplicate)) {
1172                 log_err("cannot add RR to domain");
1173                 return 0;
1174         }
1175         return 1;
1176 }
1177
1178 /** Remove rr from node, ignores nonexisting RRs,
1179  * rdata points to buffer with rdatalen octets, starts with 2bytelength. */
1180 static int
1181 az_domain_remove_rr(struct auth_data* node, uint16_t rr_type,
1182         uint8_t* rdata, size_t rdatalen, int* nonexist)
1183 {
1184         struct auth_rrset* rrset;
1185         size_t index = 0;
1186
1187         /* find the plain RR of the given type */
1188         if((rrset=az_domain_rrset(node, rr_type))!= NULL) {
1189                 if(az_rrset_find_rr(rrset->data, rdata, rdatalen, &index)) {
1190                         if(rrset->data->count == 1 &&
1191                                 rrset->data->rrsig_count == 0) {
1192                                 /* last RR, delete the rrset */
1193                                 domain_remove_rrset(node, rr_type);
1194                         } else if(rrset->data->count == 1 &&
1195                                 rrset->data->rrsig_count != 0) {
1196                                 /* move RRSIGs to the RRSIG rrset, or
1197                                  * this one becomes that RRset */
1198                                 struct auth_rrset* rrsigset = az_domain_rrset(
1199                                         node, LDNS_RR_TYPE_RRSIG);
1200                                 if(rrsigset) {
1201                                         /* move left over rrsigs to the
1202                                          * existing rrset of type RRSIG */
1203                                         rrsigs_copy_from_rrset_to_rrsigset(
1204                                                 rrset, rrsigset);
1205                                         /* and then delete the rrset */
1206                                         domain_remove_rrset(node, rr_type);
1207                                 } else {
1208                                         /* no rrset of type RRSIG, this
1209                                          * set is now of that type,
1210                                          * just remove the rr */
1211                                         if(!rrset_remove_rr(rrset, index))
1212                                                 return 0;
1213                                         rrset->type = LDNS_RR_TYPE_RRSIG;
1214                                         rrset->data->count = rrset->data->rrsig_count;
1215                                         rrset->data->rrsig_count = 0;
1216                                 }
1217                         } else {
1218                                 /* remove the RR from the rrset */
1219                                 if(!rrset_remove_rr(rrset, index))
1220                                         return 0;
1221                         }
1222                         return 1;
1223                 }
1224                 /* rr not found in rrset */
1225         }
1226
1227         /* is it a type RRSIG, look under the covered type */
1228         if(rr_type == LDNS_RR_TYPE_RRSIG) {
1229                 uint16_t ctype = rrsig_rdata_get_type_covered(rdata, rdatalen);
1230                 if((rrset=az_domain_rrset(node, ctype))!= NULL) {
1231                         if(az_rrset_find_rrsig(rrset->data, rdata, rdatalen,
1232                                 &index)) {
1233                                 /* rrsig should have d->count > 0, be
1234                                  * over some rr of that type */
1235                                 /* remove the rrsig from the rrsigs list of the
1236                                  * rrset */
1237                                 if(!rrset_remove_rr(rrset, index))
1238                                         return 0;
1239                                 return 1;
1240                         }
1241                 }
1242                 /* also RRSIG not found */
1243         }
1244
1245         /* nothing found to delete */
1246         if(nonexist) *nonexist = 1;
1247         return 1;
1248 }
1249
1250 /** remove RR from zone, ignore if it does not exist, false on alloc failure*/
1251 static int
1252 az_remove_rr(struct auth_zone* z, uint8_t* rr, size_t rr_len,
1253         size_t dname_len, int* nonexist)
1254 {
1255         struct auth_data* node;
1256         uint8_t* dname = rr;
1257         uint16_t rr_type = sldns_wirerr_get_type(rr, rr_len, dname_len);
1258         uint16_t rr_class = sldns_wirerr_get_class(rr, rr_len, dname_len);
1259         size_t rdatalen = ((size_t)sldns_wirerr_get_rdatalen(rr, rr_len,
1260                 dname_len))+2;
1261         /* rdata points to rdata prefixed with uint16 rdatalength */
1262         uint8_t* rdata = sldns_wirerr_get_rdatawl(rr, rr_len, dname_len);
1263
1264         if(rr_class != z->dclass) {
1265                 log_err("wrong class for RR");
1266                 /* really also a nonexisting entry, because no records
1267                  * of that class in the zone, but return an error because
1268                  * getting records of the wrong class is a failure of the
1269                  * zone transfer */
1270                 return 0;
1271         }
1272         node = az_find_name(z, dname, dname_len);
1273         if(!node) {
1274                 /* node with that name does not exist */
1275                 /* nonexisting entry, because no such name */
1276                 *nonexist = 1;
1277                 return 1;
1278         }
1279         if(!az_domain_remove_rr(node, rr_type, rdata, rdatalen, nonexist)) {
1280                 /* alloc failure or so */
1281                 return 0;
1282         }
1283         /* remove the node, if necessary */
1284         /* an rrsets==NULL entry is not kept around for empty nonterminals,
1285          * and also parent nodes are not kept around, so we just delete it */
1286         if(node->rrsets == NULL) {
1287                 (void)rbtree_delete(&z->data, node);
1288                 auth_data_delete(node);
1289         }
1290         return 1;
1291 }
1292
1293 /** decompress an RR into the buffer where it'll be an uncompressed RR
1294  * with uncompressed dname and uncompressed rdata (dnames) */
1295 static int
1296 decompress_rr_into_buffer(struct sldns_buffer* buf, uint8_t* pkt,
1297         size_t pktlen, uint8_t* dname, uint16_t rr_type, uint16_t rr_class,
1298         uint32_t rr_ttl, uint8_t* rr_data, uint16_t rr_rdlen)
1299 {
1300         sldns_buffer pktbuf;
1301         size_t dname_len = 0;
1302         size_t rdlenpos;
1303         size_t rdlen;
1304         uint8_t* rd;
1305         const sldns_rr_descriptor* desc;
1306         sldns_buffer_init_frm_data(&pktbuf, pkt, pktlen);
1307         sldns_buffer_clear(buf);
1308
1309         /* decompress dname */
1310         sldns_buffer_set_position(&pktbuf,
1311                 (size_t)(dname - sldns_buffer_current(&pktbuf)));
1312         dname_len = pkt_dname_len(&pktbuf);
1313         if(dname_len == 0) return 0; /* parse fail on dname */
1314         if(!sldns_buffer_available(buf, dname_len)) return 0;
1315         dname_pkt_copy(&pktbuf, sldns_buffer_current(buf), dname);
1316         sldns_buffer_skip(buf, (ssize_t)dname_len);
1317
1318         /* type, class, ttl and rdatalength fields */
1319         if(!sldns_buffer_available(buf, 10)) return 0;
1320         sldns_buffer_write_u16(buf, rr_type);
1321         sldns_buffer_write_u16(buf, rr_class);
1322         sldns_buffer_write_u32(buf, rr_ttl);
1323         rdlenpos = sldns_buffer_position(buf);
1324         sldns_buffer_write_u16(buf, 0); /* rd length position */
1325
1326         /* decompress rdata */
1327         desc = sldns_rr_descript(rr_type);
1328         rd = rr_data;
1329         rdlen = rr_rdlen;
1330         if(rdlen > 0 && desc && desc->_dname_count > 0) {
1331                 int count = (int)desc->_dname_count;
1332                 int rdf = 0;
1333                 size_t len; /* how much rdata to plain copy */
1334                 size_t uncompressed_len, compressed_len;
1335                 size_t oldpos;
1336                 /* decompress dnames. */
1337                 while(rdlen > 0 && count) {
1338                         switch(desc->_wireformat[rdf]) {
1339                         case LDNS_RDF_TYPE_DNAME:
1340                                 sldns_buffer_set_position(&pktbuf,
1341                                         (size_t)(rd -
1342                                         sldns_buffer_begin(&pktbuf)));
1343                                 oldpos = sldns_buffer_position(&pktbuf);
1344                                 /* moves pktbuf to right after the
1345                                  * compressed dname, and returns uncompressed
1346                                  * dname length */
1347                                 uncompressed_len = pkt_dname_len(&pktbuf);
1348                                 if(!uncompressed_len)
1349                                         return 0; /* parse error in dname */
1350                                 if(!sldns_buffer_available(buf,
1351                                         uncompressed_len))
1352                                         /* dname too long for buffer */
1353                                         return 0;
1354                                 dname_pkt_copy(&pktbuf, 
1355                                         sldns_buffer_current(buf), rd);
1356                                 sldns_buffer_skip(buf, (ssize_t)uncompressed_len);
1357                                 compressed_len = sldns_buffer_position(
1358                                         &pktbuf) - oldpos;
1359                                 rd += compressed_len;
1360                                 rdlen -= compressed_len;
1361                                 count--;
1362                                 len = 0;
1363                                 break;
1364                         case LDNS_RDF_TYPE_STR:
1365                                 len = rd[0] + 1;
1366                                 break;
1367                         default:
1368                                 len = get_rdf_size(desc->_wireformat[rdf]);
1369                                 break;
1370                         }
1371                         if(len) {
1372                                 if(!sldns_buffer_available(buf, len))
1373                                         return 0; /* too long for buffer */
1374                                 sldns_buffer_write(buf, rd, len);
1375                                 rd += len;
1376                                 rdlen -= len;
1377                         }
1378                         rdf++;
1379                 }
1380         }
1381         /* copy remaining data */
1382         if(rdlen > 0) {
1383                 if(!sldns_buffer_available(buf, rdlen)) return 0;
1384                 sldns_buffer_write(buf, rd, rdlen);
1385         }
1386         /* fixup rdlength */
1387         sldns_buffer_write_u16_at(buf, rdlenpos,
1388                 sldns_buffer_position(buf)-rdlenpos-2);
1389         sldns_buffer_flip(buf);
1390         return 1;
1391 }
1392
1393 /** insert RR into zone, from packet, decompress RR,
1394  * if duplicate is nonNULL set the flag but otherwise ignore duplicates */
1395 static int
1396 az_insert_rr_decompress(struct auth_zone* z, uint8_t* pkt, size_t pktlen,
1397         struct sldns_buffer* scratch_buffer, uint8_t* dname, uint16_t rr_type,
1398         uint16_t rr_class, uint32_t rr_ttl, uint8_t* rr_data,
1399         uint16_t rr_rdlen, int* duplicate)
1400 {
1401         uint8_t* rr;
1402         size_t rr_len;
1403         size_t dname_len;
1404         if(!decompress_rr_into_buffer(scratch_buffer, pkt, pktlen, dname,
1405                 rr_type, rr_class, rr_ttl, rr_data, rr_rdlen)) {
1406                 log_err("could not decompress RR");
1407                 return 0;
1408         }
1409         rr = sldns_buffer_begin(scratch_buffer);
1410         rr_len = sldns_buffer_limit(scratch_buffer);
1411         dname_len = dname_valid(rr, rr_len);
1412         return az_insert_rr(z, rr, rr_len, dname_len, duplicate);
1413 }
1414
1415 /** remove RR from zone, from packet, decompress RR,
1416  * if nonexist is nonNULL set the flag but otherwise ignore nonexisting entries*/
1417 static int
1418 az_remove_rr_decompress(struct auth_zone* z, uint8_t* pkt, size_t pktlen,
1419         struct sldns_buffer* scratch_buffer, uint8_t* dname, uint16_t rr_type,
1420         uint16_t rr_class, uint32_t rr_ttl, uint8_t* rr_data,
1421         uint16_t rr_rdlen, int* nonexist)
1422 {
1423         uint8_t* rr;
1424         size_t rr_len;
1425         size_t dname_len;
1426         if(!decompress_rr_into_buffer(scratch_buffer, pkt, pktlen, dname,
1427                 rr_type, rr_class, rr_ttl, rr_data, rr_rdlen)) {
1428                 log_err("could not decompress RR");
1429                 return 0;
1430         }
1431         rr = sldns_buffer_begin(scratch_buffer);
1432         rr_len = sldns_buffer_limit(scratch_buffer);
1433         dname_len = dname_valid(rr, rr_len);
1434         return az_remove_rr(z, rr, rr_len, dname_len, nonexist);
1435 }
1436
1437 /** 
1438  * Parse zonefile
1439  * @param z: zone to read in.
1440  * @param in: file to read from (just opened).
1441  * @param rr: buffer to use for RRs, 64k.
1442  *      passed so that recursive includes can use the same buffer and do
1443  *      not grow the stack too much.
1444  * @param rrbuflen: sizeof rr buffer.
1445  * @param state: parse state with $ORIGIN, $TTL and 'prev-dname' and so on,
1446  *      that is kept between includes.
1447  *      The lineno is set at 1 and then increased by the function.
1448  * @param fname: file name.
1449  * @param depth: recursion depth for includes
1450  * returns false on failure, has printed an error message
1451  */
1452 static int
1453 az_parse_file(struct auth_zone* z, FILE* in, uint8_t* rr, size_t rrbuflen,
1454         struct sldns_file_parse_state* state, char* fname, int depth)
1455 {
1456         size_t rr_len, dname_len;
1457         int status;
1458         state->lineno = 1;
1459
1460         while(!feof(in)) {
1461                 rr_len = rrbuflen;
1462                 dname_len = 0;
1463                 status = sldns_fp2wire_rr_buf(in, rr, &rr_len, &dname_len,
1464                         state);
1465                 if(status == LDNS_WIREPARSE_ERR_INCLUDE && rr_len == 0) {
1466                         /* we have $INCLUDE or $something */
1467                         if(strncmp((char*)rr, "$INCLUDE ", 9) == 0 ||
1468                            strncmp((char*)rr, "$INCLUDE\t", 9) == 0) {
1469                                 FILE* inc;
1470                                 int lineno_orig = state->lineno;
1471                                 char* incfile = (char*)rr + 8;
1472                                 if(depth > MAX_INCLUDE_DEPTH) {
1473                                         log_err("%s:%d max include depth"
1474                                           "exceeded", fname, state->lineno);
1475                                         return 0;
1476                                 }
1477                                 /* skip spaces */
1478                                 while(*incfile == ' ' || *incfile == '\t')
1479                                         incfile++;
1480                                 incfile = strdup(incfile);
1481                                 if(!incfile) {
1482                                         log_err("malloc failure");
1483                                         return 0;
1484                                 }
1485                                 verbose(VERB_ALGO, "opening $INCLUDE %s",
1486                                         incfile);
1487                                 inc = fopen(incfile, "r");
1488                                 if(!inc) {
1489                                         log_err("%s:%d cannot open include "
1490                                                 "file %s: %s", z->zonefile,
1491                                                 lineno_orig, incfile,
1492                                                 strerror(errno));
1493                                         free(incfile);
1494                                         return 0;
1495                                 }
1496                                 /* recurse read that file now */
1497                                 if(!az_parse_file(z, inc, rr, rrbuflen,
1498                                         state, incfile, depth+1)) {
1499                                         log_err("%s:%d cannot parse include "
1500                                                 "file %s", fname,
1501                                                 lineno_orig, incfile);
1502                                         fclose(inc);
1503                                         free(incfile);
1504                                         return 0;
1505                                 }
1506                                 fclose(inc);
1507                                 verbose(VERB_ALGO, "done with $INCLUDE %s",
1508                                         incfile);
1509                                 free(incfile);
1510                                 state->lineno = lineno_orig;
1511                         }
1512                         continue;
1513                 }
1514                 if(status != 0) {
1515                         log_err("parse error %s %d:%d: %s", fname,
1516                                 state->lineno, LDNS_WIREPARSE_OFFSET(status),
1517                                 sldns_get_errorstr_parse(status));
1518                         return 0;
1519                 }
1520                 if(rr_len == 0) {
1521                         /* EMPTY line, TTL or ORIGIN */
1522                         continue;
1523                 }
1524                 /* insert wirerr in rrbuf */
1525                 if(!az_insert_rr(z, rr, rr_len, dname_len, NULL)) {
1526                         char buf[17];
1527                         sldns_wire2str_type_buf(sldns_wirerr_get_type(rr,
1528                                 rr_len, dname_len), buf, sizeof(buf));
1529                         log_err("%s:%d cannot insert RR of type %s",
1530                                 fname, state->lineno, buf);
1531                         return 0;
1532                 }
1533         }
1534         return 1;
1535 }
1536
1537 int
1538 auth_zone_read_zonefile(struct auth_zone* z)
1539 {
1540         uint8_t rr[LDNS_RR_BUF_SIZE];
1541         struct sldns_file_parse_state state;
1542         FILE* in;
1543         if(!z || !z->zonefile || z->zonefile[0]==0)
1544                 return 1; /* no file, or "", nothing to read */
1545         if(verbosity >= VERB_ALGO) {
1546                 char nm[255+1];
1547                 dname_str(z->name, nm);
1548                 verbose(VERB_ALGO, "read zonefile %s for %s", z->zonefile, nm);
1549         }
1550         in = fopen(z->zonefile, "r");
1551         if(!in) {
1552                 char* n = sldns_wire2str_dname(z->name, z->namelen);
1553                 if(z->zone_is_slave && errno == ENOENT) {
1554                         /* we fetch the zone contents later, no file yet */
1555                         verbose(VERB_ALGO, "no zonefile %s for %s",
1556                                 z->zonefile, n?n:"error");
1557                         free(n);
1558                         return 1;
1559                 }
1560                 log_err("cannot open zonefile %s for %s: %s",
1561                         z->zonefile, n?n:"error", strerror(errno));
1562                 free(n);
1563                 return 0;
1564         }
1565
1566         /* clear the data tree */
1567         traverse_postorder(&z->data, auth_data_del, NULL);
1568         rbtree_init(&z->data, &auth_data_cmp);
1569
1570         memset(&state, 0, sizeof(state));
1571         /* default TTL to 3600 */
1572         state.default_ttl = 3600;
1573         /* set $ORIGIN to the zone name */
1574         if(z->namelen <= sizeof(state.origin)) {
1575                 memcpy(state.origin, z->name, z->namelen);
1576                 state.origin_len = z->namelen;
1577         }
1578         /* parse the (toplevel) file */
1579         if(!az_parse_file(z, in, rr, sizeof(rr), &state, z->zonefile, 0)) {
1580                 char* n = sldns_wire2str_dname(z->name, z->namelen);
1581                 log_err("error parsing zonefile %s for %s",
1582                         z->zonefile, n?n:"error");
1583                 free(n);
1584                 fclose(in);
1585                 return 0;
1586         }
1587         fclose(in);
1588         return 1;
1589 }
1590
1591 /** write buffer to file and check return codes */
1592 static int
1593 write_out(FILE* out, const char* str, size_t len)
1594 {
1595         size_t r;
1596         if(len == 0)
1597                 return 1;
1598         r = fwrite(str, 1, len, out);
1599         if(r == 0) {
1600                 log_err("write failed: %s", strerror(errno));
1601                 return 0;
1602         } else if(r < len) {
1603                 log_err("write failed: too short (disk full?)");
1604                 return 0;
1605         }
1606         return 1;
1607 }
1608
1609 /** convert auth rr to string */
1610 static int
1611 auth_rr_to_string(uint8_t* nm, size_t nmlen, uint16_t tp, uint16_t cl,
1612         struct packed_rrset_data* data, size_t i, char* s, size_t buflen)
1613 {
1614         int w = 0;
1615         size_t slen = buflen, datlen;
1616         uint8_t* dat;
1617         if(i >= data->count) tp = LDNS_RR_TYPE_RRSIG;
1618         dat = nm;
1619         datlen = nmlen;
1620         w += sldns_wire2str_dname_scan(&dat, &datlen, &s, &slen, NULL, 0);
1621         w += sldns_str_print(&s, &slen, "\t");
1622         w += sldns_str_print(&s, &slen, "%lu\t", (unsigned long)data->rr_ttl[i]);
1623         w += sldns_wire2str_class_print(&s, &slen, cl);
1624         w += sldns_str_print(&s, &slen, "\t");
1625         w += sldns_wire2str_type_print(&s, &slen, tp);
1626         w += sldns_str_print(&s, &slen, "\t");
1627         datlen = data->rr_len[i]-2;
1628         dat = data->rr_data[i]+2;
1629         w += sldns_wire2str_rdata_scan(&dat, &datlen, &s, &slen, tp, NULL, 0);
1630
1631         if(tp == LDNS_RR_TYPE_DNSKEY) {
1632                 w += sldns_str_print(&s, &slen, " ;{id = %u}",
1633                         sldns_calc_keytag_raw(data->rr_data[i]+2,
1634                                 data->rr_len[i]-2));
1635         }
1636         w += sldns_str_print(&s, &slen, "\n");
1637
1638         if(w > (int)buflen) {
1639                 log_nametypeclass(0, "RR too long to print", nm, tp, cl);
1640                 return 0;
1641         }
1642         return 1;
1643 }
1644
1645 /** write rrset to file */
1646 static int
1647 auth_zone_write_rrset(struct auth_zone* z, struct auth_data* node,
1648         struct auth_rrset* r, FILE* out)
1649 {
1650         size_t i, count = r->data->count + r->data->rrsig_count;
1651         char buf[LDNS_RR_BUF_SIZE];
1652         for(i=0; i<count; i++) {
1653                 if(!auth_rr_to_string(node->name, node->namelen, r->type,
1654                         z->dclass, r->data, i, buf, sizeof(buf))) {
1655                         verbose(VERB_ALGO, "failed to rr2str rr %d", (int)i);
1656                         continue;
1657                 }
1658                 if(!write_out(out, buf, strlen(buf)))
1659                         return 0;
1660         }
1661         return 1;
1662 }
1663
1664 /** write domain to file */
1665 static int
1666 auth_zone_write_domain(struct auth_zone* z, struct auth_data* n, FILE* out)
1667 {
1668         struct auth_rrset* r;
1669         /* if this is zone apex, write SOA first */
1670         if(z->namelen == n->namelen) {
1671                 struct auth_rrset* soa = az_domain_rrset(n, LDNS_RR_TYPE_SOA);
1672                 if(soa) {
1673                         if(!auth_zone_write_rrset(z, n, soa, out))
1674                                 return 0;
1675                 }
1676         }
1677         /* write all the RRsets for this domain */
1678         for(r = n->rrsets; r; r = r->next) {
1679                 if(z->namelen == n->namelen &&
1680                         r->type == LDNS_RR_TYPE_SOA)
1681                         continue; /* skip SOA here */
1682                 if(!auth_zone_write_rrset(z, n, r, out))
1683                         return 0;
1684         }
1685         return 1;
1686 }
1687
1688 int auth_zone_write_file(struct auth_zone* z, const char* fname)
1689 {
1690         FILE* out;
1691         struct auth_data* n;
1692         out = fopen(fname, "w");
1693         if(!out) {
1694                 log_err("could not open %s: %s", fname, strerror(errno));
1695                 return 0;
1696         }
1697         RBTREE_FOR(n, struct auth_data*, &z->data) {
1698                 if(!auth_zone_write_domain(z, n, out)) {
1699                         log_err("could not write domain to %s", fname);
1700                         fclose(out);
1701                         return 0;
1702                 }
1703         }
1704         fclose(out);
1705         return 1;
1706 }
1707
1708 /** read all auth zones from file (if they have) */
1709 static int
1710 auth_zones_read_zones(struct auth_zones* az)
1711 {
1712         struct auth_zone* z;
1713         lock_rw_wrlock(&az->lock);
1714         RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
1715                 lock_rw_wrlock(&z->lock);
1716                 if(!auth_zone_read_zonefile(z)) {
1717                         lock_rw_unlock(&z->lock);
1718                         lock_rw_unlock(&az->lock);
1719                         return 0;
1720                 }
1721                 lock_rw_unlock(&z->lock);
1722         }
1723         lock_rw_unlock(&az->lock);
1724         return 1;
1725 }
1726
1727 /** find serial number of zone or false if none */
1728 int
1729 auth_zone_get_serial(struct auth_zone* z, uint32_t* serial)
1730 {
1731         struct auth_data* apex;
1732         struct auth_rrset* soa;
1733         struct packed_rrset_data* d;
1734         apex = az_find_name(z, z->name, z->namelen);
1735         if(!apex) return 0;
1736         soa = az_domain_rrset(apex, LDNS_RR_TYPE_SOA);
1737         if(!soa || soa->data->count==0)
1738                 return 0; /* no RRset or no RRs in rrset */
1739         if(soa->data->rr_len[0] < 2+4*5) return 0; /* SOA too short */
1740         d = soa->data;
1741         *serial = sldns_read_uint32(d->rr_data[0]+(d->rr_len[0]-20));
1742         return 1;
1743 }
1744
1745 /** Find auth_zone SOA and populate the values in xfr(soa values). */
1746 static int
1747 xfr_find_soa(struct auth_zone* z, struct auth_xfer* xfr)
1748 {
1749         struct auth_data* apex;
1750         struct auth_rrset* soa;
1751         struct packed_rrset_data* d;
1752         apex = az_find_name(z, z->name, z->namelen);
1753         if(!apex) return 0;
1754         soa = az_domain_rrset(apex, LDNS_RR_TYPE_SOA);
1755         if(!soa || soa->data->count==0)
1756                 return 0; /* no RRset or no RRs in rrset */
1757         if(soa->data->rr_len[0] < 2+4*5) return 0; /* SOA too short */
1758         /* SOA record ends with serial, refresh, retry, expiry, minimum,
1759          * as 4 byte fields */
1760         d = soa->data;
1761         xfr->have_zone = 1;
1762         xfr->serial = sldns_read_uint32(d->rr_data[0]+(d->rr_len[0]-20));
1763         xfr->refresh = sldns_read_uint32(d->rr_data[0]+(d->rr_len[0]-16));
1764         xfr->retry = sldns_read_uint32(d->rr_data[0]+(d->rr_len[0]-12));
1765         xfr->expiry = sldns_read_uint32(d->rr_data[0]+(d->rr_len[0]-8));
1766         /* soa minimum at d->rr_len[0]-4 */
1767         return 1;
1768 }
1769
1770 /** 
1771  * Setup auth_xfer zone
1772  * This populates the have_zone, soa values, and so on times.
1773  * Doesn't do network traffic yet, can set option flags.
1774  * @param z: locked by caller, and modified for setup
1775  * @param x: locked by caller, and modified.
1776  * @return false on failure.
1777  */
1778 static int
1779 auth_xfer_setup(struct auth_zone* z, struct auth_xfer* x)
1780 {
1781         /* for a zone without zone transfers, x==NULL, so skip them,
1782          * i.e. the zone config is fixed with no masters or urls */
1783         if(!z || !x) return 1;
1784         if(!xfr_find_soa(z, x)) {
1785                 return 1;
1786         }
1787         /* nothing for probe, nextprobe and transfer tasks */
1788         return 1;
1789 }
1790
1791 /**
1792  * Setup all zones
1793  * @param az: auth zones structure
1794  * @return false on failure.
1795  */
1796 static int
1797 auth_zones_setup_zones(struct auth_zones* az)
1798 {
1799         struct auth_zone* z;
1800         struct auth_xfer* x;
1801         lock_rw_wrlock(&az->lock);
1802         RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
1803                 lock_rw_wrlock(&z->lock);
1804                 x = auth_xfer_find(az, z->name, z->namelen, z->dclass);
1805                 if(x) {
1806                         lock_basic_lock(&x->lock);
1807                 }
1808                 if(!auth_xfer_setup(z, x)) {
1809                         if(x) {
1810                                 lock_basic_unlock(&x->lock);
1811                         }
1812                         lock_rw_unlock(&z->lock);
1813                         lock_rw_unlock(&az->lock);
1814                         return 0;
1815                 }
1816                 if(x) {
1817                         lock_basic_unlock(&x->lock);
1818                 }
1819                 lock_rw_unlock(&z->lock);
1820         }
1821         lock_rw_unlock(&az->lock);
1822         return 1;
1823 }
1824
1825 /** set config items and create zones */
1826 static int
1827 auth_zones_cfg(struct auth_zones* az, struct config_auth* c)
1828 {
1829         struct auth_zone* z;
1830         struct auth_xfer* x = NULL;
1831
1832         /* create zone */
1833         lock_rw_wrlock(&az->lock);
1834         if(!(z=auth_zones_find_or_add_zone(az, c->name))) {
1835                 lock_rw_unlock(&az->lock);
1836                 return 0;
1837         }
1838         if(c->masters || c->urls) {
1839                 if(!(x=auth_zones_find_or_add_xfer(az, z))) {
1840                         lock_rw_unlock(&az->lock);
1841                         lock_rw_unlock(&z->lock);
1842                         return 0;
1843                 }
1844         }
1845         if(c->for_downstream)
1846                 az->have_downstream = 1;
1847         lock_rw_unlock(&az->lock);
1848
1849         /* set options */
1850         z->zone_deleted = 0;
1851         if(!auth_zone_set_zonefile(z, c->zonefile)) {
1852                 if(x) {
1853                         lock_basic_unlock(&x->lock);
1854                 }
1855                 lock_rw_unlock(&z->lock);
1856                 return 0;
1857         }
1858         z->for_downstream = c->for_downstream;
1859         z->for_upstream = c->for_upstream;
1860         z->fallback_enabled = c->fallback_enabled;
1861
1862         /* xfer zone */
1863         if(x) {
1864                 z->zone_is_slave = 1;
1865                 /* set options on xfer zone */
1866                 if(!xfer_set_masters(&x->task_probe->masters, c, 0)) {
1867                         lock_basic_unlock(&x->lock);
1868                         lock_rw_unlock(&z->lock);
1869                         return 0;
1870                 }
1871                 if(!xfer_set_masters(&x->task_transfer->masters, c, 1)) {
1872                         lock_basic_unlock(&x->lock);
1873                         lock_rw_unlock(&z->lock);
1874                         return 0;
1875                 }
1876                 lock_basic_unlock(&x->lock);
1877         }
1878
1879         lock_rw_unlock(&z->lock);
1880         return 1;
1881 }
1882
1883 /** set all auth zones deleted, then in auth_zones_cfg, it marks them
1884  * as nondeleted (if they are still in the config), and then later
1885  * we can find deleted zones */
1886 static void
1887 az_setall_deleted(struct auth_zones* az)
1888 {
1889         struct auth_zone* z;
1890         lock_rw_wrlock(&az->lock);
1891         RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
1892                 lock_rw_wrlock(&z->lock);
1893                 z->zone_deleted = 1;
1894                 lock_rw_unlock(&z->lock);
1895         }
1896         lock_rw_unlock(&az->lock);
1897 }
1898
1899 /** find zones that are marked deleted and delete them.
1900  * This is called from apply_cfg, and there are no threads and no
1901  * workers, so the xfr can just be deleted. */
1902 static void
1903 az_delete_deleted_zones(struct auth_zones* az)
1904 {
1905         struct auth_zone* z;
1906         struct auth_zone* delete_list = NULL, *next;
1907         struct auth_xfer* xfr;
1908         lock_rw_wrlock(&az->lock);
1909         RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
1910                 lock_rw_wrlock(&z->lock);
1911                 if(z->zone_deleted) {
1912                         /* we cannot alter the rbtree right now, but
1913                          * we can put it on a linked list and then
1914                          * delete it */
1915                         z->delete_next = delete_list;
1916                         delete_list = z;
1917                 }
1918                 lock_rw_unlock(&z->lock);
1919         }
1920         /* now we are out of the tree loop and we can loop and delete
1921          * the zones */
1922         z = delete_list;
1923         while(z) {
1924                 next = z->delete_next;
1925                 xfr = auth_xfer_find(az, z->name, z->namelen, z->dclass);
1926                 if(xfr) {
1927                         (void)rbtree_delete(&az->xtree, &xfr->node);
1928                         auth_xfer_delete(xfr);
1929                 }
1930                 (void)rbtree_delete(&az->ztree, &z->node);
1931                 auth_zone_delete(z);
1932                 z = next;
1933         }
1934         lock_rw_unlock(&az->lock);
1935 }
1936
1937 int auth_zones_apply_cfg(struct auth_zones* az, struct config_file* cfg,
1938         int setup)
1939 {
1940         struct config_auth* p;
1941         az_setall_deleted(az);
1942         for(p = cfg->auths; p; p = p->next) {
1943                 if(!p->name || p->name[0] == 0) {
1944                         log_warn("auth-zone without a name, skipped");
1945                         continue;
1946                 }
1947                 if(!auth_zones_cfg(az, p)) {
1948                         log_err("cannot config auth zone %s", p->name);
1949                         return 0;
1950                 }
1951         }
1952         az_delete_deleted_zones(az);
1953         if(!auth_zones_read_zones(az))
1954                 return 0;
1955         if(setup) {
1956                 if(!auth_zones_setup_zones(az))
1957                         return 0;
1958         }
1959         return 1;
1960 }
1961
1962 /** delete chunks
1963  * @param at: transfer structure with chunks list.  The chunks and their
1964  *      data are freed.
1965  */
1966 static void
1967 auth_chunks_delete(struct auth_transfer* at)
1968 {
1969         if(at->chunks_first) {
1970                 struct auth_chunk* c, *cn;
1971                 c = at->chunks_first;
1972                 while(c) {
1973                         cn = c->next;
1974                         free(c->data);
1975                         free(c);
1976                         c = cn;
1977                 }
1978         }
1979         at->chunks_first = NULL;
1980         at->chunks_last = NULL;
1981 }
1982
1983 /** free master addr list */
1984 static void
1985 auth_free_master_addrs(struct auth_addr* list)
1986 {
1987         struct auth_addr *n;
1988         while(list) {
1989                 n = list->next;
1990                 free(list);
1991                 list = n;
1992         }
1993 }
1994
1995 /** free the masters list */
1996 static void
1997 auth_free_masters(struct auth_master* list)
1998 {
1999         struct auth_master* n;
2000         while(list) {
2001                 n = list->next;
2002                 auth_free_master_addrs(list->list);
2003                 free(list->host);
2004                 free(list->file);
2005                 free(list);
2006                 list = n;
2007         }
2008 }
2009
2010 /** delete auth xfer structure
2011  * @param xfr: delete this xfer and its tasks.
2012  */
2013 static void
2014 auth_xfer_delete(struct auth_xfer* xfr)
2015 {
2016         if(!xfr) return;
2017         lock_basic_destroy(&xfr->lock);
2018         free(xfr->name);
2019         if(xfr->task_nextprobe) {
2020                 comm_timer_delete(xfr->task_nextprobe->timer);
2021                 free(xfr->task_nextprobe);
2022         }
2023         if(xfr->task_probe) {
2024                 auth_free_masters(xfr->task_probe->masters);
2025                 comm_point_delete(xfr->task_probe->cp);
2026                 free(xfr->task_probe);
2027         }
2028         if(xfr->task_transfer) {
2029                 auth_free_masters(xfr->task_transfer->masters);
2030                 comm_point_delete(xfr->task_transfer->cp);
2031                 if(xfr->task_transfer->chunks_first) {
2032                         auth_chunks_delete(xfr->task_transfer);
2033                 }
2034                 free(xfr->task_transfer);
2035         }
2036         auth_free_masters(xfr->allow_notify_list);
2037         free(xfr);
2038 }
2039
2040 /** helper traverse to delete zones */
2041 static void
2042 auth_zone_del(rbnode_type* n, void* ATTR_UNUSED(arg))
2043 {
2044         struct auth_zone* z = (struct auth_zone*)n->key;
2045         auth_zone_delete(z);
2046 }
2047
2048 /** helper traverse to delete xfer zones */
2049 static void
2050 auth_xfer_del(rbnode_type* n, void* ATTR_UNUSED(arg))
2051 {
2052         struct auth_xfer* z = (struct auth_xfer*)n->key;
2053         auth_xfer_delete(z);
2054 }
2055
2056 void auth_zones_delete(struct auth_zones* az)
2057 {
2058         if(!az) return;
2059         lock_rw_destroy(&az->lock);
2060         traverse_postorder(&az->ztree, auth_zone_del, NULL);
2061         traverse_postorder(&az->xtree, auth_xfer_del, NULL);
2062         free(az);
2063 }
2064
2065 /** true if domain has only nsec3 */
2066 static int
2067 domain_has_only_nsec3(struct auth_data* n)
2068 {
2069         struct auth_rrset* rrset = n->rrsets;
2070         int nsec3_seen = 0;
2071         while(rrset) {
2072                 if(rrset->type == LDNS_RR_TYPE_NSEC3) {
2073                         nsec3_seen = 1;
2074                 } else if(rrset->type != LDNS_RR_TYPE_RRSIG) {
2075                         return 0;
2076                 }
2077                 rrset = rrset->next;
2078         }
2079         return nsec3_seen;
2080 }
2081
2082 /** see if the domain has a wildcard child '*.domain' */
2083 static struct auth_data*
2084 az_find_wildcard_domain(struct auth_zone* z, uint8_t* nm, size_t nmlen)
2085 {
2086         uint8_t wc[LDNS_MAX_DOMAINLEN];
2087         if(nmlen+2 > sizeof(wc))
2088                 return NULL; /* result would be too long */
2089         wc[0] = 1; /* length of wildcard label */
2090         wc[1] = (uint8_t)'*'; /* wildcard label */
2091         memmove(wc+2, nm, nmlen);
2092         return az_find_name(z, wc, nmlen+2);
2093 }
2094
2095 /** find wildcard between qname and cename */
2096 static struct auth_data*
2097 az_find_wildcard(struct auth_zone* z, struct query_info* qinfo,
2098         struct auth_data* ce)
2099 {
2100         uint8_t* nm = qinfo->qname;
2101         size_t nmlen = qinfo->qname_len;
2102         struct auth_data* node;
2103         if(!dname_subdomain_c(nm, z->name))
2104                 return NULL; /* out of zone */
2105         while((node=az_find_wildcard_domain(z, nm, nmlen))==NULL) {
2106                 /* see if we can go up to find the wildcard */
2107                 if(nmlen == z->namelen)
2108                         return NULL; /* top of zone reached */
2109                 if(ce && nmlen == ce->namelen)
2110                         return NULL; /* ce reached */
2111                 if(dname_is_root(nm))
2112                         return NULL; /* cannot go up */
2113                 dname_remove_label(&nm, &nmlen);
2114         }
2115         return node;
2116 }
2117
2118 /** domain is not exact, find first candidate ce (name that matches
2119  * a part of qname) in tree */
2120 static struct auth_data*
2121 az_find_candidate_ce(struct auth_zone* z, struct query_info* qinfo,
2122         struct auth_data* n)
2123 {
2124         uint8_t* nm;
2125         size_t nmlen;
2126         if(n) {
2127                 nm = dname_get_shared_topdomain(qinfo->qname, n->name);
2128         } else {
2129                 nm = qinfo->qname;
2130         }
2131         dname_count_size_labels(nm, &nmlen);
2132         n = az_find_name(z, nm, nmlen);
2133         /* delete labels and go up on name */
2134         while(!n) {
2135                 if(dname_is_root(nm))
2136                         return NULL; /* cannot go up */
2137                 dname_remove_label(&nm, &nmlen);
2138                 n = az_find_name(z, nm, nmlen);
2139         }
2140         return n;
2141 }
2142
2143 /** go up the auth tree to next existing name. */
2144 static struct auth_data*
2145 az_domain_go_up(struct auth_zone* z, struct auth_data* n)
2146 {
2147         uint8_t* nm = n->name;
2148         size_t nmlen = n->namelen;
2149         while(!dname_is_root(nm)) {
2150                 dname_remove_label(&nm, &nmlen);
2151                 if((n=az_find_name(z, nm, nmlen)) != NULL)
2152                         return n;
2153         }
2154         return NULL;
2155 }
2156
2157 /** Find the closest encloser, an name that exists and is above the
2158  * qname.
2159  * return true if the node (param node) is existing, nonobscured and
2160  *      can be used to generate answers from.  It is then also node_exact.
2161  * returns false if the node is not good enough (or it wasn't node_exact)
2162  *      in this case the ce can be filled.
2163  *      if ce is NULL, no ce exists, and likely the zone is completely empty,
2164  *      not even with a zone apex.
2165  *      if ce is nonNULL it is the closest enclosing upper name (that exists
2166  *      itself for answer purposes).  That name may have DNAME, NS or wildcard
2167  *      rrset is the closest DNAME or NS rrset that was found.
2168  */
2169 static int
2170 az_find_ce(struct auth_zone* z, struct query_info* qinfo,
2171         struct auth_data* node, int node_exact, struct auth_data** ce,
2172         struct auth_rrset** rrset)
2173 {
2174         struct auth_data* n = node;
2175         *ce = NULL;
2176         *rrset = NULL;
2177         if(!node_exact) {
2178                 /* if not exact, lookup closest exact match */
2179                 n = az_find_candidate_ce(z, qinfo, n);
2180         } else {
2181                 /* if exact, the node itself is the first candidate ce */
2182                 *ce = n;
2183         }
2184
2185         /* no direct answer from nsec3-only domains */
2186         if(n && domain_has_only_nsec3(n)) {
2187                 node_exact = 0;
2188                 *ce = NULL;
2189         }
2190
2191         /* with exact matches, walk up the labels until we find the
2192          * delegation, or DNAME or zone end */
2193         while(n) {
2194                 /* see if the current candidate has issues */
2195                 /* not zone apex and has type NS */
2196                 if(n->namelen != z->namelen &&
2197                         (*rrset=az_domain_rrset(n, LDNS_RR_TYPE_NS)) &&
2198                         /* delegate here, but DS at exact the dp has notype */
2199                         (qinfo->qtype != LDNS_RR_TYPE_DS || 
2200                         n->namelen != qinfo->qname_len)) {
2201                         /* referral */
2202                         /* this is ce and the lowernode is nonexisting */
2203                         *ce = n;
2204                         return 0;
2205                 }
2206                 /* not equal to qname and has type DNAME */
2207                 if(n->namelen != qinfo->qname_len &&
2208                         (*rrset=az_domain_rrset(n, LDNS_RR_TYPE_DNAME))) {
2209                         /* this is ce and the lowernode is nonexisting */
2210                         *ce = n;
2211                         return 0;
2212                 }
2213
2214                 if(*ce == NULL && !domain_has_only_nsec3(n)) {
2215                         /* if not found yet, this exact name must be
2216                          * our lowest match (but not nsec3onlydomain) */
2217                         *ce = n;
2218                 }
2219
2220                 /* walk up the tree by removing labels from name and lookup */
2221                 n = az_domain_go_up(z, n);
2222         }
2223         /* found no problems, if it was an exact node, it is fine to use */
2224         return node_exact;
2225 }
2226
2227 /** add additional A/AAAA from domain names in rrset rdata (+offset)
2228  * offset is number of bytes in rdata where the dname is located. */
2229 static int
2230 az_add_additionals_from(struct auth_zone* z, struct regional* region,
2231         struct dns_msg* msg, struct auth_rrset* rrset, size_t offset)
2232 {
2233         struct packed_rrset_data* d = rrset->data;
2234         size_t i;
2235         if(!d) return 0;
2236         for(i=0; i<d->count; i++) {
2237                 size_t dlen;
2238                 struct auth_data* domain;
2239                 struct auth_rrset* ref;
2240                 if(d->rr_len[i] < 2+offset)
2241                         continue; /* too short */
2242                 if(!(dlen = dname_valid(d->rr_data[i]+2+offset,
2243                         d->rr_len[i]-2-offset)))
2244                         continue; /* malformed */
2245                 domain = az_find_name(z, d->rr_data[i]+2+offset, dlen);
2246                 if(!domain)
2247                         continue;
2248                 if((ref=az_domain_rrset(domain, LDNS_RR_TYPE_A)) != NULL) {
2249                         if(!msg_add_rrset_ar(z, region, msg, domain, ref))
2250                                 return 0;
2251                 }
2252                 if((ref=az_domain_rrset(domain, LDNS_RR_TYPE_AAAA)) != NULL) {
2253                         if(!msg_add_rrset_ar(z, region, msg, domain, ref))
2254                                 return 0;
2255                 }
2256         }
2257         return 1;
2258 }
2259
2260 /** add negative SOA record (with negative TTL) */
2261 static int
2262 az_add_negative_soa(struct auth_zone* z, struct regional* region,
2263         struct dns_msg* msg)
2264 {
2265         uint32_t minimum;
2266         struct packed_rrset_data* d;
2267         struct auth_rrset* soa;
2268         struct auth_data* apex = az_find_name(z, z->name, z->namelen);
2269         if(!apex) return 0;
2270         soa = az_domain_rrset(apex, LDNS_RR_TYPE_SOA);
2271         if(!soa) return 0;
2272         /* must be first to put in message; we want to fix the TTL with
2273          * one RRset here, otherwise we'd need to loop over the RRs to get
2274          * the resulting lower TTL */
2275         log_assert(msg->rep->rrset_count == 0);
2276         if(!msg_add_rrset_ns(z, region, msg, apex, soa)) return 0;
2277         /* fixup TTL */
2278         d = (struct packed_rrset_data*)msg->rep->rrsets[msg->rep->rrset_count-1]->entry.data;
2279         /* last 4 bytes are minimum ttl in network format */
2280         if(d->count == 0) return 0;
2281         if(d->rr_len[0] < 2+4) return 0;
2282         minimum = sldns_read_uint32(d->rr_data[0]+(d->rr_len[0]-4));
2283         d->ttl = (time_t)minimum;
2284         d->rr_ttl[0] = (time_t)minimum;
2285         msg->rep->ttl = get_rrset_ttl(msg->rep->rrsets[0]);
2286         msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
2287         return 1;
2288 }
2289
2290 /** See if the query goes to empty nonterminal (that has no auth_data,
2291  * but there are nodes underneath.  We already checked that there are
2292  * not NS, or DNAME above, so that we only need to check if some node
2293  * exists below (with nonempty rr list), return true if emptynonterminal */
2294 static int
2295 az_empty_nonterminal(struct auth_zone* z, struct query_info* qinfo,
2296         struct auth_data* node)
2297 {
2298         struct auth_data* next;
2299         if(!node) {
2300                 /* no smaller was found, use first (smallest) node as the
2301                  * next one */
2302                 next = (struct auth_data*)rbtree_first(&z->data);
2303         } else {
2304                 next = (struct auth_data*)rbtree_next(&node->node);
2305         }
2306         while(next && (rbnode_type*)next != RBTREE_NULL && next->rrsets == NULL) {
2307                 /* the next name has empty rrsets, is an empty nonterminal
2308                  * itself, see if there exists something below it */
2309                 next = (struct auth_data*)rbtree_next(&node->node);
2310         }
2311         if((rbnode_type*)next == RBTREE_NULL || !next) {
2312                 /* there is no next node, so something below it cannot
2313                  * exist */
2314                 return 0;
2315         }
2316         /* a next node exists, if there was something below the query,
2317          * this node has to be it.  See if it is below the query name */
2318         if(dname_strict_subdomain_c(next->name, qinfo->qname))
2319                 return 1;
2320         return 0;
2321 }
2322
2323 /** create synth cname target name in buffer, or fail if too long */
2324 static size_t
2325 synth_cname_buf(uint8_t* qname, size_t qname_len, size_t dname_len,
2326         uint8_t* dtarg, size_t dtarglen, uint8_t* buf, size_t buflen)
2327 {
2328         size_t newlen = qname_len + dtarglen - dname_len;
2329         if(newlen > buflen) {
2330                 /* YXDOMAIN error */
2331                 return 0;
2332         }
2333         /* new name is concatenation of qname front (without DNAME owner)
2334          * and DNAME target name */
2335         memcpy(buf, qname, qname_len-dname_len);
2336         memmove(buf+(qname_len-dname_len), dtarg, dtarglen);
2337         return newlen;
2338 }
2339
2340 /** create synthetic CNAME rrset for in a DNAME answer in region,
2341  * false on alloc failure, cname==NULL when name too long. */
2342 static int
2343 create_synth_cname(uint8_t* qname, size_t qname_len, struct regional* region,
2344         struct auth_data* node, struct auth_rrset* dname, uint16_t dclass,
2345         struct ub_packed_rrset_key** cname)
2346 {
2347         uint8_t buf[LDNS_MAX_DOMAINLEN];
2348         uint8_t* dtarg;
2349         size_t dtarglen, newlen;
2350         struct packed_rrset_data* d;
2351
2352         /* get DNAME target name */
2353         if(dname->data->count < 1) return 0;
2354         if(dname->data->rr_len[0] < 3) return 0; /* at least rdatalen +1 */
2355         dtarg = dname->data->rr_data[0]+2;
2356         dtarglen = dname->data->rr_len[0]-2;
2357         if(sldns_read_uint16(dname->data->rr_data[0]) != dtarglen)
2358                 return 0; /* rdatalen in DNAME rdata is malformed */
2359         if(dname_valid(dtarg, dtarglen) != dtarglen)
2360                 return 0; /* DNAME RR has malformed rdata */
2361
2362         /* synthesize a CNAME */
2363         newlen = synth_cname_buf(qname, qname_len, node->namelen,
2364                 dtarg, dtarglen, buf, sizeof(buf));
2365         if(newlen == 0) {
2366                 /* YXDOMAIN error */
2367                 *cname = NULL;
2368                 return 1;
2369         }
2370         *cname = (struct ub_packed_rrset_key*)regional_alloc(region,
2371                 sizeof(struct ub_packed_rrset_key));
2372         if(!*cname)
2373                 return 0; /* out of memory */
2374         memset(&(*cname)->entry, 0, sizeof((*cname)->entry));
2375         (*cname)->entry.key = (*cname);
2376         (*cname)->rk.type = htons(LDNS_RR_TYPE_CNAME);
2377         (*cname)->rk.rrset_class = htons(dclass);
2378         (*cname)->rk.flags = 0;
2379         (*cname)->rk.dname = regional_alloc_init(region, qname, qname_len);
2380         if(!(*cname)->rk.dname)
2381                 return 0; /* out of memory */
2382         (*cname)->rk.dname_len = qname_len;
2383         (*cname)->entry.hash = rrset_key_hash(&(*cname)->rk);
2384         d = (struct packed_rrset_data*)regional_alloc_zero(region,
2385                 sizeof(struct packed_rrset_data) + sizeof(size_t) +
2386                 sizeof(uint8_t*) + sizeof(time_t) + sizeof(uint16_t)
2387                 + newlen);
2388         if(!d)
2389                 return 0; /* out of memory */
2390         (*cname)->entry.data = d;
2391         d->ttl = 0; /* 0 for synthesized CNAME TTL */
2392         d->count = 1;
2393         d->rrsig_count = 0;
2394         d->trust = rrset_trust_ans_noAA;
2395         d->rr_len = (size_t*)((uint8_t*)d +
2396                 sizeof(struct packed_rrset_data));
2397         d->rr_len[0] = newlen + sizeof(uint16_t);
2398         packed_rrset_ptr_fixup(d);
2399         d->rr_ttl[0] = d->ttl;
2400         sldns_write_uint16(d->rr_data[0], newlen);
2401         memmove(d->rr_data[0] + sizeof(uint16_t), buf, newlen);
2402         return 1;
2403 }
2404
2405 /** add a synthesized CNAME to the answer section */
2406 static int
2407 add_synth_cname(struct auth_zone* z, uint8_t* qname, size_t qname_len,
2408         struct regional* region, struct dns_msg* msg, struct auth_data* dname,
2409         struct auth_rrset* rrset)
2410 {
2411         struct ub_packed_rrset_key* cname;
2412         /* synthesize a CNAME */
2413         if(!create_synth_cname(qname, qname_len, region, dname, rrset,
2414                 z->dclass, &cname)) {
2415                 /* out of memory */
2416                 return 0;
2417         }
2418         if(!cname) {
2419                 /* cname cannot be create because of YXDOMAIN */
2420                 msg->rep->flags |= LDNS_RCODE_YXDOMAIN;
2421                 return 1;
2422         }
2423         /* add cname to message */
2424         if(!msg_grow_array(region, msg))
2425                 return 0;
2426         msg->rep->rrsets[msg->rep->rrset_count] = cname;
2427         msg->rep->rrset_count++;
2428         msg->rep->an_numrrsets++;
2429         msg_ttl(msg);
2430         return 1;
2431 }
2432
2433 /** Change a dname to a different one, for wildcard namechange */
2434 static void
2435 az_change_dnames(struct dns_msg* msg, uint8_t* oldname, uint8_t* newname,
2436         size_t newlen, int an_only)
2437 {
2438         size_t i;
2439         size_t start = 0, end = msg->rep->rrset_count;
2440         if(!an_only) start = msg->rep->an_numrrsets;
2441         if(an_only) end = msg->rep->an_numrrsets;
2442         for(i=start; i<end; i++) {
2443                 /* allocated in region so we can change the ptrs */
2444                 if(query_dname_compare(msg->rep->rrsets[i]->rk.dname, oldname)
2445                         == 0) {
2446                         msg->rep->rrsets[i]->rk.dname = newname;
2447                         msg->rep->rrsets[i]->rk.dname_len = newlen;
2448                 }
2449         }
2450 }
2451
2452 /** find NSEC record covering the query */
2453 static struct auth_rrset*
2454 az_find_nsec_cover(struct auth_zone* z, struct auth_data** node)
2455 {
2456         uint8_t* nm = (*node)->name;
2457         size_t nmlen = (*node)->namelen;
2458         struct auth_rrset* rrset;
2459         /* find the NSEC for the smallest-or-equal node */
2460         /* if node == NULL, we did not find a smaller name.  But the zone
2461          * name is the smallest name and should have an NSEC. So there is
2462          * no NSEC to return (for a properly signed zone) */
2463         /* for empty nonterminals, the auth-data node should not exist,
2464          * and thus we don't need to go rbtree_previous here to find
2465          * a domain with an NSEC record */
2466         /* but there could be glue, and if this is node, then it has no NSEC.
2467          * Go up to find nonglue (previous) NSEC-holding nodes */
2468         while((rrset=az_domain_rrset(*node, LDNS_RR_TYPE_NSEC)) == NULL) {
2469                 if(dname_is_root(nm)) return NULL;
2470                 if(nmlen == z->namelen) return NULL;
2471                 dname_remove_label(&nm, &nmlen);
2472                 /* adjust *node for the nsec rrset to find in */
2473                 *node = az_find_name(z, nm, nmlen);
2474         }
2475         return rrset;
2476 }
2477
2478 /** Find NSEC and add for wildcard denial */
2479 static int
2480 az_nsec_wildcard_denial(struct auth_zone* z, struct regional* region,
2481         struct dns_msg* msg, uint8_t* cenm, size_t cenmlen)
2482 {
2483         struct query_info qinfo;
2484         int node_exact;
2485         struct auth_data* node;
2486         struct auth_rrset* nsec;
2487         uint8_t wc[LDNS_MAX_DOMAINLEN];
2488         if(cenmlen+2 > sizeof(wc))
2489                 return 0; /* result would be too long */
2490         wc[0] = 1; /* length of wildcard label */
2491         wc[1] = (uint8_t)'*'; /* wildcard label */
2492         memmove(wc+2, cenm, cenmlen);
2493
2494         /* we have '*.ce' in wc wildcard name buffer */
2495         /* get nsec cover for that */
2496         qinfo.qname = wc;
2497         qinfo.qname_len = cenmlen+2;
2498         qinfo.qtype = 0;
2499         qinfo.qclass = 0;
2500         az_find_domain(z, &qinfo, &node_exact, &node);
2501         if((nsec=az_find_nsec_cover(z, &node)) != NULL) {
2502                 if(!msg_add_rrset_ns(z, region, msg, node, nsec)) return 0;
2503         }
2504         return 1;
2505 }
2506
2507 /** Find the NSEC3PARAM rrset (if any) and if true you have the parameters */
2508 static int
2509 az_nsec3_param(struct auth_zone* z, int* algo, size_t* iter, uint8_t** salt,
2510         size_t* saltlen)
2511 {
2512         struct auth_data* apex;
2513         struct auth_rrset* param;
2514         size_t i;
2515         apex = az_find_name(z, z->name, z->namelen);
2516         if(!apex) return 0;
2517         param = az_domain_rrset(apex, LDNS_RR_TYPE_NSEC3PARAM);
2518         if(!param || param->data->count==0)
2519                 return 0; /* no RRset or no RRs in rrset */
2520         /* find out which NSEC3PARAM RR has supported parameters */
2521         /* skip unknown flags (dynamic signer is recalculating nsec3 chain) */
2522         for(i=0; i<param->data->count; i++) {
2523                 uint8_t* rdata = param->data->rr_data[i]+2;
2524                 size_t rdatalen = param->data->rr_len[i];
2525                 if(rdatalen < 2+5)
2526                         continue; /* too short */
2527                 if(!nsec3_hash_algo_size_supported((int)(rdata[0])))
2528                         continue; /* unsupported algo */
2529                 if(rdatalen < (size_t)(2+5+(size_t)rdata[4]))
2530                         continue; /* salt missing */
2531                 if((rdata[1]&NSEC3_UNKNOWN_FLAGS)!=0)
2532                         continue; /* unknown flags */
2533                 *algo = (int)(rdata[0]);
2534                 *iter = sldns_read_uint16(rdata+2);
2535                 *saltlen = rdata[4];
2536                 if(*saltlen == 0)
2537                         *salt = NULL;
2538                 else    *salt = rdata+5;
2539                 return 1;
2540         }
2541         /* no supported params */
2542         return 0;
2543 }
2544
2545 /** Hash a name with nsec3param into buffer, it has zone name appended.
2546  * return length of hash */
2547 static size_t
2548 az_nsec3_hash(uint8_t* buf, size_t buflen, uint8_t* nm, size_t nmlen,
2549         int algo, size_t iter, uint8_t* salt, size_t saltlen)
2550 {
2551         size_t hlen = nsec3_hash_algo_size_supported(algo);
2552         /* buffer has domain name, nsec3hash, and 256 is for max saltlen
2553          * (salt has 0-255 length) */
2554         unsigned char p[LDNS_MAX_DOMAINLEN+1+N3HASHBUFLEN+256];
2555         size_t i;
2556         if(nmlen+saltlen > sizeof(p) || hlen+saltlen > sizeof(p))
2557                 return 0;
2558         if(hlen > buflen)
2559                 return 0; /* somehow too large for destination buffer */
2560         /* hashfunc(name, salt) */
2561         memmove(p, nm, nmlen);
2562         query_dname_tolower(p);
2563         memmove(p+nmlen, salt, saltlen);
2564         (void)secalgo_nsec3_hash(algo, p, nmlen+saltlen, (unsigned char*)buf);
2565         for(i=0; i<iter; i++) {
2566                 /* hashfunc(hash, salt) */
2567                 memmove(p, buf, hlen);
2568                 memmove(p+hlen, salt, saltlen);
2569                 (void)secalgo_nsec3_hash(algo, p, hlen+saltlen,
2570                         (unsigned char*)buf);
2571         }
2572         return hlen;
2573 }
2574
2575 /** Hash name and return b32encoded hashname for lookup, zone name appended */
2576 static int
2577 az_nsec3_hashname(struct auth_zone* z, uint8_t* hashname, size_t* hashnmlen,
2578         uint8_t* nm, size_t nmlen, int algo, size_t iter, uint8_t* salt,
2579         size_t saltlen)
2580 {
2581         uint8_t hash[N3HASHBUFLEN];
2582         size_t hlen;
2583         int ret;
2584         hlen = az_nsec3_hash(hash, sizeof(hash), nm, nmlen, algo, iter,
2585                 salt, saltlen);
2586         if(!hlen) return 0;
2587         /* b32 encode */
2588         if(*hashnmlen < hlen*2+1+z->namelen) /* approx b32 as hexb16 */
2589                 return 0;
2590         ret = sldns_b32_ntop_extended_hex(hash, hlen, (char*)(hashname+1),
2591                 (*hashnmlen)-1);
2592         if(ret<1)
2593                 return 0;
2594         hashname[0] = (uint8_t)ret;
2595         ret++;
2596         if((*hashnmlen) - ret < z->namelen)
2597                 return 0;
2598         memmove(hashname+ret, z->name, z->namelen);
2599         *hashnmlen = z->namelen+(size_t)ret;
2600         return 1;
2601 }
2602
2603 /** Find the datanode that covers the nsec3hash-name */
2604 static struct auth_data*
2605 az_nsec3_findnode(struct auth_zone* z, uint8_t* hashnm, size_t hashnmlen)
2606 {
2607         struct query_info qinfo;
2608         struct auth_data* node;
2609         int node_exact;
2610         qinfo.qclass = 0;
2611         qinfo.qtype = 0;
2612         qinfo.qname = hashnm;
2613         qinfo.qname_len = hashnmlen;
2614         /* because canonical ordering and b32 nsec3 ordering are the same.
2615          * this is a good lookup to find the nsec3 name. */
2616         az_find_domain(z, &qinfo, &node_exact, &node);
2617         /* but we may have to skip non-nsec3 nodes */
2618         /* this may be a lot, the way to speed that up is to have a
2619          * separate nsec3 tree with nsec3 nodes */
2620         while(node && (rbnode_type*)node != RBTREE_NULL &&
2621                 !az_domain_rrset(node, LDNS_RR_TYPE_NSEC3)) {
2622                 node = (struct auth_data*)rbtree_previous(&node->node);
2623         }
2624         if((rbnode_type*)node == RBTREE_NULL)
2625                 node = NULL;
2626         return node;
2627 }
2628
2629 /** Find cover for hashed(nm, nmlen) (or NULL) */
2630 static struct auth_data*
2631 az_nsec3_find_cover(struct auth_zone* z, uint8_t* nm, size_t nmlen,
2632         int algo, size_t iter, uint8_t* salt, size_t saltlen)
2633 {
2634         struct auth_data* node;
2635         uint8_t hname[LDNS_MAX_DOMAINLEN];
2636         size_t hlen = sizeof(hname);
2637         if(!az_nsec3_hashname(z, hname, &hlen, nm, nmlen, algo, iter,
2638                 salt, saltlen))
2639                 return NULL;
2640         node = az_nsec3_findnode(z, hname, hlen);
2641         if(node)
2642                 return node;
2643         /* we did not find any, perhaps because the NSEC3 hash is before
2644          * the first hash, we have to find the 'last hash' in the zone */
2645         node = (struct auth_data*)rbtree_last(&z->data);
2646         while(node && (rbnode_type*)node != RBTREE_NULL &&
2647                 !az_domain_rrset(node, LDNS_RR_TYPE_NSEC3)) {
2648                 node = (struct auth_data*)rbtree_previous(&node->node);
2649         }
2650         if((rbnode_type*)node == RBTREE_NULL)
2651                 node = NULL;
2652         return node;
2653 }
2654
2655 /** Find exact match for hashed(nm, nmlen) NSEC3 record or NULL */
2656 static struct auth_data*
2657 az_nsec3_find_exact(struct auth_zone* z, uint8_t* nm, size_t nmlen,
2658         int algo, size_t iter, uint8_t* salt, size_t saltlen)
2659 {
2660         struct auth_data* node;
2661         uint8_t hname[LDNS_MAX_DOMAINLEN];
2662         size_t hlen = sizeof(hname);
2663         if(!az_nsec3_hashname(z, hname, &hlen, nm, nmlen, algo, iter,
2664                 salt, saltlen))
2665                 return NULL;
2666         node = az_find_name(z, hname, hlen);
2667         if(az_domain_rrset(node, LDNS_RR_TYPE_NSEC3))
2668                 return node;
2669         return NULL;
2670 }
2671
2672 /** Return nextcloser name (as a ref into the qname).  This is one label
2673  * more than the cenm (cename must be a suffix of qname) */
2674 static void
2675 az_nsec3_get_nextcloser(uint8_t* cenm, uint8_t* qname, size_t qname_len,
2676         uint8_t** nx, size_t* nxlen)
2677 {
2678         int celabs = dname_count_labels(cenm);
2679         int qlabs = dname_count_labels(qname);
2680         int strip = qlabs - celabs -1;
2681         log_assert(dname_strict_subdomain(qname, qlabs, cenm, celabs));
2682         *nx = qname;
2683         *nxlen = qname_len;
2684         if(strip>0)
2685                 dname_remove_labels(nx, nxlen, strip);
2686 }
2687
2688 /** Find the closest encloser that has exact NSEC3.
2689  * updated cenm to the new name. If it went up no-exact-ce is true. */
2690 static struct auth_data*
2691 az_nsec3_find_ce(struct auth_zone* z, uint8_t** cenm, size_t* cenmlen,
2692         int* no_exact_ce, int algo, size_t iter, uint8_t* salt, size_t saltlen)
2693 {
2694         struct auth_data* node;
2695         while((node = az_nsec3_find_exact(z, *cenm, *cenmlen,
2696                 algo, iter, salt, saltlen)) == NULL) {
2697                 if(*cenmlen == z->namelen) {
2698                         /* next step up would take us out of the zone. fail */
2699                         return NULL;
2700                 }
2701                 *no_exact_ce = 1;
2702                 dname_remove_label(cenm, cenmlen);
2703         }
2704         return node;
2705 }
2706
2707 /* Insert NSEC3 record in authority section, if NULL does nothing */
2708 static int
2709 az_nsec3_insert(struct auth_zone* z, struct regional* region,
2710         struct dns_msg* msg, struct auth_data* node)
2711 {
2712         struct auth_rrset* nsec3;
2713         if(!node) return 1; /* no node, skip this */
2714         nsec3 = az_domain_rrset(node, LDNS_RR_TYPE_NSEC3);
2715         if(!nsec3) return 1; /* if no nsec3 RR, skip it */
2716         if(!msg_add_rrset_ns(z, region, msg, node, nsec3)) return 0;
2717         return 1;
2718 }
2719
2720 /** add NSEC3 records to the zone for the nsec3 proof.
2721  * Specify with the flags with parts of the proof are required.
2722  * the ce is the exact matching name (for notype) but also delegation points.
2723  * qname is the one where the nextcloser name can be derived from.
2724  * If NSEC3 is not properly there (in the zone) nothing is added.
2725  * always enabled: include nsec3 proving about the Closest Encloser.
2726  *      that is an exact match that should exist for it.
2727  *      If that does not exist, a higher exact match + nxproof is enabled
2728  *      (for some sort of opt-out empty nonterminal cases).
2729  * nxproof: include denial of the qname.
2730  * wcproof: include denial of wildcard (wildcard.ce).
2731  */
2732 static int
2733 az_add_nsec3_proof(struct auth_zone* z, struct regional* region,
2734         struct dns_msg* msg, uint8_t* cenm, size_t cenmlen, uint8_t* qname,
2735         size_t qname_len, int nxproof, int wcproof)
2736 {
2737         int algo;
2738         size_t iter, saltlen;
2739         uint8_t* salt;
2740         int no_exact_ce = 0;
2741         struct auth_data* node;
2742
2743         /* find parameters of nsec3 proof */
2744         if(!az_nsec3_param(z, &algo, &iter, &salt, &saltlen))
2745                 return 1; /* no nsec3 */
2746         /* find ce that has an NSEC3 */
2747         node = az_nsec3_find_ce(z, &cenm, &cenmlen, &no_exact_ce,
2748                 algo, iter, salt, saltlen);
2749         if(no_exact_ce) nxproof = 1;
2750         if(!az_nsec3_insert(z, region, msg, node))
2751                 return 0;
2752
2753         if(nxproof) {
2754                 uint8_t* nx;
2755                 size_t nxlen;
2756                 /* create nextcloser domain name */
2757                 az_nsec3_get_nextcloser(cenm, qname, qname_len, &nx, &nxlen);
2758                 /* find nsec3 that matches or covers it */
2759                 node = az_nsec3_find_cover(z, nx, nxlen, algo, iter, salt,
2760                         saltlen);
2761                 if(!az_nsec3_insert(z, region, msg, node))
2762                         return 0;
2763         }
2764         if(wcproof) {
2765                 /* create wildcard name *.ce */
2766                 uint8_t wc[LDNS_MAX_DOMAINLEN];
2767                 size_t wclen;
2768                 if(cenmlen+2 > sizeof(wc))
2769                         return 0; /* result would be too long */
2770                 wc[0] = 1; /* length of wildcard label */
2771                 wc[1] = (uint8_t)'*'; /* wildcard label */
2772                 memmove(wc+2, cenm, cenmlen);
2773                 wclen = cenmlen+2;
2774                 /* find nsec3 that matches or covers it */
2775                 node = az_nsec3_find_cover(z, wc, wclen, algo, iter, salt,
2776                         saltlen);
2777                 if(!az_nsec3_insert(z, region, msg, node))
2778                         return 0;
2779         }
2780         return 1;
2781 }
2782
2783 /** generate answer for positive answer */
2784 static int
2785 az_generate_positive_answer(struct auth_zone* z, struct regional* region,
2786         struct dns_msg* msg, struct auth_data* node, struct auth_rrset* rrset)
2787 {
2788         if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
2789         /* see if we want additional rrs */
2790         if(rrset->type == LDNS_RR_TYPE_MX) {
2791                 if(!az_add_additionals_from(z, region, msg, rrset, 2))
2792                         return 0;
2793         } else if(rrset->type == LDNS_RR_TYPE_SRV) {
2794                 if(!az_add_additionals_from(z, region, msg, rrset, 6))
2795                         return 0;
2796         } else if(rrset->type == LDNS_RR_TYPE_NS) {
2797                 if(!az_add_additionals_from(z, region, msg, rrset, 0))
2798                         return 0;
2799         }
2800         return 1;
2801 }
2802
2803 /** generate answer for type ANY answer */
2804 static int
2805 az_generate_any_answer(struct auth_zone* z, struct regional* region,
2806         struct dns_msg* msg, struct auth_data* node)
2807 {
2808         struct auth_rrset* rrset;
2809         int added = 0;
2810         /* add a couple (at least one) RRs */
2811         if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_SOA)) != NULL) {
2812                 if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
2813                 added++;
2814         }
2815         if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_MX)) != NULL) {
2816                 if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
2817                 added++;
2818         }
2819         if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_A)) != NULL) {
2820                 if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
2821                 added++;
2822         }
2823         if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_AAAA)) != NULL) {
2824                 if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
2825                 added++;
2826         }
2827         if(added == 0 && node->rrsets) {
2828                 if(!msg_add_rrset_an(z, region, msg, node,
2829                         node->rrsets)) return 0;
2830         }
2831         return 1;
2832 }
2833
2834 /** follow cname chain and add more data to the answer section */
2835 static int
2836 follow_cname_chain(struct auth_zone* z, uint16_t qtype,
2837         struct regional* region, struct dns_msg* msg,
2838         struct packed_rrset_data* d)
2839 {
2840         int maxchain = 0;
2841         /* see if we can add the target of the CNAME into the answer */
2842         while(maxchain++ < MAX_CNAME_CHAIN) {
2843                 struct auth_data* node;
2844                 struct auth_rrset* rrset;
2845                 size_t clen;
2846                 /* d has cname rdata */
2847                 if(d->count == 0) break; /* no CNAME */
2848                 if(d->rr_len[0] < 2+1) break; /* too small */
2849                 if((clen=dname_valid(d->rr_data[0]+2, d->rr_len[0]-2))==0)
2850                         break; /* malformed */
2851                 if(!dname_subdomain_c(d->rr_data[0]+2, z->name))
2852                         break; /* target out of zone */
2853                 if((node = az_find_name(z, d->rr_data[0]+2, clen))==NULL)
2854                         break; /* no such target name */
2855                 if((rrset=az_domain_rrset(node, qtype))!=NULL) {
2856                         /* done we found the target */
2857                         if(!msg_add_rrset_an(z, region, msg, node, rrset))
2858                                 return 0;
2859                         break;
2860                 }
2861                 if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_CNAME))==NULL)
2862                         break; /* no further CNAME chain, notype */
2863                 if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
2864                 d = rrset->data;
2865         }
2866         return 1;
2867 }
2868
2869 /** generate answer for cname answer */
2870 static int
2871 az_generate_cname_answer(struct auth_zone* z, struct query_info* qinfo,
2872         struct regional* region, struct dns_msg* msg,
2873         struct auth_data* node, struct auth_rrset* rrset)
2874 {
2875         if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
2876         if(!rrset) return 1;
2877         if(!follow_cname_chain(z, qinfo->qtype, region, msg, rrset->data))
2878                 return 0;
2879         return 1;
2880 }
2881
2882 /** generate answer for notype answer */
2883 static int
2884 az_generate_notype_answer(struct auth_zone* z, struct regional* region,
2885         struct dns_msg* msg, struct auth_data* node)
2886 {
2887         struct auth_rrset* rrset;
2888         if(!az_add_negative_soa(z, region, msg)) return 0;
2889         /* DNSSEC denial NSEC */
2890         if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_NSEC))!=NULL) {
2891                 if(!msg_add_rrset_ns(z, region, msg, node, rrset)) return 0;
2892         } else if(node) {
2893                 /* DNSSEC denial NSEC3 */
2894                 if(!az_add_nsec3_proof(z, region, msg, node->name,
2895                         node->namelen, msg->qinfo.qname,
2896                         msg->qinfo.qname_len, 0, 0))
2897                         return 0;
2898         }
2899         return 1;
2900 }
2901
2902 /** generate answer for referral answer */
2903 static int
2904 az_generate_referral_answer(struct auth_zone* z, struct regional* region,
2905         struct dns_msg* msg, struct auth_data* ce, struct auth_rrset* rrset)
2906 {
2907         struct auth_rrset* ds, *nsec;
2908         /* turn off AA flag, referral is nonAA because it leaves the zone */
2909         log_assert(ce);
2910         msg->rep->flags &= ~BIT_AA;
2911         if(!msg_add_rrset_ns(z, region, msg, ce, rrset)) return 0;
2912         /* add DS or deny it */
2913         if((ds=az_domain_rrset(ce, LDNS_RR_TYPE_DS))!=NULL) {
2914                 if(!msg_add_rrset_ns(z, region, msg, ce, ds)) return 0;
2915         } else {
2916                 /* deny the DS */
2917                 if((nsec=az_domain_rrset(ce, LDNS_RR_TYPE_NSEC))!=NULL) {
2918                         if(!msg_add_rrset_ns(z, region, msg, ce, nsec))
2919                                 return 0;
2920                 } else {
2921                         if(!az_add_nsec3_proof(z, region, msg, ce->name,
2922                                 ce->namelen, msg->qinfo.qname,
2923                                 msg->qinfo.qname_len, 0, 0))
2924                                 return 0;
2925                 }
2926         }
2927         /* add additional rrs for type NS */
2928         if(!az_add_additionals_from(z, region, msg, rrset, 0)) return 0;
2929         return 1;
2930 }
2931
2932 /** generate answer for DNAME answer */
2933 static int
2934 az_generate_dname_answer(struct auth_zone* z, struct query_info* qinfo,
2935         struct regional* region, struct dns_msg* msg, struct auth_data* ce,
2936         struct auth_rrset* rrset)
2937 {
2938         log_assert(ce);
2939         /* add the DNAME and then a CNAME */
2940         if(!msg_add_rrset_an(z, region, msg, ce, rrset)) return 0;
2941         if(!add_synth_cname(z, qinfo->qname, qinfo->qname_len, region,
2942                 msg, ce, rrset)) return 0;
2943         if(FLAGS_GET_RCODE(msg->rep->flags) == LDNS_RCODE_YXDOMAIN)
2944                 return 1;
2945         if(msg->rep->rrset_count == 0 ||
2946                 !msg->rep->rrsets[msg->rep->rrset_count-1])
2947                 return 0;
2948         if(!follow_cname_chain(z, qinfo->qtype, region, msg, 
2949                 (struct packed_rrset_data*)msg->rep->rrsets[
2950                 msg->rep->rrset_count-1]->entry.data))
2951                 return 0;
2952         return 1;
2953 }
2954
2955 /** generate answer for wildcard answer */
2956 static int
2957 az_generate_wildcard_answer(struct auth_zone* z, struct query_info* qinfo,
2958         struct regional* region, struct dns_msg* msg, struct auth_data* ce,
2959         struct auth_data* wildcard, struct auth_data* node)
2960 {
2961         struct auth_rrset* rrset, *nsec;
2962         if((rrset=az_domain_rrset(wildcard, qinfo->qtype)) != NULL) {
2963                 /* wildcard has type, add it */
2964                 if(!msg_add_rrset_an(z, region, msg, wildcard, rrset))
2965                         return 0;
2966                 az_change_dnames(msg, wildcard->name, msg->qinfo.qname,
2967                         msg->qinfo.qname_len, 1);
2968         } else if((rrset=az_domain_rrset(wildcard, LDNS_RR_TYPE_CNAME))!=NULL) {
2969                 /* wildcard has cname instead, do that */
2970                 if(!msg_add_rrset_an(z, region, msg, wildcard, rrset))
2971                         return 0;
2972                 az_change_dnames(msg, wildcard->name, msg->qinfo.qname,
2973                         msg->qinfo.qname_len, 1);
2974                 if(!follow_cname_chain(z, qinfo->qtype, region, msg,
2975                         rrset->data))
2976                         return 0;
2977         } else if(qinfo->qtype == LDNS_RR_TYPE_ANY && wildcard->rrsets) {
2978                 /* add ANY rrsets from wildcard node */
2979                 if(!az_generate_any_answer(z, region, msg, wildcard))
2980                         return 0;
2981                 az_change_dnames(msg, wildcard->name, msg->qinfo.qname,
2982                         msg->qinfo.qname_len, 1);
2983         } else {
2984                 /* wildcard has nodata, notype answer */
2985                 /* call other notype routine for dnssec notype denials */
2986                 if(!az_generate_notype_answer(z, region, msg, wildcard))
2987                         return 0;
2988         }
2989
2990         /* ce and node for dnssec denial of wildcard original name */
2991         if((nsec=az_find_nsec_cover(z, &node)) != NULL) {
2992                 if(!msg_add_rrset_ns(z, region, msg, node, nsec)) return 0;
2993         } else if(ce) {
2994                 if(!az_add_nsec3_proof(z, region, msg, ce->name,
2995                         ce->namelen, msg->qinfo.qname,
2996                         msg->qinfo.qname_len, 1, 0))
2997                         return 0;
2998         }
2999
3000         /* fixup name of wildcard from *.zone to qname, use already allocated
3001          * pointer to msg qname */
3002         az_change_dnames(msg, wildcard->name, msg->qinfo.qname,
3003                 msg->qinfo.qname_len, 0);
3004         return 1;
3005 }
3006
3007 /** generate answer for nxdomain answer */
3008 static int
3009 az_generate_nxdomain_answer(struct auth_zone* z, struct regional* region,
3010         struct dns_msg* msg, struct auth_data* ce, struct auth_data* node)
3011 {
3012         struct auth_rrset* nsec;
3013         msg->rep->flags |= LDNS_RCODE_NXDOMAIN;
3014         if(!az_add_negative_soa(z, region, msg)) return 0;
3015         if((nsec=az_find_nsec_cover(z, &node)) != NULL) {
3016                 if(!msg_add_rrset_ns(z, region, msg, node, nsec)) return 0;
3017                 if(ce && !az_nsec_wildcard_denial(z, region, msg, ce->name,
3018                         ce->namelen)) return 0;
3019         } else if(ce) {
3020                 if(!az_add_nsec3_proof(z, region, msg, ce->name,
3021                         ce->namelen, msg->qinfo.qname,
3022                         msg->qinfo.qname_len, 1, 1))
3023                         return 0;
3024         }
3025         return 1;
3026 }
3027
3028 /** Create answers when an exact match exists for the domain name */
3029 static int
3030 az_generate_answer_with_node(struct auth_zone* z, struct query_info* qinfo,
3031         struct regional* region, struct dns_msg* msg, struct auth_data* node)
3032 {
3033         struct auth_rrset* rrset;
3034         /* positive answer, rrset we are looking for exists */
3035         if((rrset=az_domain_rrset(node, qinfo->qtype)) != NULL) {
3036                 return az_generate_positive_answer(z, region, msg, node, rrset);
3037         }
3038         /* CNAME? */
3039         if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_CNAME)) != NULL) {
3040                 return az_generate_cname_answer(z, qinfo, region, msg,
3041                         node, rrset);
3042         }
3043         /* type ANY ? */
3044         if(qinfo->qtype == LDNS_RR_TYPE_ANY) {
3045                 return az_generate_any_answer(z, region, msg, node);
3046         }
3047         /* NOERROR/NODATA (no such type at domain name) */
3048         return az_generate_notype_answer(z, region, msg, node);
3049 }
3050
3051 /** Generate answer without an existing-node that we can use.
3052  * So it'll be a referral, DNAME or nxdomain */
3053 static int
3054 az_generate_answer_nonexistnode(struct auth_zone* z, struct query_info* qinfo,
3055         struct regional* region, struct dns_msg* msg, struct auth_data* ce,
3056         struct auth_rrset* rrset, struct auth_data* node)
3057 {
3058         struct auth_data* wildcard;
3059
3060         /* we do not have an exact matching name (that exists) */
3061         /* see if we have a NS or DNAME in the ce */
3062         if(ce && rrset && rrset->type == LDNS_RR_TYPE_NS) {
3063                 return az_generate_referral_answer(z, region, msg, ce, rrset);
3064         }
3065         if(ce && rrset && rrset->type == LDNS_RR_TYPE_DNAME) {
3066                 return az_generate_dname_answer(z, qinfo, region, msg, ce,
3067                         rrset);
3068         }
3069         /* if there is an empty nonterminal, wildcard and nxdomain don't
3070          * happen, it is a notype answer */
3071         if(az_empty_nonterminal(z, qinfo, node)) {
3072                 return az_generate_notype_answer(z, region, msg, node);
3073         }
3074         /* see if we have a wildcard under the ce */
3075         if((wildcard=az_find_wildcard(z, qinfo, ce)) != NULL) {
3076                 return az_generate_wildcard_answer(z, qinfo, region, msg,
3077                         ce, wildcard, node);
3078         }
3079         /* generate nxdomain answer */
3080         return az_generate_nxdomain_answer(z, region, msg, ce, node);
3081 }
3082
3083 /** Lookup answer in a zone. */
3084 static int
3085 auth_zone_generate_answer(struct auth_zone* z, struct query_info* qinfo,
3086         struct regional* region, struct dns_msg** msg, int* fallback)
3087 {
3088         struct auth_data* node, *ce;
3089         struct auth_rrset* rrset;
3090         int node_exact, node_exists;
3091         /* does the zone want fallback in case of failure? */
3092         *fallback = z->fallback_enabled;
3093         if(!(*msg=msg_create(region, qinfo))) return 0;
3094
3095         /* lookup if there is a matching domain name for the query */
3096         az_find_domain(z, qinfo, &node_exact, &node);
3097
3098         /* see if node exists for generating answers from (i.e. not glue and
3099          * obscured by NS or DNAME or NSEC3-only), and also return the
3100          * closest-encloser from that, closest node that should be used
3101          * to generate answers from that is above the query */
3102         node_exists = az_find_ce(z, qinfo, node, node_exact, &ce, &rrset);
3103
3104         if(verbosity >= VERB_ALGO) {
3105                 char zname[256], qname[256], nname[256], cename[256],
3106                         tpstr[32], rrstr[32];
3107                 sldns_wire2str_dname_buf(qinfo->qname, qinfo->qname_len, qname,
3108                         sizeof(qname));
3109                 sldns_wire2str_type_buf(qinfo->qtype, tpstr, sizeof(tpstr));
3110                 sldns_wire2str_dname_buf(z->name, z->namelen, zname,
3111                         sizeof(zname));
3112                 if(node)
3113                         sldns_wire2str_dname_buf(node->name, node->namelen,
3114                                 nname, sizeof(nname));
3115                 else    snprintf(nname, sizeof(nname), "NULL");
3116                 if(ce)
3117                         sldns_wire2str_dname_buf(ce->name, ce->namelen,
3118                                 cename, sizeof(cename));
3119                 else    snprintf(cename, sizeof(cename), "NULL");
3120                 if(rrset) sldns_wire2str_type_buf(rrset->type, rrstr,
3121                         sizeof(rrstr));
3122                 else    snprintf(rrstr, sizeof(rrstr), "NULL");
3123                 log_info("auth_zone %s query %s %s, domain %s %s %s, "
3124                         "ce %s, rrset %s", zname, qname, tpstr, nname,
3125                         (node_exact?"exact":"notexact"),
3126                         (node_exists?"exist":"notexist"), cename, rrstr);
3127         }
3128
3129         if(node_exists) {
3130                 /* the node is fine, generate answer from node */
3131                 return az_generate_answer_with_node(z, qinfo, region, *msg,
3132                         node);
3133         }
3134         return az_generate_answer_nonexistnode(z, qinfo, region, *msg,
3135                 ce, rrset, node);
3136 }
3137
3138 int auth_zones_lookup(struct auth_zones* az, struct query_info* qinfo,
3139         struct regional* region, struct dns_msg** msg, int* fallback,
3140         uint8_t* dp_nm, size_t dp_nmlen)
3141 {
3142         int r;
3143         struct auth_zone* z;
3144         /* find the zone that should contain the answer. */
3145         lock_rw_rdlock(&az->lock);
3146         z = auth_zone_find(az, dp_nm, dp_nmlen, qinfo->qclass);
3147         if(!z) {
3148                 lock_rw_unlock(&az->lock);
3149                 /* no auth zone, fallback to internet */
3150                 *fallback = 1;
3151                 return 0;
3152         }
3153         lock_rw_rdlock(&z->lock);
3154         lock_rw_unlock(&az->lock);
3155
3156         /* if not for upstream queries, fallback */
3157         if(!z->for_upstream) {
3158                 lock_rw_unlock(&z->lock);
3159                 *fallback = 1;
3160                 return 0;
3161         }
3162         /* see what answer that zone would generate */
3163         r = auth_zone_generate_answer(z, qinfo, region, msg, fallback);
3164         lock_rw_unlock(&z->lock);
3165         return r;
3166 }
3167
3168 /** encode auth answer */
3169 static void
3170 auth_answer_encode(struct query_info* qinfo, struct module_env* env,
3171         struct edns_data* edns, sldns_buffer* buf, struct regional* temp,
3172         struct dns_msg* msg)
3173 {
3174         uint16_t udpsize;
3175         udpsize = edns->udp_size;
3176         edns->edns_version = EDNS_ADVERTISED_VERSION;
3177         edns->udp_size = EDNS_ADVERTISED_SIZE;
3178         edns->ext_rcode = 0;
3179         edns->bits &= EDNS_DO;
3180
3181         if(!inplace_cb_reply_local_call(env, qinfo, NULL, msg->rep,
3182                 (int)FLAGS_GET_RCODE(msg->rep->flags), edns, temp)
3183                 || !reply_info_answer_encode(qinfo, msg->rep,
3184                 *(uint16_t*)sldns_buffer_begin(buf),
3185                 sldns_buffer_read_u16_at(buf, 2),
3186                 buf, 0, 0, temp, udpsize, edns,
3187                 (int)(edns->bits&EDNS_DO), 0)) {
3188                 error_encode(buf, (LDNS_RCODE_SERVFAIL|BIT_AA), qinfo,
3189                         *(uint16_t*)sldns_buffer_begin(buf),
3190                         sldns_buffer_read_u16_at(buf, 2), edns);
3191         }
3192 }
3193
3194 /** encode auth error answer */
3195 static void
3196 auth_error_encode(struct query_info* qinfo, struct module_env* env,
3197         struct edns_data* edns, sldns_buffer* buf, struct regional* temp,
3198         int rcode)
3199 {
3200         edns->edns_version = EDNS_ADVERTISED_VERSION;
3201         edns->udp_size = EDNS_ADVERTISED_SIZE;
3202         edns->ext_rcode = 0;
3203         edns->bits &= EDNS_DO;
3204
3205         if(!inplace_cb_reply_local_call(env, qinfo, NULL, NULL,
3206                 rcode, edns, temp))
3207                 edns->opt_list = NULL;
3208         error_encode(buf, rcode|BIT_AA, qinfo,
3209                 *(uint16_t*)sldns_buffer_begin(buf),
3210                 sldns_buffer_read_u16_at(buf, 2), edns);
3211 }
3212
3213 int auth_zones_answer(struct auth_zones* az, struct module_env* env,
3214         struct query_info* qinfo, struct edns_data* edns, struct sldns_buffer* buf,
3215         struct regional* temp)
3216 {
3217         struct dns_msg* msg = NULL;
3218         struct auth_zone* z;
3219         int r;
3220         int fallback = 0;
3221
3222         lock_rw_rdlock(&az->lock);
3223         if(!az->have_downstream) {
3224                 /* no downstream auth zones */
3225                 lock_rw_unlock(&az->lock);
3226                 return 0;
3227         }
3228         if(qinfo->qtype == LDNS_RR_TYPE_DS) {
3229                 uint8_t* delname = qinfo->qname;
3230                 size_t delnamelen = qinfo->qname_len;
3231                 dname_remove_label(&delname, &delnamelen);
3232                 z = auth_zones_find_zone(az, delname, delnamelen,
3233                         qinfo->qclass);
3234         } else {
3235                 z = auth_zones_find_zone(az, qinfo->qname, qinfo->qname_len,
3236                         qinfo->qclass);
3237         }
3238         if(!z) {
3239                 /* no zone above it */
3240                 lock_rw_unlock(&az->lock);
3241                 return 0;
3242         }
3243         lock_rw_rdlock(&z->lock);
3244         lock_rw_unlock(&az->lock);
3245         if(!z->for_downstream) {
3246                 lock_rw_unlock(&z->lock);
3247                 return 0;
3248         }
3249
3250         /* answer it from zone z */
3251         r = auth_zone_generate_answer(z, qinfo, temp, &msg, &fallback);
3252         lock_rw_unlock(&z->lock);
3253         if(!r && fallback) {
3254                 /* fallback to regular answering (recursive) */
3255                 return 0;
3256         }
3257         lock_rw_wrlock(&az->lock);
3258         az->num_query_down++;
3259         lock_rw_unlock(&az->lock);
3260
3261         /* encode answer */
3262         if(!r)
3263                 auth_error_encode(qinfo, env, edns, buf, temp,
3264                         LDNS_RCODE_SERVFAIL);
3265         else    auth_answer_encode(qinfo, env, edns, buf, temp, msg);
3266
3267         return 1;
3268 }
3269
3270 int auth_zones_can_fallback(struct auth_zones* az, uint8_t* nm, size_t nmlen,
3271         uint16_t dclass)
3272 {
3273         int r;
3274         struct auth_zone* z;
3275         lock_rw_rdlock(&az->lock);
3276         z = auth_zone_find(az, nm, nmlen, dclass);
3277         if(!z) {
3278                 lock_rw_unlock(&az->lock);
3279                 /* no such auth zone, fallback */
3280                 return 1;
3281         }
3282         lock_rw_rdlock(&z->lock);
3283         lock_rw_unlock(&az->lock);
3284         r = z->fallback_enabled || (!z->for_upstream);
3285         lock_rw_unlock(&z->lock);
3286         return r;
3287 }
3288
3289 int
3290 auth_zone_parse_notify_serial(sldns_buffer* pkt, uint32_t *serial)
3291 {
3292         struct query_info q;
3293         uint16_t rdlen;
3294         memset(&q, 0, sizeof(q));
3295         sldns_buffer_set_position(pkt, 0);
3296         if(!query_info_parse(&q, pkt)) return 0;
3297         if(LDNS_ANCOUNT(sldns_buffer_begin(pkt)) == 0) return 0;
3298         /* skip name of RR in answer section */
3299         if(sldns_buffer_remaining(pkt) < 1) return 0;
3300         if(pkt_dname_len(pkt) == 0) return 0;
3301         /* check type */
3302         if(sldns_buffer_remaining(pkt) < 10 /* type,class,ttl,rdatalen*/)
3303                 return 0;
3304         if(sldns_buffer_read_u16(pkt) != LDNS_RR_TYPE_SOA) return 0;
3305         sldns_buffer_skip(pkt, 2); /* class */
3306         sldns_buffer_skip(pkt, 4); /* ttl */
3307         rdlen = sldns_buffer_read_u16(pkt); /* rdatalen */
3308         if(sldns_buffer_remaining(pkt) < rdlen) return 0;
3309         if(rdlen < 22) return 0; /* bad soa length */
3310         sldns_buffer_skip(pkt, (ssize_t)(rdlen-20));
3311         *serial = sldns_buffer_read_u32(pkt);
3312         /* return true when has serial in answer section */
3313         return 1;
3314 }
3315
3316 /** see if addr appears in the list */
3317 static int
3318 addr_in_list(struct auth_addr* list, struct sockaddr_storage* addr,
3319         socklen_t addrlen)
3320 {
3321         struct auth_addr* p;
3322         for(p=list; p; p=p->next) {
3323                 if(sockaddr_cmp_addr(addr, addrlen, &p->addr, p->addrlen)==0)
3324                         return 1;
3325         }
3326         return 0;
3327 }
3328
3329 /** check if an address matches a master specification (or one of its
3330  * addresses in the addr list) */
3331 static int
3332 addr_matches_master(struct auth_master* master, struct sockaddr_storage* addr,
3333         socklen_t addrlen, struct auth_master** fromhost)
3334 {
3335         struct sockaddr_storage a;
3336         socklen_t alen = 0;
3337         int net = 0;
3338         if(addr_in_list(master->list, addr, addrlen)) {
3339                 *fromhost = master;
3340                 return 1;       
3341         }
3342         /* compare address (but not port number, that is the destination
3343          * port of the master, the port number of the received notify is
3344          * allowed to by any port on that master) */
3345         if(extstrtoaddr(master->host, &a, &alen) &&
3346                 sockaddr_cmp_addr(addr, addrlen, &a, alen)==0) {
3347                 *fromhost = master;
3348                 return 1;
3349         }
3350         /* prefixes, addr/len, like 10.0.0.0/8 */
3351         /* not http and has a / and there is one / */
3352         if(master->allow_notify && !master->http &&
3353                 strchr(master->host, '/') != NULL &&
3354                 strchr(master->host, '/') == strrchr(master->host, '/') &&
3355                 netblockstrtoaddr(master->host, UNBOUND_DNS_PORT, &a, &alen,
3356                 &net) && alen == addrlen) {
3357                 if(addr_in_common(addr, (addr_is_ip6(addr, addrlen)?128:32),
3358                         &a, net, alen) >= net) {
3359                         *fromhost = NULL; /* prefix does not have destination
3360                                 to send the probe or transfer with */
3361                         return 1; /* matches the netblock */
3362                 }
3363         }
3364         return 0;
3365 }
3366
3367 /** check access list for notifies */
3368 static int
3369 az_xfr_allowed_notify(struct auth_xfer* xfr, struct sockaddr_storage* addr,
3370         socklen_t addrlen, struct auth_master** fromhost)
3371 {
3372         struct auth_master* p;
3373         for(p=xfr->allow_notify_list; p; p=p->next) {
3374                 if(addr_matches_master(p, addr, addrlen, fromhost)) {
3375                         return 1;
3376                 }
3377         }
3378         return 0;
3379 }
3380
3381 /** see if the serial means the zone has to be updated, i.e. the serial
3382  * is newer than the zone serial, or we have no zone */
3383 static int
3384 xfr_serial_means_update(struct auth_xfer* xfr, uint32_t serial)
3385 {
3386         if(!xfr->have_zone)
3387                 return 1; /* no zone, anything is better */
3388         if(xfr->zone_expired)
3389                 return 1; /* expired, the sent serial is better than expired
3390                         data */
3391         if(compare_serial(xfr->serial, serial) < 0)
3392                 return 1; /* our serial is smaller than the sent serial,
3393                         the data is newer, fetch it */
3394         return 0;
3395 }
3396
3397 /** note notify serial, updates the notify information in the xfr struct */
3398 static void
3399 xfr_note_notify_serial(struct auth_xfer* xfr, int has_serial, uint32_t serial)
3400 {
3401         if(xfr->notify_received && xfr->notify_has_serial && has_serial) {
3402                 /* see if this serial is newer */
3403                 if(compare_serial(xfr->notify_serial, serial) < 0)
3404                         xfr->notify_serial = serial;
3405         } else if(xfr->notify_received && xfr->notify_has_serial &&
3406                 !has_serial) {
3407                 /* remove serial, we have notify without serial */
3408                 xfr->notify_has_serial = 0;
3409                 xfr->notify_serial = 0;
3410         } else if(xfr->notify_received && !xfr->notify_has_serial) {
3411                 /* we already have notify without serial, keep it
3412                  * that way; no serial check when current operation
3413                  * is done */
3414         } else {
3415                 xfr->notify_received = 1;
3416                 xfr->notify_has_serial = has_serial;
3417                 xfr->notify_serial = serial;
3418         }
3419 }
3420
3421 /** process a notify serial, start new probe or note serial. xfr is locked */
3422 static void
3423 xfr_process_notify(struct auth_xfer* xfr, struct module_env* env,
3424         int has_serial, uint32_t serial, struct auth_master* fromhost)
3425 {
3426         /* if the serial of notify is older than we have, don't fetch
3427          * a zone, we already have it */
3428         if(has_serial && !xfr_serial_means_update(xfr, serial)) {
3429                 lock_basic_unlock(&xfr->lock);
3430                 return;
3431         }
3432         /* start new probe with this addr src, or note serial */
3433         if(!xfr_start_probe(xfr, env, fromhost)) {
3434                 /* not started because already in progress, note the serial */
3435                 xfr_note_notify_serial(xfr, has_serial, serial);
3436                 lock_basic_unlock(&xfr->lock);
3437         }
3438         /* successful end of start_probe unlocked xfr->lock */
3439 }
3440
3441 int auth_zones_notify(struct auth_zones* az, struct module_env* env,
3442         uint8_t* nm, size_t nmlen, uint16_t dclass,
3443         struct sockaddr_storage* addr, socklen_t addrlen, int has_serial,
3444         uint32_t serial, int* refused)
3445 {
3446         struct auth_xfer* xfr;
3447         struct auth_master* fromhost = NULL;
3448         /* see which zone this is */
3449         lock_rw_rdlock(&az->lock);
3450         xfr = auth_xfer_find(az, nm, nmlen, dclass);
3451         if(!xfr) {
3452                 lock_rw_unlock(&az->lock);
3453                 /* no such zone, refuse the notify */
3454                 *refused = 1;
3455                 return 0;
3456         }
3457         lock_basic_lock(&xfr->lock);
3458         lock_rw_unlock(&az->lock);
3459         
3460         /* check access list for notifies */
3461         if(!az_xfr_allowed_notify(xfr, addr, addrlen, &fromhost)) {
3462                 lock_basic_unlock(&xfr->lock);
3463                 /* notify not allowed, refuse the notify */
3464                 *refused = 1;
3465                 return 0;
3466         }
3467
3468         /* process the notify */
3469         xfr_process_notify(xfr, env, has_serial, serial, fromhost);
3470         return 1;
3471 }
3472
3473 /** set a zone expired */
3474 static void
3475 auth_xfer_set_expired(struct auth_xfer* xfr, struct module_env* env,
3476         int expired)
3477 {
3478         struct auth_zone* z;
3479
3480         /* expire xfr */
3481         lock_basic_lock(&xfr->lock);
3482         xfr->zone_expired = expired;
3483         lock_basic_unlock(&xfr->lock);
3484
3485         /* find auth_zone */
3486         lock_rw_rdlock(&env->auth_zones->lock);
3487         z = auth_zone_find(env->auth_zones, xfr->name, xfr->namelen,
3488                 xfr->dclass);
3489         if(!z) {
3490                 lock_rw_unlock(&env->auth_zones->lock);
3491                 return;
3492         }
3493         lock_rw_wrlock(&z->lock);
3494         lock_rw_unlock(&env->auth_zones->lock);
3495
3496         /* expire auth_zone */
3497         z->zone_expired = expired;
3498         lock_rw_unlock(&z->lock);
3499 }
3500
3501 /** find master (from notify or probe) in list of masters */
3502 static struct auth_master*
3503 find_master_by_host(struct auth_master* list, char* host)
3504 {
3505         struct auth_master* p;
3506         for(p=list; p; p=p->next) {
3507                 if(strcmp(p->host, host) == 0)
3508                         return p;
3509         }
3510         return NULL;
3511 }
3512
3513 /** delete the looked up auth_addrs for all the masters in the list */
3514 static void
3515 xfr_masterlist_free_addrs(struct auth_master* list)
3516 {
3517         struct auth_master* m;
3518         for(m=list; m; m=m->next) {
3519                 if(m->list) {
3520                         auth_free_master_addrs(m->list);
3521                         m->list = NULL;
3522                 }
3523         }
3524 }
3525
3526 /** copy a list of auth_addrs */
3527 static struct auth_addr*
3528 auth_addr_list_copy(struct auth_addr* source)
3529 {
3530         struct auth_addr* list = NULL, *last = NULL;
3531         struct auth_addr* p;
3532         for(p=source; p; p=p->next) {
3533                 struct auth_addr* a = (struct auth_addr*)memdup(p, sizeof(*p));
3534                 if(!a) {
3535                         log_err("malloc failure");
3536                         auth_free_master_addrs(list);
3537                         return NULL;
3538                 }
3539                 a->next = NULL;
3540                 if(last) last->next = a;
3541                 if(!list) list = a;
3542                 last = a;
3543         }
3544         return list;
3545 }
3546
3547 /** copy a master to a new structure, NULL on alloc failure */
3548 static struct auth_master*
3549 auth_master_copy(struct auth_master* o)
3550 {
3551         struct auth_master* m;
3552         if(!o) return NULL;
3553         m = (struct auth_master*)memdup(o, sizeof(*o));
3554         if(!m) {
3555                 log_err("malloc failure");
3556                 return NULL;
3557         }
3558         m->next = NULL;
3559         if(m->host) {
3560                 m->host = strdup(m->host);
3561                 if(!m->host) {
3562                         free(m);
3563                         log_err("malloc failure");
3564                         return NULL;
3565                 }
3566         }
3567         if(m->file) {
3568                 m->file = strdup(m->file);
3569                 if(!m->file) {
3570                         free(m->host);
3571                         free(m);
3572                         log_err("malloc failure");
3573                         return NULL;
3574                 }
3575         }
3576         if(m->list) {
3577                 m->list = auth_addr_list_copy(m->list);
3578                 if(!m->list) {
3579                         free(m->file);
3580                         free(m->host);
3581                         free(m);
3582                         return NULL;
3583                 }
3584         }
3585         return m;
3586 }
3587
3588 /** copy the master addresses from the task_probe lookups to the allow_notify
3589  * list of masters */
3590 static void
3591 probe_copy_masters_for_allow_notify(struct auth_xfer* xfr)
3592 {
3593         struct auth_master* list = NULL, *last = NULL;
3594         struct auth_master* p;
3595         /* build up new list with copies */
3596         for(p = xfr->task_probe->masters; p; p=p->next) {
3597                 struct auth_master* m = auth_master_copy(p);
3598                 if(!m) {
3599                         auth_free_masters(list);
3600                         /* failed because of malloc failure, use old list */
3601                         return;
3602                 }
3603                 m->next = NULL;
3604                 if(last) last->next = m;
3605                 if(!list) list = m;
3606                 last = m;
3607         }
3608         /* success, replace list */
3609         auth_free_masters(xfr->allow_notify_list);
3610         xfr->allow_notify_list = list;
3611 }
3612
3613 /** start the lookups for task_transfer */
3614 static void
3615 xfr_transfer_start_lookups(struct auth_xfer* xfr)
3616 {
3617         /* delete all the looked up addresses in the list */
3618         xfr_masterlist_free_addrs(xfr->task_transfer->masters);
3619
3620         /* start lookup at the first master */
3621         xfr->task_transfer->lookup_target = xfr->task_transfer->masters;
3622         xfr->task_transfer->lookup_aaaa = 0;
3623 }
3624
3625 /** move to the next lookup of hostname for task_transfer */
3626 static void
3627 xfr_transfer_move_to_next_lookup(struct auth_xfer* xfr, struct module_env* env)
3628 {
3629         if(!xfr->task_transfer->lookup_target)
3630                 return; /* already at end of list */
3631         if(!xfr->task_transfer->lookup_aaaa && env->cfg->do_ip6) {
3632                 /* move to lookup AAAA */
3633                 xfr->task_transfer->lookup_aaaa = 1;
3634                 return;
3635         }
3636         xfr->task_transfer->lookup_target = 
3637                 xfr->task_transfer->lookup_target->next;
3638         xfr->task_transfer->lookup_aaaa = 0;
3639         if(!env->cfg->do_ip4 && xfr->task_transfer->lookup_target!=NULL)
3640                 xfr->task_transfer->lookup_aaaa = 1;
3641 }
3642
3643 /** start the lookups for task_probe */
3644 static void
3645 xfr_probe_start_lookups(struct auth_xfer* xfr)
3646 {
3647         /* delete all the looked up addresses in the list */
3648         xfr_masterlist_free_addrs(xfr->task_probe->masters);
3649
3650         /* start lookup at the first master */
3651         xfr->task_probe->lookup_target = xfr->task_probe->masters;
3652         xfr->task_probe->lookup_aaaa = 0;
3653 }
3654
3655 /** move to the next lookup of hostname for task_probe */
3656 static void
3657 xfr_probe_move_to_next_lookup(struct auth_xfer* xfr, struct module_env* env)
3658 {
3659         if(!xfr->task_probe->lookup_target)
3660                 return; /* already at end of list */
3661         if(!xfr->task_probe->lookup_aaaa && env->cfg->do_ip6) {
3662                 /* move to lookup AAAA */
3663                 xfr->task_probe->lookup_aaaa = 1;
3664                 return;
3665         }
3666         xfr->task_probe->lookup_target = xfr->task_probe->lookup_target->next;
3667         xfr->task_probe->lookup_aaaa = 0;
3668         if(!env->cfg->do_ip4 && xfr->task_probe->lookup_target!=NULL)
3669                 xfr->task_probe->lookup_aaaa = 1;
3670 }
3671
3672 /** start the iteration of the task_transfer list of masters */
3673 static void
3674 xfr_transfer_start_list(struct auth_xfer* xfr, struct auth_master* spec) 
3675 {
3676         if(spec) {
3677                 xfr->task_transfer->scan_specific = find_master_by_host(
3678                         xfr->task_transfer->masters, spec->host);
3679                 if(xfr->task_transfer->scan_specific) {
3680                         xfr->task_transfer->scan_target = NULL;
3681                         xfr->task_transfer->scan_addr = NULL;
3682                         if(xfr->task_transfer->scan_specific->list)
3683                                 xfr->task_transfer->scan_addr =
3684                                         xfr->task_transfer->scan_specific->list;
3685                         return;
3686                 }
3687         }
3688         /* no specific (notified) host to scan */
3689         xfr->task_transfer->scan_specific = NULL;
3690         xfr->task_transfer->scan_addr = NULL;
3691         /* pick up first scan target */
3692         xfr->task_transfer->scan_target = xfr->task_transfer->masters;
3693         if(xfr->task_transfer->scan_target && xfr->task_transfer->
3694                 scan_target->list)
3695                 xfr->task_transfer->scan_addr =
3696                         xfr->task_transfer->scan_target->list;
3697 }
3698
3699 /** start the iteration of the task_probe list of masters */
3700 static void
3701 xfr_probe_start_list(struct auth_xfer* xfr, struct auth_master* spec) 
3702 {
3703         if(spec) {
3704                 xfr->task_probe->scan_specific = find_master_by_host(
3705                         xfr->task_probe->masters, spec->host);
3706                 if(xfr->task_probe->scan_specific) {
3707                         xfr->task_probe->scan_target = NULL;
3708                         xfr->task_probe->scan_addr = NULL;
3709                         if(xfr->task_probe->scan_specific->list)
3710                                 xfr->task_probe->scan_addr =
3711                                         xfr->task_probe->scan_specific->list;
3712                         return;
3713                 }
3714         }
3715         /* no specific (notified) host to scan */
3716         xfr->task_probe->scan_specific = NULL;
3717         xfr->task_probe->scan_addr = NULL;
3718         /* pick up first scan target */
3719         xfr->task_probe->scan_target = xfr->task_probe->masters;
3720         if(xfr->task_probe->scan_target && xfr->task_probe->scan_target->list)
3721                 xfr->task_probe->scan_addr =
3722                         xfr->task_probe->scan_target->list;
3723 }
3724
3725 /** pick up the master that is being scanned right now, task_transfer */
3726 static struct auth_master*
3727 xfr_transfer_current_master(struct auth_xfer* xfr)
3728 {
3729         if(xfr->task_transfer->scan_specific)
3730                 return xfr->task_transfer->scan_specific;
3731         return xfr->task_transfer->scan_target;
3732 }
3733
3734 /** pick up the master that is being scanned right now, task_probe */
3735 static struct auth_master*
3736 xfr_probe_current_master(struct auth_xfer* xfr)
3737 {
3738         if(xfr->task_probe->scan_specific)
3739                 return xfr->task_probe->scan_specific;
3740         return xfr->task_probe->scan_target;
3741 }
3742
3743 /** true if at end of list, task_transfer */
3744 static int
3745 xfr_transfer_end_of_list(struct auth_xfer* xfr)
3746 {
3747         return !xfr->task_transfer->scan_specific &&
3748                 !xfr->task_transfer->scan_target;
3749 }
3750
3751 /** true if at end of list, task_probe */
3752 static int
3753 xfr_probe_end_of_list(struct auth_xfer* xfr)
3754 {
3755         return !xfr->task_probe->scan_specific && !xfr->task_probe->scan_target;
3756 }
3757
3758 /** move to next master in list, task_transfer */
3759 static void
3760 xfr_transfer_nextmaster(struct auth_xfer* xfr)
3761 {
3762         if(!xfr->task_transfer->scan_specific &&
3763                 !xfr->task_transfer->scan_target)
3764                 return;
3765         if(xfr->task_transfer->scan_addr) {
3766                 xfr->task_transfer->scan_addr =
3767                         xfr->task_transfer->scan_addr->next;
3768                 if(xfr->task_transfer->scan_addr)
3769                         return;
3770         }
3771         if(xfr->task_transfer->scan_specific) {
3772                 xfr->task_transfer->scan_specific = NULL;
3773                 xfr->task_transfer->scan_target = xfr->task_transfer->masters;
3774                 if(xfr->task_transfer->scan_target && xfr->task_transfer->
3775                         scan_target->list)
3776                         xfr->task_transfer->scan_addr =
3777                                 xfr->task_transfer->scan_target->list;
3778                 return;
3779         }
3780         if(!xfr->task_transfer->scan_target)
3781                 return;
3782         xfr->task_transfer->scan_target = xfr->task_transfer->scan_target->next;
3783         if(xfr->task_transfer->scan_target && xfr->task_transfer->
3784                 scan_target->list)
3785                 xfr->task_transfer->scan_addr =
3786                         xfr->task_transfer->scan_target->list;
3787         return;
3788 }
3789
3790 /** move to next master in list, task_probe */
3791 static void
3792 xfr_probe_nextmaster(struct auth_xfer* xfr)
3793 {
3794         if(!xfr->task_probe->scan_specific && !xfr->task_probe->scan_target)
3795                 return;
3796         if(xfr->task_probe->scan_addr) {
3797                 xfr->task_probe->scan_addr = xfr->task_probe->scan_addr->next;
3798                 if(xfr->task_probe->scan_addr)
3799                         return;
3800         }
3801         if(xfr->task_probe->scan_specific) {
3802                 xfr->task_probe->scan_specific = NULL;
3803                 xfr->task_probe->scan_target = xfr->task_probe->masters;
3804                 if(xfr->task_probe->scan_target && xfr->task_probe->
3805                         scan_target->list)
3806                         xfr->task_probe->scan_addr =
3807                                 xfr->task_probe->scan_target->list;
3808                 return;
3809         }
3810         if(!xfr->task_probe->scan_target)
3811                 return;
3812         xfr->task_probe->scan_target = xfr->task_probe->scan_target->next;
3813         if(xfr->task_probe->scan_target && xfr->task_probe->
3814                 scan_target->list)
3815                 xfr->task_probe->scan_addr =
3816                         xfr->task_probe->scan_target->list;
3817         return;
3818 }
3819
3820 /** create SOA probe packet for xfr */
3821 static void
3822 xfr_create_soa_probe_packet(struct auth_xfer* xfr, sldns_buffer* buf, 
3823         uint16_t id)
3824 {
3825         struct query_info qinfo;
3826
3827         memset(&qinfo, 0, sizeof(qinfo));
3828         qinfo.qname = xfr->name;
3829         qinfo.qname_len = xfr->namelen;
3830         qinfo.qtype = LDNS_RR_TYPE_SOA;
3831         qinfo.qclass = xfr->dclass;
3832         qinfo_query_encode(buf, &qinfo);
3833         sldns_buffer_write_u16_at(buf, 0, id);
3834 }
3835
3836 /** create IXFR/AXFR packet for xfr */
3837 static void
3838 xfr_create_ixfr_packet(struct auth_xfer* xfr, sldns_buffer* buf, uint16_t id,
3839         struct auth_master* master)
3840 {
3841         struct query_info qinfo;
3842         uint32_t serial;
3843         int have_zone;
3844         have_zone = xfr->have_zone;
3845         serial = xfr->serial;
3846
3847         memset(&qinfo, 0, sizeof(qinfo));
3848         qinfo.qname = xfr->name;
3849         qinfo.qname_len = xfr->namelen;
3850         xfr->task_transfer->got_xfr_serial = 0;
3851         xfr->task_transfer->rr_scan_num = 0;
3852         xfr->task_transfer->incoming_xfr_serial = 0;
3853         xfr->task_transfer->on_ixfr_is_axfr = 0;
3854         xfr->task_transfer->on_ixfr = 1;
3855         qinfo.qtype = LDNS_RR_TYPE_IXFR;
3856         if(!have_zone || xfr->task_transfer->ixfr_fail || !master->ixfr) {
3857                 qinfo.qtype = LDNS_RR_TYPE_AXFR;
3858                 xfr->task_transfer->ixfr_fail = 0;
3859                 xfr->task_transfer->on_ixfr = 0;
3860         }
3861
3862         qinfo.qclass = xfr->dclass;
3863         qinfo_query_encode(buf, &qinfo);
3864         sldns_buffer_write_u16_at(buf, 0, id);
3865
3866         /* append serial for IXFR */
3867         if(qinfo.qtype == LDNS_RR_TYPE_IXFR) {
3868                 size_t end = sldns_buffer_limit(buf);
3869                 sldns_buffer_clear(buf);
3870                 sldns_buffer_set_position(buf, end);
3871                 /* auth section count 1 */
3872                 sldns_buffer_write_u16_at(buf, LDNS_NSCOUNT_OFF, 1);
3873                 /* write SOA */
3874                 sldns_buffer_write_u8(buf, 0xC0); /* compressed ptr to qname */
3875                 sldns_buffer_write_u8(buf, 0x0C);
3876                 sldns_buffer_write_u16(buf, LDNS_RR_TYPE_SOA);
3877                 sldns_buffer_write_u16(buf, qinfo.qclass);
3878                 sldns_buffer_write_u32(buf, 0); /* ttl */
3879                 sldns_buffer_write_u16(buf, 22); /* rdata length */
3880                 sldns_buffer_write_u8(buf, 0); /* . */
3881                 sldns_buffer_write_u8(buf, 0); /* . */
3882                 sldns_buffer_write_u32(buf, serial); /* serial */
3883                 sldns_buffer_write_u32(buf, 0); /* refresh */
3884                 sldns_buffer_write_u32(buf, 0); /* retry */
3885                 sldns_buffer_write_u32(buf, 0); /* expire */
3886                 sldns_buffer_write_u32(buf, 0); /* minimum */
3887                 sldns_buffer_flip(buf);
3888         }
3889 }
3890
3891 /** check if returned packet is OK */
3892 static int
3893 check_packet_ok(sldns_buffer* pkt, uint16_t qtype, struct auth_xfer* xfr,
3894         uint32_t* serial)
3895 {
3896         /* parse to see if packet worked, valid reply */
3897
3898         /* check serial number of SOA */
3899         if(sldns_buffer_limit(pkt) < LDNS_HEADER_SIZE)
3900                 return 0;
3901
3902         /* check ID */
3903         if(LDNS_ID_WIRE(sldns_buffer_begin(pkt)) != xfr->task_probe->id)
3904                 return 0;
3905
3906         /* check flag bits and rcode */
3907         if(!LDNS_QR_WIRE(sldns_buffer_begin(pkt)))
3908                 return 0;
3909         if(LDNS_OPCODE_WIRE(sldns_buffer_begin(pkt)) != LDNS_PACKET_QUERY)
3910                 return 0;
3911         if(LDNS_RCODE_WIRE(sldns_buffer_begin(pkt)) != LDNS_RCODE_NOERROR)
3912                 return 0;
3913
3914         /* check qname */
3915         if(LDNS_QDCOUNT(sldns_buffer_begin(pkt)) != 1)
3916                 return 0;
3917         sldns_buffer_skip(pkt, LDNS_HEADER_SIZE);
3918         if(sldns_buffer_remaining(pkt) < xfr->namelen)
3919                 return 0;
3920         if(query_dname_compare(sldns_buffer_current(pkt), xfr->name) != 0)
3921                 return 0;
3922         sldns_buffer_skip(pkt, (ssize_t)xfr->namelen);
3923
3924         /* check qtype, qclass */
3925         if(sldns_buffer_remaining(pkt) < 4)
3926                 return 0;
3927         if(sldns_buffer_read_u16(pkt) != qtype)
3928                 return 0;
3929         if(sldns_buffer_read_u16(pkt) != xfr->dclass)
3930                 return 0;
3931
3932         if(serial) {
3933                 uint16_t rdlen;
3934                 /* read serial number, from answer section SOA */
3935                 if(LDNS_ANCOUNT(sldns_buffer_begin(pkt)) == 0)
3936                         return 0;
3937                 /* read from first record SOA record */
3938                 if(sldns_buffer_remaining(pkt) < 1)
3939                         return 0;
3940                 if(dname_pkt_compare(pkt, sldns_buffer_current(pkt),
3941                         xfr->name) != 0)
3942                         return 0;
3943                 if(!pkt_dname_len(pkt))
3944                         return 0;
3945                 /* type, class, ttl, rdatalen */
3946                 if(sldns_buffer_remaining(pkt) < 4+4+2)
3947                         return 0;
3948                 if(sldns_buffer_read_u16(pkt) != qtype)
3949                         return 0;
3950                 if(sldns_buffer_read_u16(pkt) != xfr->dclass)
3951                         return 0;
3952                 sldns_buffer_skip(pkt, 4); /* ttl */
3953                 rdlen = sldns_buffer_read_u16(pkt);
3954                 if(sldns_buffer_remaining(pkt) < rdlen)
3955                         return 0;
3956                 if(sldns_buffer_remaining(pkt) < 1)
3957                         return 0;
3958                 if(!pkt_dname_len(pkt)) /* soa name */
3959                         return 0;
3960                 if(sldns_buffer_remaining(pkt) < 1)
3961                         return 0;
3962                 if(!pkt_dname_len(pkt)) /* soa name */
3963                         return 0;
3964                 if(sldns_buffer_remaining(pkt) < 20)
3965                         return 0;
3966                 *serial = sldns_buffer_read_u32(pkt);
3967         }
3968         return 1;
3969 }
3970
3971 /** read one line from chunks into buffer at current position */
3972 static int
3973 chunkline_get_line(struct auth_chunk** chunk, size_t* chunk_pos,
3974         sldns_buffer* buf)
3975 {
3976         int readsome = 0;
3977         while(*chunk) {
3978                 /* more text in this chunk? */
3979                 if(*chunk_pos < (*chunk)->len) {
3980                         readsome = 1;
3981                         while(*chunk_pos < (*chunk)->len) {
3982                                 char c = (char)((*chunk)->data[*chunk_pos]);
3983                                 (*chunk_pos)++;
3984                                 if(sldns_buffer_remaining(buf) < 2) {
3985                                         /* buffer too short */
3986                                         verbose(VERB_ALGO, "http chunkline, "
3987                                                 "line too long");
3988                                         return 0;
3989                                 }
3990                                 sldns_buffer_write_u8(buf, (uint8_t)c);
3991                                 if(c == '\n') {
3992                                         /* we are done */
3993                                         return 1;
3994                                 }
3995                         }
3996                 }
3997                 /* move to next chunk */
3998                 *chunk = (*chunk)->next;
3999                 *chunk_pos = 0;
4000         }
4001         /* no more text */
4002         if(readsome) return 1;
4003         return 0;
4004 }
4005
4006 /** count number of open and closed parenthesis in a chunkline */
4007 static int
4008 chunkline_count_parens(sldns_buffer* buf, size_t start)
4009 {
4010         size_t end = sldns_buffer_position(buf);
4011         size_t i;
4012         int count = 0;
4013         int squote = 0, dquote = 0;
4014         for(i=start; i<end; i++) {
4015                 char c = (char)sldns_buffer_read_u8_at(buf, i);
4016                 if(squote && c != '\'') continue;
4017                 if(dquote && c != '"') continue;
4018                 if(c == '"')
4019                         dquote = !dquote; /* skip quoted part */
4020                 else if(c == '\'')
4021                         squote = !squote; /* skip quoted part */
4022                 else if(c == '(')
4023                         count ++;
4024                 else if(c == ')')
4025                         count --;
4026                 else if(c == ';') {
4027                         /* rest is a comment */
4028                         return count;
4029                 }
4030         }
4031         return count;
4032 }
4033
4034 /** remove trailing ;... comment from a line in the chunkline buffer */
4035 static void
4036 chunkline_remove_trailcomment(sldns_buffer* buf, size_t start)
4037 {
4038         size_t end = sldns_buffer_position(buf);
4039         size_t i;
4040         int squote = 0, dquote = 0;
4041         for(i=start; i<end; i++) {
4042                 char c = (char)sldns_buffer_read_u8_at(buf, i);
4043                 if(squote && c != '\'') continue;
4044                 if(dquote && c != '"') continue;
4045                 if(c == '"')
4046                         dquote = !dquote; /* skip quoted part */
4047                 else if(c == '\'')
4048                         squote = !squote; /* skip quoted part */
4049                 else if(c == ';') {
4050                         /* rest is a comment */
4051                         sldns_buffer_set_position(buf, i);
4052                         return;
4053                 }
4054         }
4055         /* nothing to remove */
4056 }
4057
4058 /** see if a chunkline is a comment line (or empty line) */
4059 static int
4060 chunkline_is_comment_line_or_empty(sldns_buffer* buf)
4061 {
4062         size_t i, end = sldns_buffer_limit(buf);
4063         for(i=0; i<end; i++) {
4064                 char c = (char)sldns_buffer_read_u8_at(buf, i);
4065                 if(c == ';')
4066                         return 1; /* comment */
4067                 else if(c != ' ' && c != '\t' && c != '\r' && c != '\n')
4068                         return 0; /* not a comment */
4069         }
4070         return 1; /* empty */
4071 }
4072
4073 /** find a line with ( ) collated */
4074 static int
4075 chunkline_get_line_collated(struct auth_chunk** chunk, size_t* chunk_pos,
4076         sldns_buffer* buf)
4077 {
4078         size_t pos;
4079         int parens = 0;
4080         sldns_buffer_clear(buf);
4081         pos = sldns_buffer_position(buf);
4082         if(!chunkline_get_line(chunk, chunk_pos, buf)) {
4083                 if(sldns_buffer_position(buf) < sldns_buffer_limit(buf))
4084                         sldns_buffer_write_u8_at(buf, sldns_buffer_position(buf), 0);
4085                 else sldns_buffer_write_u8_at(buf, sldns_buffer_position(buf)-1, 0);
4086                 sldns_buffer_flip(buf);
4087                 return 0;
4088         }
4089         parens += chunkline_count_parens(buf, pos);
4090         while(parens > 0) {
4091                 chunkline_remove_trailcomment(buf, pos);
4092                 pos = sldns_buffer_position(buf);
4093                 if(!chunkline_get_line(chunk, chunk_pos, buf)) {
4094                         if(sldns_buffer_position(buf) < sldns_buffer_limit(buf))
4095                                 sldns_buffer_write_u8_at(buf, sldns_buffer_position(buf), 0);
4096                         else sldns_buffer_write_u8_at(buf, sldns_buffer_position(buf)-1, 0);
4097                         sldns_buffer_flip(buf);
4098                         return 0;
4099                 }
4100                 parens += chunkline_count_parens(buf, pos);
4101         }
4102
4103         if(sldns_buffer_remaining(buf) < 1) {
4104                 verbose(VERB_ALGO, "http chunkline: "
4105                         "line too long");
4106                 return 0;
4107         }
4108         sldns_buffer_write_u8_at(buf, sldns_buffer_position(buf), 0);
4109         sldns_buffer_flip(buf);
4110         return 1;
4111 }
4112
4113 /** process $ORIGIN for http */
4114 static int
4115 http_parse_origin(sldns_buffer* buf, struct sldns_file_parse_state* pstate)
4116 {
4117         char* line = (char*)sldns_buffer_begin(buf);
4118         if(strncmp(line, "$ORIGIN", 7) == 0 &&
4119                 isspace((unsigned char)line[7])) {
4120                 int s;
4121                 pstate->origin_len = sizeof(pstate->origin);
4122                 s = sldns_str2wire_dname_buf(sldns_strip_ws(line+8),
4123                         pstate->origin, &pstate->origin_len);
4124                 if(s) pstate->origin_len = 0;
4125                 return 1;
4126         }
4127         return 0;
4128 }
4129
4130 /** process $TTL for http */
4131 static int
4132 http_parse_ttl(sldns_buffer* buf, struct sldns_file_parse_state* pstate)
4133 {
4134         char* line = (char*)sldns_buffer_begin(buf);
4135         if(strncmp(line, "$TTL", 4) == 0 &&
4136                 isspace((unsigned char)line[4])) {
4137                 const char* end = NULL;
4138                 pstate->default_ttl = sldns_str2period(
4139                         sldns_strip_ws(line+5), &end);
4140                 return 1;
4141         }
4142         return 0;
4143 }
4144
4145 /** find noncomment RR line in chunks, collates lines if ( ) format */
4146 static int
4147 chunkline_non_comment_RR(struct auth_chunk** chunk, size_t* chunk_pos,
4148         sldns_buffer* buf, struct sldns_file_parse_state* pstate)
4149 {
4150         while(chunkline_get_line_collated(chunk, chunk_pos, buf)) {
4151                 if(chunkline_is_comment_line_or_empty(buf)) {
4152                         /* a comment, go to next line */
4153                         continue;
4154                 }
4155                 if(http_parse_origin(buf, pstate)) {
4156                         continue; /* $ORIGIN has been handled */
4157                 }
4158                 if(http_parse_ttl(buf, pstate)) {
4159                         continue; /* $TTL has been handled */
4160                 }
4161                 return 1;
4162         }
4163         /* no noncomments, fail */
4164         return 0;
4165 }
4166
4167 /** check syntax of chunklist zonefile, parse first RR, return false on
4168  * failure and return a string in the scratch buffer (first RR string)
4169  * on failure. */
4170 static int
4171 http_zonefile_syntax_check(struct auth_xfer* xfr, sldns_buffer* buf)
4172 {
4173         uint8_t rr[LDNS_RR_BUF_SIZE];
4174         size_t rr_len, dname_len = 0;
4175         struct sldns_file_parse_state pstate;
4176         struct auth_chunk* chunk;
4177         size_t chunk_pos;
4178         int e;
4179         memset(&pstate, 0, sizeof(pstate));
4180         pstate.default_ttl = 3600;
4181         if(xfr->namelen < sizeof(pstate.origin)) {
4182                 pstate.origin_len = xfr->namelen;
4183                 memmove(pstate.origin, xfr->name, xfr->namelen);
4184         }
4185         chunk = xfr->task_transfer->chunks_first;
4186         chunk_pos = 0;
4187         if(!chunkline_non_comment_RR(&chunk, &chunk_pos, buf, &pstate)) {
4188                 return 0;
4189         }
4190         rr_len = sizeof(rr);
4191         e=sldns_str2wire_rr_buf((char*)sldns_buffer_begin(buf), rr, &rr_len,
4192                 &dname_len, pstate.default_ttl,
4193                 pstate.origin_len?pstate.origin:NULL, pstate.origin_len,
4194                 pstate.prev_rr_len?pstate.prev_rr:NULL, pstate.prev_rr_len);
4195         if(e != 0) {
4196                 log_err("parse failure on first RR[%d]: %s",
4197                         LDNS_WIREPARSE_OFFSET(e),
4198                         sldns_get_errorstr_parse(LDNS_WIREPARSE_ERROR(e)));
4199                 return 0;
4200         }
4201         /* check that class is correct */
4202         if(sldns_wirerr_get_class(rr, rr_len, dname_len) != xfr->dclass) {
4203                 log_err("parse failure: first record in downloaded zonefile "
4204                         "from wrong RR class");
4205                 return 0;
4206         }
4207         return 1;
4208 }
4209
4210 /** sum sizes of chunklist */
4211 static size_t
4212 chunklist_sum(struct auth_chunk* list)
4213 {
4214         struct auth_chunk* p;
4215         size_t s = 0;
4216         for(p=list; p; p=p->next) {
4217                 s += p->len;
4218         }
4219         return s;
4220 }
4221
4222 /** remove newlines from collated line */
4223 static void
4224 chunkline_newline_removal(sldns_buffer* buf)
4225 {
4226         size_t i, end=sldns_buffer_limit(buf);
4227         for(i=0; i<end; i++) {
4228                 char c = (char)sldns_buffer_read_u8_at(buf, i);
4229                 if(c == '\n' && i==end-1) {
4230                         sldns_buffer_write_u8_at(buf, i, 0);
4231                         sldns_buffer_set_limit(buf, end-1);
4232                         return;
4233                 }
4234                 if(c == '\n')
4235                         sldns_buffer_write_u8_at(buf, i, (uint8_t)' ');
4236         }
4237 }
4238
4239 /** for http download, parse and add RR to zone */
4240 static int
4241 http_parse_add_rr(struct auth_xfer* xfr, struct auth_zone* z,
4242         sldns_buffer* buf, struct sldns_file_parse_state* pstate)
4243 {
4244         uint8_t rr[LDNS_RR_BUF_SIZE];
4245         size_t rr_len, dname_len = 0;
4246         int e;
4247         char* line = (char*)sldns_buffer_begin(buf);
4248         rr_len = sizeof(rr);
4249         e = sldns_str2wire_rr_buf(line, rr, &rr_len, &dname_len,
4250                 pstate->default_ttl,
4251                 pstate->origin_len?pstate->origin:NULL, pstate->origin_len,
4252                 pstate->prev_rr_len?pstate->prev_rr:NULL, pstate->prev_rr_len);
4253         if(e != 0) {
4254                 log_err("%s/%s parse failure RR[%d]: %s in '%s'",
4255                         xfr->task_transfer->master->host,
4256                         xfr->task_transfer->master->file,
4257                         LDNS_WIREPARSE_OFFSET(e),
4258                         sldns_get_errorstr_parse(LDNS_WIREPARSE_ERROR(e)),
4259                         line);
4260                 return 0;
4261         }
4262         if(rr_len == 0)
4263                 return 1; /* empty line or so */
4264
4265         /* set prev */
4266         if(dname_len < sizeof(pstate->prev_rr)) {
4267                 memmove(pstate->prev_rr, rr, dname_len);
4268                 pstate->prev_rr_len = dname_len;
4269         }
4270
4271         return az_insert_rr(z, rr, rr_len, dname_len, NULL);
4272 }
4273
4274 /** RR list iterator, returns RRs from answer section one by one from the
4275  * dns packets in the chunklist */
4276 static void
4277 chunk_rrlist_start(struct auth_xfer* xfr, struct auth_chunk** rr_chunk,
4278         int* rr_num, size_t* rr_pos)
4279 {
4280         *rr_chunk = xfr->task_transfer->chunks_first;
4281         *rr_num = 0;
4282         *rr_pos = 0;
4283 }
4284
4285 /** RR list iterator, see if we are at the end of the list */
4286 static int
4287 chunk_rrlist_end(struct auth_chunk* rr_chunk, int rr_num)
4288 {
4289         while(rr_chunk) {
4290                 if(rr_chunk->len < LDNS_HEADER_SIZE)
4291                         return 1;
4292                 if(rr_num < (int)LDNS_ANCOUNT(rr_chunk->data))
4293                         return 0;
4294                 /* no more RRs in this chunk */
4295                 /* continue with next chunk, see if it has RRs */
4296                 rr_chunk = rr_chunk->next;
4297                 rr_num = 0;
4298         }
4299         return 1;
4300 }
4301
4302 /** RR list iterator, move to next RR */
4303 static void
4304 chunk_rrlist_gonext(struct auth_chunk** rr_chunk, int* rr_num,
4305         size_t* rr_pos, size_t rr_nextpos)
4306 {
4307         /* already at end of chunks? */
4308         if(!*rr_chunk)
4309                 return;
4310         /* move within this chunk */
4311         if((*rr_chunk)->len >= LDNS_HEADER_SIZE &&
4312                 (*rr_num)+1 < (int)LDNS_ANCOUNT((*rr_chunk)->data)) {
4313                 (*rr_num) += 1;
4314                 *rr_pos = rr_nextpos;
4315                 return;
4316         }
4317         /* no more RRs in this chunk */
4318         /* continue with next chunk, see if it has RRs */
4319         if(*rr_chunk)
4320                 *rr_chunk = (*rr_chunk)->next;
4321         while(*rr_chunk) {
4322                 *rr_num = 0;
4323                 *rr_pos = 0;
4324                 if((*rr_chunk)->len >= LDNS_HEADER_SIZE &&
4325                         LDNS_ANCOUNT((*rr_chunk)->data) > 0) {
4326                         return;
4327                 }
4328                 *rr_chunk = (*rr_chunk)->next;
4329         }
4330 }
4331
4332 /** RR iterator, get current RR information, false on parse error */
4333 static int
4334 chunk_rrlist_get_current(struct auth_chunk* rr_chunk, int rr_num,
4335         size_t rr_pos, uint8_t** rr_dname, uint16_t* rr_type,
4336         uint16_t* rr_class, uint32_t* rr_ttl, uint16_t* rr_rdlen,
4337         uint8_t** rr_rdata, size_t* rr_nextpos)
4338 {
4339         sldns_buffer pkt;
4340         /* integrity checks on position */
4341         if(!rr_chunk) return 0;
4342         if(rr_chunk->len < LDNS_HEADER_SIZE) return 0;
4343         if(rr_num >= (int)LDNS_ANCOUNT(rr_chunk->data)) return 0;
4344         if(rr_pos >= rr_chunk->len) return 0;
4345
4346         /* fetch rr information */
4347         sldns_buffer_init_frm_data(&pkt, rr_chunk->data, rr_chunk->len);
4348         if(rr_pos == 0) {
4349                 size_t i;
4350                 /* skip question section */
4351                 sldns_buffer_set_position(&pkt, LDNS_HEADER_SIZE);
4352                 for(i=0; i<LDNS_QDCOUNT(rr_chunk->data); i++) {
4353                         if(pkt_dname_len(&pkt) == 0) return 0;
4354                         if(sldns_buffer_remaining(&pkt) < 4) return 0;
4355                         sldns_buffer_skip(&pkt, 4); /* type and class */
4356                 }
4357         } else  {
4358                 sldns_buffer_set_position(&pkt, rr_pos);
4359         }
4360         *rr_dname = sldns_buffer_current(&pkt);
4361         if(pkt_dname_len(&pkt) == 0) return 0;
4362         if(sldns_buffer_remaining(&pkt) < 10) return 0;
4363         *rr_type = sldns_buffer_read_u16(&pkt);
4364         *rr_class = sldns_buffer_read_u16(&pkt);
4365         *rr_ttl = sldns_buffer_read_u32(&pkt);
4366         *rr_rdlen = sldns_buffer_read_u16(&pkt);
4367         if(sldns_buffer_remaining(&pkt) < (*rr_rdlen)) return 0;
4368         *rr_rdata = sldns_buffer_current(&pkt);
4369         sldns_buffer_skip(&pkt, (ssize_t)(*rr_rdlen));
4370         *rr_nextpos = sldns_buffer_position(&pkt);
4371         return 1;
4372 }
4373
4374 /** print log message where we are in parsing the zone transfer */
4375 static void
4376 log_rrlist_position(const char* label, struct auth_chunk* rr_chunk,
4377         uint8_t* rr_dname, uint16_t rr_type, size_t rr_counter)
4378 {
4379         sldns_buffer pkt;
4380         size_t dlen;
4381         uint8_t buf[256];
4382         char str[256];
4383         char typestr[32];
4384         sldns_buffer_init_frm_data(&pkt, rr_chunk->data, rr_chunk->len);
4385         sldns_buffer_set_position(&pkt, (size_t)(rr_dname -
4386                 sldns_buffer_begin(&pkt)));
4387         if((dlen=pkt_dname_len(&pkt)) == 0) return;
4388         if(dlen >= sizeof(buf)) return;
4389         dname_pkt_copy(&pkt, buf, rr_dname);
4390         dname_str(buf, str);
4391         (void)sldns_wire2str_type_buf(rr_type, typestr, sizeof(typestr));
4392         verbose(VERB_ALGO, "%s at[%d] %s %s", label, (int)rr_counter,
4393                 str, typestr);
4394 }
4395
4396 /** check that start serial is OK for ixfr. we are at rr_counter == 0,
4397  * and we are going to check rr_counter == 1 (has to be type SOA) serial */
4398 static int
4399 ixfr_start_serial(struct auth_chunk* rr_chunk, int rr_num, size_t rr_pos,
4400         uint8_t* rr_dname, uint16_t rr_type, uint16_t rr_class,
4401         uint32_t rr_ttl, uint16_t rr_rdlen, uint8_t* rr_rdata,
4402         size_t rr_nextpos, uint32_t transfer_serial, uint32_t xfr_serial)
4403 {
4404         uint32_t startserial;
4405         /* move forward on RR */
4406         chunk_rrlist_gonext(&rr_chunk, &rr_num, &rr_pos, rr_nextpos);
4407         if(chunk_rrlist_end(rr_chunk, rr_num)) {
4408                 /* no second SOA */
4409                 verbose(VERB_OPS, "IXFR has no second SOA record");
4410                 return 0;
4411         }
4412         if(!chunk_rrlist_get_current(rr_chunk, rr_num, rr_pos,
4413                 &rr_dname, &rr_type, &rr_class, &rr_ttl, &rr_rdlen,
4414                 &rr_rdata, &rr_nextpos)) {
4415                 verbose(VERB_OPS, "IXFR cannot parse second SOA record");
4416                 /* failed to parse RR */
4417                 return 0;
4418         }
4419         if(rr_type != LDNS_RR_TYPE_SOA) {
4420                 verbose(VERB_OPS, "IXFR second record is not type SOA");
4421                 return 0;
4422         }
4423         if(rr_rdlen < 22) {
4424                 verbose(VERB_OPS, "IXFR, second SOA has short rdlength");
4425                 return 0; /* bad SOA rdlen */
4426         }
4427         startserial = sldns_read_uint32(rr_rdata+rr_rdlen-20);
4428         if(startserial == transfer_serial) {
4429                 /* empty AXFR, not an IXFR */
4430                 verbose(VERB_OPS, "IXFR second serial same as first");
4431                 return 0;
4432         }
4433         if(startserial != xfr_serial) {
4434                 /* wrong start serial, it does not match the serial in
4435                  * memory */
4436                 verbose(VERB_OPS, "IXFR is from serial %u to %u but %u "
4437                         "in memory, rejecting the zone transfer",
4438                         (unsigned)startserial, (unsigned)transfer_serial,
4439                         (unsigned)xfr_serial);
4440                 return 0;
4441         }
4442         /* everything OK in second SOA serial */
4443         return 1;
4444 }
4445
4446 /** apply IXFR to zone in memory. z is locked. false on failure(mallocfail) */
4447 static int
4448 apply_ixfr(struct auth_xfer* xfr, struct auth_zone* z,
4449         struct sldns_buffer* scratch_buffer)
4450 {
4451         struct auth_chunk* rr_chunk;
4452         int rr_num;
4453         size_t rr_pos;
4454         uint8_t* rr_dname, *rr_rdata;
4455         uint16_t rr_type, rr_class, rr_rdlen;
4456         uint32_t rr_ttl;
4457         size_t rr_nextpos;
4458         int have_transfer_serial = 0;
4459         uint32_t transfer_serial = 0;
4460         size_t rr_counter = 0;
4461         int delmode = 0;
4462         int softfail = 0;
4463
4464         /* start RR iterator over chunklist of packets */
4465         chunk_rrlist_start(xfr, &rr_chunk, &rr_num, &rr_pos);
4466         while(!chunk_rrlist_end(rr_chunk, rr_num)) {
4467                 if(!chunk_rrlist_get_current(rr_chunk, rr_num, rr_pos,
4468                         &rr_dname, &rr_type, &rr_class, &rr_ttl, &rr_rdlen,
4469                         &rr_rdata, &rr_nextpos)) {
4470                         /* failed to parse RR */
4471                         return 0;
4472                 }
4473                 if(verbosity>=7) log_rrlist_position("apply ixfr",
4474                         rr_chunk, rr_dname, rr_type, rr_counter);
4475                 /* twiddle add/del mode and check for start and end */
4476                 if(rr_counter == 0 && rr_type != LDNS_RR_TYPE_SOA)
4477                         return 0;
4478                 if(rr_counter == 1 && rr_type != LDNS_RR_TYPE_SOA) {
4479                         /* this is an AXFR returned from the IXFR master */
4480                         /* but that should already have been detected, by
4481                          * on_ixfr_is_axfr */
4482                         return 0;
4483                 }
4484                 if(rr_type == LDNS_RR_TYPE_SOA) {
4485                         uint32_t serial;
4486                         if(rr_rdlen < 22) return 0; /* bad SOA rdlen */
4487                         serial = sldns_read_uint32(rr_rdata+rr_rdlen-20);
4488                         if(have_transfer_serial == 0) {
4489                                 have_transfer_serial = 1;
4490                                 transfer_serial = serial;
4491                                 delmode = 1; /* gets negated below */
4492                                 /* check second RR before going any further */
4493                                 if(!ixfr_start_serial(rr_chunk, rr_num, rr_pos,
4494                                         rr_dname, rr_type, rr_class, rr_ttl,
4495                                         rr_rdlen, rr_rdata, rr_nextpos,
4496                                         transfer_serial, xfr->serial)) {
4497                                         return 0;
4498                                 }
4499                         } else if(transfer_serial == serial) {
4500                                 have_transfer_serial++;
4501                                 if(rr_counter == 1) {
4502                                         /* empty AXFR, with SOA; SOA; */
4503                                         /* should have been detected by
4504                                          * on_ixfr_is_axfr */
4505                                         return 0;
4506                                 }
4507                                 if(have_transfer_serial == 3) {
4508                                         /* see serial three times for end */
4509                                         /* eg. IXFR:
4510                                          *  SOA 3 start
4511                                          *  SOA 1 second RR, followed by del
4512                                          *  SOA 2 followed by add
4513                                          *  SOA 2 followed by del
4514                                          *  SOA 3 followed by add
4515                                          *  SOA 3 end */
4516                                         /* ended by SOA record */
4517                                         xfr->serial = transfer_serial;
4518                                         break;
4519                                 }
4520                         }
4521                         /* twiddle add/del mode */
4522                         /* switch from delete part to add part and back again
4523                          * just before the soa, it gets deleted and added too
4524                          * this means we switch to delete mode for the final
4525                          * SOA(so skip that one) */
4526                         delmode = !delmode;
4527                 }
4528                 /* process this RR */
4529                 /* if the RR is deleted twice or added twice, then we 
4530                  * softfail, and continue with the rest of the IXFR, so
4531                  * that we serve something fairly nice during the refetch */
4532                 if(verbosity>=7) log_rrlist_position((delmode?"del":"add"),
4533                         rr_chunk, rr_dname, rr_type, rr_counter);
4534                 if(delmode) {
4535                         /* delete this RR */
4536                         int nonexist = 0;
4537                         if(!az_remove_rr_decompress(z, rr_chunk->data,
4538                                 rr_chunk->len, scratch_buffer, rr_dname,
4539                                 rr_type, rr_class, rr_ttl, rr_rdata, rr_rdlen,
4540                                 &nonexist)) {
4541                                 /* failed, malloc error or so */
4542                                 return 0;
4543                         }
4544                         if(nonexist) {
4545                                 /* it was removal of a nonexisting RR */
4546                                 if(verbosity>=4) log_rrlist_position(
4547                                         "IXFR error nonexistent RR",
4548                                         rr_chunk, rr_dname, rr_type, rr_counter);
4549                                 softfail = 1;
4550                         }
4551                 } else if(rr_counter != 0) {
4552                         /* skip first SOA RR for addition, it is added in
4553                          * the addition part near the end of the ixfr, when
4554                          * that serial is seen the second time. */
4555                         int duplicate = 0;
4556                         /* add this RR */
4557                         if(!az_insert_rr_decompress(z, rr_chunk->data,
4558                                 rr_chunk->len, scratch_buffer, rr_dname,
4559                                 rr_type, rr_class, rr_ttl, rr_rdata, rr_rdlen,
4560                                 &duplicate)) {
4561                                 /* failed, malloc error or so */
4562                                 return 0;
4563                         }
4564                         if(duplicate) {
4565                                 /* it was a duplicate */
4566                                 if(verbosity>=4) log_rrlist_position(
4567                                         "IXFR error duplicate RR",
4568                                         rr_chunk, rr_dname, rr_type, rr_counter);
4569                                 softfail = 1;
4570                         }
4571                 }
4572
4573                 rr_counter++;
4574                 chunk_rrlist_gonext(&rr_chunk, &rr_num, &rr_pos, rr_nextpos);
4575         }
4576         if(softfail) {
4577                 verbose(VERB_ALGO, "IXFR did not apply cleanly, fetching full zone");
4578                 return 0;
4579         }
4580         return 1;
4581 }
4582
4583 /** apply AXFR to zone in memory. z is locked. false on failure(mallocfail) */
4584 static int
4585 apply_axfr(struct auth_xfer* xfr, struct auth_zone* z,
4586         struct sldns_buffer* scratch_buffer)
4587 {
4588         struct auth_chunk* rr_chunk;
4589         int rr_num;
4590         size_t rr_pos;
4591         uint8_t* rr_dname, *rr_rdata;
4592         uint16_t rr_type, rr_class, rr_rdlen;
4593         uint32_t rr_ttl;
4594         uint32_t serial = 0;
4595         size_t rr_nextpos;
4596         size_t rr_counter = 0;
4597         int have_end_soa = 0;
4598
4599         /* clear the data tree */
4600         traverse_postorder(&z->data, auth_data_del, NULL);
4601         rbtree_init(&z->data, &auth_data_cmp);
4602         xfr->have_zone = 0;
4603         xfr->serial = 0;
4604
4605         /* insert all RRs in to the zone */
4606         /* insert the SOA only once, skip the last one */
4607         /* start RR iterator over chunklist of packets */
4608         chunk_rrlist_start(xfr, &rr_chunk, &rr_num, &rr_pos);
4609         while(!chunk_rrlist_end(rr_chunk, rr_num)) {
4610                 if(!chunk_rrlist_get_current(rr_chunk, rr_num, rr_pos,
4611                         &rr_dname, &rr_type, &rr_class, &rr_ttl, &rr_rdlen,
4612                         &rr_rdata, &rr_nextpos)) {
4613                         /* failed to parse RR */
4614                         return 0;
4615                 }
4616                 if(verbosity>=7) log_rrlist_position("apply_axfr",
4617                         rr_chunk, rr_dname, rr_type, rr_counter);
4618                 if(rr_type == LDNS_RR_TYPE_SOA) {
4619                         if(rr_counter != 0) {
4620                                 /* end of the axfr */
4621                                 have_end_soa = 1;
4622                                 break;
4623                         }
4624                         if(rr_rdlen < 22) return 0; /* bad SOA rdlen */
4625                         serial = sldns_read_uint32(rr_rdata+rr_rdlen-20);
4626                 }
4627
4628                 /* add this RR */
4629                 if(!az_insert_rr_decompress(z, rr_chunk->data, rr_chunk->len,
4630                         scratch_buffer, rr_dname, rr_type, rr_class, rr_ttl,
4631                         rr_rdata, rr_rdlen, NULL)) {
4632                         /* failed, malloc error or so */
4633                         return 0;
4634                 }
4635
4636                 rr_counter++;
4637                 chunk_rrlist_gonext(&rr_chunk, &rr_num, &rr_pos, rr_nextpos);
4638         }
4639         if(!have_end_soa) {
4640                 log_err("no end SOA record for AXFR");
4641                 return 0;
4642         }
4643
4644         xfr->serial = serial;
4645         xfr->have_zone = 1;
4646         return 1;
4647 }
4648
4649 /** apply HTTP to zone in memory. z is locked. false on failure(mallocfail) */
4650 static int
4651 apply_http(struct auth_xfer* xfr, struct auth_zone* z,
4652         struct sldns_buffer* scratch_buffer)
4653 {
4654         /* parse data in chunks */
4655         /* parse RR's and read into memory. ignore $INCLUDE from the
4656          * downloaded file*/
4657         struct sldns_file_parse_state pstate;
4658         struct auth_chunk* chunk;
4659         size_t chunk_pos;
4660         memset(&pstate, 0, sizeof(pstate));
4661         pstate.default_ttl = 3600;
4662         if(xfr->namelen < sizeof(pstate.origin)) {
4663                 pstate.origin_len = xfr->namelen;
4664                 memmove(pstate.origin, xfr->name, xfr->namelen);
4665         }
4666
4667         if(verbosity >= VERB_ALGO)
4668                 verbose(VERB_ALGO, "http download %s of size %d",
4669                 xfr->task_transfer->master->file,
4670                 (int)chunklist_sum(xfr->task_transfer->chunks_first));
4671         if(xfr->task_transfer->chunks_first && verbosity >= VERB_ALGO) {
4672                 char preview[1024];
4673                 if(xfr->task_transfer->chunks_first->len+1 > sizeof(preview)) {
4674                         memmove(preview, xfr->task_transfer->chunks_first->data,
4675                                 sizeof(preview)-1);
4676                         preview[sizeof(preview)-1]=0;
4677                 } else {
4678                         memmove(preview, xfr->task_transfer->chunks_first->data,
4679                                 xfr->task_transfer->chunks_first->len);
4680                         preview[xfr->task_transfer->chunks_first->len]=0;
4681                 }
4682                 log_info("auth zone http downloaded content preview: %s",
4683                         preview);
4684         }
4685
4686         /* perhaps a little syntax check before we try to apply the data? */
4687         if(!http_zonefile_syntax_check(xfr, scratch_buffer)) {
4688                 log_err("http download %s/%s does not contain a zonefile, "
4689                         "but got '%s'", xfr->task_transfer->master->host,
4690                         xfr->task_transfer->master->file,
4691                         sldns_buffer_begin(scratch_buffer));
4692                 return 0;
4693         }
4694
4695         /* clear the data tree */
4696         traverse_postorder(&z->data, auth_data_del, NULL);
4697         rbtree_init(&z->data, &auth_data_cmp);
4698         xfr->have_zone = 0;
4699         xfr->serial = 0;
4700
4701         chunk = xfr->task_transfer->chunks_first;
4702         chunk_pos = 0;
4703         pstate.lineno = 0;
4704         while(chunkline_get_line_collated(&chunk, &chunk_pos, scratch_buffer)) {
4705                 /* process this line */
4706                 pstate.lineno++;
4707                 chunkline_newline_removal(scratch_buffer);
4708                 if(chunkline_is_comment_line_or_empty(scratch_buffer)) {
4709                         continue;
4710                 }
4711                 /* parse line and add RR */
4712                 if(http_parse_origin(scratch_buffer, &pstate)) {
4713                         continue; /* $ORIGIN has been handled */
4714                 }
4715                 if(http_parse_ttl(scratch_buffer, &pstate)) {
4716                         continue; /* $TTL has been handled */
4717                 }
4718                 if(!http_parse_add_rr(xfr, z, scratch_buffer, &pstate)) {
4719                         verbose(VERB_ALGO, "error parsing line [%s:%d] %s",
4720                                 xfr->task_transfer->master->file,
4721                                 pstate.lineno,
4722                                 sldns_buffer_begin(scratch_buffer));
4723                         return 0;
4724                 }
4725         }
4726         return 1;
4727 }
4728
4729 /** write http chunks to zonefile to create downloaded file */
4730 static int
4731 auth_zone_write_chunks(struct auth_xfer* xfr, const char* fname)
4732 {
4733         FILE* out;
4734         struct auth_chunk* p;
4735         out = fopen(fname, "w");
4736         if(!out) {
4737                 log_err("could not open %s: %s", fname, strerror(errno));
4738                 return 0;
4739         }
4740         for(p = xfr->task_transfer->chunks_first; p ; p = p->next) {
4741                 if(!write_out(out, (char*)p->data, p->len)) {
4742                         log_err("could not write http download to %s", fname);
4743                         fclose(out);
4744                         return 0;
4745                 }
4746         }
4747         fclose(out);
4748         return 1;
4749 }
4750
4751 /** write to zonefile after zone has been updated */
4752 static void
4753 xfr_write_after_update(struct auth_xfer* xfr, struct module_env* env)
4754 {
4755         struct auth_zone* z;
4756         char tmpfile[1024];
4757         lock_basic_unlock(&xfr->lock);
4758
4759         /* get lock again, so it is a readlock and concurrently queries
4760          * can be answered */
4761         lock_rw_rdlock(&env->auth_zones->lock);
4762         z = auth_zone_find(env->auth_zones, xfr->name, xfr->namelen,
4763                 xfr->dclass);
4764         if(!z) {
4765                 lock_rw_unlock(&env->auth_zones->lock);
4766                 /* the zone is gone, ignore xfr results */
4767                 lock_basic_lock(&xfr->lock);
4768                 return;
4769         }
4770         lock_rw_rdlock(&z->lock);
4771         lock_basic_lock(&xfr->lock);
4772         lock_rw_unlock(&env->auth_zones->lock);
4773
4774         if(z->zonefile == NULL) {
4775                 lock_rw_unlock(&z->lock);
4776                 /* no write needed, no zonefile set */
4777                 return;
4778         }
4779
4780         /* write to tempfile first */
4781         if((size_t)strlen(z->zonefile) + 16 > sizeof(tmpfile)) {
4782                 verbose(VERB_ALGO, "tmpfilename too long, cannot update "
4783                         " zonefile %s", z->zonefile);
4784                 lock_rw_unlock(&z->lock);
4785                 return;
4786         }
4787         snprintf(tmpfile, sizeof(tmpfile), "%s.tmp%u", z->zonefile,
4788                 (unsigned)getpid());
4789         if(xfr->task_transfer->master->http) {
4790                 /* use the stored chunk list to write them */
4791                 if(!auth_zone_write_chunks(xfr, tmpfile)) {
4792                         unlink(tmpfile);
4793                         lock_rw_unlock(&z->lock);
4794                 }
4795         } else if(!auth_zone_write_file(z, tmpfile)) {
4796                 unlink(tmpfile);
4797                 lock_rw_unlock(&z->lock);
4798                 return;
4799         }
4800         if(rename(tmpfile, z->zonefile) < 0) {
4801                 log_err("could not rename(%s, %s): %s", tmpfile, z->zonefile,
4802                         strerror(errno));
4803                 unlink(tmpfile);
4804                 lock_rw_unlock(&z->lock);
4805                 return;
4806         }
4807         lock_rw_unlock(&z->lock);
4808 }
4809
4810 /** process chunk list and update zone in memory,
4811  * return false if it did not work */
4812 static int
4813 xfr_process_chunk_list(struct auth_xfer* xfr, struct module_env* env,
4814         int* ixfr_fail)
4815 {
4816         struct auth_zone* z;
4817
4818         /* obtain locks and structures */
4819         /* release xfr lock, then, while holding az->lock grab both
4820          * z->lock and xfr->lock */
4821         lock_basic_unlock(&xfr->lock);
4822         lock_rw_rdlock(&env->auth_zones->lock);
4823         z = auth_zone_find(env->auth_zones, xfr->name, xfr->namelen,
4824                 xfr->dclass);
4825         if(!z) {
4826                 lock_rw_unlock(&env->auth_zones->lock);
4827                 /* the zone is gone, ignore xfr results */
4828                 lock_basic_lock(&xfr->lock);
4829                 return 0;
4830         }
4831         lock_rw_wrlock(&z->lock);
4832         lock_basic_lock(&xfr->lock);
4833         lock_rw_unlock(&env->auth_zones->lock);
4834
4835         /* apply data */
4836         if(xfr->task_transfer->master->http) {
4837                 if(!apply_http(xfr, z, env->scratch_buffer)) {
4838                         lock_rw_unlock(&z->lock);
4839                         verbose(VERB_ALGO, "http from %s: could not store data",
4840                                 xfr->task_transfer->master->host);
4841                         return 0;
4842                 }
4843         } else if(xfr->task_transfer->on_ixfr &&
4844                 !xfr->task_transfer->on_ixfr_is_axfr) {
4845                 if(!apply_ixfr(xfr, z, env->scratch_buffer)) {
4846                         lock_rw_unlock(&z->lock);
4847                         verbose(VERB_ALGO, "xfr from %s: could not store IXFR"
4848                                 " data", xfr->task_transfer->master->host);
4849                         *ixfr_fail = 1;
4850                         return 0;
4851                 }
4852         } else {
4853                 if(!apply_axfr(xfr, z, env->scratch_buffer)) {
4854                         lock_rw_unlock(&z->lock);
4855                         verbose(VERB_ALGO, "xfr from %s: could not store AXFR"
4856                                 " data", xfr->task_transfer->master->host);
4857                         return 0;
4858                 }
4859         }
4860         xfr->zone_expired = 0;
4861         z->zone_expired = 0;
4862         if(!xfr_find_soa(z, xfr)) {
4863                 lock_rw_unlock(&z->lock);
4864                 verbose(VERB_ALGO, "xfr from %s: no SOA in zone after update"
4865                         " (or malformed RR)", xfr->task_transfer->master->host);
4866                 return 0;
4867         }
4868         if(xfr->have_zone)
4869                 xfr->lease_time = *env->now;
4870
4871         /* unlock */
4872         lock_rw_unlock(&z->lock);
4873
4874         if(verbosity >= VERB_QUERY && xfr->have_zone) {
4875                 char zname[256];
4876                 dname_str(xfr->name, zname);
4877                 verbose(VERB_QUERY, "auth zone %s updated to serial %u", zname,
4878                         (unsigned)xfr->serial);
4879         }
4880         /* see if we need to write to a zonefile */
4881         xfr_write_after_update(xfr, env);
4882         return 1;
4883 }
4884
4885 /** disown task_transfer.  caller must hold xfr.lock */
4886 static void
4887 xfr_transfer_disown(struct auth_xfer* xfr)
4888 {
4889         /* remove the commpoint */
4890         comm_point_delete(xfr->task_transfer->cp);
4891         xfr->task_transfer->cp = NULL;
4892         /* we don't own this item anymore */
4893         xfr->task_transfer->worker = NULL;
4894         xfr->task_transfer->env = NULL;
4895 }
4896
4897 /** lookup a host name for its addresses, if needed */
4898 static int
4899 xfr_transfer_lookup_host(struct auth_xfer* xfr, struct module_env* env)
4900 {
4901         struct sockaddr_storage addr;
4902         socklen_t addrlen = 0;
4903         struct auth_master* master = xfr->task_transfer->lookup_target;
4904         struct query_info qinfo;
4905         uint16_t qflags = BIT_RD;
4906         uint8_t dname[LDNS_MAX_DOMAINLEN+1];
4907         struct edns_data edns;
4908         sldns_buffer* buf = env->scratch_buffer;
4909         if(!master) return 0;
4910         if(extstrtoaddr(master->host, &addr, &addrlen)) {
4911                 /* not needed, host is in IP addr format */
4912                 return 0;
4913         }
4914         if(master->allow_notify)
4915                 return 0; /* allow-notifies are not transferred from, no
4916                 lookup is needed */
4917
4918         /* use mesh_new_callback to probe for non-addr hosts,
4919          * and then wait for them to be looked up (in cache, or query) */
4920         qinfo.qname_len = sizeof(dname);
4921         if(sldns_str2wire_dname_buf(master->host, dname, &qinfo.qname_len)
4922                 != 0) {
4923                 log_err("cannot parse host name of master %s", master->host);
4924                 return 0;
4925         }
4926         qinfo.qname = dname;
4927         qinfo.qclass = xfr->dclass;
4928         qinfo.qtype = LDNS_RR_TYPE_A;
4929         if(xfr->task_transfer->lookup_aaaa)
4930                 qinfo.qtype = LDNS_RR_TYPE_AAAA;
4931         qinfo.local_alias = NULL;
4932         if(verbosity >= VERB_ALGO) {
4933                 char buf[512];
4934                 char buf2[LDNS_MAX_DOMAINLEN+1];
4935                 dname_str(xfr->name, buf2);
4936                 snprintf(buf, sizeof(buf), "auth zone %s: master lookup"
4937                         " for task_transfer", buf2);
4938                 log_query_info(VERB_ALGO, buf, &qinfo);
4939         }
4940         edns.edns_present = 1;
4941         edns.ext_rcode = 0;
4942         edns.edns_version = 0;
4943         edns.bits = EDNS_DO;
4944         edns.opt_list = NULL;
4945         if(sldns_buffer_capacity(buf) < 65535)
4946                 edns.udp_size = (uint16_t)sldns_buffer_capacity(buf);
4947         else    edns.udp_size = 65535;
4948
4949         /* unlock xfr during mesh_new_callback() because the callback can be
4950          * called straight away */
4951         lock_basic_unlock(&xfr->lock);
4952         if(!mesh_new_callback(env->mesh, &qinfo, qflags, &edns, buf, 0,
4953                 &auth_xfer_transfer_lookup_callback, xfr)) {
4954                 lock_basic_lock(&xfr->lock);
4955                 log_err("out of memory lookup up master %s", master->host);
4956                 return 0;
4957         }
4958         lock_basic_lock(&xfr->lock);
4959         return 1;
4960 }
4961
4962 /** initiate TCP to the target and fetch zone.
4963  * returns true if that was successfully started, and timeout setup. */
4964 static int
4965 xfr_transfer_init_fetch(struct auth_xfer* xfr, struct module_env* env)
4966 {
4967         struct sockaddr_storage addr;
4968         socklen_t addrlen = 0;
4969         struct auth_master* master = xfr->task_transfer->master;
4970         if(!master) return 0;
4971         if(master->allow_notify) return 0; /* only for notify */
4972
4973         /* get master addr */
4974         if(xfr->task_transfer->scan_addr) {
4975                 addrlen = xfr->task_transfer->scan_addr->addrlen;
4976                 memmove(&addr, &xfr->task_transfer->scan_addr->addr, addrlen);
4977         } else {
4978                 if(!extstrtoaddr(master->host, &addr, &addrlen)) {
4979                         /* the ones that are not in addr format are supposed
4980                          * to be looked up.  The lookup has failed however,
4981                          * so skip them */
4982                         char zname[255+1];
4983                         dname_str(xfr->name, zname);
4984                         log_err("%s: failed lookup, cannot transfer from master %s",
4985                                 zname, master->host);
4986                         return 0;
4987                 }
4988         }
4989
4990         /* remove previous TCP connection (if any) */
4991         if(xfr->task_transfer->cp) {
4992                 comm_point_delete(xfr->task_transfer->cp);
4993                 xfr->task_transfer->cp = NULL;
4994         }
4995
4996         if(master->http) {
4997                 /* perform http fetch */
4998                 /* store http port number into sockaddr,
4999                  * unless someone used unbound's host@port notation */
5000                 if(strchr(master->host, '@') == NULL)
5001                         sockaddr_store_port(&addr, addrlen, master->port);
5002                 xfr->task_transfer->cp = outnet_comm_point_for_http(
5003                         env->outnet, auth_xfer_transfer_http_callback, xfr,
5004                         &addr, addrlen, AUTH_TRANSFER_TIMEOUT, master->ssl,
5005                         master->host, master->file);
5006                 if(!xfr->task_transfer->cp) {
5007                         char zname[255+1];
5008                         dname_str(xfr->name, zname);
5009                         verbose(VERB_ALGO, "cannot create http cp "
5010                                 "connection for %s to %s", zname,
5011                                 master->host);
5012                         return 0;
5013                 }
5014                 return 1;
5015         }
5016
5017         /* perform AXFR/IXFR */
5018         /* set the packet to be written */
5019         /* create new ID */
5020         xfr->task_transfer->id = (uint16_t)(ub_random(env->rnd)&0xffff);
5021         xfr_create_ixfr_packet(xfr, env->scratch_buffer,
5022                 xfr->task_transfer->id, master);
5023
5024         /* connect on fd */
5025         xfr->task_transfer->cp = outnet_comm_point_for_tcp(env->outnet,
5026                 auth_xfer_transfer_tcp_callback, xfr, &addr, addrlen,
5027                 env->scratch_buffer, AUTH_TRANSFER_TIMEOUT);
5028         if(!xfr->task_transfer->cp) {
5029                 char zname[255+1];
5030                 dname_str(xfr->name, zname);
5031                 verbose(VERB_ALGO, "cannot create tcp cp connection for "
5032                         "xfr %s to %s", zname, master->host);
5033                 return 0;
5034         }
5035         return 1;
5036 }
5037
5038 /** perform next lookup, next transfer TCP, or end and resume wait time task */
5039 static void
5040 xfr_transfer_nexttarget_or_end(struct auth_xfer* xfr, struct module_env* env)
5041 {
5042         log_assert(xfr->task_transfer->worker == env->worker);
5043
5044         /* are we performing lookups? */
5045         while(xfr->task_transfer->lookup_target) {
5046                 if(xfr_transfer_lookup_host(xfr, env)) {
5047                         /* wait for lookup to finish,
5048                          * note that the hostname may be in unbound's cache
5049                          * and we may then get an instant cache response,
5050                          * and that calls the callback just like a full
5051                          * lookup and lookup failures also call callback */
5052                         lock_basic_unlock(&xfr->lock);
5053                         return;
5054                 }
5055                 xfr_transfer_move_to_next_lookup(xfr, env);
5056         }
5057
5058         /* initiate TCP and fetch the zone from the master */
5059         /* and set timeout on it */
5060         while(!xfr_transfer_end_of_list(xfr)) {
5061                 xfr->task_transfer->master = xfr_transfer_current_master(xfr);
5062                 if(xfr_transfer_init_fetch(xfr, env)) {
5063                         /* successfully started, wait for callback */
5064                         lock_basic_unlock(&xfr->lock);
5065                         return;
5066                 }
5067                 /* failed to fetch, next master */
5068                 xfr_transfer_nextmaster(xfr);
5069         }
5070
5071         /* we failed to fetch the zone, move to wait task
5072          * use the shorter retry timeout */
5073         xfr_transfer_disown(xfr);
5074
5075         /* pick up the nextprobe task and wait */
5076         xfr_set_timeout(xfr, env, 1, 0);
5077         lock_basic_unlock(&xfr->lock);
5078 }
5079
5080 /** add addrs from A or AAAA rrset to the master */
5081 static void
5082 xfr_master_add_addrs(struct auth_master* m, struct ub_packed_rrset_key* rrset,
5083         uint16_t rrtype)
5084 {
5085         size_t i;
5086         struct packed_rrset_data* data;
5087         if(!m || !rrset) return;
5088         if(rrtype != LDNS_RR_TYPE_A && rrtype != LDNS_RR_TYPE_AAAA)
5089                 return;
5090         data = (struct packed_rrset_data*)rrset->entry.data;
5091         for(i=0; i<data->count; i++) {
5092                 struct auth_addr* a;
5093                 size_t len = data->rr_len[i] - 2;
5094                 uint8_t* rdata = data->rr_data[i]+2;
5095                 if(rrtype == LDNS_RR_TYPE_A && len != INET_SIZE)
5096                         continue; /* wrong length for A */
5097                 if(rrtype == LDNS_RR_TYPE_AAAA && len != INET6_SIZE)
5098                         continue; /* wrong length for AAAA */
5099                 
5100                 /* add and alloc it */
5101                 a = (struct auth_addr*)calloc(1, sizeof(*a));
5102                 if(!a) {
5103                         log_err("out of memory");
5104                         return;
5105                 }
5106                 if(rrtype == LDNS_RR_TYPE_A) {
5107                         struct sockaddr_in* sa;
5108                         a->addrlen = (socklen_t)sizeof(*sa);
5109                         sa = (struct sockaddr_in*)&a->addr;
5110                         sa->sin_family = AF_INET;
5111                         sa->sin_port = (in_port_t)htons(UNBOUND_DNS_PORT);
5112                         memmove(&sa->sin_addr, rdata, INET_SIZE);
5113                 } else {
5114                         struct sockaddr_in6* sa;
5115                         a->addrlen = (socklen_t)sizeof(*sa);
5116                         sa = (struct sockaddr_in6*)&a->addr;
5117                         sa->sin6_family = AF_INET6;
5118                         sa->sin6_port = (in_port_t)htons(UNBOUND_DNS_PORT);
5119                         memmove(&sa->sin6_addr, rdata, INET6_SIZE);
5120                 }
5121                 if(verbosity >= VERB_ALGO) {
5122                         char s[64];
5123                         addr_to_str(&a->addr, a->addrlen, s, sizeof(s));
5124                         verbose(VERB_ALGO, "auth host %s lookup %s",
5125                                 m->host, s);
5126                 }
5127                 /* append to list */
5128                 a->next = m->list;
5129                 m->list = a;
5130         }
5131 }
5132
5133 /** callback for task_transfer lookup of host name, of A or AAAA */
5134 void auth_xfer_transfer_lookup_callback(void* arg, int rcode, sldns_buffer* buf,
5135         enum sec_status ATTR_UNUSED(sec), char* ATTR_UNUSED(why_bogus))
5136 {
5137         struct auth_xfer* xfr = (struct auth_xfer*)arg;
5138         struct module_env* env;
5139         log_assert(xfr->task_transfer);
5140         lock_basic_lock(&xfr->lock);
5141         env = xfr->task_transfer->env;
5142         if(env->outnet->want_to_quit) {
5143                 lock_basic_unlock(&xfr->lock);
5144                 return; /* stop on quit */
5145         }
5146
5147         /* process result */
5148         if(rcode == LDNS_RCODE_NOERROR) {
5149                 uint16_t wanted_qtype = LDNS_RR_TYPE_A;
5150                 struct regional* temp = env->scratch;
5151                 struct query_info rq;
5152                 struct reply_info* rep;
5153                 if(xfr->task_transfer->lookup_aaaa)
5154                         wanted_qtype = LDNS_RR_TYPE_AAAA;
5155                 memset(&rq, 0, sizeof(rq));
5156                 rep = parse_reply_in_temp_region(buf, temp, &rq);
5157                 if(rep && rq.qtype == wanted_qtype &&
5158                         FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NOERROR) {
5159                         /* parsed successfully */
5160                         struct ub_packed_rrset_key* answer =
5161                                 reply_find_answer_rrset(&rq, rep);
5162                         if(answer) {
5163                                 xfr_master_add_addrs(xfr->task_transfer->
5164                                         lookup_target, answer, wanted_qtype);
5165                         }
5166                 }
5167         }
5168         if(xfr->task_transfer->lookup_target->list &&
5169                 xfr->task_transfer->lookup_target == xfr_transfer_current_master(xfr))
5170                 xfr->task_transfer->scan_addr = xfr->task_transfer->lookup_target->list;
5171
5172         /* move to lookup AAAA after A lookup, move to next hostname lookup,
5173          * or move to fetch the zone, or, if nothing to do, end task_transfer */
5174         xfr_transfer_move_to_next_lookup(xfr, env);
5175         xfr_transfer_nexttarget_or_end(xfr, env);
5176 }
5177
5178 /** check if xfer (AXFR or IXFR) packet is OK.
5179  * return false if we lost connection (SERVFAIL, or unreadable).
5180  * return false if we need to move from IXFR to AXFR, with gonextonfail
5181  *      set to false, so the same master is tried again, but with AXFR.
5182  * return true if fine to link into data.
5183  * return true with transferdone=true when the transfer has ended.
5184  */
5185 static int
5186 check_xfer_packet(sldns_buffer* pkt, struct auth_xfer* xfr,
5187         int* gonextonfail, int* transferdone)
5188 {
5189         uint8_t* wire = sldns_buffer_begin(pkt);
5190         int i;
5191         if(sldns_buffer_limit(pkt) < LDNS_HEADER_SIZE) {
5192                 verbose(VERB_ALGO, "xfr to %s failed, packet too small",
5193                         xfr->task_transfer->master->host);
5194                 return 0;
5195         }
5196         if(!LDNS_QR_WIRE(wire)) {
5197                 verbose(VERB_ALGO, "xfr to %s failed, packet has no QR flag",
5198                         xfr->task_transfer->master->host);
5199                 return 0;
5200         }
5201         if(LDNS_TC_WIRE(wire)) {
5202                 verbose(VERB_ALGO, "xfr to %s failed, packet has TC flag",
5203                         xfr->task_transfer->master->host);
5204                 return 0;
5205         }
5206         /* check ID */
5207         if(LDNS_ID_WIRE(wire) != xfr->task_transfer->id) {
5208                 verbose(VERB_ALGO, "xfr to %s failed, packet wrong ID",
5209                         xfr->task_transfer->master->host);
5210                 return 0;
5211         }
5212         if(LDNS_RCODE_WIRE(wire) != LDNS_RCODE_NOERROR) {
5213                 char rcode[32];
5214                 sldns_wire2str_rcode_buf((int)LDNS_RCODE_WIRE(wire), rcode,
5215                         sizeof(rcode));
5216                 /* if we are doing IXFR, check for fallback */
5217                 if(xfr->task_transfer->on_ixfr) {
5218                         if(LDNS_RCODE_WIRE(wire) == LDNS_RCODE_NOTIMPL ||
5219                                 LDNS_RCODE_WIRE(wire) == LDNS_RCODE_SERVFAIL ||
5220                                 LDNS_RCODE_WIRE(wire) == LDNS_RCODE_REFUSED ||
5221                                 LDNS_RCODE_WIRE(wire) == LDNS_RCODE_FORMERR) {
5222                                 verbose(VERB_ALGO, "xfr to %s, fallback "
5223                                         "from IXFR to AXFR (with rcode %s)",
5224                                         xfr->task_transfer->master->host,
5225                                         rcode);
5226                                 xfr->task_transfer->ixfr_fail = 1;
5227                                 *gonextonfail = 0;
5228                                 return 0;
5229                         }
5230                 }
5231                 verbose(VERB_ALGO, "xfr to %s failed, packet with rcode %s",
5232                         xfr->task_transfer->master->host, rcode);
5233                 return 0;
5234         }
5235         if(LDNS_OPCODE_WIRE(wire) != LDNS_PACKET_QUERY) {
5236                 verbose(VERB_ALGO, "xfr to %s failed, packet with bad opcode",
5237                         xfr->task_transfer->master->host);
5238                 return 0;
5239         }
5240         if(LDNS_QDCOUNT(wire) > 1) {
5241                 verbose(VERB_ALGO, "xfr to %s failed, packet has qdcount %d",
5242                         xfr->task_transfer->master->host,
5243                         (int)LDNS_QDCOUNT(wire));
5244                 return 0;
5245         }
5246
5247         /* check qname */
5248         sldns_buffer_set_position(pkt, LDNS_HEADER_SIZE);
5249         for(i=0; i<(int)LDNS_QDCOUNT(wire); i++) {
5250                 size_t pos = sldns_buffer_position(pkt);
5251                 uint16_t qtype, qclass;
5252                 if(pkt_dname_len(pkt) == 0) {
5253                         verbose(VERB_ALGO, "xfr to %s failed, packet with "
5254                                 "malformed dname",
5255                                 xfr->task_transfer->master->host);
5256                         return 0;
5257                 }
5258                 if(dname_pkt_compare(pkt, sldns_buffer_at(pkt, pos),
5259                         xfr->name) != 0) {
5260                         verbose(VERB_ALGO, "xfr to %s failed, packet with "
5261                                 "wrong qname",
5262                                 xfr->task_transfer->master->host);
5263                         return 0;
5264                 }
5265                 if(sldns_buffer_remaining(pkt) < 4) {
5266                         verbose(VERB_ALGO, "xfr to %s failed, packet with "
5267                                 "truncated query RR",
5268                                 xfr->task_transfer->master->host);
5269                         return 0;
5270                 }
5271                 qtype = sldns_buffer_read_u16(pkt);
5272                 qclass = sldns_buffer_read_u16(pkt);
5273                 if(qclass != xfr->dclass) {
5274                         verbose(VERB_ALGO, "xfr to %s failed, packet with "
5275                                 "wrong qclass",
5276                                 xfr->task_transfer->master->host);
5277                         return 0;
5278                 }
5279                 if(xfr->task_transfer->on_ixfr) {
5280                         if(qtype != LDNS_RR_TYPE_IXFR) {
5281                                 verbose(VERB_ALGO, "xfr to %s failed, packet "
5282                                         "with wrong qtype, expected IXFR",
5283                                 xfr->task_transfer->master->host);
5284                                 return 0;
5285                         }
5286                 } else {
5287                         if(qtype != LDNS_RR_TYPE_AXFR) {
5288                                 verbose(VERB_ALGO, "xfr to %s failed, packet "
5289                                         "with wrong qtype, expected AXFR",
5290                                 xfr->task_transfer->master->host);
5291                                 return 0;
5292                         }
5293                 }
5294         }
5295
5296         /* check parse of RRs in packet, store first SOA serial
5297          * to be able to detect last SOA (with that serial) to see if done */
5298         /* also check for IXFR 'zone up to date' reply */
5299         for(i=0; i<(int)LDNS_ANCOUNT(wire); i++) {
5300                 size_t pos = sldns_buffer_position(pkt);
5301                 uint16_t tp, rdlen;
5302                 if(pkt_dname_len(pkt) == 0) {
5303                         verbose(VERB_ALGO, "xfr to %s failed, packet with "
5304                                 "malformed dname in answer section",
5305                                 xfr->task_transfer->master->host);
5306                         return 0;
5307                 }
5308                 if(sldns_buffer_remaining(pkt) < 10) {
5309                         verbose(VERB_ALGO, "xfr to %s failed, packet with "
5310                                 "truncated RR",
5311                                 xfr->task_transfer->master->host);
5312                         return 0;
5313                 }
5314                 tp = sldns_buffer_read_u16(pkt);
5315                 (void)sldns_buffer_read_u16(pkt); /* class */
5316                 (void)sldns_buffer_read_u32(pkt); /* ttl */
5317                 rdlen = sldns_buffer_read_u16(pkt);
5318                 if(sldns_buffer_remaining(pkt) < rdlen) {
5319                         verbose(VERB_ALGO, "xfr to %s failed, packet with "
5320                                 "truncated RR rdata",
5321                                 xfr->task_transfer->master->host);
5322                         return 0;
5323                 }
5324
5325                 /* RR parses (haven't checked rdata itself), now look at
5326                  * SOA records to see serial number */
5327                 if(xfr->task_transfer->rr_scan_num == 0 &&
5328                         tp != LDNS_RR_TYPE_SOA) {
5329                         verbose(VERB_ALGO, "xfr to %s failed, packet with "
5330                                 "malformed zone transfer, no start SOA",
5331                                 xfr->task_transfer->master->host);
5332                         return 0;
5333                 }
5334                 if(xfr->task_transfer->rr_scan_num == 1 &&
5335                         tp != LDNS_RR_TYPE_SOA) {
5336                         /* second RR is not a SOA record, this is not an IXFR
5337                          * the master is replying with an AXFR */
5338                         xfr->task_transfer->on_ixfr_is_axfr = 1;
5339                 }
5340                 if(tp == LDNS_RR_TYPE_SOA) {
5341                         uint32_t serial;
5342                         if(rdlen < 22) {
5343                                 verbose(VERB_ALGO, "xfr to %s failed, packet "
5344                                         "with SOA with malformed rdata",
5345                                         xfr->task_transfer->master->host);
5346                                 return 0;
5347                         }
5348                         if(dname_pkt_compare(pkt, sldns_buffer_at(pkt, pos),
5349                                 xfr->name) != 0) {
5350                                 verbose(VERB_ALGO, "xfr to %s failed, packet "
5351                                         "with SOA with wrong dname",
5352                                         xfr->task_transfer->master->host);
5353                                 return 0;
5354                         }
5355
5356                         /* read serial number of SOA */
5357                         serial = sldns_buffer_read_u32_at(pkt,
5358                                 sldns_buffer_position(pkt)+rdlen-20);
5359
5360                         /* check for IXFR 'zone has SOA x' reply */
5361                         if(xfr->task_transfer->on_ixfr &&
5362                                 xfr->task_transfer->rr_scan_num == 0 &&
5363                                 LDNS_ANCOUNT(wire)==1) {
5364                                 verbose(VERB_ALGO, "xfr to %s ended, "
5365                                         "IXFR reply that zone has serial %u",
5366                                         xfr->task_transfer->master->host,
5367                                         (unsigned)serial);
5368                                 return 0;
5369                         }
5370
5371                         /* if first SOA, store serial number */
5372                         if(xfr->task_transfer->got_xfr_serial == 0) {
5373                                 xfr->task_transfer->got_xfr_serial = 1;
5374                                 xfr->task_transfer->incoming_xfr_serial =
5375                                         serial;
5376                                 verbose(VERB_ALGO, "xfr %s: contains "
5377                                         "SOA serial %u",
5378                                         xfr->task_transfer->master->host,
5379                                         (unsigned)serial);
5380                         /* see if end of AXFR */
5381                         } else if(!xfr->task_transfer->on_ixfr ||
5382                                 xfr->task_transfer->on_ixfr_is_axfr) {
5383                                 /* second SOA with serial is the end
5384                                  * for AXFR */
5385                                 *transferdone = 1;
5386                                 verbose(VERB_ALGO, "xfr %s: last AXFR packet",
5387                                         xfr->task_transfer->master->host);
5388                         /* for IXFR, count SOA records with that serial */
5389                         } else if(xfr->task_transfer->incoming_xfr_serial ==
5390                                 serial && xfr->task_transfer->got_xfr_serial
5391                                 == 1) {
5392                                 xfr->task_transfer->got_xfr_serial++;
5393                         /* if not first soa, if serial==firstserial, the
5394                          * third time we are at the end, for IXFR */
5395                         } else if(xfr->task_transfer->incoming_xfr_serial ==
5396                                 serial && xfr->task_transfer->got_xfr_serial
5397                                 == 2) {
5398                                 verbose(VERB_ALGO, "xfr %s: last IXFR packet",
5399                                         xfr->task_transfer->master->host);
5400                                 *transferdone = 1;
5401                                 /* continue parse check, if that succeeds,
5402                                  * transfer is done */
5403                         }
5404                 }
5405                 xfr->task_transfer->rr_scan_num++;
5406
5407                 /* skip over RR rdata to go to the next RR */
5408                 sldns_buffer_skip(pkt, (ssize_t)rdlen);
5409         }
5410
5411         /* check authority section */
5412         /* we skip over the RRs checking packet format */
5413         for(i=0; i<(int)LDNS_NSCOUNT(wire); i++) {
5414                 uint16_t rdlen;
5415                 if(pkt_dname_len(pkt) == 0) {
5416                         verbose(VERB_ALGO, "xfr to %s failed, packet with "
5417                                 "malformed dname in authority section",
5418                                 xfr->task_transfer->master->host);
5419                         return 0;
5420                 }
5421                 if(sldns_buffer_remaining(pkt) < 10) {
5422                         verbose(VERB_ALGO, "xfr to %s failed, packet with "
5423                                 "truncated RR",
5424                                 xfr->task_transfer->master->host);
5425                         return 0;
5426                 }
5427                 (void)sldns_buffer_read_u16(pkt); /* type */
5428                 (void)sldns_buffer_read_u16(pkt); /* class */
5429                 (void)sldns_buffer_read_u32(pkt); /* ttl */
5430                 rdlen = sldns_buffer_read_u16(pkt);
5431                 if(sldns_buffer_remaining(pkt) < rdlen) {
5432                         verbose(VERB_ALGO, "xfr to %s failed, packet with "
5433                                 "truncated RR rdata",
5434                                 xfr->task_transfer->master->host);
5435                         return 0;
5436                 }
5437                 /* skip over RR rdata to go to the next RR */
5438                 sldns_buffer_skip(pkt, (ssize_t)rdlen);
5439         }
5440
5441         /* check additional section */
5442         for(i=0; i<(int)LDNS_ARCOUNT(wire); i++) {
5443                 uint16_t rdlen;
5444                 if(pkt_dname_len(pkt) == 0) {
5445                         verbose(VERB_ALGO, "xfr to %s failed, packet with "
5446                                 "malformed dname in additional section",
5447                                 xfr->task_transfer->master->host);
5448                         return 0;
5449                 }
5450                 if(sldns_buffer_remaining(pkt) < 10) {
5451                         verbose(VERB_ALGO, "xfr to %s failed, packet with "
5452                                 "truncated RR",
5453                                 xfr->task_transfer->master->host);
5454                         return 0;
5455                 }
5456                 (void)sldns_buffer_read_u16(pkt); /* type */
5457                 (void)sldns_buffer_read_u16(pkt); /* class */
5458                 (void)sldns_buffer_read_u32(pkt); /* ttl */
5459                 rdlen = sldns_buffer_read_u16(pkt);
5460                 if(sldns_buffer_remaining(pkt) < rdlen) {
5461                         verbose(VERB_ALGO, "xfr to %s failed, packet with "
5462                                 "truncated RR rdata",
5463                                 xfr->task_transfer->master->host);
5464                         return 0;
5465                 }
5466                 /* skip over RR rdata to go to the next RR */
5467                 sldns_buffer_skip(pkt, (ssize_t)rdlen);
5468         }
5469
5470         return 1;
5471 }
5472
5473 /** Link the data from this packet into the worklist of transferred data */
5474 static int
5475 xfer_link_data(sldns_buffer* pkt, struct auth_xfer* xfr)
5476 {
5477         /* alloc it */
5478         struct auth_chunk* e;
5479         e = (struct auth_chunk*)calloc(1, sizeof(*e));
5480         if(!e) return 0;
5481         e->next = NULL;
5482         e->len = sldns_buffer_limit(pkt);
5483         e->data = memdup(sldns_buffer_begin(pkt), e->len);
5484         if(!e->data) {
5485                 free(e);
5486                 return 0;
5487         }
5488
5489         /* alloc succeeded, link into list */
5490         if(!xfr->task_transfer->chunks_first)
5491                 xfr->task_transfer->chunks_first = e;
5492         if(xfr->task_transfer->chunks_last)
5493                 xfr->task_transfer->chunks_last->next = e;
5494         xfr->task_transfer->chunks_last = e;
5495         return 1;
5496 }
5497
5498 /** task transfer.  the list of data is complete. process it and if failed
5499  * move to next master, if succeeded, end the task transfer */
5500 static void
5501 process_list_end_transfer(struct auth_xfer* xfr, struct module_env* env)
5502 {
5503         int ixfr_fail = 0;
5504         if(xfr_process_chunk_list(xfr, env, &ixfr_fail)) {
5505                 /* it worked! */
5506                 auth_chunks_delete(xfr->task_transfer);
5507
5508                 /* we fetched the zone, move to wait task */
5509                 xfr_transfer_disown(xfr);
5510
5511                 if(xfr->notify_received && (!xfr->notify_has_serial ||
5512                         (xfr->notify_has_serial && 
5513                         xfr_serial_means_update(xfr, xfr->notify_serial)))) {
5514                         uint32_t sr = xfr->notify_serial;
5515                         int has_sr = xfr->notify_has_serial;
5516                         /* we received a notify while probe/transfer was
5517                          * in progress.  start a new probe and transfer */
5518                         xfr->notify_received = 0;
5519                         xfr->notify_has_serial = 0;
5520                         xfr->notify_serial = 0;
5521                         if(!xfr_start_probe(xfr, env, NULL)) {
5522                                 /* if we couldn't start it, already in
5523                                  * progress; restore notify serial,
5524                                  * while xfr still locked */
5525                                 xfr->notify_received = 1;
5526                                 xfr->notify_has_serial = has_sr;
5527                                 xfr->notify_serial = sr;
5528                                 lock_basic_unlock(&xfr->lock);
5529                         }
5530                         return;
5531                 } else {
5532                         /* pick up the nextprobe task and wait (normail wait time) */
5533                         xfr_set_timeout(xfr, env, 0, 0);
5534                 }
5535                 lock_basic_unlock(&xfr->lock);
5536                 return;
5537         }
5538         /* processing failed */
5539         /* when done, delete data from list */
5540         auth_chunks_delete(xfr->task_transfer);
5541         if(ixfr_fail) {
5542                 xfr->task_transfer->ixfr_fail = 1;
5543         } else {
5544                 xfr_transfer_nextmaster(xfr);
5545         }
5546         xfr_transfer_nexttarget_or_end(xfr, env);
5547 }
5548
5549 /** callback for task_transfer tcp connections */
5550 int
5551 auth_xfer_transfer_tcp_callback(struct comm_point* c, void* arg, int err,
5552         struct comm_reply* ATTR_UNUSED(repinfo))
5553 {
5554         struct auth_xfer* xfr = (struct auth_xfer*)arg;
5555         struct module_env* env;
5556         int gonextonfail = 1;
5557         int transferdone = 0;
5558         log_assert(xfr->task_transfer);
5559         lock_basic_lock(&xfr->lock);
5560         env = xfr->task_transfer->env;
5561         if(env->outnet->want_to_quit) {
5562                 lock_basic_unlock(&xfr->lock);
5563                 return 0; /* stop on quit */
5564         }
5565
5566         if(err != NETEVENT_NOERROR) {
5567                 /* connection failed, closed, or timeout */
5568                 /* stop this transfer, cleanup 
5569                  * and continue task_transfer*/
5570                 verbose(VERB_ALGO, "xfr stopped, connection lost to %s",
5571                         xfr->task_transfer->master->host);
5572         failed:
5573                 /* delete transferred data from list */
5574                 auth_chunks_delete(xfr->task_transfer);
5575                 comm_point_delete(xfr->task_transfer->cp);
5576                 xfr->task_transfer->cp = NULL;
5577                 xfr_transfer_nextmaster(xfr);
5578                 xfr_transfer_nexttarget_or_end(xfr, env);
5579                 return 0;
5580         }
5581
5582         /* handle returned packet */
5583         /* if it fails, cleanup and end this transfer */
5584         /* if it needs to fallback from IXFR to AXFR, do that */
5585         if(!check_xfer_packet(c->buffer, xfr, &gonextonfail, &transferdone)) {
5586                 goto failed;
5587         }
5588         /* if it is good, link it into the list of data */
5589         /* if the link into list of data fails (malloc fail) cleanup and end */
5590         if(!xfer_link_data(c->buffer, xfr)) {
5591                 verbose(VERB_ALGO, "xfr stopped to %s, malloc failed",
5592                         xfr->task_transfer->master->host);
5593                 goto failed;
5594         }
5595         /* if the transfer is done now, disconnect and process the list */
5596         if(transferdone) {
5597                 comm_point_delete(xfr->task_transfer->cp);
5598                 xfr->task_transfer->cp = NULL;
5599                 process_list_end_transfer(xfr, env);
5600                 return 0;
5601         }
5602
5603         /* if we want to read more messages, setup the commpoint to read
5604          * a DNS packet, and the timeout */
5605         lock_basic_unlock(&xfr->lock);
5606         c->tcp_is_reading = 1;
5607         sldns_buffer_clear(c->buffer);
5608         comm_point_start_listening(c, -1, AUTH_TRANSFER_TIMEOUT);
5609         return 0;
5610 }
5611
5612 /** callback for task_transfer http connections */
5613 int
5614 auth_xfer_transfer_http_callback(struct comm_point* c, void* arg, int err,
5615         struct comm_reply* repinfo)
5616 {
5617         struct auth_xfer* xfr = (struct auth_xfer*)arg;
5618         struct module_env* env;
5619         log_assert(xfr->task_transfer);
5620         lock_basic_lock(&xfr->lock);
5621         env = xfr->task_transfer->env;
5622         if(env->outnet->want_to_quit) {
5623                 lock_basic_unlock(&xfr->lock);
5624                 return 0; /* stop on quit */
5625         }
5626         verbose(VERB_ALGO, "auth zone transfer http callback");
5627
5628         if(err != NETEVENT_NOERROR && err != NETEVENT_DONE) {
5629                 /* connection failed, closed, or timeout */
5630                 /* stop this transfer, cleanup 
5631                  * and continue task_transfer*/
5632                 verbose(VERB_ALGO, "http stopped, connection lost to %s",
5633                         xfr->task_transfer->master->host);
5634         failed:
5635                 /* delete transferred data from list */
5636                 auth_chunks_delete(xfr->task_transfer);
5637                 if(repinfo) repinfo->c = NULL; /* signal cp deleted to
5638                                 the routine calling this callback */
5639                 comm_point_delete(xfr->task_transfer->cp);
5640                 xfr->task_transfer->cp = NULL;
5641                 xfr_transfer_nextmaster(xfr);
5642                 xfr_transfer_nexttarget_or_end(xfr, env);
5643                 return 0;
5644         }
5645
5646         /* if it is good, link it into the list of data */
5647         /* if the link into list of data fails (malloc fail) cleanup and end */
5648         if(sldns_buffer_limit(c->buffer) > 0) {
5649                 verbose(VERB_ALGO, "auth zone http queued up %d bytes",
5650                         (int)sldns_buffer_limit(c->buffer));
5651                 if(!xfer_link_data(c->buffer, xfr)) {
5652                         verbose(VERB_ALGO, "http stopped to %s, malloc failed",
5653                                 xfr->task_transfer->master->host);
5654                         goto failed;
5655                 }
5656         }
5657         /* if the transfer is done now, disconnect and process the list */
5658         if(err == NETEVENT_DONE) {
5659                 if(repinfo) repinfo->c = NULL; /* signal cp deleted to
5660                                 the routine calling this callback */
5661                 comm_point_delete(xfr->task_transfer->cp);
5662                 xfr->task_transfer->cp = NULL;
5663                 process_list_end_transfer(xfr, env);
5664                 return 0;
5665         }
5666
5667         /* if we want to read more messages, setup the commpoint to read
5668          * a DNS packet, and the timeout */
5669         lock_basic_unlock(&xfr->lock);
5670         c->tcp_is_reading = 1;
5671         sldns_buffer_clear(c->buffer);
5672         comm_point_start_listening(c, -1, AUTH_TRANSFER_TIMEOUT);
5673         return 0;
5674 }
5675
5676
5677 /** start transfer task by this worker , xfr is locked. */
5678 static void
5679 xfr_start_transfer(struct auth_xfer* xfr, struct module_env* env,
5680         struct auth_master* master)
5681 {
5682         log_assert(xfr->task_transfer != NULL);
5683         log_assert(xfr->task_transfer->worker == NULL);
5684         log_assert(xfr->task_transfer->chunks_first == NULL);
5685         log_assert(xfr->task_transfer->chunks_last == NULL);
5686         xfr->task_transfer->worker = env->worker;
5687         xfr->task_transfer->env = env;
5688
5689         /* init transfer process */
5690         /* find that master in the transfer's list of masters? */
5691         xfr_transfer_start_list(xfr, master);
5692         /* start lookup for hostnames in transfer master list */
5693         xfr_transfer_start_lookups(xfr);
5694
5695         /* initiate TCP, and set timeout on it */
5696         xfr_transfer_nexttarget_or_end(xfr, env);
5697 }
5698
5699 /** disown task_probe.  caller must hold xfr.lock */
5700 static void
5701 xfr_probe_disown(struct auth_xfer* xfr)
5702 {
5703         /* remove timer (from this worker's event base) */
5704         comm_timer_delete(xfr->task_probe->timer);
5705         xfr->task_probe->timer = NULL;
5706         /* remove the commpoint */
5707         comm_point_delete(xfr->task_probe->cp);
5708         xfr->task_probe->cp = NULL;
5709         /* we don't own this item anymore */
5710         xfr->task_probe->worker = NULL;
5711         xfr->task_probe->env = NULL;
5712 }
5713
5714 /** send the UDP probe to the master, this is part of task_probe */
5715 static int
5716 xfr_probe_send_probe(struct auth_xfer* xfr, struct module_env* env,
5717         int timeout)
5718 {
5719         struct sockaddr_storage addr;
5720         socklen_t addrlen = 0;
5721         struct timeval t;
5722         /* pick master */
5723         struct auth_master* master = xfr_probe_current_master(xfr);
5724         if(!master) return 0;
5725         if(master->allow_notify) return 0; /* only for notify */
5726         if(master->http) return 0; /* only masters get SOA UDP probe,
5727                 not urls, if those are in this list */
5728
5729         /* get master addr */
5730         if(xfr->task_probe->scan_addr) {
5731                 addrlen = xfr->task_probe->scan_addr->addrlen;
5732                 memmove(&addr, &xfr->task_probe->scan_addr->addr, addrlen);
5733         } else {
5734                 if(!extstrtoaddr(master->host, &addr, &addrlen)) {
5735                         /* the ones that are not in addr format are supposed
5736                          * to be looked up.  The lookup has failed however,
5737                          * so skip them */
5738                         char zname[255+1];
5739                         dname_str(xfr->name, zname);
5740                         log_err("%s: failed lookup, cannot probe to master %s",
5741                                 zname, master->host);
5742                         return 0;
5743                 }
5744         }
5745
5746         /* create packet */
5747         /* create new ID for new probes, but not on timeout retries,
5748          * this means we'll accept replies to previous retries to same ip */
5749         if(timeout == AUTH_PROBE_TIMEOUT)
5750                 xfr->task_probe->id = (uint16_t)(ub_random(env->rnd)&0xffff);
5751         xfr_create_soa_probe_packet(xfr, env->scratch_buffer, 
5752                 xfr->task_probe->id);
5753         if(!xfr->task_probe->cp) {
5754                 xfr->task_probe->cp = outnet_comm_point_for_udp(env->outnet,
5755                         auth_xfer_probe_udp_callback, xfr, &addr, addrlen);
5756                 if(!xfr->task_probe->cp) {
5757                         char zname[255+1];
5758                         dname_str(xfr->name, zname);
5759                         verbose(VERB_ALGO, "cannot create udp cp for "
5760                                 "probe %s to %s", zname, master->host);
5761                         return 0;
5762                 }
5763         }
5764         if(!xfr->task_probe->timer) {
5765                 xfr->task_probe->timer = comm_timer_create(env->worker_base,
5766                         auth_xfer_probe_timer_callback, xfr);
5767                 if(!xfr->task_probe->timer) {
5768                         log_err("malloc failure");
5769                         return 0;
5770                 }
5771         }
5772
5773         /* send udp packet */
5774         if(!comm_point_send_udp_msg(xfr->task_probe->cp, env->scratch_buffer,
5775                 (struct sockaddr*)&addr, addrlen)) {
5776                 char zname[255+1];
5777                 dname_str(xfr->name, zname);
5778                 verbose(VERB_ALGO, "failed to send soa probe for %s to %s",
5779                         zname, master->host);
5780                 return 0;
5781         }
5782         xfr->task_probe->timeout = timeout;
5783 #ifndef S_SPLINT_S
5784         t.tv_sec = timeout/1000;
5785         t.tv_usec = (timeout%1000)*1000;
5786 #endif
5787         comm_timer_set(xfr->task_probe->timer, &t);
5788
5789         return 1;
5790 }
5791
5792 /** callback for task_probe timer */
5793 void
5794 auth_xfer_probe_timer_callback(void* arg)
5795 {
5796         struct auth_xfer* xfr = (struct auth_xfer*)arg;
5797         struct module_env* env;
5798         log_assert(xfr->task_probe);
5799         lock_basic_lock(&xfr->lock);
5800         env = xfr->task_probe->env;
5801         if(env->outnet->want_to_quit) {
5802                 lock_basic_unlock(&xfr->lock);
5803                 return; /* stop on quit */
5804         }
5805
5806         if(xfr->task_probe->timeout <= AUTH_PROBE_TIMEOUT_STOP) {
5807                 /* try again with bigger timeout */
5808                 if(xfr_probe_send_probe(xfr, env, xfr->task_probe->timeout*2)) {
5809                         lock_basic_unlock(&xfr->lock);
5810                         return;
5811                 }
5812         }
5813         /* delete commpoint so a new one is created, with a fresh port nr */
5814         comm_point_delete(xfr->task_probe->cp);
5815         xfr->task_probe->cp = NULL;
5816
5817         /* too many timeouts (or fail to send), move to next or end */
5818         xfr_probe_nextmaster(xfr);
5819         xfr_probe_send_or_end(xfr, env);
5820 }
5821
5822 /** callback for task_probe udp packets */
5823 int
5824 auth_xfer_probe_udp_callback(struct comm_point* c, void* arg, int err,
5825         struct comm_reply* repinfo)
5826 {
5827         struct auth_xfer* xfr = (struct auth_xfer*)arg;
5828         struct module_env* env;
5829         log_assert(xfr->task_probe);
5830         lock_basic_lock(&xfr->lock);
5831         env = xfr->task_probe->env;
5832         if(env->outnet->want_to_quit) {
5833                 lock_basic_unlock(&xfr->lock);
5834                 return 0; /* stop on quit */
5835         }
5836
5837         /* the comm_point_udp_callback is in a for loop for NUM_UDP_PER_SELECT
5838          * and we set rep.c=NULL to stop if from looking inside the commpoint*/
5839         repinfo->c = NULL;
5840         /* stop the timer */
5841         comm_timer_disable(xfr->task_probe->timer);
5842
5843         /* see if we got a packet and what that means */
5844         if(err == NETEVENT_NOERROR) {
5845                 uint32_t serial = 0;
5846                 if(check_packet_ok(c->buffer, LDNS_RR_TYPE_SOA, xfr,
5847                         &serial)) {
5848                         /* successful lookup */
5849                         if(verbosity >= VERB_ALGO) {
5850                                 char buf[256];
5851                                 dname_str(xfr->name, buf);
5852                                 verbose(VERB_ALGO, "auth zone %s: soa probe "
5853                                         "serial is %u", buf, (unsigned)serial);
5854                         }
5855                         /* see if this serial indicates that the zone has
5856                          * to be updated */
5857                         if(xfr_serial_means_update(xfr, serial)) {
5858                                 /* if updated, start the transfer task, if needed */
5859                                 verbose(VERB_ALGO, "auth_zone updated, start transfer");
5860                                 if(xfr->task_transfer->worker == NULL) {
5861                                         struct auth_master* master =
5862                                                 xfr_probe_current_master(xfr);
5863                                         /* if we have download URLs use them
5864                                          * in preference to this master we
5865                                          * just probed the SOA from */
5866                                         if(xfr->task_transfer->masters &&
5867                                                 xfr->task_transfer->masters->http)
5868                                                 master = NULL;
5869                                         xfr_probe_disown(xfr);
5870                                         xfr_start_transfer(xfr, env, master);
5871                                         return 0;
5872
5873                                 }
5874                         } else {
5875                                 /* if zone not updated, start the wait timer again */
5876                                 verbose(VERB_ALGO, "auth_zone unchanged, new lease, wait");
5877                                 if(xfr->have_zone)
5878                                         xfr->lease_time = *env->now;
5879                                 if(xfr->task_nextprobe->worker == NULL)
5880                                         xfr_set_timeout(xfr, env, 0, 0);
5881                         }
5882                         /* other tasks are running, we don't do this anymore */
5883                         xfr_probe_disown(xfr);
5884                         lock_basic_unlock(&xfr->lock);
5885                         /* return, we don't sent a reply to this udp packet,
5886                          * and we setup the tasks to do next */
5887                         return 0;
5888                 }
5889         }
5890         if(verbosity >= VERB_ALGO) {
5891                 char buf[256];
5892                 dname_str(xfr->name, buf);
5893                 verbose(VERB_ALGO, "auth zone %s: soa probe failed", buf);
5894         }
5895         
5896         /* failed lookup */
5897         /* delete commpoint so a new one is created, with a fresh port nr */
5898         comm_point_delete(xfr->task_probe->cp);
5899         xfr->task_probe->cp = NULL;
5900
5901         /* if the result was not a successfull probe, we need
5902          * to send the next one */
5903         xfr_probe_nextmaster(xfr);
5904         xfr_probe_send_or_end(xfr, env);
5905         return 0;
5906 }
5907
5908 /** lookup a host name for its addresses, if needed */
5909 static int
5910 xfr_probe_lookup_host(struct auth_xfer* xfr, struct module_env* env)
5911 {
5912         struct sockaddr_storage addr;
5913         socklen_t addrlen = 0;
5914         struct auth_master* master = xfr->task_probe->lookup_target;
5915         struct query_info qinfo;
5916         uint16_t qflags = BIT_RD;
5917         uint8_t dname[LDNS_MAX_DOMAINLEN+1];
5918         struct edns_data edns;
5919         sldns_buffer* buf = env->scratch_buffer;
5920         if(!master) return 0;
5921         if(extstrtoaddr(master->host, &addr, &addrlen)) {
5922                 /* not needed, host is in IP addr format */
5923                 return 0;
5924         }
5925         if(master->allow_notify && !master->http &&
5926                 strchr(master->host, '/') != NULL &&
5927                 strchr(master->host, '/') == strrchr(master->host, '/')) {
5928                 return 0; /* is IP/prefix format, not something to look up */
5929         }
5930
5931         /* use mesh_new_callback to probe for non-addr hosts,
5932          * and then wait for them to be looked up (in cache, or query) */
5933         qinfo.qname_len = sizeof(dname);
5934         if(sldns_str2wire_dname_buf(master->host, dname, &qinfo.qname_len)
5935                 != 0) {
5936                 log_err("cannot parse host name of master %s", master->host);
5937                 return 0;
5938         }
5939         qinfo.qname = dname;
5940         qinfo.qclass = xfr->dclass;
5941         qinfo.qtype = LDNS_RR_TYPE_A;
5942         if(xfr->task_probe->lookup_aaaa)
5943                 qinfo.qtype = LDNS_RR_TYPE_AAAA;
5944         qinfo.local_alias = NULL;
5945         if(verbosity >= VERB_ALGO) {
5946                 char buf[512];
5947                 char buf2[LDNS_MAX_DOMAINLEN+1];
5948                 dname_str(xfr->name, buf2);
5949                 snprintf(buf, sizeof(buf), "auth zone %s: master lookup"
5950                         " for task_probe", buf2);
5951                 log_query_info(VERB_ALGO, buf, &qinfo);
5952         }
5953         edns.edns_present = 1;
5954         edns.ext_rcode = 0;
5955         edns.edns_version = 0;
5956         edns.bits = EDNS_DO;
5957         edns.opt_list = NULL;
5958         if(sldns_buffer_capacity(buf) < 65535)
5959                 edns.udp_size = (uint16_t)sldns_buffer_capacity(buf);
5960         else    edns.udp_size = 65535;
5961
5962         /* unlock xfr during mesh_new_callback() because the callback can be
5963          * called straight away */
5964         lock_basic_unlock(&xfr->lock);
5965         if(!mesh_new_callback(env->mesh, &qinfo, qflags, &edns, buf, 0,
5966                 &auth_xfer_probe_lookup_callback, xfr)) {
5967                 lock_basic_lock(&xfr->lock);
5968                 log_err("out of memory lookup up master %s", master->host);
5969                 return 0;
5970         }
5971         lock_basic_lock(&xfr->lock);
5972         return 1;
5973 }
5974
5975 /** move to sending the probe packets, next if fails. task_probe */
5976 static void
5977 xfr_probe_send_or_end(struct auth_xfer* xfr, struct module_env* env)
5978 {
5979         /* are we doing hostname lookups? */
5980         while(xfr->task_probe->lookup_target) {
5981                 if(xfr_probe_lookup_host(xfr, env)) {
5982                         /* wait for lookup to finish,
5983                          * note that the hostname may be in unbound's cache
5984                          * and we may then get an instant cache response,
5985                          * and that calls the callback just like a full
5986                          * lookup and lookup failures also call callback */
5987                         lock_basic_unlock(&xfr->lock);
5988                         return;
5989                 }
5990                 xfr_probe_move_to_next_lookup(xfr, env);
5991         }
5992         /* probe of list has ended.  Create or refresh the list of of
5993          * allow_notify addrs */
5994         probe_copy_masters_for_allow_notify(xfr);
5995         if(xfr->task_probe->only_lookup) {
5996                 /* only wanted lookups for copy, stop probe and start wait */
5997                 xfr->task_probe->only_lookup = 0;
5998                 xfr_probe_disown(xfr);
5999                 xfr_set_timeout(xfr, env, 0, 0);
6000                 lock_basic_unlock(&xfr->lock);
6001                 return;
6002         }
6003
6004         /* send probe packets */
6005         while(!xfr_probe_end_of_list(xfr)) {
6006                 if(xfr_probe_send_probe(xfr, env, AUTH_PROBE_TIMEOUT)) {
6007                         /* successfully sent probe, wait for callback */
6008                         lock_basic_unlock(&xfr->lock);
6009                         return;
6010                 }
6011                 /* failed to send probe, next master */
6012                 xfr_probe_nextmaster(xfr);
6013         }
6014
6015         /* we failed to send this as well, move to the wait task,
6016          * use the shorter retry timeout */
6017         xfr_probe_disown(xfr);
6018
6019         /* pick up the nextprobe task and wait */
6020         xfr_set_timeout(xfr, env, 1, 0);
6021         lock_basic_unlock(&xfr->lock);
6022 }
6023
6024 /** callback for task_probe lookup of host name, of A or AAAA */
6025 void auth_xfer_probe_lookup_callback(void* arg, int rcode, sldns_buffer* buf,
6026         enum sec_status ATTR_UNUSED(sec), char* ATTR_UNUSED(why_bogus))
6027 {
6028         struct auth_xfer* xfr = (struct auth_xfer*)arg;
6029         struct module_env* env;
6030         log_assert(xfr->task_probe);
6031         lock_basic_lock(&xfr->lock);
6032         env = xfr->task_probe->env;
6033         if(env->outnet->want_to_quit) {
6034                 lock_basic_unlock(&xfr->lock);
6035                 return; /* stop on quit */
6036         }
6037
6038         /* process result */
6039         if(rcode == LDNS_RCODE_NOERROR) {
6040                 uint16_t wanted_qtype = LDNS_RR_TYPE_A;
6041                 struct regional* temp = env->scratch;
6042                 struct query_info rq;
6043                 struct reply_info* rep;
6044                 if(xfr->task_probe->lookup_aaaa)
6045                         wanted_qtype = LDNS_RR_TYPE_AAAA;
6046                 memset(&rq, 0, sizeof(rq));
6047                 rep = parse_reply_in_temp_region(buf, temp, &rq);
6048                 if(rep && rq.qtype == wanted_qtype &&
6049                         FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NOERROR) {
6050                         /* parsed successfully */
6051                         struct ub_packed_rrset_key* answer =
6052                                 reply_find_answer_rrset(&rq, rep);
6053                         if(answer) {
6054                                 xfr_master_add_addrs(xfr->task_probe->
6055                                         lookup_target, answer, wanted_qtype);
6056                         }
6057                 }
6058         }
6059         if(xfr->task_probe->lookup_target->list &&
6060                 xfr->task_probe->lookup_target == xfr_probe_current_master(xfr))
6061                 xfr->task_probe->scan_addr = xfr->task_probe->lookup_target->list;
6062
6063         /* move to lookup AAAA after A lookup, move to next hostname lookup,
6064          * or move to send the probes, or, if nothing to do, end task_probe */
6065         xfr_probe_move_to_next_lookup(xfr, env);
6066         xfr_probe_send_or_end(xfr, env);
6067 }
6068
6069 /** disown task_nextprobe.  caller must hold xfr.lock */
6070 static void
6071 xfr_nextprobe_disown(struct auth_xfer* xfr)
6072 {
6073         /* delete the timer, because the next worker to pick this up may
6074          * not have the same event base */
6075         comm_timer_delete(xfr->task_nextprobe->timer);
6076         xfr->task_nextprobe->timer = NULL;
6077         xfr->task_nextprobe->next_probe = 0;
6078         /* we don't own this item anymore */
6079         xfr->task_nextprobe->worker = NULL;
6080         xfr->task_nextprobe->env = NULL;
6081 }
6082
6083 /** xfer nextprobe timeout callback, this is part of task_nextprobe */
6084 void
6085 auth_xfer_timer(void* arg)
6086 {
6087         struct auth_xfer* xfr = (struct auth_xfer*)arg;
6088         struct module_env* env;
6089         log_assert(xfr->task_nextprobe);
6090         lock_basic_lock(&xfr->lock);
6091         env = xfr->task_nextprobe->env;
6092         if(env->outnet->want_to_quit) {
6093                 lock_basic_unlock(&xfr->lock);
6094                 return; /* stop on quit */
6095         }
6096
6097         /* see if zone has expired, and if so, also set auth_zone expired */
6098         if(xfr->have_zone && !xfr->zone_expired &&
6099            *env->now >= xfr->lease_time + xfr->expiry) {
6100                 lock_basic_unlock(&xfr->lock);
6101                 auth_xfer_set_expired(xfr, env, 1);
6102                 lock_basic_lock(&xfr->lock);
6103         }
6104
6105         xfr_nextprobe_disown(xfr);
6106
6107         if(!xfr_start_probe(xfr, env, NULL)) {
6108                 /* not started because already in progress */
6109                 lock_basic_unlock(&xfr->lock);
6110         }
6111 }
6112
6113 /** return true if there are probe (SOA UDP query) targets in the master list*/
6114 static int
6115 have_probe_targets(struct auth_master* list)
6116 {
6117         struct auth_master* p;
6118         for(p=list; p; p = p->next) {
6119                 if(!p->allow_notify && p->host)
6120                         return 1;
6121         }
6122         return 0;
6123 }
6124
6125 /** start task_probe if possible, if no masters for probe start task_transfer
6126  * returns true if task has been started, and false if the task is already
6127  * in progress. */
6128 static int
6129 xfr_start_probe(struct auth_xfer* xfr, struct module_env* env,
6130         struct auth_master* spec)
6131 {
6132         /* see if we need to start a probe (or maybe it is already in
6133          * progress (due to notify)) */
6134         if(xfr->task_probe->worker == NULL) {
6135                 if(!have_probe_targets(xfr->task_probe->masters) &&
6136                         !(xfr->task_probe->only_lookup &&
6137                         xfr->task_probe->masters != NULL)) {
6138                         /* useless to pick up task_probe, no masters to
6139                          * probe. Instead attempt to pick up task transfer */
6140                         if(xfr->task_transfer->worker == NULL) {
6141                                 xfr_start_transfer(xfr, env, spec);
6142                                 return 1;
6143                         }
6144                         /* task transfer already in progress */
6145                         return 0;
6146                 }
6147
6148                 /* pick up the probe task ourselves */
6149                 xfr->task_probe->worker = env->worker;
6150                 xfr->task_probe->env = env;
6151                 xfr->task_probe->cp = NULL;
6152
6153                 /* start the task */
6154                 /* if this was a timeout, no specific first master to scan */
6155                 /* otherwise, spec is nonNULL the notified master, scan
6156                  * first and also transfer first from it */
6157                 xfr_probe_start_list(xfr, spec);
6158                 /* setup to start the lookup of hostnames of masters afresh */
6159                 xfr_probe_start_lookups(xfr);
6160                 /* send the probe packet or next send, or end task */
6161                 xfr_probe_send_or_end(xfr, env);
6162                 return 1;
6163         }
6164         return 0;
6165 }
6166
6167 /** for task_nextprobe.
6168  * determine next timeout for auth_xfer. Also (re)sets timer.
6169  * @param xfr: task structure
6170  * @param env: module environment, with worker and time.
6171  * @param failure: set true if timer should be set for failure retry.
6172  * @param lookup_only: only perform lookups when timer done, 0 sec timeout
6173  */
6174 static void
6175 xfr_set_timeout(struct auth_xfer* xfr, struct module_env* env,
6176         int failure, int lookup_only)
6177 {
6178         struct timeval tv;
6179         log_assert(xfr->task_nextprobe != NULL);
6180         log_assert(xfr->task_nextprobe->worker == NULL ||
6181                 xfr->task_nextprobe->worker == env->worker);
6182         /* normally, nextprobe = startoflease + refresh,
6183          * but if expiry is sooner, use that one.
6184          * after a failure, use the retry timer instead. */
6185         xfr->task_nextprobe->next_probe = *env->now;
6186         if(xfr->lease_time && !failure)
6187                 xfr->task_nextprobe->next_probe = xfr->lease_time;
6188         
6189         if(!failure) {
6190                 xfr->task_nextprobe->backoff = 0;
6191         } else {
6192                 if(xfr->task_nextprobe->backoff == 0)
6193                                 xfr->task_nextprobe->backoff = 3;
6194                 else    xfr->task_nextprobe->backoff *= 2;
6195                 if(xfr->task_nextprobe->backoff > AUTH_TRANSFER_MAX_BACKOFF)
6196                         xfr->task_nextprobe->backoff =
6197                                 AUTH_TRANSFER_MAX_BACKOFF;
6198         }
6199
6200         if(xfr->have_zone) {
6201                 time_t wait = xfr->refresh;
6202                 if(failure) wait = xfr->retry;
6203                 if(xfr->expiry < wait)
6204                         xfr->task_nextprobe->next_probe += xfr->expiry;
6205                 else    xfr->task_nextprobe->next_probe += wait;
6206                 if(failure)
6207                         xfr->task_nextprobe->next_probe +=
6208                                 xfr->task_nextprobe->backoff;
6209                 /* put the timer exactly on expiry, if possible */
6210                 if(xfr->lease_time && xfr->lease_time+xfr->expiry <
6211                         xfr->task_nextprobe->next_probe &&
6212                         xfr->lease_time+xfr->expiry > *env->now)
6213                         xfr->task_nextprobe->next_probe =
6214                                 xfr->lease_time+xfr->expiry;
6215         } else {
6216                 xfr->task_nextprobe->next_probe +=
6217                         xfr->task_nextprobe->backoff;
6218         }
6219
6220         if(!xfr->task_nextprobe->timer) {
6221                 xfr->task_nextprobe->timer = comm_timer_create(
6222                         env->worker_base, auth_xfer_timer, xfr);
6223                 if(!xfr->task_nextprobe->timer) {
6224                         /* failed to malloc memory. likely zone transfer
6225                          * also fails for that. skip the timeout */
6226                         char zname[255+1];
6227                         dname_str(xfr->name, zname);
6228                         log_err("cannot allocate timer, no refresh for %s",
6229                                 zname);
6230                         return;
6231                 }
6232         }
6233         xfr->task_nextprobe->worker = env->worker;
6234         xfr->task_nextprobe->env = env;
6235         if(*(xfr->task_nextprobe->env->now) <= xfr->task_nextprobe->next_probe)
6236                 tv.tv_sec = xfr->task_nextprobe->next_probe - 
6237                         *(xfr->task_nextprobe->env->now);
6238         else    tv.tv_sec = 0;
6239         if(tv.tv_sec != 0 && lookup_only && xfr->task_probe->masters) {
6240                 /* don't lookup_only, if lookup timeout is 0 anyway,
6241                  * or if we don't have masters to lookup */
6242                 tv.tv_sec = 0;
6243                 if(xfr->task_probe && xfr->task_probe->worker == NULL)
6244                         xfr->task_probe->only_lookup = 1;
6245         }
6246         if(verbosity >= VERB_ALGO) {
6247                 char zname[255+1];
6248                 dname_str(xfr->name, zname);
6249                 verbose(VERB_ALGO, "auth zone %s timeout in %d seconds",
6250                         zname, (int)tv.tv_sec);
6251         }
6252         tv.tv_usec = 0;
6253         comm_timer_set(xfr->task_nextprobe->timer, &tv);
6254 }
6255
6256 /** initial pick up of worker timeouts, ties events to worker event loop */
6257 void
6258 auth_xfer_pickup_initial(struct auth_zones* az, struct module_env* env)
6259 {
6260         struct auth_xfer* x;
6261         lock_rw_wrlock(&az->lock);
6262         RBTREE_FOR(x, struct auth_xfer*, &az->xtree) {
6263                 lock_basic_lock(&x->lock);
6264                 /* set lease_time, because we now have timestamp in env,
6265                  * (not earlier during startup and apply_cfg), and this
6266                  * notes the start time when the data was acquired */
6267                 if(x->have_zone)
6268                         x->lease_time = *env->now;
6269                 if(x->task_nextprobe && x->task_nextprobe->worker == NULL) {
6270                         xfr_set_timeout(x, env, 0, 1);
6271                 }
6272                 lock_basic_unlock(&x->lock);
6273         }
6274         lock_rw_unlock(&az->lock);
6275 }
6276
6277 void auth_zones_cleanup(struct auth_zones* az)
6278 {
6279         struct auth_xfer* x;
6280         lock_rw_wrlock(&az->lock);
6281         RBTREE_FOR(x, struct auth_xfer*, &az->xtree) {
6282                 lock_basic_lock(&x->lock);
6283                 if(x->task_nextprobe && x->task_nextprobe->worker != NULL) {
6284                         xfr_nextprobe_disown(x);
6285                 }
6286                 if(x->task_probe && x->task_probe->worker != NULL) {
6287                         xfr_probe_disown(x);
6288                 }
6289                 if(x->task_transfer && x->task_transfer->worker != NULL) {
6290                         auth_chunks_delete(x->task_transfer);
6291                         xfr_transfer_disown(x);
6292                 }
6293                 lock_basic_unlock(&x->lock);
6294         }
6295         lock_rw_unlock(&az->lock);
6296 }
6297
6298 /**
6299  * malloc the xfer and tasks
6300  * @param z: auth_zone with name of zone.
6301  */
6302 static struct auth_xfer*
6303 auth_xfer_new(struct auth_zone* z)
6304 {
6305         struct auth_xfer* xfr;
6306         xfr = (struct auth_xfer*)calloc(1, sizeof(*xfr));
6307         if(!xfr) return NULL;
6308         xfr->name = memdup(z->name, z->namelen);
6309         if(!xfr->name) {
6310                 free(xfr);
6311                 return NULL;
6312         }
6313         xfr->node.key = xfr;
6314         xfr->namelen = z->namelen;
6315         xfr->namelabs = z->namelabs;
6316         xfr->dclass = z->dclass;
6317
6318         xfr->task_nextprobe = (struct auth_nextprobe*)calloc(1,
6319                 sizeof(struct auth_nextprobe));
6320         if(!xfr->task_nextprobe) {
6321                 free(xfr->name);
6322                 free(xfr);
6323                 return NULL;
6324         }
6325         xfr->task_probe = (struct auth_probe*)calloc(1,
6326                 sizeof(struct auth_probe));
6327         if(!xfr->task_probe) {
6328                 free(xfr->task_nextprobe);
6329                 free(xfr->name);
6330                 free(xfr);
6331                 return NULL;
6332         }
6333         xfr->task_transfer = (struct auth_transfer*)calloc(1,
6334                 sizeof(struct auth_transfer));
6335         if(!xfr->task_transfer) {
6336                 free(xfr->task_probe);
6337                 free(xfr->task_nextprobe);
6338                 free(xfr->name);
6339                 free(xfr);
6340                 return NULL;
6341         }
6342
6343         lock_basic_init(&xfr->lock);
6344         lock_protect(&xfr->lock, &xfr->name, sizeof(xfr->name));
6345         lock_protect(&xfr->lock, &xfr->namelen, sizeof(xfr->namelen));
6346         lock_protect(&xfr->lock, xfr->name, xfr->namelen);
6347         lock_protect(&xfr->lock, &xfr->namelabs, sizeof(xfr->namelabs));
6348         lock_protect(&xfr->lock, &xfr->dclass, sizeof(xfr->dclass));
6349         lock_protect(&xfr->lock, &xfr->notify_received, sizeof(xfr->notify_received));
6350         lock_protect(&xfr->lock, &xfr->notify_serial, sizeof(xfr->notify_serial));
6351         lock_protect(&xfr->lock, &xfr->zone_expired, sizeof(xfr->zone_expired));
6352         lock_protect(&xfr->lock, &xfr->have_zone, sizeof(xfr->have_zone));
6353         lock_protect(&xfr->lock, &xfr->serial, sizeof(xfr->serial));
6354         lock_protect(&xfr->lock, &xfr->retry, sizeof(xfr->retry));
6355         lock_protect(&xfr->lock, &xfr->refresh, sizeof(xfr->refresh));
6356         lock_protect(&xfr->lock, &xfr->expiry, sizeof(xfr->expiry));
6357         lock_protect(&xfr->lock, &xfr->lease_time, sizeof(xfr->lease_time));
6358         lock_protect(&xfr->lock, &xfr->task_nextprobe->worker,
6359                 sizeof(xfr->task_nextprobe->worker));
6360         lock_protect(&xfr->lock, &xfr->task_probe->worker,
6361                 sizeof(xfr->task_probe->worker));
6362         lock_protect(&xfr->lock, &xfr->task_transfer->worker,
6363                 sizeof(xfr->task_transfer->worker));
6364         lock_basic_lock(&xfr->lock);
6365         return xfr;
6366 }
6367
6368 /** Create auth_xfer structure.
6369  * This populates the have_zone, soa values, and so on times.
6370  * and sets the timeout, if a zone transfer is needed a short timeout is set.
6371  * For that the auth_zone itself must exist (and read in zonefile)
6372  * returns false on alloc failure. */
6373 struct auth_xfer*
6374 auth_xfer_create(struct auth_zones* az, struct auth_zone* z)
6375 {
6376         struct auth_xfer* xfr;
6377
6378         /* malloc it */
6379         xfr = auth_xfer_new(z);
6380         if(!xfr) {
6381                 log_err("malloc failure");
6382                 return NULL;
6383         }
6384         /* insert in tree */
6385         (void)rbtree_insert(&az->xtree, &xfr->node);
6386         return xfr;
6387 }
6388
6389 /** create new auth_master structure */
6390 static struct auth_master*
6391 auth_master_new(struct auth_master*** list)
6392 {
6393         struct auth_master *m;
6394         m = (struct auth_master*)calloc(1, sizeof(*m));
6395         if(!m) {
6396                 log_err("malloc failure");
6397                 return NULL;
6398         }
6399         /* set first pointer to m, or next pointer of previous element to m */
6400         (**list) = m;
6401         /* store m's next pointer as future point to store at */
6402         (*list) = &(m->next);
6403         return m;
6404 }
6405
6406 /** dup_prefix : create string from initial part of other string, malloced */
6407 static char*
6408 dup_prefix(char* str, size_t num)
6409 {
6410         char* result;
6411         size_t len = strlen(str);
6412         if(len < num) num = len; /* not more than strlen */
6413         result = (char*)malloc(num+1);
6414         if(!result) {
6415                 log_err("malloc failure");
6416                 return result;
6417         }
6418         memmove(result, str, num);
6419         result[num] = 0;
6420         return result;
6421 }
6422
6423 /** dup string and print error on error */
6424 static char*
6425 dup_all(char* str)
6426 {
6427         char* result = strdup(str);
6428         if(!result) {
6429                 log_err("malloc failure");
6430                 return NULL;
6431         }
6432         return result;
6433 }
6434
6435 /** find first of two characters */
6436 static char*
6437 str_find_first_of_chars(char* s, char a, char b)
6438 {
6439         char* ra = strchr(s, a);
6440         char* rb = strchr(s, b);
6441         if(!ra) return rb;
6442         if(!rb) return ra;
6443         if(ra < rb) return ra;
6444         return rb;
6445 }
6446
6447 /** parse URL into host and file parts, false on malloc or parse error */
6448 static int
6449 parse_url(char* url, char** host, char** file, int* port, int* ssl)
6450 {
6451         char* p = url;
6452         /* parse http://www.example.com/file.htm
6453          * or http://127.0.0.1   (index.html)
6454          * or https://[::1@1234]/a/b/c/d */
6455         *ssl = 1;
6456         *port = AUTH_HTTPS_PORT;
6457
6458         /* parse http:// or https:// */
6459         if(strncmp(p, "http://", 7) == 0) {
6460                 p += 7;
6461                 *ssl = 0;
6462                 *port = AUTH_HTTP_PORT;
6463         } else if(strncmp(p, "https://", 8) == 0) {
6464                 p += 8;
6465         } else if(strstr(p, "://") && strchr(p, '/') > strstr(p, "://") &&
6466                 strchr(p, ':') >= strstr(p, "://")) {
6467                 char* uri = dup_prefix(p, (size_t)(strstr(p, "://")-p));
6468                 log_err("protocol %s:// not supported (for url %s)",
6469                         uri?uri:"", p);
6470                 free(uri);
6471                 return 0;
6472         }
6473
6474         /* parse hostname part */
6475         if(p[0] == '[') {
6476                 char* end = strchr(p, ']');
6477                 p++; /* skip over [ */
6478                 if(end) {
6479                         *host = dup_prefix(p, (size_t)(end-p));
6480                         if(!*host) return 0;
6481                         p = end+1; /* skip over ] */
6482                 } else {
6483                         *host = dup_all(p);
6484                         if(!*host) return 0;
6485                         p = end;
6486                 }
6487         } else {
6488                 char* end = str_find_first_of_chars(p, ':', '/');
6489                 if(end) {
6490                         *host = dup_prefix(p, (size_t)(end-p));
6491                         if(!*host) return 0;
6492                 } else {
6493                         *host = dup_all(p);
6494                         if(!*host) return 0;
6495                 }
6496                 p = end; /* at next : or / or NULL */
6497         }
6498
6499         /* parse port number */
6500         if(p && p[0] == ':') {
6501                 char* end = NULL;
6502                 *port = strtol(p+1, &end, 10);
6503                 p = end;
6504         }
6505
6506         /* parse filename part */
6507         while(p && *p == '/')
6508                 p++;
6509         if(!p || p[0] == 0)
6510                 *file = strdup("index.html");
6511         else    *file = strdup(p);
6512         if(!*file) {
6513                 log_err("malloc failure");
6514                 return 0;
6515         }
6516         return 1;
6517 }
6518
6519 int
6520 xfer_set_masters(struct auth_master** list, struct config_auth* c,
6521         int with_http)
6522 {
6523         struct auth_master* m;
6524         struct config_strlist* p;
6525         /* list points to the first, or next pointer for the new element */
6526         while(*list) {
6527                 list = &( (*list)->next );
6528         }
6529         if(with_http)
6530           for(p = c->urls; p; p = p->next) {
6531                 m = auth_master_new(&list);
6532                 m->http = 1;
6533                 if(!parse_url(p->str, &m->host, &m->file, &m->port, &m->ssl))
6534                         return 0;
6535         }
6536         for(p = c->masters; p; p = p->next) {
6537                 m = auth_master_new(&list);
6538                 m->ixfr = 1; /* this flag is not configurable */
6539                 m->host = strdup(p->str);
6540                 if(!m->host) {
6541                         log_err("malloc failure");
6542                         return 0;
6543                 }
6544         }
6545         for(p = c->allow_notify; p; p = p->next) {
6546                 m = auth_master_new(&list);
6547                 m->allow_notify = 1;
6548                 m->host = strdup(p->str);
6549                 if(!m->host) {
6550                         log_err("malloc failure");
6551                         return 0;
6552                 }
6553         }
6554         return 1;
6555 }
6556
6557 #define SERIAL_BITS     32
6558 int
6559 compare_serial(uint32_t a, uint32_t b)
6560 {
6561         const uint32_t cutoff = ((uint32_t) 1 << (SERIAL_BITS - 1));
6562
6563         if (a == b) {
6564                 return 0;
6565         } else if ((a < b && b - a < cutoff) || (a > b && a - b > cutoff)) {
6566                 return -1;
6567         } else {
6568                 return 1;
6569         }
6570 }