Coverage Report

Created: 2026-04-12 06:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/unbound/services/authzone.c
Line
Count
Source
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_nsec.h"
71
#include "validator/val_secalgo.h"
72
#include "validator/val_sigcrypt.h"
73
#include "validator/val_anchor.h"
74
#include "validator/val_utils.h"
75
#include <ctype.h>
76
77
/** bytes to use for NSEC3 hash buffer. 20 for sha1 */
78
#define N3HASHBUFLEN 32
79
/** max number of CNAMEs we are willing to follow (in one answer) */
80
0
#define MAX_CNAME_CHAIN 8
81
/** timeout for probe packets for SOA */
82
0
#define AUTH_PROBE_TIMEOUT 100 /* msec */
83
/** when to stop with SOA probes (when exponential timeouts exceed this) */
84
0
#define AUTH_PROBE_TIMEOUT_STOP 1000 /* msec */
85
/* auth transfer timeout for TCP connections, in msec */
86
0
#define AUTH_TRANSFER_TIMEOUT 10000 /* msec */
87
/* auth transfer max backoff for failed transfers and probes */
88
0
#define AUTH_TRANSFER_MAX_BACKOFF 86400 /* sec */
89
/* auth http port number */
90
0
#define AUTH_HTTP_PORT 80
91
/* auth https port number */
92
0
#define AUTH_HTTPS_PORT 443
93
/* max depth for nested $INCLUDEs */
94
0
#define MAX_INCLUDE_DEPTH 10
95
/** number of timeouts before we fallback from IXFR to AXFR,
96
 * because some versions of servers (eg. dnsmasq) drop IXFR packets. */
97
0
#define NUM_TIMEOUTS_FALLBACK_IXFR 3
98
99
/** pick up nextprobe task to start waiting to perform transfer actions */
100
static void xfr_set_timeout(struct auth_xfer* xfr, struct module_env* env,
101
  int failure, int lookup_only);
102
/** move to sending the probe packets, next if fails. task_probe */
103
static void xfr_probe_send_or_end(struct auth_xfer* xfr,
104
  struct module_env* env);
105
/** pick up probe task with specified(or NULL) destination first,
106
 * or transfer task if nothing to probe, or false if already in progress */
107
static int xfr_start_probe(struct auth_xfer* xfr, struct module_env* env,
108
  struct auth_master* spec);
109
/** delete xfer structure (not its tree entry) */
110
void auth_xfer_delete(struct auth_xfer* xfr);
111
112
/** create new dns_msg */
113
static struct dns_msg*
114
msg_create(struct regional* region, struct query_info* qinfo)
115
0
{
116
0
  struct dns_msg* msg = (struct dns_msg*)regional_alloc(region,
117
0
    sizeof(struct dns_msg));
118
0
  if(!msg)
119
0
    return NULL;
120
0
  msg->qinfo.qname = regional_alloc_init(region, qinfo->qname,
121
0
    qinfo->qname_len);
122
0
  if(!msg->qinfo.qname)
123
0
    return NULL;
124
0
  msg->qinfo.qname_len = qinfo->qname_len;
125
0
  msg->qinfo.qtype = qinfo->qtype;
126
0
  msg->qinfo.qclass = qinfo->qclass;
127
0
  msg->qinfo.local_alias = NULL;
128
  /* non-packed reply_info, because it needs to grow the array */
129
0
  msg->rep = (struct reply_info*)regional_alloc_zero(region,
130
0
    sizeof(struct reply_info)-sizeof(struct rrset_ref));
131
0
  if(!msg->rep)
132
0
    return NULL;
133
0
  msg->rep->flags = (uint16_t)(BIT_QR | BIT_AA);
134
0
  msg->rep->authoritative = 1;
135
0
  msg->rep->reason_bogus = LDNS_EDE_NONE;
136
0
  msg->rep->qdcount = 1;
137
  /* rrsets is NULL, no rrsets yet */
138
0
  return msg;
139
0
}
140
141
/** grow rrset array by one in msg */
142
static int
143
msg_grow_array(struct regional* region, struct dns_msg* msg)
144
0
{
145
0
  if(msg->rep->rrsets == NULL) {
146
0
    msg->rep->rrsets = regional_alloc_zero(region,
147
0
      sizeof(struct ub_packed_rrset_key*)*(msg->rep->rrset_count+1));
148
0
    if(!msg->rep->rrsets)
149
0
      return 0;
150
0
  } else {
151
0
    struct ub_packed_rrset_key** rrsets_old = msg->rep->rrsets;
152
0
    msg->rep->rrsets = regional_alloc_zero(region,
153
0
      sizeof(struct ub_packed_rrset_key*)*(msg->rep->rrset_count+1));
154
0
    if(!msg->rep->rrsets)
155
0
      return 0;
156
0
    memmove(msg->rep->rrsets, rrsets_old,
157
0
      sizeof(struct ub_packed_rrset_key*)*msg->rep->rrset_count);
158
0
  }
159
0
  return 1;
160
0
}
161
162
/** get ttl of rrset */
163
static time_t
164
get_rrset_ttl(struct ub_packed_rrset_key* k)
165
0
{
166
0
  struct packed_rrset_data* d = (struct packed_rrset_data*)
167
0
    k->entry.data;
168
0
  return d->ttl;
169
0
}
170
171
/** Copy rrset into region from domain-datanode and packet rrset */
172
static struct ub_packed_rrset_key*
173
auth_packed_rrset_copy_region(struct auth_zone* z, struct auth_data* node,
174
  struct auth_rrset* rrset, struct regional* region)
175
0
{
176
0
  struct ub_packed_rrset_key key;
177
0
  memset(&key, 0, sizeof(key));
178
0
  key.entry.key = &key;
179
0
  key.entry.data = rrset->data;
180
0
  key.rk.dname = node->name;
181
0
  key.rk.dname_len = node->namelen;
182
0
  key.rk.type = htons(rrset->type);
183
0
  key.rk.rrset_class = htons(z->dclass);
184
0
  key.entry.hash = rrset_key_hash(&key.rk);
185
0
  return packed_rrset_copy_region(&key, region, 0);
186
0
}
187
188
/** fix up msg->rep TTL and prefetch ttl */
189
static void
190
msg_ttl(struct dns_msg* msg)
191
0
{
192
0
  if(msg->rep->rrset_count == 0) return;
193
0
  if(msg->rep->rrset_count == 1) {
194
0
    msg->rep->ttl = get_rrset_ttl(msg->rep->rrsets[0]);
195
0
    msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
196
0
    msg->rep->serve_expired_ttl = msg->rep->ttl + SERVE_EXPIRED_TTL;
197
0
  } else if(get_rrset_ttl(msg->rep->rrsets[msg->rep->rrset_count-1]) <
198
0
    msg->rep->ttl) {
199
0
    msg->rep->ttl = get_rrset_ttl(msg->rep->rrsets[
200
0
      msg->rep->rrset_count-1]);
201
0
    msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
202
0
    msg->rep->serve_expired_ttl = msg->rep->ttl + SERVE_EXPIRED_TTL;
203
0
  }
204
0
}
205
206
/** see if rrset is a duplicate in the answer message */
207
static int
208
msg_rrset_duplicate(struct dns_msg* msg, uint8_t* nm, size_t nmlen,
209
  uint16_t type, uint16_t dclass)
210
0
{
211
0
  size_t i;
212
0
  for(i=0; i<msg->rep->rrset_count; i++) {
213
0
    struct ub_packed_rrset_key* k = msg->rep->rrsets[i];
214
0
    if(ntohs(k->rk.type) == type && k->rk.dname_len == nmlen &&
215
0
      ntohs(k->rk.rrset_class) == dclass &&
216
0
      query_dname_compare(k->rk.dname, nm) == 0)
217
0
      return 1;
218
0
  }
219
0
  return 0;
220
0
}
221
222
/** add rrset to answer section (no auth, add rrsets yet) */
223
static int
224
msg_add_rrset_an(struct auth_zone* z, struct regional* region,
225
  struct dns_msg* msg, struct auth_data* node, struct auth_rrset* rrset)
226
0
{
227
0
  log_assert(msg->rep->ns_numrrsets == 0);
228
0
  log_assert(msg->rep->ar_numrrsets == 0);
229
0
  if(!rrset || !node)
230
0
    return 1;
231
0
  if(msg_rrset_duplicate(msg, node->name, node->namelen, rrset->type,
232
0
    z->dclass))
233
0
    return 1;
234
  /* grow array */
235
0
  if(!msg_grow_array(region, msg))
236
0
    return 0;
237
  /* copy it */
238
0
  if(!(msg->rep->rrsets[msg->rep->rrset_count] =
239
0
    auth_packed_rrset_copy_region(z, node, rrset, region)))
240
0
    return 0;
241
0
  msg->rep->rrset_count++;
242
0
  msg->rep->an_numrrsets++;
243
0
  msg_ttl(msg);
244
0
  return 1;
245
0
}
246
247
/** add rrset to authority section (no additional section rrsets yet) */
248
static int
249
msg_add_rrset_ns(struct auth_zone* z, struct regional* region,
250
  struct dns_msg* msg, struct auth_data* node, struct auth_rrset* rrset)
251
0
{
252
0
  log_assert(msg->rep->ar_numrrsets == 0);
253
0
  if(!rrset || !node)
254
0
    return 1;
255
0
  if(msg_rrset_duplicate(msg, node->name, node->namelen, rrset->type,
256
0
    z->dclass))
257
0
    return 1;
258
  /* grow array */
259
0
  if(!msg_grow_array(region, msg))
260
0
    return 0;
261
  /* copy it */
262
0
  if(!(msg->rep->rrsets[msg->rep->rrset_count] =
263
0
    auth_packed_rrset_copy_region(z, node, rrset, region)))
264
0
    return 0;
265
0
  msg->rep->rrset_count++;
266
0
  msg->rep->ns_numrrsets++;
267
0
  msg_ttl(msg);
268
0
  return 1;
269
0
}
270
271
/** add rrset to additional section */
272
static int
273
msg_add_rrset_ar(struct auth_zone* z, struct regional* region,
274
  struct dns_msg* msg, struct auth_data* node, struct auth_rrset* rrset)
275
0
{
276
0
  if(!rrset || !node)
277
0
    return 1;
278
0
  if(msg_rrset_duplicate(msg, node->name, node->namelen, rrset->type,
279
0
    z->dclass))
280
0
    return 1;
281
  /* grow array */
282
0
  if(!msg_grow_array(region, msg))
283
0
    return 0;
284
  /* copy it */
285
0
  if(!(msg->rep->rrsets[msg->rep->rrset_count] =
286
0
    auth_packed_rrset_copy_region(z, node, rrset, region)))
287
0
    return 0;
288
0
  msg->rep->rrset_count++;
289
0
  msg->rep->ar_numrrsets++;
290
0
  msg_ttl(msg);
291
0
  return 1;
292
0
}
293
294
struct auth_zones* auth_zones_create(void)
295
0
{
296
0
  struct auth_zones* az = (struct auth_zones*)calloc(1, sizeof(*az));
297
0
  if(!az) {
298
0
    log_err("out of memory");
299
0
    return NULL;
300
0
  }
301
0
  rbtree_init(&az->ztree, &auth_zone_cmp);
302
0
  rbtree_init(&az->xtree, &auth_xfer_cmp);
303
0
  lock_rw_init(&az->lock);
304
0
  lock_protect(&az->lock, &az->ztree, sizeof(az->ztree));
305
0
  lock_protect(&az->lock, &az->xtree, sizeof(az->xtree));
306
  /* also lock protects the rbnode's in struct auth_zone, auth_xfer */
307
0
  lock_rw_init(&az->rpz_lock);
308
0
  lock_protect(&az->rpz_lock, &az->rpz_first, sizeof(az->rpz_first));
309
0
  return az;
310
0
}
311
312
int auth_zone_cmp(const void* z1, const void* z2)
313
0
{
314
  /* first sort on class, so that hierarchy can be maintained within
315
   * a class */
316
0
  struct auth_zone* a = (struct auth_zone*)z1;
317
0
  struct auth_zone* b = (struct auth_zone*)z2;
318
0
  int m;
319
0
  if(a->dclass != b->dclass) {
320
0
    if(a->dclass < b->dclass)
321
0
      return -1;
322
0
    return 1;
323
0
  }
324
  /* sorted such that higher zones sort before lower zones (their
325
   * contents) */
326
0
  return dname_lab_cmp(a->name, a->namelabs, b->name, b->namelabs, &m);
327
0
}
328
329
int auth_data_cmp(const void* z1, const void* z2)
330
0
{
331
0
  struct auth_data* a = (struct auth_data*)z1;
332
0
  struct auth_data* b = (struct auth_data*)z2;
333
0
  int m;
334
  /* canonical sort, because DNSSEC needs that */
335
0
  return dname_canon_lab_cmp(a->name, a->namelabs, b->name,
336
0
    b->namelabs, &m);
337
0
}
338
339
int auth_xfer_cmp(const void* z1, const void* z2)
340
0
{
341
  /* first sort on class, so that hierarchy can be maintained within
342
   * a class */
343
0
  struct auth_xfer* a = (struct auth_xfer*)z1;
344
0
  struct auth_xfer* b = (struct auth_xfer*)z2;
345
0
  int m;
346
0
  if(a->dclass != b->dclass) {
347
0
    if(a->dclass < b->dclass)
348
0
      return -1;
349
0
    return 1;
350
0
  }
351
  /* sorted such that higher zones sort before lower zones (their
352
   * contents) */
353
0
  return dname_lab_cmp(a->name, a->namelabs, b->name, b->namelabs, &m);
354
0
}
355
356
/** delete auth rrset node */
357
static void
358
auth_rrset_delete(struct auth_rrset* rrset)
359
0
{
360
0
  if(!rrset) return;
361
0
  free(rrset->data);
362
0
  free(rrset);
363
0
}
364
365
/** delete auth data domain node */
366
static void
367
auth_data_delete(struct auth_data* n)
368
0
{
369
0
  struct auth_rrset* p, *np;
370
0
  if(!n) return;
371
0
  p = n->rrsets;
372
0
  while(p) {
373
0
    np = p->next;
374
0
    auth_rrset_delete(p);
375
0
    p = np;
376
0
  }
377
0
  free(n->name);
378
0
  free(n);
379
0
}
380
381
/** helper traverse to delete zones */
382
static void
383
auth_data_del(rbnode_type* n, void* ATTR_UNUSED(arg))
384
0
{
385
0
  struct auth_data* z = (struct auth_data*)n->key;
386
0
  auth_data_delete(z);
387
0
}
388
389
/** delete an auth zone structure (tree remove must be done elsewhere) */
390
static void
391
auth_zone_delete(struct auth_zone* z, struct auth_zones* az)
392
0
{
393
0
  if(!z) return;
394
0
  lock_rw_destroy(&z->lock);
395
0
  traverse_postorder(&z->data, auth_data_del, NULL);
396
397
0
  if(az && z->rpz) {
398
    /* keep RPZ linked list intact */
399
0
    lock_rw_wrlock(&az->rpz_lock);
400
0
    if(z->rpz_az_prev)
401
0
      z->rpz_az_prev->rpz_az_next = z->rpz_az_next;
402
0
    else
403
0
      az->rpz_first = z->rpz_az_next;
404
0
    if(z->rpz_az_next)
405
0
      z->rpz_az_next->rpz_az_prev = z->rpz_az_prev;
406
0
    lock_rw_unlock(&az->rpz_lock);
407
0
  }
408
0
  if(z->rpz)
409
0
    rpz_delete(z->rpz);
410
0
  free(z->name);
411
0
  free(z->zonefile);
412
0
  free(z);
413
0
}
414
415
struct auth_zone*
416
auth_zone_create(struct auth_zones* az, uint8_t* nm, size_t nmlen,
417
  uint16_t dclass)
418
0
{
419
0
  struct auth_zone* z = (struct auth_zone*)calloc(1, sizeof(*z));
420
0
  if(!z) {
421
0
    return NULL;
422
0
  }
423
0
  z->node.key = z;
424
0
  z->dclass = dclass;
425
0
  z->namelen = nmlen;
426
0
  z->namelabs = dname_count_labels(nm);
427
0
  z->name = memdup(nm, nmlen);
428
0
  if(!z->name) {
429
0
    free(z);
430
0
    return NULL;
431
0
  }
432
0
  rbtree_init(&z->data, &auth_data_cmp);
433
0
  lock_rw_init(&z->lock);
434
0
  lock_protect(&z->lock, &z->name, sizeof(*z)-sizeof(rbnode_type)-
435
0
      sizeof(&z->rpz_az_next)-sizeof(&z->rpz_az_prev));
436
0
  lock_rw_wrlock(&z->lock);
437
  /* z lock protects all, except rbtree itself and the rpz linked list
438
   * pointers, which are protected using az->lock */
439
0
  if(!rbtree_insert(&az->ztree, &z->node)) {
440
0
    lock_rw_unlock(&z->lock);
441
0
    auth_zone_delete(z, NULL);
442
0
    log_warn("duplicate auth zone");
443
0
    return NULL;
444
0
  }
445
0
  return z;
446
0
}
447
448
struct auth_zone*
449
auth_zone_find(struct auth_zones* az, uint8_t* nm, size_t nmlen,
450
  uint16_t dclass)
451
0
{
452
0
  struct auth_zone key;
453
0
  key.node.key = &key;
454
0
  key.dclass = dclass;
455
0
  key.name = nm;
456
0
  key.namelen = nmlen;
457
0
  key.namelabs = dname_count_labels(nm);
458
0
  return (struct auth_zone*)rbtree_search(&az->ztree, &key);
459
0
}
460
461
struct auth_xfer*
462
auth_xfer_find(struct auth_zones* az, uint8_t* nm, size_t nmlen,
463
  uint16_t dclass)
464
0
{
465
0
  struct auth_xfer key;
466
0
  key.node.key = &key;
467
0
  key.dclass = dclass;
468
0
  key.name = nm;
469
0
  key.namelen = nmlen;
470
0
  key.namelabs = dname_count_labels(nm);
471
0
  return (struct auth_xfer*)rbtree_search(&az->xtree, &key);
472
0
}
473
474
/** find an auth zone or sorted less-or-equal, return true if exact */
475
static int
476
auth_zone_find_less_equal(struct auth_zones* az, uint8_t* nm, size_t nmlen,
477
  uint16_t dclass, struct auth_zone** z)
478
0
{
479
0
  struct auth_zone key;
480
0
  key.node.key = &key;
481
0
  key.dclass = dclass;
482
0
  key.name = nm;
483
0
  key.namelen = nmlen;
484
0
  key.namelabs = dname_count_labels(nm);
485
0
  return rbtree_find_less_equal(&az->ztree, &key, (rbnode_type**)z);
486
0
}
487
488
489
/** find the auth zone that is above the given name */
490
struct auth_zone*
491
auth_zones_find_zone(struct auth_zones* az, uint8_t* name, size_t name_len,
492
  uint16_t dclass)
493
0
{
494
0
  uint8_t* nm = name;
495
0
  size_t nmlen = name_len;
496
0
  struct auth_zone* z;
497
0
  if(auth_zone_find_less_equal(az, nm, nmlen, dclass, &z)) {
498
    /* exact match */
499
0
    return z;
500
0
  } else {
501
    /* less-or-nothing */
502
0
    if(!z) return NULL; /* nothing smaller, nothing above it */
503
    /* we found smaller name; smaller may be above the name,
504
     * but not below it. */
505
0
    nm = dname_get_shared_topdomain(z->name, name);
506
0
    dname_count_size_labels(nm, &nmlen);
507
0
    z = NULL;
508
0
  }
509
510
  /* search up */
511
0
  while(!z) {
512
0
    z = auth_zone_find(az, nm, nmlen, dclass);
513
0
    if(z) return z;
514
0
    if(dname_is_root(nm)) break;
515
0
    dname_remove_label(&nm, &nmlen);
516
0
  }
517
0
  return NULL;
518
0
}
519
520
/** find or create zone with name str. caller must have lock on az. 
521
 * returns a wrlocked zone */
522
static struct auth_zone*
523
auth_zones_find_or_add_zone(struct auth_zones* az, char* name)
524
0
{
525
0
  uint8_t nm[LDNS_MAX_DOMAINLEN+1];
526
0
  size_t nmlen = sizeof(nm);
527
0
  struct auth_zone* z;
528
529
0
  if(sldns_str2wire_dname_buf(name, nm, &nmlen) != 0) {
530
0
    log_err("cannot parse auth zone name: %s", name);
531
0
    return 0;
532
0
  }
533
0
  z = auth_zone_find(az, nm, nmlen, LDNS_RR_CLASS_IN);
534
0
  if(!z) {
535
    /* not found, create the zone */
536
0
    z = auth_zone_create(az, nm, nmlen, LDNS_RR_CLASS_IN);
537
0
  } else {
538
0
    lock_rw_wrlock(&z->lock);
539
0
  }
540
0
  return z;
541
0
}
542
543
/** find or create xfer zone with name str. caller must have lock on az. 
544
 * returns a locked xfer */
545
static struct auth_xfer*
546
auth_zones_find_or_add_xfer(struct auth_zones* az, struct auth_zone* z)
547
0
{
548
0
  struct auth_xfer* x;
549
0
  x = auth_xfer_find(az, z->name, z->namelen, z->dclass);
550
0
  if(!x) {
551
    /* not found, create the zone */
552
0
    x = auth_xfer_create(az, z);
553
0
  } else {
554
0
    lock_basic_lock(&x->lock);
555
0
  }
556
0
  return x;
557
0
}
558
559
int
560
auth_zone_set_zonefile(struct auth_zone* z, char* zonefile)
561
0
{
562
0
  if(z->zonefile) free(z->zonefile);
563
0
  if(zonefile == NULL) {
564
0
    z->zonefile = NULL;
565
0
  } else {
566
0
    z->zonefile = strdup(zonefile);
567
0
    if(!z->zonefile) {
568
0
      log_err("malloc failure");
569
0
      return 0;
570
0
    }
571
0
  }
572
0
  return 1;
573
0
}
574
575
/** set auth zone fallback. caller must have lock on zone */
576
int
577
auth_zone_set_fallback(struct auth_zone* z, char* fallbackstr)
578
0
{
579
0
  if(strcmp(fallbackstr, "yes") != 0 && strcmp(fallbackstr, "no") != 0){
580
0
    log_err("auth zone fallback, expected yes or no, got %s",
581
0
      fallbackstr);
582
0
    return 0;
583
0
  }
584
0
  z->fallback_enabled = (strcmp(fallbackstr, "yes")==0);
585
0
  return 1;
586
0
}
587
588
/** create domain with the given name */
589
static struct auth_data*
590
az_domain_create(struct auth_zone* z, uint8_t* nm, size_t nmlen)
591
0
{
592
0
  struct auth_data* n = (struct auth_data*)malloc(sizeof(*n));
593
0
  if(!n) return NULL;
594
0
  memset(n, 0, sizeof(*n));
595
0
  n->node.key = n;
596
0
  n->name = memdup(nm, nmlen);
597
0
  if(!n->name) {
598
0
    free(n);
599
0
    return NULL;
600
0
  }
601
0
  n->namelen = nmlen;
602
0
  n->namelabs = dname_count_labels(nm);
603
0
  if(!rbtree_insert(&z->data, &n->node)) {
604
0
    log_warn("duplicate auth domain name");
605
0
    free(n->name);
606
0
    free(n);
607
0
    return NULL;
608
0
  }
609
0
  return n;
610
0
}
611
612
/** find domain with exactly the given name */
613
static struct auth_data*
614
az_find_name(struct auth_zone* z, uint8_t* nm, size_t nmlen)
615
0
{
616
0
  struct auth_zone key;
617
0
  key.node.key = &key;
618
0
  key.name = nm;
619
0
  key.namelen = nmlen;
620
0
  key.namelabs = dname_count_labels(nm);
621
0
  return (struct auth_data*)rbtree_search(&z->data, &key);
622
0
}
623
624
/** Find domain name (or closest match) */
625
static void
626
az_find_domain(struct auth_zone* z, struct query_info* qinfo, int* node_exact,
627
  struct auth_data** node)
628
0
{
629
0
  struct auth_zone key;
630
0
  key.node.key = &key;
631
0
  key.name = qinfo->qname;
632
0
  key.namelen = qinfo->qname_len;
633
0
  key.namelabs = dname_count_labels(key.name);
634
0
  *node_exact = rbtree_find_less_equal(&z->data, &key,
635
0
    (rbnode_type**)node);
636
0
}
637
638
/** find or create domain with name in zone */
639
static struct auth_data*
640
az_domain_find_or_create(struct auth_zone* z, uint8_t* dname,
641
  size_t dname_len)
642
0
{
643
0
  struct auth_data* n = az_find_name(z, dname, dname_len);
644
0
  if(!n) {
645
0
    n = az_domain_create(z, dname, dname_len);
646
0
  }
647
0
  return n;
648
0
}
649
650
/** find rrset of given type in the domain */
651
static struct auth_rrset*
652
az_domain_rrset(struct auth_data* n, uint16_t t)
653
0
{
654
0
  struct auth_rrset* rrset;
655
0
  if(!n) return NULL;
656
0
  rrset = n->rrsets;
657
0
  while(rrset) {
658
0
    if(rrset->type == t)
659
0
      return rrset;
660
0
    rrset = rrset->next;
661
0
  }
662
0
  return NULL;
663
0
}
664
665
/** remove rrset of this type from domain */
666
static void
667
domain_remove_rrset(struct auth_data* node, uint16_t rr_type)
668
0
{
669
0
  struct auth_rrset* rrset, *prev;
670
0
  if(!node) return;
671
0
  prev = NULL;
672
0
  rrset = node->rrsets;
673
0
  while(rrset) {
674
0
    if(rrset->type == rr_type) {
675
      /* found it, now delete it */
676
0
      if(prev) prev->next = rrset->next;
677
0
      else  node->rrsets = rrset->next;
678
0
      auth_rrset_delete(rrset);
679
0
      return;
680
0
    }
681
0
    prev = rrset;
682
0
    rrset = rrset->next;
683
0
  }
684
0
}
685
686
/** find an rrsig index in the rrset.  returns true if found */
687
static int
688
az_rrset_find_rrsig(struct packed_rrset_data* d, uint8_t* rdata, size_t len,
689
  size_t* index)
690
0
{
691
0
  size_t i;
692
0
  for(i=d->count; i<d->count + d->rrsig_count; i++) {
693
0
    if(d->rr_len[i] != len)
694
0
      continue;
695
0
    if(memcmp(d->rr_data[i], rdata, len) == 0) {
696
0
      *index = i;
697
0
      return 1;
698
0
    }
699
0
  }
700
0
  return 0;
701
0
}
702
703
/** see if rdata is duplicate */
704
static int
705
rdata_duplicate(struct packed_rrset_data* d, uint8_t* rdata, size_t len)
706
0
{
707
0
  size_t i;
708
0
  for(i=0; i<d->count + d->rrsig_count; i++) {
709
0
    if(d->rr_len[i] != len)
710
0
      continue;
711
0
    if(memcmp(d->rr_data[i], rdata, len) == 0)
712
0
      return 1;
713
0
  }
714
0
  return 0;
715
0
}
716
717
/** get rrsig type covered from rdata.
718
 * @param rdata: rdata in wireformat, starting with 16bit rdlength.
719
 * @param rdatalen: length of rdata buffer.
720
 * @return type covered (or 0).
721
 */
722
static uint16_t
723
rrsig_rdata_get_type_covered(uint8_t* rdata, size_t rdatalen)
724
0
{
725
0
  if(rdatalen < 4)
726
0
    return 0;
727
0
  return sldns_read_uint16(rdata+2);
728
0
}
729
730
/** remove RR from existing RRset. Also sig, if it is a signature.
731
 * reallocates the packed rrset for a new one, false on alloc failure */
732
static int
733
rrset_remove_rr(struct auth_rrset* rrset, size_t index)
734
0
{
735
0
  struct packed_rrset_data* d, *old = rrset->data;
736
0
  size_t i;
737
0
  if(index >= old->count + old->rrsig_count)
738
0
    return 0; /* index out of bounds */
739
0
  d = (struct packed_rrset_data*)calloc(1, packed_rrset_sizeof(old) - (
740
0
    sizeof(size_t) + sizeof(uint8_t*) + sizeof(time_t) +
741
0
    old->rr_len[index]));
742
0
  if(!d) {
743
0
    log_err("malloc failure");
744
0
    return 0;
745
0
  }
746
0
  d->ttl = old->ttl;
747
0
  d->count = old->count;
748
0
  d->rrsig_count = old->rrsig_count;
749
0
  if(index < d->count) d->count--;
750
0
  else d->rrsig_count--;
751
0
  d->trust = old->trust;
752
0
  d->security = old->security;
753
754
  /* set rr_len, needed for ptr_fixup */
755
0
  d->rr_len = (size_t*)((uint8_t*)d +
756
0
    sizeof(struct packed_rrset_data));
757
0
  if(index > 0)
758
0
    memmove(d->rr_len, old->rr_len, (index)*sizeof(size_t));
759
0
  if(index+1 < old->count+old->rrsig_count)
760
0
    memmove(&d->rr_len[index], &old->rr_len[index+1],
761
0
    (old->count+old->rrsig_count - (index+1))*sizeof(size_t));
762
0
  packed_rrset_ptr_fixup(d);
763
764
  /* move over ttls */
765
0
  if(index > 0)
766
0
    memmove(d->rr_ttl, old->rr_ttl, (index)*sizeof(time_t));
767
0
  if(index+1 < old->count+old->rrsig_count)
768
0
    memmove(&d->rr_ttl[index], &old->rr_ttl[index+1],
769
0
    (old->count+old->rrsig_count - (index+1))*sizeof(time_t));
770
  
771
  /* move over rr_data */
772
0
  for(i=0; i<d->count+d->rrsig_count; i++) {
773
0
    size_t oldi;
774
0
    if(i < index) oldi = i;
775
0
    else oldi = i+1;
776
0
    memmove(d->rr_data[i], old->rr_data[oldi], d->rr_len[i]);
777
0
  }
778
779
  /* recalc ttl (lowest of remaining RR ttls) */
780
0
  if(d->count + d->rrsig_count > 0)
781
0
    d->ttl = d->rr_ttl[0];
782
0
  for(i=0; i<d->count+d->rrsig_count; i++) {
783
0
    if(d->rr_ttl[i] < d->ttl)
784
0
      d->ttl = d->rr_ttl[i];
785
0
  }
786
787
0
  free(rrset->data);
788
0
  rrset->data = d;
789
0
  return 1;
790
0
}
791
792
/** add RR to existing RRset. If insert_sig is true, add to rrsigs. 
793
 * This reallocates the packed rrset for a new one */
794
static int
795
rrset_add_rr(struct auth_rrset* rrset, uint32_t rr_ttl, uint8_t* rdata,
796
  size_t rdatalen, int insert_sig)
797
0
{
798
0
  struct packed_rrset_data* d, *old = rrset->data;
799
0
  size_t total, old_total;
800
801
0
  d = (struct packed_rrset_data*)calloc(1, packed_rrset_sizeof(old)
802
0
    + sizeof(size_t) + sizeof(uint8_t*) + sizeof(time_t)
803
0
    + rdatalen);
804
0
  if(!d) {
805
0
    log_err("out of memory");
806
0
    return 0;
807
0
  }
808
  /* copy base values */
809
0
  memcpy(d, old, sizeof(struct packed_rrset_data));
810
0
  if(!insert_sig) {
811
0
    d->count++;
812
0
  } else {
813
0
    d->rrsig_count++;
814
0
  }
815
0
  old_total = old->count + old->rrsig_count;
816
0
  total = d->count + d->rrsig_count;
817
  /* set rr_len, needed for ptr_fixup */
818
0
  d->rr_len = (size_t*)((uint8_t*)d +
819
0
    sizeof(struct packed_rrset_data));
820
0
  if(old->count != 0)
821
0
    memmove(d->rr_len, old->rr_len, old->count*sizeof(size_t));
822
0
  if(old->rrsig_count != 0)
823
0
    memmove(d->rr_len+d->count, old->rr_len+old->count,
824
0
      old->rrsig_count*sizeof(size_t));
825
0
  if(!insert_sig)
826
0
    d->rr_len[d->count-1] = rdatalen;
827
0
  else  d->rr_len[total-1] = rdatalen;
828
0
  packed_rrset_ptr_fixup(d);
829
0
  if((time_t)rr_ttl < d->ttl)
830
0
    d->ttl = rr_ttl;
831
832
  /* copy old values into new array */
833
0
  if(old->count != 0) {
834
0
    memmove(d->rr_ttl, old->rr_ttl, old->count*sizeof(time_t));
835
    /* all the old rr pieces are allocated sequential, so we
836
     * can copy them in one go */
837
0
    memmove(d->rr_data[0], old->rr_data[0],
838
0
      (old->rr_data[old->count-1] - old->rr_data[0]) +
839
0
      old->rr_len[old->count-1]);
840
0
  }
841
0
  if(old->rrsig_count != 0) {
842
0
    memmove(d->rr_ttl+d->count, old->rr_ttl+old->count,
843
0
      old->rrsig_count*sizeof(time_t));
844
0
    memmove(d->rr_data[d->count], old->rr_data[old->count],
845
0
      (old->rr_data[old_total-1] - old->rr_data[old->count]) +
846
0
      old->rr_len[old_total-1]);
847
0
  }
848
849
  /* insert new value */
850
0
  if(!insert_sig) {
851
0
    d->rr_ttl[d->count-1] = rr_ttl;
852
0
    memmove(d->rr_data[d->count-1], rdata, rdatalen);
853
0
  } else {
854
0
    d->rr_ttl[total-1] = rr_ttl;
855
0
    memmove(d->rr_data[total-1], rdata, rdatalen);
856
0
  }
857
858
0
  rrset->data = d;
859
0
  free(old);
860
0
  return 1;
861
0
}
862
863
/** Create new rrset for node with packed rrset with one RR element */
864
static struct auth_rrset*
865
rrset_create(struct auth_data* node, uint16_t rr_type, uint32_t rr_ttl,
866
  uint8_t* rdata, size_t rdatalen)
867
0
{
868
0
  struct auth_rrset* rrset = (struct auth_rrset*)calloc(1,
869
0
    sizeof(*rrset));
870
0
  struct auth_rrset* p, *prev;
871
0
  struct packed_rrset_data* d;
872
0
  if(!rrset) {
873
0
    log_err("out of memory");
874
0
    return NULL;
875
0
  }
876
0
  rrset->type = rr_type;
877
878
  /* the rrset data structure, with one RR */
879
0
  d = (struct packed_rrset_data*)calloc(1,
880
0
    sizeof(struct packed_rrset_data) + sizeof(size_t) +
881
0
    sizeof(uint8_t*) + sizeof(time_t) + rdatalen);
882
0
  if(!d) {
883
0
    free(rrset);
884
0
    log_err("out of memory");
885
0
    return NULL;
886
0
  }
887
0
  rrset->data = d;
888
0
  d->ttl = rr_ttl;
889
0
  d->trust = rrset_trust_prim_noglue;
890
0
  d->rr_len = (size_t*)((uint8_t*)d + sizeof(struct packed_rrset_data));
891
0
  d->rr_data = (uint8_t**)&(d->rr_len[1]);
892
0
  d->rr_ttl = (time_t*)&(d->rr_data[1]);
893
0
  d->rr_data[0] = (uint8_t*)&(d->rr_ttl[1]);
894
895
  /* insert the RR */
896
0
  d->rr_len[0] = rdatalen;
897
0
  d->rr_ttl[0] = rr_ttl;
898
0
  memmove(d->rr_data[0], rdata, rdatalen);
899
0
  d->count++;
900
901
  /* insert rrset into linked list for domain */
902
  /* find sorted place to link the rrset into the list */
903
0
  prev = NULL;
904
0
  p = node->rrsets;
905
0
  while(p && p->type<=rr_type) {
906
0
    prev = p;
907
0
    p = p->next;
908
0
  }
909
  /* so, prev is smaller, and p is larger than rr_type */
910
0
  rrset->next = p;
911
0
  if(prev) prev->next = rrset;
912
0
  else node->rrsets = rrset;
913
0
  return rrset;
914
0
}
915
916
/** count number (and size) of rrsigs that cover a type */
917
static size_t
918
rrsig_num_that_cover(struct auth_rrset* rrsig, uint16_t rr_type, size_t* sigsz)
919
0
{
920
0
  struct packed_rrset_data* d = rrsig->data;
921
0
  size_t i, num = 0;
922
0
  *sigsz = 0;
923
0
  log_assert(d && rrsig->type == LDNS_RR_TYPE_RRSIG);
924
0
  for(i=0; i<d->count+d->rrsig_count; i++) {
925
0
    if(rrsig_rdata_get_type_covered(d->rr_data[i],
926
0
      d->rr_len[i]) == rr_type) {
927
0
      num++;
928
0
      (*sigsz) += d->rr_len[i];
929
0
    }
930
0
  }
931
0
  return num;
932
0
}
933
934
/** See if rrsig set has covered sigs for rrset and move them over */
935
static int
936
rrset_moveover_rrsigs(struct auth_data* node, uint16_t rr_type,
937
  struct auth_rrset* rrset, struct auth_rrset* rrsig)
938
0
{
939
0
  size_t sigs, sigsz, i, j, total;
940
0
  struct packed_rrset_data* sigold = rrsig->data;
941
0
  struct packed_rrset_data* old = rrset->data;
942
0
  struct packed_rrset_data* d, *sigd;
943
944
0
  log_assert(rrset->type == rr_type);
945
0
  log_assert(rrsig->type == LDNS_RR_TYPE_RRSIG);
946
0
  sigs = rrsig_num_that_cover(rrsig, rr_type, &sigsz);
947
0
  if(sigs == 0) {
948
    /* 0 rrsigs to move over, done */
949
0
    return 1;
950
0
  }
951
952
  /* allocate rrset sigsz larger for extra sigs elements, and
953
   * allocate rrsig sigsz smaller for less sigs elements. */
954
0
  d = (struct packed_rrset_data*)calloc(1, packed_rrset_sizeof(old)
955
0
    + sigs*(sizeof(size_t) + sizeof(uint8_t*) + sizeof(time_t))
956
0
    + sigsz);
957
0
  if(!d) {
958
0
    log_err("out of memory");
959
0
    return 0;
960
0
  }
961
  /* copy base values */
962
0
  total = old->count + old->rrsig_count;
963
0
  memcpy(d, old, sizeof(struct packed_rrset_data));
964
0
  d->rrsig_count += sigs;
965
  /* setup rr_len */
966
0
  d->rr_len = (size_t*)((uint8_t*)d +
967
0
    sizeof(struct packed_rrset_data));
968
0
  if(total != 0)
969
0
    memmove(d->rr_len, old->rr_len, total*sizeof(size_t));
970
0
  j = d->count+d->rrsig_count-sigs;
971
0
  for(i=0; i<sigold->count+sigold->rrsig_count; i++) {
972
0
    if(rrsig_rdata_get_type_covered(sigold->rr_data[i],
973
0
      sigold->rr_len[i]) == rr_type) {
974
0
      d->rr_len[j] = sigold->rr_len[i];
975
0
      j++;
976
0
    }
977
0
  }
978
0
  packed_rrset_ptr_fixup(d);
979
980
  /* copy old values into new array */
981
0
  if(total != 0) {
982
0
    memmove(d->rr_ttl, old->rr_ttl, total*sizeof(time_t));
983
    /* all the old rr pieces are allocated sequential, so we
984
     * can copy them in one go */
985
0
    memmove(d->rr_data[0], old->rr_data[0],
986
0
      (old->rr_data[total-1] - old->rr_data[0]) +
987
0
      old->rr_len[total-1]);
988
0
  }
989
990
  /* move over the rrsigs to the larger rrset*/
991
0
  j = d->count+d->rrsig_count-sigs;
992
0
  for(i=0; i<sigold->count+sigold->rrsig_count; i++) {
993
0
    if(rrsig_rdata_get_type_covered(sigold->rr_data[i],
994
0
      sigold->rr_len[i]) == rr_type) {
995
      /* move this one over to location j */
996
0
      d->rr_ttl[j] = sigold->rr_ttl[i];
997
0
      memmove(d->rr_data[j], sigold->rr_data[i],
998
0
        sigold->rr_len[i]);
999
0
      if(d->rr_ttl[j] < d->ttl)
1000
0
        d->ttl = d->rr_ttl[j];
1001
0
      j++;
1002
0
    }
1003
0
  }
1004
1005
  /* put it in and deallocate the old rrset */
1006
0
  rrset->data = d;
1007
0
  free(old);
1008
1009
  /* now make rrsig set smaller */
1010
0
  if(sigold->count+sigold->rrsig_count == sigs) {
1011
    /* remove all sigs from rrsig, remove it entirely */
1012
0
    domain_remove_rrset(node, LDNS_RR_TYPE_RRSIG);
1013
0
    return 1;
1014
0
  }
1015
0
  log_assert(packed_rrset_sizeof(sigold) > sigs*(sizeof(size_t) +
1016
0
    sizeof(uint8_t*) + sizeof(time_t)) + sigsz);
1017
0
  sigd = (struct packed_rrset_data*)calloc(1, packed_rrset_sizeof(sigold)
1018
0
    - sigs*(sizeof(size_t) + sizeof(uint8_t*) + sizeof(time_t))
1019
0
    - sigsz);
1020
0
  if(!sigd) {
1021
    /* no need to free up d, it has already been placed in the
1022
     * node->rrset structure */
1023
0
    log_err("out of memory");
1024
0
    return 0;
1025
0
  }
1026
  /* copy base values */
1027
0
  memcpy(sigd, sigold, sizeof(struct packed_rrset_data));
1028
  /* in sigd the RRSIGs are stored in the base of the RR, in count */
1029
0
  sigd->count -= sigs;
1030
  /* setup rr_len */
1031
0
  sigd->rr_len = (size_t*)((uint8_t*)sigd +
1032
0
    sizeof(struct packed_rrset_data));
1033
0
  j = 0;
1034
0
  for(i=0; i<sigold->count+sigold->rrsig_count; i++) {
1035
0
    if(rrsig_rdata_get_type_covered(sigold->rr_data[i],
1036
0
      sigold->rr_len[i]) != rr_type) {
1037
0
      sigd->rr_len[j] = sigold->rr_len[i];
1038
0
      j++;
1039
0
    }
1040
0
  }
1041
0
  packed_rrset_ptr_fixup(sigd);
1042
1043
  /* copy old values into new rrsig array */
1044
0
  j = 0;
1045
0
  for(i=0; i<sigold->count+sigold->rrsig_count; i++) {
1046
0
    if(rrsig_rdata_get_type_covered(sigold->rr_data[i],
1047
0
      sigold->rr_len[i]) != rr_type) {
1048
      /* move this one over to location j */
1049
0
      sigd->rr_ttl[j] = sigold->rr_ttl[i];
1050
0
      memmove(sigd->rr_data[j], sigold->rr_data[i],
1051
0
        sigold->rr_len[i]);
1052
0
      if(j==0) sigd->ttl = sigd->rr_ttl[j];
1053
0
      else {
1054
0
        if(sigd->rr_ttl[j] < sigd->ttl)
1055
0
          sigd->ttl = sigd->rr_ttl[j];
1056
0
      }
1057
0
      j++;
1058
0
    }
1059
0
  }
1060
1061
  /* put it in and deallocate the old rrset */
1062
0
  rrsig->data = sigd;
1063
0
  free(sigold);
1064
1065
0
  return 1;
1066
0
}
1067
1068
/** copy the rrsigs from the rrset to the rrsig rrset, because the rrset
1069
 * is going to be deleted.  reallocates the RRSIG rrset data. */
1070
static int
1071
rrsigs_copy_from_rrset_to_rrsigset(struct auth_rrset* rrset,
1072
  struct auth_rrset* rrsigset)
1073
0
{
1074
0
  size_t i;
1075
0
  if(rrset->data->rrsig_count == 0)
1076
0
    return 1;
1077
1078
  /* move them over one by one, because there might be duplicates,
1079
   * duplicates are ignored */
1080
0
  for(i=rrset->data->count;
1081
0
    i<rrset->data->count+rrset->data->rrsig_count; i++) {
1082
0
    uint8_t* rdata = rrset->data->rr_data[i];
1083
0
    size_t rdatalen = rrset->data->rr_len[i];
1084
0
    time_t rr_ttl  = rrset->data->rr_ttl[i];
1085
1086
0
    if(rdata_duplicate(rrsigset->data, rdata, rdatalen)) {
1087
0
      continue;
1088
0
    }
1089
0
    if(!rrset_add_rr(rrsigset, rr_ttl, rdata, rdatalen, 0))
1090
0
      return 0;
1091
0
  }
1092
0
  return 1;
1093
0
}
1094
1095
/** Add rr to node, ignores duplicate RRs,
1096
 * rdata points to buffer with rdatalen octets, starts with 2bytelength. */
1097
static int
1098
az_domain_add_rr(struct auth_data* node, uint16_t rr_type, uint32_t rr_ttl,
1099
  uint8_t* rdata, size_t rdatalen, int* duplicate)
1100
0
{
1101
0
  struct auth_rrset* rrset;
1102
  /* packed rrsets have their rrsigs along with them, sort them out */
1103
0
  if(rr_type == LDNS_RR_TYPE_RRSIG) {
1104
0
    uint16_t ctype = rrsig_rdata_get_type_covered(rdata, rdatalen);
1105
0
    if((rrset=az_domain_rrset(node, ctype))!= NULL) {
1106
      /* a node of the correct type exists, add the RRSIG
1107
       * to the rrset of the covered data type */
1108
0
      if(rdata_duplicate(rrset->data, rdata, rdatalen)) {
1109
0
        if(duplicate) *duplicate = 1;
1110
0
        return 1;
1111
0
      }
1112
0
      if(!rrset_add_rr(rrset, rr_ttl, rdata, rdatalen, 1))
1113
0
        return 0;
1114
0
    } else if((rrset=az_domain_rrset(node, rr_type))!= NULL) {
1115
      /* add RRSIG to rrset of type RRSIG */
1116
0
      if(rdata_duplicate(rrset->data, rdata, rdatalen)) {
1117
0
        if(duplicate) *duplicate = 1;
1118
0
        return 1;
1119
0
      }
1120
0
      if(!rrset_add_rr(rrset, rr_ttl, rdata, rdatalen, 0))
1121
0
        return 0;
1122
0
    } else {
1123
      /* create rrset of type RRSIG */
1124
0
      if(!rrset_create(node, rr_type, rr_ttl, rdata,
1125
0
        rdatalen))
1126
0
        return 0;
1127
0
    }
1128
0
  } else {
1129
    /* normal RR type */
1130
0
    if((rrset=az_domain_rrset(node, rr_type))!= NULL) {
1131
      /* add data to existing node with data type */
1132
0
      if(rdata_duplicate(rrset->data, rdata, rdatalen)) {
1133
0
        if(duplicate) *duplicate = 1;
1134
0
        return 1;
1135
0
      }
1136
0
      if(!rrset_add_rr(rrset, rr_ttl, rdata, rdatalen, 0))
1137
0
        return 0;
1138
0
    } else {
1139
0
      struct auth_rrset* rrsig;
1140
      /* create new node with data type */
1141
0
      if(!(rrset=rrset_create(node, rr_type, rr_ttl, rdata,
1142
0
        rdatalen)))
1143
0
        return 0;
1144
1145
      /* see if node of type RRSIG has signatures that
1146
       * cover the data type, and move them over */
1147
      /* and then make the RRSIG type smaller */
1148
0
      if((rrsig=az_domain_rrset(node, LDNS_RR_TYPE_RRSIG))
1149
0
        != NULL) {
1150
0
        if(!rrset_moveover_rrsigs(node, rr_type,
1151
0
          rrset, rrsig))
1152
0
          return 0;
1153
0
      }
1154
0
    }
1155
0
  }
1156
0
  return 1;
1157
0
}
1158
1159
/** insert RR into zone, ignore duplicates */
1160
static int
1161
az_insert_rr(struct auth_zone* z, uint8_t* rr, size_t rr_len,
1162
  size_t dname_len, int* duplicate)
1163
0
{
1164
0
  struct auth_data* node;
1165
0
  uint8_t* dname = rr;
1166
0
  uint16_t rr_type = sldns_wirerr_get_type(rr, rr_len, dname_len);
1167
0
  uint16_t rr_class = sldns_wirerr_get_class(rr, rr_len, dname_len);
1168
0
  uint32_t rr_ttl = sldns_wirerr_get_ttl(rr, rr_len, dname_len);
1169
0
  size_t rdatalen = ((size_t)sldns_wirerr_get_rdatalen(rr, rr_len,
1170
0
    dname_len))+2;
1171
  /* rdata points to rdata prefixed with uint16 rdatalength */
1172
0
  uint8_t* rdata = sldns_wirerr_get_rdatawl(rr, rr_len, dname_len);
1173
1174
0
  if(rr_class != z->dclass) {
1175
0
    log_err("wrong class for RR");
1176
0
    return 0;
1177
0
  }
1178
0
  if(!(node=az_domain_find_or_create(z, dname, dname_len))) {
1179
0
    log_err("cannot create domain");
1180
0
    return 0;
1181
0
  }
1182
0
  if(!az_domain_add_rr(node, rr_type, rr_ttl, rdata, rdatalen,
1183
0
    duplicate)) {
1184
0
    log_err("cannot add RR to domain");
1185
0
    return 0;
1186
0
  }
1187
0
  if(z->rpz) {
1188
0
    if(!(rpz_insert_rr(z->rpz, z->name, z->namelen, dname,
1189
0
      dname_len, rr_type, rr_class, rr_ttl, rdata, rdatalen,
1190
0
      rr, rr_len)))
1191
0
      return 0;
1192
0
  }
1193
0
  return 1;
1194
0
}
1195
1196
/** Remove rr from node, ignores nonexisting RRs,
1197
 * rdata points to buffer with rdatalen octets, starts with 2bytelength. */
1198
static int
1199
az_domain_remove_rr(struct auth_data* node, uint16_t rr_type,
1200
  uint8_t* rdata, size_t rdatalen, int* nonexist)
1201
0
{
1202
0
  struct auth_rrset* rrset;
1203
0
  size_t index = 0;
1204
1205
  /* find the plain RR of the given type */
1206
0
  if((rrset=az_domain_rrset(node, rr_type))!= NULL) {
1207
0
    if(packed_rrset_find_rr(rrset->data, rdata, rdatalen, &index)) {
1208
0
      if(rrset->data->count == 1 &&
1209
0
        rrset->data->rrsig_count == 0) {
1210
        /* last RR, delete the rrset */
1211
0
        domain_remove_rrset(node, rr_type);
1212
0
      } else if(rrset->data->count == 1 &&
1213
0
        rrset->data->rrsig_count != 0) {
1214
        /* move RRSIGs to the RRSIG rrset, or
1215
         * this one becomes that RRset */
1216
0
        struct auth_rrset* rrsigset = az_domain_rrset(
1217
0
          node, LDNS_RR_TYPE_RRSIG);
1218
0
        if(rrsigset) {
1219
          /* move left over rrsigs to the
1220
           * existing rrset of type RRSIG */
1221
0
          rrsigs_copy_from_rrset_to_rrsigset(
1222
0
            rrset, rrsigset);
1223
          /* and then delete the rrset */
1224
0
          domain_remove_rrset(node, rr_type);
1225
0
        } else {
1226
          /* no rrset of type RRSIG, this
1227
           * set is now of that type,
1228
           * just remove the rr */
1229
0
          if(!rrset_remove_rr(rrset, index))
1230
0
            return 0;
1231
0
          rrset->type = LDNS_RR_TYPE_RRSIG;
1232
0
          rrset->data->count = rrset->data->rrsig_count;
1233
0
          rrset->data->rrsig_count = 0;
1234
0
        }
1235
0
      } else {
1236
        /* remove the RR from the rrset */
1237
0
        if(!rrset_remove_rr(rrset, index))
1238
0
          return 0;
1239
0
      }
1240
0
      return 1;
1241
0
    }
1242
    /* rr not found in rrset */
1243
0
  }
1244
1245
  /* is it a type RRSIG, look under the covered type */
1246
0
  if(rr_type == LDNS_RR_TYPE_RRSIG) {
1247
0
    uint16_t ctype = rrsig_rdata_get_type_covered(rdata, rdatalen);
1248
0
    if((rrset=az_domain_rrset(node, ctype))!= NULL) {
1249
0
      if(az_rrset_find_rrsig(rrset->data, rdata, rdatalen,
1250
0
        &index)) {
1251
        /* rrsig should have d->count > 0, be
1252
         * over some rr of that type */
1253
        /* remove the rrsig from the rrsigs list of the
1254
         * rrset */
1255
0
        if(!rrset_remove_rr(rrset, index))
1256
0
          return 0;
1257
0
        return 1;
1258
0
      }
1259
0
    }
1260
    /* also RRSIG not found */
1261
0
  }
1262
1263
  /* nothing found to delete */
1264
0
  if(nonexist) *nonexist = 1;
1265
0
  return 1;
1266
0
}
1267
1268
/** remove RR from zone, ignore if it does not exist, false on alloc failure*/
1269
static int
1270
az_remove_rr(struct auth_zone* z, uint8_t* rr, size_t rr_len,
1271
  size_t dname_len, int* nonexist)
1272
0
{
1273
0
  struct auth_data* node;
1274
0
  uint8_t* dname = rr;
1275
0
  uint16_t rr_type = sldns_wirerr_get_type(rr, rr_len, dname_len);
1276
0
  uint16_t rr_class = sldns_wirerr_get_class(rr, rr_len, dname_len);
1277
0
  size_t rdatalen = ((size_t)sldns_wirerr_get_rdatalen(rr, rr_len,
1278
0
    dname_len))+2;
1279
  /* rdata points to rdata prefixed with uint16 rdatalength */
1280
0
  uint8_t* rdata = sldns_wirerr_get_rdatawl(rr, rr_len, dname_len);
1281
1282
0
  if(rr_class != z->dclass) {
1283
0
    log_err("wrong class for RR");
1284
    /* really also a nonexisting entry, because no records
1285
     * of that class in the zone, but return an error because
1286
     * getting records of the wrong class is a failure of the
1287
     * zone transfer */
1288
0
    return 0;
1289
0
  }
1290
0
  node = az_find_name(z, dname, dname_len);
1291
0
  if(!node) {
1292
    /* node with that name does not exist */
1293
    /* nonexisting entry, because no such name */
1294
0
    *nonexist = 1;
1295
0
    return 1;
1296
0
  }
1297
0
  if(!az_domain_remove_rr(node, rr_type, rdata, rdatalen, nonexist)) {
1298
    /* alloc failure or so */
1299
0
    return 0;
1300
0
  }
1301
  /* remove the node, if necessary */
1302
  /* an rrsets==NULL entry is not kept around for empty nonterminals,
1303
   * and also parent nodes are not kept around, so we just delete it */
1304
0
  if(node->rrsets == NULL) {
1305
0
    (void)rbtree_delete(&z->data, node);
1306
0
    auth_data_delete(node);
1307
0
  }
1308
0
  if(z->rpz) {
1309
0
    rpz_remove_rr(z->rpz, z->name, z->namelen, dname, dname_len,
1310
0
      rr_type, rr_class, rdata, rdatalen);
1311
0
  }
1312
0
  return 1;
1313
0
}
1314
1315
/** decompress an RR into the buffer where it'll be an uncompressed RR
1316
 * with uncompressed dname and uncompressed rdata (dnames) */
1317
static int
1318
decompress_rr_into_buffer(struct sldns_buffer* buf, uint8_t* pkt,
1319
  size_t pktlen, uint8_t* dname, uint16_t rr_type, uint16_t rr_class,
1320
  uint32_t rr_ttl, uint8_t* rr_data, uint16_t rr_rdlen)
1321
0
{
1322
0
  sldns_buffer pktbuf;
1323
0
  size_t dname_len = 0;
1324
0
  size_t rdlenpos;
1325
0
  size_t rdlen;
1326
0
  uint8_t* rd;
1327
0
  const sldns_rr_descriptor* desc;
1328
0
  sldns_buffer_init_frm_data(&pktbuf, pkt, pktlen);
1329
0
  sldns_buffer_clear(buf);
1330
1331
  /* decompress dname */
1332
0
  sldns_buffer_set_position(&pktbuf,
1333
0
    (size_t)(dname - sldns_buffer_current(&pktbuf)));
1334
0
  dname_len = pkt_dname_len(&pktbuf);
1335
0
  if(dname_len == 0) return 0; /* parse fail on dname */
1336
0
  if(!sldns_buffer_available(buf, dname_len)) return 0;
1337
0
  dname_pkt_copy(&pktbuf, sldns_buffer_current(buf), dname);
1338
0
  sldns_buffer_skip(buf, (ssize_t)dname_len);
1339
1340
  /* type, class, ttl and rdatalength fields */
1341
0
  if(!sldns_buffer_available(buf, 10)) return 0;
1342
0
  sldns_buffer_write_u16(buf, rr_type);
1343
0
  sldns_buffer_write_u16(buf, rr_class);
1344
0
  sldns_buffer_write_u32(buf, rr_ttl);
1345
0
  rdlenpos = sldns_buffer_position(buf);
1346
0
  sldns_buffer_write_u16(buf, 0); /* rd length position */
1347
1348
  /* decompress rdata */
1349
0
  desc = sldns_rr_descript(rr_type);
1350
0
  rd = rr_data;
1351
0
  rdlen = rr_rdlen;
1352
0
  if(rdlen > 0 && desc && desc->_dname_count > 0) {
1353
0
    int count = (int)desc->_dname_count;
1354
0
    int rdf = 0;
1355
0
    size_t len; /* how much rdata to plain copy */
1356
0
    size_t uncompressed_len, compressed_len;
1357
0
    size_t oldpos;
1358
    /* decompress dnames. */
1359
0
    while(rdlen > 0 && count) {
1360
0
      switch(desc->_wireformat[rdf]) {
1361
0
      case LDNS_RDF_TYPE_DNAME:
1362
0
        sldns_buffer_set_position(&pktbuf,
1363
0
          (size_t)(rd -
1364
0
          sldns_buffer_begin(&pktbuf)));
1365
0
        oldpos = sldns_buffer_position(&pktbuf);
1366
        /* moves pktbuf to right after the
1367
         * compressed dname, and returns uncompressed
1368
         * dname length */
1369
0
        uncompressed_len = pkt_dname_len(&pktbuf);
1370
0
        if(!uncompressed_len)
1371
0
          return 0; /* parse error in dname */
1372
0
        if(!sldns_buffer_available(buf,
1373
0
          uncompressed_len))
1374
          /* dname too long for buffer */
1375
0
          return 0;
1376
0
        dname_pkt_copy(&pktbuf, 
1377
0
          sldns_buffer_current(buf), rd);
1378
0
        sldns_buffer_skip(buf, (ssize_t)uncompressed_len);
1379
0
        compressed_len = sldns_buffer_position(
1380
0
          &pktbuf) - oldpos;
1381
0
        rd += compressed_len;
1382
0
        rdlen -= compressed_len;
1383
0
        count--;
1384
0
        len = 0;
1385
0
        break;
1386
0
      case LDNS_RDF_TYPE_STR:
1387
        /* Check rdlen for resilience, because it is
1388
         * checked above, that rdlen > 0 */
1389
0
        if(rdlen < 1) return 0; /* malformed */
1390
0
        len = rd[0] + 1;
1391
0
        break;
1392
0
      default:
1393
0
        len = get_rdf_size(desc->_wireformat[rdf]);
1394
0
        break;
1395
0
      }
1396
0
      if(len) {
1397
0
        if(len > rdlen)
1398
0
          return 0; /* malformed */
1399
0
        if(!sldns_buffer_available(buf, len))
1400
0
          return 0; /* too long for buffer */
1401
0
        sldns_buffer_write(buf, rd, len);
1402
0
        rd += len;
1403
0
        rdlen -= len;
1404
0
      }
1405
0
      rdf++;
1406
0
    }
1407
0
  }
1408
  /* copy remaining data */
1409
0
  if(rdlen > 0) {
1410
0
    if(!sldns_buffer_available(buf, rdlen)) return 0;
1411
0
    sldns_buffer_write(buf, rd, rdlen);
1412
0
  }
1413
  /* fixup rdlength */
1414
0
  sldns_buffer_write_u16_at(buf, rdlenpos,
1415
0
    sldns_buffer_position(buf)-rdlenpos-2);
1416
0
  sldns_buffer_flip(buf);
1417
0
  return 1;
1418
0
}
1419
1420
/** insert RR into zone, from packet, decompress RR,
1421
 * if duplicate is nonNULL set the flag but otherwise ignore duplicates */
1422
static int
1423
az_insert_rr_decompress(struct auth_zone* z, uint8_t* pkt, size_t pktlen,
1424
  struct sldns_buffer* scratch_buffer, uint8_t* dname, uint16_t rr_type,
1425
  uint16_t rr_class, uint32_t rr_ttl, uint8_t* rr_data,
1426
  uint16_t rr_rdlen, int* duplicate)
1427
0
{
1428
0
  uint8_t* rr;
1429
0
  size_t rr_len;
1430
0
  size_t dname_len;
1431
0
  if(!decompress_rr_into_buffer(scratch_buffer, pkt, pktlen, dname,
1432
0
    rr_type, rr_class, rr_ttl, rr_data, rr_rdlen)) {
1433
0
    log_err("could not decompress RR");
1434
0
    return 0;
1435
0
  }
1436
0
  rr = sldns_buffer_begin(scratch_buffer);
1437
0
  rr_len = sldns_buffer_limit(scratch_buffer);
1438
0
  dname_len = dname_valid(rr, rr_len);
1439
0
  return az_insert_rr(z, rr, rr_len, dname_len, duplicate);
1440
0
}
1441
1442
/** remove RR from zone, from packet, decompress RR,
1443
 * if nonexist is nonNULL set the flag but otherwise ignore nonexisting entries*/
1444
static int
1445
az_remove_rr_decompress(struct auth_zone* z, uint8_t* pkt, size_t pktlen,
1446
  struct sldns_buffer* scratch_buffer, uint8_t* dname, uint16_t rr_type,
1447
  uint16_t rr_class, uint32_t rr_ttl, uint8_t* rr_data,
1448
  uint16_t rr_rdlen, int* nonexist)
1449
0
{
1450
0
  uint8_t* rr;
1451
0
  size_t rr_len;
1452
0
  size_t dname_len;
1453
0
  if(!decompress_rr_into_buffer(scratch_buffer, pkt, pktlen, dname,
1454
0
    rr_type, rr_class, rr_ttl, rr_data, rr_rdlen)) {
1455
0
    log_err("could not decompress RR");
1456
0
    return 0;
1457
0
  }
1458
0
  rr = sldns_buffer_begin(scratch_buffer);
1459
0
  rr_len = sldns_buffer_limit(scratch_buffer);
1460
0
  dname_len = dname_valid(rr, rr_len);
1461
0
  return az_remove_rr(z, rr, rr_len, dname_len, nonexist);
1462
0
}
1463
1464
/** 
1465
 * Parse zonefile
1466
 * @param z: zone to read in.
1467
 * @param in: file to read from (just opened).
1468
 * @param rr: buffer to use for RRs, 64k.
1469
 *  passed so that recursive includes can use the same buffer and do
1470
 *  not grow the stack too much.
1471
 * @param rrbuflen: sizeof rr buffer.
1472
 * @param state: parse state with $ORIGIN, $TTL and 'prev-dname' and so on,
1473
 *  that is kept between includes.
1474
 *  The lineno is set at 1 and then increased by the function.
1475
 * @param fname: file name.
1476
 * @param depth: recursion depth for includes
1477
 * @param cfg: config for chroot.
1478
 * returns false on failure, has printed an error message
1479
 */
1480
static int
1481
az_parse_file(struct auth_zone* z, FILE* in, uint8_t* rr, size_t rrbuflen,
1482
  struct sldns_file_parse_state* state, char* fname, int depth,
1483
  struct config_file* cfg)
1484
0
{
1485
0
  size_t rr_len, dname_len;
1486
0
  int status;
1487
0
  state->lineno = 1;
1488
1489
0
  while(!feof(in)) {
1490
0
    rr_len = rrbuflen;
1491
0
    dname_len = 0;
1492
0
    status = sldns_fp2wire_rr_buf(in, rr, &rr_len, &dname_len,
1493
0
      state);
1494
0
    if(status == LDNS_WIREPARSE_ERR_INCLUDE && rr_len == 0) {
1495
      /* we have $INCLUDE or $something */
1496
0
      if(strncmp((char*)rr, "$INCLUDE ", 9) == 0 ||
1497
0
         strncmp((char*)rr, "$INCLUDE\t", 9) == 0) {
1498
0
        FILE* inc;
1499
0
        int lineno_orig = state->lineno;
1500
0
        char* incfile = (char*)rr + 8;
1501
0
        if(depth > MAX_INCLUDE_DEPTH) {
1502
0
          log_err("%s:%d max include depth"
1503
0
            "exceeded", fname, state->lineno);
1504
0
          return 0;
1505
0
        }
1506
        /* skip spaces */
1507
0
        while(*incfile == ' ' || *incfile == '\t')
1508
0
          incfile++;
1509
        /* adjust for chroot on include file */
1510
0
        if(cfg->chrootdir && cfg->chrootdir[0] &&
1511
0
          strncmp(incfile, cfg->chrootdir,
1512
0
            strlen(cfg->chrootdir)) == 0)
1513
0
          incfile += strlen(cfg->chrootdir);
1514
0
        incfile = strdup(incfile);
1515
0
        if(!incfile) {
1516
0
          log_err("malloc failure");
1517
0
          return 0;
1518
0
        }
1519
0
        verbose(VERB_ALGO, "opening $INCLUDE %s",
1520
0
          incfile);
1521
0
        inc = fopen(incfile, "r");
1522
0
        if(!inc) {
1523
0
          log_err("%s:%d cannot open include "
1524
0
            "file %s: %s", fname,
1525
0
            lineno_orig, incfile,
1526
0
            strerror(errno));
1527
0
          free(incfile);
1528
0
          return 0;
1529
0
        }
1530
        /* recurse read that file now */
1531
0
        if(!az_parse_file(z, inc, rr, rrbuflen,
1532
0
          state, incfile, depth+1, cfg)) {
1533
0
          log_err("%s:%d cannot parse include "
1534
0
            "file %s", fname,
1535
0
            lineno_orig, incfile);
1536
0
          fclose(inc);
1537
0
          free(incfile);
1538
0
          return 0;
1539
0
        }
1540
0
        fclose(inc);
1541
0
        verbose(VERB_ALGO, "done with $INCLUDE %s",
1542
0
          incfile);
1543
0
        free(incfile);
1544
0
        state->lineno = lineno_orig;
1545
0
      }
1546
0
      continue;
1547
0
    }
1548
0
    if(status != 0) {
1549
0
      log_err("parse error %s %d:%d: %s", fname,
1550
0
        state->lineno, LDNS_WIREPARSE_OFFSET(status),
1551
0
        sldns_get_errorstr_parse(status));
1552
0
      return 0;
1553
0
    }
1554
0
    if(rr_len == 0) {
1555
      /* EMPTY line, TTL or ORIGIN */
1556
0
      continue;
1557
0
    }
1558
    /* insert wirerr in rrbuf */
1559
0
    if(!az_insert_rr(z, rr, rr_len, dname_len, NULL)) {
1560
0
      char buf[17];
1561
0
      sldns_wire2str_type_buf(sldns_wirerr_get_type(rr,
1562
0
        rr_len, dname_len), buf, sizeof(buf));
1563
0
      log_err("%s:%d cannot insert RR of type %s",
1564
0
        fname, state->lineno, buf);
1565
0
      return 0;
1566
0
    }
1567
0
  }
1568
0
  return 1;
1569
0
}
1570
1571
int
1572
auth_zone_read_zonefile(struct auth_zone* z, struct config_file* cfg)
1573
0
{
1574
0
  uint8_t rr[LDNS_RR_BUF_SIZE];
1575
0
  struct sldns_file_parse_state state;
1576
0
  char* zfilename;
1577
0
  FILE* in;
1578
0
  if(!z || !z->zonefile || z->zonefile[0]==0)
1579
0
    return 1; /* no file, or "", nothing to read */
1580
  
1581
0
  zfilename = z->zonefile;
1582
0
  if(cfg->chrootdir && cfg->chrootdir[0] && strncmp(zfilename,
1583
0
    cfg->chrootdir, strlen(cfg->chrootdir)) == 0)
1584
0
    zfilename += strlen(cfg->chrootdir);
1585
0
  if(verbosity >= VERB_ALGO) {
1586
0
    char nm[LDNS_MAX_DOMAINLEN];
1587
0
    dname_str(z->name, nm);
1588
0
    verbose(VERB_ALGO, "read zonefile %s for %s", zfilename, nm);
1589
0
  }
1590
0
  in = fopen(zfilename, "r");
1591
0
  if(!in) {
1592
0
    char* n = sldns_wire2str_dname(z->name, z->namelen);
1593
0
    if(z->zone_is_slave && errno == ENOENT) {
1594
      /* we fetch the zone contents later, no file yet */
1595
0
      verbose(VERB_ALGO, "no zonefile %s for %s",
1596
0
        zfilename, n?n:"error");
1597
0
      free(n);
1598
0
      return 1;
1599
0
    }
1600
0
    log_err("cannot open zonefile %s for %s: %s",
1601
0
      zfilename, n?n:"error", strerror(errno));
1602
0
    free(n);
1603
0
    return 0;
1604
0
  }
1605
1606
  /* clear the data tree */
1607
0
  traverse_postorder(&z->data, auth_data_del, NULL);
1608
0
  rbtree_init(&z->data, &auth_data_cmp);
1609
  /* clear the RPZ policies */
1610
0
  if(z->rpz)
1611
0
    rpz_clear(z->rpz);
1612
1613
0
  memset(&state, 0, sizeof(state));
1614
  /* default TTL to 3600 */
1615
0
  state.default_ttl = 3600;
1616
  /* set $ORIGIN to the zone name */
1617
0
  if(z->namelen <= sizeof(state.origin)) {
1618
0
    memcpy(state.origin, z->name, z->namelen);
1619
0
    state.origin_len = z->namelen;
1620
0
  }
1621
  /* parse the (toplevel) file */
1622
0
  if(!az_parse_file(z, in, rr, sizeof(rr), &state, zfilename, 0, cfg)) {
1623
0
    char* n = sldns_wire2str_dname(z->name, z->namelen);
1624
0
    log_err("error parsing zonefile %s for %s",
1625
0
      zfilename, n?n:"error");
1626
0
    free(n);
1627
0
    fclose(in);
1628
0
    return 0;
1629
0
  }
1630
0
  fclose(in);
1631
1632
0
  if(z->rpz)
1633
0
    rpz_finish_config(z->rpz);
1634
0
  return 1;
1635
0
}
1636
1637
/** write buffer to file and check return codes */
1638
static int
1639
write_out(FILE* out, const char* str, size_t len)
1640
0
{
1641
0
  size_t r;
1642
0
  if(len == 0)
1643
0
    return 1;
1644
0
  r = fwrite(str, 1, len, out);
1645
0
  if(r == 0) {
1646
0
    log_err("write failed: %s", strerror(errno));
1647
0
    return 0;
1648
0
  } else if(r < len) {
1649
0
    log_err("write failed: too short (disk full?)");
1650
0
    return 0;
1651
0
  }
1652
0
  return 1;
1653
0
}
1654
1655
/** convert auth rr to string */
1656
static int
1657
auth_rr_to_string(uint8_t* nm, size_t nmlen, uint16_t tp, uint16_t cl,
1658
  struct packed_rrset_data* data, size_t i, char* s, size_t buflen)
1659
0
{
1660
0
  int w = 0;
1661
0
  size_t slen = buflen, datlen;
1662
0
  uint8_t* dat;
1663
0
  if(i >= data->count) tp = LDNS_RR_TYPE_RRSIG;
1664
0
  dat = nm;
1665
0
  datlen = nmlen;
1666
0
  w += sldns_wire2str_dname_scan(&dat, &datlen, &s, &slen, NULL, 0, NULL);
1667
0
  w += sldns_str_print(&s, &slen, "\t");
1668
0
  w += sldns_str_print(&s, &slen, "%lu\t", (unsigned long)data->rr_ttl[i]);
1669
0
  w += sldns_wire2str_class_print(&s, &slen, cl);
1670
0
  w += sldns_str_print(&s, &slen, "\t");
1671
0
  w += sldns_wire2str_type_print(&s, &slen, tp);
1672
0
  w += sldns_str_print(&s, &slen, "\t");
1673
0
  datlen = data->rr_len[i]-2;
1674
0
  dat = data->rr_data[i]+2;
1675
0
  w += sldns_wire2str_rdata_scan(&dat, &datlen, &s, &slen, tp, NULL, 0, NULL);
1676
1677
0
  if(tp == LDNS_RR_TYPE_DNSKEY) {
1678
0
    w += sldns_str_print(&s, &slen, " ;{id = %u}",
1679
0
      sldns_calc_keytag_raw(data->rr_data[i]+2,
1680
0
        data->rr_len[i]-2));
1681
0
  }
1682
0
  w += sldns_str_print(&s, &slen, "\n");
1683
1684
0
  if(w >= (int)buflen) {
1685
0
    log_nametypeclass(NO_VERBOSE, "RR too long to print", nm, tp, cl);
1686
0
    return 0;
1687
0
  }
1688
0
  return 1;
1689
0
}
1690
1691
/** write rrset to file */
1692
static int
1693
auth_zone_write_rrset(struct auth_zone* z, struct auth_data* node,
1694
  struct auth_rrset* r, FILE* out)
1695
0
{
1696
0
  size_t i, count = r->data->count + r->data->rrsig_count;
1697
0
  char buf[LDNS_RR_BUF_SIZE];
1698
0
  for(i=0; i<count; i++) {
1699
0
    if(!auth_rr_to_string(node->name, node->namelen, r->type,
1700
0
      z->dclass, r->data, i, buf, sizeof(buf))) {
1701
0
      verbose(VERB_ALGO, "failed to rr2str rr %d", (int)i);
1702
0
      continue;
1703
0
    }
1704
0
    if(!write_out(out, buf, strlen(buf)))
1705
0
      return 0;
1706
0
  }
1707
0
  return 1;
1708
0
}
1709
1710
/** write domain to file */
1711
static int
1712
auth_zone_write_domain(struct auth_zone* z, struct auth_data* n, FILE* out)
1713
0
{
1714
0
  struct auth_rrset* r;
1715
  /* if this is zone apex, write SOA first */
1716
0
  if(z->namelen == n->namelen) {
1717
0
    struct auth_rrset* soa = az_domain_rrset(n, LDNS_RR_TYPE_SOA);
1718
0
    if(soa) {
1719
0
      if(!auth_zone_write_rrset(z, n, soa, out))
1720
0
        return 0;
1721
0
    }
1722
0
  }
1723
  /* write all the RRsets for this domain */
1724
0
  for(r = n->rrsets; r; r = r->next) {
1725
0
    if(z->namelen == n->namelen &&
1726
0
      r->type == LDNS_RR_TYPE_SOA)
1727
0
      continue; /* skip SOA here */
1728
0
    if(!auth_zone_write_rrset(z, n, r, out))
1729
0
      return 0;
1730
0
  }
1731
0
  return 1;
1732
0
}
1733
1734
int auth_zone_write_file(struct auth_zone* z, const char* fname)
1735
0
{
1736
0
  FILE* out;
1737
0
  struct auth_data* n;
1738
0
  out = fopen(fname, "w");
1739
0
  if(!out) {
1740
0
    log_err("could not open %s: %s", fname, strerror(errno));
1741
0
    return 0;
1742
0
  }
1743
0
  RBTREE_FOR(n, struct auth_data*, &z->data) {
1744
0
    if(!auth_zone_write_domain(z, n, out)) {
1745
0
      log_err("could not write domain to %s", fname);
1746
0
      fclose(out);
1747
0
      return 0;
1748
0
    }
1749
0
  }
1750
0
  fclose(out);
1751
0
  return 1;
1752
0
}
1753
1754
/** offline verify for zonemd, while reading a zone file to immediately
1755
 * spot bad hashes in zonefile as they are read.
1756
 * Creates temp buffers, but uses anchors and validation environment
1757
 * from the module_env. */
1758
static void
1759
zonemd_offline_verify(struct auth_zone* z, struct module_env* env_for_val,
1760
  struct module_stack* mods)
1761
0
{
1762
0
  struct module_env env;
1763
0
  time_t now = 0;
1764
0
  if(!z->zonemd_check)
1765
0
    return;
1766
0
  env = *env_for_val;
1767
0
  env.scratch_buffer = sldns_buffer_new(env.cfg->msg_buffer_size);
1768
0
  if(!env.scratch_buffer) {
1769
0
    log_err("out of memory");
1770
0
    goto clean_exit;
1771
0
  }
1772
0
  env.scratch = regional_create();
1773
0
  if(!env.now) {
1774
0
    env.now = &now;
1775
0
    now = time(NULL);
1776
0
  }
1777
0
  if(!env.scratch) {
1778
0
    log_err("out of memory");
1779
0
    goto clean_exit;
1780
0
  }
1781
0
  auth_zone_verify_zonemd(z, &env, mods, NULL, 1, 0);
1782
1783
0
clean_exit:
1784
  /* clean up and exit */
1785
0
  sldns_buffer_free(env.scratch_buffer);
1786
0
  regional_destroy(env.scratch);
1787
0
}
1788
1789
/** read all auth zones from file (if they have) */
1790
static int
1791
auth_zones_read_zones(struct auth_zones* az, struct config_file* cfg,
1792
  struct module_env* env, struct module_stack* mods)
1793
0
{
1794
0
  struct auth_zone* z;
1795
0
  lock_rw_wrlock(&az->lock);
1796
0
  RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
1797
0
    lock_rw_wrlock(&z->lock);
1798
0
    if(!auth_zone_read_zonefile(z, cfg)) {
1799
0
      lock_rw_unlock(&z->lock);
1800
0
      lock_rw_unlock(&az->lock);
1801
0
      return 0;
1802
0
    }
1803
0
    if(z->zonefile && z->zonefile[0]!=0 && env)
1804
0
      zonemd_offline_verify(z, env, mods);
1805
0
    lock_rw_unlock(&z->lock);
1806
0
  }
1807
0
  lock_rw_unlock(&az->lock);
1808
0
  return 1;
1809
0
}
1810
1811
/** fetch the content of a ZONEMD RR from the rdata */
1812
static int zonemd_fetch_parameters(struct auth_rrset* zonemd_rrset, size_t i,
1813
  uint32_t* serial, int* scheme, int* hashalgo, uint8_t** hash,
1814
  size_t* hashlen)
1815
0
{
1816
0
  size_t rr_len;
1817
0
  uint8_t* rdata;
1818
0
  if(i >= zonemd_rrset->data->count)
1819
0
    return 0;
1820
0
  rr_len = zonemd_rrset->data->rr_len[i];
1821
0
  if(rr_len < 2+4+1+1)
1822
0
    return 0; /* too short, for rdlen+serial+scheme+algo */
1823
0
  rdata = zonemd_rrset->data->rr_data[i];
1824
0
  *serial = sldns_read_uint32(rdata+2);
1825
0
  *scheme = rdata[6];
1826
0
  *hashalgo = rdata[7];
1827
0
  *hashlen = rr_len - 8;
1828
0
  if(*hashlen == 0)
1829
0
    *hash = NULL;
1830
0
  else  *hash = rdata+8;
1831
0
  return 1;
1832
0
}
1833
1834
/**
1835
 * See if the ZONEMD scheme, hash occurs more than once.
1836
 * @param zonemd_rrset: the zonemd rrset to check with the RRs in it.
1837
 * @param index: index of the original, this is allowed to have that
1838
 *  scheme and hashalgo, but other RRs should not have it.
1839
 * @param scheme: the scheme to check for.
1840
 * @param hashalgo: the hash algorithm to check for.
1841
 * @return true if it occurs more than once.
1842
 */
1843
static int zonemd_is_duplicate_scheme_hash(struct auth_rrset* zonemd_rrset,
1844
  size_t index, int scheme, int hashalgo)
1845
0
{
1846
0
  size_t j;
1847
0
  for(j=0; j<zonemd_rrset->data->count; j++) {
1848
0
    uint32_t serial2 = 0;
1849
0
    int scheme2 = 0, hashalgo2 = 0;
1850
0
    uint8_t* hash2 = NULL;
1851
0
    size_t hashlen2 = 0;
1852
0
    if(index == j) {
1853
      /* this is the original */
1854
0
      continue;
1855
0
    }
1856
0
    if(!zonemd_fetch_parameters(zonemd_rrset, j, &serial2,
1857
0
      &scheme2, &hashalgo2, &hash2, &hashlen2)) {
1858
      /* malformed, skip it */
1859
0
      continue;
1860
0
    }
1861
0
    if(scheme == scheme2 && hashalgo == hashalgo2) {
1862
      /* duplicate scheme, hash */
1863
0
      verbose(VERB_ALGO, "zonemd duplicate for scheme %d "
1864
0
        "and hash %d", scheme, hashalgo);
1865
0
      return 1;
1866
0
    }
1867
0
  }
1868
0
  return 0;
1869
0
}
1870
1871
/**
1872
 * Check ZONEMDs if present for the auth zone.  Depending on config
1873
 * it can warn or fail on that.  Checks the hash of the ZONEMD.
1874
 * @param z: auth zone to check for.
1875
 *  caller must hold lock on zone.
1876
 * @param env: module env for temp buffers.
1877
 * @param reason: returned on failure.
1878
 * @return false on failure, true if hash checks out.
1879
 */
1880
static int auth_zone_zonemd_check_hash(struct auth_zone* z,
1881
  struct module_env* env, char** reason)
1882
0
{
1883
  /* loop over ZONEMDs and see which one is valid. if not print
1884
   * failure (depending on config) */
1885
0
  struct auth_data* apex;
1886
0
  struct auth_rrset* zonemd_rrset;
1887
0
  size_t i;
1888
0
  struct regional* region = NULL;
1889
0
  struct sldns_buffer* buf = NULL;
1890
0
  uint32_t soa_serial = 0;
1891
0
  char* unsupported_reason = NULL;
1892
0
  int only_unsupported = 1;
1893
0
  region = env->scratch;
1894
0
  regional_free_all(region);
1895
0
  buf = env->scratch_buffer;
1896
0
  if(!auth_zone_get_serial(z, &soa_serial)) {
1897
0
    *reason = "zone has no SOA serial";
1898
0
    return 0;
1899
0
  }
1900
1901
0
  apex = az_find_name(z, z->name, z->namelen);
1902
0
  if(!apex) {
1903
0
    *reason = "zone has no apex";
1904
0
    return 0;
1905
0
  }
1906
0
  zonemd_rrset = az_domain_rrset(apex, LDNS_RR_TYPE_ZONEMD);
1907
0
  if(!zonemd_rrset || zonemd_rrset->data->count==0) {
1908
0
    *reason = "zone has no ZONEMD";
1909
0
    return 0; /* no RRset or no RRs in rrset */
1910
0
  }
1911
1912
  /* we have a ZONEMD, check if it is correct */
1913
0
  for(i=0; i<zonemd_rrset->data->count; i++) {
1914
0
    uint32_t serial = 0;
1915
0
    int scheme = 0, hashalgo = 0;
1916
0
    uint8_t* hash = NULL;
1917
0
    size_t hashlen = 0;
1918
0
    if(!zonemd_fetch_parameters(zonemd_rrset, i, &serial, &scheme,
1919
0
      &hashalgo, &hash, &hashlen)) {
1920
      /* malformed RR */
1921
0
      *reason = "ZONEMD rdata malformed";
1922
0
      only_unsupported = 0;
1923
0
      continue;
1924
0
    }
1925
    /* check for duplicates */
1926
0
    if(zonemd_is_duplicate_scheme_hash(zonemd_rrset, i, scheme,
1927
0
      hashalgo)) {
1928
      /* duplicate hash of the same scheme,hash
1929
       * is not allowed. */
1930
0
      *reason = "ZONEMD RRSet contains more than one RR "
1931
0
        "with the same scheme and hash algorithm";
1932
0
      only_unsupported = 0;
1933
0
      continue;
1934
0
    }
1935
0
    regional_free_all(region);
1936
0
    if(serial != soa_serial) {
1937
0
      *reason = "ZONEMD serial is wrong";
1938
0
      only_unsupported = 0;
1939
0
      continue;
1940
0
    }
1941
0
    *reason = NULL;
1942
0
    if(auth_zone_generate_zonemd_check(z, scheme, hashalgo,
1943
0
      hash, hashlen, region, buf, reason)) {
1944
      /* success */
1945
0
      if(*reason) {
1946
0
        if(!unsupported_reason)
1947
0
          unsupported_reason = *reason;
1948
        /* continue to check for valid ZONEMD */
1949
0
        if(verbosity >= VERB_ALGO) {
1950
0
          char zstr[LDNS_MAX_DOMAINLEN];
1951
0
          dname_str(z->name, zstr);
1952
0
          verbose(VERB_ALGO, "auth-zone %s ZONEMD %d %d is unsupported: %s", zstr, (int)scheme, (int)hashalgo, *reason);
1953
0
        }
1954
0
        *reason = NULL;
1955
0
        continue;
1956
0
      }
1957
0
      if(verbosity >= VERB_ALGO) {
1958
0
        char zstr[LDNS_MAX_DOMAINLEN];
1959
0
        dname_str(z->name, zstr);
1960
0
        if(!*reason)
1961
0
          verbose(VERB_ALGO, "auth-zone %s ZONEMD hash is correct", zstr);
1962
0
      }
1963
0
      return 1;
1964
0
    }
1965
0
    only_unsupported = 0;
1966
    /* try next one */
1967
0
  }
1968
  /* have we seen no failures but only unsupported algo,
1969
   * and one unsupported algorithm, or more. */
1970
0
  if(only_unsupported && unsupported_reason) {
1971
    /* only unsupported algorithms, with valid serial, not
1972
     * malformed. Did not see supported algorithms, failed or
1973
     * successful ones. */
1974
0
    *reason = unsupported_reason;
1975
0
    return 1;
1976
0
  }
1977
  /* fail, we may have reason */
1978
0
  if(!*reason)
1979
0
    *reason = "no ZONEMD records found";
1980
0
  if(verbosity >= VERB_ALGO) {
1981
0
    char zstr[LDNS_MAX_DOMAINLEN];
1982
0
    dname_str(z->name, zstr);
1983
0
    verbose(VERB_ALGO, "auth-zone %s ZONEMD failed: %s", zstr, *reason);
1984
0
  }
1985
0
  return 0;
1986
0
}
1987
1988
/** find the apex SOA RRset, if it exists */
1989
struct auth_rrset* auth_zone_get_soa_rrset(struct auth_zone* z)
1990
0
{
1991
0
  struct auth_data* apex;
1992
0
  struct auth_rrset* soa;
1993
0
  apex = az_find_name(z, z->name, z->namelen);
1994
0
  if(!apex) return NULL;
1995
0
  soa = az_domain_rrset(apex, LDNS_RR_TYPE_SOA);
1996
0
  return soa;
1997
0
}
1998
1999
/** find serial number of zone or false if none */
2000
int
2001
auth_zone_get_serial(struct auth_zone* z, uint32_t* serial)
2002
0
{
2003
0
  struct auth_data* apex;
2004
0
  struct auth_rrset* soa;
2005
0
  struct packed_rrset_data* d;
2006
0
  apex = az_find_name(z, z->name, z->namelen);
2007
0
  if(!apex) return 0;
2008
0
  soa = az_domain_rrset(apex, LDNS_RR_TYPE_SOA);
2009
0
  if(!soa || soa->data->count==0)
2010
0
    return 0; /* no RRset or no RRs in rrset */
2011
0
  if(soa->data->rr_len[0] < 2+4*5) return 0; /* SOA too short */
2012
0
  d = soa->data;
2013
0
  *serial = sldns_read_uint32(d->rr_data[0]+(d->rr_len[0]-20));
2014
0
  return 1;
2015
0
}
2016
2017
/** Find auth_zone SOA and populate the values in xfr(soa values). */
2018
int
2019
xfr_find_soa(struct auth_zone* z, struct auth_xfer* xfr)
2020
0
{
2021
0
  struct auth_data* apex;
2022
0
  struct auth_rrset* soa;
2023
0
  struct packed_rrset_data* d;
2024
0
  apex = az_find_name(z, z->name, z->namelen);
2025
0
  if(!apex) return 0;
2026
0
  soa = az_domain_rrset(apex, LDNS_RR_TYPE_SOA);
2027
0
  if(!soa || soa->data->count==0)
2028
0
    return 0; /* no RRset or no RRs in rrset */
2029
0
  if(soa->data->rr_len[0] < 2+4*5) return 0; /* SOA too short */
2030
  /* SOA record ends with serial, refresh, retry, expiry, minimum,
2031
   * as 4 byte fields */
2032
0
  d = soa->data;
2033
0
  xfr->have_zone = 1;
2034
0
  xfr->serial = sldns_read_uint32(d->rr_data[0]+(d->rr_len[0]-20));
2035
0
  xfr->refresh = sldns_read_uint32(d->rr_data[0]+(d->rr_len[0]-16));
2036
0
  xfr->retry = sldns_read_uint32(d->rr_data[0]+(d->rr_len[0]-12));
2037
0
  xfr->expiry = sldns_read_uint32(d->rr_data[0]+(d->rr_len[0]-8));
2038
  /* soa minimum at d->rr_len[0]-4 */
2039
0
  return 1;
2040
0
}
2041
2042
/** 
2043
 * Setup auth_xfer zone
2044
 * This populates the have_zone, soa values, and so on times.
2045
 * Doesn't do network traffic yet, can set option flags.
2046
 * @param z: locked by caller, and modified for setup
2047
 * @param x: locked by caller, and modified.
2048
 * @return false on failure.
2049
 */
2050
static int
2051
auth_xfer_setup(struct auth_zone* z, struct auth_xfer* x)
2052
0
{
2053
  /* for a zone without zone transfers, x==NULL, so skip them,
2054
   * i.e. the zone config is fixed with no masters or urls */
2055
0
  if(!z || !x) return 1;
2056
0
  if(!xfr_find_soa(z, x)) {
2057
0
    return 1;
2058
0
  }
2059
  /* nothing for probe, nextprobe and transfer tasks */
2060
0
  return 1;
2061
0
}
2062
2063
/**
2064
 * Setup all zones
2065
 * @param az: auth zones structure
2066
 * @return false on failure.
2067
 */
2068
static int
2069
auth_zones_setup_zones(struct auth_zones* az)
2070
0
{
2071
0
  struct auth_zone* z;
2072
0
  struct auth_xfer* x;
2073
0
  lock_rw_wrlock(&az->lock);
2074
0
  RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
2075
0
    lock_rw_wrlock(&z->lock);
2076
0
    x = auth_xfer_find(az, z->name, z->namelen, z->dclass);
2077
0
    if(x) {
2078
0
      lock_basic_lock(&x->lock);
2079
0
    }
2080
0
    if(!auth_xfer_setup(z, x)) {
2081
0
      if(x) {
2082
0
        lock_basic_unlock(&x->lock);
2083
0
      }
2084
0
      lock_rw_unlock(&z->lock);
2085
0
      lock_rw_unlock(&az->lock);
2086
0
      return 0;
2087
0
    }
2088
0
    if(x) {
2089
0
      lock_basic_unlock(&x->lock);
2090
0
    }
2091
0
    lock_rw_unlock(&z->lock);
2092
0
  }
2093
0
  lock_rw_unlock(&az->lock);
2094
0
  return 1;
2095
0
}
2096
2097
/** set config items and create zones */
2098
static int
2099
auth_zones_cfg(struct auth_zones* az, struct config_auth* c)
2100
0
{
2101
0
  struct auth_zone* z;
2102
0
  struct auth_xfer* x = NULL;
2103
2104
  /* create zone */
2105
0
  if(c->isrpz) {
2106
    /* if the rpz lock is needed, grab it before the other
2107
     * locks to avoid a lock dependency cycle */
2108
0
    lock_rw_wrlock(&az->rpz_lock);
2109
0
  }
2110
0
  lock_rw_wrlock(&az->lock);
2111
0
  if(!(z=auth_zones_find_or_add_zone(az, c->name))) {
2112
0
    lock_rw_unlock(&az->lock);
2113
0
    if(c->isrpz) {
2114
0
      lock_rw_unlock(&az->rpz_lock);
2115
0
    }
2116
0
    return 0;
2117
0
  }
2118
0
  if(c->masters || c->urls) {
2119
0
    if(!(x=auth_zones_find_or_add_xfer(az, z))) {
2120
0
      lock_rw_unlock(&az->lock);
2121
0
      lock_rw_unlock(&z->lock);
2122
0
      if(c->isrpz) {
2123
0
        lock_rw_unlock(&az->rpz_lock);
2124
0
      }
2125
0
      return 0;
2126
0
    }
2127
0
  }
2128
0
  if(c->for_downstream)
2129
0
    az->have_downstream = 1;
2130
0
  lock_rw_unlock(&az->lock);
2131
2132
  /* set options */
2133
0
  z->zone_deleted = 0;
2134
0
  if(!auth_zone_set_zonefile(z, c->zonefile)) {
2135
0
    if(x) {
2136
0
      lock_basic_unlock(&x->lock);
2137
0
    }
2138
0
    lock_rw_unlock(&z->lock);
2139
0
    if(c->isrpz) {
2140
0
      lock_rw_unlock(&az->rpz_lock);
2141
0
    }
2142
0
    return 0;
2143
0
  }
2144
0
  z->for_downstream = c->for_downstream;
2145
0
  z->for_upstream = c->for_upstream;
2146
0
  z->fallback_enabled = c->fallback_enabled;
2147
0
  z->zonemd_check = c->zonemd_check;
2148
0
  z->zonemd_reject_absence = c->zonemd_reject_absence;
2149
0
  if(c->isrpz && !z->rpz){
2150
0
    if(!(z->rpz = rpz_create(c))){
2151
0
      fatal_exit("Could not setup RPZ zones");
2152
0
      return 0;
2153
0
    }
2154
0
    lock_protect(&z->lock, &z->rpz->local_zones, sizeof(*z->rpz));
2155
    /* the az->rpz_lock is locked above */
2156
0
    z->rpz_az_next = az->rpz_first;
2157
0
    if(az->rpz_first)
2158
0
      az->rpz_first->rpz_az_prev = z;
2159
0
    az->rpz_first = z;
2160
0
  } else if(c->isrpz && z->rpz) {
2161
0
    if(!rpz_config(z->rpz, c)) {
2162
0
      log_err("Could not change rpz config");
2163
0
      if(x) {
2164
0
        lock_basic_unlock(&x->lock);
2165
0
      }
2166
0
      lock_rw_unlock(&z->lock);
2167
0
      lock_rw_unlock(&az->rpz_lock);
2168
0
      return 0;
2169
0
    }
2170
0
  }
2171
0
  if(c->isrpz) {
2172
0
    lock_rw_unlock(&az->rpz_lock);
2173
0
  }
2174
2175
  /* xfer zone */
2176
0
  if(x) {
2177
0
    z->zone_is_slave = 1;
2178
    /* set options on xfer zone */
2179
0
    if(!xfer_set_masters(&x->task_probe->masters, c, 0)) {
2180
0
      lock_basic_unlock(&x->lock);
2181
0
      lock_rw_unlock(&z->lock);
2182
0
      return 0;
2183
0
    }
2184
0
    if(!xfer_set_masters(&x->task_transfer->masters, c, 1)) {
2185
0
      lock_basic_unlock(&x->lock);
2186
0
      lock_rw_unlock(&z->lock);
2187
0
      return 0;
2188
0
    }
2189
0
    lock_basic_unlock(&x->lock);
2190
0
  }
2191
2192
0
  lock_rw_unlock(&z->lock);
2193
0
  return 1;
2194
0
}
2195
2196
/** set all auth zones deleted, then in auth_zones_cfg, it marks them
2197
 * as nondeleted (if they are still in the config), and then later
2198
 * we can find deleted zones */
2199
static void
2200
az_setall_deleted(struct auth_zones* az)
2201
0
{
2202
0
  struct auth_zone* z;
2203
0
  lock_rw_wrlock(&az->lock);
2204
0
  RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
2205
0
    lock_rw_wrlock(&z->lock);
2206
0
    z->zone_deleted = 1;
2207
0
    lock_rw_unlock(&z->lock);
2208
0
  }
2209
0
  lock_rw_unlock(&az->lock);
2210
0
}
2211
2212
/** find zones that are marked deleted and delete them.
2213
 * This is called from apply_cfg, and there are no threads and no
2214
 * workers, so the xfr can just be deleted. */
2215
static void
2216
az_delete_deleted_zones(struct auth_zones* az)
2217
0
{
2218
0
  struct auth_zone* z;
2219
0
  struct auth_zone* delete_list = NULL, *next;
2220
0
  struct auth_xfer* xfr;
2221
0
  lock_rw_wrlock(&az->lock);
2222
0
  RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
2223
0
    lock_rw_wrlock(&z->lock);
2224
0
    if(z->zone_deleted) {
2225
      /* we cannot alter the rbtree right now, but
2226
       * we can put it on a linked list and then
2227
       * delete it */
2228
0
      z->delete_next = delete_list;
2229
0
      delete_list = z;
2230
0
    }
2231
0
    lock_rw_unlock(&z->lock);
2232
0
  }
2233
  /* now we are out of the tree loop and we can loop and delete
2234
   * the zones */
2235
0
  z = delete_list;
2236
0
  while(z) {
2237
0
    next = z->delete_next;
2238
0
    xfr = auth_xfer_find(az, z->name, z->namelen, z->dclass);
2239
0
    if(xfr) {
2240
0
      (void)rbtree_delete(&az->xtree, &xfr->node);
2241
0
      auth_xfer_delete(xfr);
2242
0
    }
2243
0
    (void)rbtree_delete(&az->ztree, &z->node);
2244
0
    auth_zone_delete(z, az);
2245
0
    z = next;
2246
0
  }
2247
0
  lock_rw_unlock(&az->lock);
2248
0
}
2249
2250
int auth_zones_apply_cfg(struct auth_zones* az, struct config_file* cfg,
2251
  int setup, int* is_rpz, struct module_env* env,
2252
  struct module_stack* mods)
2253
0
{
2254
0
  struct config_auth* p;
2255
0
  az_setall_deleted(az);
2256
0
  for(p = cfg->auths; p; p = p->next) {
2257
0
    if(!p->name || p->name[0] == 0) {
2258
0
      log_warn("auth-zone without a name, skipped");
2259
0
      continue;
2260
0
    }
2261
0
    *is_rpz = (*is_rpz || p->isrpz);
2262
0
    if(!auth_zones_cfg(az, p)) {
2263
0
      log_err("cannot config auth zone %s", p->name);
2264
0
      return 0;
2265
0
    }
2266
0
  }
2267
0
  az_delete_deleted_zones(az);
2268
0
  if(!auth_zones_read_zones(az, cfg, env, mods))
2269
0
    return 0;
2270
0
  if(setup) {
2271
0
    if(!auth_zones_setup_zones(az))
2272
0
      return 0;
2273
0
  }
2274
0
  return 1;
2275
0
}
2276
2277
/** delete chunks
2278
 * @param at: transfer structure with chunks list.  The chunks and their
2279
 *  data are freed.
2280
 */
2281
static void
2282
auth_chunks_delete(struct auth_transfer* at)
2283
0
{
2284
0
  if(at->chunks_first) {
2285
0
    struct auth_chunk* c, *cn;
2286
0
    c = at->chunks_first;
2287
0
    while(c) {
2288
0
      cn = c->next;
2289
0
      free(c->data);
2290
0
      free(c);
2291
0
      c = cn;
2292
0
    }
2293
0
  }
2294
0
  at->chunks_first = NULL;
2295
0
  at->chunks_last = NULL;
2296
0
}
2297
2298
/** free master addr list */
2299
static void
2300
auth_free_master_addrs(struct auth_addr* list)
2301
0
{
2302
0
  struct auth_addr *n;
2303
0
  while(list) {
2304
0
    n = list->next;
2305
0
    free(list);
2306
0
    list = n;
2307
0
  }
2308
0
}
2309
2310
/** free the masters list */
2311
static void
2312
auth_free_masters(struct auth_master* list)
2313
0
{
2314
0
  struct auth_master* n;
2315
0
  while(list) {
2316
0
    n = list->next;
2317
0
    auth_free_master_addrs(list->list);
2318
0
    free(list->host);
2319
0
    free(list->file);
2320
0
    free(list);
2321
0
    list = n;
2322
0
  }
2323
0
}
2324
2325
void
2326
auth_xfer_delete(struct auth_xfer* xfr)
2327
0
{
2328
0
  if(!xfr) return;
2329
0
  lock_basic_destroy(&xfr->lock);
2330
0
  free(xfr->name);
2331
0
  if(xfr->task_nextprobe) {
2332
0
    comm_timer_delete(xfr->task_nextprobe->timer);
2333
0
    free(xfr->task_nextprobe);
2334
0
  }
2335
0
  if(xfr->task_probe) {
2336
0
    auth_free_masters(xfr->task_probe->masters);
2337
0
    comm_point_delete(xfr->task_probe->cp);
2338
0
    comm_timer_delete(xfr->task_probe->timer);
2339
0
    free(xfr->task_probe);
2340
0
  }
2341
0
  if(xfr->task_transfer) {
2342
0
    auth_free_masters(xfr->task_transfer->masters);
2343
0
    comm_point_delete(xfr->task_transfer->cp);
2344
0
    comm_timer_delete(xfr->task_transfer->timer);
2345
0
    if(xfr->task_transfer->chunks_first) {
2346
0
      auth_chunks_delete(xfr->task_transfer);
2347
0
    }
2348
0
    free(xfr->task_transfer);
2349
0
  }
2350
0
  auth_free_masters(xfr->allow_notify_list);
2351
0
  free(xfr);
2352
0
}
2353
2354
/** helper traverse to delete zones */
2355
static void
2356
auth_zone_del(rbnode_type* n, void* ATTR_UNUSED(arg))
2357
0
{
2358
0
  struct auth_zone* z = (struct auth_zone*)n->key;
2359
0
  auth_zone_delete(z, NULL);
2360
0
}
2361
2362
/** helper traverse to delete xfer zones */
2363
static void
2364
auth_xfer_del(rbnode_type* n, void* ATTR_UNUSED(arg))
2365
0
{
2366
0
  struct auth_xfer* z = (struct auth_xfer*)n->key;
2367
0
  auth_xfer_delete(z);
2368
0
}
2369
2370
void auth_zones_delete(struct auth_zones* az)
2371
0
{
2372
0
  if(!az) return;
2373
0
  lock_rw_destroy(&az->lock);
2374
0
  lock_rw_destroy(&az->rpz_lock);
2375
0
  traverse_postorder(&az->ztree, auth_zone_del, NULL);
2376
0
  traverse_postorder(&az->xtree, auth_xfer_del, NULL);
2377
0
  free(az);
2378
0
}
2379
2380
/** true if domain has only nsec3 */
2381
static int
2382
domain_has_only_nsec3(struct auth_data* n)
2383
0
{
2384
0
  struct auth_rrset* rrset = n->rrsets;
2385
0
  int nsec3_seen = 0;
2386
0
  while(rrset) {
2387
0
    if(rrset->type == LDNS_RR_TYPE_NSEC3) {
2388
0
      nsec3_seen = 1;
2389
0
    } else if(rrset->type != LDNS_RR_TYPE_RRSIG) {
2390
0
      return 0;
2391
0
    }
2392
0
    rrset = rrset->next;
2393
0
  }
2394
0
  return nsec3_seen;
2395
0
}
2396
2397
/** see if the domain has a wildcard child '*.domain' */
2398
static struct auth_data*
2399
az_find_wildcard_domain(struct auth_zone* z, uint8_t* nm, size_t nmlen)
2400
0
{
2401
0
  uint8_t wc[LDNS_MAX_DOMAINLEN];
2402
0
  if(nmlen+2 > sizeof(wc))
2403
0
    return NULL; /* result would be too long */
2404
0
  wc[0] = 1; /* length of wildcard label */
2405
0
  wc[1] = (uint8_t)'*'; /* wildcard label */
2406
0
  memmove(wc+2, nm, nmlen);
2407
0
  return az_find_name(z, wc, nmlen+2);
2408
0
}
2409
2410
/** find wildcard between qname and cename */
2411
static struct auth_data*
2412
az_find_wildcard(struct auth_zone* z, struct query_info* qinfo,
2413
  struct auth_data* ce)
2414
0
{
2415
0
  uint8_t* nm = qinfo->qname;
2416
0
  size_t nmlen = qinfo->qname_len;
2417
0
  struct auth_data* node;
2418
0
  if(!dname_subdomain_c(nm, z->name))
2419
0
    return NULL; /* out of zone */
2420
0
  while((node=az_find_wildcard_domain(z, nm, nmlen))==NULL) {
2421
0
    if(nmlen == z->namelen)
2422
0
      return NULL; /* top of zone reached */
2423
0
    if(ce && nmlen == ce->namelen)
2424
0
      return NULL; /* ce reached */
2425
0
    if(!dname_remove_label_limit_len(&nm, &nmlen, z->namelen))
2426
0
      return NULL; /* can't go up */
2427
0
  }
2428
0
  return node;
2429
0
}
2430
2431
/** domain is not exact, find first candidate ce (name that matches
2432
 * a part of qname) in tree */
2433
static struct auth_data*
2434
az_find_candidate_ce(struct auth_zone* z, struct query_info* qinfo,
2435
  struct auth_data* n)
2436
0
{
2437
0
  uint8_t* nm;
2438
0
  size_t nmlen;
2439
0
  if(n) {
2440
0
    nm = dname_get_shared_topdomain(qinfo->qname, n->name);
2441
0
  } else {
2442
0
    nm = qinfo->qname;
2443
0
  }
2444
0
  dname_count_size_labels(nm, &nmlen);
2445
0
  n = az_find_name(z, nm, nmlen);
2446
  /* delete labels and go up on name */
2447
0
  while(!n) {
2448
0
    if(!dname_remove_label_limit_len(&nm, &nmlen, z->namelen))
2449
0
      return NULL; /* can't go up */
2450
0
    n = az_find_name(z, nm, nmlen);
2451
0
  }
2452
0
  return n;
2453
0
}
2454
2455
/** go up the auth tree to next existing name. */
2456
static struct auth_data*
2457
az_domain_go_up(struct auth_zone* z, struct auth_data* n)
2458
0
{
2459
0
  uint8_t* nm = n->name;
2460
0
  size_t nmlen = n->namelen;
2461
0
  while(dname_remove_label_limit_len(&nm, &nmlen, z->namelen)) {
2462
0
    if((n=az_find_name(z, nm, nmlen)) != NULL)
2463
0
      return n;
2464
0
  }
2465
0
  return NULL;
2466
0
}
2467
2468
/** Find the closest encloser, an name that exists and is above the
2469
 * qname.
2470
 * return true if the node (param node) is existing, nonobscured and
2471
 *  can be used to generate answers from.  It is then also node_exact.
2472
 * returns false if the node is not good enough (or it wasn't node_exact)
2473
 *  in this case the ce can be filled.
2474
 *  if ce is NULL, no ce exists, and likely the zone is completely empty,
2475
 *  not even with a zone apex.
2476
 *  if ce is nonNULL it is the closest enclosing upper name (that exists
2477
 *  itself for answer purposes).  That name may have DNAME, NS or wildcard
2478
 *  rrset is the closest DNAME or NS rrset that was found.
2479
 */
2480
static int
2481
az_find_ce(struct auth_zone* z, struct query_info* qinfo,
2482
  struct auth_data* node, int node_exact, struct auth_data** ce,
2483
  struct auth_rrset** rrset)
2484
0
{
2485
0
  struct auth_data* n = node;
2486
0
  struct auth_rrset* lookrrset;
2487
0
  *ce = NULL;
2488
0
  *rrset = NULL;
2489
0
  if(!node_exact) {
2490
    /* if not exact, lookup closest exact match */
2491
0
    n = az_find_candidate_ce(z, qinfo, n);
2492
0
  } else {
2493
    /* if exact, the node itself is the first candidate ce */
2494
0
    *ce = n;
2495
0
  }
2496
2497
  /* no direct answer from nsec3-only domains */
2498
0
  if(n && domain_has_only_nsec3(n)) {
2499
0
    node_exact = 0;
2500
0
    *ce = NULL;
2501
0
  }
2502
2503
  /* with exact matches, walk up the labels until we find the
2504
   * delegation, or DNAME or zone end */
2505
0
  while(n) {
2506
    /* see if the current candidate has issues */
2507
    /* not zone apex and has type NS */
2508
0
    if(n->namelen != z->namelen &&
2509
0
      (lookrrset=az_domain_rrset(n, LDNS_RR_TYPE_NS)) &&
2510
      /* delegate here, but DS at exact the dp has notype */
2511
0
      (qinfo->qtype != LDNS_RR_TYPE_DS || 
2512
0
      n->namelen != qinfo->qname_len)) {
2513
      /* referral */
2514
      /* this is ce and the lowernode is nonexisting */
2515
0
      *ce = n;
2516
0
      *rrset = lookrrset;
2517
0
      node_exact = 0;
2518
0
    }
2519
    /* not equal to qname and has type DNAME */
2520
0
    if(n->namelen != qinfo->qname_len &&
2521
0
      (lookrrset=az_domain_rrset(n, LDNS_RR_TYPE_DNAME))) {
2522
      /* this is ce and the lowernode is nonexisting */
2523
0
      *ce = n;
2524
0
      *rrset = lookrrset;
2525
0
      node_exact = 0;
2526
0
    }
2527
2528
0
    if(*ce == NULL && !domain_has_only_nsec3(n)) {
2529
      /* if not found yet, this exact name must be
2530
       * our lowest match (but not nsec3onlydomain) */
2531
0
      *ce = n;
2532
0
    }
2533
2534
    /* walk up the tree by removing labels from name and lookup */
2535
0
    n = az_domain_go_up(z, n);
2536
0
  }
2537
  /* found no problems, if it was an exact node, it is fine to use */
2538
0
  return node_exact;
2539
0
}
2540
2541
/** add additional A/AAAA from domain names in rrset rdata (+offset)
2542
 * offset is number of bytes in rdata where the dname is located. */
2543
static int
2544
az_add_additionals_from(struct auth_zone* z, struct regional* region,
2545
  struct dns_msg* msg, struct auth_rrset* rrset, size_t offset)
2546
0
{
2547
0
  struct packed_rrset_data* d = rrset->data;
2548
0
  size_t i;
2549
0
  if(!d) return 0;
2550
0
  for(i=0; i<d->count; i++) {
2551
0
    size_t dlen;
2552
0
    struct auth_data* domain;
2553
0
    struct auth_rrset* ref;
2554
0
    if(d->rr_len[i] < 2+offset)
2555
0
      continue; /* too short */
2556
0
    if(!(dlen = dname_valid(d->rr_data[i]+2+offset,
2557
0
      d->rr_len[i]-2-offset)))
2558
0
      continue; /* malformed */
2559
0
    domain = az_find_name(z, d->rr_data[i]+2+offset, dlen);
2560
0
    if(!domain)
2561
0
      continue;
2562
0
    if((ref=az_domain_rrset(domain, LDNS_RR_TYPE_A)) != NULL) {
2563
0
      if(!msg_add_rrset_ar(z, region, msg, domain, ref))
2564
0
        return 0;
2565
0
    }
2566
0
    if((ref=az_domain_rrset(domain, LDNS_RR_TYPE_AAAA)) != NULL) {
2567
0
      if(!msg_add_rrset_ar(z, region, msg, domain, ref))
2568
0
        return 0;
2569
0
    }
2570
0
  }
2571
0
  return 1;
2572
0
}
2573
2574
/** add negative SOA record (with negative TTL) */
2575
static int
2576
az_add_negative_soa(struct auth_zone* z, struct regional* region,
2577
  struct dns_msg* msg)
2578
0
{
2579
0
  time_t minimum;
2580
0
  size_t i;
2581
0
  struct packed_rrset_data* d;
2582
0
  struct auth_rrset* soa;
2583
0
  struct auth_data* apex = az_find_name(z, z->name, z->namelen);
2584
0
  if(!apex) return 0;
2585
0
  soa = az_domain_rrset(apex, LDNS_RR_TYPE_SOA);
2586
0
  if(!soa) return 0;
2587
  /* must be first to put in message; we want to fix the TTL with
2588
   * one RRset here, otherwise we'd need to loop over the RRs to get
2589
   * the resulting lower TTL */
2590
0
  log_assert(msg->rep->rrset_count == 0);
2591
0
  if(!msg_add_rrset_ns(z, region, msg, apex, soa)) return 0;
2592
  /* fixup TTL */
2593
0
  d = (struct packed_rrset_data*)msg->rep->rrsets[msg->rep->rrset_count-1]->entry.data;
2594
  /* last 4 bytes are minimum ttl in network format */
2595
0
  if(d->count == 0) return 0;
2596
0
  if(d->rr_len[0] < 2+4) return 0;
2597
0
  minimum = (time_t)sldns_read_uint32(d->rr_data[0]+(d->rr_len[0]-4));
2598
0
  minimum = d->ttl<minimum?d->ttl:minimum;
2599
0
  d->ttl = minimum;
2600
0
  for(i=0; i < d->count + d->rrsig_count; i++)
2601
0
    d->rr_ttl[i] = minimum;
2602
0
  msg->rep->ttl = get_rrset_ttl(msg->rep->rrsets[0]);
2603
0
  msg->rep->prefetch_ttl = PREFETCH_TTL_CALC(msg->rep->ttl);
2604
0
  msg->rep->serve_expired_ttl = msg->rep->ttl + SERVE_EXPIRED_TTL;
2605
0
  return 1;
2606
0
}
2607
2608
/** See if the query goes to empty nonterminal (that has no auth_data,
2609
 * but there are nodes underneath.  We already checked that there are
2610
 * not NS, or DNAME above, so that we only need to check if some node
2611
 * exists below (with nonempty rr list), return true if emptynonterminal */
2612
static int
2613
az_empty_nonterminal(struct auth_zone* z, struct query_info* qinfo,
2614
  struct auth_data* node)
2615
0
{
2616
0
  struct auth_data* next;
2617
0
  if(!node) {
2618
    /* no smaller was found, use first (smallest) node as the
2619
     * next one */
2620
0
    next = (struct auth_data*)rbtree_first(&z->data);
2621
0
  } else {
2622
0
    next = (struct auth_data*)rbtree_next(&node->node);
2623
0
  }
2624
0
  while(next && (rbnode_type*)next != RBTREE_NULL && next->rrsets == NULL) {
2625
    /* the next name has empty rrsets, is an empty nonterminal
2626
     * itself, see if there exists something below it */
2627
0
    next = (struct auth_data*)rbtree_next(&node->node);
2628
0
  }
2629
0
  if((rbnode_type*)next == RBTREE_NULL || !next) {
2630
    /* there is no next node, so something below it cannot
2631
     * exist */
2632
0
    return 0;
2633
0
  }
2634
  /* a next node exists, if there was something below the query,
2635
   * this node has to be it.  See if it is below the query name */
2636
0
  if(dname_strict_subdomain_c(next->name, qinfo->qname))
2637
0
    return 1;
2638
0
  return 0;
2639
0
}
2640
2641
/** create synth cname target name in buffer, or fail if too long */
2642
static size_t
2643
synth_cname_buf(uint8_t* qname, size_t qname_len, size_t dname_len,
2644
  uint8_t* dtarg, size_t dtarglen, uint8_t* buf, size_t buflen)
2645
0
{
2646
0
  size_t newlen = qname_len + dtarglen - dname_len;
2647
0
  if(newlen > buflen) {
2648
    /* YXDOMAIN error */
2649
0
    return 0;
2650
0
  }
2651
  /* new name is concatenation of qname front (without DNAME owner)
2652
   * and DNAME target name */
2653
0
  memcpy(buf, qname, qname_len-dname_len);
2654
0
  memmove(buf+(qname_len-dname_len), dtarg, dtarglen);
2655
0
  return newlen;
2656
0
}
2657
2658
/** create synthetic CNAME rrset for in a DNAME answer in region,
2659
 * false on alloc failure, cname==NULL when name too long. */
2660
static int
2661
create_synth_cname(uint8_t* qname, size_t qname_len, struct regional* region,
2662
  struct auth_data* node, struct auth_rrset* dname, uint16_t dclass,
2663
  struct ub_packed_rrset_key** cname)
2664
0
{
2665
0
  uint8_t buf[LDNS_MAX_DOMAINLEN];
2666
0
  uint8_t* dtarg;
2667
0
  size_t dtarglen, newlen;
2668
0
  struct packed_rrset_data* d;
2669
2670
  /* get DNAME target name */
2671
0
  if(dname->data->count < 1) return 0;
2672
0
  if(dname->data->rr_len[0] < 3) return 0; /* at least rdatalen +1 */
2673
0
  dtarg = dname->data->rr_data[0]+2;
2674
0
  dtarglen = dname->data->rr_len[0]-2;
2675
0
  if(sldns_read_uint16(dname->data->rr_data[0]) != dtarglen)
2676
0
    return 0; /* rdatalen in DNAME rdata is malformed */
2677
0
  if(dname_valid(dtarg, dtarglen) != dtarglen)
2678
0
    return 0; /* DNAME RR has malformed rdata */
2679
0
  if(qname_len == 0)
2680
0
    return 0; /* too short */
2681
0
  if(qname_len <= node->namelen)
2682
0
    return 0; /* qname too short for dname removal */
2683
2684
  /* synthesize a CNAME */
2685
0
  newlen = synth_cname_buf(qname, qname_len, node->namelen,
2686
0
    dtarg, dtarglen, buf, sizeof(buf));
2687
0
  if(newlen == 0) {
2688
    /* YXDOMAIN error */
2689
0
    *cname = NULL;
2690
0
    return 1;
2691
0
  }
2692
0
  *cname = (struct ub_packed_rrset_key*)regional_alloc(region,
2693
0
    sizeof(struct ub_packed_rrset_key));
2694
0
  if(!*cname)
2695
0
    return 0; /* out of memory */
2696
0
  memset(&(*cname)->entry, 0, sizeof((*cname)->entry));
2697
0
  (*cname)->entry.key = (*cname);
2698
0
  (*cname)->rk.type = htons(LDNS_RR_TYPE_CNAME);
2699
0
  (*cname)->rk.rrset_class = htons(dclass);
2700
0
  (*cname)->rk.flags = 0;
2701
0
  (*cname)->rk.dname = regional_alloc_init(region, qname, qname_len);
2702
0
  if(!(*cname)->rk.dname)
2703
0
    return 0; /* out of memory */
2704
0
  (*cname)->rk.dname_len = qname_len;
2705
0
  (*cname)->entry.hash = rrset_key_hash(&(*cname)->rk);
2706
0
  d = (struct packed_rrset_data*)regional_alloc_zero(region,
2707
0
    sizeof(struct packed_rrset_data) + sizeof(size_t) +
2708
0
    sizeof(uint8_t*) + sizeof(time_t) + sizeof(uint16_t)
2709
0
    + newlen);
2710
0
  if(!d)
2711
0
    return 0; /* out of memory */
2712
0
  (*cname)->entry.data = d;
2713
0
  d->ttl = dname->data->ttl; /* RFC6672: synth CNAME TTL == DNAME TTL */
2714
0
  d->count = 1;
2715
0
  d->rrsig_count = 0;
2716
0
  d->trust = rrset_trust_ans_noAA;
2717
0
  d->rr_len = (size_t*)((uint8_t*)d +
2718
0
    sizeof(struct packed_rrset_data));
2719
0
  d->rr_len[0] = newlen + sizeof(uint16_t);
2720
0
  packed_rrset_ptr_fixup(d);
2721
0
  d->rr_ttl[0] = d->ttl;
2722
0
  sldns_write_uint16(d->rr_data[0], newlen);
2723
0
  memmove(d->rr_data[0] + sizeof(uint16_t), buf, newlen);
2724
0
  return 1;
2725
0
}
2726
2727
/** add a synthesized CNAME to the answer section */
2728
static int
2729
add_synth_cname(struct auth_zone* z, uint8_t* qname, size_t qname_len,
2730
  struct regional* region, struct dns_msg* msg, struct auth_data* dname,
2731
  struct auth_rrset* rrset)
2732
0
{
2733
0
  struct ub_packed_rrset_key* cname;
2734
  /* synthesize a CNAME */
2735
0
  if(!create_synth_cname(qname, qname_len, region, dname, rrset,
2736
0
    z->dclass, &cname)) {
2737
    /* out of memory */
2738
0
    return 0;
2739
0
  }
2740
0
  if(!cname) {
2741
    /* cname cannot be create because of YXDOMAIN */
2742
0
    msg->rep->flags |= LDNS_RCODE_YXDOMAIN;
2743
0
    return 1;
2744
0
  }
2745
  /* add cname to message */
2746
0
  if(!msg_grow_array(region, msg))
2747
0
    return 0;
2748
0
  msg->rep->rrsets[msg->rep->rrset_count] = cname;
2749
0
  msg->rep->rrset_count++;
2750
0
  msg->rep->an_numrrsets++;
2751
0
  msg_ttl(msg);
2752
0
  return 1;
2753
0
}
2754
2755
/** Change a dname to a different one, for wildcard namechange */
2756
static void
2757
az_change_dnames(struct dns_msg* msg, uint8_t* oldname, uint8_t* newname,
2758
  size_t newlen, int an_only)
2759
0
{
2760
0
  size_t i;
2761
0
  size_t start = 0, end = msg->rep->rrset_count;
2762
0
  if(!an_only) start = msg->rep->an_numrrsets;
2763
0
  if(an_only) end = msg->rep->an_numrrsets;
2764
0
  for(i=start; i<end; i++) {
2765
    /* allocated in region so we can change the ptrs */
2766
0
    if(query_dname_compare(msg->rep->rrsets[i]->rk.dname, oldname)
2767
0
      == 0) {
2768
0
      msg->rep->rrsets[i]->rk.dname = newname;
2769
0
      msg->rep->rrsets[i]->rk.dname_len = newlen;
2770
0
      msg->rep->rrsets[i]->entry.hash = rrset_key_hash(&msg->rep->rrsets[i]->rk);
2771
0
    }
2772
0
  }
2773
0
}
2774
2775
/** find NSEC record covering the query, with the given node in the zone */
2776
static struct auth_rrset*
2777
az_find_nsec_cover(struct auth_zone* z, struct auth_data** node)
2778
0
{
2779
0
  uint8_t* nm;
2780
0
  size_t nmlen;
2781
0
  struct auth_rrset* rrset;
2782
0
  log_assert(*node); /* we already have a node when calling this */
2783
0
  nm = (*node)->name;
2784
0
  nmlen = (*node)->namelen;
2785
  /* find the NSEC for the smallest-or-equal node */
2786
  /* But there could be glue, and then it has no NSEC.
2787
   * Go up to find nonglue (previous) NSEC-holding nodes */
2788
0
  while((rrset=az_domain_rrset(*node, LDNS_RR_TYPE_NSEC)) == NULL) {
2789
0
    if(nmlen == z->namelen) return NULL;
2790
0
    if(!dname_remove_label_limit_len(&nm, &nmlen, z->namelen))
2791
0
      return NULL; /* can't go up */
2792
    /* adjust *node for the nsec rrset to find in */
2793
0
    *node = az_find_name(z, nm, nmlen);
2794
0
  }
2795
0
  return rrset;
2796
0
}
2797
2798
/** Find NSEC and add for wildcard denial */
2799
static int
2800
az_nsec_wildcard_denial(struct auth_zone* z, struct regional* region,
2801
  struct dns_msg* msg, uint8_t* cenm, size_t cenmlen)
2802
0
{
2803
0
  struct query_info qinfo;
2804
0
  int node_exact;
2805
0
  struct auth_data* node;
2806
0
  struct auth_rrset* nsec;
2807
0
  uint8_t wc[LDNS_MAX_DOMAINLEN];
2808
0
  if(cenmlen+2 > sizeof(wc))
2809
0
    return 0; /* result would be too long */
2810
0
  wc[0] = 1; /* length of wildcard label */
2811
0
  wc[1] = (uint8_t)'*'; /* wildcard label */
2812
0
  memmove(wc+2, cenm, cenmlen);
2813
2814
  /* we have '*.ce' in wc wildcard name buffer */
2815
  /* get nsec cover for that */
2816
0
  qinfo.qname = wc;
2817
0
  qinfo.qname_len = cenmlen+2;
2818
0
  qinfo.qtype = 0;
2819
0
  qinfo.qclass = 0;
2820
0
  az_find_domain(z, &qinfo, &node_exact, &node);
2821
0
  if((nsec=az_find_nsec_cover(z, &node)) != NULL) {
2822
0
    if(!msg_add_rrset_ns(z, region, msg, node, nsec)) return 0;
2823
0
  }
2824
0
  return 1;
2825
0
}
2826
2827
/** Find the NSEC3PARAM rrset (if any) and if true you have the parameters */
2828
static int
2829
az_nsec3_param(struct auth_zone* z, int* algo, size_t* iter, uint8_t** salt,
2830
  size_t* saltlen)
2831
0
{
2832
0
  struct auth_data* apex;
2833
0
  struct auth_rrset* param;
2834
0
  size_t i;
2835
0
  apex = az_find_name(z, z->name, z->namelen);
2836
0
  if(!apex) return 0;
2837
0
  param = az_domain_rrset(apex, LDNS_RR_TYPE_NSEC3PARAM);
2838
0
  if(!param || param->data->count==0)
2839
0
    return 0; /* no RRset or no RRs in rrset */
2840
  /* find out which NSEC3PARAM RR has supported parameters */
2841
  /* skip unknown flags (dynamic signer is recalculating nsec3 chain) */
2842
0
  for(i=0; i<param->data->count; i++) {
2843
0
    uint8_t* rdata = param->data->rr_data[i]+2;
2844
0
    size_t rdatalen = param->data->rr_len[i];
2845
0
    if(rdatalen < 2+5)
2846
0
      continue; /* too short */
2847
0
    if(!nsec3_hash_algo_size_supported((int)(rdata[0])))
2848
0
      continue; /* unsupported algo */
2849
0
    if(rdatalen < (size_t)(2+5+(size_t)rdata[4]))
2850
0
      continue; /* salt missing */
2851
0
    if((rdata[1]&NSEC3_UNKNOWN_FLAGS)!=0)
2852
0
      continue; /* unknown flags */
2853
0
    *algo = (int)(rdata[0]);
2854
0
    *iter = sldns_read_uint16(rdata+2);
2855
0
    *saltlen = rdata[4];
2856
0
    if(*saltlen == 0)
2857
0
      *salt = NULL;
2858
0
    else  *salt = rdata+5;
2859
0
    return 1;
2860
0
  }
2861
  /* no supported params */
2862
0
  return 0;
2863
0
}
2864
2865
/** Hash a name with nsec3param into buffer, it has zone name appended.
2866
 * return length of hash */
2867
static size_t
2868
az_nsec3_hash(uint8_t* buf, size_t buflen, uint8_t* nm, size_t nmlen,
2869
  int algo, size_t iter, uint8_t* salt, size_t saltlen)
2870
0
{
2871
0
  size_t hlen = nsec3_hash_algo_size_supported(algo);
2872
  /* buffer has domain name, nsec3hash, and 256 is for max saltlen
2873
   * (salt has 0-255 length) */
2874
0
  unsigned char p[LDNS_MAX_DOMAINLEN+1+N3HASHBUFLEN+256];
2875
0
  size_t i;
2876
0
  if(nmlen+saltlen > sizeof(p) || hlen+saltlen > sizeof(p))
2877
0
    return 0;
2878
0
  if(hlen > buflen)
2879
0
    return 0; /* somehow too large for destination buffer */
2880
  /* hashfunc(name, salt) */
2881
0
  memmove(p, nm, nmlen);
2882
0
  query_dname_tolower(p);
2883
0
  if(salt && saltlen > 0)
2884
0
    memmove(p+nmlen, salt, saltlen);
2885
0
  (void)secalgo_nsec3_hash(algo, p, nmlen+saltlen, (unsigned char*)buf);
2886
0
  for(i=0; i<iter; i++) {
2887
    /* hashfunc(hash, salt) */
2888
0
    memmove(p, buf, hlen);
2889
0
    if(salt && saltlen > 0)
2890
0
      memmove(p+hlen, salt, saltlen);
2891
0
    (void)secalgo_nsec3_hash(algo, p, hlen+saltlen,
2892
0
      (unsigned char*)buf);
2893
0
  }
2894
0
  return hlen;
2895
0
}
2896
2897
/** Hash name and return b32encoded hashname for lookup, zone name appended */
2898
static int
2899
az_nsec3_hashname(struct auth_zone* z, uint8_t* hashname, size_t* hashnmlen,
2900
  uint8_t* nm, size_t nmlen, int algo, size_t iter, uint8_t* salt,
2901
  size_t saltlen)
2902
0
{
2903
0
  uint8_t hash[N3HASHBUFLEN];
2904
0
  size_t hlen;
2905
0
  int ret;
2906
0
  hlen = az_nsec3_hash(hash, sizeof(hash), nm, nmlen, algo, iter,
2907
0
    salt, saltlen);
2908
0
  if(!hlen) return 0;
2909
  /* b32 encode */
2910
0
  if(*hashnmlen < hlen*2+1+z->namelen) /* approx b32 as hexb16 */
2911
0
    return 0;
2912
0
  ret = sldns_b32_ntop_extended_hex(hash, hlen, (char*)(hashname+1),
2913
0
    (*hashnmlen)-1);
2914
0
  if(ret<1)
2915
0
    return 0;
2916
0
  hashname[0] = (uint8_t)ret;
2917
0
  ret++;
2918
0
  if((*hashnmlen) - ret < z->namelen)
2919
0
    return 0;
2920
0
  memmove(hashname+ret, z->name, z->namelen);
2921
0
  *hashnmlen = z->namelen+(size_t)ret;
2922
0
  return 1;
2923
0
}
2924
2925
/** Find the datanode that covers the nsec3hash-name */
2926
static struct auth_data*
2927
az_nsec3_findnode(struct auth_zone* z, uint8_t* hashnm, size_t hashnmlen)
2928
0
{
2929
0
  struct query_info qinfo;
2930
0
  struct auth_data* node;
2931
0
  int node_exact;
2932
0
  qinfo.qclass = 0;
2933
0
  qinfo.qtype = 0;
2934
0
  qinfo.qname = hashnm;
2935
0
  qinfo.qname_len = hashnmlen;
2936
  /* because canonical ordering and b32 nsec3 ordering are the same.
2937
   * this is a good lookup to find the nsec3 name. */
2938
0
  az_find_domain(z, &qinfo, &node_exact, &node);
2939
  /* but we may have to skip non-nsec3 nodes */
2940
  /* this may be a lot, the way to speed that up is to have a
2941
   * separate nsec3 tree with nsec3 nodes */
2942
0
  while(node && (rbnode_type*)node != RBTREE_NULL &&
2943
0
    !az_domain_rrset(node, LDNS_RR_TYPE_NSEC3)) {
2944
0
    node = (struct auth_data*)rbtree_previous(&node->node);
2945
0
  }
2946
0
  if((rbnode_type*)node == RBTREE_NULL)
2947
0
    node = NULL;
2948
0
  return node;
2949
0
}
2950
2951
/** Find cover for hashed(nm, nmlen) (or NULL) */
2952
static struct auth_data*
2953
az_nsec3_find_cover(struct auth_zone* z, uint8_t* nm, size_t nmlen,
2954
  int algo, size_t iter, uint8_t* salt, size_t saltlen)
2955
0
{
2956
0
  struct auth_data* node;
2957
0
  uint8_t hname[LDNS_MAX_DOMAINLEN];
2958
0
  size_t hlen = sizeof(hname);
2959
0
  if(!az_nsec3_hashname(z, hname, &hlen, nm, nmlen, algo, iter,
2960
0
    salt, saltlen))
2961
0
    return NULL;
2962
0
  node = az_nsec3_findnode(z, hname, hlen);
2963
0
  if(node)
2964
0
    return node;
2965
  /* we did not find any, perhaps because the NSEC3 hash is before
2966
   * the first hash, we have to find the 'last hash' in the zone */
2967
0
  node = (struct auth_data*)rbtree_last(&z->data);
2968
0
  while(node && (rbnode_type*)node != RBTREE_NULL &&
2969
0
    !az_domain_rrset(node, LDNS_RR_TYPE_NSEC3)) {
2970
0
    node = (struct auth_data*)rbtree_previous(&node->node);
2971
0
  }
2972
0
  if((rbnode_type*)node == RBTREE_NULL)
2973
0
    node = NULL;
2974
0
  return node;
2975
0
}
2976
2977
/** Find exact match for hashed(nm, nmlen) NSEC3 record or NULL */
2978
static struct auth_data*
2979
az_nsec3_find_exact(struct auth_zone* z, uint8_t* nm, size_t nmlen,
2980
  int algo, size_t iter, uint8_t* salt, size_t saltlen)
2981
0
{
2982
0
  struct auth_data* node;
2983
0
  uint8_t hname[LDNS_MAX_DOMAINLEN];
2984
0
  size_t hlen = sizeof(hname);
2985
0
  if(!az_nsec3_hashname(z, hname, &hlen, nm, nmlen, algo, iter,
2986
0
    salt, saltlen))
2987
0
    return NULL;
2988
0
  node = az_find_name(z, hname, hlen);
2989
0
  if(az_domain_rrset(node, LDNS_RR_TYPE_NSEC3))
2990
0
    return node;
2991
0
  return NULL;
2992
0
}
2993
2994
/** Return nextcloser name (as a ref into the qname).  This is one label
2995
 * more than the cenm (cename must be a suffix of qname) */
2996
static void
2997
az_nsec3_get_nextcloser(uint8_t* cenm, uint8_t* qname, size_t qname_len,
2998
  uint8_t** nx, size_t* nxlen)
2999
0
{
3000
0
  int celabs = dname_count_labels(cenm);
3001
0
  int qlabs = dname_count_labels(qname);
3002
0
  int strip = qlabs - celabs -1;
3003
0
  log_assert(dname_strict_subdomain(qname, qlabs, cenm, celabs));
3004
0
  *nx = qname;
3005
0
  *nxlen = qname_len;
3006
0
  if(strip>0)
3007
0
    dname_remove_labels(nx, nxlen, strip);
3008
0
}
3009
3010
/** Find the closest encloser that has exact NSEC3.
3011
 * updated cenm to the new name. If it went up no-exact-ce is true. */
3012
static struct auth_data*
3013
az_nsec3_find_ce(struct auth_zone* z, uint8_t** cenm, size_t* cenmlen,
3014
  int* no_exact_ce, int algo, size_t iter, uint8_t* salt, size_t saltlen)
3015
0
{
3016
0
  struct auth_data* node;
3017
0
  while((node = az_nsec3_find_exact(z, *cenm, *cenmlen,
3018
0
    algo, iter, salt, saltlen)) == NULL) {
3019
0
    if(!dname_remove_label_limit_len(cenm, cenmlen, z->namelen))
3020
0
      return NULL; /* can't go up */
3021
0
    *no_exact_ce = 1;
3022
0
  }
3023
0
  return node;
3024
0
}
3025
3026
/* Insert NSEC3 record in authority section, if NULL does nothing */
3027
static int
3028
az_nsec3_insert(struct auth_zone* z, struct regional* region,
3029
  struct dns_msg* msg, struct auth_data* node)
3030
0
{
3031
0
  struct auth_rrset* nsec3;
3032
0
  if(!node) return 1; /* no node, skip this */
3033
0
  nsec3 = az_domain_rrset(node, LDNS_RR_TYPE_NSEC3);
3034
0
  if(!nsec3) return 1; /* if no nsec3 RR, skip it */
3035
0
  if(!msg_add_rrset_ns(z, region, msg, node, nsec3)) return 0;
3036
0
  return 1;
3037
0
}
3038
3039
/** add NSEC3 records to the zone for the nsec3 proof.
3040
 * Specify with the flags with parts of the proof are required.
3041
 * the ce is the exact matching name (for notype) but also delegation points.
3042
 * qname is the one where the nextcloser name can be derived from.
3043
 * If NSEC3 is not properly there (in the zone) nothing is added.
3044
 * always enabled: include nsec3 proving about the Closest Encloser.
3045
 *  that is an exact match that should exist for it.
3046
 *  If that does not exist, a higher exact match + nxproof is enabled
3047
 *  (for some sort of opt-out empty nonterminal cases).
3048
 * nodataproof: search for exact match and include that instead.
3049
 * ceproof: include ce proof NSEC3 (omitted for wildcard replies).
3050
 * nxproof: include denial of the qname.
3051
 * wcproof: include denial of wildcard (wildcard.ce).
3052
 */
3053
static int
3054
az_add_nsec3_proof(struct auth_zone* z, struct regional* region,
3055
  struct dns_msg* msg, uint8_t* cenm, size_t cenmlen, uint8_t* qname,
3056
  size_t qname_len, int nodataproof, int ceproof, int nxproof,
3057
  int wcproof)
3058
0
{
3059
0
  int algo;
3060
0
  size_t iter, saltlen;
3061
0
  uint8_t* salt;
3062
0
  int no_exact_ce = 0;
3063
0
  struct auth_data* node;
3064
3065
  /* find parameters of nsec3 proof */
3066
0
  if(!az_nsec3_param(z, &algo, &iter, &salt, &saltlen))
3067
0
    return 1; /* no nsec3 */
3068
0
  if(nodataproof) {
3069
    /* see if the node has a hash of itself for the nodata
3070
     * proof nsec3, this has to be an exact match nsec3. */
3071
0
    struct auth_data* match;
3072
0
    match = az_nsec3_find_exact(z, qname, qname_len, algo,
3073
0
      iter, salt, saltlen);
3074
0
    if(match) {
3075
0
      if(!az_nsec3_insert(z, region, msg, match))
3076
0
        return 0;
3077
      /* only nodata NSEC3 needed, no CE or others. */
3078
0
      return 1;
3079
0
    }
3080
0
  }
3081
  /* find ce that has an NSEC3 */
3082
0
  if(ceproof) {
3083
0
    node = az_nsec3_find_ce(z, &cenm, &cenmlen, &no_exact_ce,
3084
0
      algo, iter, salt, saltlen);
3085
0
    if(no_exact_ce) nxproof = 1;
3086
0
    if(!az_nsec3_insert(z, region, msg, node))
3087
0
      return 0;
3088
0
  }
3089
3090
0
  if(nxproof) {
3091
0
    uint8_t* nx;
3092
0
    size_t nxlen;
3093
    /* create nextcloser domain name */
3094
0
    az_nsec3_get_nextcloser(cenm, qname, qname_len, &nx, &nxlen);
3095
    /* find nsec3 that matches or covers it */
3096
0
    node = az_nsec3_find_cover(z, nx, nxlen, algo, iter, salt,
3097
0
      saltlen);
3098
0
    if(!az_nsec3_insert(z, region, msg, node))
3099
0
      return 0;
3100
0
  }
3101
0
  if(wcproof) {
3102
    /* create wildcard name *.ce */
3103
0
    uint8_t wc[LDNS_MAX_DOMAINLEN];
3104
0
    size_t wclen;
3105
0
    if(cenmlen+2 > sizeof(wc))
3106
0
      return 0; /* result would be too long */
3107
0
    wc[0] = 1; /* length of wildcard label */
3108
0
    wc[1] = (uint8_t)'*'; /* wildcard label */
3109
0
    memmove(wc+2, cenm, cenmlen);
3110
0
    wclen = cenmlen+2;
3111
    /* find nsec3 that matches or covers it */
3112
0
    node = az_nsec3_find_cover(z, wc, wclen, algo, iter, salt,
3113
0
      saltlen);
3114
0
    if(!az_nsec3_insert(z, region, msg, node))
3115
0
      return 0;
3116
0
  }
3117
0
  return 1;
3118
0
}
3119
3120
/** generate answer for positive answer */
3121
static int
3122
az_generate_positive_answer(struct auth_zone* z, struct regional* region,
3123
  struct dns_msg* msg, struct auth_data* node, struct auth_rrset* rrset)
3124
0
{
3125
0
  if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
3126
  /* see if we want additional rrs */
3127
0
  if(rrset->type == LDNS_RR_TYPE_MX) {
3128
0
    if(!az_add_additionals_from(z, region, msg, rrset, 2))
3129
0
      return 0;
3130
0
  } else if(rrset->type == LDNS_RR_TYPE_SRV) {
3131
0
    if(!az_add_additionals_from(z, region, msg, rrset, 6))
3132
0
      return 0;
3133
0
  } else if(rrset->type == LDNS_RR_TYPE_NS) {
3134
0
    if(!az_add_additionals_from(z, region, msg, rrset, 0))
3135
0
      return 0;
3136
0
  }
3137
0
  return 1;
3138
0
}
3139
3140
/** generate answer for type ANY answer */
3141
static int
3142
az_generate_any_answer(struct auth_zone* z, struct regional* region,
3143
  struct dns_msg* msg, struct auth_data* node)
3144
0
{
3145
0
  struct auth_rrset* rrset;
3146
0
  int added = 0;
3147
  /* add a couple (at least one) RRs */
3148
0
  if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_SOA)) != NULL) {
3149
0
    if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
3150
0
    added++;
3151
0
  }
3152
0
  if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_MX)) != NULL) {
3153
0
    if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
3154
0
    added++;
3155
0
  }
3156
0
  if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_A)) != NULL) {
3157
0
    if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
3158
0
    added++;
3159
0
  }
3160
0
  if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_AAAA)) != NULL) {
3161
0
    if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
3162
0
    added++;
3163
0
  }
3164
0
  if(added == 0 && node && node->rrsets) {
3165
0
    if(!msg_add_rrset_an(z, region, msg, node,
3166
0
      node->rrsets)) return 0;
3167
0
  }
3168
0
  return 1;
3169
0
}
3170
3171
/** follow cname chain and add more data to the answer section */
3172
static int
3173
follow_cname_chain(struct auth_zone* z, uint16_t qtype,
3174
  struct regional* region, struct dns_msg* msg,
3175
  struct packed_rrset_data* d)
3176
0
{
3177
0
  int maxchain = 0;
3178
  /* see if we can add the target of the CNAME into the answer */
3179
0
  while(maxchain++ < MAX_CNAME_CHAIN) {
3180
0
    struct auth_data* node;
3181
0
    struct auth_rrset* rrset;
3182
0
    size_t clen;
3183
    /* d has cname rdata */
3184
0
    if(d->count == 0) break; /* no CNAME */
3185
0
    if(d->rr_len[0] < 2+1) break; /* too small */
3186
0
    if((clen=dname_valid(d->rr_data[0]+2, d->rr_len[0]-2))==0)
3187
0
      break; /* malformed */
3188
0
    if(!dname_subdomain_c(d->rr_data[0]+2, z->name))
3189
0
      break; /* target out of zone */
3190
0
    if((node = az_find_name(z, d->rr_data[0]+2, clen))==NULL)
3191
0
      break; /* no such target name */
3192
0
    if((rrset=az_domain_rrset(node, qtype))!=NULL) {
3193
      /* done we found the target */
3194
0
      if(!msg_add_rrset_an(z, region, msg, node, rrset))
3195
0
        return 0;
3196
0
      break;
3197
0
    }
3198
0
    if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_CNAME))==NULL)
3199
0
      break; /* no further CNAME chain, notype */
3200
0
    if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
3201
0
    d = rrset->data;
3202
0
  }
3203
0
  return 1;
3204
0
}
3205
3206
/** generate answer for cname answer */
3207
static int
3208
az_generate_cname_answer(struct auth_zone* z, struct query_info* qinfo,
3209
  struct regional* region, struct dns_msg* msg,
3210
  struct auth_data* node, struct auth_rrset* rrset)
3211
0
{
3212
0
  if(!msg_add_rrset_an(z, region, msg, node, rrset)) return 0;
3213
0
  if(!rrset) return 1;
3214
0
  if(!follow_cname_chain(z, qinfo->qtype, region, msg, rrset->data))
3215
0
    return 0;
3216
0
  return 1;
3217
0
}
3218
3219
/** generate answer for notype answer */
3220
static int
3221
az_generate_notype_answer(struct auth_zone* z, struct regional* region,
3222
  struct dns_msg* msg, struct auth_data* node)
3223
0
{
3224
0
  struct auth_rrset* rrset;
3225
0
  if(!az_add_negative_soa(z, region, msg)) return 0;
3226
  /* DNSSEC denial NSEC */
3227
0
  if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_NSEC))!=NULL) {
3228
0
    if(!msg_add_rrset_ns(z, region, msg, node, rrset)) return 0;
3229
0
  } else if(node) {
3230
    /* DNSSEC denial NSEC3 */
3231
0
    if(!az_add_nsec3_proof(z, region, msg, node->name,
3232
0
      node->namelen, msg->qinfo.qname,
3233
0
      msg->qinfo.qname_len, 1, 1, 0, 0))
3234
0
      return 0;
3235
0
  }
3236
0
  return 1;
3237
0
}
3238
3239
/** generate answer for referral answer */
3240
static int
3241
az_generate_referral_answer(struct auth_zone* z, struct regional* region,
3242
  struct dns_msg* msg, struct auth_data* ce, struct auth_rrset* rrset)
3243
0
{
3244
0
  struct auth_rrset* ds, *nsec;
3245
  /* turn off AA flag, referral is nonAA because it leaves the zone */
3246
0
  log_assert(ce);
3247
0
  msg->rep->flags &= ~BIT_AA;
3248
0
  if(!msg_add_rrset_ns(z, region, msg, ce, rrset)) return 0;
3249
  /* add DS or deny it */
3250
0
  if((ds=az_domain_rrset(ce, LDNS_RR_TYPE_DS))!=NULL) {
3251
0
    if(!msg_add_rrset_ns(z, region, msg, ce, ds)) return 0;
3252
0
  } else {
3253
    /* deny the DS */
3254
0
    if((nsec=az_domain_rrset(ce, LDNS_RR_TYPE_NSEC))!=NULL) {
3255
0
      if(!msg_add_rrset_ns(z, region, msg, ce, nsec))
3256
0
        return 0;
3257
0
    } else {
3258
0
      if(!az_add_nsec3_proof(z, region, msg, ce->name,
3259
0
        ce->namelen, msg->qinfo.qname,
3260
0
        msg->qinfo.qname_len, 1, 1, 0, 0))
3261
0
        return 0;
3262
0
    }
3263
0
  }
3264
  /* add additional rrs for type NS */
3265
0
  if(!az_add_additionals_from(z, region, msg, rrset, 0)) return 0;
3266
0
  return 1;
3267
0
}
3268
3269
/** generate answer for DNAME answer */
3270
static int
3271
az_generate_dname_answer(struct auth_zone* z, struct query_info* qinfo,
3272
  struct regional* region, struct dns_msg* msg, struct auth_data* ce,
3273
  struct auth_rrset* rrset)
3274
0
{
3275
0
  log_assert(ce);
3276
  /* add the DNAME and then a CNAME */
3277
0
  if(!msg_add_rrset_an(z, region, msg, ce, rrset)) return 0;
3278
0
  if(!add_synth_cname(z, qinfo->qname, qinfo->qname_len, region,
3279
0
    msg, ce, rrset)) return 0;
3280
0
  if(FLAGS_GET_RCODE(msg->rep->flags) == LDNS_RCODE_YXDOMAIN)
3281
0
    return 1;
3282
0
  if(msg->rep->rrset_count == 0 ||
3283
0
    !msg->rep->rrsets[msg->rep->rrset_count-1])
3284
0
    return 0;
3285
0
  if(!follow_cname_chain(z, qinfo->qtype, region, msg, 
3286
0
    (struct packed_rrset_data*)msg->rep->rrsets[
3287
0
    msg->rep->rrset_count-1]->entry.data))
3288
0
    return 0;
3289
0
  return 1;
3290
0
}
3291
3292
/** generate answer for wildcard answer */
3293
static int
3294
az_generate_wildcard_answer(struct auth_zone* z, struct query_info* qinfo,
3295
  struct regional* region, struct dns_msg* msg, struct auth_data* ce,
3296
  struct auth_data* wildcard, struct auth_data* node)
3297
0
{
3298
0
  struct auth_rrset* rrset, *nsec;
3299
0
  int insert_ce = 0;
3300
0
  if((rrset=az_domain_rrset(wildcard, qinfo->qtype)) != NULL) {
3301
    /* wildcard has type, add it */
3302
0
    if(!msg_add_rrset_an(z, region, msg, wildcard, rrset))
3303
0
      return 0;
3304
0
    az_change_dnames(msg, wildcard->name, msg->qinfo.qname,
3305
0
      msg->qinfo.qname_len, 1);
3306
0
  } else if((rrset=az_domain_rrset(wildcard, LDNS_RR_TYPE_CNAME))!=NULL) {
3307
    /* wildcard has cname instead, do that */
3308
0
    if(!msg_add_rrset_an(z, region, msg, wildcard, rrset))
3309
0
      return 0;
3310
0
    az_change_dnames(msg, wildcard->name, msg->qinfo.qname,
3311
0
      msg->qinfo.qname_len, 1);
3312
0
    if(!follow_cname_chain(z, qinfo->qtype, region, msg,
3313
0
      rrset->data))
3314
0
      return 0;
3315
0
  } else if(qinfo->qtype == LDNS_RR_TYPE_ANY && wildcard->rrsets) {
3316
    /* add ANY rrsets from wildcard node */
3317
0
    if(!az_generate_any_answer(z, region, msg, wildcard))
3318
0
      return 0;
3319
0
    az_change_dnames(msg, wildcard->name, msg->qinfo.qname,
3320
0
      msg->qinfo.qname_len, 1);
3321
0
  } else {
3322
    /* wildcard has nodata, notype answer */
3323
    /* call other notype routine for dnssec notype denials */
3324
0
    if(!az_generate_notype_answer(z, region, msg, wildcard))
3325
0
      return 0;
3326
    /* because the notype, there is no positive data with an
3327
     * RRSIG that indicates the wildcard position.  Thus the
3328
     * wildcard qname denial needs to have a CE nsec3. */
3329
0
    insert_ce = 1;
3330
0
  }
3331
3332
  /* ce and node for dnssec denial of wildcard original name */
3333
0
  if((nsec=az_find_nsec_cover(z, &node)) != NULL) {
3334
0
    if(!msg_add_rrset_ns(z, region, msg, node, nsec)) return 0;
3335
0
  } else if(ce) {
3336
0
    uint8_t* wildup = wildcard->name;
3337
0
    size_t wilduplen= wildcard->namelen;
3338
0
    if(!dname_remove_label_limit_len(&wildup, &wilduplen, z->namelen))
3339
0
      return 0; /* can't go up */
3340
0
    if(!az_add_nsec3_proof(z, region, msg, wildup,
3341
0
      wilduplen, msg->qinfo.qname,
3342
0
      msg->qinfo.qname_len, 0, insert_ce, 1, 0))
3343
0
      return 0;
3344
0
  }
3345
3346
  /* fixup name of wildcard from *.zone to qname, use already allocated
3347
   * pointer to msg qname */
3348
0
  az_change_dnames(msg, wildcard->name, msg->qinfo.qname,
3349
0
    msg->qinfo.qname_len, 0);
3350
0
  return 1;
3351
0
}
3352
3353
/** generate answer for nxdomain answer */
3354
static int
3355
az_generate_nxdomain_answer(struct auth_zone* z, struct regional* region,
3356
  struct dns_msg* msg, struct auth_data* ce, struct auth_data* node)
3357
0
{
3358
0
  struct auth_rrset* nsec;
3359
0
  msg->rep->flags |= LDNS_RCODE_NXDOMAIN;
3360
0
  if(!az_add_negative_soa(z, region, msg)) return 0;
3361
0
  if((nsec=az_find_nsec_cover(z, &node)) != NULL) {
3362
0
    if(!msg_add_rrset_ns(z, region, msg, node, nsec)) return 0;
3363
0
    if(ce && !az_nsec_wildcard_denial(z, region, msg, ce->name,
3364
0
      ce->namelen)) return 0;
3365
0
  } else if(ce) {
3366
0
    if(!az_add_nsec3_proof(z, region, msg, ce->name,
3367
0
      ce->namelen, msg->qinfo.qname,
3368
0
      msg->qinfo.qname_len, 0, 1, 1, 1))
3369
0
      return 0;
3370
0
  }
3371
0
  return 1;
3372
0
}
3373
3374
/** Create answers when an exact match exists for the domain name */
3375
static int
3376
az_generate_answer_with_node(struct auth_zone* z, struct query_info* qinfo,
3377
  struct regional* region, struct dns_msg* msg, struct auth_data* node)
3378
0
{
3379
0
  struct auth_rrset* rrset;
3380
  /* positive answer, rrset we are looking for exists */
3381
0
  if((rrset=az_domain_rrset(node, qinfo->qtype)) != NULL) {
3382
0
    return az_generate_positive_answer(z, region, msg, node, rrset);
3383
0
  }
3384
  /* CNAME? */
3385
0
  if((rrset=az_domain_rrset(node, LDNS_RR_TYPE_CNAME)) != NULL) {
3386
0
    return az_generate_cname_answer(z, qinfo, region, msg,
3387
0
      node, rrset);
3388
0
  }
3389
  /* type ANY ? */
3390
0
  if(qinfo->qtype == LDNS_RR_TYPE_ANY) {
3391
0
    return az_generate_any_answer(z, region, msg, node);
3392
0
  }
3393
  /* NOERROR/NODATA (no such type at domain name) */
3394
0
  return az_generate_notype_answer(z, region, msg, node);
3395
0
}
3396
3397
/** Generate answer without an existing-node that we can use.
3398
 * So it'll be a referral, DNAME, notype, wildcard or nxdomain */
3399
static int
3400
az_generate_answer_nonexistnode(struct auth_zone* z, struct query_info* qinfo,
3401
  struct regional* region, struct dns_msg* msg, struct auth_data* ce,
3402
  struct auth_rrset* rrset, struct auth_data* node)
3403
0
{
3404
0
  struct auth_data* wildcard;
3405
3406
  /* we do not have an exact matching name (that exists) */
3407
  /* see if we have a NS or DNAME in the ce */
3408
0
  if(ce && rrset && rrset->type == LDNS_RR_TYPE_NS) {
3409
0
    return az_generate_referral_answer(z, region, msg, ce, rrset);
3410
0
  }
3411
0
  if(ce && rrset && rrset->type == LDNS_RR_TYPE_DNAME) {
3412
0
    return az_generate_dname_answer(z, qinfo, region, msg, ce,
3413
0
      rrset);
3414
0
  }
3415
  /* if there is an empty nonterminal, wildcard and nxdomain don't
3416
   * happen, it is a notype answer */
3417
0
  if(az_empty_nonterminal(z, qinfo, node)) {
3418
0
    return az_generate_notype_answer(z, region, msg, node);
3419
0
  }
3420
  /* see if we have a wildcard under the ce */
3421
0
  if((wildcard=az_find_wildcard(z, qinfo, ce)) != NULL) {
3422
0
    return az_generate_wildcard_answer(z, qinfo, region, msg,
3423
0
      ce, wildcard, node);
3424
0
  }
3425
  /* generate nxdomain answer */
3426
0
  return az_generate_nxdomain_answer(z, region, msg, ce, node);
3427
0
}
3428
3429
/** Lookup answer in a zone. */
3430
static int
3431
auth_zone_generate_answer(struct auth_zone* z, struct query_info* qinfo,
3432
  struct regional* region, struct dns_msg** msg, int* fallback)
3433
0
{
3434
0
  struct auth_data* node, *ce;
3435
0
  struct auth_rrset* rrset;
3436
0
  int node_exact, node_exists;
3437
  /* does the zone want fallback in case of failure? */
3438
0
  *fallback = z->fallback_enabled;
3439
0
  if(!(*msg=msg_create(region, qinfo))) return 0;
3440
3441
  /* lookup if there is a matching domain name for the query */
3442
0
  az_find_domain(z, qinfo, &node_exact, &node);
3443
3444
  /* see if node exists for generating answers from (i.e. not glue and
3445
   * obscured by NS or DNAME or NSEC3-only), and also return the
3446
   * closest-encloser from that, closest node that should be used
3447
   * to generate answers from that is above the query */
3448
0
  node_exists = az_find_ce(z, qinfo, node, node_exact, &ce, &rrset);
3449
3450
0
  if(verbosity >= VERB_ALGO) {
3451
0
    char zname[256], qname[256], nname[256], cename[256],
3452
0
      tpstr[32], rrstr[32];
3453
0
    sldns_wire2str_dname_buf(qinfo->qname, qinfo->qname_len, qname,
3454
0
      sizeof(qname));
3455
0
    sldns_wire2str_type_buf(qinfo->qtype, tpstr, sizeof(tpstr));
3456
0
    sldns_wire2str_dname_buf(z->name, z->namelen, zname,
3457
0
      sizeof(zname));
3458
0
    if(node)
3459
0
      sldns_wire2str_dname_buf(node->name, node->namelen,
3460
0
        nname, sizeof(nname));
3461
0
    else  snprintf(nname, sizeof(nname), "NULL");
3462
0
    if(ce)
3463
0
      sldns_wire2str_dname_buf(ce->name, ce->namelen,
3464
0
        cename, sizeof(cename));
3465
0
    else  snprintf(cename, sizeof(cename), "NULL");
3466
0
    if(rrset) sldns_wire2str_type_buf(rrset->type, rrstr,
3467
0
      sizeof(rrstr));
3468
0
    else  snprintf(rrstr, sizeof(rrstr), "NULL");
3469
0
    log_info("auth_zone %s query %s %s, domain %s %s %s, "
3470
0
      "ce %s, rrset %s", zname, qname, tpstr, nname,
3471
0
      (node_exact?"exact":"notexact"),
3472
0
      (node_exists?"exist":"notexist"), cename, rrstr);
3473
0
  }
3474
3475
0
  if(node_exists) {
3476
    /* the node is fine, generate answer from node */
3477
0
    return az_generate_answer_with_node(z, qinfo, region, *msg,
3478
0
      node);
3479
0
  }
3480
0
  return az_generate_answer_nonexistnode(z, qinfo, region, *msg,
3481
0
    ce, rrset, node);
3482
0
}
3483
3484
int auth_zones_lookup(struct auth_zones* az, struct query_info* qinfo,
3485
  struct regional* region, struct dns_msg** msg, int* fallback,
3486
  uint8_t* dp_nm, size_t dp_nmlen)
3487
0
{
3488
0
  int r;
3489
0
  struct auth_zone* z;
3490
  /* find the zone that should contain the answer. */
3491
0
  lock_rw_rdlock(&az->lock);
3492
0
  z = auth_zone_find(az, dp_nm, dp_nmlen, qinfo->qclass);
3493
0
  if(!z) {
3494
0
    lock_rw_unlock(&az->lock);
3495
    /* no auth zone, fallback to internet */
3496
0
    *fallback = 1;
3497
0
    return 0;
3498
0
  }
3499
0
  lock_rw_rdlock(&z->lock);
3500
0
  lock_rw_unlock(&az->lock);
3501
3502
  /* if not for upstream queries, fallback */
3503
0
  if(!z->for_upstream) {
3504
0
    lock_rw_unlock(&z->lock);
3505
0
    *fallback = 1;
3506
0
    return 0;
3507
0
  }
3508
0
  if(z->zone_expired) {
3509
0
    *fallback = z->fallback_enabled;
3510
0
    lock_rw_unlock(&z->lock);
3511
0
    return 0;
3512
0
  }
3513
  /* see what answer that zone would generate */
3514
0
  r = auth_zone_generate_answer(z, qinfo, region, msg, fallback);
3515
0
  lock_rw_unlock(&z->lock);
3516
0
  return r;
3517
0
}
3518
3519
/** encode auth answer */
3520
static void
3521
auth_answer_encode(struct query_info* qinfo, struct module_env* env,
3522
  struct edns_data* edns, struct comm_reply* repinfo, sldns_buffer* buf,
3523
  struct regional* temp, struct dns_msg* msg)
3524
0
{
3525
0
  uint16_t udpsize;
3526
0
  udpsize = edns->udp_size;
3527
0
  edns->edns_version = EDNS_ADVERTISED_VERSION;
3528
0
  edns->udp_size = EDNS_ADVERTISED_SIZE;
3529
0
  edns->ext_rcode = 0;
3530
0
  edns->bits &= EDNS_DO;
3531
3532
0
  if(!inplace_cb_reply_local_call(env, qinfo, NULL, msg->rep,
3533
0
    (int)FLAGS_GET_RCODE(msg->rep->flags), edns, repinfo, temp, env->now_tv)
3534
0
    || !reply_info_answer_encode(qinfo, msg->rep,
3535
0
    *(uint16_t*)sldns_buffer_begin(buf),
3536
0
    sldns_buffer_read_u16_at(buf, 2),
3537
0
    buf, 0, 0, temp, udpsize, edns,
3538
0
    (int)(edns->bits&EDNS_DO), 0)) {
3539
0
    error_encode(buf, (LDNS_RCODE_SERVFAIL|BIT_AA), qinfo,
3540
0
      *(uint16_t*)sldns_buffer_begin(buf),
3541
0
      sldns_buffer_read_u16_at(buf, 2), edns);
3542
0
  }
3543
0
}
3544
3545
/** encode auth error answer */
3546
static void
3547
auth_error_encode(struct query_info* qinfo, struct module_env* env,
3548
  struct edns_data* edns, struct comm_reply* repinfo, sldns_buffer* buf,
3549
  struct regional* temp, int rcode)
3550
0
{
3551
0
  edns->edns_version = EDNS_ADVERTISED_VERSION;
3552
0
  edns->udp_size = EDNS_ADVERTISED_SIZE;
3553
0
  edns->ext_rcode = 0;
3554
0
  edns->bits &= EDNS_DO;
3555
3556
0
  if(!inplace_cb_reply_local_call(env, qinfo, NULL, NULL,
3557
0
    rcode, edns, repinfo, temp, env->now_tv))
3558
0
    edns->opt_list_inplace_cb_out = NULL;
3559
0
  error_encode(buf, rcode|BIT_AA, qinfo,
3560
0
    *(uint16_t*)sldns_buffer_begin(buf),
3561
0
    sldns_buffer_read_u16_at(buf, 2), edns);
3562
0
}
3563
3564
int auth_zones_downstream_answer(struct auth_zones* az, struct module_env* env,
3565
  struct query_info* qinfo, struct edns_data* edns,
3566
  struct comm_reply* repinfo, struct sldns_buffer* buf,
3567
  struct regional* temp)
3568
0
{
3569
0
  struct dns_msg* msg = NULL;
3570
0
  struct auth_zone* z;
3571
0
  int r;
3572
0
  int fallback = 0;
3573
  /* Copy the qinfo in case of cname aliasing from local-zone */
3574
0
  struct query_info zqinfo = *qinfo;
3575
3576
0
  lock_rw_rdlock(&az->lock);
3577
0
  if(!az->have_downstream) {
3578
    /* no downstream auth zones */
3579
0
    lock_rw_unlock(&az->lock);
3580
0
    return 0;
3581
0
  }
3582
3583
0
  if(qinfo->qtype == LDNS_RR_TYPE_DS) {
3584
0
    uint8_t* delname = qinfo->qname;
3585
0
    size_t delnamelen = qinfo->qname_len;
3586
0
    dname_remove_label(&delname, &delnamelen);
3587
0
    z = auth_zones_find_zone(az, delname, delnamelen,
3588
0
      qinfo->qclass);
3589
0
  } else {
3590
0
    if(zqinfo.local_alias && !local_alias_shallow_copy_qname(
3591
0
      zqinfo.local_alias, &zqinfo.qname,
3592
0
      &zqinfo.qname_len)) {
3593
0
      lock_rw_unlock(&az->lock);
3594
0
      return 0;
3595
0
    }
3596
0
    z = auth_zones_find_zone(az, zqinfo.qname, zqinfo.qname_len,
3597
0
      zqinfo.qclass);
3598
0
  }
3599
0
  if(!z) {
3600
    /* no zone above it */
3601
0
    lock_rw_unlock(&az->lock);
3602
0
    return 0;
3603
0
  }
3604
0
  lock_rw_rdlock(&z->lock);
3605
0
  lock_rw_unlock(&az->lock);
3606
0
  if(!z->for_downstream) {
3607
0
    lock_rw_unlock(&z->lock);
3608
0
    return 0;
3609
0
  }
3610
0
  if(z->zone_expired) {
3611
0
    if(z->fallback_enabled) {
3612
0
      lock_rw_unlock(&z->lock);
3613
0
      return 0;
3614
0
    }
3615
0
    lock_rw_unlock(&z->lock);
3616
0
    env->mesh->num_query_authzone_down++;
3617
0
    auth_error_encode(qinfo, env, edns, repinfo, buf, temp,
3618
0
      LDNS_RCODE_SERVFAIL);
3619
0
    return 1;
3620
0
  }
3621
3622
  /* answer it from zone z */
3623
0
  r = auth_zone_generate_answer(z, &zqinfo, temp, &msg, &fallback);
3624
0
  lock_rw_unlock(&z->lock);
3625
0
  if(!r && fallback) {
3626
    /* fallback to regular answering (recursive) */
3627
0
    return 0;
3628
0
  }
3629
0
  env->mesh->num_query_authzone_down++;
3630
3631
  /* encode answer */
3632
0
  if(!r)
3633
0
    auth_error_encode(qinfo, env, edns, repinfo, buf, temp,
3634
0
      LDNS_RCODE_SERVFAIL);
3635
0
  else  auth_answer_encode(qinfo, env, edns, repinfo, buf, temp, msg);
3636
3637
0
  return 1;
3638
0
}
3639
3640
int auth_zones_can_fallback(struct auth_zones* az, uint8_t* nm, size_t nmlen,
3641
  uint16_t dclass)
3642
0
{
3643
0
  int r;
3644
0
  struct auth_zone* z;
3645
0
  lock_rw_rdlock(&az->lock);
3646
0
  z = auth_zone_find(az, nm, nmlen, dclass);
3647
0
  if(!z) {
3648
0
    lock_rw_unlock(&az->lock);
3649
    /* no such auth zone, fallback */
3650
0
    return 1;
3651
0
  }
3652
0
  lock_rw_rdlock(&z->lock);
3653
0
  lock_rw_unlock(&az->lock);
3654
0
  r = z->fallback_enabled || (!z->for_upstream);
3655
0
  lock_rw_unlock(&z->lock);
3656
0
  return r;
3657
0
}
3658
3659
int
3660
auth_zone_parse_notify_serial(sldns_buffer* pkt, uint32_t *serial)
3661
0
{
3662
0
  struct query_info q;
3663
0
  uint16_t rdlen;
3664
0
  memset(&q, 0, sizeof(q));
3665
0
  sldns_buffer_set_position(pkt, 0);
3666
0
  if(!query_info_parse(&q, pkt)) return 0;
3667
0
  if(LDNS_ANCOUNT(sldns_buffer_begin(pkt)) == 0) return 0;
3668
  /* skip name of RR in answer section */
3669
0
  if(sldns_buffer_remaining(pkt) < 1) return 0;
3670
0
  if(pkt_dname_len(pkt) == 0) return 0;
3671
  /* check type */
3672
0
  if(sldns_buffer_remaining(pkt) < 10 /* type,class,ttl,rdatalen*/)
3673
0
    return 0;
3674
0
  if(sldns_buffer_read_u16(pkt) != LDNS_RR_TYPE_SOA) return 0;
3675
0
  sldns_buffer_skip(pkt, 2); /* class */
3676
0
  sldns_buffer_skip(pkt, 4); /* ttl */
3677
0
  rdlen = sldns_buffer_read_u16(pkt); /* rdatalen */
3678
0
  if(sldns_buffer_remaining(pkt) < rdlen) return 0;
3679
0
  if(rdlen < 22) return 0; /* bad soa length */
3680
0
  sldns_buffer_skip(pkt, (ssize_t)(rdlen-20));
3681
0
  *serial = sldns_buffer_read_u32(pkt);
3682
  /* return true when has serial in answer section */
3683
0
  return 1;
3684
0
}
3685
3686
/** print addr to str, and if not 53, append "@port_number", for logs. */
3687
static void addr_port_to_str(struct sockaddr_storage* addr, socklen_t addrlen,
3688
  char* buf, size_t len)
3689
0
{
3690
0
  uint16_t port = 0;
3691
0
  if(addr_is_ip6(addr, addrlen)) {
3692
0
    struct sockaddr_in6* sa = (struct sockaddr_in6*)addr;
3693
0
    port = ntohs((uint16_t)sa->sin6_port);
3694
0
  } else {
3695
0
    struct sockaddr_in* sa = (struct sockaddr_in*)addr;
3696
0
    port = ntohs((uint16_t)sa->sin_port);
3697
0
  }
3698
0
  if(port == UNBOUND_DNS_PORT) {
3699
    /* If it is port 53, print it plainly. */
3700
0
    addr_to_str(addr, addrlen, buf, len);
3701
0
  } else {
3702
0
    char a[256];
3703
0
    a[0]=0;
3704
0
    addr_to_str(addr, addrlen, a, sizeof(a));
3705
0
    snprintf(buf, len, "%s@%d", a, (int)port);
3706
0
  }
3707
0
}
3708
3709
/** see if addr appears in the list */
3710
static int
3711
addr_in_list(struct auth_addr* list, struct sockaddr_storage* addr,
3712
  socklen_t addrlen)
3713
0
{
3714
0
  struct auth_addr* p;
3715
0
  for(p=list; p; p=p->next) {
3716
0
    if(sockaddr_cmp_addr(addr, addrlen, &p->addr, p->addrlen)==0)
3717
0
      return 1;
3718
0
  }
3719
0
  return 0;
3720
0
}
3721
3722
/** check if an address matches a master specification (or one of its
3723
 * addresses in the addr list) */
3724
static int
3725
addr_matches_master(struct auth_master* master, struct sockaddr_storage* addr,
3726
  socklen_t addrlen, struct auth_master** fromhost)
3727
0
{
3728
0
  struct sockaddr_storage a;
3729
0
  socklen_t alen = 0;
3730
0
  int net = 0;
3731
0
  if(addr_in_list(master->list, addr, addrlen)) {
3732
0
    *fromhost = master;
3733
0
    return 1; 
3734
0
  }
3735
  /* compare address (but not port number, that is the destination
3736
   * port of the master, the port number of the received notify is
3737
   * allowed to by any port on that master) */
3738
0
  if(extstrtoaddr(master->host, &a, &alen, UNBOUND_DNS_PORT) &&
3739
0
    sockaddr_cmp_addr(addr, addrlen, &a, alen)==0) {
3740
0
    *fromhost = master;
3741
0
    return 1;
3742
0
  }
3743
  /* prefixes, addr/len, like 10.0.0.0/8 */
3744
  /* not http and has a / and there is one / */
3745
0
  if(master->allow_notify && !master->http &&
3746
0
    strchr(master->host, '/') != NULL &&
3747
0
    strchr(master->host, '/') == strrchr(master->host, '/') &&
3748
0
    netblockstrtoaddr(master->host, UNBOUND_DNS_PORT, &a, &alen,
3749
0
    &net) && alen == addrlen) {
3750
0
    if(addr_in_common(addr, (addr_is_ip6(addr, addrlen)?128:32),
3751
0
      &a, net, alen) >= net) {
3752
0
      *fromhost = NULL; /* prefix does not have destination
3753
        to send the probe or transfer with */
3754
0
      return 1; /* matches the netblock */
3755
0
    }
3756
0
  }
3757
0
  return 0;
3758
0
}
3759
3760
/** check access list for notifies */
3761
static int
3762
az_xfr_allowed_notify(struct auth_xfer* xfr, struct sockaddr_storage* addr,
3763
  socklen_t addrlen, struct auth_master** fromhost)
3764
0
{
3765
0
  struct auth_master* p;
3766
0
  for(p=xfr->allow_notify_list; p; p=p->next) {
3767
0
    if(addr_matches_master(p, addr, addrlen, fromhost)) {
3768
0
      return 1;
3769
0
    }
3770
0
  }
3771
0
  return 0;
3772
0
}
3773
3774
/** see if the serial means the zone has to be updated, i.e. the serial
3775
 * is newer than the zone serial, or we have no zone */
3776
static int
3777
xfr_serial_means_update(struct auth_xfer* xfr, uint32_t serial)
3778
0
{
3779
0
  if(!xfr->have_zone)
3780
0
    return 1; /* no zone, anything is better */
3781
0
  if(xfr->zone_expired)
3782
0
    return 1; /* expired, the sent serial is better than expired
3783
      data */
3784
0
  if(compare_serial(xfr->serial, serial) < 0)
3785
0
    return 1; /* our serial is smaller than the sent serial,
3786
      the data is newer, fetch it */
3787
0
  return 0;
3788
0
}
3789
3790
/** note notify serial, updates the notify information in the xfr struct */
3791
static void
3792
xfr_note_notify_serial(struct auth_xfer* xfr, int has_serial, uint32_t serial)
3793
0
{
3794
0
  if(xfr->notify_received && xfr->notify_has_serial && has_serial) {
3795
    /* see if this serial is newer */
3796
0
    if(compare_serial(xfr->notify_serial, serial) < 0)
3797
0
      xfr->notify_serial = serial;
3798
0
  } else if(xfr->notify_received && xfr->notify_has_serial &&
3799
0
    !has_serial) {
3800
    /* remove serial, we have notify without serial */
3801
0
    xfr->notify_has_serial = 0;
3802
0
    xfr->notify_serial = 0;
3803
0
  } else if(xfr->notify_received && !xfr->notify_has_serial) {
3804
    /* we already have notify without serial, keep it
3805
     * that way; no serial check when current operation
3806
     * is done */
3807
0
  } else {
3808
0
    xfr->notify_received = 1;
3809
0
    xfr->notify_has_serial = has_serial;
3810
0
    xfr->notify_serial = serial;
3811
0
  }
3812
0
}
3813
3814
/** process a notify serial, start new probe or note serial. xfr is locked */
3815
static void
3816
xfr_process_notify(struct auth_xfer* xfr, struct module_env* env,
3817
  int has_serial, uint32_t serial, struct auth_master* fromhost)
3818
0
{
3819
  /* if the serial of notify is older than we have, don't fetch
3820
   * a zone, we already have it */
3821
0
  if(has_serial && !xfr_serial_means_update(xfr, serial)) {
3822
0
    lock_basic_unlock(&xfr->lock);
3823
0
    return;
3824
0
  }
3825
  /* start new probe with this addr src, or note serial */
3826
0
  if(!xfr_start_probe(xfr, env, fromhost)) {
3827
    /* not started because already in progress, note the serial */
3828
0
    xfr_note_notify_serial(xfr, has_serial, serial);
3829
0
    lock_basic_unlock(&xfr->lock);
3830
0
  }
3831
  /* successful end of start_probe unlocked xfr->lock */
3832
0
}
3833
3834
int auth_zones_notify(struct auth_zones* az, struct module_env* env,
3835
  uint8_t* nm, size_t nmlen, uint16_t dclass,
3836
  struct sockaddr_storage* addr, socklen_t addrlen, int has_serial,
3837
  uint32_t serial, int* refused)
3838
0
{
3839
0
  struct auth_xfer* xfr;
3840
0
  struct auth_master* fromhost = NULL;
3841
  /* see which zone this is */
3842
0
  lock_rw_rdlock(&az->lock);
3843
0
  xfr = auth_xfer_find(az, nm, nmlen, dclass);
3844
0
  if(!xfr) {
3845
0
    lock_rw_unlock(&az->lock);
3846
    /* no such zone, refuse the notify */
3847
0
    *refused = 1;
3848
0
    return 0;
3849
0
  }
3850
0
  lock_basic_lock(&xfr->lock);
3851
0
  lock_rw_unlock(&az->lock);
3852
  
3853
  /* check access list for notifies */
3854
0
  if(!az_xfr_allowed_notify(xfr, addr, addrlen, &fromhost)) {
3855
0
    lock_basic_unlock(&xfr->lock);
3856
    /* notify not allowed, refuse the notify */
3857
0
    *refused = 1;
3858
0
    return 0;
3859
0
  }
3860
3861
  /* process the notify */
3862
0
  xfr_process_notify(xfr, env, has_serial, serial, fromhost);
3863
0
  return 1;
3864
0
}
3865
3866
int auth_zones_startprobesequence(struct auth_zones* az,
3867
  struct module_env* env, uint8_t* nm, size_t nmlen, uint16_t dclass)
3868
0
{
3869
0
  struct auth_xfer* xfr;
3870
0
  lock_rw_rdlock(&az->lock);
3871
0
  xfr = auth_xfer_find(az, nm, nmlen, dclass);
3872
0
  if(!xfr) {
3873
0
    lock_rw_unlock(&az->lock);
3874
0
    return 0;
3875
0
  }
3876
0
  lock_basic_lock(&xfr->lock);
3877
0
  lock_rw_unlock(&az->lock);
3878
3879
0
  xfr_process_notify(xfr, env, 0, 0, NULL);
3880
0
  return 1;
3881
0
}
3882
3883
/** set a zone expired */
3884
static void
3885
auth_xfer_set_expired(struct auth_xfer* xfr, struct module_env* env,
3886
  int expired)
3887
0
{
3888
0
  struct auth_zone* z;
3889
3890
  /* expire xfr */
3891
0
  lock_basic_lock(&xfr->lock);
3892
0
  xfr->zone_expired = expired;
3893
0
  lock_basic_unlock(&xfr->lock);
3894
3895
  /* find auth_zone */
3896
0
  lock_rw_rdlock(&env->auth_zones->lock);
3897
0
  z = auth_zone_find(env->auth_zones, xfr->name, xfr->namelen,
3898
0
    xfr->dclass);
3899
0
  if(!z) {
3900
0
    lock_rw_unlock(&env->auth_zones->lock);
3901
0
    return;
3902
0
  }
3903
0
  lock_rw_wrlock(&z->lock);
3904
0
  lock_rw_unlock(&env->auth_zones->lock);
3905
3906
  /* expire auth_zone */
3907
0
  z->zone_expired = expired;
3908
0
  lock_rw_unlock(&z->lock);
3909
0
}
3910
3911
/** find master (from notify or probe) in list of masters */
3912
static struct auth_master*
3913
find_master_by_host(struct auth_master* list, char* host)
3914
0
{
3915
0
  struct auth_master* p;
3916
0
  for(p=list; p; p=p->next) {
3917
0
    if(strcmp(p->host, host) == 0)
3918
0
      return p;
3919
0
  }
3920
0
  return NULL;
3921
0
}
3922
3923
/** delete the looked up auth_addrs for all the masters in the list */
3924
static void
3925
xfr_masterlist_free_addrs(struct auth_master* list)
3926
0
{
3927
0
  struct auth_master* m;
3928
0
  for(m=list; m; m=m->next) {
3929
0
    if(m->list) {
3930
0
      auth_free_master_addrs(m->list);
3931
0
      m->list = NULL;
3932
0
    }
3933
0
  }
3934
0
}
3935
3936
/** copy a list of auth_addrs */
3937
static struct auth_addr*
3938
auth_addr_list_copy(struct auth_addr* source)
3939
0
{
3940
0
  struct auth_addr* list = NULL, *last = NULL;
3941
0
  struct auth_addr* p;
3942
0
  for(p=source; p; p=p->next) {
3943
0
    struct auth_addr* a = (struct auth_addr*)memdup(p, sizeof(*p));
3944
0
    if(!a) {
3945
0
      log_err("malloc failure");
3946
0
      auth_free_master_addrs(list);
3947
0
      return NULL;
3948
0
    }
3949
0
    a->next = NULL;
3950
0
    if(last) last->next = a;
3951
0
    if(!list) list = a;
3952
0
    last = a;
3953
0
  }
3954
0
  return list;
3955
0
}
3956
3957
/** copy a master to a new structure, NULL on alloc failure */
3958
static struct auth_master*
3959
auth_master_copy(struct auth_master* o)
3960
0
{
3961
0
  struct auth_master* m;
3962
0
  if(!o) return NULL;
3963
0
  m = (struct auth_master*)memdup(o, sizeof(*o));
3964
0
  if(!m) {
3965
0
    log_err("malloc failure");
3966
0
    return NULL;
3967
0
  }
3968
0
  m->next = NULL;
3969
0
  if(m->host) {
3970
0
    m->host = strdup(m->host);
3971
0
    if(!m->host) {
3972
0
      free(m);
3973
0
      log_err("malloc failure");
3974
0
      return NULL;
3975
0
    }
3976
0
  }
3977
0
  if(m->file) {
3978
0
    m->file = strdup(m->file);
3979
0
    if(!m->file) {
3980
0
      free(m->host);
3981
0
      free(m);
3982
0
      log_err("malloc failure");
3983
0
      return NULL;
3984
0
    }
3985
0
  }
3986
0
  if(m->list) {
3987
0
    m->list = auth_addr_list_copy(m->list);
3988
0
    if(!m->list) {
3989
0
      free(m->file);
3990
0
      free(m->host);
3991
0
      free(m);
3992
0
      return NULL;
3993
0
    }
3994
0
  }
3995
0
  return m;
3996
0
}
3997
3998
/** append the master to the copied list. */
3999
static int
4000
auth_master_copy_and_append(struct auth_master* p, struct auth_master** list,
4001
  struct auth_master** last)
4002
0
{
4003
0
  struct auth_master* m = auth_master_copy(p);
4004
0
  if(!m) {
4005
0
    return 0;
4006
0
  }
4007
0
  m->next = NULL;
4008
0
  if(*last) (*last)->next = m;
4009
0
  if(!*list) *list = m;
4010
0
  *last = m;
4011
0
  return 1;
4012
0
}
4013
4014
/** copy the master addresses from the task_probe lookups to the allow_notify
4015
 * list of masters */
4016
static void
4017
probe_copy_masters_for_allow_notify(struct auth_xfer* xfr)
4018
0
{
4019
0
  struct auth_master* list = NULL, *last = NULL;
4020
0
  struct auth_master* p;
4021
  /* build up new list with copies */
4022
  /* The list in task probe has been looked up before the list in
4023
   * task transfer. */
4024
0
  for(p = xfr->task_probe->masters; p; p=p->next) {
4025
0
    if(!auth_master_copy_and_append(p, &list, &last)) {
4026
0
      auth_free_masters(list);
4027
      /* failed because of malloc failure, use old list */
4028
0
      return;
4029
0
    }
4030
0
  }
4031
  /* The list in task transfer also contains the http entries. */
4032
0
  for(p = xfr->task_transfer->masters; p; p=p->next) {
4033
    /* Copy the http entries from this lookup. The allow_notify
4034
     * entries are not looked up from this list. The other
4035
     * ones are already in from the probe lookups. */
4036
0
    if(!p->http)
4037
0
      continue;
4038
0
    if(!auth_master_copy_and_append(p, &list, &last)) {
4039
0
      auth_free_masters(list);
4040
      /* failed because of malloc failure, use old list */
4041
0
      return;
4042
0
    }
4043
0
  }
4044
  /* success, replace list */
4045
0
  auth_free_masters(xfr->allow_notify_list);
4046
0
  xfr->allow_notify_list = list;
4047
0
}
4048
4049
/** start the lookups for task_transfer */
4050
static void
4051
xfr_transfer_start_lookups(struct auth_xfer* xfr)
4052
0
{
4053
  /* delete all the looked up addresses in the list */
4054
0
  xfr->task_transfer->scan_addr = NULL;
4055
0
  xfr_masterlist_free_addrs(xfr->task_transfer->masters);
4056
4057
  /* start lookup at the first master */
4058
0
  xfr->task_transfer->lookup_target = xfr->task_transfer->masters;
4059
0
  xfr->task_transfer->lookup_aaaa = 0;
4060
0
}
4061
4062
/** move to the next lookup of hostname for task_transfer */
4063
static void
4064
xfr_transfer_move_to_next_lookup(struct auth_xfer* xfr, struct module_env* env)
4065
0
{
4066
0
  if(!xfr->task_transfer->lookup_target)
4067
0
    return; /* already at end of list */
4068
0
  if(!xfr->task_transfer->lookup_aaaa && env->cfg->do_ip6) {
4069
    /* move to lookup AAAA */
4070
0
    xfr->task_transfer->lookup_aaaa = 1;
4071
0
    return;
4072
0
  }
4073
0
  xfr->task_transfer->lookup_target = 
4074
0
    xfr->task_transfer->lookup_target->next;
4075
0
  xfr->task_transfer->lookup_aaaa = 0;
4076
0
  if(!env->cfg->do_ip4 && xfr->task_transfer->lookup_target!=NULL)
4077
0
    xfr->task_transfer->lookup_aaaa = 1;
4078
0
}
4079
4080
/** start the lookups for task_probe */
4081
static void
4082
xfr_probe_start_lookups(struct auth_xfer* xfr)
4083
0
{
4084
  /* delete all the looked up addresses in the list */
4085
0
  xfr->task_probe->scan_addr = NULL;
4086
0
  xfr_masterlist_free_addrs(xfr->task_probe->masters);
4087
4088
  /* start lookup at the first master */
4089
0
  xfr->task_probe->lookup_target = xfr->task_probe->masters;
4090
0
  xfr->task_probe->lookup_aaaa = 0;
4091
0
}
4092
4093
/** move to the next lookup of hostname for task_probe */
4094
static void
4095
xfr_probe_move_to_next_lookup(struct auth_xfer* xfr, struct module_env* env)
4096
0
{
4097
0
  if(!xfr->task_probe->lookup_target)
4098
0
    return; /* already at end of list */
4099
0
  if(!xfr->task_probe->lookup_aaaa && env->cfg->do_ip6) {
4100
    /* move to lookup AAAA */
4101
0
    xfr->task_probe->lookup_aaaa = 1;
4102
0
    return;
4103
0
  }
4104
0
  xfr->task_probe->lookup_target = xfr->task_probe->lookup_target->next;
4105
0
  xfr->task_probe->lookup_aaaa = 0;
4106
0
  if(!env->cfg->do_ip4 && xfr->task_probe->lookup_target!=NULL)
4107
0
    xfr->task_probe->lookup_aaaa = 1;
4108
0
}
4109
4110
/** start the iteration of the task_transfer list of masters */
4111
static void
4112
xfr_transfer_start_list(struct auth_xfer* xfr, struct auth_master* spec) 
4113
0
{
4114
0
  if(spec) {
4115
0
    xfr->task_transfer->scan_specific = find_master_by_host(
4116
0
      xfr->task_transfer->masters, spec->host);
4117
0
    if(xfr->task_transfer->scan_specific) {
4118
0
      xfr->task_transfer->scan_target = NULL;
4119
0
      xfr->task_transfer->scan_addr = NULL;
4120
0
      if(xfr->task_transfer->scan_specific->list)
4121
0
        xfr->task_transfer->scan_addr =
4122
0
          xfr->task_transfer->scan_specific->list;
4123
0
      return;
4124
0
    }
4125
0
  }
4126
  /* no specific (notified) host to scan */
4127
0
  xfr->task_transfer->scan_specific = NULL;
4128
0
  xfr->task_transfer->scan_addr = NULL;
4129
  /* pick up first scan target */
4130
0
  xfr->task_transfer->scan_target = xfr->task_transfer->masters;
4131
0
  if(xfr->task_transfer->scan_target && xfr->task_transfer->
4132
0
    scan_target->list)
4133
0
    xfr->task_transfer->scan_addr =
4134
0
      xfr->task_transfer->scan_target->list;
4135
0
}
4136
4137
/** start the iteration of the task_probe list of masters */
4138
static void
4139
xfr_probe_start_list(struct auth_xfer* xfr, struct auth_master* spec) 
4140
0
{
4141
0
  if(spec) {
4142
0
    xfr->task_probe->scan_specific = find_master_by_host(
4143
0
      xfr->task_probe->masters, spec->host);
4144
0
    if(xfr->task_probe->scan_specific) {
4145
0
      xfr->task_probe->scan_target = NULL;
4146
0
      xfr->task_probe->scan_addr = NULL;
4147
0
      if(xfr->task_probe->scan_specific->list)
4148
0
        xfr->task_probe->scan_addr =
4149
0
          xfr->task_probe->scan_specific->list;
4150
0
      return;
4151
0
    }
4152
0
  }
4153
  /* no specific (notified) host to scan */
4154
0
  xfr->task_probe->scan_specific = NULL;
4155
0
  xfr->task_probe->scan_addr = NULL;
4156
  /* pick up first scan target */
4157
0
  xfr->task_probe->scan_target = xfr->task_probe->masters;
4158
0
  if(xfr->task_probe->scan_target && xfr->task_probe->scan_target->list)
4159
0
    xfr->task_probe->scan_addr =
4160
0
      xfr->task_probe->scan_target->list;
4161
0
}
4162
4163
/** pick up the master that is being scanned right now, task_transfer */
4164
static struct auth_master*
4165
xfr_transfer_current_master(struct auth_xfer* xfr)
4166
0
{
4167
0
  if(xfr->task_transfer->scan_specific)
4168
0
    return xfr->task_transfer->scan_specific;
4169
0
  return xfr->task_transfer->scan_target;
4170
0
}
4171
4172
/** pick up the master that is being scanned right now, task_probe */
4173
static struct auth_master*
4174
xfr_probe_current_master(struct auth_xfer* xfr)
4175
0
{
4176
0
  if(xfr->task_probe->scan_specific)
4177
0
    return xfr->task_probe->scan_specific;
4178
0
  return xfr->task_probe->scan_target;
4179
0
}
4180
4181
/** true if at end of list, task_transfer */
4182
static int
4183
xfr_transfer_end_of_list(struct auth_xfer* xfr)
4184
0
{
4185
0
  return !xfr->task_transfer->scan_specific &&
4186
0
    !xfr->task_transfer->scan_target;
4187
0
}
4188
4189
/** true if at end of list, task_probe */
4190
static int
4191
xfr_probe_end_of_list(struct auth_xfer* xfr)
4192
0
{
4193
0
  return !xfr->task_probe->scan_specific && !xfr->task_probe->scan_target;
4194
0
}
4195
4196
/** move to next master in list, task_transfer */
4197
static void
4198
xfr_transfer_nextmaster(struct auth_xfer* xfr)
4199
0
{
4200
0
  if(!xfr->task_transfer->scan_specific &&
4201
0
    !xfr->task_transfer->scan_target)
4202
0
    return;
4203
0
  if(xfr->task_transfer->scan_addr) {
4204
0
    xfr->task_transfer->scan_addr =
4205
0
      xfr->task_transfer->scan_addr->next;
4206
0
    if(xfr->task_transfer->scan_addr)
4207
0
      return;
4208
0
  }
4209
0
  if(xfr->task_transfer->scan_specific) {
4210
0
    xfr->task_transfer->scan_specific = NULL;
4211
0
    xfr->task_transfer->scan_target = xfr->task_transfer->masters;
4212
0
    if(xfr->task_transfer->scan_target && xfr->task_transfer->
4213
0
      scan_target->list)
4214
0
      xfr->task_transfer->scan_addr =
4215
0
        xfr->task_transfer->scan_target->list;
4216
0
    return;
4217
0
  }
4218
0
  if(!xfr->task_transfer->scan_target)
4219
0
    return;
4220
0
  xfr->task_transfer->scan_target = xfr->task_transfer->scan_target->next;
4221
0
  if(xfr->task_transfer->scan_target && xfr->task_transfer->
4222
0
    scan_target->list)
4223
0
    xfr->task_transfer->scan_addr =
4224
0
      xfr->task_transfer->scan_target->list;
4225
0
  return;
4226
0
}
4227
4228
/** move to next master in list, task_probe */
4229
static void
4230
xfr_probe_nextmaster(struct auth_xfer* xfr)
4231
0
{
4232
0
  if(!xfr->task_probe->scan_specific && !xfr->task_probe->scan_target)
4233
0
    return;
4234
0
  if(xfr->task_probe->scan_addr) {
4235
0
    xfr->task_probe->scan_addr = xfr->task_probe->scan_addr->next;
4236
0
    if(xfr->task_probe->scan_addr)
4237
0
      return;
4238
0
  }
4239
0
  if(xfr->task_probe->scan_specific) {
4240
0
    xfr->task_probe->scan_specific = NULL;
4241
0
    xfr->task_probe->scan_target = xfr->task_probe->masters;
4242
0
    if(xfr->task_probe->scan_target && xfr->task_probe->
4243
0
      scan_target->list)
4244
0
      xfr->task_probe->scan_addr =
4245
0
        xfr->task_probe->scan_target->list;
4246
0
    return;
4247
0
  }
4248
0
  if(!xfr->task_probe->scan_target)
4249
0
    return;
4250
0
  xfr->task_probe->scan_target = xfr->task_probe->scan_target->next;
4251
0
  if(xfr->task_probe->scan_target && xfr->task_probe->
4252
0
    scan_target->list)
4253
0
    xfr->task_probe->scan_addr =
4254
0
      xfr->task_probe->scan_target->list;
4255
0
  return;
4256
0
}
4257
4258
/** create SOA probe packet for xfr */
4259
static void
4260
xfr_create_soa_probe_packet(struct auth_xfer* xfr, sldns_buffer* buf, 
4261
  uint16_t id)
4262
0
{
4263
0
  struct query_info qinfo;
4264
4265
0
  memset(&qinfo, 0, sizeof(qinfo));
4266
0
  qinfo.qname = xfr->name;
4267
0
  qinfo.qname_len = xfr->namelen;
4268
0
  qinfo.qtype = LDNS_RR_TYPE_SOA;
4269
0
  qinfo.qclass = xfr->dclass;
4270
0
  qinfo_query_encode(buf, &qinfo);
4271
0
  sldns_buffer_write_u16_at(buf, 0, id);
4272
0
}
4273
4274
/** create IXFR/AXFR packet for xfr */
4275
static void
4276
xfr_create_ixfr_packet(struct auth_xfer* xfr, sldns_buffer* buf, uint16_t id,
4277
  struct auth_master* master)
4278
0
{
4279
0
  struct query_info qinfo;
4280
0
  uint32_t serial;
4281
0
  int have_zone;
4282
0
  have_zone = xfr->have_zone;
4283
0
  serial = xfr->serial;
4284
4285
0
  memset(&qinfo, 0, sizeof(qinfo));
4286
0
  qinfo.qname = xfr->name;
4287
0
  qinfo.qname_len = xfr->namelen;
4288
0
  xfr->task_transfer->got_xfr_serial = 0;
4289
0
  xfr->task_transfer->rr_scan_num = 0;
4290
0
  xfr->task_transfer->incoming_xfr_serial = 0;
4291
0
  xfr->task_transfer->on_ixfr_is_axfr = 0;
4292
0
  xfr->task_transfer->on_ixfr = 1;
4293
0
  qinfo.qtype = LDNS_RR_TYPE_IXFR;
4294
0
  if(!have_zone || xfr->task_transfer->ixfr_fail || !master->ixfr) {
4295
0
    qinfo.qtype = LDNS_RR_TYPE_AXFR;
4296
0
    xfr->task_transfer->ixfr_fail = 0;
4297
0
    xfr->task_transfer->on_ixfr = 0;
4298
0
  }
4299
4300
0
  qinfo.qclass = xfr->dclass;
4301
0
  qinfo_query_encode(buf, &qinfo);
4302
0
  sldns_buffer_write_u16_at(buf, 0, id);
4303
4304
  /* append serial for IXFR */
4305
0
  if(qinfo.qtype == LDNS_RR_TYPE_IXFR) {
4306
0
    size_t end = sldns_buffer_limit(buf);
4307
0
    sldns_buffer_clear(buf);
4308
0
    sldns_buffer_set_position(buf, end);
4309
    /* auth section count 1 */
4310
0
    sldns_buffer_write_u16_at(buf, LDNS_NSCOUNT_OFF, 1);
4311
    /* write SOA */
4312
0
    sldns_buffer_write_u8(buf, 0xC0); /* compressed ptr to qname */
4313
0
    sldns_buffer_write_u8(buf, 0x0C);
4314
0
    sldns_buffer_write_u16(buf, LDNS_RR_TYPE_SOA);
4315
0
    sldns_buffer_write_u16(buf, qinfo.qclass);
4316
0
    sldns_buffer_write_u32(buf, 0); /* ttl */
4317
0
    sldns_buffer_write_u16(buf, 22); /* rdata length */
4318
0
    sldns_buffer_write_u8(buf, 0); /* . */
4319
0
    sldns_buffer_write_u8(buf, 0); /* . */
4320
0
    sldns_buffer_write_u32(buf, serial); /* serial */
4321
0
    sldns_buffer_write_u32(buf, 0); /* refresh */
4322
0
    sldns_buffer_write_u32(buf, 0); /* retry */
4323
0
    sldns_buffer_write_u32(buf, 0); /* expire */
4324
0
    sldns_buffer_write_u32(buf, 0); /* minimum */
4325
0
    sldns_buffer_flip(buf);
4326
0
  }
4327
0
}
4328
4329
/** check if returned packet is OK */
4330
static int
4331
check_packet_ok(sldns_buffer* pkt, uint16_t qtype, struct auth_xfer* xfr,
4332
  uint32_t* serial)
4333
0
{
4334
  /* parse to see if packet worked, valid reply */
4335
4336
  /* check serial number of SOA */
4337
0
  if(sldns_buffer_limit(pkt) < LDNS_HEADER_SIZE)
4338
0
    return 0;
4339
4340
  /* check ID */
4341
0
  if(LDNS_ID_WIRE(sldns_buffer_begin(pkt)) != xfr->task_probe->id)
4342
0
    return 0;
4343
4344
  /* check flag bits and rcode */
4345
0
  if(!LDNS_QR_WIRE(sldns_buffer_begin(pkt)))
4346
0
    return 0;
4347
0
  if(LDNS_OPCODE_WIRE(sldns_buffer_begin(pkt)) != LDNS_PACKET_QUERY)
4348
0
    return 0;
4349
0
  if(LDNS_RCODE_WIRE(sldns_buffer_begin(pkt)) != LDNS_RCODE_NOERROR)
4350
0
    return 0;
4351
4352
  /* check qname */
4353
0
  if(LDNS_QDCOUNT(sldns_buffer_begin(pkt)) != 1)
4354
0
    return 0;
4355
0
  sldns_buffer_skip(pkt, LDNS_HEADER_SIZE);
4356
0
  if(sldns_buffer_remaining(pkt) < xfr->namelen)
4357
0
    return 0;
4358
0
  if(query_dname_compare(sldns_buffer_current(pkt), xfr->name) != 0)
4359
0
    return 0;
4360
0
  sldns_buffer_skip(pkt, (ssize_t)xfr->namelen);
4361
4362
  /* check qtype, qclass */
4363
0
  if(sldns_buffer_remaining(pkt) < 4)
4364
0
    return 0;
4365
0
  if(sldns_buffer_read_u16(pkt) != qtype)
4366
0
    return 0;
4367
0
  if(sldns_buffer_read_u16(pkt) != xfr->dclass)
4368
0
    return 0;
4369
4370
0
  if(serial) {
4371
0
    uint16_t rdlen;
4372
    /* read serial number, from answer section SOA */
4373
0
    if(LDNS_ANCOUNT(sldns_buffer_begin(pkt)) == 0)
4374
0
      return 0;
4375
    /* read from first record SOA record */
4376
0
    if(sldns_buffer_remaining(pkt) < 1)
4377
0
      return 0;
4378
0
    if(dname_pkt_compare(pkt, sldns_buffer_current(pkt),
4379
0
      xfr->name) != 0)
4380
0
      return 0;
4381
0
    if(!pkt_dname_len(pkt))
4382
0
      return 0;
4383
    /* type, class, ttl, rdatalen */
4384
0
    if(sldns_buffer_remaining(pkt) < 4+4+2)
4385
0
      return 0;
4386
0
    if(sldns_buffer_read_u16(pkt) != qtype)
4387
0
      return 0;
4388
0
    if(sldns_buffer_read_u16(pkt) != xfr->dclass)
4389
0
      return 0;
4390
0
    sldns_buffer_skip(pkt, 4); /* ttl */
4391
0
    rdlen = sldns_buffer_read_u16(pkt);
4392
0
    if(sldns_buffer_remaining(pkt) < rdlen)
4393
0
      return 0;
4394
0
    if(sldns_buffer_remaining(pkt) < 1)
4395
0
      return 0;
4396
0
    if(!pkt_dname_len(pkt)) /* soa name */
4397
0
      return 0;
4398
0
    if(sldns_buffer_remaining(pkt) < 1)
4399
0
      return 0;
4400
0
    if(!pkt_dname_len(pkt)) /* soa name */
4401
0
      return 0;
4402
0
    if(sldns_buffer_remaining(pkt) < 20)
4403
0
      return 0;
4404
0
    *serial = sldns_buffer_read_u32(pkt);
4405
0
  }
4406
0
  return 1;
4407
0
}
4408
4409
/** read one line from chunks into buffer at current position */
4410
static int
4411
chunkline_get_line(struct auth_chunk** chunk, size_t* chunk_pos,
4412
  sldns_buffer* buf)
4413
0
{
4414
0
  int readsome = 0;
4415
0
  while(*chunk) {
4416
    /* more text in this chunk? */
4417
0
    if(*chunk_pos < (*chunk)->len) {
4418
0
      readsome = 1;
4419
0
      while(*chunk_pos < (*chunk)->len) {
4420
0
        char c = (char)((*chunk)->data[*chunk_pos]);
4421
0
        (*chunk_pos)++;
4422
0
        if(sldns_buffer_remaining(buf) < 2) {
4423
          /* buffer too short */
4424
0
          verbose(VERB_ALGO, "http chunkline, "
4425
0
            "line too long");
4426
0
          return 0;
4427
0
        }
4428
0
        sldns_buffer_write_u8(buf, (uint8_t)c);
4429
0
        if(c == '\n') {
4430
          /* we are done */
4431
0
          return 1;
4432
0
        }
4433
0
      }
4434
0
    }
4435
    /* move to next chunk */
4436
0
    *chunk = (*chunk)->next;
4437
0
    *chunk_pos = 0;
4438
0
  }
4439
  /* no more text */
4440
0
  if(readsome) return 1;
4441
0
  return 0;
4442
0
}
4443
4444
/** count number of open and closed parenthesis in a chunkline */
4445
static int
4446
chunkline_count_parens(sldns_buffer* buf, size_t start)
4447
0
{
4448
0
  size_t end = sldns_buffer_position(buf);
4449
0
  size_t i;
4450
0
  int count = 0;
4451
0
  int squote = 0, dquote = 0;
4452
0
  for(i=start; i<end; i++) {
4453
0
    char c = (char)sldns_buffer_read_u8_at(buf, i);
4454
0
    if(squote && c != '\'') continue;
4455
0
    if(dquote && c != '"') continue;
4456
0
    if(c == '"')
4457
0
      dquote = !dquote; /* skip quoted part */
4458
0
    else if(c == '\'')
4459
0
      squote = !squote; /* skip quoted part */
4460
0
    else if(c == '(')
4461
0
      count ++;
4462
0
    else if(c == ')')
4463
0
      count --;
4464
0
    else if(c == ';') {
4465
      /* rest is a comment */
4466
0
      return count;
4467
0
    }
4468
0
  }
4469
0
  return count;
4470
0
}
4471
4472
/** remove trailing ;... comment from a line in the chunkline buffer */
4473
static void
4474
chunkline_remove_trailcomment(sldns_buffer* buf, size_t start)
4475
0
{
4476
0
  size_t end = sldns_buffer_position(buf);
4477
0
  size_t i;
4478
0
  int squote = 0, dquote = 0;
4479
0
  for(i=start; i<end; i++) {
4480
0
    char c = (char)sldns_buffer_read_u8_at(buf, i);
4481
0
    if(squote && c != '\'') continue;
4482
0
    if(dquote && c != '"') continue;
4483
0
    if(c == '"')
4484
0
      dquote = !dquote; /* skip quoted part */
4485
0
    else if(c == '\'')
4486
0
      squote = !squote; /* skip quoted part */
4487
0
    else if(c == ';') {
4488
      /* rest is a comment */
4489
0
      sldns_buffer_set_position(buf, i);
4490
0
      return;
4491
0
    }
4492
0
  }
4493
  /* nothing to remove */
4494
0
}
4495
4496
/** see if a chunkline is a comment line (or empty line) */
4497
static int
4498
chunkline_is_comment_line_or_empty(sldns_buffer* buf)
4499
0
{
4500
0
  size_t i, end = sldns_buffer_limit(buf);
4501
0
  for(i=0; i<end; i++) {
4502
0
    char c = (char)sldns_buffer_read_u8_at(buf, i);
4503
0
    if(c == ';')
4504
0
      return 1; /* comment */
4505
0
    else if(c != ' ' && c != '\t' && c != '\r' && c != '\n')
4506
0
      return 0; /* not a comment */
4507
0
  }
4508
0
  return 1; /* empty */
4509
0
}
4510
4511
/** find a line with ( ) collated */
4512
static int
4513
chunkline_get_line_collated(struct auth_chunk** chunk, size_t* chunk_pos,
4514
  sldns_buffer* buf)
4515
0
{
4516
0
  size_t pos;
4517
0
  int parens = 0;
4518
0
  sldns_buffer_clear(buf);
4519
0
  pos = sldns_buffer_position(buf);
4520
0
  if(!chunkline_get_line(chunk, chunk_pos, buf)) {
4521
0
    if(sldns_buffer_position(buf) < sldns_buffer_limit(buf))
4522
0
      sldns_buffer_write_u8_at(buf, sldns_buffer_position(buf), 0);
4523
0
    else sldns_buffer_write_u8_at(buf, sldns_buffer_position(buf)-1, 0);
4524
0
    sldns_buffer_flip(buf);
4525
0
    return 0;
4526
0
  }
4527
0
  parens += chunkline_count_parens(buf, pos);
4528
0
  while(parens > 0) {
4529
0
    chunkline_remove_trailcomment(buf, pos);
4530
0
    pos = sldns_buffer_position(buf);
4531
0
    if(!chunkline_get_line(chunk, chunk_pos, buf)) {
4532
0
      if(sldns_buffer_position(buf) < sldns_buffer_limit(buf))
4533
0
        sldns_buffer_write_u8_at(buf, sldns_buffer_position(buf), 0);
4534
0
      else sldns_buffer_write_u8_at(buf, sldns_buffer_position(buf)-1, 0);
4535
0
      sldns_buffer_flip(buf);
4536
0
      return 0;
4537
0
    }
4538
0
    parens += chunkline_count_parens(buf, pos);
4539
0
  }
4540
4541
0
  if(sldns_buffer_remaining(buf) < 1) {
4542
0
    verbose(VERB_ALGO, "http chunkline: "
4543
0
      "line too long");
4544
0
    return 0;
4545
0
  }
4546
0
  sldns_buffer_write_u8_at(buf, sldns_buffer_position(buf), 0);
4547
0
  sldns_buffer_flip(buf);
4548
0
  return 1;
4549
0
}
4550
4551
/** process $ORIGIN for http, 0 nothing, 1 done, 2 error */
4552
static int
4553
http_parse_origin(sldns_buffer* buf, struct sldns_file_parse_state* pstate)
4554
0
{
4555
0
  char* line = (char*)sldns_buffer_begin(buf);
4556
0
  if(strncmp(line, "$ORIGIN", 7) == 0 &&
4557
0
    isspace((unsigned char)line[7])) {
4558
0
    int s;
4559
0
    pstate->origin_len = sizeof(pstate->origin);
4560
0
    s = sldns_str2wire_dname_buf(sldns_strip_ws(line+8),
4561
0
      pstate->origin, &pstate->origin_len);
4562
0
    if(s) {
4563
0
      pstate->origin_len = 0;
4564
0
      return 2;
4565
0
    }
4566
0
    return 1;
4567
0
  }
4568
0
  return 0;
4569
0
}
4570
4571
/** process $TTL for http, 0 nothing, 1 done, 2 error */
4572
static int
4573
http_parse_ttl(sldns_buffer* buf, struct sldns_file_parse_state* pstate)
4574
0
{
4575
0
  char* line = (char*)sldns_buffer_begin(buf);
4576
0
  if(strncmp(line, "$TTL", 4) == 0 &&
4577
0
    isspace((unsigned char)line[4])) {
4578
0
    const char* end = NULL;
4579
0
    int overflow = 0;
4580
0
    pstate->default_ttl = sldns_str2period(
4581
0
      sldns_strip_ws(line+5), &end, &overflow);
4582
0
    if(overflow) {
4583
0
      return 2;
4584
0
    }
4585
0
    return 1;
4586
0
  }
4587
0
  return 0;
4588
0
}
4589
4590
/** remove newlines from collated line */
4591
static void
4592
chunkline_newline_removal(sldns_buffer* buf)
4593
0
{
4594
0
  size_t i, end=sldns_buffer_limit(buf);
4595
0
  for(i=0; i<end; i++) {
4596
0
    char c = (char)sldns_buffer_read_u8_at(buf, i);
4597
0
    if(c == '\n' && i==end-1) {
4598
0
      sldns_buffer_write_u8_at(buf, i, 0);
4599
0
      sldns_buffer_set_limit(buf, end-1);
4600
0
      return;
4601
0
    }
4602
0
    if(c == '\n')
4603
0
      sldns_buffer_write_u8_at(buf, i, (uint8_t)' ');
4604
0
  }
4605
0
}
4606
4607
/** find noncomment RR line in chunks, collates lines if ( ) format */
4608
static int
4609
chunkline_non_comment_RR(struct auth_chunk** chunk, size_t* chunk_pos,
4610
  sldns_buffer* buf, struct sldns_file_parse_state* pstate)
4611
0
{
4612
0
  int ret;
4613
0
  while(chunkline_get_line_collated(chunk, chunk_pos, buf)) {
4614
0
    chunkline_newline_removal(buf);
4615
0
    if(chunkline_is_comment_line_or_empty(buf)) {
4616
      /* a comment, go to next line */
4617
0
      continue;
4618
0
    }
4619
0
    if((ret=http_parse_origin(buf, pstate))!=0) {
4620
0
      if(ret == 2)
4621
0
        return 0;
4622
0
      continue; /* $ORIGIN has been handled */
4623
0
    }
4624
0
    if((ret=http_parse_ttl(buf, pstate))!=0) {
4625
0
      if(ret == 2)
4626
0
        return 0;
4627
0
      continue; /* $TTL has been handled */
4628
0
    }
4629
0
    return 1;
4630
0
  }
4631
  /* no noncomments, fail */
4632
0
  return 0;
4633
0
}
4634
4635
/** check syntax of chunklist zonefile, parse first RR, return false on
4636
 * failure and return a string in the scratch buffer (first RR string)
4637
 * on failure. */
4638
static int
4639
http_zonefile_syntax_check(struct auth_xfer* xfr, sldns_buffer* buf)
4640
0
{
4641
0
  uint8_t rr[LDNS_RR_BUF_SIZE];
4642
0
  size_t rr_len, dname_len = 0;
4643
0
  struct sldns_file_parse_state pstate;
4644
0
  struct auth_chunk* chunk;
4645
0
  size_t chunk_pos;
4646
0
  int e;
4647
0
  memset(&pstate, 0, sizeof(pstate));
4648
0
  pstate.default_ttl = 3600;
4649
0
  if(xfr->namelen < sizeof(pstate.origin)) {
4650
0
    pstate.origin_len = xfr->namelen;
4651
0
    memmove(pstate.origin, xfr->name, xfr->namelen);
4652
0
  }
4653
0
  chunk = xfr->task_transfer->chunks_first;
4654
0
  chunk_pos = 0;
4655
0
  if(!chunkline_non_comment_RR(&chunk, &chunk_pos, buf, &pstate)) {
4656
0
    return 0;
4657
0
  }
4658
0
  rr_len = sizeof(rr);
4659
0
  e=sldns_str2wire_rr_buf((char*)sldns_buffer_begin(buf), rr, &rr_len,
4660
0
    &dname_len, pstate.default_ttl,
4661
0
    pstate.origin_len?pstate.origin:NULL, pstate.origin_len,
4662
0
    pstate.prev_rr_len?pstate.prev_rr:NULL, pstate.prev_rr_len);
4663
0
  if(e != 0) {
4664
0
    log_err("parse failure on first RR[%d]: %s",
4665
0
      LDNS_WIREPARSE_OFFSET(e),
4666
0
      sldns_get_errorstr_parse(LDNS_WIREPARSE_ERROR(e)));
4667
0
    return 0;
4668
0
  }
4669
  /* check that class is correct */
4670
0
  if(sldns_wirerr_get_class(rr, rr_len, dname_len) != xfr->dclass) {
4671
0
    log_err("parse failure: first record in downloaded zonefile "
4672
0
      "from wrong RR class");
4673
0
    return 0;
4674
0
  }
4675
0
  return 1;
4676
0
}
4677
4678
/** sum sizes of chunklist */
4679
static size_t
4680
chunklist_sum(struct auth_chunk* list)
4681
0
{
4682
0
  struct auth_chunk* p;
4683
0
  size_t s = 0;
4684
0
  for(p=list; p; p=p->next) {
4685
0
    s += p->len;
4686
0
  }
4687
0
  return s;
4688
0
}
4689
4690
/** for http download, parse and add RR to zone */
4691
static int
4692
http_parse_add_rr(struct auth_xfer* xfr, struct auth_zone* z,
4693
  sldns_buffer* buf, struct sldns_file_parse_state* pstate)
4694
0
{
4695
0
  uint8_t rr[LDNS_RR_BUF_SIZE];
4696
0
  size_t rr_len, dname_len = 0;
4697
0
  int e;
4698
0
  char* line = (char*)sldns_buffer_begin(buf);
4699
0
  rr_len = sizeof(rr);
4700
0
  e = sldns_str2wire_rr_buf(line, rr, &rr_len, &dname_len,
4701
0
    pstate->default_ttl,
4702
0
    pstate->origin_len?pstate->origin:NULL, pstate->origin_len,
4703
0
    pstate->prev_rr_len?pstate->prev_rr:NULL, pstate->prev_rr_len);
4704
0
  if(e != 0) {
4705
0
    log_err("%s/%s parse failure RR[%d]: %s in '%s'",
4706
0
      xfr->task_transfer->master->host,
4707
0
      xfr->task_transfer->master->file,
4708
0
      LDNS_WIREPARSE_OFFSET(e),
4709
0
      sldns_get_errorstr_parse(LDNS_WIREPARSE_ERROR(e)),
4710
0
      line);
4711
0
    return 0;
4712
0
  }
4713
0
  if(rr_len == 0)
4714
0
    return 1; /* empty line or so */
4715
4716
  /* set prev */
4717
0
  if(dname_len < sizeof(pstate->prev_rr)) {
4718
0
    memmove(pstate->prev_rr, rr, dname_len);
4719
0
    pstate->prev_rr_len = dname_len;
4720
0
  }
4721
4722
0
  return az_insert_rr(z, rr, rr_len, dname_len, NULL);
4723
0
}
4724
4725
/** RR list iterator, returns RRs from answer section one by one from the
4726
 * dns packets in the chunklist */
4727
static void
4728
chunk_rrlist_start(struct auth_xfer* xfr, struct auth_chunk** rr_chunk,
4729
  int* rr_num, size_t* rr_pos)
4730
0
{
4731
0
  *rr_chunk = xfr->task_transfer->chunks_first;
4732
0
  *rr_num = 0;
4733
0
  *rr_pos = 0;
4734
0
}
4735
4736
/** RR list iterator, see if we are at the end of the list */
4737
static int
4738
chunk_rrlist_end(struct auth_chunk* rr_chunk, int rr_num)
4739
0
{
4740
0
  while(rr_chunk) {
4741
0
    if(rr_chunk->len < LDNS_HEADER_SIZE)
4742
0
      return 1;
4743
0
    if(rr_num < (int)LDNS_ANCOUNT(rr_chunk->data))
4744
0
      return 0;
4745
    /* no more RRs in this chunk */
4746
    /* continue with next chunk, see if it has RRs */
4747
0
    rr_chunk = rr_chunk->next;
4748
0
    rr_num = 0;
4749
0
  }
4750
0
  return 1;
4751
0
}
4752
4753
/** RR list iterator, move to next RR */
4754
static void
4755
chunk_rrlist_gonext(struct auth_chunk** rr_chunk, int* rr_num,
4756
  size_t* rr_pos, size_t rr_nextpos)
4757
0
{
4758
  /* already at end of chunks? */
4759
0
  if(!*rr_chunk)
4760
0
    return;
4761
  /* move within this chunk */
4762
0
  if((*rr_chunk)->len >= LDNS_HEADER_SIZE &&
4763
0
    (*rr_num)+1 < (int)LDNS_ANCOUNT((*rr_chunk)->data)) {
4764
0
    (*rr_num) += 1;
4765
0
    *rr_pos = rr_nextpos;
4766
0
    return;
4767
0
  }
4768
  /* no more RRs in this chunk */
4769
  /* continue with next chunk, see if it has RRs */
4770
0
  if(*rr_chunk)
4771
0
    *rr_chunk = (*rr_chunk)->next;
4772
0
  while(*rr_chunk) {
4773
0
    *rr_num = 0;
4774
0
    *rr_pos = 0;
4775
0
    if((*rr_chunk)->len >= LDNS_HEADER_SIZE &&
4776
0
      LDNS_ANCOUNT((*rr_chunk)->data) > 0) {
4777
0
      return;
4778
0
    }
4779
0
    *rr_chunk = (*rr_chunk)->next;
4780
0
  }
4781
0
}
4782
4783
/** RR iterator, get current RR information, false on parse error */
4784
static int
4785
chunk_rrlist_get_current(struct auth_chunk* rr_chunk, int rr_num,
4786
  size_t rr_pos, uint8_t** rr_dname, uint16_t* rr_type,
4787
  uint16_t* rr_class, uint32_t* rr_ttl, uint16_t* rr_rdlen,
4788
  uint8_t** rr_rdata, size_t* rr_nextpos)
4789
0
{
4790
0
  sldns_buffer pkt;
4791
  /* integrity checks on position */
4792
0
  if(!rr_chunk) return 0;
4793
0
  if(rr_chunk->len < LDNS_HEADER_SIZE) return 0;
4794
0
  if(rr_num >= (int)LDNS_ANCOUNT(rr_chunk->data)) return 0;
4795
0
  if(rr_pos >= rr_chunk->len) return 0;
4796
4797
  /* fetch rr information */
4798
0
  sldns_buffer_init_frm_data(&pkt, rr_chunk->data, rr_chunk->len);
4799
0
  if(rr_pos == 0) {
4800
0
    size_t i;
4801
    /* skip question section */
4802
0
    sldns_buffer_set_position(&pkt, LDNS_HEADER_SIZE);
4803
0
    for(i=0; i<LDNS_QDCOUNT(rr_chunk->data); i++) {
4804
0
      if(pkt_dname_len(&pkt) == 0) return 0;
4805
0
      if(sldns_buffer_remaining(&pkt) < 4) return 0;
4806
0
      sldns_buffer_skip(&pkt, 4); /* type and class */
4807
0
    }
4808
0
  } else  {
4809
0
    sldns_buffer_set_position(&pkt, rr_pos);
4810
0
  }
4811
0
  *rr_dname = sldns_buffer_current(&pkt);
4812
0
  if(pkt_dname_len(&pkt) == 0) return 0;
4813
0
  if(sldns_buffer_remaining(&pkt) < 10) return 0;
4814
0
  *rr_type = sldns_buffer_read_u16(&pkt);
4815
0
  *rr_class = sldns_buffer_read_u16(&pkt);
4816
0
  *rr_ttl = sldns_buffer_read_u32(&pkt);
4817
0
  *rr_rdlen = sldns_buffer_read_u16(&pkt);
4818
0
  if(sldns_buffer_remaining(&pkt) < (*rr_rdlen)) return 0;
4819
0
  *rr_rdata = sldns_buffer_current(&pkt);
4820
0
  sldns_buffer_skip(&pkt, (ssize_t)(*rr_rdlen));
4821
0
  *rr_nextpos = sldns_buffer_position(&pkt);
4822
0
  return 1;
4823
0
}
4824
4825
/** print log message where we are in parsing the zone transfer */
4826
static void
4827
log_rrlist_position(const char* label, struct auth_chunk* rr_chunk,
4828
  uint8_t* rr_dname, uint16_t rr_type, size_t rr_counter)
4829
0
{
4830
0
  sldns_buffer pkt;
4831
0
  size_t dlen;
4832
0
  uint8_t buf[LDNS_MAX_DOMAINLEN];
4833
0
  char str[LDNS_MAX_DOMAINLEN];
4834
0
  char typestr[32];
4835
0
  sldns_buffer_init_frm_data(&pkt, rr_chunk->data, rr_chunk->len);
4836
0
  sldns_buffer_set_position(&pkt, (size_t)(rr_dname -
4837
0
    sldns_buffer_begin(&pkt)));
4838
0
  if((dlen=pkt_dname_len(&pkt)) == 0) return;
4839
0
  if(dlen >= sizeof(buf)) return;
4840
0
  dname_pkt_copy(&pkt, buf, rr_dname);
4841
0
  dname_str(buf, str);
4842
0
  (void)sldns_wire2str_type_buf(rr_type, typestr, sizeof(typestr));
4843
0
  verbose(VERB_ALGO, "%s at[%d] %s %s", label, (int)rr_counter,
4844
0
    str, typestr);
4845
0
}
4846
4847
/** check that start serial is OK for ixfr. we are at rr_counter == 0,
4848
 * and we are going to check rr_counter == 1 (has to be type SOA) serial */
4849
static int
4850
ixfr_start_serial(struct auth_chunk* rr_chunk, int rr_num, size_t rr_pos,
4851
  uint8_t* rr_dname, uint16_t rr_type, uint16_t rr_class,
4852
  uint32_t rr_ttl, uint16_t rr_rdlen, uint8_t* rr_rdata,
4853
  size_t rr_nextpos, uint32_t transfer_serial, uint32_t xfr_serial)
4854
0
{
4855
0
  uint32_t startserial;
4856
  /* move forward on RR */
4857
0
  chunk_rrlist_gonext(&rr_chunk, &rr_num, &rr_pos, rr_nextpos);
4858
0
  if(chunk_rrlist_end(rr_chunk, rr_num)) {
4859
    /* no second SOA */
4860
0
    verbose(VERB_OPS, "IXFR has no second SOA record");
4861
0
    return 0;
4862
0
  }
4863
0
  if(!chunk_rrlist_get_current(rr_chunk, rr_num, rr_pos,
4864
0
    &rr_dname, &rr_type, &rr_class, &rr_ttl, &rr_rdlen,
4865
0
    &rr_rdata, &rr_nextpos)) {
4866
0
    verbose(VERB_OPS, "IXFR cannot parse second SOA record");
4867
    /* failed to parse RR */
4868
0
    return 0;
4869
0
  }
4870
0
  if(rr_type != LDNS_RR_TYPE_SOA) {
4871
0
    verbose(VERB_OPS, "IXFR second record is not type SOA");
4872
0
    return 0;
4873
0
  }
4874
0
  if(rr_rdlen < 22) {
4875
0
    verbose(VERB_OPS, "IXFR, second SOA has short rdlength");
4876
0
    return 0; /* bad SOA rdlen */
4877
0
  }
4878
0
  startserial = sldns_read_uint32(rr_rdata+rr_rdlen-20);
4879
0
  if(startserial == transfer_serial) {
4880
    /* empty AXFR, not an IXFR */
4881
0
    verbose(VERB_OPS, "IXFR second serial same as first");
4882
0
    return 0;
4883
0
  }
4884
0
  if(startserial != xfr_serial) {
4885
    /* wrong start serial, it does not match the serial in
4886
     * memory */
4887
0
    verbose(VERB_OPS, "IXFR is from serial %u to %u but %u "
4888
0
      "in memory, rejecting the zone transfer",
4889
0
      (unsigned)startserial, (unsigned)transfer_serial,
4890
0
      (unsigned)xfr_serial);
4891
0
    return 0;
4892
0
  }
4893
  /* everything OK in second SOA serial */
4894
0
  return 1;
4895
0
}
4896
4897
/** apply IXFR to zone in memory. z is locked. false on failure(mallocfail) */
4898
static int
4899
apply_ixfr(struct auth_xfer* xfr, struct auth_zone* z,
4900
  struct sldns_buffer* scratch_buffer)
4901
0
{
4902
0
  struct auth_chunk* rr_chunk;
4903
0
  int rr_num;
4904
0
  size_t rr_pos;
4905
0
  uint8_t* rr_dname, *rr_rdata;
4906
0
  uint16_t rr_type, rr_class, rr_rdlen;
4907
0
  uint32_t rr_ttl;
4908
0
  size_t rr_nextpos;
4909
0
  int have_transfer_serial = 0;
4910
0
  uint32_t transfer_serial = 0;
4911
0
  size_t rr_counter = 0;
4912
0
  int delmode = 0;
4913
0
  int softfail = 0;
4914
4915
  /* start RR iterator over chunklist of packets */
4916
0
  chunk_rrlist_start(xfr, &rr_chunk, &rr_num, &rr_pos);
4917
0
  while(!chunk_rrlist_end(rr_chunk, rr_num)) {
4918
0
    if(!chunk_rrlist_get_current(rr_chunk, rr_num, rr_pos,
4919
0
      &rr_dname, &rr_type, &rr_class, &rr_ttl, &rr_rdlen,
4920
0
      &rr_rdata, &rr_nextpos)) {
4921
      /* failed to parse RR */
4922
0
      return 0;
4923
0
    }
4924
0
    if(verbosity>=7) log_rrlist_position("apply ixfr",
4925
0
      rr_chunk, rr_dname, rr_type, rr_counter);
4926
    /* twiddle add/del mode and check for start and end */
4927
0
    if(rr_counter == 0 && rr_type != LDNS_RR_TYPE_SOA)
4928
0
      return 0;
4929
0
    if(rr_counter == 1 && rr_type != LDNS_RR_TYPE_SOA) {
4930
      /* this is an AXFR returned from the IXFR master */
4931
      /* but that should already have been detected, by
4932
       * on_ixfr_is_axfr */
4933
0
      return 0;
4934
0
    }
4935
0
    if(rr_type == LDNS_RR_TYPE_SOA) {
4936
0
      uint32_t serial;
4937
0
      if(rr_rdlen < 22) return 0; /* bad SOA rdlen */
4938
0
      serial = sldns_read_uint32(rr_rdata+rr_rdlen-20);
4939
0
      if(have_transfer_serial == 0) {
4940
0
        have_transfer_serial = 1;
4941
0
        transfer_serial = serial;
4942
0
        delmode = 1; /* gets negated below */
4943
        /* check second RR before going any further */
4944
0
        if(!ixfr_start_serial(rr_chunk, rr_num, rr_pos,
4945
0
          rr_dname, rr_type, rr_class, rr_ttl,
4946
0
          rr_rdlen, rr_rdata, rr_nextpos,
4947
0
          transfer_serial, xfr->serial)) {
4948
0
          return 0;
4949
0
        }
4950
0
      } else if(transfer_serial == serial) {
4951
0
        have_transfer_serial++;
4952
0
        if(rr_counter == 1) {
4953
          /* empty AXFR, with SOA; SOA; */
4954
          /* should have been detected by
4955
           * on_ixfr_is_axfr */
4956
0
          return 0;
4957
0
        }
4958
0
        if(have_transfer_serial == 3) {
4959
          /* see serial three times for end */
4960
          /* eg. IXFR:
4961
           *  SOA 3 start
4962
           *  SOA 1 second RR, followed by del
4963
           *  SOA 2 followed by add
4964
           *  SOA 2 followed by del
4965
           *  SOA 3 followed by add
4966
           *  SOA 3 end */
4967
          /* ended by SOA record */
4968
0
          xfr->serial = transfer_serial;
4969
0
          break;
4970
0
        }
4971
0
      }
4972
      /* twiddle add/del mode */
4973
      /* switch from delete part to add part and back again
4974
       * just before the soa, it gets deleted and added too
4975
       * this means we switch to delete mode for the final
4976
       * SOA(so skip that one) */
4977
0
      delmode = !delmode;
4978
0
    }
4979
    /* process this RR */
4980
    /* if the RR is deleted twice or added twice, then we 
4981
     * softfail, and continue with the rest of the IXFR, so
4982
     * that we serve something fairly nice during the refetch */
4983
0
    if(verbosity>=7) log_rrlist_position((delmode?"del":"add"),
4984
0
      rr_chunk, rr_dname, rr_type, rr_counter);
4985
0
    if(delmode) {
4986
      /* delete this RR */
4987
0
      int nonexist = 0;
4988
0
      if(!az_remove_rr_decompress(z, rr_chunk->data,
4989
0
        rr_chunk->len, scratch_buffer, rr_dname,
4990
0
        rr_type, rr_class, rr_ttl, rr_rdata, rr_rdlen,
4991
0
        &nonexist)) {
4992
        /* failed, malloc error or so */
4993
0
        return 0;
4994
0
      }
4995
0
      if(nonexist) {
4996
        /* it was removal of a nonexisting RR */
4997
0
        if(verbosity>=4) log_rrlist_position(
4998
0
          "IXFR error nonexistent RR",
4999
0
          rr_chunk, rr_dname, rr_type, rr_counter);
5000
0
        softfail = 1;
5001
0
      }
5002
0
    } else if(rr_counter != 0) {
5003
      /* skip first SOA RR for addition, it is added in
5004
       * the addition part near the end of the ixfr, when
5005
       * that serial is seen the second time. */
5006
0
      int duplicate = 0;
5007
      /* add this RR */
5008
0
      if(!az_insert_rr_decompress(z, rr_chunk->data,
5009
0
        rr_chunk->len, scratch_buffer, rr_dname,
5010
0
        rr_type, rr_class, rr_ttl, rr_rdata, rr_rdlen,
5011
0
        &duplicate)) {
5012
        /* failed, malloc error or so */
5013
0
        return 0;
5014
0
      }
5015
0
      if(duplicate) {
5016
        /* it was a duplicate */
5017
0
        if(verbosity>=4) log_rrlist_position(
5018
0
          "IXFR error duplicate RR",
5019
0
          rr_chunk, rr_dname, rr_type, rr_counter);
5020
0
        softfail = 1;
5021
0
      }
5022
0
    }
5023
5024
0
    rr_counter++;
5025
0
    chunk_rrlist_gonext(&rr_chunk, &rr_num, &rr_pos, rr_nextpos);
5026
0
  }
5027
0
  if(softfail) {
5028
0
    verbose(VERB_ALGO, "IXFR did not apply cleanly, fetching full zone");
5029
0
    return 0;
5030
0
  }
5031
0
  return 1;
5032
0
}
5033
5034
/** apply AXFR to zone in memory. z is locked. false on failure(mallocfail) */
5035
static int
5036
apply_axfr(struct auth_xfer* xfr, struct auth_zone* z,
5037
  struct sldns_buffer* scratch_buffer)
5038
0
{
5039
0
  struct auth_chunk* rr_chunk;
5040
0
  int rr_num;
5041
0
  size_t rr_pos;
5042
0
  uint8_t* rr_dname, *rr_rdata;
5043
0
  uint16_t rr_type, rr_class, rr_rdlen;
5044
0
  uint32_t rr_ttl;
5045
0
  uint32_t serial = 0;
5046
0
  size_t rr_nextpos;
5047
0
  size_t rr_counter = 0;
5048
0
  int have_end_soa = 0;
5049
5050
  /* clear the data tree */
5051
0
  traverse_postorder(&z->data, auth_data_del, NULL);
5052
0
  rbtree_init(&z->data, &auth_data_cmp);
5053
  /* clear the RPZ policies */
5054
0
  if(z->rpz)
5055
0
    rpz_clear(z->rpz);
5056
5057
0
  xfr->have_zone = 0;
5058
0
  xfr->serial = 0;
5059
0
  xfr->soa_zone_acquired = 0;
5060
5061
  /* insert all RRs in to the zone */
5062
  /* insert the SOA only once, skip the last one */
5063
  /* start RR iterator over chunklist of packets */
5064
0
  chunk_rrlist_start(xfr, &rr_chunk, &rr_num, &rr_pos);
5065
0
  while(!chunk_rrlist_end(rr_chunk, rr_num)) {
5066
0
    if(!chunk_rrlist_get_current(rr_chunk, rr_num, rr_pos,
5067
0
      &rr_dname, &rr_type, &rr_class, &rr_ttl, &rr_rdlen,
5068
0
      &rr_rdata, &rr_nextpos)) {
5069
      /* failed to parse RR */
5070
0
      return 0;
5071
0
    }
5072
0
    if(verbosity>=7) log_rrlist_position("apply_axfr",
5073
0
      rr_chunk, rr_dname, rr_type, rr_counter);
5074
0
    if(rr_type == LDNS_RR_TYPE_SOA) {
5075
0
      if(rr_counter != 0) {
5076
        /* end of the axfr */
5077
0
        have_end_soa = 1;
5078
0
        break;
5079
0
      }
5080
0
      if(rr_rdlen < 22) return 0; /* bad SOA rdlen */
5081
0
      serial = sldns_read_uint32(rr_rdata+rr_rdlen-20);
5082
0
    }
5083
5084
    /* add this RR */
5085
0
    if(!az_insert_rr_decompress(z, rr_chunk->data, rr_chunk->len,
5086
0
      scratch_buffer, rr_dname, rr_type, rr_class, rr_ttl,
5087
0
      rr_rdata, rr_rdlen, NULL)) {
5088
      /* failed, malloc error or so */
5089
0
      return 0;
5090
0
    }
5091
5092
0
    rr_counter++;
5093
0
    chunk_rrlist_gonext(&rr_chunk, &rr_num, &rr_pos, rr_nextpos);
5094
0
  }
5095
0
  if(!have_end_soa) {
5096
0
    log_err("no end SOA record for AXFR");
5097
0
    return 0;
5098
0
  }
5099
5100
0
  xfr->serial = serial;
5101
0
  xfr->have_zone = 1;
5102
0
  return 1;
5103
0
}
5104
5105
/** apply HTTP to zone in memory. z is locked. false on failure(mallocfail) */
5106
static int
5107
apply_http(struct auth_xfer* xfr, struct auth_zone* z,
5108
  struct sldns_buffer* scratch_buffer)
5109
0
{
5110
  /* parse data in chunks */
5111
  /* parse RR's and read into memory. ignore $INCLUDE from the
5112
   * downloaded file*/
5113
0
  struct sldns_file_parse_state pstate;
5114
0
  struct auth_chunk* chunk;
5115
0
  size_t chunk_pos;
5116
0
  int ret;
5117
0
  memset(&pstate, 0, sizeof(pstate));
5118
0
  pstate.default_ttl = 3600;
5119
0
  if(xfr->namelen < sizeof(pstate.origin)) {
5120
0
    pstate.origin_len = xfr->namelen;
5121
0
    memmove(pstate.origin, xfr->name, xfr->namelen);
5122
0
  }
5123
5124
0
  if(verbosity >= VERB_ALGO)
5125
0
    verbose(VERB_ALGO, "http download %s of size %d",
5126
0
    xfr->task_transfer->master->file,
5127
0
    (int)chunklist_sum(xfr->task_transfer->chunks_first));
5128
0
  if(xfr->task_transfer->chunks_first && verbosity >= VERB_ALGO) {
5129
0
    char preview[1024];
5130
0
    if(xfr->task_transfer->chunks_first->len+1 > sizeof(preview)) {
5131
0
      memmove(preview, xfr->task_transfer->chunks_first->data,
5132
0
        sizeof(preview)-1);
5133
0
      preview[sizeof(preview)-1]=0;
5134
0
    } else {
5135
0
      memmove(preview, xfr->task_transfer->chunks_first->data,
5136
0
        xfr->task_transfer->chunks_first->len);
5137
0
      preview[xfr->task_transfer->chunks_first->len]=0;
5138
0
    }
5139
0
    log_info("auth zone http downloaded content preview: %s",
5140
0
      preview);
5141
0
  }
5142
5143
  /* perhaps a little syntax check before we try to apply the data? */
5144
0
  if(!http_zonefile_syntax_check(xfr, scratch_buffer)) {
5145
0
    log_err("http download %s/%s does not contain a zonefile, "
5146
0
      "but got '%s'", xfr->task_transfer->master->host,
5147
0
      xfr->task_transfer->master->file,
5148
0
      sldns_buffer_begin(scratch_buffer));
5149
0
    return 0;
5150
0
  }
5151
5152
  /* clear the data tree */
5153
0
  traverse_postorder(&z->data, auth_data_del, NULL);
5154
0
  rbtree_init(&z->data, &auth_data_cmp);
5155
  /* clear the RPZ policies */
5156
0
  if(z->rpz)
5157
0
    rpz_clear(z->rpz);
5158
5159
0
  xfr->have_zone = 0;
5160
0
  xfr->serial = 0;
5161
0
  xfr->soa_zone_acquired = 0;
5162
5163
0
  chunk = xfr->task_transfer->chunks_first;
5164
0
  chunk_pos = 0;
5165
0
  pstate.lineno = 0;
5166
0
  while(chunkline_get_line_collated(&chunk, &chunk_pos, scratch_buffer)) {
5167
    /* process this line */
5168
0
    pstate.lineno++;
5169
0
    chunkline_newline_removal(scratch_buffer);
5170
0
    if(chunkline_is_comment_line_or_empty(scratch_buffer)) {
5171
0
      continue;
5172
0
    }
5173
    /* parse line and add RR */
5174
0
    if((ret=http_parse_origin(scratch_buffer, &pstate))!=0) {
5175
0
      if(ret == 2) {
5176
0
        verbose(VERB_ALGO, "error parsing ORIGIN on line [%s:%d] %s",
5177
0
          xfr->task_transfer->master->file,
5178
0
          pstate.lineno,
5179
0
          sldns_buffer_begin(scratch_buffer));
5180
0
        return 0;
5181
0
      }
5182
0
      continue; /* $ORIGIN has been handled */
5183
0
    }
5184
0
    if((ret=http_parse_ttl(scratch_buffer, &pstate))!=0) {
5185
0
      if(ret == 2) {
5186
0
        verbose(VERB_ALGO, "error parsing TTL on line [%s:%d] %s",
5187
0
          xfr->task_transfer->master->file,
5188
0
          pstate.lineno,
5189
0
          sldns_buffer_begin(scratch_buffer));
5190
0
        return 0;
5191
0
      }
5192
0
      continue; /* $TTL has been handled */
5193
0
    }
5194
0
    if(!http_parse_add_rr(xfr, z, scratch_buffer, &pstate)) {
5195
0
      verbose(VERB_ALGO, "error parsing line [%s:%d] %s",
5196
0
        xfr->task_transfer->master->file,
5197
0
        pstate.lineno,
5198
0
        sldns_buffer_begin(scratch_buffer));
5199
0
      return 0;
5200
0
    }
5201
0
  }
5202
0
  return 1;
5203
0
}
5204
5205
/** write http chunks to zonefile to create downloaded file */
5206
static int
5207
auth_zone_write_chunks(struct auth_xfer* xfr, const char* fname)
5208
0
{
5209
0
  FILE* out;
5210
0
  struct auth_chunk* p;
5211
0
  out = fopen(fname, "w");
5212
0
  if(!out) {
5213
0
    log_err("could not open %s: %s", fname, strerror(errno));
5214
0
    return 0;
5215
0
  }
5216
0
  for(p = xfr->task_transfer->chunks_first; p ; p = p->next) {
5217
0
    if(!write_out(out, (char*)p->data, p->len)) {
5218
0
      log_err("could not write http download to %s", fname);
5219
0
      fclose(out);
5220
0
      return 0;
5221
0
    }
5222
0
  }
5223
0
  fclose(out);
5224
0
  return 1;
5225
0
}
5226
5227
/** write to zonefile after zone has been updated */
5228
static void
5229
xfr_write_after_update(struct auth_xfer* xfr, struct module_env* env)
5230
0
{
5231
0
  struct config_file* cfg = env->cfg;
5232
0
  struct auth_zone* z;
5233
0
  char tmpfile[1024];
5234
0
  char* zfilename;
5235
0
  lock_basic_unlock(&xfr->lock);
5236
5237
  /* get lock again, so it is a readlock and concurrently queries
5238
   * can be answered */
5239
0
  lock_rw_rdlock(&env->auth_zones->lock);
5240
0
  z = auth_zone_find(env->auth_zones, xfr->name, xfr->namelen,
5241
0
    xfr->dclass);
5242
0
  if(!z) {
5243
0
    lock_rw_unlock(&env->auth_zones->lock);
5244
    /* the zone is gone, ignore xfr results */
5245
0
    lock_basic_lock(&xfr->lock);
5246
0
    return;
5247
0
  }
5248
0
  lock_rw_rdlock(&z->lock);
5249
0
  lock_basic_lock(&xfr->lock);
5250
0
  lock_rw_unlock(&env->auth_zones->lock);
5251
5252
0
  if(z->zonefile == NULL || z->zonefile[0] == 0) {
5253
0
    lock_rw_unlock(&z->lock);
5254
    /* no write needed, no zonefile set */
5255
0
    return;
5256
0
  }
5257
0
  zfilename = z->zonefile;
5258
0
  if(cfg->chrootdir && cfg->chrootdir[0] && strncmp(zfilename,
5259
0
    cfg->chrootdir, strlen(cfg->chrootdir)) == 0)
5260
0
    zfilename += strlen(cfg->chrootdir);
5261
0
  if(verbosity >= VERB_ALGO) {
5262
0
    char nm[LDNS_MAX_DOMAINLEN];
5263
0
    dname_str(z->name, nm);
5264
0
    verbose(VERB_ALGO, "write zonefile %s for %s", zfilename, nm);
5265
0
  }
5266
5267
  /* write to tempfile first */
5268
0
  if((size_t)strlen(zfilename) + 16 > sizeof(tmpfile)) {
5269
0
    verbose(VERB_ALGO, "tmpfilename too long, cannot update "
5270
0
      " zonefile %s", zfilename);
5271
0
    lock_rw_unlock(&z->lock);
5272
0
    return;
5273
0
  }
5274
0
  snprintf(tmpfile, sizeof(tmpfile), "%s.tmp%u", zfilename,
5275
0
    (unsigned)getpid());
5276
0
  if(xfr->task_transfer->master->http) {
5277
    /* use the stored chunk list to write them */
5278
0
    if(!auth_zone_write_chunks(xfr, tmpfile)) {
5279
0
      unlink(tmpfile);
5280
0
      lock_rw_unlock(&z->lock);
5281
0
      return;
5282
0
    }
5283
0
  } else if(!auth_zone_write_file(z, tmpfile)) {
5284
0
    unlink(tmpfile);
5285
0
    lock_rw_unlock(&z->lock);
5286
0
    return;
5287
0
  }
5288
#ifdef UB_ON_WINDOWS
5289
  (void)unlink(zfilename); /* windows does not replace file with rename() */
5290
#endif
5291
0
  if(rename(tmpfile, zfilename) < 0) {
5292
0
    log_err("could not rename(%s, %s): %s", tmpfile, zfilename,
5293
0
      strerror(errno));
5294
0
    unlink(tmpfile);
5295
0
    lock_rw_unlock(&z->lock);
5296
0
    return;
5297
0
  }
5298
0
  lock_rw_unlock(&z->lock);
5299
0
}
5300
5301
/** reacquire locks and structures. Starts with no locks, ends
5302
 * with xfr and z locks, if fail, no z lock */
5303
static int xfr_process_reacquire_locks(struct auth_xfer* xfr,
5304
  struct module_env* env, struct auth_zone** z)
5305
0
{
5306
  /* release xfr lock, then, while holding az->lock grab both
5307
   * z->lock and xfr->lock */
5308
0
  lock_rw_rdlock(&env->auth_zones->lock);
5309
0
  *z = auth_zone_find(env->auth_zones, xfr->name, xfr->namelen,
5310
0
    xfr->dclass);
5311
0
  if(!*z) {
5312
0
    lock_rw_unlock(&env->auth_zones->lock);
5313
0
    lock_basic_lock(&xfr->lock);
5314
0
    *z = NULL;
5315
0
    return 0;
5316
0
  }
5317
0
  lock_rw_wrlock(&(*z)->lock);
5318
0
  lock_basic_lock(&xfr->lock);
5319
0
  lock_rw_unlock(&env->auth_zones->lock);
5320
0
  return 1;
5321
0
}
5322
5323
/** process chunk list and update zone in memory,
5324
 * return false if it did not work */
5325
static int
5326
xfr_process_chunk_list(struct auth_xfer* xfr, struct module_env* env,
5327
  int* ixfr_fail)
5328
0
{
5329
0
  struct auth_zone* z;
5330
5331
  /* obtain locks and structures */
5332
0
  lock_basic_unlock(&xfr->lock);
5333
0
  if(!xfr_process_reacquire_locks(xfr, env, &z)) {
5334
    /* the zone is gone, ignore xfr results */
5335
0
    return 0;
5336
0
  }
5337
  /* holding xfr and z locks */
5338
5339
  /* apply data */
5340
0
  if(xfr->task_transfer->master->http) {
5341
0
    if(!apply_http(xfr, z, env->scratch_buffer)) {
5342
0
      lock_rw_unlock(&z->lock);
5343
0
      verbose(VERB_ALGO, "http from %s: could not store data",
5344
0
        xfr->task_transfer->master->host);
5345
0
      return 0;
5346
0
    }
5347
0
  } else if(xfr->task_transfer->on_ixfr &&
5348
0
    !xfr->task_transfer->on_ixfr_is_axfr) {
5349
0
    if(!apply_ixfr(xfr, z, env->scratch_buffer)) {
5350
0
      lock_rw_unlock(&z->lock);
5351
0
      verbose(VERB_ALGO, "xfr from %s: could not store IXFR"
5352
0
        " data", xfr->task_transfer->master->host);
5353
0
      *ixfr_fail = 1;
5354
0
      return 0;
5355
0
    }
5356
0
  } else {
5357
0
    if(!apply_axfr(xfr, z, env->scratch_buffer)) {
5358
0
      lock_rw_unlock(&z->lock);
5359
0
      verbose(VERB_ALGO, "xfr from %s: could not store AXFR"
5360
0
        " data", xfr->task_transfer->master->host);
5361
0
      return 0;
5362
0
    }
5363
0
  }
5364
0
  xfr->zone_expired = 0;
5365
0
  z->zone_expired = 0;
5366
0
  if(!xfr_find_soa(z, xfr)) {
5367
0
    lock_rw_unlock(&z->lock);
5368
0
    verbose(VERB_ALGO, "xfr from %s: no SOA in zone after update"
5369
0
      " (or malformed RR)", xfr->task_transfer->master->host);
5370
0
    return 0;
5371
0
  }
5372
0
  z->soa_zone_acquired = *env->now;
5373
0
  xfr->soa_zone_acquired = *env->now;
5374
5375
  /* release xfr lock while verifying zonemd because it may have
5376
   * to spawn lookups in the state machines */
5377
0
  lock_basic_unlock(&xfr->lock);
5378
  /* holding z lock */
5379
0
  auth_zone_verify_zonemd(z, env, &env->mesh->mods, NULL, 0, 0);
5380
0
  if(z->zone_expired) {
5381
0
    char zname[LDNS_MAX_DOMAINLEN];
5382
    /* ZONEMD must have failed */
5383
    /* reacquire locks, so we hold xfr lock on exit of routine,
5384
     * and both xfr and z again after releasing xfr for potential
5385
     * state machine mesh callbacks */
5386
0
    lock_rw_unlock(&z->lock);
5387
0
    if(!xfr_process_reacquire_locks(xfr, env, &z))
5388
0
      return 0;
5389
0
    dname_str(xfr->name, zname);
5390
0
    verbose(VERB_ALGO, "xfr from %s: ZONEMD failed for %s, transfer is failed", xfr->task_transfer->master->host, zname);
5391
0
    xfr->zone_expired = 1;
5392
0
    lock_rw_unlock(&z->lock);
5393
0
    return 0;
5394
0
  }
5395
  /* reacquire locks, so we hold xfr lock on exit of routine,
5396
   * and both xfr and z again after releasing xfr for potential
5397
   * state machine mesh callbacks */
5398
0
  lock_rw_unlock(&z->lock);
5399
0
  if(!xfr_process_reacquire_locks(xfr, env, &z))
5400
0
    return 0;
5401
  /* holding xfr and z locks */
5402
5403
0
  if(xfr->have_zone)
5404
0
    xfr->lease_time = *env->now;
5405
5406
0
  if(z->rpz)
5407
0
    rpz_finish_config(z->rpz);
5408
5409
  /* unlock */
5410
0
  lock_rw_unlock(&z->lock);
5411
5412
0
  if(verbosity >= VERB_QUERY && xfr->have_zone) {
5413
0
    char zname[LDNS_MAX_DOMAINLEN];
5414
0
    dname_str(xfr->name, zname);
5415
0
    verbose(VERB_QUERY, "auth zone %s updated to serial %u", zname,
5416
0
      (unsigned)xfr->serial);
5417
0
  }
5418
  /* see if we need to write to a zonefile */
5419
0
  xfr_write_after_update(xfr, env);
5420
0
  return 1;
5421
0
}
5422
5423
/** disown task_transfer.  caller must hold xfr.lock */
5424
static void
5425
xfr_transfer_disown(struct auth_xfer* xfr)
5426
0
{
5427
  /* remove timer (from this worker's event base) */
5428
0
  comm_timer_delete(xfr->task_transfer->timer);
5429
0
  xfr->task_transfer->timer = NULL;
5430
  /* remove the commpoint */
5431
0
  comm_point_delete(xfr->task_transfer->cp);
5432
0
  xfr->task_transfer->cp = NULL;
5433
  /* we don't own this item anymore */
5434
0
  xfr->task_transfer->worker = NULL;
5435
0
  xfr->task_transfer->env = NULL;
5436
0
}
5437
5438
/** lookup a host name for its addresses, if needed */
5439
static int
5440
xfr_transfer_lookup_host(struct auth_xfer* xfr, struct module_env* env)
5441
0
{
5442
0
  struct sockaddr_storage addr;
5443
0
  socklen_t addrlen = 0;
5444
0
  struct auth_master* master = xfr->task_transfer->lookup_target;
5445
0
  struct query_info qinfo;
5446
0
  uint16_t qflags = BIT_RD;
5447
0
  uint8_t dname[LDNS_MAX_DOMAINLEN+1];
5448
0
  struct edns_data edns;
5449
0
  sldns_buffer* buf = env->scratch_buffer;
5450
0
  if(!master) return 0;
5451
0
  if(extstrtoaddr(master->host, &addr, &addrlen, UNBOUND_DNS_PORT)) {
5452
    /* not needed, host is in IP addr format */
5453
0
    return 0;
5454
0
  }
5455
0
  if(master->allow_notify)
5456
0
    return 0; /* allow-notifies are not transferred from, no
5457
    lookup is needed */
5458
5459
  /* use mesh_new_callback to probe for non-addr hosts,
5460
   * and then wait for them to be looked up (in cache, or query) */
5461
0
  qinfo.qname_len = sizeof(dname);
5462
0
  if(sldns_str2wire_dname_buf(master->host, dname, &qinfo.qname_len)
5463
0
    != 0) {
5464
0
    log_err("cannot parse host name of master %s", master->host);
5465
0
    return 0;
5466
0
  }
5467
0
  qinfo.qname = dname;
5468
0
  qinfo.qclass = xfr->dclass;
5469
0
  qinfo.qtype = LDNS_RR_TYPE_A;
5470
0
  if(xfr->task_transfer->lookup_aaaa)
5471
0
    qinfo.qtype = LDNS_RR_TYPE_AAAA;
5472
0
  qinfo.local_alias = NULL;
5473
0
  if(verbosity >= VERB_ALGO) {
5474
0
    char buf1[512];
5475
0
    char buf2[LDNS_MAX_DOMAINLEN];
5476
0
    dname_str(xfr->name, buf2);
5477
0
    snprintf(buf1, sizeof(buf1), "auth zone %s: master lookup"
5478
0
      " for task_transfer", buf2);
5479
0
    log_query_info(VERB_ALGO, buf1, &qinfo);
5480
0
  }
5481
0
  edns.edns_present = 1;
5482
0
  edns.ext_rcode = 0;
5483
0
  edns.edns_version = 0;
5484
0
  edns.bits = EDNS_DO;
5485
0
  edns.opt_list_in = NULL;
5486
0
  edns.opt_list_out = NULL;
5487
0
  edns.opt_list_inplace_cb_out = NULL;
5488
0
  edns.padding_block_size = 0;
5489
0
  edns.cookie_present = 0;
5490
0
  edns.cookie_valid = 0;
5491
0
  if(sldns_buffer_capacity(buf) < 65535)
5492
0
    edns.udp_size = (uint16_t)sldns_buffer_capacity(buf);
5493
0
  else  edns.udp_size = 65535;
5494
5495
  /* unlock xfr during mesh_new_callback() because the callback can be
5496
   * called straight away */
5497
0
  lock_basic_unlock(&xfr->lock);
5498
0
  if(!mesh_new_callback(env->mesh, &qinfo, qflags, &edns, buf, 0,
5499
0
    &auth_xfer_transfer_lookup_callback, xfr, 0)) {
5500
0
    lock_basic_lock(&xfr->lock);
5501
0
    log_err("out of memory lookup up master %s", master->host);
5502
0
    return 0;
5503
0
  }
5504
0
  lock_basic_lock(&xfr->lock);
5505
0
  return 1;
5506
0
}
5507
5508
/** initiate TCP to the target and fetch zone.
5509
 * returns true if that was successfully started, and timeout setup. */
5510
static int
5511
xfr_transfer_init_fetch(struct auth_xfer* xfr, struct module_env* env)
5512
0
{
5513
0
  struct sockaddr_storage addr;
5514
0
  socklen_t addrlen = 0;
5515
0
  struct auth_master* master = xfr->task_transfer->master;
5516
0
  char *auth_name = NULL;
5517
0
  struct timeval t;
5518
0
  int timeout;
5519
0
  if(!master) return 0;
5520
0
  if(master->allow_notify) return 0; /* only for notify */
5521
5522
  /* get master addr */
5523
0
  if(xfr->task_transfer->scan_addr) {
5524
0
    addrlen = xfr->task_transfer->scan_addr->addrlen;
5525
0
    memmove(&addr, &xfr->task_transfer->scan_addr->addr, addrlen);
5526
0
  } else {
5527
0
    if(!authextstrtoaddr(master->host, &addr, &addrlen, &auth_name)) {
5528
      /* the ones that are not in addr format are supposed
5529
       * to be looked up.  The lookup has failed however,
5530
       * so skip them */
5531
0
      char zname[LDNS_MAX_DOMAINLEN];
5532
0
      dname_str(xfr->name, zname);
5533
0
      log_err("%s: failed lookup, cannot transfer from master %s",
5534
0
        zname, master->host);
5535
0
      return 0;
5536
0
    }
5537
0
  }
5538
5539
  /* remove previous TCP connection (if any) */
5540
0
  if(xfr->task_transfer->cp) {
5541
0
    comm_point_delete(xfr->task_transfer->cp);
5542
0
    xfr->task_transfer->cp = NULL;
5543
0
  }
5544
0
  if(!xfr->task_transfer->timer) {
5545
0
    xfr->task_transfer->timer = comm_timer_create(env->worker_base,
5546
0
      auth_xfer_transfer_timer_callback, xfr);
5547
0
    if(!xfr->task_transfer->timer) {
5548
0
      log_err("malloc failure");
5549
0
      return 0;
5550
0
    }
5551
0
  }
5552
0
  timeout = AUTH_TRANSFER_TIMEOUT;
5553
0
#ifndef S_SPLINT_S
5554
0
        t.tv_sec = timeout/1000;
5555
0
        t.tv_usec = (timeout%1000)*1000;
5556
0
#endif
5557
5558
0
  if(master->http) {
5559
    /* perform http fetch */
5560
    /* store http port number into sockaddr,
5561
     * unless someone used unbound's host@port notation */
5562
0
    xfr->task_transfer->on_ixfr = 0;
5563
0
    if(strchr(master->host, '@') == NULL)
5564
0
      sockaddr_store_port(&addr, addrlen, master->port);
5565
0
    xfr->task_transfer->cp = outnet_comm_point_for_http(
5566
0
      env->outnet, auth_xfer_transfer_http_callback, xfr,
5567
0
      &addr, addrlen, -1, master->ssl, master->host,
5568
0
      master->file, env->cfg);
5569
0
    if(!xfr->task_transfer->cp) {
5570
0
      char zname[LDNS_MAX_DOMAINLEN], as[256];
5571
0
      dname_str(xfr->name, zname);
5572
0
      addr_port_to_str(&addr, addrlen, as, sizeof(as));
5573
0
      verbose(VERB_ALGO, "cannot create http cp "
5574
0
        "connection for %s to %s", zname, as);
5575
0
      return 0;
5576
0
    }
5577
0
    comm_timer_set(xfr->task_transfer->timer, &t);
5578
0
    if(verbosity >= VERB_ALGO) {
5579
0
      char zname[LDNS_MAX_DOMAINLEN], as[256];
5580
0
      dname_str(xfr->name, zname);
5581
0
      addr_port_to_str(&addr, addrlen, as, sizeof(as));
5582
0
      verbose(VERB_ALGO, "auth zone %s transfer next HTTP fetch from %s started", zname, as);
5583
0
    }
5584
    /* Create or refresh the list of allow_notify addrs */
5585
0
    probe_copy_masters_for_allow_notify(xfr);
5586
0
    return 1;
5587
0
  }
5588
5589
  /* perform AXFR/IXFR */
5590
  /* set the packet to be written */
5591
  /* create new ID */
5592
0
  xfr->task_transfer->id = GET_RANDOM_ID(env->rnd);
5593
0
  xfr_create_ixfr_packet(xfr, env->scratch_buffer,
5594
0
    xfr->task_transfer->id, master);
5595
5596
  /* connect on fd */
5597
0
  xfr->task_transfer->cp = outnet_comm_point_for_tcp(env->outnet,
5598
0
    auth_xfer_transfer_tcp_callback, xfr, &addr, addrlen,
5599
0
    env->scratch_buffer, -1,
5600
0
    auth_name != NULL, auth_name);
5601
0
  if(!xfr->task_transfer->cp) {
5602
0
    char zname[LDNS_MAX_DOMAINLEN], as[256];
5603
0
    dname_str(xfr->name, zname);
5604
0
    addr_port_to_str(&addr, addrlen, as, sizeof(as));
5605
0
    verbose(VERB_ALGO, "cannot create tcp cp connection for "
5606
0
      "xfr %s to %s", zname, as);
5607
0
    return 0;
5608
0
  }
5609
0
  comm_timer_set(xfr->task_transfer->timer, &t);
5610
0
  if(verbosity >= VERB_ALGO) {
5611
0
    char zname[LDNS_MAX_DOMAINLEN], as[256];
5612
0
    dname_str(xfr->name, zname);
5613
0
    addr_port_to_str(&addr, addrlen, as, sizeof(as));
5614
0
    verbose(VERB_ALGO, "auth zone %s transfer next %s fetch from %s started", zname, 
5615
0
      (xfr->task_transfer->on_ixfr?"IXFR":"AXFR"), as);
5616
0
  }
5617
0
  return 1;
5618
0
}
5619
5620
/** perform next lookup, next transfer TCP, or end and resume wait time task */
5621
static void
5622
xfr_transfer_nexttarget_or_end(struct auth_xfer* xfr, struct module_env* env)
5623
0
{
5624
0
  log_assert(xfr->task_transfer->worker == env->worker);
5625
5626
  /* are we performing lookups? */
5627
0
  while(xfr->task_transfer->lookup_target) {
5628
0
    if(xfr_transfer_lookup_host(xfr, env)) {
5629
      /* wait for lookup to finish,
5630
       * note that the hostname may be in unbound's cache
5631
       * and we may then get an instant cache response,
5632
       * and that calls the callback just like a full
5633
       * lookup and lookup failures also call callback */
5634
0
      if(verbosity >= VERB_ALGO) {
5635
0
        char zname[LDNS_MAX_DOMAINLEN];
5636
0
        dname_str(xfr->name, zname);
5637
0
        verbose(VERB_ALGO, "auth zone %s transfer next target lookup", zname);
5638
0
      }
5639
0
      lock_basic_unlock(&xfr->lock);
5640
0
      return;
5641
0
    }
5642
0
    xfr_transfer_move_to_next_lookup(xfr, env);
5643
0
  }
5644
5645
  /* initiate TCP and fetch the zone from the master */
5646
  /* and set timeout on it */
5647
0
  while(!xfr_transfer_end_of_list(xfr)) {
5648
0
    xfr->task_transfer->master = xfr_transfer_current_master(xfr);
5649
0
    if(xfr_transfer_init_fetch(xfr, env)) {
5650
      /* successfully started, wait for callback */
5651
0
      lock_basic_unlock(&xfr->lock);
5652
0
      return;
5653
0
    }
5654
    /* failed to fetch, next master */
5655
0
    xfr_transfer_nextmaster(xfr);
5656
0
  }
5657
0
  if(verbosity >= VERB_ALGO) {
5658
0
    char zname[LDNS_MAX_DOMAINLEN];
5659
0
    dname_str(xfr->name, zname);
5660
0
    verbose(VERB_ALGO, "auth zone %s transfer failed, wait", zname);
5661
0
  }
5662
5663
  /* we failed to fetch the zone, move to wait task
5664
   * use the shorter retry timeout */
5665
0
  xfr_transfer_disown(xfr);
5666
5667
  /* pick up the nextprobe task and wait */
5668
0
  if(xfr->task_nextprobe->worker == NULL)
5669
0
    xfr_set_timeout(xfr, env, 1, 0);
5670
0
  lock_basic_unlock(&xfr->lock);
5671
0
}
5672
5673
/** add addrs from A or AAAA rrset to the master */
5674
static void
5675
xfr_master_add_addrs(struct auth_master* m, struct ub_packed_rrset_key* rrset,
5676
  uint16_t rrtype)
5677
0
{
5678
0
  size_t i;
5679
0
  struct packed_rrset_data* data;
5680
0
  if(!m || !rrset) return;
5681
0
  if(rrtype != LDNS_RR_TYPE_A && rrtype != LDNS_RR_TYPE_AAAA)
5682
0
    return;
5683
0
  data = (struct packed_rrset_data*)rrset->entry.data;
5684
0
  for(i=0; i<data->count; i++) {
5685
0
    struct auth_addr* a;
5686
0
    size_t len = data->rr_len[i] - 2;
5687
0
    uint8_t* rdata = data->rr_data[i]+2;
5688
0
    if(rrtype == LDNS_RR_TYPE_A && len != INET_SIZE)
5689
0
      continue; /* wrong length for A */
5690
0
    if(rrtype == LDNS_RR_TYPE_AAAA && len != INET6_SIZE)
5691
0
      continue; /* wrong length for AAAA */
5692
    
5693
    /* add and alloc it */
5694
0
    a = (struct auth_addr*)calloc(1, sizeof(*a));
5695
0
    if(!a) {
5696
0
      log_err("out of memory");
5697
0
      return;
5698
0
    }
5699
0
    if(rrtype == LDNS_RR_TYPE_A) {
5700
0
      struct sockaddr_in* sa;
5701
0
      a->addrlen = (socklen_t)sizeof(*sa);
5702
0
      sa = (struct sockaddr_in*)&a->addr;
5703
0
      sa->sin_family = AF_INET;
5704
0
      sa->sin_port = (in_port_t)htons(UNBOUND_DNS_PORT);
5705
0
      memmove(&sa->sin_addr, rdata, INET_SIZE);
5706
0
    } else {
5707
0
      struct sockaddr_in6* sa;
5708
0
      a->addrlen = (socklen_t)sizeof(*sa);
5709
0
      sa = (struct sockaddr_in6*)&a->addr;
5710
0
      sa->sin6_family = AF_INET6;
5711
0
      sa->sin6_port = (in_port_t)htons(UNBOUND_DNS_PORT);
5712
0
      memmove(&sa->sin6_addr, rdata, INET6_SIZE);
5713
0
    }
5714
0
    if(verbosity >= VERB_ALGO) {
5715
0
      char s[64];
5716
0
      addr_port_to_str(&a->addr, a->addrlen, s, sizeof(s));
5717
0
      verbose(VERB_ALGO, "auth host %s lookup %s",
5718
0
        m->host, s);
5719
0
    }
5720
    /* append to list */
5721
0
    a->next = m->list;
5722
0
    m->list = a;
5723
0
  }
5724
0
}
5725
5726
/** callback for task_transfer lookup of host name, of A or AAAA */
5727
void auth_xfer_transfer_lookup_callback(void* arg, int rcode, sldns_buffer* buf,
5728
  enum sec_status ATTR_UNUSED(sec), char* ATTR_UNUSED(why_bogus),
5729
  int ATTR_UNUSED(was_ratelimited))
5730
0
{
5731
0
  struct auth_xfer* xfr = (struct auth_xfer*)arg;
5732
0
  struct module_env* env;
5733
0
  log_assert(xfr->task_transfer);
5734
0
  lock_basic_lock(&xfr->lock);
5735
0
  env = xfr->task_transfer->env;
5736
0
  if(!env || env->outnet->want_to_quit) {
5737
0
    lock_basic_unlock(&xfr->lock);
5738
0
    return; /* stop on quit */
5739
0
  }
5740
5741
  /* process result */
5742
0
  if(rcode == LDNS_RCODE_NOERROR) {
5743
0
    uint16_t wanted_qtype = LDNS_RR_TYPE_A;
5744
0
    struct regional* temp = env->scratch;
5745
0
    struct query_info rq;
5746
0
    struct reply_info* rep;
5747
0
    if(xfr->task_transfer->lookup_aaaa)
5748
0
      wanted_qtype = LDNS_RR_TYPE_AAAA;
5749
0
    memset(&rq, 0, sizeof(rq));
5750
0
    rep = parse_reply_in_temp_region(buf, temp, &rq);
5751
0
    if(rep && rq.qtype == wanted_qtype &&
5752
0
      FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NOERROR) {
5753
      /* parsed successfully */
5754
0
      struct ub_packed_rrset_key* answer =
5755
0
        reply_find_answer_rrset(&rq, rep);
5756
0
      if(answer) {
5757
0
        xfr_master_add_addrs(xfr->task_transfer->
5758
0
          lookup_target, answer, wanted_qtype);
5759
0
      } else {
5760
0
        if(verbosity >= VERB_ALGO) {
5761
0
          char zname[LDNS_MAX_DOMAINLEN];
5762
0
          dname_str(xfr->name, zname);
5763
0
          verbose(VERB_ALGO, "auth zone %s host %s type %s transfer lookup has nodata", zname, xfr->task_transfer->lookup_target->host, (xfr->task_transfer->lookup_aaaa?"AAAA":"A"));
5764
0
        }
5765
0
      }
5766
0
    } else {
5767
0
      if(verbosity >= VERB_ALGO) {
5768
0
        char zname[LDNS_MAX_DOMAINLEN];
5769
0
        dname_str(xfr->name, zname);
5770
0
        verbose(VERB_ALGO, "auth zone %s host %s type %s transfer lookup has no answer", zname, xfr->task_transfer->lookup_target->host, (xfr->task_transfer->lookup_aaaa?"AAAA":"A"));
5771
0
      }
5772
0
    }
5773
0
    regional_free_all(temp);
5774
0
  } else {
5775
0
    if(verbosity >= VERB_ALGO) {
5776
0
      char zname[LDNS_MAX_DOMAINLEN];
5777
0
      dname_str(xfr->name, zname);
5778
0
      verbose(VERB_ALGO, "auth zone %s host %s type %s transfer lookup failed", zname, xfr->task_transfer->lookup_target->host, (xfr->task_transfer->lookup_aaaa?"AAAA":"A"));
5779
0
    }
5780
0
  }
5781
0
  if(xfr->task_transfer->lookup_target->list &&
5782
0
    xfr->task_transfer->lookup_target == xfr_transfer_current_master(xfr))
5783
0
    xfr->task_transfer->scan_addr = xfr->task_transfer->lookup_target->list;
5784
5785
  /* move to lookup AAAA after A lookup, move to next hostname lookup,
5786
   * or move to fetch the zone, or, if nothing to do, end task_transfer */
5787
0
  xfr_transfer_move_to_next_lookup(xfr, env);
5788
0
  xfr_transfer_nexttarget_or_end(xfr, env);
5789
0
}
5790
5791
/** check if xfer (AXFR or IXFR) packet is OK.
5792
 * return false if we lost connection (SERVFAIL, or unreadable).
5793
 * return false if we need to move from IXFR to AXFR, with gonextonfail
5794
 *  set to false, so the same master is tried again, but with AXFR.
5795
 * return true if fine to link into data.
5796
 * return true with transferdone=true when the transfer has ended.
5797
 */
5798
static int
5799
check_xfer_packet(sldns_buffer* pkt, struct auth_xfer* xfr,
5800
  int* gonextonfail, int* transferdone)
5801
0
{
5802
0
  uint8_t* wire = sldns_buffer_begin(pkt);
5803
0
  int i;
5804
0
  if(sldns_buffer_limit(pkt) < LDNS_HEADER_SIZE) {
5805
0
    verbose(VERB_ALGO, "xfr to %s failed, packet too small",
5806
0
      xfr->task_transfer->master->host);
5807
0
    return 0;
5808
0
  }
5809
0
  if(!LDNS_QR_WIRE(wire)) {
5810
0
    verbose(VERB_ALGO, "xfr to %s failed, packet has no QR flag",
5811
0
      xfr->task_transfer->master->host);
5812
0
    return 0;
5813
0
  }
5814
0
  if(LDNS_TC_WIRE(wire)) {
5815
0
    verbose(VERB_ALGO, "xfr to %s failed, packet has TC flag",
5816
0
      xfr->task_transfer->master->host);
5817
0
    return 0;
5818
0
  }
5819
  /* check ID */
5820
0
  if(LDNS_ID_WIRE(wire) != xfr->task_transfer->id) {
5821
0
    verbose(VERB_ALGO, "xfr to %s failed, packet wrong ID",
5822
0
      xfr->task_transfer->master->host);
5823
0
    return 0;
5824
0
  }
5825
0
  if(LDNS_RCODE_WIRE(wire) != LDNS_RCODE_NOERROR) {
5826
0
    char rcode[32];
5827
0
    sldns_wire2str_rcode_buf((int)LDNS_RCODE_WIRE(wire), rcode,
5828
0
      sizeof(rcode));
5829
    /* if we are doing IXFR, check for fallback */
5830
0
    if(xfr->task_transfer->on_ixfr) {
5831
0
      if(LDNS_RCODE_WIRE(wire) == LDNS_RCODE_NOTIMPL ||
5832
0
        LDNS_RCODE_WIRE(wire) == LDNS_RCODE_SERVFAIL ||
5833
0
        LDNS_RCODE_WIRE(wire) == LDNS_RCODE_REFUSED ||
5834
0
        LDNS_RCODE_WIRE(wire) == LDNS_RCODE_FORMERR) {
5835
0
        verbose(VERB_ALGO, "xfr to %s, fallback "
5836
0
          "from IXFR to AXFR (with rcode %s)",
5837
0
          xfr->task_transfer->master->host,
5838
0
          rcode);
5839
0
        xfr->task_transfer->ixfr_fail = 1;
5840
0
        *gonextonfail = 0;
5841
0
        return 0;
5842
0
      }
5843
0
    }
5844
0
    verbose(VERB_ALGO, "xfr to %s failed, packet with rcode %s",
5845
0
      xfr->task_transfer->master->host, rcode);
5846
0
    return 0;
5847
0
  }
5848
0
  if(LDNS_OPCODE_WIRE(wire) != LDNS_PACKET_QUERY) {
5849
0
    verbose(VERB_ALGO, "xfr to %s failed, packet with bad opcode",
5850
0
      xfr->task_transfer->master->host);
5851
0
    return 0;
5852
0
  }
5853
0
  if(LDNS_QDCOUNT(wire) > 1) {
5854
0
    verbose(VERB_ALGO, "xfr to %s failed, packet has qdcount %d",
5855
0
      xfr->task_transfer->master->host,
5856
0
      (int)LDNS_QDCOUNT(wire));
5857
0
    return 0;
5858
0
  }
5859
5860
  /* check qname */
5861
0
  sldns_buffer_set_position(pkt, LDNS_HEADER_SIZE);
5862
0
  for(i=0; i<(int)LDNS_QDCOUNT(wire); i++) {
5863
0
    size_t pos = sldns_buffer_position(pkt);
5864
0
    uint16_t qtype, qclass;
5865
0
    if(pkt_dname_len(pkt) == 0) {
5866
0
      verbose(VERB_ALGO, "xfr to %s failed, packet with "
5867
0
        "malformed dname",
5868
0
        xfr->task_transfer->master->host);
5869
0
      return 0;
5870
0
    }
5871
0
    if(dname_pkt_compare(pkt, sldns_buffer_at(pkt, pos),
5872
0
      xfr->name) != 0) {
5873
0
      verbose(VERB_ALGO, "xfr to %s failed, packet with "
5874
0
        "wrong qname",
5875
0
        xfr->task_transfer->master->host);
5876
0
      return 0;
5877
0
    }
5878
0
    if(sldns_buffer_remaining(pkt) < 4) {
5879
0
      verbose(VERB_ALGO, "xfr to %s failed, packet with "
5880
0
        "truncated query RR",
5881
0
        xfr->task_transfer->master->host);
5882
0
      return 0;
5883
0
    }
5884
0
    qtype = sldns_buffer_read_u16(pkt);
5885
0
    qclass = sldns_buffer_read_u16(pkt);
5886
0
    if(qclass != xfr->dclass) {
5887
0
      verbose(VERB_ALGO, "xfr to %s failed, packet with "
5888
0
        "wrong qclass",
5889
0
        xfr->task_transfer->master->host);
5890
0
      return 0;
5891
0
    }
5892
0
    if(xfr->task_transfer->on_ixfr) {
5893
0
      if(qtype != LDNS_RR_TYPE_IXFR) {
5894
0
        verbose(VERB_ALGO, "xfr to %s failed, packet "
5895
0
          "with wrong qtype, expected IXFR",
5896
0
        xfr->task_transfer->master->host);
5897
0
        return 0;
5898
0
      }
5899
0
    } else {
5900
0
      if(qtype != LDNS_RR_TYPE_AXFR) {
5901
0
        verbose(VERB_ALGO, "xfr to %s failed, packet "
5902
0
          "with wrong qtype, expected AXFR",
5903
0
        xfr->task_transfer->master->host);
5904
0
        return 0;
5905
0
      }
5906
0
    }
5907
0
  }
5908
5909
  /* check parse of RRs in packet, store first SOA serial
5910
   * to be able to detect last SOA (with that serial) to see if done */
5911
  /* also check for IXFR 'zone up to date' reply */
5912
0
  for(i=0; i<(int)LDNS_ANCOUNT(wire); i++) {
5913
0
    size_t pos = sldns_buffer_position(pkt);
5914
0
    uint16_t tp, rdlen;
5915
0
    if(pkt_dname_len(pkt) == 0) {
5916
0
      verbose(VERB_ALGO, "xfr to %s failed, packet with "
5917
0
        "malformed dname in answer section",
5918
0
        xfr->task_transfer->master->host);
5919
0
      return 0;
5920
0
    }
5921
0
    if(sldns_buffer_remaining(pkt) < 10) {
5922
0
      verbose(VERB_ALGO, "xfr to %s failed, packet with "
5923
0
        "truncated RR",
5924
0
        xfr->task_transfer->master->host);
5925
0
      return 0;
5926
0
    }
5927
0
    tp = sldns_buffer_read_u16(pkt);
5928
0
    (void)sldns_buffer_read_u16(pkt); /* class */
5929
0
    (void)sldns_buffer_read_u32(pkt); /* ttl */
5930
0
    rdlen = sldns_buffer_read_u16(pkt);
5931
0
    if(sldns_buffer_remaining(pkt) < rdlen) {
5932
0
      verbose(VERB_ALGO, "xfr to %s failed, packet with "
5933
0
        "truncated RR rdata",
5934
0
        xfr->task_transfer->master->host);
5935
0
      return 0;
5936
0
    }
5937
5938
    /* RR parses (haven't checked rdata itself), now look at
5939
     * SOA records to see serial number */
5940
0
    if(xfr->task_transfer->rr_scan_num == 0 &&
5941
0
      tp != LDNS_RR_TYPE_SOA) {
5942
0
      verbose(VERB_ALGO, "xfr to %s failed, packet with "
5943
0
        "malformed zone transfer, no start SOA",
5944
0
        xfr->task_transfer->master->host);
5945
0
      return 0;
5946
0
    }
5947
0
    if(xfr->task_transfer->rr_scan_num == 1 &&
5948
0
      tp != LDNS_RR_TYPE_SOA) {
5949
      /* second RR is not a SOA record, this is not an IXFR
5950
       * the master is replying with an AXFR */
5951
0
      xfr->task_transfer->on_ixfr_is_axfr = 1;
5952
0
    }
5953
0
    if(tp == LDNS_RR_TYPE_SOA) {
5954
0
      uint32_t serial;
5955
0
      if(rdlen < 22) {
5956
0
        verbose(VERB_ALGO, "xfr to %s failed, packet "
5957
0
          "with SOA with malformed rdata",
5958
0
          xfr->task_transfer->master->host);
5959
0
        return 0;
5960
0
      }
5961
0
      if(dname_pkt_compare(pkt, sldns_buffer_at(pkt, pos),
5962
0
        xfr->name) != 0) {
5963
0
        verbose(VERB_ALGO, "xfr to %s failed, packet "
5964
0
          "with SOA with wrong dname",
5965
0
          xfr->task_transfer->master->host);
5966
0
        return 0;
5967
0
      }
5968
5969
      /* read serial number of SOA */
5970
0
      serial = sldns_buffer_read_u32_at(pkt,
5971
0
        sldns_buffer_position(pkt)+rdlen-20);
5972
5973
      /* check for IXFR 'zone has SOA x' reply */
5974
0
      if(xfr->task_transfer->on_ixfr &&
5975
0
        xfr->task_transfer->rr_scan_num == 0 &&
5976
0
        LDNS_ANCOUNT(wire)==1) {
5977
0
        verbose(VERB_ALGO, "xfr to %s ended, "
5978
0
          "IXFR reply that zone has serial %u,"
5979
0
          " fallback from IXFR to AXFR",
5980
0
          xfr->task_transfer->master->host,
5981
0
          (unsigned)serial);
5982
0
        xfr->task_transfer->ixfr_fail = 1;
5983
0
        *gonextonfail = 0;
5984
0
        return 0;
5985
0
      }
5986
5987
      /* if first SOA, store serial number */
5988
0
      if(xfr->task_transfer->got_xfr_serial == 0) {
5989
0
        xfr->task_transfer->got_xfr_serial = 1;
5990
0
        xfr->task_transfer->incoming_xfr_serial =
5991
0
          serial;
5992
0
        verbose(VERB_ALGO, "xfr %s: contains "
5993
0
          "SOA serial %u",
5994
0
          xfr->task_transfer->master->host,
5995
0
          (unsigned)serial);
5996
      /* see if end of AXFR */
5997
0
      } else if(!xfr->task_transfer->on_ixfr ||
5998
0
        xfr->task_transfer->on_ixfr_is_axfr) {
5999
        /* second SOA with serial is the end
6000
         * for AXFR */
6001
0
        *transferdone = 1;
6002
0
        verbose(VERB_ALGO, "xfr %s: last AXFR packet",
6003
0
          xfr->task_transfer->master->host);
6004
      /* for IXFR, count SOA records with that serial */
6005
0
      } else if(xfr->task_transfer->incoming_xfr_serial ==
6006
0
        serial && xfr->task_transfer->got_xfr_serial
6007
0
        == 1) {
6008
0
        xfr->task_transfer->got_xfr_serial++;
6009
      /* if not first soa, if serial==firstserial, the
6010
       * third time we are at the end, for IXFR */
6011
0
      } else if(xfr->task_transfer->incoming_xfr_serial ==
6012
0
        serial && xfr->task_transfer->got_xfr_serial
6013
0
        == 2) {
6014
0
        verbose(VERB_ALGO, "xfr %s: last IXFR packet",
6015
0
          xfr->task_transfer->master->host);
6016
0
        *transferdone = 1;
6017
        /* continue parse check, if that succeeds,
6018
         * transfer is done */
6019
0
      }
6020
0
    }
6021
0
    xfr->task_transfer->rr_scan_num++;
6022
6023
    /* skip over RR rdata to go to the next RR */
6024
0
    sldns_buffer_skip(pkt, (ssize_t)rdlen);
6025
0
  }
6026
6027
  /* check authority section */
6028
  /* we skip over the RRs checking packet format */
6029
0
  for(i=0; i<(int)LDNS_NSCOUNT(wire); i++) {
6030
0
    uint16_t rdlen;
6031
0
    if(pkt_dname_len(pkt) == 0) {
6032
0
      verbose(VERB_ALGO, "xfr to %s failed, packet with "
6033
0
        "malformed dname in authority section",
6034
0
        xfr->task_transfer->master->host);
6035
0
      return 0;
6036
0
    }
6037
0
    if(sldns_buffer_remaining(pkt) < 10) {
6038
0
      verbose(VERB_ALGO, "xfr to %s failed, packet with "
6039
0
        "truncated RR",
6040
0
        xfr->task_transfer->master->host);
6041
0
      return 0;
6042
0
    }
6043
0
    (void)sldns_buffer_read_u16(pkt); /* type */
6044
0
    (void)sldns_buffer_read_u16(pkt); /* class */
6045
0
    (void)sldns_buffer_read_u32(pkt); /* ttl */
6046
0
    rdlen = sldns_buffer_read_u16(pkt);
6047
0
    if(sldns_buffer_remaining(pkt) < rdlen) {
6048
0
      verbose(VERB_ALGO, "xfr to %s failed, packet with "
6049
0
        "truncated RR rdata",
6050
0
        xfr->task_transfer->master->host);
6051
0
      return 0;
6052
0
    }
6053
    /* skip over RR rdata to go to the next RR */
6054
0
    sldns_buffer_skip(pkt, (ssize_t)rdlen);
6055
0
  }
6056
6057
  /* check additional section */
6058
0
  for(i=0; i<(int)LDNS_ARCOUNT(wire); i++) {
6059
0
    uint16_t rdlen;
6060
0
    if(pkt_dname_len(pkt) == 0) {
6061
0
      verbose(VERB_ALGO, "xfr to %s failed, packet with "
6062
0
        "malformed dname in additional section",
6063
0
        xfr->task_transfer->master->host);
6064
0
      return 0;
6065
0
    }
6066
0
    if(sldns_buffer_remaining(pkt) < 10) {
6067
0
      verbose(VERB_ALGO, "xfr to %s failed, packet with "
6068
0
        "truncated RR",
6069
0
        xfr->task_transfer->master->host);
6070
0
      return 0;
6071
0
    }
6072
0
    (void)sldns_buffer_read_u16(pkt); /* type */
6073
0
    (void)sldns_buffer_read_u16(pkt); /* class */
6074
0
    (void)sldns_buffer_read_u32(pkt); /* ttl */
6075
0
    rdlen = sldns_buffer_read_u16(pkt);
6076
0
    if(sldns_buffer_remaining(pkt) < rdlen) {
6077
0
      verbose(VERB_ALGO, "xfr to %s failed, packet with "
6078
0
        "truncated RR rdata",
6079
0
        xfr->task_transfer->master->host);
6080
0
      return 0;
6081
0
    }
6082
    /* skip over RR rdata to go to the next RR */
6083
0
    sldns_buffer_skip(pkt, (ssize_t)rdlen);
6084
0
  }
6085
6086
0
  return 1;
6087
0
}
6088
6089
/** Link the data from this packet into the worklist of transferred data */
6090
static int
6091
xfer_link_data(sldns_buffer* pkt, struct auth_xfer* xfr)
6092
0
{
6093
  /* alloc it */
6094
0
  struct auth_chunk* e;
6095
0
  e = (struct auth_chunk*)calloc(1, sizeof(*e));
6096
0
  if(!e) return 0;
6097
0
  e->next = NULL;
6098
0
  e->len = sldns_buffer_limit(pkt);
6099
0
  e->data = memdup(sldns_buffer_begin(pkt), e->len);
6100
0
  if(!e->data) {
6101
0
    free(e);
6102
0
    return 0;
6103
0
  }
6104
6105
  /* alloc succeeded, link into list */
6106
0
  if(!xfr->task_transfer->chunks_first)
6107
0
    xfr->task_transfer->chunks_first = e;
6108
0
  if(xfr->task_transfer->chunks_last)
6109
0
    xfr->task_transfer->chunks_last->next = e;
6110
0
  xfr->task_transfer->chunks_last = e;
6111
0
  return 1;
6112
0
}
6113
6114
/** task transfer.  the list of data is complete. process it and if failed
6115
 * move to next master, if succeeded, end the task transfer */
6116
static void
6117
process_list_end_transfer(struct auth_xfer* xfr, struct module_env* env)
6118
0
{
6119
0
  int ixfr_fail = 0;
6120
0
  if(xfr_process_chunk_list(xfr, env, &ixfr_fail)) {
6121
    /* it worked! */
6122
0
    auth_chunks_delete(xfr->task_transfer);
6123
6124
    /* we fetched the zone, move to wait task */
6125
0
    xfr_transfer_disown(xfr);
6126
6127
0
    if(xfr->notify_received && (!xfr->notify_has_serial ||
6128
0
      (xfr->notify_has_serial && 
6129
0
      xfr_serial_means_update(xfr, xfr->notify_serial)))) {
6130
0
      uint32_t sr = xfr->notify_serial;
6131
0
      int has_sr = xfr->notify_has_serial;
6132
      /* we received a notify while probe/transfer was
6133
       * in progress.  start a new probe and transfer */
6134
0
      xfr->notify_received = 0;
6135
0
      xfr->notify_has_serial = 0;
6136
0
      xfr->notify_serial = 0;
6137
0
      if(!xfr_start_probe(xfr, env, NULL)) {
6138
        /* if we couldn't start it, already in
6139
         * progress; restore notify serial,
6140
         * while xfr still locked */
6141
0
        xfr->notify_received = 1;
6142
0
        xfr->notify_has_serial = has_sr;
6143
0
        xfr->notify_serial = sr;
6144
0
        lock_basic_unlock(&xfr->lock);
6145
0
      }
6146
0
      return;
6147
0
    } else {
6148
      /* pick up the nextprobe task and wait (normail wait time) */
6149
0
      if(xfr->task_nextprobe->worker == NULL)
6150
0
        xfr_set_timeout(xfr, env, 0, 0);
6151
0
    }
6152
0
    lock_basic_unlock(&xfr->lock);
6153
0
    return;
6154
0
  }
6155
  /* processing failed */
6156
  /* when done, delete data from list */
6157
0
  auth_chunks_delete(xfr->task_transfer);
6158
0
  if(ixfr_fail) {
6159
0
    xfr->task_transfer->ixfr_fail = 1;
6160
0
  } else {
6161
0
    xfr_transfer_nextmaster(xfr);
6162
0
  }
6163
0
  xfr_transfer_nexttarget_or_end(xfr, env);
6164
0
}
6165
6166
/** callback for the task_transfer timer */
6167
void
6168
auth_xfer_transfer_timer_callback(void* arg)
6169
0
{
6170
0
  struct auth_xfer* xfr = (struct auth_xfer*)arg;
6171
0
  struct module_env* env;
6172
0
  int gonextonfail = 1;
6173
0
  log_assert(xfr->task_transfer);
6174
0
  lock_basic_lock(&xfr->lock);
6175
0
  env = xfr->task_transfer->env;
6176
0
  if(!env || env->outnet->want_to_quit) {
6177
0
    lock_basic_unlock(&xfr->lock);
6178
0
    return; /* stop on quit */
6179
0
  }
6180
6181
0
  verbose(VERB_ALGO, "xfr stopped, connection timeout to %s",
6182
0
    xfr->task_transfer->master->host);
6183
6184
  /* see if IXFR caused the failure, if so, try AXFR */
6185
0
  if(xfr->task_transfer->on_ixfr) {
6186
0
    xfr->task_transfer->ixfr_possible_timeout_count++;
6187
0
    if(xfr->task_transfer->ixfr_possible_timeout_count >=
6188
0
      NUM_TIMEOUTS_FALLBACK_IXFR) {
6189
0
      verbose(VERB_ALGO, "xfr to %s, fallback "
6190
0
        "from IXFR to AXFR (because of timeouts)",
6191
0
        xfr->task_transfer->master->host);
6192
0
      xfr->task_transfer->ixfr_fail = 1;
6193
0
      gonextonfail = 0;
6194
0
    }
6195
0
  }
6196
6197
  /* delete transferred data from list */
6198
0
  auth_chunks_delete(xfr->task_transfer);
6199
0
  comm_point_delete(xfr->task_transfer->cp);
6200
0
  xfr->task_transfer->cp = NULL;
6201
0
  if(gonextonfail)
6202
0
    xfr_transfer_nextmaster(xfr);
6203
0
  xfr_transfer_nexttarget_or_end(xfr, env);
6204
0
}
6205
6206
/** callback for task_transfer tcp connections */
6207
int
6208
auth_xfer_transfer_tcp_callback(struct comm_point* c, void* arg, int err,
6209
  struct comm_reply* ATTR_UNUSED(repinfo))
6210
0
{
6211
0
  struct auth_xfer* xfr = (struct auth_xfer*)arg;
6212
0
  struct module_env* env;
6213
0
  int gonextonfail = 1;
6214
0
  int transferdone = 0;
6215
0
  log_assert(xfr->task_transfer);
6216
0
  lock_basic_lock(&xfr->lock);
6217
0
  env = xfr->task_transfer->env;
6218
0
  if(!env || env->outnet->want_to_quit) {
6219
0
    lock_basic_unlock(&xfr->lock);
6220
0
    return 0; /* stop on quit */
6221
0
  }
6222
  /* stop the timer */
6223
0
  comm_timer_disable(xfr->task_transfer->timer);
6224
6225
0
  if(err != NETEVENT_NOERROR) {
6226
    /* connection failed, closed, or timeout */
6227
    /* stop this transfer, cleanup 
6228
     * and continue task_transfer*/
6229
0
    verbose(VERB_ALGO, "xfr stopped, connection lost to %s",
6230
0
      xfr->task_transfer->master->host);
6231
6232
    /* see if IXFR caused the failure, if so, try AXFR */
6233
0
    if(xfr->task_transfer->on_ixfr) {
6234
0
      xfr->task_transfer->ixfr_possible_timeout_count++;
6235
0
      if(xfr->task_transfer->ixfr_possible_timeout_count >=
6236
0
        NUM_TIMEOUTS_FALLBACK_IXFR) {
6237
0
        verbose(VERB_ALGO, "xfr to %s, fallback "
6238
0
          "from IXFR to AXFR (because of timeouts)",
6239
0
          xfr->task_transfer->master->host);
6240
0
        xfr->task_transfer->ixfr_fail = 1;
6241
0
        gonextonfail = 0;
6242
0
      }
6243
0
    }
6244
6245
0
  failed:
6246
    /* delete transferred data from list */
6247
0
    auth_chunks_delete(xfr->task_transfer);
6248
0
    comm_point_delete(xfr->task_transfer->cp);
6249
0
    xfr->task_transfer->cp = NULL;
6250
0
    if(gonextonfail)
6251
0
      xfr_transfer_nextmaster(xfr);
6252
0
    xfr_transfer_nexttarget_or_end(xfr, env);
6253
0
    return 0;
6254
0
  }
6255
  /* note that IXFR worked without timeout */
6256
0
  if(xfr->task_transfer->on_ixfr)
6257
0
    xfr->task_transfer->ixfr_possible_timeout_count = 0;
6258
6259
  /* handle returned packet */
6260
  /* if it fails, cleanup and end this transfer */
6261
  /* if it needs to fallback from IXFR to AXFR, do that */
6262
0
  if(!check_xfer_packet(c->buffer, xfr, &gonextonfail, &transferdone)) {
6263
0
    goto failed;
6264
0
  }
6265
  /* if it is good, link it into the list of data */
6266
  /* if the link into list of data fails (malloc fail) cleanup and end */
6267
0
  if(!xfer_link_data(c->buffer, xfr)) {
6268
0
    verbose(VERB_ALGO, "xfr stopped to %s, malloc failed",
6269
0
      xfr->task_transfer->master->host);
6270
0
    goto failed;
6271
0
  }
6272
  /* if the transfer is done now, disconnect and process the list */
6273
0
  if(transferdone) {
6274
0
    comm_point_delete(xfr->task_transfer->cp);
6275
0
    xfr->task_transfer->cp = NULL;
6276
0
    process_list_end_transfer(xfr, env);
6277
0
    return 0;
6278
0
  }
6279
6280
  /* if we want to read more messages, setup the commpoint to read
6281
   * a DNS packet, and the timeout */
6282
0
  lock_basic_unlock(&xfr->lock);
6283
0
  c->tcp_is_reading = 1;
6284
0
  sldns_buffer_clear(c->buffer);
6285
0
  comm_point_start_listening(c, -1, AUTH_TRANSFER_TIMEOUT);
6286
0
  return 0;
6287
0
}
6288
6289
/** callback for task_transfer http connections */
6290
int
6291
auth_xfer_transfer_http_callback(struct comm_point* c, void* arg, int err,
6292
  struct comm_reply* repinfo)
6293
0
{
6294
0
  struct auth_xfer* xfr = (struct auth_xfer*)arg;
6295
0
  struct module_env* env;
6296
0
  log_assert(xfr->task_transfer);
6297
0
  lock_basic_lock(&xfr->lock);
6298
0
  env = xfr->task_transfer->env;
6299
0
  if(!env || env->outnet->want_to_quit) {
6300
0
    lock_basic_unlock(&xfr->lock);
6301
0
    return 0; /* stop on quit */
6302
0
  }
6303
0
  verbose(VERB_ALGO, "auth zone transfer http callback");
6304
  /* stop the timer */
6305
0
  comm_timer_disable(xfr->task_transfer->timer);
6306
6307
0
  if(err != NETEVENT_NOERROR && err != NETEVENT_DONE) {
6308
    /* connection failed, closed, or timeout */
6309
    /* stop this transfer, cleanup 
6310
     * and continue task_transfer*/
6311
0
    verbose(VERB_ALGO, "http stopped, connection lost to %s",
6312
0
      xfr->task_transfer->master->host);
6313
0
  failed:
6314
    /* delete transferred data from list */
6315
0
    auth_chunks_delete(xfr->task_transfer);
6316
0
    if(repinfo) repinfo->c = NULL; /* signal cp deleted to
6317
        the routine calling this callback */
6318
0
    comm_point_delete(xfr->task_transfer->cp);
6319
0
    xfr->task_transfer->cp = NULL;
6320
0
    xfr_transfer_nextmaster(xfr);
6321
0
    xfr_transfer_nexttarget_or_end(xfr, env);
6322
0
    return 0;
6323
0
  }
6324
6325
  /* if it is good, link it into the list of data */
6326
  /* if the link into list of data fails (malloc fail) cleanup and end */
6327
0
  if(sldns_buffer_limit(c->buffer) > 0) {
6328
0
    verbose(VERB_ALGO, "auth zone http queued up %d bytes",
6329
0
      (int)sldns_buffer_limit(c->buffer));
6330
0
    if(!xfer_link_data(c->buffer, xfr)) {
6331
0
      verbose(VERB_ALGO, "http stopped to %s, malloc failed",
6332
0
        xfr->task_transfer->master->host);
6333
0
      goto failed;
6334
0
    }
6335
0
  }
6336
  /* if the transfer is done now, disconnect and process the list */
6337
0
  if(err == NETEVENT_DONE) {
6338
0
    if(repinfo) repinfo->c = NULL; /* signal cp deleted to
6339
        the routine calling this callback */
6340
0
    comm_point_delete(xfr->task_transfer->cp);
6341
0
    xfr->task_transfer->cp = NULL;
6342
0
    process_list_end_transfer(xfr, env);
6343
0
    return 0;
6344
0
  }
6345
6346
  /* if we want to read more messages, setup the commpoint to read
6347
   * a DNS packet, and the timeout */
6348
0
  lock_basic_unlock(&xfr->lock);
6349
0
  c->tcp_is_reading = 1;
6350
0
  sldns_buffer_clear(c->buffer);
6351
0
  comm_point_start_listening(c, -1, AUTH_TRANSFER_TIMEOUT);
6352
0
  return 0;
6353
0
}
6354
6355
6356
/** start transfer task by this worker , xfr is locked. */
6357
static void
6358
xfr_start_transfer(struct auth_xfer* xfr, struct module_env* env,
6359
  struct auth_master* master)
6360
0
{
6361
0
  log_assert(xfr->task_transfer != NULL);
6362
0
  log_assert(xfr->task_transfer->worker == NULL);
6363
0
  log_assert(xfr->task_transfer->chunks_first == NULL);
6364
0
  log_assert(xfr->task_transfer->chunks_last == NULL);
6365
0
  xfr->task_transfer->worker = env->worker;
6366
0
  xfr->task_transfer->env = env;
6367
6368
  /* init transfer process */
6369
  /* find that master in the transfer's list of masters? */
6370
0
  xfr_transfer_start_list(xfr, master);
6371
  /* start lookup for hostnames in transfer master list */
6372
0
  xfr_transfer_start_lookups(xfr);
6373
6374
  /* initiate TCP, and set timeout on it */
6375
0
  xfr_transfer_nexttarget_or_end(xfr, env);
6376
0
}
6377
6378
/** disown task_probe.  caller must hold xfr.lock */
6379
static void
6380
xfr_probe_disown(struct auth_xfer* xfr)
6381
0
{
6382
  /* remove timer (from this worker's event base) */
6383
0
  comm_timer_delete(xfr->task_probe->timer);
6384
0
  xfr->task_probe->timer = NULL;
6385
  /* remove the commpoint */
6386
0
  comm_point_delete(xfr->task_probe->cp);
6387
0
  xfr->task_probe->cp = NULL;
6388
  /* we don't own this item anymore */
6389
0
  xfr->task_probe->worker = NULL;
6390
0
  xfr->task_probe->env = NULL;
6391
0
}
6392
6393
/** send the UDP probe to the master, this is part of task_probe */
6394
static int
6395
xfr_probe_send_probe(struct auth_xfer* xfr, struct module_env* env,
6396
  int timeout)
6397
0
{
6398
0
  struct sockaddr_storage addr;
6399
0
  socklen_t addrlen = 0;
6400
0
  struct timeval t;
6401
  /* pick master */
6402
0
  struct auth_master* master = xfr_probe_current_master(xfr);
6403
0
  char *auth_name = NULL;
6404
0
  if(!master) return 0;
6405
0
  if(master->allow_notify) return 0; /* only for notify */
6406
0
  if(master->http) return 0; /* only masters get SOA UDP probe,
6407
    not urls, if those are in this list */
6408
6409
  /* get master addr */
6410
0
  if(xfr->task_probe->scan_addr) {
6411
0
    addrlen = xfr->task_probe->scan_addr->addrlen;
6412
0
    memmove(&addr, &xfr->task_probe->scan_addr->addr, addrlen);
6413
0
  } else {
6414
0
    if(!authextstrtoaddr(master->host, &addr, &addrlen, &auth_name)) {
6415
      /* the ones that are not in addr format are supposed
6416
       * to be looked up.  The lookup has failed however,
6417
       * so skip them */
6418
0
      char zname[LDNS_MAX_DOMAINLEN];
6419
0
      dname_str(xfr->name, zname);
6420
0
      log_err("%s: failed lookup, cannot probe to master %s",
6421
0
        zname, master->host);
6422
0
      return 0;
6423
0
    }
6424
0
    if (auth_name != NULL) {
6425
0
      if (addr.ss_family == AF_INET
6426
0
      &&  (int)ntohs(((struct sockaddr_in *)&addr)->sin_port)
6427
0
                == env->cfg->ssl_port)
6428
0
        ((struct sockaddr_in *)&addr)->sin_port
6429
0
          = htons((uint16_t)env->cfg->port);
6430
0
      else if (addr.ss_family == AF_INET6
6431
0
      &&  (int)ntohs(((struct sockaddr_in6 *)&addr)->sin6_port)
6432
0
                == env->cfg->ssl_port)
6433
0
                          ((struct sockaddr_in6 *)&addr)->sin6_port
6434
0
          = htons((uint16_t)env->cfg->port);
6435
0
    }
6436
0
  }
6437
6438
  /* create packet */
6439
  /* create new ID for new probes, but not on timeout retries,
6440
   * this means we'll accept replies to previous retries to same ip */
6441
0
  if(timeout == AUTH_PROBE_TIMEOUT)
6442
0
    xfr->task_probe->id = GET_RANDOM_ID(env->rnd);
6443
0
  xfr_create_soa_probe_packet(xfr, env->scratch_buffer, 
6444
0
    xfr->task_probe->id);
6445
  /* we need to remove the cp if we have a different ip4/ip6 type now */
6446
0
  if(xfr->task_probe->cp &&
6447
0
    ((xfr->task_probe->cp_is_ip6 && !addr_is_ip6(&addr, addrlen)) ||
6448
0
    (!xfr->task_probe->cp_is_ip6 && addr_is_ip6(&addr, addrlen)))
6449
0
    ) {
6450
0
    comm_point_delete(xfr->task_probe->cp);
6451
0
    xfr->task_probe->cp = NULL;
6452
0
  }
6453
0
  if(!xfr->task_probe->cp) {
6454
0
    if(addr_is_ip6(&addr, addrlen))
6455
0
      xfr->task_probe->cp_is_ip6 = 1;
6456
0
    else  xfr->task_probe->cp_is_ip6 = 0;
6457
0
    xfr->task_probe->cp = outnet_comm_point_for_udp(env->outnet,
6458
0
      auth_xfer_probe_udp_callback, xfr, &addr, addrlen);
6459
0
    if(!xfr->task_probe->cp) {
6460
0
      char zname[LDNS_MAX_DOMAINLEN], as[256];
6461
0
      dname_str(xfr->name, zname);
6462
0
      addr_port_to_str(&addr, addrlen, as, sizeof(as));
6463
0
      verbose(VERB_ALGO, "cannot create udp cp for "
6464
0
        "probe %s to %s", zname, as);
6465
0
      return 0;
6466
0
    }
6467
0
  }
6468
0
  if(!xfr->task_probe->timer) {
6469
0
    xfr->task_probe->timer = comm_timer_create(env->worker_base,
6470
0
      auth_xfer_probe_timer_callback, xfr);
6471
0
    if(!xfr->task_probe->timer) {
6472
0
      log_err("malloc failure");
6473
0
      return 0;
6474
0
    }
6475
0
  }
6476
6477
  /* send udp packet */
6478
0
  if(!comm_point_send_udp_msg(xfr->task_probe->cp, env->scratch_buffer,
6479
0
    (struct sockaddr*)&addr, addrlen, 0)) {
6480
0
    char zname[LDNS_MAX_DOMAINLEN], as[256];
6481
0
    dname_str(xfr->name, zname);
6482
0
    addr_port_to_str(&addr, addrlen, as, sizeof(as));
6483
0
    verbose(VERB_ALGO, "failed to send soa probe for %s to %s",
6484
0
      zname, as);
6485
0
    return 0;
6486
0
  }
6487
0
  if(verbosity >= VERB_ALGO) {
6488
0
    char zname[LDNS_MAX_DOMAINLEN], as[256];
6489
0
    dname_str(xfr->name, zname);
6490
0
    addr_port_to_str(&addr, addrlen, as, sizeof(as));
6491
0
    verbose(VERB_ALGO, "auth zone %s soa probe sent to %s", zname,
6492
0
      as);
6493
0
  }
6494
0
  xfr->task_probe->timeout = timeout;
6495
0
#ifndef S_SPLINT_S
6496
0
  t.tv_sec = timeout/1000;
6497
0
  t.tv_usec = (timeout%1000)*1000;
6498
0
#endif
6499
0
  comm_timer_set(xfr->task_probe->timer, &t);
6500
6501
0
  return 1;
6502
0
}
6503
6504
/** callback for task_probe timer */
6505
void
6506
auth_xfer_probe_timer_callback(void* arg)
6507
0
{
6508
0
  struct auth_xfer* xfr = (struct auth_xfer*)arg;
6509
0
  struct module_env* env;
6510
0
  log_assert(xfr->task_probe);
6511
0
  lock_basic_lock(&xfr->lock);
6512
0
  env = xfr->task_probe->env;
6513
0
  if(!env || env->outnet->want_to_quit) {
6514
0
    lock_basic_unlock(&xfr->lock);
6515
0
    return; /* stop on quit */
6516
0
  }
6517
6518
0
  if(verbosity >= VERB_ALGO) {
6519
0
    char zname[LDNS_MAX_DOMAINLEN];
6520
0
    dname_str(xfr->name, zname);
6521
0
    verbose(VERB_ALGO, "auth zone %s soa probe timeout", zname);
6522
0
  }
6523
0
  if(xfr->task_probe->timeout <= AUTH_PROBE_TIMEOUT_STOP) {
6524
    /* try again with bigger timeout */
6525
0
    if(xfr_probe_send_probe(xfr, env, xfr->task_probe->timeout*2)) {
6526
0
      lock_basic_unlock(&xfr->lock);
6527
0
      return;
6528
0
    }
6529
0
  }
6530
  /* delete commpoint so a new one is created, with a fresh port nr */
6531
0
  comm_point_delete(xfr->task_probe->cp);
6532
0
  xfr->task_probe->cp = NULL;
6533
6534
  /* too many timeouts (or fail to send), move to next or end */
6535
0
  xfr_probe_nextmaster(xfr);
6536
0
  xfr_probe_send_or_end(xfr, env);
6537
0
}
6538
6539
/** callback for task_probe udp packets */
6540
int
6541
auth_xfer_probe_udp_callback(struct comm_point* c, void* arg, int err,
6542
  struct comm_reply* repinfo)
6543
0
{
6544
0
  struct auth_xfer* xfr = (struct auth_xfer*)arg;
6545
0
  struct module_env* env;
6546
0
  log_assert(xfr->task_probe);
6547
0
  lock_basic_lock(&xfr->lock);
6548
0
  env = xfr->task_probe->env;
6549
0
  if(!env || env->outnet->want_to_quit) {
6550
0
    lock_basic_unlock(&xfr->lock);
6551
0
    return 0; /* stop on quit */
6552
0
  }
6553
6554
  /* the comm_point_udp_callback is in a for loop for NUM_UDP_PER_SELECT
6555
   * and we set rep.c=NULL to stop if from looking inside the commpoint*/
6556
0
  repinfo->c = NULL;
6557
  /* stop the timer */
6558
0
  comm_timer_disable(xfr->task_probe->timer);
6559
6560
  /* see if we got a packet and what that means */
6561
0
  if(err == NETEVENT_NOERROR) {
6562
0
    uint32_t serial = 0;
6563
0
    if(check_packet_ok(c->buffer, LDNS_RR_TYPE_SOA, xfr,
6564
0
      &serial)) {
6565
      /* successful lookup */
6566
0
      if(verbosity >= VERB_ALGO) {
6567
0
        char buf[LDNS_MAX_DOMAINLEN];
6568
0
        dname_str(xfr->name, buf);
6569
0
        verbose(VERB_ALGO, "auth zone %s: soa probe "
6570
0
          "serial is %u", buf, (unsigned)serial);
6571
0
      }
6572
      /* see if this serial indicates that the zone has
6573
       * to be updated */
6574
0
      if(xfr_serial_means_update(xfr, serial)) {
6575
        /* if updated, start the transfer task, if needed */
6576
0
        verbose(VERB_ALGO, "auth_zone updated, start transfer");
6577
0
        if(xfr->task_transfer->worker == NULL) {
6578
0
          struct auth_master* master =
6579
0
            xfr_probe_current_master(xfr);
6580
          /* if we have download URLs use them
6581
           * in preference to this master we
6582
           * just probed the SOA from */
6583
0
          if(xfr->task_transfer->masters &&
6584
0
            xfr->task_transfer->masters->http)
6585
0
            master = NULL;
6586
0
          xfr_probe_disown(xfr);
6587
0
          xfr_start_transfer(xfr, env, master);
6588
0
          return 0;
6589
6590
0
        }
6591
        /* other tasks are running, we don't do this anymore */
6592
0
        xfr_probe_disown(xfr);
6593
0
        lock_basic_unlock(&xfr->lock);
6594
        /* return, we don't sent a reply to this udp packet,
6595
         * and we setup the tasks to do next */
6596
0
        return 0;
6597
0
      } else {
6598
0
        verbose(VERB_ALGO, "auth_zone master reports unchanged soa serial");
6599
        /* we if cannot find updates amongst the
6600
         * masters, this means we then have a new lease
6601
         * on the zone */
6602
0
        xfr->task_probe->have_new_lease = 1;
6603
0
      }
6604
0
    } else {
6605
0
      if(verbosity >= VERB_ALGO) {
6606
0
        char buf[LDNS_MAX_DOMAINLEN];
6607
0
        dname_str(xfr->name, buf);
6608
0
        verbose(VERB_ALGO, "auth zone %s: bad reply to soa probe", buf);
6609
0
      }
6610
0
    }
6611
0
  } else {
6612
0
    if(verbosity >= VERB_ALGO) {
6613
0
      char buf[LDNS_MAX_DOMAINLEN];
6614
0
      dname_str(xfr->name, buf);
6615
0
      verbose(VERB_ALGO, "auth zone %s: soa probe failed", buf);
6616
0
    }
6617
0
  }
6618
  
6619
  /* failed lookup or not an update */
6620
  /* delete commpoint so a new one is created, with a fresh port nr */
6621
0
  comm_point_delete(xfr->task_probe->cp);
6622
0
  xfr->task_probe->cp = NULL;
6623
6624
  /* if the result was not a successful probe, we need
6625
   * to send the next one */
6626
0
  xfr_probe_nextmaster(xfr);
6627
0
  xfr_probe_send_or_end(xfr, env);
6628
0
  return 0;
6629
0
}
6630
6631
/** lookup a host name for its addresses, if needed */
6632
static int
6633
xfr_probe_lookup_host(struct auth_xfer* xfr, struct module_env* env)
6634
0
{
6635
0
  struct sockaddr_storage addr;
6636
0
  socklen_t addrlen = 0;
6637
0
  struct auth_master* master = xfr->task_probe->lookup_target;
6638
0
  struct query_info qinfo;
6639
0
  uint16_t qflags = BIT_RD;
6640
0
  uint8_t dname[LDNS_MAX_DOMAINLEN+1];
6641
0
  struct edns_data edns;
6642
0
  sldns_buffer* buf = env->scratch_buffer;
6643
0
  if(!master) return 0;
6644
0
  if(extstrtoaddr(master->host, &addr, &addrlen, UNBOUND_DNS_PORT)) {
6645
    /* not needed, host is in IP addr format */
6646
0
    return 0;
6647
0
  }
6648
0
  if(master->allow_notify && !master->http &&
6649
0
    strchr(master->host, '/') != NULL &&
6650
0
    strchr(master->host, '/') == strrchr(master->host, '/')) {
6651
0
    return 0; /* is IP/prefix format, not something to look up */
6652
0
  }
6653
6654
  /* use mesh_new_callback to probe for non-addr hosts,
6655
   * and then wait for them to be looked up (in cache, or query) */
6656
0
  qinfo.qname_len = sizeof(dname);
6657
0
  if(sldns_str2wire_dname_buf(master->host, dname, &qinfo.qname_len)
6658
0
    != 0) {
6659
0
    log_err("cannot parse host name of master %s", master->host);
6660
0
    return 0;
6661
0
  }
6662
0
  qinfo.qname = dname;
6663
0
  qinfo.qclass = xfr->dclass;
6664
0
  qinfo.qtype = LDNS_RR_TYPE_A;
6665
0
  if(xfr->task_probe->lookup_aaaa)
6666
0
    qinfo.qtype = LDNS_RR_TYPE_AAAA;
6667
0
  qinfo.local_alias = NULL;
6668
0
  if(verbosity >= VERB_ALGO) {
6669
0
    char buf1[512];
6670
0
    char buf2[LDNS_MAX_DOMAINLEN];
6671
0
    dname_str(xfr->name, buf2);
6672
0
    snprintf(buf1, sizeof(buf1), "auth zone %s: master lookup"
6673
0
      " for task_probe", buf2);
6674
0
    log_query_info(VERB_ALGO, buf1, &qinfo);
6675
0
  }
6676
0
  edns.edns_present = 1;
6677
0
  edns.ext_rcode = 0;
6678
0
  edns.edns_version = 0;
6679
0
  edns.bits = EDNS_DO;
6680
0
  edns.opt_list_in = NULL;
6681
0
  edns.opt_list_out = NULL;
6682
0
  edns.opt_list_inplace_cb_out = NULL;
6683
0
  edns.padding_block_size = 0;
6684
0
  edns.cookie_present = 0;
6685
0
  edns.cookie_valid = 0;
6686
0
  if(sldns_buffer_capacity(buf) < 65535)
6687
0
    edns.udp_size = (uint16_t)sldns_buffer_capacity(buf);
6688
0
  else  edns.udp_size = 65535;
6689
6690
  /* unlock xfr during mesh_new_callback() because the callback can be
6691
   * called straight away */
6692
0
  lock_basic_unlock(&xfr->lock);
6693
0
  if(!mesh_new_callback(env->mesh, &qinfo, qflags, &edns, buf, 0,
6694
0
    &auth_xfer_probe_lookup_callback, xfr, 0)) {
6695
0
    lock_basic_lock(&xfr->lock);
6696
0
    log_err("out of memory lookup up master %s", master->host);
6697
0
    return 0;
6698
0
  }
6699
0
  lock_basic_lock(&xfr->lock);
6700
0
  return 1;
6701
0
}
6702
6703
/** return true if there are probe (SOA UDP query) targets in the master list*/
6704
static int
6705
have_probe_targets(struct auth_master* list)
6706
0
{
6707
0
  struct auth_master* p;
6708
0
  for(p=list; p; p = p->next) {
6709
0
    if(!p->allow_notify && p->host)
6710
0
      return 1;
6711
0
  }
6712
0
  return 0;
6713
0
}
6714
6715
/** move to sending the probe packets, next if fails. task_probe */
6716
static void
6717
xfr_probe_send_or_end(struct auth_xfer* xfr, struct module_env* env)
6718
0
{
6719
  /* are we doing hostname lookups? */
6720
0
  while(xfr->task_probe->lookup_target) {
6721
0
    if(xfr_probe_lookup_host(xfr, env)) {
6722
      /* wait for lookup to finish,
6723
       * note that the hostname may be in unbound's cache
6724
       * and we may then get an instant cache response,
6725
       * and that calls the callback just like a full
6726
       * lookup and lookup failures also call callback */
6727
0
      if(verbosity >= VERB_ALGO) {
6728
0
        char zname[LDNS_MAX_DOMAINLEN];
6729
0
        dname_str(xfr->name, zname);
6730
0
        verbose(VERB_ALGO, "auth zone %s probe next target lookup", zname);
6731
0
      }
6732
0
      lock_basic_unlock(&xfr->lock);
6733
0
      return;
6734
0
    }
6735
0
    xfr_probe_move_to_next_lookup(xfr, env);
6736
0
  }
6737
  /* probe of list has ended.  Create or refresh the list of of
6738
   * allow_notify addrs */
6739
0
  probe_copy_masters_for_allow_notify(xfr);
6740
0
  if(verbosity >= VERB_ALGO) {
6741
0
    char zname[LDNS_MAX_DOMAINLEN];
6742
0
    dname_str(xfr->name, zname);
6743
0
    verbose(VERB_ALGO, "auth zone %s probe: notify addrs updated", zname);
6744
0
  }
6745
0
  if(xfr->task_probe->only_lookup) {
6746
    /* only wanted lookups for copy, stop probe and start wait */
6747
0
    xfr->task_probe->only_lookup = 0;
6748
0
    if(verbosity >= VERB_ALGO) {
6749
0
      char zname[LDNS_MAX_DOMAINLEN];
6750
0
      dname_str(xfr->name, zname);
6751
0
      verbose(VERB_ALGO, "auth zone %s probe: finished only_lookup", zname);
6752
0
    }
6753
0
    xfr_probe_disown(xfr);
6754
0
    if(!have_probe_targets(xfr->task_probe->masters)) {
6755
      /* If there are no masters to probe, go to transfer. */
6756
0
      if(xfr->task_transfer->worker == NULL) {
6757
0
        xfr_start_transfer(xfr, env, NULL);
6758
0
        return;
6759
0
      }
6760
      /* The transfer is already in progress. */
6761
0
      lock_basic_unlock(&xfr->lock);
6762
0
      return;
6763
0
    }
6764
0
    if(xfr->task_nextprobe->worker == NULL)
6765
0
      xfr_set_timeout(xfr, env, 0, 0);
6766
0
    lock_basic_unlock(&xfr->lock);
6767
0
    return;
6768
0
  }
6769
6770
  /* send probe packets */
6771
0
  while(!xfr_probe_end_of_list(xfr)) {
6772
0
    if(xfr_probe_send_probe(xfr, env, AUTH_PROBE_TIMEOUT)) {
6773
      /* successfully sent probe, wait for callback */
6774
0
      lock_basic_unlock(&xfr->lock);
6775
0
      return;
6776
0
    }
6777
    /* failed to send probe, next master */
6778
0
    xfr_probe_nextmaster(xfr);
6779
0
  }
6780
6781
  /* done with probe sequence, wait */
6782
0
  if(xfr->task_probe->have_new_lease) {
6783
    /* if zone not updated, start the wait timer again */
6784
0
    if(verbosity >= VERB_ALGO) {
6785
0
      char zname[LDNS_MAX_DOMAINLEN];
6786
0
      dname_str(xfr->name, zname);
6787
0
      verbose(VERB_ALGO, "auth_zone %s unchanged, new lease, wait", zname);
6788
0
    }
6789
0
    xfr_probe_disown(xfr);
6790
0
    if(xfr->have_zone)
6791
0
      xfr->lease_time = *env->now;
6792
0
    if(xfr->task_nextprobe->worker == NULL)
6793
0
      xfr_set_timeout(xfr, env, 0, 0);
6794
0
  } else {
6795
0
    if(verbosity >= VERB_ALGO) {
6796
0
      char zname[LDNS_MAX_DOMAINLEN];
6797
0
      dname_str(xfr->name, zname);
6798
0
      verbose(VERB_ALGO, "auth zone %s soa probe failed, wait to retry", zname);
6799
0
    }
6800
    /* we failed to send this as well, move to the wait task,
6801
     * use the shorter retry timeout */
6802
0
    xfr_probe_disown(xfr);
6803
    /* pick up the nextprobe task and wait */
6804
0
    if(xfr->task_nextprobe->worker == NULL)
6805
0
      xfr_set_timeout(xfr, env, 1, 0);
6806
0
  }
6807
6808
0
  lock_basic_unlock(&xfr->lock);
6809
0
}
6810
6811
/** callback for task_probe lookup of host name, of A or AAAA */
6812
void auth_xfer_probe_lookup_callback(void* arg, int rcode, sldns_buffer* buf,
6813
  enum sec_status ATTR_UNUSED(sec), char* ATTR_UNUSED(why_bogus),
6814
  int ATTR_UNUSED(was_ratelimited))
6815
0
{
6816
0
  struct auth_xfer* xfr = (struct auth_xfer*)arg;
6817
0
  struct module_env* env;
6818
0
  log_assert(xfr->task_probe);
6819
0
  lock_basic_lock(&xfr->lock);
6820
0
  env = xfr->task_probe->env;
6821
0
  if(!env || env->outnet->want_to_quit) {
6822
0
    lock_basic_unlock(&xfr->lock);
6823
0
    return; /* stop on quit */
6824
0
  }
6825
6826
  /* process result */
6827
0
  if(rcode == LDNS_RCODE_NOERROR) {
6828
0
    uint16_t wanted_qtype = LDNS_RR_TYPE_A;
6829
0
    struct regional* temp = env->scratch;
6830
0
    struct query_info rq;
6831
0
    struct reply_info* rep;
6832
0
    if(xfr->task_probe->lookup_aaaa)
6833
0
      wanted_qtype = LDNS_RR_TYPE_AAAA;
6834
0
    memset(&rq, 0, sizeof(rq));
6835
0
    rep = parse_reply_in_temp_region(buf, temp, &rq);
6836
0
    if(rep && rq.qtype == wanted_qtype &&
6837
0
      FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NOERROR) {
6838
      /* parsed successfully */
6839
0
      struct ub_packed_rrset_key* answer =
6840
0
        reply_find_answer_rrset(&rq, rep);
6841
0
      if(answer) {
6842
0
        xfr_master_add_addrs(xfr->task_probe->
6843
0
          lookup_target, answer, wanted_qtype);
6844
0
      } else {
6845
0
        if(verbosity >= VERB_ALGO) {
6846
0
          char zname[LDNS_MAX_DOMAINLEN];
6847
0
          dname_str(xfr->name, zname);
6848
0
          verbose(VERB_ALGO, "auth zone %s host %s type %s probe lookup has nodata", zname, xfr->task_probe->lookup_target->host, (xfr->task_probe->lookup_aaaa?"AAAA":"A"));
6849
0
        }
6850
0
      }
6851
0
    } else {
6852
0
      if(verbosity >= VERB_ALGO) {
6853
0
        char zname[LDNS_MAX_DOMAINLEN];
6854
0
        dname_str(xfr->name, zname);
6855
0
        verbose(VERB_ALGO, "auth zone %s host %s type %s probe lookup has no address", zname, xfr->task_probe->lookup_target->host, (xfr->task_probe->lookup_aaaa?"AAAA":"A"));
6856
0
      }
6857
0
    }
6858
0
    regional_free_all(temp);
6859
0
  } else {
6860
0
    if(verbosity >= VERB_ALGO) {
6861
0
      char zname[LDNS_MAX_DOMAINLEN];
6862
0
      dname_str(xfr->name, zname);
6863
0
      verbose(VERB_ALGO, "auth zone %s host %s type %s probe lookup failed", zname, xfr->task_probe->lookup_target->host, (xfr->task_probe->lookup_aaaa?"AAAA":"A"));
6864
0
    }
6865
0
  }
6866
0
  if(xfr->task_probe->lookup_target->list &&
6867
0
    xfr->task_probe->lookup_target == xfr_probe_current_master(xfr))
6868
0
    xfr->task_probe->scan_addr = xfr->task_probe->lookup_target->list;
6869
6870
  /* move to lookup AAAA after A lookup, move to next hostname lookup,
6871
   * or move to send the probes, or, if nothing to do, end task_probe */
6872
0
  xfr_probe_move_to_next_lookup(xfr, env);
6873
0
  xfr_probe_send_or_end(xfr, env);
6874
0
}
6875
6876
/** disown task_nextprobe.  caller must hold xfr.lock */
6877
static void
6878
xfr_nextprobe_disown(struct auth_xfer* xfr)
6879
0
{
6880
  /* delete the timer, because the next worker to pick this up may
6881
   * not have the same event base */
6882
0
  comm_timer_delete(xfr->task_nextprobe->timer);
6883
0
  xfr->task_nextprobe->timer = NULL;
6884
0
  xfr->task_nextprobe->next_probe = 0;
6885
  /* we don't own this item anymore */
6886
0
  xfr->task_nextprobe->worker = NULL;
6887
0
  xfr->task_nextprobe->env = NULL;
6888
0
}
6889
6890
/** xfer nextprobe timeout callback, this is part of task_nextprobe */
6891
void
6892
auth_xfer_timer(void* arg)
6893
0
{
6894
0
  struct auth_xfer* xfr = (struct auth_xfer*)arg;
6895
0
  struct module_env* env;
6896
0
  log_assert(xfr->task_nextprobe);
6897
0
  lock_basic_lock(&xfr->lock);
6898
0
  env = xfr->task_nextprobe->env;
6899
0
  if(!env || env->outnet->want_to_quit) {
6900
0
    lock_basic_unlock(&xfr->lock);
6901
0
    return; /* stop on quit */
6902
0
  }
6903
6904
  /* see if zone has expired, and if so, also set auth_zone expired */
6905
0
  if(xfr->have_zone && !xfr->zone_expired &&
6906
0
     *env->now >= xfr->lease_time + xfr->expiry) {
6907
0
    lock_basic_unlock(&xfr->lock);
6908
0
    auth_xfer_set_expired(xfr, env, 1);
6909
0
    lock_basic_lock(&xfr->lock);
6910
0
  }
6911
6912
0
  xfr_nextprobe_disown(xfr);
6913
6914
0
  if(!xfr_start_probe(xfr, env, NULL)) {
6915
    /* not started because already in progress */
6916
0
    lock_basic_unlock(&xfr->lock);
6917
0
  }
6918
0
}
6919
6920
/** start task_probe if possible, if no masters for probe start task_transfer
6921
 * returns true if task has been started, and false if the task is already
6922
 * in progress. */
6923
static int
6924
xfr_start_probe(struct auth_xfer* xfr, struct module_env* env,
6925
  struct auth_master* spec)
6926
0
{
6927
  /* see if we need to start a probe (or maybe it is already in
6928
   * progress (due to notify)) */
6929
0
  if(xfr->task_probe->worker == NULL) {
6930
0
    if(!have_probe_targets(xfr->task_probe->masters) &&
6931
0
      xfr->task_probe->masters != NULL)
6932
0
      xfr->task_probe->only_lookup = 1;
6933
0
    if(!(xfr->task_probe->only_lookup &&
6934
0
      xfr->task_probe->masters != NULL)) {
6935
      /* useless to pick up task_probe, no masters to
6936
       * probe. Instead attempt to pick up task transfer */
6937
0
      if(xfr->task_transfer->worker == NULL) {
6938
0
        xfr_start_transfer(xfr, env, spec);
6939
0
        return 1;
6940
0
      }
6941
      /* task transfer already in progress */
6942
0
      return 0;
6943
0
    }
6944
6945
    /* pick up the probe task ourselves */
6946
0
    xfr->task_probe->worker = env->worker;
6947
0
    xfr->task_probe->env = env;
6948
0
    xfr->task_probe->cp = NULL;
6949
6950
    /* start the task */
6951
    /* have not seen a new lease yet, this scan */
6952
0
    xfr->task_probe->have_new_lease = 0;
6953
    /* if this was a timeout, no specific first master to scan */
6954
    /* otherwise, spec is nonNULL the notified master, scan
6955
     * first and also transfer first from it */
6956
0
    xfr_probe_start_list(xfr, spec);
6957
    /* setup to start the lookup of hostnames of masters afresh */
6958
0
    xfr_probe_start_lookups(xfr);
6959
    /* send the probe packet or next send, or end task */
6960
0
    xfr_probe_send_or_end(xfr, env);
6961
0
    return 1;
6962
0
  }
6963
0
  return 0;
6964
0
}
6965
6966
/** for task_nextprobe.
6967
 * determine next timeout for auth_xfer. Also (re)sets timer.
6968
 * @param xfr: task structure
6969
 * @param env: module environment, with worker and time.
6970
 * @param failure: set true if timer should be set for failure retry.
6971
 * @param lookup_only: only perform lookups when timer done, 0 sec timeout
6972
 */
6973
static void
6974
xfr_set_timeout(struct auth_xfer* xfr, struct module_env* env,
6975
  int failure, int lookup_only)
6976
0
{
6977
0
  struct timeval tv;
6978
0
  log_assert(xfr->task_nextprobe != NULL);
6979
0
  log_assert(xfr->task_nextprobe->worker == NULL ||
6980
0
    xfr->task_nextprobe->worker == env->worker);
6981
  /* normally, nextprobe = startoflease + refresh,
6982
   * but if expiry is sooner, use that one.
6983
   * after a failure, use the retry timer instead. */
6984
0
  xfr->task_nextprobe->next_probe = *env->now;
6985
0
  if(xfr->lease_time && !failure)
6986
0
    xfr->task_nextprobe->next_probe = xfr->lease_time;
6987
  
6988
0
  if(!failure) {
6989
0
    xfr->task_nextprobe->backoff = 0;
6990
0
  } else {
6991
0
    if(xfr->task_nextprobe->backoff == 0)
6992
0
        xfr->task_nextprobe->backoff = 3;
6993
0
    else  xfr->task_nextprobe->backoff *= 2;
6994
0
    if(xfr->task_nextprobe->backoff > AUTH_TRANSFER_MAX_BACKOFF)
6995
0
      xfr->task_nextprobe->backoff =
6996
0
        AUTH_TRANSFER_MAX_BACKOFF;
6997
0
  }
6998
6999
0
  if(xfr->have_zone) {
7000
0
    time_t wait = xfr->refresh;
7001
0
    if(failure) wait = xfr->retry;
7002
0
    if(xfr->expiry < wait)
7003
0
      xfr->task_nextprobe->next_probe += xfr->expiry;
7004
0
    else  xfr->task_nextprobe->next_probe += wait;
7005
0
    if(failure)
7006
0
      xfr->task_nextprobe->next_probe +=
7007
0
        xfr->task_nextprobe->backoff;
7008
    /* put the timer exactly on expiry, if possible */
7009
0
    if(xfr->lease_time && xfr->lease_time+xfr->expiry <
7010
0
      xfr->task_nextprobe->next_probe &&
7011
0
      xfr->lease_time+xfr->expiry > *env->now)
7012
0
      xfr->task_nextprobe->next_probe =
7013
0
        xfr->lease_time+xfr->expiry;
7014
0
  } else {
7015
0
    xfr->task_nextprobe->next_probe +=
7016
0
      xfr->task_nextprobe->backoff;
7017
0
  }
7018
7019
0
  if(!xfr->task_nextprobe->timer) {
7020
0
    xfr->task_nextprobe->timer = comm_timer_create(
7021
0
      env->worker_base, auth_xfer_timer, xfr);
7022
0
    if(!xfr->task_nextprobe->timer) {
7023
      /* failed to malloc memory. likely zone transfer
7024
       * also fails for that. skip the timeout */
7025
0
      char zname[LDNS_MAX_DOMAINLEN];
7026
0
      dname_str(xfr->name, zname);
7027
0
      log_err("cannot allocate timer, no refresh for %s",
7028
0
        zname);
7029
0
      return;
7030
0
    }
7031
0
  }
7032
0
  xfr->task_nextprobe->worker = env->worker;
7033
0
  xfr->task_nextprobe->env = env;
7034
0
  if(*(xfr->task_nextprobe->env->now) <= xfr->task_nextprobe->next_probe)
7035
0
    tv.tv_sec = xfr->task_nextprobe->next_probe - 
7036
0
      *(xfr->task_nextprobe->env->now);
7037
0
  else  tv.tv_sec = 0;
7038
0
  if(tv.tv_sec != 0 && lookup_only && xfr->task_probe->masters) {
7039
    /* don't lookup_only, if lookup timeout is 0 anyway,
7040
     * or if we don't have masters to lookup */
7041
0
    tv.tv_sec = 0;
7042
0
    if(xfr->task_probe->worker == NULL)
7043
0
      xfr->task_probe->only_lookup = 1;
7044
0
  }
7045
0
  if(verbosity >= VERB_ALGO) {
7046
0
    char zname[LDNS_MAX_DOMAINLEN];
7047
0
    dname_str(xfr->name, zname);
7048
0
    verbose(VERB_ALGO, "auth zone %s timeout in %d seconds",
7049
0
      zname, (int)tv.tv_sec);
7050
0
  }
7051
0
  tv.tv_usec = 0;
7052
0
  comm_timer_set(xfr->task_nextprobe->timer, &tv);
7053
0
}
7054
7055
void auth_zone_pickup_initial_zone(struct auth_zone* z, struct module_env* env)
7056
0
{
7057
  /* Set the time, because we now have timestamp in env,
7058
   * (not earlier during startup and apply_cfg), and this
7059
   * notes the start time when the data was acquired. */
7060
0
  z->soa_zone_acquired = *env->now;
7061
0
}
7062
7063
void auth_xfer_pickup_initial_zone(struct auth_xfer* x, struct module_env* env)
7064
0
{
7065
  /* set lease_time, because we now have timestamp in env,
7066
   * (not earlier during startup and apply_cfg), and this
7067
   * notes the start time when the data was acquired */
7068
0
  if(x->have_zone) {
7069
0
    x->lease_time = *env->now;
7070
0
    x->soa_zone_acquired = *env->now;
7071
0
  }
7072
0
  if(x->task_nextprobe && x->task_nextprobe->worker == NULL) {
7073
0
    xfr_set_timeout(x, env, 0, 1);
7074
0
  }
7075
0
}
7076
7077
/** initial pick up of worker timeouts, ties events to worker event loop */
7078
void
7079
auth_xfer_pickup_initial(struct auth_zones* az, struct module_env* env)
7080
0
{
7081
0
  struct auth_xfer* x;
7082
0
  struct auth_zone* z;
7083
0
  lock_rw_wrlock(&az->lock);
7084
0
  RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
7085
0
    lock_rw_wrlock(&z->lock);
7086
0
    auth_zone_pickup_initial_zone(z, env);
7087
0
    lock_rw_unlock(&z->lock);
7088
0
  }
7089
0
  RBTREE_FOR(x, struct auth_xfer*, &az->xtree) {
7090
0
    lock_basic_lock(&x->lock);
7091
0
    auth_xfer_pickup_initial_zone(x, env);
7092
0
    lock_basic_unlock(&x->lock);
7093
0
  }
7094
0
  lock_rw_unlock(&az->lock);
7095
0
}
7096
7097
void auth_zones_cleanup(struct auth_zones* az)
7098
0
{
7099
0
  struct auth_xfer* x;
7100
0
  lock_rw_wrlock(&az->lock);
7101
0
  RBTREE_FOR(x, struct auth_xfer*, &az->xtree) {
7102
0
    lock_basic_lock(&x->lock);
7103
0
    if(x->task_nextprobe && x->task_nextprobe->worker != NULL) {
7104
0
      xfr_nextprobe_disown(x);
7105
0
    }
7106
0
    if(x->task_probe && x->task_probe->worker != NULL) {
7107
0
      xfr_probe_disown(x);
7108
0
    }
7109
0
    if(x->task_transfer && x->task_transfer->worker != NULL) {
7110
0
      auth_chunks_delete(x->task_transfer);
7111
0
      xfr_transfer_disown(x);
7112
0
    }
7113
0
    lock_basic_unlock(&x->lock);
7114
0
  }
7115
0
  lock_rw_unlock(&az->lock);
7116
0
}
7117
7118
/**
7119
 * malloc the xfer and tasks
7120
 * @param z: auth_zone with name of zone.
7121
 */
7122
static struct auth_xfer*
7123
auth_xfer_new(struct auth_zone* z)
7124
0
{
7125
0
  struct auth_xfer* xfr;
7126
0
  xfr = (struct auth_xfer*)calloc(1, sizeof(*xfr));
7127
0
  if(!xfr) return NULL;
7128
0
  xfr->name = memdup(z->name, z->namelen);
7129
0
  if(!xfr->name) {
7130
0
    free(xfr);
7131
0
    return NULL;
7132
0
  }
7133
0
  xfr->node.key = xfr;
7134
0
  xfr->namelen = z->namelen;
7135
0
  xfr->namelabs = z->namelabs;
7136
0
  xfr->dclass = z->dclass;
7137
7138
0
  xfr->task_nextprobe = (struct auth_nextprobe*)calloc(1,
7139
0
    sizeof(struct auth_nextprobe));
7140
0
  if(!xfr->task_nextprobe) {
7141
0
    free(xfr->name);
7142
0
    free(xfr);
7143
0
    return NULL;
7144
0
  }
7145
0
  xfr->task_probe = (struct auth_probe*)calloc(1,
7146
0
    sizeof(struct auth_probe));
7147
0
  if(!xfr->task_probe) {
7148
0
    free(xfr->task_nextprobe);
7149
0
    free(xfr->name);
7150
0
    free(xfr);
7151
0
    return NULL;
7152
0
  }
7153
0
  xfr->task_transfer = (struct auth_transfer*)calloc(1,
7154
0
    sizeof(struct auth_transfer));
7155
0
  if(!xfr->task_transfer) {
7156
0
    free(xfr->task_probe);
7157
0
    free(xfr->task_nextprobe);
7158
0
    free(xfr->name);
7159
0
    free(xfr);
7160
0
    return NULL;
7161
0
  }
7162
7163
0
  lock_basic_init(&xfr->lock);
7164
0
  lock_protect(&xfr->lock, &xfr->name, sizeof(xfr->name));
7165
0
  lock_protect(&xfr->lock, &xfr->namelen, sizeof(xfr->namelen));
7166
0
  lock_protect(&xfr->lock, xfr->name, xfr->namelen);
7167
0
  lock_protect(&xfr->lock, &xfr->namelabs, sizeof(xfr->namelabs));
7168
0
  lock_protect(&xfr->lock, &xfr->dclass, sizeof(xfr->dclass));
7169
0
  lock_protect(&xfr->lock, &xfr->notify_received, sizeof(xfr->notify_received));
7170
0
  lock_protect(&xfr->lock, &xfr->notify_serial, sizeof(xfr->notify_serial));
7171
0
  lock_protect(&xfr->lock, &xfr->zone_expired, sizeof(xfr->zone_expired));
7172
0
  lock_protect(&xfr->lock, &xfr->have_zone, sizeof(xfr->have_zone));
7173
0
  lock_protect(&xfr->lock, &xfr->soa_zone_acquired, sizeof(xfr->soa_zone_acquired));
7174
0
  lock_protect(&xfr->lock, &xfr->serial, sizeof(xfr->serial));
7175
0
  lock_protect(&xfr->lock, &xfr->retry, sizeof(xfr->retry));
7176
0
  lock_protect(&xfr->lock, &xfr->refresh, sizeof(xfr->refresh));
7177
0
  lock_protect(&xfr->lock, &xfr->expiry, sizeof(xfr->expiry));
7178
0
  lock_protect(&xfr->lock, &xfr->lease_time, sizeof(xfr->lease_time));
7179
0
  lock_protect(&xfr->lock, &xfr->task_nextprobe->worker,
7180
0
    sizeof(xfr->task_nextprobe->worker));
7181
0
  lock_protect(&xfr->lock, &xfr->task_probe->worker,
7182
0
    sizeof(xfr->task_probe->worker));
7183
0
  lock_protect(&xfr->lock, &xfr->task_transfer->worker,
7184
0
    sizeof(xfr->task_transfer->worker));
7185
0
  lock_basic_lock(&xfr->lock);
7186
0
  return xfr;
7187
0
}
7188
7189
/** Create auth_xfer structure.
7190
 * This populates the have_zone, soa values, and so on times.
7191
 * and sets the timeout, if a zone transfer is needed a short timeout is set.
7192
 * For that the auth_zone itself must exist (and read in zonefile)
7193
 * returns false on alloc failure. */
7194
struct auth_xfer*
7195
auth_xfer_create(struct auth_zones* az, struct auth_zone* z)
7196
0
{
7197
0
  struct auth_xfer* xfr;
7198
7199
  /* malloc it */
7200
0
  xfr = auth_xfer_new(z);
7201
0
  if(!xfr) {
7202
0
    log_err("malloc failure");
7203
0
    return NULL;
7204
0
  }
7205
  /* insert in tree */
7206
0
  (void)rbtree_insert(&az->xtree, &xfr->node);
7207
0
  return xfr;
7208
0
}
7209
7210
/** create new auth_master structure */
7211
static struct auth_master*
7212
auth_master_new(struct auth_master*** list)
7213
0
{
7214
0
  struct auth_master *m;
7215
0
  m = (struct auth_master*)calloc(1, sizeof(*m));
7216
0
  if(!m) {
7217
0
    log_err("malloc failure");
7218
0
    return NULL;
7219
0
  }
7220
  /* set first pointer to m, or next pointer of previous element to m */
7221
0
  (**list) = m;
7222
  /* store m's next pointer as future point to store at */
7223
0
  (*list) = &(m->next);
7224
0
  return m;
7225
0
}
7226
7227
/** dup_prefix : create string from initial part of other string, malloced */
7228
static char*
7229
dup_prefix(char* str, size_t num)
7230
0
{
7231
0
  char* result;
7232
0
  size_t len = strlen(str);
7233
0
  if(len < num) num = len; /* not more than strlen */
7234
0
  result = (char*)malloc(num+1);
7235
0
  if(!result) {
7236
0
    log_err("malloc failure");
7237
0
    return result;
7238
0
  }
7239
0
  memmove(result, str, num);
7240
0
  result[num] = 0;
7241
0
  return result;
7242
0
}
7243
7244
/** dup string and print error on error */
7245
static char*
7246
dup_all(char* str)
7247
0
{
7248
0
  char* result = strdup(str);
7249
0
  if(!result) {
7250
0
    log_err("malloc failure");
7251
0
    return NULL;
7252
0
  }
7253
0
  return result;
7254
0
}
7255
7256
/** find first of two characters */
7257
static char*
7258
str_find_first_of_chars(char* s, char a, char b)
7259
0
{
7260
0
  char* ra = strchr(s, a);
7261
0
  char* rb = strchr(s, b);
7262
0
  if(!ra) return rb;
7263
0
  if(!rb) return ra;
7264
0
  if(ra < rb) return ra;
7265
0
  return rb;
7266
0
}
7267
7268
/** parse URL into host and file parts, false on malloc or parse error */
7269
static int
7270
parse_url(char* url, char** host, char** file, int* port, int* ssl)
7271
0
{
7272
0
  char* p = url;
7273
  /* parse http://www.example.com/file.htm
7274
   * or http://127.0.0.1   (index.html)
7275
   * or https://[::1@1234]/a/b/c/d */
7276
0
  *ssl = 1;
7277
0
  *port = AUTH_HTTPS_PORT;
7278
7279
  /* parse http:// or https:// */
7280
0
  if(strncmp(p, "http://", 7) == 0) {
7281
0
    p += 7;
7282
0
    *ssl = 0;
7283
0
    *port = AUTH_HTTP_PORT;
7284
0
  } else if(strncmp(p, "https://", 8) == 0) {
7285
0
    p += 8;
7286
0
  } else if(strstr(p, "://") && strchr(p, '/') > strstr(p, "://") &&
7287
0
    strchr(p, ':') >= strstr(p, "://")) {
7288
0
    char* uri = dup_prefix(p, (size_t)(strstr(p, "://")-p));
7289
0
    log_err("protocol %s:// not supported (for url %s)",
7290
0
      uri?uri:"", p);
7291
0
    free(uri);
7292
0
    return 0;
7293
0
  }
7294
7295
  /* parse hostname part */
7296
0
  if(p[0] == '[') {
7297
0
    char* end = strchr(p, ']');
7298
0
    p++; /* skip over [ */
7299
0
    if(end) {
7300
0
      *host = dup_prefix(p, (size_t)(end-p));
7301
0
      if(!*host) return 0;
7302
0
      p = end+1; /* skip over ] */
7303
0
    } else {
7304
0
      *host = dup_all(p);
7305
0
      if(!*host) return 0;
7306
0
      p = end;
7307
0
    }
7308
0
  } else {
7309
0
    char* end = str_find_first_of_chars(p, ':', '/');
7310
0
    if(end) {
7311
0
      *host = dup_prefix(p, (size_t)(end-p));
7312
0
      if(!*host) return 0;
7313
0
    } else {
7314
0
      *host = dup_all(p);
7315
0
      if(!*host) return 0;
7316
0
    }
7317
0
    p = end; /* at next : or / or NULL */
7318
0
  }
7319
7320
  /* parse port number */
7321
0
  if(p && p[0] == ':') {
7322
0
    char* end = NULL;
7323
0
    *port = strtol(p+1, &end, 10);
7324
0
    p = end;
7325
0
  }
7326
7327
  /* parse filename part */
7328
0
  while(p && *p == '/')
7329
0
    p++;
7330
0
  if(!p || p[0] == 0)
7331
0
    *file = strdup("/");
7332
0
  else  *file = strdup(p);
7333
0
  if(!*file) {
7334
0
    log_err("malloc failure");
7335
0
    return 0;
7336
0
  }
7337
0
  return 1;
7338
0
}
7339
7340
int
7341
xfer_set_masters(struct auth_master** list, struct config_auth* c,
7342
  int with_http)
7343
0
{
7344
0
  struct auth_master* m;
7345
0
  struct config_strlist* p;
7346
  /* list points to the first, or next pointer for the new element */
7347
0
  while(*list) {
7348
0
    list = &( (*list)->next );
7349
0
  }
7350
0
  if(with_http)
7351
0
    for(p = c->urls; p; p = p->next) {
7352
0
    m = auth_master_new(&list);
7353
0
    if(!m) return 0;
7354
0
    m->http = 1;
7355
0
    if(!parse_url(p->str, &m->host, &m->file, &m->port, &m->ssl))
7356
0
      return 0;
7357
0
  }
7358
0
  for(p = c->masters; p; p = p->next) {
7359
0
    m = auth_master_new(&list);
7360
0
    if(!m) return 0;
7361
0
    m->ixfr = 1; /* this flag is not configurable */
7362
0
    m->host = strdup(p->str);
7363
0
    if(!m->host) {
7364
0
      log_err("malloc failure");
7365
0
      return 0;
7366
0
    }
7367
0
  }
7368
0
  for(p = c->allow_notify; p; p = p->next) {
7369
0
    m = auth_master_new(&list);
7370
0
    if(!m) return 0;
7371
0
    m->allow_notify = 1;
7372
0
    m->host = strdup(p->str);
7373
0
    if(!m->host) {
7374
0
      log_err("malloc failure");
7375
0
      return 0;
7376
0
    }
7377
0
  }
7378
0
  return 1;
7379
0
}
7380
7381
0
#define SERIAL_BITS 32
7382
int
7383
compare_serial(uint32_t a, uint32_t b)
7384
0
{
7385
0
  const uint32_t cutoff = ((uint32_t) 1 << (SERIAL_BITS - 1));
7386
7387
0
  if (a == b) {
7388
0
    return 0;
7389
0
  } else if ((a < b && b - a < cutoff) || (a > b && a - b > cutoff)) {
7390
0
    return -1;
7391
0
  } else {
7392
0
    return 1;
7393
0
  }
7394
0
}
7395
7396
int zonemd_hashalgo_supported(int hashalgo)
7397
0
{
7398
0
  if(hashalgo == ZONEMD_ALGO_SHA384) return 1;
7399
0
  if(hashalgo == ZONEMD_ALGO_SHA512) return 1;
7400
0
  return 0;
7401
0
}
7402
7403
int zonemd_scheme_supported(int scheme)
7404
0
{
7405
0
  if(scheme == ZONEMD_SCHEME_SIMPLE) return 1;
7406
0
  return 0;
7407
0
}
7408
7409
/** initialize hash for hashing with zonemd hash algo */
7410
static struct secalgo_hash* zonemd_digest_init(int hashalgo, char** reason)
7411
0
{
7412
0
  struct secalgo_hash *h;
7413
0
  if(hashalgo == ZONEMD_ALGO_SHA384) {
7414
    /* sha384 */
7415
0
    h = secalgo_hash_create_sha384();
7416
0
    if(!h)
7417
0
      *reason = "digest sha384 could not be created";
7418
0
    return h;
7419
0
  } else if(hashalgo == ZONEMD_ALGO_SHA512) {
7420
    /* sha512 */
7421
0
    h = secalgo_hash_create_sha512();
7422
0
    if(!h)
7423
0
      *reason = "digest sha512 could not be created";
7424
0
    return h;
7425
0
  }
7426
  /* unknown hash algo */
7427
0
  *reason = "unsupported algorithm";
7428
0
  return NULL;
7429
0
}
7430
7431
/** update the hash for zonemd */
7432
static int zonemd_digest_update(int hashalgo, struct secalgo_hash* h,
7433
  uint8_t* data, size_t len, char** reason)
7434
0
{
7435
0
  if(hashalgo == ZONEMD_ALGO_SHA384) {
7436
0
    if(!secalgo_hash_update(h, data, len)) {
7437
0
      *reason = "digest sha384 failed";
7438
0
      return 0;
7439
0
    }
7440
0
    return 1;
7441
0
  } else if(hashalgo == ZONEMD_ALGO_SHA512) {
7442
0
    if(!secalgo_hash_update(h, data, len)) {
7443
0
      *reason = "digest sha512 failed";
7444
0
      return 0;
7445
0
    }
7446
0
    return 1;
7447
0
  }
7448
  /* unknown hash algo */
7449
0
  *reason = "unsupported algorithm";
7450
0
  return 0;
7451
0
}
7452
7453
/** finish the hash for zonemd */
7454
static int zonemd_digest_finish(int hashalgo, struct secalgo_hash* h,
7455
  uint8_t* result, size_t hashlen, size_t* resultlen, char** reason)
7456
0
{
7457
0
  if(hashalgo == ZONEMD_ALGO_SHA384) {
7458
0
    if(hashlen < 384/8) {
7459
0
      *reason = "digest buffer too small for sha384";
7460
0
      return 0;
7461
0
    }
7462
0
    if(!secalgo_hash_final(h, result, hashlen, resultlen)) {
7463
0
      *reason = "digest sha384 finish failed";
7464
0
      return 0;
7465
0
    }
7466
0
    return 1;
7467
0
  } else if(hashalgo == ZONEMD_ALGO_SHA512) {
7468
0
    if(hashlen < 512/8) {
7469
0
      *reason = "digest buffer too small for sha512";
7470
0
      return 0;
7471
0
    }
7472
0
    if(!secalgo_hash_final(h, result, hashlen, resultlen)) {
7473
0
      *reason = "digest sha512 finish failed";
7474
0
      return 0;
7475
0
    }
7476
0
    return 1;
7477
0
  }
7478
  /* unknown algo */
7479
0
  *reason = "unsupported algorithm";
7480
0
  return 0;
7481
0
}
7482
7483
/** add rrsets from node to the list */
7484
static size_t authdata_rrsets_to_list(struct auth_rrset** array,
7485
  size_t arraysize, struct auth_rrset* first)
7486
0
{
7487
0
  struct auth_rrset* rrset = first;
7488
0
  size_t num = 0;
7489
0
  while(rrset) {
7490
0
    if(num >= arraysize)
7491
0
      return num;
7492
0
    array[num] = rrset;
7493
0
    num++;
7494
0
    rrset = rrset->next;
7495
0
  }
7496
0
  return num;
7497
0
}
7498
7499
/** compare rr list entries */
7500
static int rrlist_compare(const void* arg1, const void* arg2)
7501
0
{
7502
0
  struct auth_rrset* r1 = *(struct auth_rrset**)arg1;
7503
0
  struct auth_rrset* r2 = *(struct auth_rrset**)arg2;
7504
0
  uint16_t t1, t2;
7505
0
  if(r1 == NULL) t1 = LDNS_RR_TYPE_RRSIG;
7506
0
  else t1 = r1->type;
7507
0
  if(r2 == NULL) t2 = LDNS_RR_TYPE_RRSIG;
7508
0
  else t2 = r2->type;
7509
0
  if(t1 < t2)
7510
0
    return -1;
7511
0
  if(t1 > t2)
7512
0
    return 1;
7513
0
  return 0;
7514
0
}
7515
7516
/** add type RRSIG to rr list if not one there already,
7517
 * this is to perform RRSIG collate processing at that point. */
7518
static void addrrsigtype_if_needed(struct auth_rrset** array,
7519
  size_t arraysize, size_t* rrnum, struct auth_data* node)
7520
0
{
7521
0
  if(az_domain_rrset(node, LDNS_RR_TYPE_RRSIG))
7522
0
    return; /* already one there */
7523
0
  if((*rrnum) >= arraysize)
7524
0
    return; /* array too small? */
7525
0
  array[*rrnum] = NULL; /* nothing there, but need entry in list */
7526
0
  (*rrnum)++;
7527
0
}
7528
7529
/** collate the RRs in an RRset using the simple scheme */
7530
static int zonemd_simple_rrset(struct auth_zone* z, int hashalgo,
7531
  struct secalgo_hash* h, struct auth_data* node,
7532
  struct auth_rrset* rrset, struct regional* region,
7533
  struct sldns_buffer* buf, char** reason)
7534
0
{
7535
  /* canonicalize */
7536
0
  struct ub_packed_rrset_key key;
7537
0
  memset(&key, 0, sizeof(key));
7538
0
  key.entry.key = &key;
7539
0
  key.entry.data = rrset->data;
7540
0
  key.rk.dname = node->name;
7541
0
  key.rk.dname_len = node->namelen;
7542
0
  key.rk.type = htons(rrset->type);
7543
0
  key.rk.rrset_class = htons(z->dclass);
7544
0
  if(!rrset_canonicalize_to_buffer(region, buf, &key)) {
7545
0
    *reason = "out of memory";
7546
0
    return 0;
7547
0
  }
7548
0
  regional_free_all(region);
7549
7550
  /* hash */
7551
0
  if(!zonemd_digest_update(hashalgo, h, sldns_buffer_begin(buf),
7552
0
    sldns_buffer_limit(buf), reason)) {
7553
0
    return 0;
7554
0
  }
7555
0
  return 1;
7556
0
}
7557
7558
/** count number of RRSIGs in a domain name rrset list */
7559
static size_t zonemd_simple_count_rrsig(struct auth_rrset* rrset,
7560
  struct auth_rrset** rrlist, size_t rrnum,
7561
  struct auth_zone* z, struct auth_data* node)
7562
0
{
7563
0
  size_t i, count = 0;
7564
0
  if(rrset) {
7565
0
    size_t j;
7566
0
    for(j = 0; j<rrset->data->count; j++) {
7567
0
      if(rrsig_rdata_get_type_covered(rrset->data->
7568
0
        rr_data[j], rrset->data->rr_len[j]) ==
7569
0
        LDNS_RR_TYPE_ZONEMD &&
7570
0
        query_dname_compare(z->name, node->name)==0) {
7571
        /* omit RRSIGs over type ZONEMD at apex */
7572
0
        continue;
7573
0
      }
7574
0
      count++;
7575
0
    }
7576
0
  }
7577
0
  for(i=0; i<rrnum; i++) {
7578
0
    if(rrlist[i] && rrlist[i]->type == LDNS_RR_TYPE_ZONEMD &&
7579
0
      query_dname_compare(z->name, node->name)==0) {
7580
      /* omit RRSIGs over type ZONEMD at apex */
7581
0
      continue;
7582
0
    }
7583
0
    count += (rrlist[i]?rrlist[i]->data->rrsig_count:0);
7584
0
  }
7585
0
  return count;
7586
0
}
7587
7588
/** allocate sparse rrset data for the number of entries in tepm region */
7589
static int zonemd_simple_rrsig_allocs(struct regional* region,
7590
  struct packed_rrset_data* data, size_t count)
7591
0
{
7592
0
  data->rr_len = regional_alloc(region, sizeof(*data->rr_len) * count);
7593
0
  if(!data->rr_len) {
7594
0
    return 0;
7595
0
  }
7596
0
  data->rr_ttl = regional_alloc(region, sizeof(*data->rr_ttl) * count);
7597
0
  if(!data->rr_ttl) {
7598
0
    return 0;
7599
0
  }
7600
0
  data->rr_data = regional_alloc(region, sizeof(*data->rr_data) * count);
7601
0
  if(!data->rr_data) {
7602
0
    return 0;
7603
0
  }
7604
0
  return 1;
7605
0
}
7606
7607
/** add the RRSIGs from the rrs in the domain into the data */
7608
static void add_rrlist_rrsigs_into_data(struct packed_rrset_data* data,
7609
  size_t* done, struct auth_rrset** rrlist, size_t rrnum,
7610
  struct auth_zone* z, struct auth_data* node)
7611
0
{
7612
0
  size_t i;
7613
0
  for(i=0; i<rrnum; i++) {
7614
0
    size_t j;
7615
0
    if(!rrlist[i])
7616
0
      continue;
7617
0
    if(rrlist[i]->type == LDNS_RR_TYPE_ZONEMD &&
7618
0
      query_dname_compare(z->name, node->name)==0) {
7619
      /* omit RRSIGs over type ZONEMD at apex */
7620
0
      continue;
7621
0
    }
7622
0
    for(j = 0; j<rrlist[i]->data->rrsig_count; j++) {
7623
0
      data->rr_len[*done] = rrlist[i]->data->rr_len[rrlist[i]->data->count + j];
7624
0
      data->rr_ttl[*done] = rrlist[i]->data->rr_ttl[rrlist[i]->data->count + j];
7625
      /* reference the rdata in the rrset, no need to
7626
       * copy it, it is no longer needed at the end of
7627
       * the routine */
7628
0
      data->rr_data[*done] = rrlist[i]->data->rr_data[rrlist[i]->data->count + j];
7629
0
      (*done)++;
7630
0
    }
7631
0
  }
7632
0
}
7633
7634
static void add_rrset_into_data(struct packed_rrset_data* data,
7635
  size_t* done, struct auth_rrset* rrset,
7636
  struct auth_zone* z, struct auth_data* node)
7637
0
{
7638
0
  if(rrset) {
7639
0
    size_t j;
7640
0
    for(j = 0; j<rrset->data->count; j++) {
7641
0
      if(rrsig_rdata_get_type_covered(rrset->data->
7642
0
        rr_data[j], rrset->data->rr_len[j]) ==
7643
0
        LDNS_RR_TYPE_ZONEMD &&
7644
0
        query_dname_compare(z->name, node->name)==0) {
7645
        /* omit RRSIGs over type ZONEMD at apex */
7646
0
        continue;
7647
0
      }
7648
0
      data->rr_len[*done] = rrset->data->rr_len[j];
7649
0
      data->rr_ttl[*done] = rrset->data->rr_ttl[j];
7650
      /* reference the rdata in the rrset, no need to
7651
       * copy it, it is no longer need at the end of
7652
       * the routine */
7653
0
      data->rr_data[*done] = rrset->data->rr_data[j];
7654
0
      (*done)++;
7655
0
    }
7656
0
  }
7657
0
}
7658
7659
/** collate the RRSIGs using the simple scheme */
7660
static int zonemd_simple_rrsig(struct auth_zone* z, int hashalgo,
7661
  struct secalgo_hash* h, struct auth_data* node,
7662
  struct auth_rrset* rrset, struct auth_rrset** rrlist, size_t rrnum,
7663
  struct regional* region, struct sldns_buffer* buf, char** reason)
7664
0
{
7665
  /* the rrset pointer can be NULL, this means it is type RRSIG and
7666
   * there is no ordinary type RRSIG there.  The RRSIGs are stored
7667
   * with the RRsets in their data.
7668
   *
7669
   * The RRset pointer can be nonNULL. This happens if there is
7670
   * no RR that is covered by the RRSIG for the domain.  Then this
7671
   * RRSIG RR is stored in an rrset of type RRSIG. The other RRSIGs
7672
   * are stored in the rrset entries for the RRs in the rr list for
7673
   * the domain node.  We need to collate the rrset's data, if any, and
7674
   * the rrlist's rrsigs */
7675
  /* if this is the apex, omit RRSIGs that cover type ZONEMD */
7676
  /* build rrsig rrset */
7677
0
  size_t done = 0;
7678
0
  struct ub_packed_rrset_key key;
7679
0
  struct packed_rrset_data data;
7680
0
  memset(&key, 0, sizeof(key));
7681
0
  memset(&data, 0, sizeof(data));
7682
0
  key.entry.key = &key;
7683
0
  key.entry.data = &data;
7684
0
  key.rk.dname = node->name;
7685
0
  key.rk.dname_len = node->namelen;
7686
0
  key.rk.type = htons(LDNS_RR_TYPE_RRSIG);
7687
0
  key.rk.rrset_class = htons(z->dclass);
7688
0
  data.count = zonemd_simple_count_rrsig(rrset, rrlist, rrnum, z, node);
7689
0
  if(!zonemd_simple_rrsig_allocs(region, &data, data.count)) {
7690
0
    *reason = "out of memory";
7691
0
    regional_free_all(region);
7692
0
    return 0;
7693
0
  }
7694
  /* all the RRSIGs stored in the other rrsets for this domain node */
7695
0
  add_rrlist_rrsigs_into_data(&data, &done, rrlist, rrnum, z, node);
7696
  /* plus the RRSIGs stored in an rrset of type RRSIG for this node */
7697
0
  add_rrset_into_data(&data, &done, rrset, z, node);
7698
7699
  /* canonicalize */
7700
0
  if(!rrset_canonicalize_to_buffer(region, buf, &key)) {
7701
0
    *reason = "out of memory";
7702
0
    regional_free_all(region);
7703
0
    return 0;
7704
0
  }
7705
0
  regional_free_all(region);
7706
7707
  /* hash */
7708
0
  if(!zonemd_digest_update(hashalgo, h, sldns_buffer_begin(buf),
7709
0
    sldns_buffer_limit(buf), reason)) {
7710
0
    return 0;
7711
0
  }
7712
0
  return 1;
7713
0
}
7714
7715
/** collate a domain's rrsets using the simple scheme */
7716
static int zonemd_simple_domain(struct auth_zone* z, int hashalgo,
7717
  struct secalgo_hash* h, struct auth_data* node,
7718
  struct regional* region, struct sldns_buffer* buf, char** reason)
7719
0
{
7720
0
  const size_t rrlistsize = 65536;
7721
0
  struct auth_rrset* rrlist[rrlistsize];
7722
0
  size_t i, rrnum = 0;
7723
  /* see if the domain is out of scope, the zone origin,
7724
   * that would be omitted */
7725
0
  if(!dname_subdomain_c(node->name, z->name))
7726
0
    return 1; /* continue */
7727
  /* loop over the rrsets in ascending order. */
7728
0
  rrnum = authdata_rrsets_to_list(rrlist, rrlistsize, node->rrsets);
7729
0
  addrrsigtype_if_needed(rrlist, rrlistsize, &rrnum, node);
7730
0
  qsort(rrlist, rrnum, sizeof(*rrlist), rrlist_compare);
7731
0
  for(i=0; i<rrnum; i++) {
7732
0
    if(rrlist[i] && rrlist[i]->type == LDNS_RR_TYPE_ZONEMD &&
7733
0
      query_dname_compare(z->name, node->name) == 0) {
7734
      /* omit type ZONEMD at apex */
7735
0
      continue;
7736
0
    }
7737
0
    if(rrlist[i] == NULL || rrlist[i]->type ==
7738
0
      LDNS_RR_TYPE_RRSIG) {
7739
0
      if(!zonemd_simple_rrsig(z, hashalgo, h, node,
7740
0
        rrlist[i], rrlist, rrnum, region, buf, reason))
7741
0
        return 0;
7742
0
    } else if(!zonemd_simple_rrset(z, hashalgo, h, node,
7743
0
      rrlist[i], region, buf, reason)) {
7744
0
      return 0;
7745
0
    }
7746
0
  }
7747
0
  return 1;
7748
0
}
7749
7750
/** collate the zone using the simple scheme */
7751
static int zonemd_simple_collate(struct auth_zone* z, int hashalgo,
7752
  struct secalgo_hash* h, struct regional* region,
7753
  struct sldns_buffer* buf, char** reason)
7754
0
{
7755
  /* our tree is sorted in canonical order, so we can just loop over
7756
   * the tree */
7757
0
  struct auth_data* n;
7758
0
  RBTREE_FOR(n, struct auth_data*, &z->data) {
7759
0
    if(!zonemd_simple_domain(z, hashalgo, h, n, region, buf,
7760
0
      reason))
7761
0
      return 0;
7762
0
  }
7763
0
  return 1;
7764
0
}
7765
7766
int auth_zone_generate_zonemd_hash(struct auth_zone* z, int scheme,
7767
  int hashalgo, uint8_t* hash, size_t hashlen, size_t* resultlen,
7768
  struct regional* region, struct sldns_buffer* buf, char** reason)
7769
0
{
7770
0
  struct secalgo_hash* h = zonemd_digest_init(hashalgo, reason);
7771
0
  if(!h) {
7772
0
    if(!*reason)
7773
0
      *reason = "digest init fail";
7774
0
    return 0;
7775
0
  }
7776
0
  if(scheme == ZONEMD_SCHEME_SIMPLE) {
7777
0
    if(!zonemd_simple_collate(z, hashalgo, h, region, buf, reason)) {
7778
0
      if(!*reason) *reason = "scheme simple collate fail";
7779
0
      secalgo_hash_delete(h);
7780
0
      return 0;
7781
0
    }
7782
0
  }
7783
0
  if(!zonemd_digest_finish(hashalgo, h, hash, hashlen, resultlen,
7784
0
    reason)) {
7785
0
    secalgo_hash_delete(h);
7786
0
    *reason = "digest finish fail";
7787
0
    return 0;
7788
0
  }
7789
0
  secalgo_hash_delete(h);
7790
0
  return 1;
7791
0
}
7792
7793
int auth_zone_generate_zonemd_check(struct auth_zone* z, int scheme,
7794
  int hashalgo, uint8_t* hash, size_t hashlen, struct regional* region,
7795
  struct sldns_buffer* buf, char** reason)
7796
0
{
7797
0
  uint8_t gen[512];
7798
0
  size_t genlen = 0;
7799
0
  *reason = NULL;
7800
0
  if(!zonemd_hashalgo_supported(hashalgo)) {
7801
    /* allow it */
7802
0
    *reason = "unsupported algorithm";
7803
0
    return 1;
7804
0
  }
7805
0
  if(!zonemd_scheme_supported(scheme)) {
7806
    /* allow it */
7807
0
    *reason = "unsupported scheme";
7808
0
    return 1;
7809
0
  }
7810
0
  if(hashlen < 12) {
7811
    /* the ZONEMD draft requires digests to fail if too small */
7812
0
    *reason = "digest length too small, less than 12";
7813
0
    return 0;
7814
0
  }
7815
  /* generate digest */
7816
0
  if(!auth_zone_generate_zonemd_hash(z, scheme, hashalgo, gen,
7817
0
    sizeof(gen), &genlen, region, buf, reason)) {
7818
    /* reason filled in by zonemd hash routine */
7819
0
    return 0;
7820
0
  }
7821
  /* check digest length */
7822
0
  if(hashlen != genlen) {
7823
0
    *reason = "incorrect digest length";
7824
0
    if(verbosity >= VERB_ALGO) {
7825
0
      verbose(VERB_ALGO, "zonemd scheme=%d hashalgo=%d",
7826
0
        scheme, hashalgo);
7827
0
      log_hex("ZONEMD should be  ", gen, genlen);
7828
0
      log_hex("ZONEMD to check is", hash, hashlen);
7829
0
    }
7830
0
    return 0;
7831
0
  }
7832
  /* check digest */
7833
0
  if(memcmp(hash, gen, genlen) != 0) {
7834
0
    *reason = "incorrect digest";
7835
0
    if(verbosity >= VERB_ALGO) {
7836
0
      verbose(VERB_ALGO, "zonemd scheme=%d hashalgo=%d",
7837
0
        scheme, hashalgo);
7838
0
      log_hex("ZONEMD should be  ", gen, genlen);
7839
0
      log_hex("ZONEMD to check is", hash, hashlen);
7840
0
    }
7841
0
    return 0;
7842
0
  }
7843
0
  return 1;
7844
0
}
7845
7846
/** log auth zone message with zone name in front. */
7847
static void auth_zone_log(uint8_t* name, enum verbosity_value level,
7848
  const char* format, ...) ATTR_FORMAT(printf, 3, 4);
7849
static void auth_zone_log(uint8_t* name, enum verbosity_value level,
7850
  const char* format, ...)
7851
0
{
7852
0
  va_list args;
7853
0
  va_start(args, format);
7854
0
  if(verbosity >= level) {
7855
0
    char str[LDNS_MAX_DOMAINLEN];
7856
0
    char msg[MAXSYSLOGMSGLEN];
7857
0
    dname_str(name, str);
7858
0
    vsnprintf(msg, sizeof(msg), format, args);
7859
0
    verbose(level, "auth zone %s %s", str, msg);
7860
0
  }
7861
0
  va_end(args);
7862
0
}
7863
7864
/** ZONEMD, dnssec verify the rrset with the dnskey */
7865
static int zonemd_dnssec_verify_rrset(struct auth_zone* z,
7866
  struct module_env* env, struct module_stack* mods,
7867
  struct ub_packed_rrset_key* dnskey, struct auth_data* node,
7868
  struct auth_rrset* rrset, char** why_bogus, uint8_t* sigalg,
7869
  char* reasonbuf, size_t reasonlen)
7870
0
{
7871
0
  struct ub_packed_rrset_key pk;
7872
0
  enum sec_status sec;
7873
0
  struct val_env* ve;
7874
0
  int m;
7875
0
  int verified = 0;
7876
0
  m = modstack_find(mods, "validator");
7877
0
  if(m == -1) {
7878
0
    auth_zone_log(z->name, VERB_ALGO, "zonemd dnssec verify: have "
7879
0
      "DNSKEY chain of trust, but no validator module");
7880
0
    return 0;
7881
0
  }
7882
0
  ve = (struct val_env*)env->modinfo[m];
7883
7884
0
  memset(&pk, 0, sizeof(pk));
7885
0
  pk.entry.key = &pk;
7886
0
  pk.entry.data = rrset->data;
7887
0
  pk.rk.dname = node->name;
7888
0
  pk.rk.dname_len = node->namelen;
7889
0
  pk.rk.type = htons(rrset->type);
7890
0
  pk.rk.rrset_class = htons(z->dclass);
7891
0
  if(verbosity >= VERB_ALGO) {
7892
0
    char typestr[32];
7893
0
    typestr[0]=0;
7894
0
    sldns_wire2str_type_buf(rrset->type, typestr, sizeof(typestr));
7895
0
    auth_zone_log(z->name, VERB_ALGO,
7896
0
      "zonemd: verify %s RRset with DNSKEY", typestr);
7897
0
  }
7898
0
  sec = dnskeyset_verify_rrset(env, ve, &pk, dnskey, sigalg, why_bogus, NULL,
7899
0
    LDNS_SECTION_ANSWER, NULL, &verified, reasonbuf, reasonlen);
7900
0
  if(sec == sec_status_secure) {
7901
0
    return 1;
7902
0
  }
7903
0
  if(why_bogus)
7904
0
    auth_zone_log(z->name, VERB_ALGO, "DNSSEC verify was bogus: %s", *why_bogus);
7905
0
  return 0;
7906
0
}
7907
7908
/** check for nsec3, the RR with params equal, if bitmap has the type */
7909
static int nsec3_of_param_has_type(struct auth_rrset* nsec3, int algo,
7910
  size_t iter, uint8_t* salt, size_t saltlen, uint16_t rrtype)
7911
0
{
7912
0
  int i, count = (int)nsec3->data->count;
7913
0
  struct ub_packed_rrset_key pk;
7914
0
  memset(&pk, 0, sizeof(pk));
7915
0
  pk.entry.data = nsec3->data;
7916
0
  for(i=0; i<count; i++) {
7917
0
    int rralgo;
7918
0
    size_t rriter, rrsaltlen;
7919
0
    uint8_t* rrsalt;
7920
0
    if(!nsec3_get_params(&pk, i, &rralgo, &rriter, &rrsalt,
7921
0
      &rrsaltlen))
7922
0
      continue; /* no parameters, malformed */
7923
0
    if(rralgo != algo || rriter != iter || rrsaltlen != saltlen)
7924
0
      continue; /* different parameters */
7925
0
    if(saltlen != 0) {
7926
0
      if(rrsalt == NULL || salt == NULL)
7927
0
        continue;
7928
0
      if(memcmp(rrsalt, salt, saltlen) != 0)
7929
0
        continue; /* different salt parameters */
7930
0
    }
7931
0
    if(nsec3_has_type(&pk, i, rrtype))
7932
0
      return 1;
7933
0
  }
7934
0
  return 0;
7935
0
}
7936
7937
/** Verify the absence of ZONEMD with DNSSEC by checking NSEC, NSEC3 type flag.
7938
 * return false on failure, reason contains description of failure. */
7939
static int zonemd_check_dnssec_absence(struct auth_zone* z,
7940
  struct module_env* env, struct module_stack* mods,
7941
  struct ub_packed_rrset_key* dnskey, struct auth_data* apex,
7942
  char** reason, char** why_bogus, uint8_t* sigalg, char* reasonbuf,
7943
  size_t reasonlen)
7944
0
{
7945
0
  struct auth_rrset* nsec = NULL;
7946
0
  if(!apex) {
7947
0
    *reason = "zone has no apex domain but ZONEMD missing";
7948
0
    return 0;
7949
0
  }
7950
0
  nsec = az_domain_rrset(apex, LDNS_RR_TYPE_NSEC);
7951
0
  if(nsec) {
7952
0
    struct ub_packed_rrset_key pk;
7953
    /* dnssec verify the NSEC */
7954
0
    if(!zonemd_dnssec_verify_rrset(z, env, mods, dnskey, apex,
7955
0
      nsec, why_bogus, sigalg, reasonbuf, reasonlen)) {
7956
0
      *reason = "DNSSEC verify failed for NSEC RRset";
7957
0
      return 0;
7958
0
    }
7959
    /* check type bitmap */
7960
0
    memset(&pk, 0, sizeof(pk));
7961
0
    pk.entry.data = nsec->data;
7962
0
    if(nsec_has_type(&pk, LDNS_RR_TYPE_ZONEMD)) {
7963
0
      *reason = "DNSSEC NSEC bitmap says type ZONEMD exists";
7964
0
      return 0;
7965
0
    }
7966
0
    auth_zone_log(z->name, VERB_ALGO, "zonemd DNSSEC NSEC verification of absence of ZONEMD secure");
7967
0
  } else {
7968
    /* NSEC3 perhaps ? */
7969
0
    int algo;
7970
0
    size_t iter, saltlen;
7971
0
    uint8_t* salt;
7972
0
    struct auth_rrset* nsec3param = az_domain_rrset(apex,
7973
0
      LDNS_RR_TYPE_NSEC3PARAM);
7974
0
    struct auth_data* match;
7975
0
    struct auth_rrset* nsec3;
7976
0
    if(!nsec3param) {
7977
0
      *reason = "zone has no NSEC information but ZONEMD missing";
7978
0
      return 0;
7979
0
    }
7980
0
    if(!az_nsec3_param(z, &algo, &iter, &salt, &saltlen)) {
7981
0
      *reason = "zone has no NSEC information but ZONEMD missing";
7982
0
      return 0;
7983
0
    }
7984
    /* find the NSEC3 record */
7985
0
    match = az_nsec3_find_exact(z, z->name, z->namelen, algo,
7986
0
      iter, salt, saltlen);
7987
0
    if(!match) {
7988
0
      *reason = "zone has no NSEC3 domain for the apex but ZONEMD missing";
7989
0
      return 0;
7990
0
    }
7991
0
    nsec3 = az_domain_rrset(match, LDNS_RR_TYPE_NSEC3);
7992
0
    if(!nsec3) {
7993
0
      *reason = "zone has no NSEC3 RRset for the apex but ZONEMD missing";
7994
0
      return 0;
7995
0
    }
7996
    /* dnssec verify the NSEC3 */
7997
0
    if(!zonemd_dnssec_verify_rrset(z, env, mods, dnskey, match,
7998
0
      nsec3, why_bogus, sigalg, reasonbuf, reasonlen)) {
7999
0
      *reason = "DNSSEC verify failed for NSEC3 RRset";
8000
0
      return 0;
8001
0
    }
8002
    /* check type bitmap */
8003
0
    if(nsec3_of_param_has_type(nsec3, algo, iter, salt, saltlen,
8004
0
      LDNS_RR_TYPE_ZONEMD)) {
8005
0
      *reason = "DNSSEC NSEC3 bitmap says type ZONEMD exists";
8006
0
      return 0;
8007
0
    }
8008
0
    auth_zone_log(z->name, VERB_ALGO, "zonemd DNSSEC NSEC3 verification of absence of ZONEMD secure");
8009
0
  }
8010
8011
0
  return 1;
8012
0
}
8013
8014
/** Verify the SOA and ZONEMD DNSSEC signatures.
8015
 * return false on failure, reason contains description of failure. */
8016
static int zonemd_check_dnssec_soazonemd(struct auth_zone* z,
8017
  struct module_env* env, struct module_stack* mods,
8018
  struct ub_packed_rrset_key* dnskey, struct auth_data* apex,
8019
  struct auth_rrset* zonemd_rrset, char** reason, char** why_bogus,
8020
  uint8_t* sigalg, char* reasonbuf, size_t reasonlen)
8021
0
{
8022
0
  struct auth_rrset* soa;
8023
0
  if(!apex) {
8024
0
    *reason = "zone has no apex domain";
8025
0
    return 0;
8026
0
  }
8027
0
  soa = az_domain_rrset(apex, LDNS_RR_TYPE_SOA);
8028
0
  if(!soa) {
8029
0
    *reason = "zone has no SOA RRset";
8030
0
    return 0;
8031
0
  }
8032
0
  if(!zonemd_dnssec_verify_rrset(z, env, mods, dnskey, apex, soa,
8033
0
    why_bogus, sigalg, reasonbuf, reasonlen)) {
8034
0
    *reason = "DNSSEC verify failed for SOA RRset";
8035
0
    return 0;
8036
0
  }
8037
0
  if(!zonemd_dnssec_verify_rrset(z, env, mods, dnskey, apex,
8038
0
    zonemd_rrset, why_bogus, sigalg, reasonbuf, reasonlen)) {
8039
0
    *reason = "DNSSEC verify failed for ZONEMD RRset";
8040
0
    return 0;
8041
0
  }
8042
0
  auth_zone_log(z->name, VERB_ALGO, "zonemd DNSSEC verification of SOA and ZONEMD RRsets secure");
8043
0
  return 1;
8044
0
}
8045
8046
/**
8047
 * Fail the ZONEMD verification.
8048
 * @param z: auth zone that fails.
8049
 * @param env: environment with config, to ignore failure or not.
8050
 * @param reason: failure string description.
8051
 * @param why_bogus: failure string for DNSSEC verification failure.
8052
 * @param result: strdup result in here if not NULL.
8053
 */
8054
static void auth_zone_zonemd_fail(struct auth_zone* z, struct module_env* env,
8055
  char* reason, char* why_bogus, char** result)
8056
0
{
8057
0
  char zstr[LDNS_MAX_DOMAINLEN];
8058
  /* if fail: log reason, and depending on config also take action
8059
   * and drop the zone, eg. it is gone from memory, set zone_expired */
8060
0
  dname_str(z->name, zstr);
8061
0
  if(!reason) reason = "verification failed";
8062
0
  if(result) {
8063
0
    if(why_bogus) {
8064
0
      char res[1024];
8065
0
      snprintf(res, sizeof(res), "%s: %s", reason,
8066
0
        why_bogus);
8067
0
      *result = strdup(res);
8068
0
    } else {
8069
0
      *result = strdup(reason);
8070
0
    }
8071
0
    if(!*result) log_err("out of memory");
8072
0
  } else {
8073
0
    log_warn("auth zone %s: ZONEMD verification failed: %s", zstr, reason);
8074
0
  }
8075
8076
0
  if(env->cfg->zonemd_permissive_mode) {
8077
0
    verbose(VERB_ALGO, "zonemd-permissive-mode enabled, "
8078
0
      "not blocking zone %s", zstr);
8079
0
    return;
8080
0
  }
8081
8082
  /* expired means the zone gives servfail and is not used by
8083
   * lookup if fallback_enabled*/
8084
0
  z->zone_expired = 1;
8085
0
}
8086
8087
/**
8088
 * Verify the zonemd with DNSSEC and hash check, with given key.
8089
 * @param z: auth zone.
8090
 * @param env: environment with config and temp buffers.
8091
 * @param mods: module stack with validator env for verification.
8092
 * @param dnskey: dnskey that we can use, or NULL.  If nonnull, the key
8093
 *  has been verified and is the start of the chain of trust.
8094
 * @param is_insecure: if true, the dnskey is not used, the zone is insecure.
8095
 *  And dnssec is not used.  It is DNSSEC secure insecure or not under
8096
 *  a trust anchor.
8097
 * @param sigalg: if nonNULL provide algorithm downgrade protection.
8098
 *  Otherwise one algorithm is enough. Must have space of ALGO_NEEDS_MAX+1.
8099
 * @param result: if not NULL result reason copied here.
8100
 */
8101
static void
8102
auth_zone_verify_zonemd_with_key(struct auth_zone* z, struct module_env* env,
8103
  struct module_stack* mods, struct ub_packed_rrset_key* dnskey,
8104
  int is_insecure, char** result, uint8_t* sigalg)
8105
0
{
8106
0
  char reasonbuf[256];
8107
0
  char* reason = NULL, *why_bogus = NULL;
8108
0
  struct auth_data* apex = NULL;
8109
0
  struct auth_rrset* zonemd_rrset = NULL;
8110
0
  int zonemd_absent = 0, zonemd_absence_dnssecok = 0;
8111
8112
  /* see if ZONEMD is present or absent. */
8113
0
  apex = az_find_name(z, z->name, z->namelen);
8114
0
  if(!apex) {
8115
0
    zonemd_absent = 1;
8116
0
  } else {
8117
0
    zonemd_rrset = az_domain_rrset(apex, LDNS_RR_TYPE_ZONEMD);
8118
0
    if(!zonemd_rrset || zonemd_rrset->data->count==0) {
8119
0
      zonemd_absent = 1;
8120
0
      zonemd_rrset = NULL;
8121
0
    }
8122
0
  }
8123
8124
  /* if no DNSSEC, done. */
8125
  /* if no ZONEMD, and DNSSEC, use DNSKEY to verify NSEC or NSEC3 for
8126
   * zone apex.  Check ZONEMD bit is turned off or else fail */
8127
  /* if ZONEMD, and DNSSEC, check DNSSEC signature on SOA and ZONEMD,
8128
   * or else fail */
8129
0
  if(!dnskey && !is_insecure) {
8130
0
    auth_zone_zonemd_fail(z, env, "DNSKEY missing", NULL, result);
8131
0
    return;
8132
0
  } else if(!zonemd_rrset && dnskey && !is_insecure) {
8133
    /* fetch, DNSSEC verify, and check NSEC/NSEC3 */
8134
0
    if(!zonemd_check_dnssec_absence(z, env, mods, dnskey, apex,
8135
0
      &reason, &why_bogus, sigalg, reasonbuf,
8136
0
      sizeof(reasonbuf))) {
8137
0
      auth_zone_zonemd_fail(z, env, reason, why_bogus, result);
8138
0
      return;
8139
0
    }
8140
0
    zonemd_absence_dnssecok = 1;
8141
0
  } else if(zonemd_rrset && dnskey && !is_insecure) {
8142
    /* check DNSSEC verify of SOA and ZONEMD */
8143
0
    if(!zonemd_check_dnssec_soazonemd(z, env, mods, dnskey, apex,
8144
0
      zonemd_rrset, &reason, &why_bogus, sigalg, reasonbuf,
8145
0
      sizeof(reasonbuf))) {
8146
0
      auth_zone_zonemd_fail(z, env, reason, why_bogus, result);
8147
0
      return;
8148
0
    }
8149
0
  }
8150
8151
0
  if(zonemd_absent && z->zonemd_reject_absence) {
8152
0
    auth_zone_zonemd_fail(z, env, "ZONEMD absent and that is not allowed by config", NULL, result);
8153
0
    return;
8154
0
  }
8155
0
  if(zonemd_absent && zonemd_absence_dnssecok) {
8156
0
    auth_zone_log(z->name, VERB_ALGO, "DNSSEC verified nonexistence of ZONEMD");
8157
0
    if(result) {
8158
0
      *result = strdup("DNSSEC verified nonexistence of ZONEMD");
8159
0
      if(!*result) log_err("out of memory");
8160
0
    }
8161
0
    return;
8162
0
  }
8163
0
  if(zonemd_absent) {
8164
0
    auth_zone_log(z->name, VERB_ALGO, "no ZONEMD present");
8165
0
    if(result) {
8166
0
      *result = strdup("no ZONEMD present");
8167
0
      if(!*result) log_err("out of memory");
8168
0
    }
8169
0
    return;
8170
0
  }
8171
8172
  /* check ZONEMD checksum and report or else fail. */
8173
0
  if(!auth_zone_zonemd_check_hash(z, env, &reason)) {
8174
0
    auth_zone_zonemd_fail(z, env, reason, NULL, result);
8175
0
    return;
8176
0
  }
8177
8178
  /* success! log the success */
8179
0
  if(reason)
8180
0
    auth_zone_log(z->name, VERB_ALGO, "ZONEMD %s", reason);
8181
0
  else  auth_zone_log(z->name, VERB_ALGO, "ZONEMD verification successful");
8182
0
  if(result) {
8183
0
    if(reason)
8184
0
      *result = strdup(reason);
8185
0
    else  *result = strdup("ZONEMD verification successful");
8186
0
    if(!*result) log_err("out of memory");
8187
0
  }
8188
0
}
8189
8190
/**
8191
 * verify the zone DNSKEY rrset from the trust anchor
8192
 * This is possible because the anchor is for the zone itself, and can
8193
 * thus apply straight to the zone DNSKEY set.
8194
 * @param z: the auth zone.
8195
 * @param env: environment with time and temp buffers.
8196
 * @param mods: module stack for validator environment for dnssec validation.
8197
 * @param anchor: trust anchor to use
8198
 * @param is_insecure: returned, true if the zone is securely insecure.
8199
 * @param why_bogus: if the routine fails, returns the failure reason.
8200
 * @param keystorage: where to store the ub_packed_rrset_key that is created
8201
 *  on success. A pointer to it is returned on success.
8202
 * @param reasonbuf: buffer to use for fail reason string print.
8203
 * @param reasonlen: length of reasonbuf.
8204
 * @return the dnskey RRset, reference to zone data and keystorage, or
8205
 *  NULL on failure.
8206
 */
8207
static struct ub_packed_rrset_key*
8208
zonemd_get_dnskey_from_anchor(struct auth_zone* z, struct module_env* env,
8209
  struct module_stack* mods, struct trust_anchor* anchor,
8210
  int* is_insecure, char** why_bogus,
8211
  struct ub_packed_rrset_key* keystorage, char* reasonbuf,
8212
  size_t reasonlen)
8213
0
{
8214
0
  struct auth_data* apex;
8215
0
  struct auth_rrset* dnskey_rrset;
8216
0
  enum sec_status sec;
8217
0
  struct val_env* ve;
8218
0
  int m;
8219
8220
0
  apex = az_find_name(z, z->name, z->namelen);
8221
0
  if(!apex) {
8222
0
    *why_bogus = "have trust anchor, but zone has no apex domain for DNSKEY";
8223
0
    return 0;
8224
0
  }
8225
0
  dnskey_rrset = az_domain_rrset(apex, LDNS_RR_TYPE_DNSKEY);
8226
0
  if(!dnskey_rrset || dnskey_rrset->data->count==0) {
8227
0
    *why_bogus = "have trust anchor, but zone has no DNSKEY";
8228
0
    return 0;
8229
0
  }
8230
8231
0
  m = modstack_find(mods, "validator");
8232
0
  if(m == -1) {
8233
0
    *why_bogus = "have trust anchor, but no validator module";
8234
0
    return 0;
8235
0
  }
8236
0
  ve = (struct val_env*)env->modinfo[m];
8237
8238
0
  memset(keystorage, 0, sizeof(*keystorage));
8239
0
  keystorage->entry.key = keystorage;
8240
0
  keystorage->entry.data = dnskey_rrset->data;
8241
0
  keystorage->rk.dname = apex->name;
8242
0
  keystorage->rk.dname_len = apex->namelen;
8243
0
  keystorage->rk.type = htons(LDNS_RR_TYPE_DNSKEY);
8244
0
  keystorage->rk.rrset_class = htons(z->dclass);
8245
0
  auth_zone_log(z->name, VERB_QUERY,
8246
0
    "zonemd: verify DNSKEY RRset with trust anchor");
8247
0
  sec = val_verify_DNSKEY_with_TA(env, ve, keystorage, anchor->ds_rrset,
8248
0
    anchor->dnskey_rrset, NULL, why_bogus, NULL, NULL, reasonbuf,
8249
0
    reasonlen);
8250
0
  regional_free_all(env->scratch);
8251
0
  if(sec == sec_status_secure) {
8252
    /* success */
8253
0
    *is_insecure = 0;
8254
0
    return keystorage;
8255
0
  } else if(sec == sec_status_insecure) {
8256
    /* insecure */
8257
0
    *is_insecure = 1;
8258
0
  } else {
8259
    /* bogus */
8260
0
    *is_insecure = 0;
8261
0
    auth_zone_log(z->name, VERB_ALGO,
8262
0
      "zonemd: verify DNSKEY RRset with trust anchor failed: %s", *why_bogus);
8263
0
  }
8264
0
  return NULL;
8265
0
}
8266
8267
/** verify the DNSKEY from the zone with looked up DS record */
8268
static struct ub_packed_rrset_key*
8269
auth_zone_verify_zonemd_key_with_ds(struct auth_zone* z,
8270
  struct module_env* env, struct module_stack* mods,
8271
  struct ub_packed_rrset_key* ds, int* is_insecure, char** why_bogus,
8272
  struct ub_packed_rrset_key* keystorage, uint8_t* sigalg,
8273
  char* reasonbuf, size_t reasonlen)
8274
0
{
8275
0
  struct auth_data* apex;
8276
0
  struct auth_rrset* dnskey_rrset;
8277
0
  enum sec_status sec;
8278
0
  struct val_env* ve;
8279
0
  int m;
8280
8281
  /* fetch DNSKEY from zone data */
8282
0
  apex = az_find_name(z, z->name, z->namelen);
8283
0
  if(!apex) {
8284
0
    *why_bogus = "in verifywithDS, zone has no apex";
8285
0
    return NULL;
8286
0
  }
8287
0
  dnskey_rrset = az_domain_rrset(apex, LDNS_RR_TYPE_DNSKEY);
8288
0
  if(!dnskey_rrset || dnskey_rrset->data->count==0) {
8289
0
    *why_bogus = "in verifywithDS, zone has no DNSKEY";
8290
0
    return NULL;
8291
0
  }
8292
8293
0
  m = modstack_find(mods, "validator");
8294
0
  if(m == -1) {
8295
0
    *why_bogus = "in verifywithDS, have no validator module";
8296
0
    return NULL;
8297
0
  }
8298
0
  ve = (struct val_env*)env->modinfo[m];
8299
8300
0
  memset(keystorage, 0, sizeof(*keystorage));
8301
0
  keystorage->entry.key = keystorage;
8302
0
  keystorage->entry.data = dnskey_rrset->data;
8303
0
  keystorage->rk.dname = apex->name;
8304
0
  keystorage->rk.dname_len = apex->namelen;
8305
0
  keystorage->rk.type = htons(LDNS_RR_TYPE_DNSKEY);
8306
0
  keystorage->rk.rrset_class = htons(z->dclass);
8307
0
  auth_zone_log(z->name, VERB_QUERY, "zonemd: verify zone DNSKEY with DS");
8308
0
  sec = val_verify_DNSKEY_with_DS(env, ve, keystorage, ds, sigalg,
8309
0
    why_bogus, NULL, NULL, reasonbuf, reasonlen);
8310
0
  regional_free_all(env->scratch);
8311
0
  if(sec == sec_status_secure) {
8312
    /* success */
8313
0
    return keystorage;
8314
0
  } else if(sec == sec_status_insecure) {
8315
    /* insecure */
8316
0
    *is_insecure = 1;
8317
0
  } else {
8318
    /* bogus */
8319
0
    *is_insecure = 0;
8320
0
    if(*why_bogus == NULL)
8321
0
      *why_bogus = "verify failed";
8322
0
    auth_zone_log(z->name, VERB_ALGO,
8323
0
      "zonemd: verify DNSKEY RRset with DS failed: %s",
8324
0
      *why_bogus);
8325
0
  }
8326
0
  return NULL;
8327
0
}
8328
8329
/** callback for ZONEMD lookup of DNSKEY */
8330
void auth_zonemd_dnskey_lookup_callback(void* arg, int rcode, sldns_buffer* buf,
8331
  enum sec_status sec, char* why_bogus, int ATTR_UNUSED(was_ratelimited))
8332
0
{
8333
0
  struct auth_zone* z = (struct auth_zone*)arg;
8334
0
  struct module_env* env;
8335
0
  char reasonbuf[256];
8336
0
  char* reason = NULL, *ds_bogus = NULL, *typestr="DNSKEY";
8337
0
  struct ub_packed_rrset_key* dnskey = NULL, *ds = NULL;
8338
0
  int is_insecure = 0, downprot;
8339
0
  struct ub_packed_rrset_key keystorage;
8340
0
  uint8_t sigalg[ALGO_NEEDS_MAX+1];
8341
8342
0
  lock_rw_wrlock(&z->lock);
8343
0
  env = z->zonemd_callback_env;
8344
  /* release the env variable so another worker can pick up the
8345
   * ZONEMD verification task if it wants to */
8346
0
  z->zonemd_callback_env = NULL;
8347
0
  if(!env || env->outnet->want_to_quit || z->zone_deleted) {
8348
0
    lock_rw_unlock(&z->lock);
8349
0
    return; /* stop on quit */
8350
0
  }
8351
0
  if(z->zonemd_callback_qtype == LDNS_RR_TYPE_DS)
8352
0
    typestr = "DS";
8353
0
  downprot = env->cfg->harden_algo_downgrade;
8354
8355
  /* process result */
8356
0
  if(sec == sec_status_bogus) {
8357
0
    reason = why_bogus;
8358
0
    if(!reason) {
8359
0
      if(z->zonemd_callback_qtype == LDNS_RR_TYPE_DNSKEY)
8360
0
        reason = "lookup of DNSKEY was bogus";
8361
0
      else  reason = "lookup of DS was bogus";
8362
0
    }
8363
0
    auth_zone_log(z->name, VERB_ALGO,
8364
0
      "zonemd lookup of %s was bogus: %s", typestr, reason);
8365
0
  } else if(rcode == LDNS_RCODE_NOERROR) {
8366
0
    uint16_t wanted_qtype = z->zonemd_callback_qtype;
8367
0
    struct regional* temp = env->scratch;
8368
0
    struct query_info rq;
8369
0
    struct reply_info* rep;
8370
0
    memset(&rq, 0, sizeof(rq));
8371
0
    rep = parse_reply_in_temp_region(buf, temp, &rq);
8372
0
    if(rep && rq.qtype == wanted_qtype &&
8373
0
      query_dname_compare(z->name, rq.qname) == 0 &&
8374
0
      FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NOERROR) {
8375
      /* parsed successfully */
8376
0
      struct ub_packed_rrset_key* answer =
8377
0
        reply_find_answer_rrset(&rq, rep);
8378
0
      if(answer && sec == sec_status_secure) {
8379
0
        if(z->zonemd_callback_qtype == LDNS_RR_TYPE_DNSKEY)
8380
0
          dnskey = answer;
8381
0
        else  ds = answer;
8382
0
        auth_zone_log(z->name, VERB_ALGO,
8383
0
          "zonemd lookup of %s was secure", typestr);
8384
0
      } else if(sec == sec_status_secure && !answer) {
8385
0
        is_insecure = 1;
8386
0
        auth_zone_log(z->name, VERB_ALGO,
8387
0
          "zonemd lookup of %s has no content, but is secure, treat as insecure", typestr);
8388
0
      } else if(sec == sec_status_insecure) {
8389
0
        is_insecure = 1;
8390
0
        auth_zone_log(z->name, VERB_ALGO,
8391
0
          "zonemd lookup of %s was insecure", typestr);
8392
0
      } else if(sec == sec_status_indeterminate) {
8393
0
        is_insecure = 1;
8394
0
        auth_zone_log(z->name, VERB_ALGO,
8395
0
          "zonemd lookup of %s was indeterminate, treat as insecure", typestr);
8396
0
      } else {
8397
0
        auth_zone_log(z->name, VERB_ALGO,
8398
0
          "zonemd lookup of %s has nodata", typestr);
8399
0
        if(z->zonemd_callback_qtype == LDNS_RR_TYPE_DNSKEY)
8400
0
          reason = "lookup of DNSKEY has nodata";
8401
0
        else  reason = "lookup of DS has nodata";
8402
0
      }
8403
0
    } else if(rep && rq.qtype == wanted_qtype &&
8404
0
      query_dname_compare(z->name, rq.qname) == 0 &&
8405
0
      FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NXDOMAIN &&
8406
0
      sec == sec_status_secure) {
8407
      /* secure nxdomain, so the zone is like some RPZ zone
8408
       * that does not exist in the wider internet, with
8409
       * a secure nxdomain answer outside of it. So we
8410
       * treat the zonemd zone without a dnssec chain of
8411
       * trust, as insecure. */
8412
0
      is_insecure = 1;
8413
0
      auth_zone_log(z->name, VERB_ALGO,
8414
0
        "zonemd lookup of %s was secure NXDOMAIN, treat as insecure", typestr);
8415
0
    } else if(rep && rq.qtype == wanted_qtype &&
8416
0
      query_dname_compare(z->name, rq.qname) == 0 &&
8417
0
      FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NXDOMAIN &&
8418
0
      sec == sec_status_insecure) {
8419
0
      is_insecure = 1;
8420
0
      auth_zone_log(z->name, VERB_ALGO,
8421
0
        "zonemd lookup of %s was insecure NXDOMAIN, treat as insecure", typestr);
8422
0
    } else if(rep && rq.qtype == wanted_qtype &&
8423
0
      query_dname_compare(z->name, rq.qname) == 0 &&
8424
0
      FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NXDOMAIN &&
8425
0
      sec == sec_status_indeterminate) {
8426
0
      is_insecure = 1;
8427
0
      auth_zone_log(z->name, VERB_ALGO,
8428
0
        "zonemd lookup of %s was indeterminate NXDOMAIN, treat as insecure", typestr);
8429
0
    } else {
8430
0
      auth_zone_log(z->name, VERB_ALGO,
8431
0
        "zonemd lookup of %s has no answer", typestr);
8432
0
      if(z->zonemd_callback_qtype == LDNS_RR_TYPE_DNSKEY)
8433
0
        reason = "lookup of DNSKEY has no answer";
8434
0
      else  reason = "lookup of DS has no answer";
8435
0
    }
8436
0
  } else {
8437
0
    auth_zone_log(z->name, VERB_ALGO,
8438
0
      "zonemd lookup of %s failed", typestr);
8439
0
    if(z->zonemd_callback_qtype == LDNS_RR_TYPE_DNSKEY)
8440
0
      reason = "lookup of DNSKEY failed";
8441
0
    else  reason = "lookup of DS failed";
8442
0
  }
8443
8444
0
  if(!reason && !is_insecure && !dnskey && ds) {
8445
0
    dnskey = auth_zone_verify_zonemd_key_with_ds(z, env,
8446
0
      &env->mesh->mods, ds, &is_insecure, &ds_bogus,
8447
0
      &keystorage, downprot?sigalg:NULL, reasonbuf,
8448
0
      sizeof(reasonbuf));
8449
0
    if(!dnskey && !is_insecure && !reason)
8450
0
      reason = "DNSKEY verify with DS failed";
8451
0
  }
8452
8453
0
  if(reason) {
8454
0
    auth_zone_zonemd_fail(z, env, reason, ds_bogus, NULL);
8455
0
    lock_rw_unlock(&z->lock);
8456
0
    regional_free_all(env->scratch);
8457
0
    return;
8458
0
  }
8459
8460
0
  auth_zone_verify_zonemd_with_key(z, env, &env->mesh->mods, dnskey,
8461
0
    is_insecure, NULL, downprot?sigalg:NULL);
8462
0
  regional_free_all(env->scratch);
8463
0
  lock_rw_unlock(&z->lock);
8464
0
}
8465
8466
/** lookup DNSKEY for ZONEMD verification */
8467
static int
8468
zonemd_lookup_dnskey(struct auth_zone* z, struct module_env* env)
8469
0
{
8470
0
  struct query_info qinfo;
8471
0
  uint16_t qflags = BIT_RD;
8472
0
  struct edns_data edns;
8473
0
  sldns_buffer* buf = env->scratch_buffer;
8474
0
  int fetch_ds = 0;
8475
8476
0
  if(!z->fallback_enabled) {
8477
    /* we cannot actually get the DNSKEY, because it is in the
8478
     * zone we have ourselves, and it is not served yet
8479
     * (possibly), so fetch type DS */
8480
0
    fetch_ds = 1;
8481
0
  }
8482
0
  if(z->zonemd_callback_env) {
8483
    /* another worker is already working on the callback
8484
     * for the DNSKEY lookup for ZONEMD verification.
8485
     * We do not also have to do ZONEMD verification, let that
8486
     * worker do it */
8487
0
    auth_zone_log(z->name, VERB_ALGO,
8488
0
      "zonemd needs lookup of %s and that already is worked on by another worker", (fetch_ds?"DS":"DNSKEY"));
8489
0
    return 1;
8490
0
  }
8491
8492
  /* use mesh_new_callback to lookup the DNSKEY,
8493
   * and then wait for them to be looked up (in cache, or query) */
8494
0
  qinfo.qname_len = z->namelen;
8495
0
  qinfo.qname = z->name;
8496
0
  qinfo.qclass = z->dclass;
8497
0
  if(fetch_ds)
8498
0
    qinfo.qtype = LDNS_RR_TYPE_DS;
8499
0
  else  qinfo.qtype = LDNS_RR_TYPE_DNSKEY;
8500
0
  qinfo.local_alias = NULL;
8501
0
  if(verbosity >= VERB_ALGO) {
8502
0
    char buf1[512];
8503
0
    char buf2[LDNS_MAX_DOMAINLEN];
8504
0
    dname_str(z->name, buf2);
8505
0
    snprintf(buf1, sizeof(buf1), "auth zone %s: lookup %s "
8506
0
      "for zonemd verification", buf2,
8507
0
      (fetch_ds?"DS":"DNSKEY"));
8508
0
    log_query_info(VERB_ALGO, buf1, &qinfo);
8509
0
  }
8510
0
  edns.edns_present = 1;
8511
0
  edns.ext_rcode = 0;
8512
0
  edns.edns_version = 0;
8513
0
  edns.bits = EDNS_DO;
8514
0
  edns.opt_list_in = NULL;
8515
0
  edns.opt_list_out = NULL;
8516
0
  edns.opt_list_inplace_cb_out = NULL;
8517
0
  if(sldns_buffer_capacity(buf) < 65535)
8518
0
    edns.udp_size = (uint16_t)sldns_buffer_capacity(buf);
8519
0
  else  edns.udp_size = 65535;
8520
8521
  /* store the worker-specific module env for the callback.
8522
   * We can then reference this when the callback executes */
8523
0
  z->zonemd_callback_env = env;
8524
0
  z->zonemd_callback_qtype = qinfo.qtype;
8525
  /* the callback can be called straight away */
8526
0
  lock_rw_unlock(&z->lock);
8527
0
  if(!mesh_new_callback(env->mesh, &qinfo, qflags, &edns, buf, 0,
8528
0
    &auth_zonemd_dnskey_lookup_callback, z, 0)) {
8529
0
    lock_rw_wrlock(&z->lock);
8530
0
    log_err("out of memory lookup of %s for zonemd",
8531
0
      (fetch_ds?"DS":"DNSKEY"));
8532
0
    return 0;
8533
0
  }
8534
0
  lock_rw_wrlock(&z->lock);
8535
0
  return 1;
8536
0
}
8537
8538
void auth_zone_verify_zonemd(struct auth_zone* z, struct module_env* env,
8539
  struct module_stack* mods, char** result, int offline, int only_online)
8540
0
{
8541
0
  char reasonbuf[256];
8542
0
  char* reason = NULL, *why_bogus = NULL;
8543
0
  struct trust_anchor* anchor = NULL;
8544
0
  struct ub_packed_rrset_key* dnskey = NULL;
8545
0
  struct ub_packed_rrset_key keystorage;
8546
0
  int is_insecure = 0;
8547
  /* verify the ZONEMD if present.
8548
   * If not present check if absence is allowed by DNSSEC */
8549
0
  if(!z->zonemd_check)
8550
0
    return;
8551
0
  if(z->data.count == 0)
8552
0
    return; /* no data */
8553
8554
  /* if zone is under a trustanchor */
8555
  /* is it equal to trustanchor - get dnskey's verified */
8556
  /* else, find chain of trust by fetching DNSKEYs lookup for zone */
8557
  /* result if that, if insecure, means no DNSSEC for the ZONEMD,
8558
   * otherwise we have the zone DNSKEY for the DNSSEC verification. */
8559
0
  if(env->anchors)
8560
0
    anchor = anchors_lookup(env->anchors, z->name, z->namelen,
8561
0
      z->dclass);
8562
0
  if(anchor && anchor->numDS == 0 && anchor->numDNSKEY == 0) {
8563
    /* domain-insecure trust anchor for unsigned zones */
8564
0
    lock_basic_unlock(&anchor->lock);
8565
0
    if(only_online)
8566
0
      return;
8567
0
    dnskey = NULL;
8568
0
    is_insecure = 1;
8569
0
  } else if(anchor && query_dname_compare(z->name, anchor->name) == 0) {
8570
0
    if(only_online) {
8571
0
      lock_basic_unlock(&anchor->lock);
8572
0
      return;
8573
0
    }
8574
    /* equal to trustanchor, no need for online lookups */
8575
0
    dnskey = zonemd_get_dnskey_from_anchor(z, env, mods, anchor,
8576
0
      &is_insecure, &why_bogus, &keystorage, reasonbuf,
8577
0
      sizeof(reasonbuf));
8578
0
    lock_basic_unlock(&anchor->lock);
8579
0
    if(!dnskey && !reason && !is_insecure) {
8580
0
      reason = "verify DNSKEY RRset with trust anchor failed";
8581
0
    }
8582
0
  } else if(anchor) {
8583
0
    lock_basic_unlock(&anchor->lock);
8584
    /* perform online lookups */
8585
0
    if(offline)
8586
0
      return;
8587
    /* setup online lookups, and wait for them */
8588
0
    if(zonemd_lookup_dnskey(z, env)) {
8589
      /* wait for the lookup */
8590
0
      return;
8591
0
    }
8592
0
    reason = "could not lookup DNSKEY for chain of trust";
8593
0
  } else {
8594
    /* the zone is not under a trust anchor */
8595
0
    if(only_online)
8596
0
      return;
8597
0
    dnskey = NULL;
8598
0
    is_insecure = 1;
8599
0
  }
8600
8601
0
  if(reason) {
8602
0
    auth_zone_zonemd_fail(z, env, reason, why_bogus, result);
8603
0
    regional_free_all(env->scratch);
8604
0
    return;
8605
0
  }
8606
8607
0
  auth_zone_verify_zonemd_with_key(z, env, mods, dnskey, is_insecure,
8608
0
    result, NULL);
8609
0
  regional_free_all(env->scratch);
8610
0
}
8611
8612
void auth_zones_pickup_zonemd_verify(struct auth_zones* az,
8613
  struct module_env* env)
8614
0
{
8615
0
  struct auth_zone key;
8616
0
  uint8_t savezname[255+1];
8617
0
  size_t savezname_len;
8618
0
  struct auth_zone* z;
8619
0
  key.node.key = &key;
8620
0
  lock_rw_rdlock(&az->lock);
8621
0
  RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
8622
0
    lock_rw_wrlock(&z->lock);
8623
0
    if(!z->zonemd_check) {
8624
0
      lock_rw_unlock(&z->lock);
8625
0
      continue;
8626
0
    }
8627
0
    key.dclass = z->dclass;
8628
0
    key.namelabs = z->namelabs;
8629
0
    if(z->namelen > sizeof(savezname)) {
8630
0
      lock_rw_unlock(&z->lock);
8631
0
      log_err("auth_zones_pickup_zonemd_verify: zone name too long");
8632
0
      continue;
8633
0
    }
8634
0
    savezname_len = z->namelen;
8635
0
    memmove(savezname, z->name, z->namelen);
8636
0
    lock_rw_unlock(&az->lock);
8637
0
    auth_zone_verify_zonemd(z, env, &env->mesh->mods, NULL, 0, 1);
8638
0
    lock_rw_unlock(&z->lock);
8639
0
    lock_rw_rdlock(&az->lock);
8640
    /* find the zone we had before, it is not deleted,
8641
     * because we have a flag for that that is processed at
8642
     * apply_cfg time */
8643
0
    key.namelen = savezname_len;
8644
0
    key.name = savezname;
8645
0
    z = (struct auth_zone*)rbtree_search(&az->ztree, &key);
8646
0
    if(!z)
8647
0
      break;
8648
0
  }
8649
0
  lock_rw_unlock(&az->lock);
8650
0
}
8651
8652
/** Get memory usage of auth rrset */
8653
static size_t
8654
auth_rrset_get_mem(struct auth_rrset* rrset)
8655
0
{
8656
0
  size_t m = sizeof(*rrset) + packed_rrset_sizeof(rrset->data);
8657
0
  return m;
8658
0
}
8659
8660
/** Get memory usage of auth data */
8661
static size_t
8662
auth_data_get_mem(struct auth_data* node)
8663
0
{
8664
0
  size_t m = sizeof(*node) + node->namelen;
8665
0
  struct auth_rrset* rrset;
8666
0
  for(rrset = node->rrsets; rrset; rrset = rrset->next) {
8667
0
    m += auth_rrset_get_mem(rrset);
8668
0
  }
8669
0
  return m;
8670
0
}
8671
8672
/** Get memory usage of auth zone */
8673
static size_t
8674
auth_zone_get_mem(struct auth_zone* z)
8675
0
{
8676
0
  size_t m = sizeof(*z) + z->namelen;
8677
0
  struct auth_data* node;
8678
0
  if(z->zonefile)
8679
0
    m += strlen(z->zonefile)+1;
8680
0
  RBTREE_FOR(node, struct auth_data*, &z->data) {
8681
0
    m += auth_data_get_mem(node);
8682
0
  }
8683
0
  if(z->rpz)
8684
0
    m += rpz_get_mem(z->rpz);
8685
0
  return m;
8686
0
}
8687
8688
/** Get memory usage of list of auth addr */
8689
static size_t
8690
auth_addrs_get_mem(struct auth_addr* list)
8691
0
{
8692
0
  size_t m = 0;
8693
0
  struct auth_addr* a;
8694
0
  for(a = list; a; a = a->next) {
8695
0
    m += sizeof(*a);
8696
0
  }
8697
0
  return m;
8698
0
}
8699
8700
/** Get memory usage of list of primaries for auth xfer */
8701
static size_t
8702
auth_primaries_get_mem(struct auth_master* list)
8703
0
{
8704
0
  size_t m = 0;
8705
0
  struct auth_master* n;
8706
0
  for(n = list; n; n = n->next) {
8707
0
    m += sizeof(*n);
8708
0
    m += auth_addrs_get_mem(n->list);
8709
0
    if(n->host)
8710
0
      m += strlen(n->host)+1;
8711
0
    if(n->file)
8712
0
      m += strlen(n->file)+1;
8713
0
  }
8714
0
  return m;
8715
0
}
8716
8717
/** Get memory usage or list of auth chunks */
8718
static size_t
8719
auth_chunks_get_mem(struct auth_chunk* list)
8720
0
{
8721
0
  size_t m = 0;
8722
0
  struct auth_chunk* chunk;
8723
0
  for(chunk = list; chunk; chunk = chunk->next) {
8724
0
    m += sizeof(*chunk) + chunk->len;
8725
0
  }
8726
0
  return m;
8727
0
}
8728
8729
/** Get memory usage of auth xfer */
8730
static size_t
8731
auth_xfer_get_mem(struct auth_xfer* xfr)
8732
0
{
8733
0
  size_t m = sizeof(*xfr) + xfr->namelen;
8734
8735
  /* auth_nextprobe */
8736
0
  m += comm_timer_get_mem(xfr->task_nextprobe->timer);
8737
8738
  /* auth_probe */
8739
0
  m += auth_primaries_get_mem(xfr->task_probe->masters);
8740
0
  m += comm_point_get_mem(xfr->task_probe->cp);
8741
0
  m += comm_timer_get_mem(xfr->task_probe->timer);
8742
8743
  /* auth_transfer */
8744
0
  m += auth_chunks_get_mem(xfr->task_transfer->chunks_first);
8745
0
  m += auth_primaries_get_mem(xfr->task_transfer->masters);
8746
0
  m += comm_point_get_mem(xfr->task_transfer->cp);
8747
0
  m += comm_timer_get_mem(xfr->task_transfer->timer);
8748
8749
  /* allow_notify_list */
8750
0
  m += auth_primaries_get_mem(xfr->allow_notify_list);
8751
8752
0
  return m;
8753
0
}
8754
8755
/** Get memory usage of auth zones ztree */
8756
static size_t
8757
az_ztree_get_mem(struct auth_zones* az)
8758
0
{
8759
0
  size_t m = 0;
8760
0
  struct auth_zone* z;
8761
0
  RBTREE_FOR(z, struct auth_zone*, &az->ztree) {
8762
0
    lock_rw_rdlock(&z->lock);
8763
0
    m += auth_zone_get_mem(z);
8764
0
    lock_rw_unlock(&z->lock);
8765
0
  }
8766
0
  return m;
8767
0
}
8768
8769
/** Get memory usage of auth zones xtree */
8770
static size_t
8771
az_xtree_get_mem(struct auth_zones* az)
8772
0
{
8773
0
  size_t m = 0;
8774
0
  struct auth_xfer* xfr;
8775
0
  RBTREE_FOR(xfr, struct auth_xfer*, &az->xtree) {
8776
0
    lock_basic_lock(&xfr->lock);
8777
0
    m += auth_xfer_get_mem(xfr);
8778
0
    lock_basic_unlock(&xfr->lock);
8779
0
  }
8780
0
  return m;
8781
0
}
8782
8783
size_t auth_zones_get_mem(struct auth_zones* zones)
8784
0
{
8785
0
  size_t m;
8786
0
  if(!zones) return 0;
8787
0
  m = sizeof(*zones);
8788
0
  lock_rw_rdlock(&zones->rpz_lock);
8789
0
  lock_rw_rdlock(&zones->lock);
8790
0
  m += az_ztree_get_mem(zones);
8791
0
  m += az_xtree_get_mem(zones);
8792
0
  lock_rw_unlock(&zones->lock);
8793
0
  lock_rw_unlock(&zones->rpz_lock);
8794
0
  return m;
8795
0
}
8796
8797
void xfr_disown_tasks(struct auth_xfer* xfr, struct worker* worker)
8798
0
{
8799
0
  if(xfr->task_nextprobe->worker == worker) {
8800
0
    xfr_nextprobe_disown(xfr);
8801
0
  }
8802
0
  if(xfr->task_probe->worker == worker) {
8803
0
    xfr_probe_disown(xfr);
8804
0
  }
8805
0
  if(xfr->task_transfer->worker == worker) {
8806
0
    xfr_transfer_disown(xfr);
8807
0
  }
8808
0
}