Coverage Report

Created: 2025-12-11 07:06

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/unbound/services/mesh.c
Line
Count
Source
1
/*
2
 * services/mesh.c - deal with mesh of query states and handle events for that.
3
 *
4
 * Copyright (c) 2007, 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 functions to assist in dealing with a mesh of
40
 * query states. This mesh is supposed to be thread-specific.
41
 * It consists of query states (per qname, qtype, qclass) and connections
42
 * between query states and the super and subquery states, and replies to
43
 * send back to clients.
44
 */
45
#include "config.h"
46
#include "services/mesh.h"
47
#include "services/outbound_list.h"
48
#include "services/cache/dns.h"
49
#include "services/cache/rrset.h"
50
#include "services/cache/infra.h"
51
#include "util/log.h"
52
#include "util/net_help.h"
53
#include "util/module.h"
54
#include "util/regional.h"
55
#include "util/data/msgencode.h"
56
#include "util/timehist.h"
57
#include "util/fptr_wlist.h"
58
#include "util/alloc.h"
59
#include "util/config_file.h"
60
#include "util/edns.h"
61
#include "sldns/sbuffer.h"
62
#include "sldns/wire2str.h"
63
#include "services/localzone.h"
64
#include "util/data/dname.h"
65
#include "respip/respip.h"
66
#include "services/listen_dnsport.h"
67
#include "util/timeval_func.h"
68
69
#ifdef CLIENT_SUBNET
70
#include "edns-subnet/subnetmod.h"
71
#include "edns-subnet/edns-subnet.h"
72
#endif
73
#ifdef HAVE_SYS_TYPES_H
74
#  include <sys/types.h>
75
#endif
76
#ifdef HAVE_NETDB_H
77
#include <netdb.h>
78
#endif
79
80
/** Compare two views by name */
81
static int
82
view_name_compare(const char* v_a, const char* v_b)
83
0
{
84
0
  if(v_a == NULL && v_b == NULL)
85
0
    return 0;
86
  /* The NULL name is smaller than if the name is set. */
87
0
  if(v_a == NULL)
88
0
    return -1;
89
0
  if(v_b == NULL)
90
0
    return 1;
91
0
  return strcmp(v_a, v_b);
92
0
}
93
94
/**
95
 * Compare two response-ip client info entries for the purpose of mesh state
96
 * compare.  It returns 0 if ci_a and ci_b are considered equal; otherwise
97
 * 1 or -1 (they mean 'ci_a is larger/smaller than ci_b', respectively, but
98
 * in practice it should be only used to mean they are different).
99
 * We cannot share the mesh state for two queries if different response-ip
100
 * actions can apply in the end, even if those queries are otherwise identical.
101
 * For this purpose we compare tag lists and tag action lists; they should be
102
 * identical to share the same state.
103
 * For tag data, we don't look into the data content, as it can be
104
 * expensive; unless tag data are not defined for both or they point to the
105
 * exact same data in memory (i.e., they come from the same ACL entry), we
106
 * consider these data different.
107
 * Likewise, if the client info is associated with views, we don't look into
108
 * the views.  They are considered different unless they are exactly the same
109
 * even if the views only differ in the names.
110
 */
111
static int
112
client_info_compare(const struct respip_client_info* ci_a,
113
  const struct respip_client_info* ci_b)
114
0
{
115
0
  int cmp;
116
117
0
  if(!ci_a && !ci_b)
118
0
    return 0;
119
0
  if(ci_a && !ci_b)
120
0
    return -1;
121
0
  if(!ci_a && ci_b)
122
0
    return 1;
123
0
  if(ci_a->taglen != ci_b->taglen)
124
0
    return (ci_a->taglen < ci_b->taglen) ? -1 : 1;
125
0
  if(ci_a->taglist && !ci_b->taglist)
126
0
    return -1;
127
0
  if(!ci_a->taglist && ci_b->taglist)
128
0
    return 1;
129
0
  if(ci_a->taglist && ci_b->taglist) {
130
0
    cmp = memcmp(ci_a->taglist, ci_b->taglist, ci_a->taglen);
131
0
    if(cmp != 0)
132
0
      return cmp;
133
0
  }
134
0
  if(ci_a->tag_actions_size != ci_b->tag_actions_size)
135
0
    return (ci_a->tag_actions_size < ci_b->tag_actions_size) ?
136
0
      -1 : 1;
137
0
  if(ci_a->tag_actions && !ci_b->tag_actions)
138
0
    return -1;
139
0
  if(!ci_a->tag_actions && ci_b->tag_actions)
140
0
    return 1;
141
0
  if(ci_a->tag_actions && ci_b->tag_actions) {
142
0
    cmp = memcmp(ci_a->tag_actions, ci_b->tag_actions,
143
0
      ci_a->tag_actions_size);
144
0
    if(cmp != 0)
145
0
      return cmp;
146
0
  }
147
0
  if(ci_a->tag_datas != ci_b->tag_datas)
148
0
    return ci_a->tag_datas < ci_b->tag_datas ? -1 : 1;
149
0
  if(ci_a->view || ci_a->view_name || ci_b->view || ci_b->view_name) {
150
    /* Compare the views by name. */
151
0
    cmp = view_name_compare(
152
0
      (ci_a->view?ci_a->view->name:ci_a->view_name),
153
0
      (ci_b->view?ci_b->view->name:ci_b->view_name));
154
0
    if(cmp != 0)
155
0
      return cmp;
156
0
  }
157
0
  return 0;
158
0
}
159
160
int
161
mesh_state_compare(const void* ap, const void* bp)
162
0
{
163
0
  struct mesh_state* a = (struct mesh_state*)ap;
164
0
  struct mesh_state* b = (struct mesh_state*)bp;
165
0
  int cmp;
166
167
0
  if(a->unique < b->unique)
168
0
    return -1;
169
0
  if(a->unique > b->unique)
170
0
    return 1;
171
172
0
  if(a->s.is_priming && !b->s.is_priming)
173
0
    return -1;
174
0
  if(!a->s.is_priming && b->s.is_priming)
175
0
    return 1;
176
177
0
  if(a->s.is_valrec && !b->s.is_valrec)
178
0
    return -1;
179
0
  if(!a->s.is_valrec && b->s.is_valrec)
180
0
    return 1;
181
182
0
  if((a->s.query_flags&BIT_RD) && !(b->s.query_flags&BIT_RD))
183
0
    return -1;
184
0
  if(!(a->s.query_flags&BIT_RD) && (b->s.query_flags&BIT_RD))
185
0
    return 1;
186
187
0
  if((a->s.query_flags&BIT_CD) && !(b->s.query_flags&BIT_CD))
188
0
    return -1;
189
0
  if(!(a->s.query_flags&BIT_CD) && (b->s.query_flags&BIT_CD))
190
0
    return 1;
191
192
0
  cmp = query_info_compare(&a->s.qinfo, &b->s.qinfo);
193
0
  if(cmp != 0)
194
0
    return cmp;
195
0
  return client_info_compare(a->s.client_info, b->s.client_info);
196
0
}
197
198
int
199
mesh_state_ref_compare(const void* ap, const void* bp)
200
0
{
201
0
  struct mesh_state_ref* a = (struct mesh_state_ref*)ap;
202
0
  struct mesh_state_ref* b = (struct mesh_state_ref*)bp;
203
0
  return mesh_state_compare(a->s, b->s);
204
0
}
205
206
struct mesh_area*
207
mesh_create(struct module_stack* stack, struct module_env* env)
208
0
{
209
0
  struct mesh_area* mesh = calloc(1, sizeof(struct mesh_area));
210
0
  if(!mesh) {
211
0
    log_err("mesh area alloc: out of memory");
212
0
    return NULL;
213
0
  }
214
0
  mesh->histogram = timehist_setup();
215
0
  mesh->qbuf_bak = sldns_buffer_new(env->cfg->msg_buffer_size);
216
0
  if(!mesh->histogram || !mesh->qbuf_bak) {
217
0
    free(mesh);
218
0
    log_err("mesh area alloc: out of memory");
219
0
    return NULL;
220
0
  }
221
0
  mesh->mods = *stack;
222
0
  mesh->env = env;
223
0
  rbtree_init(&mesh->run, &mesh_state_compare);
224
0
  rbtree_init(&mesh->all, &mesh_state_compare);
225
0
  mesh->num_reply_addrs = 0;
226
0
  mesh->num_reply_states = 0;
227
0
  mesh->num_detached_states = 0;
228
0
  mesh->num_forever_states = 0;
229
0
  mesh->stats_jostled = 0;
230
0
  mesh->stats_dropped = 0;
231
0
  mesh->ans_expired = 0;
232
0
  mesh->ans_cachedb = 0;
233
0
  mesh->num_queries_discard_timeout = 0;
234
0
  mesh->num_queries_replyaddr_limit = 0;
235
0
  mesh->num_queries_wait_limit = 0;
236
0
  mesh->num_dns_error_reports = 0;
237
0
  mesh->max_reply_states = env->cfg->num_queries_per_thread;
238
0
  mesh->max_forever_states = (mesh->max_reply_states+1)/2;
239
0
#ifndef S_SPLINT_S
240
0
  mesh->jostle_max.tv_sec = (time_t)(env->cfg->jostle_time / 1000);
241
0
  mesh->jostle_max.tv_usec = (time_t)((env->cfg->jostle_time % 1000)
242
0
    *1000);
243
0
#endif
244
0
  return mesh;
245
0
}
246
247
/** help mesh delete delete mesh states */
248
static void
249
mesh_delete_helper(rbnode_type* n)
250
0
{
251
0
  struct mesh_state* mstate = (struct mesh_state*)n->key;
252
  /* perform a full delete, not only 'cleanup' routine,
253
   * because other callbacks expect a clean state in the mesh.
254
   * For 're-entrant' calls */
255
0
  mesh_state_delete(&mstate->s);
256
  /* but because these delete the items from the tree, postorder
257
   * traversal and rbtree rebalancing do not work together */
258
0
}
259
260
void
261
mesh_delete(struct mesh_area* mesh)
262
0
{
263
0
  if(!mesh)
264
0
    return;
265
  /* free all query states */
266
0
  while(mesh->all.count)
267
0
    mesh_delete_helper(mesh->all.root);
268
0
  timehist_delete(mesh->histogram);
269
0
  sldns_buffer_free(mesh->qbuf_bak);
270
0
  free(mesh);
271
0
}
272
273
void
274
mesh_delete_all(struct mesh_area* mesh)
275
0
{
276
  /* free all query states */
277
0
  while(mesh->all.count)
278
0
    mesh_delete_helper(mesh->all.root);
279
0
  mesh->stats_dropped += mesh->num_reply_addrs;
280
  /* clear mesh area references */
281
0
  rbtree_init(&mesh->run, &mesh_state_compare);
282
0
  rbtree_init(&mesh->all, &mesh_state_compare);
283
0
  mesh->num_reply_addrs = 0;
284
0
  mesh->num_reply_states = 0;
285
0
  mesh->num_detached_states = 0;
286
0
  mesh->num_forever_states = 0;
287
0
  mesh->forever_first = NULL;
288
0
  mesh->forever_last = NULL;
289
0
  mesh->jostle_first = NULL;
290
0
  mesh->jostle_last = NULL;
291
0
}
292
293
int mesh_make_new_space(struct mesh_area* mesh, sldns_buffer* qbuf)
294
0
{
295
0
  struct mesh_state* m = mesh->jostle_first;
296
  /* free space is available */
297
0
  if(mesh->num_reply_states < mesh->max_reply_states)
298
0
    return 1;
299
  /* try to kick out a jostle-list item */
300
0
  if(m && m->reply_list && m->list_select == mesh_jostle_list) {
301
    /* how old is it? */
302
0
    struct timeval age;
303
0
    timeval_subtract(&age, mesh->env->now_tv,
304
0
      &m->reply_list->start_time);
305
0
    if(timeval_smaller(&mesh->jostle_max, &age)) {
306
      /* its a goner */
307
0
      log_nametypeclass(VERB_ALGO, "query jostled out to "
308
0
        "make space for a new one",
309
0
        m->s.qinfo.qname, m->s.qinfo.qtype,
310
0
        m->s.qinfo.qclass);
311
      /* backup the query */
312
0
      if(qbuf) sldns_buffer_copy(mesh->qbuf_bak, qbuf);
313
      /* notify supers */
314
0
      if(m->super_set.count > 0) {
315
0
        verbose(VERB_ALGO, "notify supers of failure");
316
0
        m->s.return_msg = NULL;
317
0
        m->s.return_rcode = LDNS_RCODE_SERVFAIL;
318
0
        mesh_walk_supers(mesh, m);
319
0
      }
320
0
      mesh->stats_jostled ++;
321
0
      mesh_state_delete(&m->s);
322
      /* restore the query - note that the qinfo ptr to
323
       * the querybuffer is then correct again. */
324
0
      if(qbuf) sldns_buffer_copy(qbuf, mesh->qbuf_bak);
325
0
      return 1;
326
0
    }
327
0
  }
328
  /* no space for new item */
329
0
  return 0;
330
0
}
331
332
struct dns_msg*
333
mesh_serve_expired_lookup(struct module_qstate* qstate,
334
  struct query_info* lookup_qinfo, int* is_expired)
335
0
{
336
0
  hashvalue_type h;
337
0
  struct lruhash_entry* e;
338
0
  struct dns_msg* msg;
339
0
  struct reply_info* data;
340
0
  struct msgreply_entry* key;
341
0
  time_t timenow = *qstate->env->now;
342
0
  int must_validate = (!(qstate->query_flags&BIT_CD)
343
0
    || qstate->env->cfg->ignore_cd) && qstate->env->need_to_validate;
344
0
  *is_expired = 0;
345
  /* Lookup cache */
346
0
  h = query_info_hash(lookup_qinfo, qstate->query_flags);
347
0
  e = slabhash_lookup(qstate->env->msg_cache, h, lookup_qinfo, 0);
348
0
  if(!e) return NULL;
349
350
0
  key = (struct msgreply_entry*)e->key;
351
0
  data = (struct reply_info*)e->data;
352
0
  if(TTL_IS_EXPIRED(data->ttl, timenow)) *is_expired = 1;
353
0
  msg = tomsg(qstate->env, &key->key, data, qstate->region, timenow,
354
0
    qstate->env->cfg->serve_expired, qstate->env->scratch);
355
0
  if(!msg)
356
0
    goto bail_out;
357
358
  /* Check CNAME chain (if any)
359
   * This is part of tomsg above; no need to check now. */
360
361
  /* Check security status of the cached answer.
362
   * tomsg above has a subset of these checks, so we are leaving
363
   * these as is.
364
   * In case of bogus or revalidation we don't care to reply here. */
365
0
  if(must_validate && (msg->rep->security == sec_status_bogus ||
366
0
    msg->rep->security == sec_status_secure_sentinel_fail)) {
367
0
    verbose(VERB_ALGO, "Serve expired: bogus answer found in cache");
368
0
    goto bail_out;
369
0
  } else if(msg->rep->security == sec_status_unchecked && must_validate) {
370
0
    verbose(VERB_ALGO, "Serve expired: unchecked entry needs "
371
0
      "validation");
372
0
    goto bail_out; /* need to validate cache entry first */
373
0
  } else if(msg->rep->security == sec_status_secure &&
374
0
    !reply_all_rrsets_secure(msg->rep) && must_validate) {
375
0
      verbose(VERB_ALGO, "Serve expired: secure entry"
376
0
        " changed status");
377
0
      goto bail_out; /* rrset changed, re-verify */
378
0
  }
379
380
0
  lock_rw_unlock(&e->lock);
381
0
  return msg;
382
383
0
bail_out:
384
0
  lock_rw_unlock(&e->lock);
385
0
  return NULL;
386
0
}
387
388
389
/** Init the serve expired data structure */
390
static int
391
mesh_serve_expired_init(struct mesh_state* mstate, int timeout)
392
0
{
393
0
  struct timeval t;
394
395
  /* Create serve_expired_data if not there yet */
396
0
  if(!mstate->s.serve_expired_data) {
397
0
    mstate->s.serve_expired_data = (struct serve_expired_data*)
398
0
      regional_alloc_zero(
399
0
        mstate->s.region, sizeof(struct serve_expired_data));
400
0
    if(!mstate->s.serve_expired_data)
401
0
      return 0;
402
0
  }
403
404
  /* Don't overwrite the function if already set */
405
0
  mstate->s.serve_expired_data->get_cached_answer =
406
0
    mstate->s.serve_expired_data->get_cached_answer?
407
0
    mstate->s.serve_expired_data->get_cached_answer:
408
0
    &mesh_serve_expired_lookup;
409
410
  /* In case this timer already popped, start it again */
411
0
  if(!mstate->s.serve_expired_data->timer && timeout != -1) {
412
0
    mstate->s.serve_expired_data->timer = comm_timer_create(
413
0
      mstate->s.env->worker_base, mesh_serve_expired_callback, mstate);
414
0
    if(!mstate->s.serve_expired_data->timer)
415
0
      return 0;
416
0
#ifndef S_SPLINT_S
417
0
    t.tv_sec = timeout/1000;
418
0
    t.tv_usec = (timeout%1000)*1000;
419
0
#endif
420
0
    comm_timer_set(mstate->s.serve_expired_data->timer, &t);
421
0
  }
422
0
  return 1;
423
0
}
424
425
void mesh_new_client(struct mesh_area* mesh, struct query_info* qinfo,
426
  struct respip_client_info* cinfo, uint16_t qflags,
427
  struct edns_data* edns, struct comm_reply* rep, uint16_t qid,
428
  int rpz_passthru)
429
0
{
430
0
  struct mesh_state* s = NULL;
431
0
  int unique = unique_mesh_state(edns->opt_list_in, mesh->env);
432
0
  int was_detached = 0;
433
0
  int was_noreply = 0;
434
0
  int added = 0;
435
0
  int timeout = mesh->env->cfg->serve_expired?
436
0
    mesh->env->cfg->serve_expired_client_timeout:0;
437
0
  struct sldns_buffer* r_buffer = rep->c->buffer;
438
0
  uint16_t mesh_flags = qflags&(BIT_RD|BIT_CD);
439
0
  if(rep->c->tcp_req_info) {
440
0
    r_buffer = rep->c->tcp_req_info->spool_buffer;
441
0
  }
442
0
  if(!infra_wait_limit_allowed(mesh->env->infra_cache, rep,
443
0
    edns->cookie_valid, mesh->env->cfg)) {
444
0
    verbose(VERB_ALGO, "Too many queries waiting from the IP. "
445
0
      "servfail incoming query.");
446
0
    mesh->num_queries_wait_limit++;
447
0
    edns_opt_list_append_ede(&edns->opt_list_out,
448
0
      mesh->env->scratch, LDNS_EDE_OTHER,
449
0
      "Too many queries queued up and waiting from the IP");
450
0
    if(!inplace_cb_reply_servfail_call(mesh->env, qinfo, NULL, NULL,
451
0
      LDNS_RCODE_SERVFAIL, edns, rep, mesh->env->scratch, mesh->env->now_tv))
452
0
        edns->opt_list_inplace_cb_out = NULL;
453
0
    error_encode(r_buffer, LDNS_RCODE_SERVFAIL,
454
0
      qinfo, qid, qflags, edns);
455
0
    regional_free_all(mesh->env->scratch);
456
0
    comm_point_send_reply(rep);
457
0
    return;
458
0
  }
459
0
  if(!unique)
460
0
    s = mesh_area_find(mesh, cinfo, qinfo, mesh_flags, 0, 0);
461
  /* does this create a new reply state? */
462
0
  if(!s || s->list_select == mesh_no_list) {
463
0
    if(!mesh_make_new_space(mesh, rep->c->buffer)) {
464
0
      verbose(VERB_ALGO, "Too many queries. dropping "
465
0
        "incoming query.");
466
0
      if(rep->c->use_h2)
467
0
        http2_stream_remove_mesh_state(rep->c->h2_stream);
468
0
      comm_point_drop_reply(rep);
469
0
      mesh->stats_dropped++;
470
0
      return;
471
0
    }
472
    /* for this new reply state, the reply address is free,
473
     * so the limit of reply addresses does not stop reply states*/
474
0
  } else {
475
    /* protect our memory usage from storing reply addresses */
476
0
    if(mesh->num_reply_addrs > mesh->max_reply_states*16) {
477
0
      verbose(VERB_ALGO, "Too many requests queued. "
478
0
        "dropping incoming query.");
479
0
      if(rep->c->use_h2)
480
0
        http2_stream_remove_mesh_state(rep->c->h2_stream);
481
0
      comm_point_drop_reply(rep);
482
0
      mesh->num_queries_replyaddr_limit++;
483
0
      return;
484
0
    }
485
0
  }
486
  /* see if it already exists, if not, create one */
487
0
  if(!s) {
488
#ifdef UNBOUND_DEBUG
489
    struct rbnode_type* n;
490
#endif
491
0
    s = mesh_state_create(mesh->env, qinfo, cinfo,
492
0
      mesh_flags, 0, 0);
493
0
    if(!s) {
494
0
      log_err("mesh_state_create: out of memory; SERVFAIL");
495
0
      if(!inplace_cb_reply_servfail_call(mesh->env, qinfo, NULL, NULL,
496
0
        LDNS_RCODE_SERVFAIL, edns, rep, mesh->env->scratch, mesh->env->now_tv))
497
0
          edns->opt_list_inplace_cb_out = NULL;
498
0
      error_encode(r_buffer, LDNS_RCODE_SERVFAIL,
499
0
        qinfo, qid, qflags, edns);
500
0
      comm_point_send_reply(rep);
501
0
      return;
502
0
    }
503
    /* set detached (it is now) */
504
0
    mesh->num_detached_states++;
505
0
    if(unique)
506
0
      mesh_state_make_unique(s);
507
0
    s->s.rpz_passthru = rpz_passthru;
508
    /* copy the edns options we got from the front */
509
0
    if(edns->opt_list_in) {
510
0
      s->s.edns_opts_front_in = edns_opt_copy_region(edns->opt_list_in,
511
0
        s->s.region);
512
0
      if(!s->s.edns_opts_front_in) {
513
0
        log_err("edns_opt_copy_region: out of memory; SERVFAIL");
514
0
        if(!inplace_cb_reply_servfail_call(mesh->env, qinfo, NULL,
515
0
          NULL, LDNS_RCODE_SERVFAIL, edns, rep, mesh->env->scratch, mesh->env->now_tv))
516
0
            edns->opt_list_inplace_cb_out = NULL;
517
0
        error_encode(r_buffer, LDNS_RCODE_SERVFAIL,
518
0
          qinfo, qid, qflags, edns);
519
0
        comm_point_send_reply(rep);
520
0
        mesh_state_delete(&s->s);
521
0
        return;
522
0
      }
523
0
    }
524
525
#ifdef UNBOUND_DEBUG
526
    n =
527
#else
528
0
    (void)
529
0
#endif
530
0
    rbtree_insert(&mesh->all, &s->node);
531
0
    log_assert(n != NULL);
532
0
    added = 1;
533
0
  }
534
0
  if(!s->reply_list && !s->cb_list) {
535
0
    was_noreply = 1;
536
0
    if(s->super_set.count == 0) {
537
0
      was_detached = 1;
538
0
    }
539
0
  }
540
  /* add reply to s */
541
0
  if(!mesh_state_add_reply(s, edns, rep, qid, qflags, qinfo)) {
542
0
    log_err("mesh_new_client: out of memory; SERVFAIL");
543
0
    goto servfail_mem;
544
0
  }
545
0
  if(rep->c->tcp_req_info) {
546
0
    if(!tcp_req_info_add_meshstate(rep->c->tcp_req_info, mesh, s)) {
547
0
      log_err("mesh_new_client: out of memory add tcpreqinfo");
548
0
      goto servfail_mem;
549
0
    }
550
0
  }
551
0
  if(rep->c->use_h2) {
552
0
    http2_stream_add_meshstate(rep->c->h2_stream, mesh, s);
553
0
  }
554
  /* add serve expired timer if required and not already there */
555
0
  if(timeout && !mesh_serve_expired_init(s, timeout)) {
556
0
    log_err("mesh_new_client: out of memory initializing serve expired");
557
0
    goto servfail_mem;
558
0
  }
559
#ifdef USE_CACHEDB
560
  if(!timeout && mesh->env->cfg->serve_expired &&
561
    !mesh->env->cfg->serve_expired_client_timeout &&
562
    (mesh->env->cachedb_enabled &&
563
     mesh->env->cfg->cachedb_check_when_serve_expired)) {
564
    if(!mesh_serve_expired_init(s, -1)) {
565
      log_err("mesh_new_client: out of memory initializing serve expired");
566
      goto servfail_mem;
567
    }
568
  }
569
#endif
570
0
  infra_wait_limit_inc(mesh->env->infra_cache, rep, *mesh->env->now,
571
0
    mesh->env->cfg);
572
  /* update statistics */
573
0
  if(was_detached) {
574
0
    log_assert(mesh->num_detached_states > 0);
575
0
    mesh->num_detached_states--;
576
0
  }
577
0
  if(was_noreply) {
578
0
    mesh->num_reply_states ++;
579
0
  }
580
0
  mesh->num_reply_addrs++;
581
0
  if(s->list_select == mesh_no_list) {
582
    /* move to either the forever or the jostle_list */
583
0
    if(mesh->num_forever_states < mesh->max_forever_states) {
584
0
      mesh->num_forever_states ++;
585
0
      mesh_list_insert(s, &mesh->forever_first,
586
0
        &mesh->forever_last);
587
0
      s->list_select = mesh_forever_list;
588
0
    } else {
589
0
      mesh_list_insert(s, &mesh->jostle_first,
590
0
        &mesh->jostle_last);
591
0
      s->list_select = mesh_jostle_list;
592
0
    }
593
0
  }
594
0
  if(added)
595
0
    mesh_run(mesh, s, module_event_new, NULL);
596
0
  return;
597
598
0
servfail_mem:
599
0
  if(!inplace_cb_reply_servfail_call(mesh->env, qinfo, &s->s,
600
0
    NULL, LDNS_RCODE_SERVFAIL, edns, rep, mesh->env->scratch, mesh->env->now_tv))
601
0
      edns->opt_list_inplace_cb_out = NULL;
602
0
  error_encode(r_buffer, LDNS_RCODE_SERVFAIL,
603
0
    qinfo, qid, qflags, edns);
604
0
  if(rep->c->use_h2)
605
0
    http2_stream_remove_mesh_state(rep->c->h2_stream);
606
0
  comm_point_send_reply(rep);
607
0
  if(added)
608
0
    mesh_state_delete(&s->s);
609
0
  return;
610
0
}
611
612
int
613
mesh_new_callback(struct mesh_area* mesh, struct query_info* qinfo,
614
  uint16_t qflags, struct edns_data* edns, sldns_buffer* buf,
615
  uint16_t qid, mesh_cb_func_type cb, void* cb_arg, int rpz_passthru)
616
0
{
617
0
  struct mesh_state* s = NULL;
618
0
  int unique = unique_mesh_state(edns->opt_list_in, mesh->env);
619
0
  int timeout = mesh->env->cfg->serve_expired?
620
0
    mesh->env->cfg->serve_expired_client_timeout:0;
621
0
  int was_detached = 0;
622
0
  int was_noreply = 0;
623
0
  int added = 0;
624
0
  uint16_t mesh_flags = qflags&(BIT_RD|BIT_CD);
625
0
  if(!unique)
626
0
    s = mesh_area_find(mesh, NULL, qinfo, mesh_flags, 0, 0);
627
628
  /* there are no limits on the number of callbacks */
629
630
  /* see if it already exists, if not, create one */
631
0
  if(!s) {
632
#ifdef UNBOUND_DEBUG
633
    struct rbnode_type* n;
634
#endif
635
0
    s = mesh_state_create(mesh->env, qinfo, NULL,
636
0
      mesh_flags, 0, 0);
637
0
    if(!s) {
638
0
      return 0;
639
0
    }
640
    /* set detached (it is now) */
641
0
    mesh->num_detached_states++;
642
0
    if(unique)
643
0
      mesh_state_make_unique(s);
644
0
    s->s.rpz_passthru = rpz_passthru;
645
0
    if(edns->opt_list_in) {
646
0
      s->s.edns_opts_front_in = edns_opt_copy_region(edns->opt_list_in,
647
0
        s->s.region);
648
0
      if(!s->s.edns_opts_front_in) {
649
0
        mesh_state_delete(&s->s);
650
0
        return 0;
651
0
      }
652
0
    }
653
#ifdef UNBOUND_DEBUG
654
    n =
655
#else
656
0
    (void)
657
0
#endif
658
0
    rbtree_insert(&mesh->all, &s->node);
659
0
    log_assert(n != NULL);
660
0
    added = 1;
661
0
  }
662
0
  if(!s->reply_list && !s->cb_list) {
663
0
    was_noreply = 1;
664
0
    if(s->super_set.count == 0) {
665
0
      was_detached = 1;
666
0
    }
667
0
  }
668
  /* add reply to s */
669
0
  if(!mesh_state_add_cb(s, edns, buf, cb, cb_arg, qid, qflags)) {
670
0
    if(added)
671
0
      mesh_state_delete(&s->s);
672
0
    return 0;
673
0
  }
674
  /* add serve expired timer if not already there */
675
0
  if(timeout && !mesh_serve_expired_init(s, timeout)) {
676
0
    if(added)
677
0
      mesh_state_delete(&s->s);
678
0
    return 0;
679
0
  }
680
#ifdef USE_CACHEDB
681
  if(!timeout && mesh->env->cfg->serve_expired &&
682
    !mesh->env->cfg->serve_expired_client_timeout &&
683
    (mesh->env->cachedb_enabled &&
684
     mesh->env->cfg->cachedb_check_when_serve_expired)) {
685
    if(!mesh_serve_expired_init(s, -1)) {
686
      if(added)
687
        mesh_state_delete(&s->s);
688
      return 0;
689
    }
690
  }
691
#endif
692
  /* update statistics */
693
0
  if(was_detached) {
694
0
    log_assert(mesh->num_detached_states > 0);
695
0
    mesh->num_detached_states--;
696
0
  }
697
0
  if(was_noreply) {
698
0
    mesh->num_reply_states ++;
699
0
  }
700
0
  mesh->num_reply_addrs++;
701
0
  if(added)
702
0
    mesh_run(mesh, s, module_event_new, NULL);
703
0
  return 1;
704
0
}
705
706
/* Internal backend routine of mesh_new_prefetch().  It takes one additional
707
 * parameter, 'run', which controls whether to run the prefetch state
708
 * immediately.  When this function is called internally 'run' could be
709
 * 0 (false), in which case the new state is only made runnable so it
710
 * will not be run recursively on top of the current state. */
711
static void mesh_schedule_prefetch(struct mesh_area* mesh,
712
  struct query_info* qinfo, uint16_t qflags, time_t leeway, int run,
713
  int rpz_passthru)
714
0
{
715
  /* Explicitly set the BIT_RD regardless of the client's flags. This is
716
   * for a prefetch query (no client attached) but it needs to be treated
717
   * as a recursion query. */
718
0
  uint16_t mesh_flags = BIT_RD|(qflags&BIT_CD);
719
0
  struct mesh_state* s = mesh_area_find(mesh, NULL, qinfo,
720
0
    mesh_flags, 0, 0);
721
#ifdef UNBOUND_DEBUG
722
  struct rbnode_type* n;
723
#endif
724
  /* already exists, and for a different purpose perhaps.
725
   * if mesh_no_list, keep it that way. */
726
0
  if(s) {
727
    /* make it ignore the cache from now on */
728
0
    if(!s->s.blacklist)
729
0
      sock_list_insert(&s->s.blacklist, NULL, 0, s->s.region);
730
0
    if(s->s.prefetch_leeway < leeway)
731
0
      s->s.prefetch_leeway = leeway;
732
0
    return;
733
0
  }
734
0
  if(!mesh_make_new_space(mesh, NULL)) {
735
0
    verbose(VERB_ALGO, "Too many queries. dropped prefetch.");
736
0
    mesh->stats_dropped ++;
737
0
    return;
738
0
  }
739
740
0
  s = mesh_state_create(mesh->env, qinfo, NULL, mesh_flags, 0, 0);
741
0
  if(!s) {
742
0
    log_err("prefetch mesh_state_create: out of memory");
743
0
    return;
744
0
  }
745
#ifdef UNBOUND_DEBUG
746
  n =
747
#else
748
0
  (void)
749
0
#endif
750
0
  rbtree_insert(&mesh->all, &s->node);
751
0
  log_assert(n != NULL);
752
  /* set detached (it is now) */
753
0
  mesh->num_detached_states++;
754
  /* make it ignore the cache */
755
0
  sock_list_insert(&s->s.blacklist, NULL, 0, s->s.region);
756
0
  s->s.prefetch_leeway = leeway;
757
758
0
  if(s->list_select == mesh_no_list) {
759
    /* move to either the forever or the jostle_list */
760
0
    if(mesh->num_forever_states < mesh->max_forever_states) {
761
0
      mesh->num_forever_states ++;
762
0
      mesh_list_insert(s, &mesh->forever_first,
763
0
        &mesh->forever_last);
764
0
      s->list_select = mesh_forever_list;
765
0
    } else {
766
0
      mesh_list_insert(s, &mesh->jostle_first,
767
0
        &mesh->jostle_last);
768
0
      s->list_select = mesh_jostle_list;
769
0
    }
770
0
  }
771
0
  s->s.rpz_passthru = rpz_passthru;
772
773
0
  if(!run) {
774
#ifdef UNBOUND_DEBUG
775
    n =
776
#else
777
0
    (void)
778
0
#endif
779
0
    rbtree_insert(&mesh->run, &s->run_node);
780
0
    log_assert(n != NULL);
781
0
    return;
782
0
  }
783
784
0
  mesh_run(mesh, s, module_event_new, NULL);
785
0
}
786
787
#ifdef CLIENT_SUBNET
788
/* Same logic as mesh_schedule_prefetch but tailored to the subnet module logic
789
 * like passing along the comm_reply info. This will be faked into an EDNS
790
 * option for processing by the subnet module if the client has not already
791
 * attached its own ECS data. */
792
static void mesh_schedule_prefetch_subnet(struct mesh_area* mesh,
793
  struct query_info* qinfo, uint16_t qflags, time_t leeway, int run,
794
  int rpz_passthru, struct sockaddr_storage* addr, struct edns_option* edns_list)
795
{
796
  struct mesh_state* s = NULL;
797
  struct edns_option* opt = NULL;
798
#ifdef UNBOUND_DEBUG
799
  struct rbnode_type* n;
800
#endif
801
  /* Explicitly set the BIT_RD regardless of the client's flags. This is
802
   * for a prefetch query (no client attached) but it needs to be treated
803
   * as a recursion query. */
804
  uint16_t mesh_flags = BIT_RD|(qflags&BIT_CD);
805
  if(!mesh_make_new_space(mesh, NULL)) {
806
    verbose(VERB_ALGO, "Too many queries. dropped prefetch.");
807
    mesh->stats_dropped ++;
808
    return;
809
  }
810
811
  s = mesh_state_create(mesh->env, qinfo, NULL, mesh_flags, 0, 0);
812
  if(!s) {
813
    log_err("prefetch_subnet mesh_state_create: out of memory");
814
    return;
815
  }
816
  mesh_state_make_unique(s);
817
818
  opt = edns_opt_list_find(edns_list, mesh->env->cfg->client_subnet_opcode);
819
  if(opt) {
820
    /* Use the client's ECS data */
821
    if(!edns_opt_list_append(&s->s.edns_opts_front_in, opt->opt_code,
822
      opt->opt_len, opt->opt_data, s->s.region)) {
823
      log_err("prefetch_subnet edns_opt_list_append: out of memory");
824
      return;
825
    }
826
  } else {
827
    /* Store the client's address. Later in the subnet module,
828
     * it is decided whether to include an ECS option or not.
829
     */
830
    s->s.client_addr =  *addr;
831
  }
832
#ifdef UNBOUND_DEBUG
833
  n =
834
#else
835
  (void)
836
#endif
837
  rbtree_insert(&mesh->all, &s->node);
838
  log_assert(n != NULL);
839
  /* set detached (it is now) */
840
  mesh->num_detached_states++;
841
  /* make it ignore the cache */
842
  sock_list_insert(&s->s.blacklist, NULL, 0, s->s.region);
843
  s->s.prefetch_leeway = leeway;
844
845
  if(s->list_select == mesh_no_list) {
846
    /* move to either the forever or the jostle_list */
847
    if(mesh->num_forever_states < mesh->max_forever_states) {
848
      mesh->num_forever_states ++;
849
      mesh_list_insert(s, &mesh->forever_first,
850
        &mesh->forever_last);
851
      s->list_select = mesh_forever_list;
852
    } else {
853
      mesh_list_insert(s, &mesh->jostle_first,
854
        &mesh->jostle_last);
855
      s->list_select = mesh_jostle_list;
856
    }
857
  }
858
  s->s.rpz_passthru = rpz_passthru;
859
860
  if(!run) {
861
#ifdef UNBOUND_DEBUG
862
    n =
863
#else
864
    (void)
865
#endif
866
    rbtree_insert(&mesh->run, &s->run_node);
867
    log_assert(n != NULL);
868
    return;
869
  }
870
871
  mesh_run(mesh, s, module_event_new, NULL);
872
}
873
#endif /* CLIENT_SUBNET */
874
875
void mesh_new_prefetch(struct mesh_area* mesh, struct query_info* qinfo,
876
  uint16_t qflags, time_t leeway, int rpz_passthru,
877
  struct sockaddr_storage* addr, struct edns_option* opt_list)
878
0
{
879
0
  (void)addr;
880
0
  (void)opt_list;
881
#ifdef CLIENT_SUBNET
882
  if(addr)
883
    mesh_schedule_prefetch_subnet(mesh, qinfo, qflags, leeway, 1,
884
      rpz_passthru, addr, opt_list);
885
  else
886
#endif
887
0
    mesh_schedule_prefetch(mesh, qinfo, qflags, leeway, 1,
888
0
      rpz_passthru);
889
0
}
890
891
void mesh_report_reply(struct mesh_area* mesh, struct outbound_entry* e,
892
        struct comm_reply* reply, int what)
893
0
{
894
0
  enum module_ev event = module_event_reply;
895
0
  e->qstate->reply = reply;
896
0
  if(what != NETEVENT_NOERROR) {
897
0
    event = module_event_noreply;
898
0
    if(what == NETEVENT_CAPSFAIL)
899
0
      event = module_event_capsfail;
900
0
  }
901
0
  mesh_run(mesh, e->qstate->mesh_info, event, e);
902
0
}
903
904
/** copy strlist to region */
905
static struct config_strlist*
906
cfg_region_strlist_copy(struct regional* region, struct config_strlist* list)
907
0
{
908
0
  struct config_strlist* result = NULL, *last = NULL, *s = list;
909
0
  while(s) {
910
0
    struct config_strlist* n = regional_alloc_zero(region,
911
0
      sizeof(*n));
912
0
    if(!n)
913
0
      return NULL;
914
0
    n->str = regional_strdup(region, s->str);
915
0
    if(!n->str)
916
0
      return NULL;
917
0
    if(last)
918
0
      last->next = n;
919
0
    else  result = n;
920
0
    last = n;
921
0
    s = s->next;
922
0
  }
923
0
  return result;
924
0
}
925
926
/** Copy the client info to the query region. */
927
static struct respip_client_info*
928
mesh_copy_client_info(struct regional* region, struct respip_client_info* cinfo)
929
0
{
930
0
  size_t i;
931
0
  struct respip_client_info* client_info;
932
0
  client_info = regional_alloc_init(region, cinfo, sizeof(*cinfo));
933
0
  if(!client_info)
934
0
    return NULL;
935
  /* Copy the client_info so that if the configuration changes,
936
   * then the data stays valid. */
937
0
  if(cinfo->taglist) {
938
0
    client_info->taglist = regional_alloc_init(region, cinfo->taglist,
939
0
      cinfo->taglen);
940
0
    if(!client_info->taglist)
941
0
      return NULL;
942
0
  }
943
0
  if(cinfo->tag_actions) {
944
0
    client_info->tag_actions = regional_alloc_init(region, cinfo->tag_actions,
945
0
      cinfo->tag_actions_size);
946
0
    if(!client_info->tag_actions)
947
0
      return NULL;
948
0
  }
949
0
  if(cinfo->tag_datas) {
950
0
    client_info->tag_datas = regional_alloc_zero(region,
951
0
      sizeof(struct config_strlist*)*cinfo->tag_datas_size);
952
0
    if(!client_info->tag_datas)
953
0
      return NULL;
954
0
    for(i=0; i<cinfo->tag_datas_size; i++) {
955
0
      if(cinfo->tag_datas[i]) {
956
0
        client_info->tag_datas[i] = cfg_region_strlist_copy(
957
0
          region, cinfo->tag_datas[i]);
958
0
        if(!client_info->tag_datas[i])
959
0
          return NULL;
960
0
      }
961
0
    }
962
0
  }
963
0
  if(cinfo->view) {
964
    /* Do not copy the view pointer but store a name instead.
965
     * The name is looked up later when done, this means that
966
     * the view tree can be changed, by reloads. */
967
0
    client_info->view = NULL;
968
0
    client_info->view_name = regional_strdup(region,
969
0
      cinfo->view->name);
970
0
    if(!client_info->view_name)
971
0
      return NULL;
972
0
  }
973
0
  return client_info;
974
0
}
975
976
struct mesh_state*
977
mesh_state_create(struct module_env* env, struct query_info* qinfo,
978
  struct respip_client_info* cinfo, uint16_t qflags, int prime,
979
  int valrec)
980
0
{
981
0
  struct regional* region = alloc_reg_obtain(env->alloc);
982
0
  struct mesh_state* mstate;
983
0
  int i;
984
0
  if(!region)
985
0
    return NULL;
986
0
  mstate = (struct mesh_state*)regional_alloc(region,
987
0
    sizeof(struct mesh_state));
988
0
  if(!mstate) {
989
0
    alloc_reg_release(env->alloc, region);
990
0
    return NULL;
991
0
  }
992
0
  memset(mstate, 0, sizeof(*mstate));
993
0
  mstate->node = *RBTREE_NULL;
994
0
  mstate->run_node = *RBTREE_NULL;
995
0
  mstate->node.key = mstate;
996
0
  mstate->run_node.key = mstate;
997
0
  mstate->reply_list = NULL;
998
0
  mstate->list_select = mesh_no_list;
999
0
  mstate->replies_sent = 0;
1000
0
  rbtree_init(&mstate->super_set, &mesh_state_ref_compare);
1001
0
  rbtree_init(&mstate->sub_set, &mesh_state_ref_compare);
1002
0
  mstate->num_activated = 0;
1003
0
  mstate->unique = NULL;
1004
  /* init module qstate */
1005
0
  mstate->s.qinfo.qtype = qinfo->qtype;
1006
0
  mstate->s.qinfo.qclass = qinfo->qclass;
1007
0
  mstate->s.qinfo.local_alias = NULL;
1008
0
  mstate->s.qinfo.qname_len = qinfo->qname_len;
1009
0
  mstate->s.qinfo.qname = regional_alloc_init(region, qinfo->qname,
1010
0
    qinfo->qname_len);
1011
0
  if(!mstate->s.qinfo.qname) {
1012
0
    alloc_reg_release(env->alloc, region);
1013
0
    return NULL;
1014
0
  }
1015
0
  if(cinfo) {
1016
0
    mstate->s.client_info = mesh_copy_client_info(region, cinfo);
1017
0
    if(!mstate->s.client_info) {
1018
0
      alloc_reg_release(env->alloc, region);
1019
0
      return NULL;
1020
0
    }
1021
0
  }
1022
  /* remove all weird bits from qflags */
1023
0
  mstate->s.query_flags = (qflags & (BIT_RD|BIT_CD));
1024
0
  mstate->s.is_priming = prime;
1025
0
  mstate->s.is_valrec = valrec;
1026
0
  mstate->s.reply = NULL;
1027
0
  mstate->s.region = region;
1028
0
  mstate->s.curmod = 0;
1029
0
  mstate->s.return_msg = 0;
1030
0
  mstate->s.return_rcode = LDNS_RCODE_NOERROR;
1031
0
  mstate->s.env = env;
1032
0
  mstate->s.mesh_info = mstate;
1033
0
  mstate->s.prefetch_leeway = 0;
1034
0
  mstate->s.serve_expired_data = NULL;
1035
0
  mstate->s.no_cache_lookup = 0;
1036
0
  mstate->s.no_cache_store = 0;
1037
0
  mstate->s.need_refetch = 0;
1038
0
  mstate->s.was_ratelimited = 0;
1039
0
  mstate->s.qstarttime = *env->now;
1040
1041
  /* init modules */
1042
0
  for(i=0; i<env->mesh->mods.num; i++) {
1043
0
    mstate->s.minfo[i] = NULL;
1044
0
    mstate->s.ext_state[i] = module_state_initial;
1045
0
  }
1046
  /* init edns option lists */
1047
0
  mstate->s.edns_opts_front_in = NULL;
1048
0
  mstate->s.edns_opts_back_out = NULL;
1049
0
  mstate->s.edns_opts_back_in = NULL;
1050
0
  mstate->s.edns_opts_front_out = NULL;
1051
1052
0
  return mstate;
1053
0
}
1054
1055
void
1056
mesh_state_make_unique(struct mesh_state* mstate)
1057
0
{
1058
0
  mstate->unique = mstate;
1059
0
}
1060
1061
void
1062
mesh_state_cleanup(struct mesh_state* mstate)
1063
0
{
1064
0
  struct mesh_area* mesh;
1065
0
  int i;
1066
0
  if(!mstate)
1067
0
    return;
1068
0
  mesh = mstate->s.env->mesh;
1069
  /* Stop and delete the serve expired timer */
1070
0
  if(mstate->s.serve_expired_data && mstate->s.serve_expired_data->timer) {
1071
0
    comm_timer_delete(mstate->s.serve_expired_data->timer);
1072
0
    mstate->s.serve_expired_data->timer = NULL;
1073
0
  }
1074
  /* drop unsent replies */
1075
0
  if(!mstate->replies_sent) {
1076
0
    struct mesh_reply* rep = mstate->reply_list;
1077
0
    struct mesh_cb* cb;
1078
    /* in tcp_req_info, the mstates linked are removed, but
1079
     * the reply_list is now NULL, so the remove-from-empty-list
1080
     * takes no time and also it does not do the mesh accounting */
1081
0
    mstate->reply_list = NULL;
1082
0
    for(; rep; rep=rep->next) {
1083
0
      infra_wait_limit_dec(mesh->env->infra_cache,
1084
0
        &rep->query_reply, mesh->env->cfg);
1085
0
      if(rep->query_reply.c->use_h2)
1086
0
        http2_stream_remove_mesh_state(rep->h2_stream);
1087
0
      comm_point_drop_reply(&rep->query_reply);
1088
0
      log_assert(mesh->num_reply_addrs > 0);
1089
0
      mesh->num_reply_addrs--;
1090
0
    }
1091
0
    while((cb = mstate->cb_list)!=NULL) {
1092
0
      mstate->cb_list = cb->next;
1093
0
      fptr_ok(fptr_whitelist_mesh_cb(cb->cb));
1094
0
      (*cb->cb)(cb->cb_arg, LDNS_RCODE_SERVFAIL, NULL,
1095
0
        sec_status_unchecked, NULL, 0);
1096
0
      log_assert(mesh->num_reply_addrs > 0);
1097
0
      mesh->num_reply_addrs--;
1098
0
    }
1099
0
  }
1100
1101
  /* de-init modules */
1102
0
  for(i=0; i<mesh->mods.num; i++) {
1103
0
    fptr_ok(fptr_whitelist_mod_clear(mesh->mods.mod[i]->clear));
1104
0
    (*mesh->mods.mod[i]->clear)(&mstate->s, i);
1105
0
    mstate->s.minfo[i] = NULL;
1106
0
    mstate->s.ext_state[i] = module_finished;
1107
0
  }
1108
0
  alloc_reg_release(mstate->s.env->alloc, mstate->s.region);
1109
0
}
1110
1111
void
1112
mesh_state_delete(struct module_qstate* qstate)
1113
0
{
1114
0
  struct mesh_area* mesh;
1115
0
  struct mesh_state_ref* super, ref;
1116
0
  struct mesh_state* mstate;
1117
0
  if(!qstate)
1118
0
    return;
1119
0
  mstate = qstate->mesh_info;
1120
0
  mesh = mstate->s.env->mesh;
1121
0
  mesh_detach_subs(&mstate->s);
1122
0
  if(mstate->list_select == mesh_forever_list) {
1123
0
    mesh->num_forever_states --;
1124
0
    mesh_list_remove(mstate, &mesh->forever_first,
1125
0
      &mesh->forever_last);
1126
0
  } else if(mstate->list_select == mesh_jostle_list) {
1127
0
    mesh_list_remove(mstate, &mesh->jostle_first,
1128
0
      &mesh->jostle_last);
1129
0
  }
1130
0
  if(!mstate->reply_list && !mstate->cb_list
1131
0
    && mstate->super_set.count == 0) {
1132
0
    log_assert(mesh->num_detached_states > 0);
1133
0
    mesh->num_detached_states--;
1134
0
  }
1135
0
  if(mstate->reply_list || mstate->cb_list) {
1136
0
    log_assert(mesh->num_reply_states > 0);
1137
0
    mesh->num_reply_states--;
1138
0
  }
1139
0
  ref.node.key = &ref;
1140
0
  ref.s = mstate;
1141
0
  RBTREE_FOR(super, struct mesh_state_ref*, &mstate->super_set) {
1142
0
    (void)rbtree_delete(&super->s->sub_set, &ref);
1143
0
  }
1144
0
  (void)rbtree_delete(&mesh->run, mstate);
1145
0
  (void)rbtree_delete(&mesh->all, mstate);
1146
0
  mesh_state_cleanup(mstate);
1147
0
}
1148
1149
/** helper recursive rbtree find routine */
1150
static int
1151
find_in_subsub(struct mesh_state* m, struct mesh_state* tofind, size_t *c)
1152
0
{
1153
0
  struct mesh_state_ref* r;
1154
0
  if((*c)++ > MESH_MAX_SUBSUB)
1155
0
    return 1;
1156
0
  RBTREE_FOR(r, struct mesh_state_ref*, &m->sub_set) {
1157
0
    if(r->s == tofind || find_in_subsub(r->s, tofind, c))
1158
0
      return 1;
1159
0
  }
1160
0
  return 0;
1161
0
}
1162
1163
/** find cycle for already looked up mesh_state */
1164
static int
1165
mesh_detect_cycle_found(struct module_qstate* qstate, struct mesh_state* dep_m)
1166
0
{
1167
0
  struct mesh_state* cyc_m = qstate->mesh_info;
1168
0
  size_t counter = 0;
1169
0
  log_assert(dep_m);
1170
0
  if(dep_m == cyc_m || find_in_subsub(dep_m, cyc_m, &counter)) {
1171
0
    if(counter > MESH_MAX_SUBSUB)
1172
0
      return 2;
1173
0
    return 1;
1174
0
  }
1175
0
  return 0;
1176
0
}
1177
1178
void mesh_detach_subs(struct module_qstate* qstate)
1179
0
{
1180
0
  struct mesh_area* mesh = qstate->env->mesh;
1181
0
  struct mesh_state_ref* ref, lookup;
1182
#ifdef UNBOUND_DEBUG
1183
  struct rbnode_type* n;
1184
#endif
1185
0
  lookup.node.key = &lookup;
1186
0
  lookup.s = qstate->mesh_info;
1187
0
  RBTREE_FOR(ref, struct mesh_state_ref*, &qstate->mesh_info->sub_set) {
1188
#ifdef UNBOUND_DEBUG
1189
    n =
1190
#else
1191
0
    (void)
1192
0
#endif
1193
0
    rbtree_delete(&ref->s->super_set, &lookup);
1194
0
    log_assert(n != NULL); /* must have been present */
1195
0
    if(!ref->s->reply_list && !ref->s->cb_list
1196
0
      && ref->s->super_set.count == 0) {
1197
0
      mesh->num_detached_states++;
1198
0
      log_assert(mesh->num_detached_states +
1199
0
        mesh->num_reply_states <= mesh->all.count);
1200
0
    }
1201
0
  }
1202
0
  rbtree_init(&qstate->mesh_info->sub_set, &mesh_state_ref_compare);
1203
0
}
1204
1205
int mesh_add_sub(struct module_qstate* qstate, struct query_info* qinfo,
1206
  struct respip_client_info* cinfo, uint16_t qflags, int prime,
1207
  int valrec, struct module_qstate** newq, struct mesh_state** sub)
1208
0
{
1209
  /* find it, if not, create it */
1210
0
  struct mesh_area* mesh = qstate->env->mesh;
1211
0
  *sub = mesh_area_find(mesh, cinfo, qinfo, qflags, prime, valrec);
1212
0
  if(!*sub) {
1213
#ifdef UNBOUND_DEBUG
1214
    struct rbnode_type* n;
1215
#endif
1216
    /* create a new one */
1217
0
    *sub = mesh_state_create(qstate->env, qinfo, cinfo, qflags,
1218
0
      prime, valrec);
1219
0
    if(!*sub) {
1220
0
      log_err("mesh_attach_sub: out of memory");
1221
0
      return 0;
1222
0
    }
1223
#ifdef UNBOUND_DEBUG
1224
    n =
1225
#else
1226
0
    (void)
1227
0
#endif
1228
0
    rbtree_insert(&mesh->all, &(*sub)->node);
1229
0
    log_assert(n != NULL);
1230
    /* set detached (it is now) */
1231
0
    mesh->num_detached_states++;
1232
    /* set new query state to run */
1233
#ifdef UNBOUND_DEBUG
1234
    n =
1235
#else
1236
0
    (void)
1237
0
#endif
1238
0
    rbtree_insert(&mesh->run, &(*sub)->run_node);
1239
0
    log_assert(n != NULL);
1240
0
    *newq = &(*sub)->s;
1241
0
  } else {
1242
0
    *newq = NULL;
1243
0
    if(mesh_detect_cycle_found(qstate, *sub)) {
1244
0
      verbose(VERB_ALGO, "attach failed, cycle detected");
1245
0
      return 0;
1246
0
    }
1247
0
  }
1248
0
  return 1;
1249
0
}
1250
1251
int mesh_attach_sub(struct module_qstate* qstate, struct query_info* qinfo,
1252
  struct respip_client_info* cinfo, uint16_t qflags, int prime,
1253
  int valrec, struct module_qstate** newq)
1254
0
{
1255
0
  struct mesh_area* mesh = qstate->env->mesh;
1256
0
  struct mesh_state* sub = NULL;
1257
0
  int was_detached;
1258
0
  if(!mesh_add_sub(qstate, qinfo, cinfo, qflags, prime, valrec, newq,
1259
0
    &sub))
1260
0
    return 0;
1261
0
  was_detached = (sub->super_set.count == 0);
1262
0
  if(!mesh_state_attachment(qstate->mesh_info, sub))
1263
0
    return 0;
1264
  /* if it was a duplicate  attachment, the count was not zero before */
1265
0
  if(!sub->reply_list && !sub->cb_list && was_detached &&
1266
0
    sub->super_set.count == 1) {
1267
    /* it used to be detached, before this one got added */
1268
0
    log_assert(mesh->num_detached_states > 0);
1269
0
    mesh->num_detached_states--;
1270
0
  }
1271
  /* *newq will be run when inited after the current module stops */
1272
0
  return 1;
1273
0
}
1274
1275
int mesh_state_attachment(struct mesh_state* super, struct mesh_state* sub)
1276
0
{
1277
#ifdef UNBOUND_DEBUG
1278
  struct rbnode_type* n;
1279
#endif
1280
0
  struct mesh_state_ref* subref; /* points to sub, inserted in super */
1281
0
  struct mesh_state_ref* superref; /* points to super, inserted in sub */
1282
0
  if( !(subref = regional_alloc(super->s.region,
1283
0
    sizeof(struct mesh_state_ref))) ||
1284
0
    !(superref = regional_alloc(sub->s.region,
1285
0
    sizeof(struct mesh_state_ref))) ) {
1286
0
    log_err("mesh_state_attachment: out of memory");
1287
0
    return 0;
1288
0
  }
1289
0
  superref->node.key = superref;
1290
0
  superref->s = super;
1291
0
  subref->node.key = subref;
1292
0
  subref->s = sub;
1293
0
  if(!rbtree_insert(&sub->super_set, &superref->node)) {
1294
    /* this should not happen, iterator and validator do not
1295
     * attach subqueries that are identical. */
1296
    /* already attached, we are done, nothing todo.
1297
     * since superref and subref already allocated in region,
1298
     * we cannot free them */
1299
0
    return 1;
1300
0
  }
1301
#ifdef UNBOUND_DEBUG
1302
  n =
1303
#else
1304
0
  (void)
1305
0
#endif
1306
0
  rbtree_insert(&super->sub_set, &subref->node);
1307
0
  log_assert(n != NULL); /* we checked above if statement, the reverse
1308
    administration should not fail now, unless they are out of sync */
1309
0
  return 1;
1310
0
}
1311
1312
/**
1313
 * callback results to mesh cb entry
1314
 * @param m: mesh state to send it for.
1315
 * @param rcode: if not 0, error code.
1316
 * @param rep: reply to send (or NULL if rcode is set).
1317
 * @param r: callback entry
1318
 * @param start_time: the time to pass to callback functions, it is 0 or
1319
 *  a value from one of the packets if the mesh state had packets.
1320
 */
1321
static void
1322
mesh_do_callback(struct mesh_state* m, int rcode, struct reply_info* rep,
1323
  struct mesh_cb* r, struct timeval* start_time)
1324
0
{
1325
0
  int secure;
1326
0
  char* reason = NULL;
1327
0
  int was_ratelimited = m->s.was_ratelimited;
1328
  /* bogus messages are not made into servfail, sec_status passed
1329
   * to the callback function */
1330
0
  if(rep && rep->security == sec_status_secure)
1331
0
    secure = 1;
1332
0
  else  secure = 0;
1333
0
  if(!rep && rcode == LDNS_RCODE_NOERROR)
1334
0
    rcode = LDNS_RCODE_SERVFAIL;
1335
0
  if(!rcode && rep && (rep->security == sec_status_bogus ||
1336
0
    rep->security == sec_status_secure_sentinel_fail)) {
1337
0
    if(!(reason = errinf_to_str_bogus(&m->s, NULL)))
1338
0
      rcode = LDNS_RCODE_SERVFAIL;
1339
0
  }
1340
  /* send the reply */
1341
0
  if(rcode) {
1342
0
    if(rcode == LDNS_RCODE_SERVFAIL) {
1343
0
      if(!inplace_cb_reply_servfail_call(m->s.env, &m->s.qinfo, &m->s,
1344
0
        rep, rcode, &r->edns, NULL, m->s.region, start_time))
1345
0
          r->edns.opt_list_inplace_cb_out = NULL;
1346
0
    } else {
1347
0
      if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep, rcode,
1348
0
        &r->edns, NULL, m->s.region, start_time))
1349
0
          r->edns.opt_list_inplace_cb_out = NULL;
1350
0
    }
1351
0
    fptr_ok(fptr_whitelist_mesh_cb(r->cb));
1352
0
    (*r->cb)(r->cb_arg, rcode, r->buf, sec_status_unchecked, NULL,
1353
0
      was_ratelimited);
1354
0
  } else {
1355
0
    size_t udp_size = r->edns.udp_size;
1356
0
    sldns_buffer_clear(r->buf);
1357
0
    r->edns.edns_version = EDNS_ADVERTISED_VERSION;
1358
0
    r->edns.udp_size = EDNS_ADVERTISED_SIZE;
1359
0
    r->edns.ext_rcode = 0;
1360
0
    r->edns.bits &= EDNS_DO;
1361
0
    if(m->s.env->cfg->disable_edns_do && (r->edns.bits&EDNS_DO))
1362
0
      r->edns.edns_present = 0;
1363
1364
0
    if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep,
1365
0
      LDNS_RCODE_NOERROR, &r->edns, NULL, m->s.region, start_time) ||
1366
0
      !reply_info_answer_encode(&m->s.qinfo, rep, r->qid,
1367
0
      r->qflags, r->buf, 0, 1,
1368
0
      m->s.env->scratch, udp_size, &r->edns,
1369
0
      (int)(r->edns.bits & EDNS_DO), secure))
1370
0
    {
1371
0
      fptr_ok(fptr_whitelist_mesh_cb(r->cb));
1372
0
      (*r->cb)(r->cb_arg, LDNS_RCODE_SERVFAIL, r->buf,
1373
0
        sec_status_unchecked, NULL, 0);
1374
0
    } else {
1375
0
      fptr_ok(fptr_whitelist_mesh_cb(r->cb));
1376
0
      (*r->cb)(r->cb_arg, LDNS_RCODE_NOERROR, r->buf,
1377
0
        (rep?rep->security:sec_status_unchecked),
1378
0
        reason, was_ratelimited);
1379
0
    }
1380
0
  }
1381
0
  free(reason);
1382
0
  log_assert(m->s.env->mesh->num_reply_addrs > 0);
1383
0
  m->s.env->mesh->num_reply_addrs--;
1384
0
}
1385
1386
static inline int
1387
mesh_is_rpz_respip_tcponly_action(struct mesh_state const* m)
1388
0
{
1389
0
  struct respip_action_info const* respip_info = m->s.respip_action_info;
1390
0
  return (respip_info == NULL
1391
0
      ? 0
1392
0
      : (respip_info->rpz_used
1393
0
      && !respip_info->rpz_disabled
1394
0
      && respip_info->action == respip_truncate))
1395
0
    || m->s.tcp_required;
1396
0
}
1397
1398
static inline int
1399
mesh_is_udp(struct mesh_reply const* r)
1400
0
{
1401
0
  return r->query_reply.c->type == comm_udp;
1402
0
}
1403
1404
static inline void
1405
mesh_find_and_attach_ede_and_reason(struct mesh_state* m,
1406
  struct reply_info* rep, struct mesh_reply* r)
1407
0
{
1408
  /* OLD note:
1409
   * During validation the EDE code can be received via two
1410
   * code paths. One code path fills the reply_info EDE, and
1411
   * the other fills it in the errinf_strlist. These paths
1412
   * intersect at some points, but where is opaque due to
1413
   * the complexity of the validator. At the time of writing
1414
   * we make the choice to prefer the EDE from errinf_strlist
1415
   * but a compelling reason to do otherwise is just as valid
1416
   * NEW note:
1417
   * The compelling reason is that with caching support, the value
1418
   * in the reply_info is cached.
1419
   * The reason members of the reply_info struct should be
1420
   * updated as they are already cached. No reason to
1421
   * try and find the EDE information in errinf anymore.
1422
   */
1423
0
  if(rep->reason_bogus != LDNS_EDE_NONE) {
1424
0
    edns_opt_list_append_ede(&r->edns.opt_list_out,
1425
0
      m->s.region, rep->reason_bogus, rep->reason_bogus_str);
1426
0
  }
1427
0
}
1428
1429
/**
1430
 * Send reply to mesh reply entry
1431
 * @param m: mesh state to send it for.
1432
 * @param rcode: if not 0, error code.
1433
 * @param rep: reply to send (or NULL if rcode is set).
1434
 * @param r: reply entry
1435
 * @param r_buffer: buffer to use for reply entry.
1436
 * @param prev: previous reply, already has its answer encoded in buffer.
1437
 * @param prev_buffer: buffer for previous reply.
1438
 */
1439
static void
1440
mesh_send_reply(struct mesh_state* m, int rcode, struct reply_info* rep,
1441
  struct mesh_reply* r, struct sldns_buffer* r_buffer,
1442
  struct mesh_reply* prev, struct sldns_buffer* prev_buffer)
1443
0
{
1444
0
  struct timeval end_time;
1445
0
  struct timeval duration;
1446
0
  int secure;
1447
  /* briefly set the replylist to null in case the
1448
   * meshsendreply calls tcpreqinfo sendreply that
1449
   * comm_point_drops because of size, and then the
1450
   * null stops the mesh state remove and thus
1451
   * reply_list modification and accounting */
1452
0
  struct mesh_reply* rlist = m->reply_list;
1453
1454
  /* rpz: apply actions */
1455
0
  rcode = mesh_is_udp(r) && mesh_is_rpz_respip_tcponly_action(m)
1456
0
      ? (rcode|BIT_TC) : rcode;
1457
1458
  /* examine security status */
1459
0
  if(m->s.env->need_to_validate && (!(r->qflags&BIT_CD) ||
1460
0
    m->s.env->cfg->ignore_cd) && rep &&
1461
0
    (rep->security <= sec_status_bogus ||
1462
0
    rep->security == sec_status_secure_sentinel_fail)) {
1463
0
    rcode = LDNS_RCODE_SERVFAIL;
1464
0
    if(m->s.env->cfg->stat_extended)
1465
0
      m->s.env->mesh->ans_bogus++;
1466
0
  }
1467
0
  if(rep && rep->security == sec_status_secure)
1468
0
    secure = 1;
1469
0
  else  secure = 0;
1470
0
  if(!rep && rcode == LDNS_RCODE_NOERROR)
1471
0
    rcode = LDNS_RCODE_SERVFAIL;
1472
0
  if(r->query_reply.c->use_h2) {
1473
0
    r->query_reply.c->h2_stream = r->h2_stream;
1474
    /* Mesh reply won't exist for long anymore. Make it impossible
1475
     * for HTTP/2 stream to refer to mesh state, in case
1476
     * connection gets cleanup before HTTP/2 stream close. */
1477
0
    r->h2_stream->mesh_state = NULL;
1478
0
  }
1479
  /* send the reply */
1480
  /* We don't reuse the encoded answer if:
1481
   * - either the previous or current response has a local alias.  We could
1482
   *   compare the alias records and still reuse the previous answer if they
1483
   *   are the same, but that would be complicated and error prone for the
1484
   *   relatively minor case. So we err on the side of safety.
1485
   * - there are registered callback functions for the given rcode, as these
1486
   *   need to be called for each reply. */
1487
0
  if(((rcode != LDNS_RCODE_SERVFAIL &&
1488
0
      !m->s.env->inplace_cb_lists[inplace_cb_reply]) ||
1489
0
    (rcode == LDNS_RCODE_SERVFAIL &&
1490
0
      !m->s.env->inplace_cb_lists[inplace_cb_reply_servfail])) &&
1491
0
    prev && prev_buffer && prev->qflags == r->qflags &&
1492
0
    !prev->local_alias && !r->local_alias &&
1493
0
    prev->edns.edns_present == r->edns.edns_present &&
1494
0
    prev->edns.bits == r->edns.bits &&
1495
0
    prev->edns.udp_size == r->edns.udp_size &&
1496
0
    edns_opt_list_compare(prev->edns.opt_list_out, r->edns.opt_list_out) == 0 &&
1497
0
    edns_opt_list_compare(prev->edns.opt_list_inplace_cb_out, r->edns.opt_list_inplace_cb_out) == 0
1498
0
    ) {
1499
    /* if the previous reply is identical to this one, fix ID */
1500
0
    if(prev_buffer != r_buffer)
1501
0
      sldns_buffer_copy(r_buffer, prev_buffer);
1502
0
    sldns_buffer_write_at(r_buffer, 0, &r->qid, sizeof(uint16_t));
1503
0
    sldns_buffer_write_at(r_buffer, 12, r->qname,
1504
0
      m->s.qinfo.qname_len);
1505
0
    m->reply_list = NULL;
1506
0
    comm_point_send_reply(&r->query_reply);
1507
0
    m->reply_list = rlist;
1508
0
  } else if(rcode) {
1509
0
    m->s.qinfo.qname = r->qname;
1510
0
    m->s.qinfo.local_alias = r->local_alias;
1511
0
    if(rcode == LDNS_RCODE_SERVFAIL) {
1512
0
      if(!inplace_cb_reply_servfail_call(m->s.env, &m->s.qinfo, &m->s,
1513
0
        rep, rcode, &r->edns, &r->query_reply, m->s.region, &r->start_time))
1514
0
          r->edns.opt_list_inplace_cb_out = NULL;
1515
0
    } else {
1516
0
      if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep, rcode,
1517
0
        &r->edns, &r->query_reply, m->s.region, &r->start_time))
1518
0
          r->edns.opt_list_inplace_cb_out = NULL;
1519
0
    }
1520
    /* Send along EDE EDNS0 option when SERVFAILing; usually
1521
     * DNSSEC validation failures */
1522
    /* Since we are SERVFAILing here, CD bit and rep->security
1523
     * is already handled. */
1524
0
    if(m->s.env->cfg->ede && rep) {
1525
0
      mesh_find_and_attach_ede_and_reason(m, rep, r);
1526
0
    }
1527
0
    error_encode(r_buffer, rcode, &m->s.qinfo, r->qid,
1528
0
      r->qflags, &r->edns);
1529
0
    m->reply_list = NULL;
1530
0
    comm_point_send_reply(&r->query_reply);
1531
0
    m->reply_list = rlist;
1532
0
  } else {
1533
0
    size_t udp_size = r->edns.udp_size;
1534
0
    r->edns.edns_version = EDNS_ADVERTISED_VERSION;
1535
0
    r->edns.udp_size = EDNS_ADVERTISED_SIZE;
1536
0
    r->edns.ext_rcode = 0;
1537
0
    r->edns.bits &= EDNS_DO;
1538
0
    if(m->s.env->cfg->disable_edns_do && (r->edns.bits&EDNS_DO))
1539
0
      r->edns.edns_present = 0;
1540
0
    m->s.qinfo.qname = r->qname;
1541
0
    m->s.qinfo.local_alias = r->local_alias;
1542
1543
    /* Attach EDE without SERVFAIL if the validation failed.
1544
     * Need to explicitly check for rep->security otherwise failed
1545
     * validation paths may attach to a secure answer. */
1546
0
    if(m->s.env->cfg->ede && rep &&
1547
0
      (rep->security <= sec_status_bogus ||
1548
0
      rep->security == sec_status_secure_sentinel_fail)) {
1549
0
      mesh_find_and_attach_ede_and_reason(m, rep, r);
1550
0
    }
1551
1552
0
    if(!inplace_cb_reply_call(m->s.env, &m->s.qinfo, &m->s, rep,
1553
0
      LDNS_RCODE_NOERROR, &r->edns, &r->query_reply, m->s.region, &r->start_time) ||
1554
0
      !reply_info_answer_encode(&m->s.qinfo, rep, r->qid,
1555
0
      r->qflags, r_buffer, 0, 1, m->s.env->scratch,
1556
0
      udp_size, &r->edns, (int)(r->edns.bits & EDNS_DO),
1557
0
      secure))
1558
0
    {
1559
0
      if(!inplace_cb_reply_servfail_call(m->s.env, &m->s.qinfo, &m->s,
1560
0
      rep, LDNS_RCODE_SERVFAIL, &r->edns, &r->query_reply, m->s.region, &r->start_time))
1561
0
        r->edns.opt_list_inplace_cb_out = NULL;
1562
      /* internal server error (probably malloc failure) so no
1563
       * EDE (RFC8914) needed */
1564
0
      error_encode(r_buffer, LDNS_RCODE_SERVFAIL,
1565
0
        &m->s.qinfo, r->qid, r->qflags, &r->edns);
1566
0
    }
1567
0
    m->reply_list = NULL;
1568
0
    comm_point_send_reply(&r->query_reply);
1569
0
    m->reply_list = rlist;
1570
0
  }
1571
0
  infra_wait_limit_dec(m->s.env->infra_cache, &r->query_reply,
1572
0
    m->s.env->cfg);
1573
  /* account */
1574
0
  log_assert(m->s.env->mesh->num_reply_addrs > 0);
1575
0
  m->s.env->mesh->num_reply_addrs--;
1576
0
  end_time = *m->s.env->now_tv;
1577
0
  timeval_subtract(&duration, &end_time, &r->start_time);
1578
0
  verbose(VERB_ALGO, "query took " ARG_LL "d.%6.6d sec",
1579
0
    (long long)duration.tv_sec, (int)duration.tv_usec);
1580
0
  m->s.env->mesh->replies_sent++;
1581
0
  timeval_add(&m->s.env->mesh->replies_sum_wait, &duration);
1582
0
  timehist_insert(m->s.env->mesh->histogram, &duration);
1583
0
  if(m->s.env->cfg->stat_extended) {
1584
0
    uint16_t rc = FLAGS_GET_RCODE(sldns_buffer_read_u16_at(
1585
0
      r_buffer, 2));
1586
0
    if(secure) m->s.env->mesh->ans_secure++;
1587
0
    m->s.env->mesh->ans_rcode[ rc ] ++;
1588
0
    if(rc == 0 && LDNS_ANCOUNT(sldns_buffer_begin(r_buffer)) == 0)
1589
0
      m->s.env->mesh->ans_nodata++;
1590
0
  }
1591
  /* Log reply sent */
1592
0
  if(m->s.env->cfg->log_replies) {
1593
0
    log_reply_info(NO_VERBOSE, &m->s.qinfo,
1594
0
      &r->query_reply.client_addr,
1595
0
      r->query_reply.client_addrlen, duration, 0, r_buffer,
1596
0
      (m->s.env->cfg->log_destaddr?(void*)r->query_reply.c->socket->addr:NULL),
1597
0
      r->query_reply.c->type, r->query_reply.c->ssl);
1598
0
  }
1599
0
}
1600
1601
/**
1602
 * Generate the DNS Error Report (RFC9567).
1603
 * If there is an EDE attached for this reply and there was a Report-Channel
1604
 * EDNS0 option from the upstream, fire up a report query.
1605
 * @param qstate: module qstate.
1606
 * @param rep: prepared reply to be sent.
1607
 */
1608
static void dns_error_reporting(struct module_qstate* qstate,
1609
  struct reply_info* rep)
1610
0
{
1611
0
  struct query_info qinfo;
1612
0
  struct mesh_state* sub;
1613
0
  struct module_qstate* newq;
1614
0
  uint8_t buf[LDNS_MAX_DOMAINLEN];
1615
0
  size_t count = 0;
1616
0
  int written;
1617
0
  size_t expected_length;
1618
0
  struct edns_option* opt;
1619
0
  sldns_ede_code reason_bogus = LDNS_EDE_NONE;
1620
0
  sldns_rr_type qtype = qstate->qinfo.qtype;
1621
0
  uint8_t* qname = qstate->qinfo.qname;
1622
0
  size_t qname_len = qstate->qinfo.qname_len-1; /* skip the trailing \0 */
1623
0
  uint8_t* agent_domain;
1624
0
  size_t agent_domain_len;
1625
1626
  /* We need a valid reporting agent;
1627
   * this is based on qstate->edns_opts_back_in that will probably have
1628
   * the latest reporting agent we found while iterating */
1629
0
  opt = edns_opt_list_find(qstate->edns_opts_back_in,
1630
0
    LDNS_EDNS_REPORT_CHANNEL);
1631
0
  if(!opt) return;
1632
0
  agent_domain_len = opt->opt_len;
1633
0
  agent_domain = opt->opt_data;
1634
0
  if(dname_valid(agent_domain, agent_domain_len) < 3) {
1635
    /* The agent domain needs to be a valid dname that is not the
1636
     * root; from RFC9567. */
1637
0
    return;
1638
0
  }
1639
1640
  /* Get the EDE generated from the mesh state, these are mostly
1641
   * validator errors. If other errors are produced in the future (e.g.,
1642
   * RPZ) we would not want them to result in error reports. */
1643
0
  reason_bogus = errinf_to_reason_bogus(qstate);
1644
0
  if(rep && ((reason_bogus == LDNS_EDE_DNSSEC_BOGUS &&
1645
0
    rep->reason_bogus != LDNS_EDE_NONE) ||
1646
0
    reason_bogus == LDNS_EDE_NONE)) {
1647
0
    reason_bogus = rep->reason_bogus;
1648
0
  }
1649
0
  if(reason_bogus == LDNS_EDE_NONE ||
1650
    /* other, does not make sense without the text that comes
1651
     * with it */
1652
0
    reason_bogus == LDNS_EDE_OTHER) return;
1653
1654
  /* Synthesize the error report query in the format:
1655
   * "_er.$qtype.$qname.$ede._er.$reporting-agent-domain" */
1656
  /* First check if the static length parts fit in the buffer.
1657
   * That is everything except for qtype and ede that need to be
1658
   * converted to decimal and checked further on. */
1659
0
  expected_length = 4/*_er*/+qname_len+4/*_er*/+agent_domain_len;
1660
0
  if(expected_length > LDNS_MAX_DOMAINLEN) goto skip;
1661
1662
0
  memmove(buf+count, "\3_er", 4);
1663
0
  count += 4;
1664
1665
0
  written = snprintf((char*)buf+count, LDNS_MAX_DOMAINLEN-count,
1666
0
    "X%d", qtype);
1667
0
  expected_length += written;
1668
  /* Skip on error, truncation or long expected length */
1669
0
  if(written < 0 || (size_t)written >= LDNS_MAX_DOMAINLEN-count ||
1670
0
    expected_length > LDNS_MAX_DOMAINLEN ) goto skip;
1671
  /* Put in the label length */
1672
0
  *(buf+count) = (char)(written - 1);
1673
0
  count += written;
1674
1675
0
  memmove(buf+count, qname, qname_len);
1676
0
  count += qname_len;
1677
1678
0
  written = snprintf((char*)buf+count, LDNS_MAX_DOMAINLEN-count,
1679
0
    "X%d", reason_bogus);
1680
0
  expected_length += written;
1681
  /* Skip on error, truncation or long expected length */
1682
0
  if(written < 0 || (size_t)written >= LDNS_MAX_DOMAINLEN-count ||
1683
0
    expected_length > LDNS_MAX_DOMAINLEN ) goto skip;
1684
0
  *(buf+count) = (char)(written - 1);
1685
0
  count += written;
1686
1687
0
  memmove(buf+count, "\3_er", 4);
1688
0
  count += 4;
1689
1690
  /* Copy the agent domain */
1691
0
  memmove(buf+count, agent_domain, agent_domain_len);
1692
0
  count += agent_domain_len;
1693
1694
0
  qinfo.qname = buf;
1695
0
  qinfo.qname_len = count;
1696
0
  qinfo.qtype = LDNS_RR_TYPE_TXT;
1697
0
  qinfo.qclass = qstate->qinfo.qclass;
1698
0
  qinfo.local_alias = NULL;
1699
1700
0
  log_query_info(VERB_ALGO, "DNS Error Reporting: generating report "
1701
0
    "query for", &qinfo);
1702
0
  if(mesh_add_sub(qstate, &qinfo, NULL, BIT_RD, 0, 0, &newq, &sub)) {
1703
0
    qstate->env->mesh->num_dns_error_reports++;
1704
0
  }
1705
0
  return;
1706
0
skip:
1707
0
  verbose(VERB_ALGO, "DNS Error Reporting: report query qname too long; "
1708
0
    "skip");
1709
0
  return;
1710
0
}
1711
1712
void mesh_query_done(struct mesh_state* mstate)
1713
0
{
1714
0
  struct mesh_reply* r;
1715
0
  struct mesh_reply* prev = NULL;
1716
0
  struct sldns_buffer* prev_buffer = NULL;
1717
0
  struct mesh_cb* c;
1718
0
  struct reply_info* rep = (mstate->s.return_msg?
1719
0
    mstate->s.return_msg->rep:NULL);
1720
0
  struct timeval tv = {0, 0};
1721
0
  int i = 0;
1722
  /* No need for the serve expired timer anymore; we are going to reply. */
1723
0
  if(mstate->s.serve_expired_data) {
1724
0
    comm_timer_delete(mstate->s.serve_expired_data->timer);
1725
0
    mstate->s.serve_expired_data->timer = NULL;
1726
0
  }
1727
0
  if(mstate->s.return_rcode == LDNS_RCODE_SERVFAIL ||
1728
0
    (rep && FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_SERVFAIL)) {
1729
0
    if(mstate->s.env->cfg->serve_expired) {
1730
      /* we are SERVFAILing; check for expired answer here */
1731
0
      mesh_respond_serve_expired(mstate);
1732
0
    }
1733
0
    if((mstate->reply_list || mstate->cb_list)
1734
0
    && mstate->s.env->cfg->log_servfail
1735
0
    && !mstate->s.env->cfg->val_log_squelch) {
1736
0
      char* err = errinf_to_str_servfail(&mstate->s);
1737
0
      if(err) { log_err("%s", err); }
1738
0
    }
1739
0
  }
1740
1741
0
  if(mstate->reply_list && mstate->s.env->cfg->dns_error_reporting)
1742
0
    dns_error_reporting(&mstate->s, rep);
1743
1744
0
  for(r = mstate->reply_list; r; r = r->next) {
1745
0
    if(mesh_is_udp(r)) {
1746
      /* For UDP queries, the old replies are discarded.
1747
       * This stops a large volume of old replies from
1748
       * building up.
1749
       * The stream replies, are not discarded. The
1750
       * stream is open, the other side is waiting.
1751
       * Some answer is needed, even if servfail, but the
1752
       * real reply is ready to go, so that is given. */
1753
0
      struct timeval old;
1754
0
      timeval_subtract(&old, mstate->s.env->now_tv, &r->start_time);
1755
0
      if(mstate->s.env->cfg->discard_timeout != 0 &&
1756
0
        ((int)old.tv_sec)*1000+((int)old.tv_usec)/1000 >
1757
0
        mstate->s.env->cfg->discard_timeout) {
1758
        /* Drop the reply, it is too old */
1759
        /* briefly set the reply_list to NULL, so that the
1760
         * tcp req info cleanup routine that calls the mesh
1761
         * to deregister the meshstate for it is not done
1762
         * because the list is NULL and also accounting is not
1763
         * done there, but instead we do that here. */
1764
0
        struct mesh_reply* reply_list = mstate->reply_list;
1765
0
        verbose(VERB_ALGO, "drop reply, it is older than discard-timeout");
1766
0
        infra_wait_limit_dec(mstate->s.env->infra_cache,
1767
0
          &r->query_reply, mstate->s.env->cfg);
1768
0
        mstate->reply_list = NULL;
1769
0
        if(r->query_reply.c->use_h2)
1770
0
          http2_stream_remove_mesh_state(r->h2_stream);
1771
0
        comm_point_drop_reply(&r->query_reply);
1772
0
        mstate->reply_list = reply_list;
1773
0
        log_assert(mstate->s.env->mesh->num_reply_addrs > 0);
1774
0
        mstate->s.env->mesh->num_reply_addrs--;
1775
0
        mstate->s.env->mesh->num_queries_discard_timeout++;
1776
0
        continue;
1777
0
      }
1778
0
    }
1779
1780
0
    i++;
1781
0
    tv = r->start_time;
1782
1783
    /* if a response-ip address block has been stored the
1784
     *  information should be logged for each client. */
1785
0
    if(mstate->s.respip_action_info &&
1786
0
      mstate->s.respip_action_info->addrinfo) {
1787
0
      respip_inform_print(mstate->s.respip_action_info,
1788
0
        r->qname, mstate->s.qinfo.qtype,
1789
0
        mstate->s.qinfo.qclass, r->local_alias,
1790
0
        &r->query_reply.client_addr,
1791
0
        r->query_reply.client_addrlen);
1792
0
    }
1793
1794
    /* if this query is determined to be dropped during the
1795
     * mesh processing, this is the point to take that action. */
1796
0
    if(mstate->s.is_drop) {
1797
      /* briefly set the reply_list to NULL, so that the
1798
       * tcp req info cleanup routine that calls the mesh
1799
       * to deregister the meshstate for it is not done
1800
       * because the list is NULL and also accounting is not
1801
       * done there, but instead we do that here. */
1802
0
      struct mesh_reply* reply_list = mstate->reply_list;
1803
0
      infra_wait_limit_dec(mstate->s.env->infra_cache,
1804
0
        &r->query_reply, mstate->s.env->cfg);
1805
0
      mstate->reply_list = NULL;
1806
0
      if(r->query_reply.c->use_h2) {
1807
0
        http2_stream_remove_mesh_state(r->h2_stream);
1808
0
      }
1809
0
      comm_point_drop_reply(&r->query_reply);
1810
0
      mstate->reply_list = reply_list;
1811
0
      log_assert(mstate->s.env->mesh->num_reply_addrs > 0);
1812
0
      mstate->s.env->mesh->num_reply_addrs--;
1813
0
    } else {
1814
0
      struct sldns_buffer* r_buffer = r->query_reply.c->buffer;
1815
0
      if(r->query_reply.c->tcp_req_info) {
1816
0
        r_buffer = r->query_reply.c->tcp_req_info->spool_buffer;
1817
0
        prev_buffer = NULL;
1818
0
      }
1819
0
      mesh_send_reply(mstate, mstate->s.return_rcode, rep,
1820
0
        r, r_buffer, prev, prev_buffer);
1821
0
      if(r->query_reply.c->tcp_req_info) {
1822
0
        tcp_req_info_remove_mesh_state(r->query_reply.c->tcp_req_info, mstate);
1823
0
        r_buffer = NULL;
1824
0
      }
1825
      /* mesh_send_reply removed mesh state from
1826
       * http2_stream. */
1827
0
      prev = r;
1828
0
      prev_buffer = r_buffer;
1829
0
    }
1830
0
  }
1831
  /* Account for each reply sent. */
1832
0
  if(i > 0 && mstate->s.respip_action_info &&
1833
0
    mstate->s.respip_action_info->addrinfo &&
1834
0
    mstate->s.env->cfg->stat_extended &&
1835
0
    mstate->s.respip_action_info->rpz_used) {
1836
0
    if(mstate->s.respip_action_info->rpz_disabled)
1837
0
      mstate->s.env->mesh->rpz_action[RPZ_DISABLED_ACTION] += i;
1838
0
    if(mstate->s.respip_action_info->rpz_cname_override)
1839
0
      mstate->s.env->mesh->rpz_action[RPZ_CNAME_OVERRIDE_ACTION] += i;
1840
0
    else
1841
0
      mstate->s.env->mesh->rpz_action[respip_action_to_rpz_action(
1842
0
        mstate->s.respip_action_info->action)] += i;
1843
0
  }
1844
0
  if(!mstate->s.is_drop && i > 0) {
1845
0
    if(mstate->s.env->cfg->stat_extended
1846
0
      && mstate->s.is_cachedb_answer) {
1847
0
      mstate->s.env->mesh->ans_cachedb += i;
1848
0
    }
1849
0
  }
1850
1851
  /* Mesh area accounting */
1852
0
  if(mstate->reply_list) {
1853
0
    mstate->reply_list = NULL;
1854
0
    if(!mstate->reply_list && !mstate->cb_list) {
1855
      /* was a reply state, not anymore */
1856
0
      log_assert(mstate->s.env->mesh->num_reply_states > 0);
1857
0
      mstate->s.env->mesh->num_reply_states--;
1858
0
    }
1859
0
    if(!mstate->reply_list && !mstate->cb_list &&
1860
0
      mstate->super_set.count == 0)
1861
0
      mstate->s.env->mesh->num_detached_states++;
1862
0
  }
1863
0
  mstate->replies_sent = 1;
1864
1865
0
  while((c = mstate->cb_list) != NULL) {
1866
    /* take this cb off the list; so that the list can be
1867
     * changed, eg. by adds from the callback routine */
1868
0
    if(!mstate->reply_list && mstate->cb_list && !c->next) {
1869
      /* was a reply state, not anymore */
1870
0
      log_assert(mstate->s.env->mesh->num_reply_states > 0);
1871
0
      mstate->s.env->mesh->num_reply_states--;
1872
0
    }
1873
0
    mstate->cb_list = c->next;
1874
0
    if(!mstate->reply_list && !mstate->cb_list &&
1875
0
      mstate->super_set.count == 0)
1876
0
      mstate->s.env->mesh->num_detached_states++;
1877
0
    mesh_do_callback(mstate, mstate->s.return_rcode, rep, c, &tv);
1878
0
  }
1879
0
}
1880
1881
void mesh_walk_supers(struct mesh_area* mesh, struct mesh_state* mstate)
1882
0
{
1883
0
  struct mesh_state_ref* ref;
1884
0
  RBTREE_FOR(ref, struct mesh_state_ref*, &mstate->super_set)
1885
0
  {
1886
    /* make super runnable */
1887
0
    (void)rbtree_insert(&mesh->run, &ref->s->run_node);
1888
    /* callback the function to inform super of result */
1889
0
    fptr_ok(fptr_whitelist_mod_inform_super(
1890
0
      mesh->mods.mod[ref->s->s.curmod]->inform_super));
1891
0
    (*mesh->mods.mod[ref->s->s.curmod]->inform_super)(&mstate->s,
1892
0
      ref->s->s.curmod, &ref->s->s);
1893
    /* copy state that is always relevant to super */
1894
0
    copy_state_to_super(&mstate->s, ref->s->s.curmod, &ref->s->s);
1895
0
  }
1896
0
}
1897
1898
struct mesh_state* mesh_area_find(struct mesh_area* mesh,
1899
  struct respip_client_info* cinfo, struct query_info* qinfo,
1900
  uint16_t qflags, int prime, int valrec)
1901
0
{
1902
0
  struct mesh_state key;
1903
0
  struct mesh_state* result;
1904
1905
0
  key.node.key = &key;
1906
0
  key.s.is_priming = prime;
1907
0
  key.s.is_valrec = valrec;
1908
0
  key.s.qinfo = *qinfo;
1909
0
  key.s.query_flags = qflags;
1910
  /* We are searching for a similar mesh state when we DO want to
1911
   * aggregate the state. Thus unique is set to NULL. (default when we
1912
   * desire aggregation).*/
1913
0
  key.unique = NULL;
1914
0
  key.s.client_info = cinfo;
1915
1916
0
  result = (struct mesh_state*)rbtree_search(&mesh->all, &key);
1917
0
  return result;
1918
0
}
1919
1920
/** remove mesh state callback */
1921
int mesh_state_del_cb(struct mesh_state* s, mesh_cb_func_type cb, void* cb_arg)
1922
0
{
1923
0
  struct mesh_cb* r, *prev = NULL;
1924
0
  r = s->cb_list;
1925
0
  while(r) {
1926
0
    if(r->cb == cb && r->cb_arg == cb_arg) {
1927
      /* Delete this entry. */
1928
      /* It was allocated in the s.region, so no free. */
1929
0
      if(prev) prev->next = r->next;
1930
0
      else s->cb_list = r->next;
1931
0
      return 1;
1932
0
    }
1933
0
    prev = r;
1934
0
    r = r->next;
1935
0
  }
1936
0
  return 0;
1937
0
}
1938
1939
int mesh_state_add_cb(struct mesh_state* s, struct edns_data* edns,
1940
        sldns_buffer* buf, mesh_cb_func_type cb, void* cb_arg,
1941
  uint16_t qid, uint16_t qflags)
1942
0
{
1943
0
  struct mesh_cb* r = regional_alloc(s->s.region,
1944
0
    sizeof(struct mesh_cb));
1945
0
  if(!r)
1946
0
    return 0;
1947
0
  r->buf = buf;
1948
0
  log_assert(fptr_whitelist_mesh_cb(cb)); /* early failure ifmissing*/
1949
0
  r->cb = cb;
1950
0
  r->cb_arg = cb_arg;
1951
0
  r->edns = *edns;
1952
0
  if(edns->opt_list_in && !(r->edns.opt_list_in =
1953
0
      edns_opt_copy_region(edns->opt_list_in, s->s.region)))
1954
0
    return 0;
1955
0
  if(edns->opt_list_out && !(r->edns.opt_list_out =
1956
0
      edns_opt_copy_region(edns->opt_list_out, s->s.region)))
1957
0
    return 0;
1958
0
  if(edns->opt_list_inplace_cb_out && !(r->edns.opt_list_inplace_cb_out =
1959
0
      edns_opt_copy_region(edns->opt_list_inplace_cb_out, s->s.region)))
1960
0
    return 0;
1961
0
  r->qid = qid;
1962
0
  r->qflags = qflags;
1963
0
  r->next = s->cb_list;
1964
0
  s->cb_list = r;
1965
0
  return 1;
1966
1967
0
}
1968
1969
int mesh_state_add_reply(struct mesh_state* s, struct edns_data* edns,
1970
        struct comm_reply* rep, uint16_t qid, uint16_t qflags,
1971
        const struct query_info* qinfo)
1972
0
{
1973
0
  struct mesh_reply* r = regional_alloc(s->s.region,
1974
0
    sizeof(struct mesh_reply));
1975
0
  if(!r)
1976
0
    return 0;
1977
0
  r->query_reply = *rep;
1978
0
  r->edns = *edns;
1979
0
  if(edns->opt_list_in && !(r->edns.opt_list_in =
1980
0
      edns_opt_copy_region(edns->opt_list_in, s->s.region)))
1981
0
    return 0;
1982
0
  if(edns->opt_list_out && !(r->edns.opt_list_out =
1983
0
      edns_opt_copy_region(edns->opt_list_out, s->s.region)))
1984
0
    return 0;
1985
0
  if(edns->opt_list_inplace_cb_out && !(r->edns.opt_list_inplace_cb_out =
1986
0
      edns_opt_copy_region(edns->opt_list_inplace_cb_out, s->s.region)))
1987
0
    return 0;
1988
0
  r->qid = qid;
1989
0
  r->qflags = qflags;
1990
0
  r->start_time = *s->s.env->now_tv;
1991
0
  r->next = s->reply_list;
1992
0
  r->qname = regional_alloc_init(s->s.region, qinfo->qname,
1993
0
    s->s.qinfo.qname_len);
1994
0
  if(!r->qname)
1995
0
    return 0;
1996
0
  if(rep->c->use_h2)
1997
0
    r->h2_stream = rep->c->h2_stream;
1998
0
  else  r->h2_stream = NULL;
1999
2000
  /* Data related to local alias stored in 'qinfo' (if any) is ephemeral
2001
   * and can be different for different original queries (even if the
2002
   * replaced query name is the same).  So we need to make a deep copy
2003
   * and store the copy for each reply info. */
2004
0
  if(qinfo->local_alias) {
2005
0
    struct packed_rrset_data* d;
2006
0
    struct packed_rrset_data* dsrc;
2007
0
    r->local_alias = regional_alloc_zero(s->s.region,
2008
0
      sizeof(*qinfo->local_alias));
2009
0
    if(!r->local_alias)
2010
0
      return 0;
2011
0
    r->local_alias->rrset = regional_alloc_init(s->s.region,
2012
0
      qinfo->local_alias->rrset,
2013
0
      sizeof(*qinfo->local_alias->rrset));
2014
0
    if(!r->local_alias->rrset)
2015
0
      return 0;
2016
0
    dsrc = qinfo->local_alias->rrset->entry.data;
2017
2018
    /* In the current implementation, a local alias must be
2019
     * a single CNAME RR (see worker_handle_request()). */
2020
0
    log_assert(!qinfo->local_alias->next && dsrc->count == 1 &&
2021
0
      qinfo->local_alias->rrset->rk.type ==
2022
0
      htons(LDNS_RR_TYPE_CNAME));
2023
    /* we should make a local copy for the owner name of
2024
     * the RRset */
2025
0
    r->local_alias->rrset->rk.dname_len =
2026
0
      qinfo->local_alias->rrset->rk.dname_len;
2027
0
    r->local_alias->rrset->rk.dname = regional_alloc_init(
2028
0
      s->s.region, qinfo->local_alias->rrset->rk.dname,
2029
0
      qinfo->local_alias->rrset->rk.dname_len);
2030
0
    if(!r->local_alias->rrset->rk.dname)
2031
0
      return 0;
2032
2033
    /* the rrset is not packed, like in the cache, but it is
2034
     * individually allocated with an allocator from localzone. */
2035
0
    d = regional_alloc_zero(s->s.region, sizeof(*d));
2036
0
    if(!d)
2037
0
      return 0;
2038
0
    r->local_alias->rrset->entry.data = d;
2039
0
    if(!rrset_insert_rr(s->s.region, d, dsrc->rr_data[0],
2040
0
      dsrc->rr_len[0], dsrc->rr_ttl[0], "CNAME local alias"))
2041
0
      return 0;
2042
0
  } else
2043
0
    r->local_alias = NULL;
2044
2045
0
  s->reply_list = r;
2046
0
  return 1;
2047
0
}
2048
2049
/* Extract the query info and flags from 'mstate' into '*qinfop' and '*qflags'.
2050
 * Since this is only used for internal refetch of otherwise-expired answer,
2051
 * we simply ignore the rare failure mode when memory allocation fails. */
2052
static void
2053
mesh_copy_qinfo(struct mesh_state* mstate, struct query_info** qinfop,
2054
  uint16_t* qflags)
2055
0
{
2056
0
  struct regional* region = mstate->s.env->scratch;
2057
0
  struct query_info* qinfo;
2058
2059
0
  qinfo = regional_alloc_init(region, &mstate->s.qinfo, sizeof(*qinfo));
2060
0
  if(!qinfo)
2061
0
    return;
2062
0
  qinfo->qname = regional_alloc_init(region, qinfo->qname,
2063
0
    qinfo->qname_len);
2064
0
  if(!qinfo->qname)
2065
0
    return;
2066
0
  *qinfop = qinfo;
2067
0
  *qflags = mstate->s.query_flags;
2068
0
}
2069
2070
/**
2071
 * Continue processing the mesh state at another module.
2072
 * Handles module to modules transfer of control.
2073
 * Handles module finished.
2074
 * @param mesh: the mesh area.
2075
 * @param mstate: currently active mesh state.
2076
 *  Deleted if finished, calls _done and _supers to
2077
 *  send replies to clients and inform other mesh states.
2078
 *  This in turn may create additional runnable mesh states.
2079
 * @param s: state at which the current module exited.
2080
 * @param ev: the event sent to the module.
2081
 *  returned is the event to send to the next module.
2082
 * @return true if continue processing at the new module.
2083
 *  false if not continued processing is needed.
2084
 */
2085
static int
2086
mesh_continue(struct mesh_area* mesh, struct mesh_state* mstate,
2087
  enum module_ext_state s, enum module_ev* ev)
2088
0
{
2089
0
  mstate->num_activated++;
2090
0
  if(mstate->num_activated > MESH_MAX_ACTIVATION) {
2091
    /* module is looping. Stop it. */
2092
0
    log_err("internal error: looping module (%s) stopped",
2093
0
      mesh->mods.mod[mstate->s.curmod]->name);
2094
0
    log_query_info(NO_VERBOSE, "pass error for qstate",
2095
0
      &mstate->s.qinfo);
2096
0
    s = module_error;
2097
0
  }
2098
0
  if(s == module_wait_module || s == module_restart_next) {
2099
    /* start next module */
2100
0
    mstate->s.curmod++;
2101
0
    if(mesh->mods.num == mstate->s.curmod) {
2102
0
      log_err("Cannot pass to next module; at last module");
2103
0
      log_query_info(VERB_QUERY, "pass error for qstate",
2104
0
        &mstate->s.qinfo);
2105
0
      mstate->s.curmod--;
2106
0
      return mesh_continue(mesh, mstate, module_error, ev);
2107
0
    }
2108
0
    if(s == module_restart_next) {
2109
0
      int curmod = mstate->s.curmod;
2110
0
      for(; mstate->s.curmod < mesh->mods.num;
2111
0
        mstate->s.curmod++) {
2112
0
        fptr_ok(fptr_whitelist_mod_clear(
2113
0
          mesh->mods.mod[mstate->s.curmod]->clear));
2114
0
        (*mesh->mods.mod[mstate->s.curmod]->clear)
2115
0
          (&mstate->s, mstate->s.curmod);
2116
0
        mstate->s.minfo[mstate->s.curmod] = NULL;
2117
0
      }
2118
0
      mstate->s.curmod = curmod;
2119
0
    }
2120
0
    *ev = module_event_pass;
2121
0
    return 1;
2122
0
  }
2123
0
  if(s == module_wait_subquery && mstate->sub_set.count == 0) {
2124
0
    log_err("module cannot wait for subquery, subquery list empty");
2125
0
    log_query_info(VERB_QUERY, "pass error for qstate",
2126
0
      &mstate->s.qinfo);
2127
0
    s = module_error;
2128
0
  }
2129
0
  if(s == module_error && mstate->s.return_rcode == LDNS_RCODE_NOERROR) {
2130
    /* error is bad, handle pass back up below */
2131
0
    mstate->s.return_rcode = LDNS_RCODE_SERVFAIL;
2132
0
  }
2133
0
  if(s == module_error) {
2134
0
    mesh_query_done(mstate);
2135
0
    mesh_walk_supers(mesh, mstate);
2136
0
    mesh_state_delete(&mstate->s);
2137
0
    return 0;
2138
0
  }
2139
0
  if(s == module_finished) {
2140
0
    if(mstate->s.curmod == 0) {
2141
0
      struct query_info* qinfo = NULL;
2142
0
      struct edns_option* opt_list = NULL;
2143
0
      struct sockaddr_storage addr;
2144
0
      uint16_t qflags;
2145
0
      int rpz_p = 0;
2146
2147
#ifdef CLIENT_SUBNET
2148
      struct edns_option* ecs;
2149
      if(mstate->s.need_refetch && mstate->reply_list &&
2150
        modstack_find(&mesh->mods, "subnetcache") != -1 &&
2151
        mstate->s.env->unique_mesh) {
2152
        addr = mstate->reply_list->query_reply.client_addr;
2153
      } else
2154
#endif
2155
0
        memset(&addr, 0, sizeof(addr));
2156
2157
0
      mesh_query_done(mstate);
2158
0
      mesh_walk_supers(mesh, mstate);
2159
2160
      /* If the answer to the query needs to be refetched
2161
       * from an external DNS server, we'll need to schedule
2162
       * a prefetch after removing the current state, so
2163
       * we need to make a copy of the query info here. */
2164
0
      if(mstate->s.need_refetch) {
2165
0
        mesh_copy_qinfo(mstate, &qinfo, &qflags);
2166
#ifdef CLIENT_SUBNET
2167
        /* Make also a copy of the ecs option if any */
2168
        if((ecs = edns_opt_list_find(
2169
          mstate->s.edns_opts_front_in,
2170
          mstate->s.env->cfg->client_subnet_opcode)) != NULL) {
2171
          (void)edns_opt_list_append(&opt_list,
2172
            ecs->opt_code, ecs->opt_len,
2173
            ecs->opt_data,
2174
            mstate->s.env->scratch);
2175
        }
2176
#endif
2177
0
        rpz_p = mstate->s.rpz_passthru;
2178
0
      }
2179
2180
0
      if(qinfo) {
2181
0
        mesh_state_delete(&mstate->s);
2182
0
        mesh_new_prefetch(mesh, qinfo, qflags, 0,
2183
0
          rpz_p,
2184
0
          addr.ss_family!=AF_UNSPEC?&addr:NULL,
2185
0
          opt_list);
2186
0
      } else {
2187
0
        mesh_state_delete(&mstate->s);
2188
0
      }
2189
0
      return 0;
2190
0
    }
2191
    /* pass along the locus of control */
2192
0
    mstate->s.curmod --;
2193
0
    *ev = module_event_moddone;
2194
0
    return 1;
2195
0
  }
2196
0
  return 0;
2197
0
}
2198
2199
void mesh_run(struct mesh_area* mesh, struct mesh_state* mstate,
2200
  enum module_ev ev, struct outbound_entry* e)
2201
0
{
2202
0
  enum module_ext_state s;
2203
0
  verbose(VERB_ALGO, "mesh_run: start");
2204
0
  while(mstate) {
2205
    /* run the module */
2206
0
    fptr_ok(fptr_whitelist_mod_operate(
2207
0
      mesh->mods.mod[mstate->s.curmod]->operate));
2208
0
    (*mesh->mods.mod[mstate->s.curmod]->operate)
2209
0
      (&mstate->s, ev, mstate->s.curmod, e);
2210
2211
    /* examine results */
2212
0
    mstate->s.reply = NULL;
2213
0
    regional_free_all(mstate->s.env->scratch);
2214
0
    s = mstate->s.ext_state[mstate->s.curmod];
2215
0
    verbose(VERB_ALGO, "mesh_run: %s module exit state is %s",
2216
0
      mesh->mods.mod[mstate->s.curmod]->name, strextstate(s));
2217
0
    e = NULL;
2218
0
    if(mesh_continue(mesh, mstate, s, &ev))
2219
0
      continue;
2220
2221
    /* run more modules */
2222
0
    ev = module_event_pass;
2223
0
    if(mesh->run.count > 0) {
2224
      /* pop random element off the runnable tree */
2225
0
      mstate = (struct mesh_state*)mesh->run.root->key;
2226
0
      (void)rbtree_delete(&mesh->run, mstate);
2227
0
    } else mstate = NULL;
2228
0
  }
2229
0
  if(verbosity >= VERB_ALGO) {
2230
0
    mesh_stats(mesh, "mesh_run: end");
2231
0
    mesh_log_list(mesh);
2232
0
  }
2233
0
}
2234
2235
void
2236
mesh_log_list(struct mesh_area* mesh)
2237
0
{
2238
0
  char buf[30];
2239
0
  struct mesh_state* m;
2240
0
  int num = 0;
2241
0
  RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
2242
0
    snprintf(buf, sizeof(buf), "%d%s%s%s%s%s%s mod%d %s%s",
2243
0
      num++, (m->s.is_priming)?"p":"",  /* prime */
2244
0
      (m->s.is_valrec)?"v":"",  /* prime */
2245
0
      (m->s.query_flags&BIT_RD)?"RD":"",
2246
0
      (m->s.query_flags&BIT_CD)?"CD":"",
2247
0
      (m->super_set.count==0)?"d":"", /* detached */
2248
0
      (m->sub_set.count!=0)?"c":"",  /* children */
2249
0
      m->s.curmod, (m->reply_list)?"rep":"", /*hasreply*/
2250
0
      (m->cb_list)?"cb":"" /* callbacks */
2251
0
      );
2252
0
    log_query_info(VERB_ALGO, buf, &m->s.qinfo);
2253
0
  }
2254
0
}
2255
2256
void
2257
mesh_stats(struct mesh_area* mesh, const char* str)
2258
0
{
2259
0
  verbose(VERB_DETAIL, "%s %u recursion states (%u with reply, "
2260
0
    "%u detached), %u waiting replies, %u recursion replies "
2261
0
    "sent, %d replies dropped, %d states jostled out",
2262
0
    str, (unsigned)mesh->all.count,
2263
0
    (unsigned)mesh->num_reply_states,
2264
0
    (unsigned)mesh->num_detached_states,
2265
0
    (unsigned)mesh->num_reply_addrs,
2266
0
    (unsigned)mesh->replies_sent,
2267
0
    (unsigned)mesh->stats_dropped,
2268
0
    (unsigned)mesh->stats_jostled);
2269
0
  if(mesh->replies_sent > 0) {
2270
0
    struct timeval avg;
2271
0
    timeval_divide(&avg, &mesh->replies_sum_wait,
2272
0
      mesh->replies_sent);
2273
0
    log_info("average recursion processing time "
2274
0
      ARG_LL "d.%6.6d sec",
2275
0
      (long long)avg.tv_sec, (int)avg.tv_usec);
2276
0
    log_info("histogram of recursion processing times");
2277
0
    timehist_log(mesh->histogram, "recursions");
2278
0
  }
2279
0
}
2280
2281
void
2282
mesh_stats_clear(struct mesh_area* mesh)
2283
0
{
2284
0
  if(!mesh)
2285
0
    return;
2286
0
  mesh->num_query_authzone_up = 0;
2287
0
  mesh->num_query_authzone_down = 0;
2288
0
  mesh->replies_sent = 0;
2289
0
  mesh->replies_sum_wait.tv_sec = 0;
2290
0
  mesh->replies_sum_wait.tv_usec = 0;
2291
0
  mesh->stats_jostled = 0;
2292
0
  mesh->stats_dropped = 0;
2293
0
  timehist_clear(mesh->histogram);
2294
0
  mesh->ans_secure = 0;
2295
0
  mesh->ans_bogus = 0;
2296
0
  mesh->val_ops = 0;
2297
0
  mesh->ans_expired = 0;
2298
0
  mesh->ans_cachedb = 0;
2299
0
  memset(&mesh->ans_rcode[0], 0, sizeof(size_t)*UB_STATS_RCODE_NUM);
2300
0
  memset(&mesh->rpz_action[0], 0, sizeof(size_t)*UB_STATS_RPZ_ACTION_NUM);
2301
0
  mesh->ans_nodata = 0;
2302
0
  mesh->num_queries_discard_timeout = 0;
2303
0
  mesh->num_queries_replyaddr_limit = 0;
2304
0
  mesh->num_queries_wait_limit = 0;
2305
0
  mesh->num_dns_error_reports = 0;
2306
0
}
2307
2308
size_t
2309
mesh_get_mem(struct mesh_area* mesh)
2310
0
{
2311
0
  struct mesh_state* m;
2312
0
  size_t s = sizeof(*mesh) + sizeof(struct timehist) +
2313
0
    sizeof(struct th_buck)*mesh->histogram->num +
2314
0
    sizeof(sldns_buffer) + sldns_buffer_capacity(mesh->qbuf_bak);
2315
0
  RBTREE_FOR(m, struct mesh_state*, &mesh->all) {
2316
    /* all, including m itself allocated in qstate region */
2317
0
    s += regional_get_mem(m->s.region);
2318
0
  }
2319
0
  return s;
2320
0
}
2321
2322
int
2323
mesh_detect_cycle(struct module_qstate* qstate, struct query_info* qinfo,
2324
  uint16_t flags, int prime, int valrec)
2325
0
{
2326
0
  struct mesh_area* mesh = qstate->env->mesh;
2327
0
  struct mesh_state* dep_m = NULL;
2328
0
  dep_m = mesh_area_find(mesh, NULL, qinfo, flags, prime, valrec);
2329
0
  return dep_m?mesh_detect_cycle_found(qstate, dep_m):0;
2330
0
}
2331
2332
void mesh_list_insert(struct mesh_state* m, struct mesh_state** fp,
2333
        struct mesh_state** lp)
2334
0
{
2335
  /* insert as last element */
2336
0
  m->prev = *lp;
2337
0
  m->next = NULL;
2338
0
  if(*lp)
2339
0
    (*lp)->next = m;
2340
0
  else  *fp = m;
2341
0
  *lp = m;
2342
0
}
2343
2344
void mesh_list_remove(struct mesh_state* m, struct mesh_state** fp,
2345
        struct mesh_state** lp)
2346
0
{
2347
0
  if(m->next)
2348
0
    m->next->prev = m->prev;
2349
0
  else  *lp = m->prev;
2350
0
  if(m->prev)
2351
0
    m->prev->next = m->next;
2352
0
  else  *fp = m->next;
2353
0
}
2354
2355
void mesh_state_remove_reply(struct mesh_area* mesh, struct mesh_state* m,
2356
  struct comm_point* cp)
2357
0
{
2358
0
  struct mesh_reply* n, *prev = NULL;
2359
0
  n = m->reply_list;
2360
  /* when in mesh_cleanup, it sets the reply_list to NULL, so that
2361
   * there is no accounting twice */
2362
0
  if(!n) return; /* nothing to remove, also no accounting needed */
2363
0
  while(n) {
2364
0
    if(n->query_reply.c == cp) {
2365
      /* unlink it */
2366
0
      if(prev) prev->next = n->next;
2367
0
      else m->reply_list = n->next;
2368
      /* delete it, but allocated in m region */
2369
0
      log_assert(mesh->num_reply_addrs > 0);
2370
0
      mesh->num_reply_addrs--;
2371
0
      infra_wait_limit_dec(mesh->env->infra_cache,
2372
0
        &n->query_reply, mesh->env->cfg);
2373
2374
      /* prev = prev; */
2375
0
      n = n->next;
2376
0
      continue;
2377
0
    }
2378
0
    prev = n;
2379
0
    n = n->next;
2380
0
  }
2381
  /* it was not detached (because it had a reply list), could be now */
2382
0
  if(!m->reply_list && !m->cb_list
2383
0
    && m->super_set.count == 0) {
2384
0
    mesh->num_detached_states++;
2385
0
  }
2386
  /* if not replies any more in mstate, it is no longer a reply_state */
2387
0
  if(!m->reply_list && !m->cb_list) {
2388
0
    log_assert(mesh->num_reply_states > 0);
2389
0
    mesh->num_reply_states--;
2390
0
  }
2391
0
}
2392
2393
2394
static int
2395
apply_respip_action(struct module_qstate* qstate,
2396
  const struct query_info* qinfo, struct respip_client_info* cinfo,
2397
  struct respip_action_info* actinfo, struct reply_info* rep,
2398
  struct ub_packed_rrset_key** alias_rrset,
2399
  struct reply_info** encode_repp, struct auth_zones* az)
2400
0
{
2401
0
  if(qinfo->qtype != LDNS_RR_TYPE_A &&
2402
0
    qinfo->qtype != LDNS_RR_TYPE_AAAA &&
2403
0
    qinfo->qtype != LDNS_RR_TYPE_ANY)
2404
0
    return 1;
2405
2406
0
  if(!respip_rewrite_reply(qinfo, cinfo, rep, encode_repp, actinfo,
2407
0
    alias_rrset, 0, qstate->region, az, NULL, qstate->env->views,
2408
0
    qstate->env->respip_set))
2409
0
    return 0;
2410
2411
  /* xxx_deny actions mean dropping the reply, unless the original reply
2412
   * was redirected to response-ip data. */
2413
0
  if((actinfo->action == respip_deny ||
2414
0
    actinfo->action == respip_inform_deny) &&
2415
0
    *encode_repp == rep)
2416
0
    *encode_repp = NULL;
2417
2418
0
  return 1;
2419
0
}
2420
2421
void
2422
mesh_serve_expired_callback(void* arg)
2423
0
{
2424
0
  struct mesh_state* mstate = (struct mesh_state*) arg;
2425
0
  struct module_qstate* qstate = &mstate->s;
2426
0
  struct mesh_reply* r;
2427
0
  struct mesh_area* mesh = qstate->env->mesh;
2428
0
  struct dns_msg* msg;
2429
0
  struct mesh_cb* c;
2430
0
  struct mesh_reply* prev = NULL;
2431
0
  struct sldns_buffer* prev_buffer = NULL;
2432
0
  struct sldns_buffer* r_buffer = NULL;
2433
0
  struct reply_info* partial_rep = NULL;
2434
0
  struct ub_packed_rrset_key* alias_rrset = NULL;
2435
0
  struct reply_info* encode_rep = NULL;
2436
0
  struct respip_action_info actinfo;
2437
0
  struct query_info* lookup_qinfo = &qstate->qinfo;
2438
0
  struct query_info qinfo_tmp;
2439
0
  struct timeval tv = {0, 0};
2440
0
  int must_validate = (!(qstate->query_flags&BIT_CD)
2441
0
    || qstate->env->cfg->ignore_cd) && qstate->env->need_to_validate;
2442
0
  int i = 0, for_count;
2443
0
  int is_expired;
2444
0
  if(!qstate->serve_expired_data) return;
2445
0
  verbose(VERB_ALGO, "Serve expired: Trying to reply with expired data");
2446
0
  comm_timer_delete(qstate->serve_expired_data->timer);
2447
0
  qstate->serve_expired_data->timer = NULL;
2448
  /* If is_drop or no_cache_lookup (modules that handle their own cache e.g.,
2449
   * subnetmod) ignore stale data from the main cache. */
2450
0
  if(qstate->no_cache_lookup || qstate->is_drop) {
2451
0
    verbose(VERB_ALGO,
2452
0
      "Serve expired: Not allowed to look into cache for stale");
2453
0
    return;
2454
0
  }
2455
  /* The following for is used instead of the `goto lookup_cache`
2456
   * like in the worker. This loop should get max 2 passes if we need to
2457
   * do any aliasing. */
2458
0
  for(for_count = 0; for_count < 2; for_count++) {
2459
0
    fptr_ok(fptr_whitelist_serve_expired_lookup(
2460
0
      qstate->serve_expired_data->get_cached_answer));
2461
0
    msg = (*qstate->serve_expired_data->get_cached_answer)(qstate,
2462
0
      lookup_qinfo, &is_expired);
2463
0
    if(!msg || (FLAGS_GET_RCODE(msg->rep->flags) != LDNS_RCODE_NOERROR
2464
0
      && FLAGS_GET_RCODE(msg->rep->flags) != LDNS_RCODE_NXDOMAIN
2465
0
      && FLAGS_GET_RCODE(msg->rep->flags) != LDNS_RCODE_YXDOMAIN)) {
2466
      /* We don't care for cached failure answers at this
2467
       * stage. */
2468
0
      return;
2469
0
    }
2470
    /* Reset these in case we pass a second time from here. */
2471
0
    encode_rep = msg->rep;
2472
0
    memset(&actinfo, 0, sizeof(actinfo));
2473
0
    actinfo.action = respip_none;
2474
0
    alias_rrset = NULL;
2475
0
    if((mesh->use_response_ip || mesh->use_rpz) &&
2476
0
      !partial_rep && !apply_respip_action(qstate, &qstate->qinfo,
2477
0
      qstate->client_info, &actinfo, msg->rep, &alias_rrset, &encode_rep,
2478
0
      qstate->env->auth_zones)) {
2479
0
      return;
2480
0
    } else if(partial_rep &&
2481
0
      !respip_merge_cname(partial_rep, &qstate->qinfo, msg->rep,
2482
0
      qstate->client_info, must_validate, &encode_rep, qstate->region,
2483
0
      qstate->env->auth_zones, qstate->env->views,
2484
0
      qstate->env->respip_set)) {
2485
0
      return;
2486
0
    }
2487
0
    if(!encode_rep || alias_rrset) {
2488
0
      if(!encode_rep) {
2489
        /* Needs drop */
2490
0
        return;
2491
0
      } else {
2492
        /* A partial CNAME chain is found. */
2493
0
        partial_rep = encode_rep;
2494
0
      }
2495
0
    }
2496
    /* We've found a partial reply ending with an
2497
    * alias.  Replace the lookup qinfo for the
2498
    * alias target and lookup the cache again to
2499
    * (possibly) complete the reply.  As we're
2500
    * passing the "base" reply, there will be no
2501
    * more alias chasing. */
2502
0
    if(partial_rep) {
2503
0
      memset(&qinfo_tmp, 0, sizeof(qinfo_tmp));
2504
0
      get_cname_target(alias_rrset, &qinfo_tmp.qname,
2505
0
        &qinfo_tmp.qname_len);
2506
0
      if(!qinfo_tmp.qname) {
2507
0
        log_err("Serve expired: unexpected: invalid answer alias");
2508
0
        return;
2509
0
      }
2510
0
      qinfo_tmp.qtype = qstate->qinfo.qtype;
2511
0
      qinfo_tmp.qclass = qstate->qinfo.qclass;
2512
0
      lookup_qinfo = &qinfo_tmp;
2513
0
      continue;
2514
0
    }
2515
0
    break;
2516
0
  }
2517
2518
0
  if(verbosity >= VERB_ALGO)
2519
0
    log_dns_msg("Serve expired lookup", &qstate->qinfo, msg->rep);
2520
2521
0
  for(r = mstate->reply_list; r; r = r->next) {
2522
0
    struct timeval old;
2523
0
    timeval_subtract(&old, mstate->s.env->now_tv, &r->start_time);
2524
0
    if(mstate->s.env->cfg->discard_timeout != 0 &&
2525
0
      ((int)old.tv_sec)*1000+((int)old.tv_usec)/1000 >
2526
0
      mstate->s.env->cfg->discard_timeout) {
2527
      /* Drop the reply, it is too old */
2528
      /* briefly set the reply_list to NULL, so that the
2529
       * tcp req info cleanup routine that calls the mesh
2530
       * to deregister the meshstate for it is not done
2531
       * because the list is NULL and also accounting is not
2532
       * done there, but instead we do that here. */
2533
0
      struct mesh_reply* reply_list = mstate->reply_list;
2534
0
      verbose(VERB_ALGO, "drop reply, it is older than discard-timeout");
2535
0
      infra_wait_limit_dec(mstate->s.env->infra_cache,
2536
0
        &r->query_reply, mstate->s.env->cfg);
2537
0
      mstate->reply_list = NULL;
2538
0
      if(r->query_reply.c->use_h2)
2539
0
        http2_stream_remove_mesh_state(r->h2_stream);
2540
0
      comm_point_drop_reply(&r->query_reply);
2541
0
      mstate->reply_list = reply_list;
2542
0
      mstate->s.env->mesh->num_queries_discard_timeout++;
2543
0
      continue;
2544
0
    }
2545
2546
0
    i++;
2547
0
    tv = r->start_time;
2548
2549
    /* If address info is returned, it means the action should be an
2550
    * 'inform' variant and the information should be logged. */
2551
0
    if(actinfo.addrinfo) {
2552
0
      respip_inform_print(&actinfo, r->qname,
2553
0
        qstate->qinfo.qtype, qstate->qinfo.qclass,
2554
0
        r->local_alias, &r->query_reply.client_addr,
2555
0
        r->query_reply.client_addrlen);
2556
0
    }
2557
2558
    /* Add EDE Stale Answer (RCF8914). Ignore global ede as this is
2559
     * warning instead of an error */
2560
0
    if(r->edns.edns_present &&
2561
0
      qstate->env->cfg->ede_serve_expired &&
2562
0
      qstate->env->cfg->ede &&
2563
0
      is_expired) {
2564
0
      edns_opt_list_append_ede(&r->edns.opt_list_out,
2565
0
        mstate->s.region, LDNS_EDE_STALE_ANSWER, NULL);
2566
0
    }
2567
2568
0
    r_buffer = r->query_reply.c->buffer;
2569
0
    if(r->query_reply.c->tcp_req_info)
2570
0
      r_buffer = r->query_reply.c->tcp_req_info->spool_buffer;
2571
0
    mesh_send_reply(mstate, LDNS_RCODE_NOERROR, msg->rep,
2572
0
      r, r_buffer, prev, prev_buffer);
2573
0
    if(r->query_reply.c->tcp_req_info)
2574
0
      tcp_req_info_remove_mesh_state(r->query_reply.c->tcp_req_info, mstate);
2575
    /* mesh_send_reply removed mesh state from http2_stream. */
2576
0
    infra_wait_limit_dec(mstate->s.env->infra_cache,
2577
0
      &r->query_reply, mstate->s.env->cfg);
2578
0
    prev = r;
2579
0
    prev_buffer = r_buffer;
2580
0
  }
2581
  /* Account for each reply sent. */
2582
0
  if(i > 0) {
2583
0
    mesh->ans_expired += i;
2584
0
    if(actinfo.addrinfo && qstate->env->cfg->stat_extended &&
2585
0
      actinfo.rpz_used) {
2586
0
      if(actinfo.rpz_disabled)
2587
0
        qstate->env->mesh->rpz_action[RPZ_DISABLED_ACTION] += i;
2588
0
      if(actinfo.rpz_cname_override)
2589
0
        qstate->env->mesh->rpz_action[RPZ_CNAME_OVERRIDE_ACTION] += i;
2590
0
      else
2591
0
        qstate->env->mesh->rpz_action[
2592
0
          respip_action_to_rpz_action(actinfo.action)] += i;
2593
0
    }
2594
0
  }
2595
2596
  /* Mesh area accounting */
2597
0
  if(mstate->reply_list) {
2598
0
    mstate->reply_list = NULL;
2599
0
    if(!mstate->reply_list && !mstate->cb_list) {
2600
0
      log_assert(mesh->num_reply_states > 0);
2601
0
      mesh->num_reply_states--;
2602
0
      if(mstate->super_set.count == 0) {
2603
0
        mesh->num_detached_states++;
2604
0
      }
2605
0
    }
2606
0
  }
2607
2608
0
  while((c = mstate->cb_list) != NULL) {
2609
    /* take this cb off the list; so that the list can be
2610
     * changed, eg. by adds from the callback routine */
2611
0
    if(!mstate->reply_list && mstate->cb_list && !c->next) {
2612
      /* was a reply state, not anymore */
2613
0
      log_assert(qstate->env->mesh->num_reply_states > 0);
2614
0
      qstate->env->mesh->num_reply_states--;
2615
0
    }
2616
0
    mstate->cb_list = c->next;
2617
0
    if(!mstate->reply_list && !mstate->cb_list &&
2618
0
      mstate->super_set.count == 0)
2619
0
      qstate->env->mesh->num_detached_states++;
2620
0
    mesh_do_callback(mstate, LDNS_RCODE_NOERROR, msg->rep, c, &tv);
2621
0
  }
2622
0
}
2623
2624
void
2625
mesh_respond_serve_expired(struct mesh_state* mstate)
2626
0
{
2627
0
  if(!mstate->s.serve_expired_data)
2628
0
    mesh_serve_expired_init(mstate, -1);
2629
0
  mesh_serve_expired_callback(mstate);
2630
0
}
2631
2632
int mesh_jostle_exceeded(struct mesh_area* mesh)
2633
0
{
2634
0
  if(mesh->all.count < mesh->max_reply_states)
2635
0
    return 0;
2636
0
  return 1;
2637
0
}
2638
2639
void mesh_remove_callback(struct mesh_area* mesh, struct query_info* qinfo,
2640
  uint16_t qflags, mesh_cb_func_type cb, void* cb_arg)
2641
0
{
2642
0
  struct mesh_state* s = NULL;
2643
0
  s = mesh_area_find(mesh, NULL, qinfo, qflags&(BIT_RD|BIT_CD), 0, 0);
2644
0
  if(!s) return;
2645
0
  if(!mesh_state_del_cb(s, cb, cb_arg)) return;
2646
2647
  /* It was in the list and removed. */
2648
0
  log_assert(mesh->num_reply_addrs > 0);
2649
0
  mesh->num_reply_addrs--;
2650
0
  if(!s->reply_list && !s->cb_list) {
2651
    /* was a reply state, not anymore */
2652
0
    log_assert(mesh->num_reply_states > 0);
2653
0
    mesh->num_reply_states--;
2654
0
  }
2655
0
  if(!s->reply_list && !s->cb_list &&
2656
0
    s->super_set.count == 0) {
2657
0
    mesh->num_detached_states++;
2658
0
  }
2659
0
}