]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/unbound/daemon/worker.c
THIS BRANCH IS OBSOLETE, PLEASE READ:
[FreeBSD/FreeBSD.git] / contrib / unbound / daemon / worker.c
1 /*
2  * daemon/worker.c - worker that handles a pending list of requests.
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 implements the worker that handles callbacks on events, for
40  * pending requests.
41  */
42 #include "config.h"
43 #include "util/log.h"
44 #include "util/net_help.h"
45 #include "util/random.h"
46 #include "daemon/worker.h"
47 #include "daemon/daemon.h"
48 #include "daemon/remote.h"
49 #include "daemon/acl_list.h"
50 #include "util/netevent.h"
51 #include "util/config_file.h"
52 #include "util/module.h"
53 #include "util/regional.h"
54 #include "util/storage/slabhash.h"
55 #include "services/listen_dnsport.h"
56 #include "services/outside_network.h"
57 #include "services/outbound_list.h"
58 #include "services/cache/rrset.h"
59 #include "services/cache/infra.h"
60 #include "services/cache/dns.h"
61 #include "services/authzone.h"
62 #include "services/mesh.h"
63 #include "services/localzone.h"
64 #include "services/rpz.h"
65 #include "util/data/msgparse.h"
66 #include "util/data/msgencode.h"
67 #include "util/data/dname.h"
68 #include "util/fptr_wlist.h"
69 #include "util/tube.h"
70 #include "util/edns.h"
71 #include "iterator/iter_fwd.h"
72 #include "iterator/iter_hints.h"
73 #include "validator/autotrust.h"
74 #include "validator/val_anchor.h"
75 #include "respip/respip.h"
76 #include "libunbound/context.h"
77 #include "libunbound/libworker.h"
78 #include "sldns/sbuffer.h"
79 #include "sldns/wire2str.h"
80 #include "util/shm_side/shm_main.h"
81 #include "dnscrypt/dnscrypt.h"
82 #include "dnstap/dtstream.h"
83
84 #ifdef HAVE_SYS_TYPES_H
85 #  include <sys/types.h>
86 #endif
87 #ifdef HAVE_NETDB_H
88 #include <netdb.h>
89 #endif
90 #include <signal.h>
91 #ifdef UB_ON_WINDOWS
92 #include "winrc/win_svc.h"
93 #endif
94
95 /** Size of an UDP datagram */
96 #define NORMAL_UDP_SIZE 512 /* bytes */
97 /** ratelimit for error responses */
98 #define ERROR_RATELIMIT 100 /* qps */
99
100 /** 
101  * seconds to add to prefetch leeway.  This is a TTL that expires old rrsets
102  * earlier than they should in order to put the new update into the cache.
103  * This additional value is to make sure that if not all TTLs are equal in
104  * the message to be updated(and replaced), that rrsets with up to this much
105  * extra TTL are also replaced.  This means that the resulting new message
106  * will have (most likely) this TTL at least, avoiding very small 'split
107  * second' TTLs due to operators choosing relative primes for TTLs (or so).
108  * Also has to be at least one to break ties (and overwrite cached entry).
109  */
110 #define PREFETCH_EXPIRY_ADD 60
111
112 /** Report on memory usage by this thread and global */
113 static void
114 worker_mem_report(struct worker* ATTR_UNUSED(worker), 
115         struct serviced_query* ATTR_UNUSED(cur_serv))
116 {
117 #ifdef UNBOUND_ALLOC_STATS
118         /* measure memory leakage */
119         extern size_t unbound_mem_alloc, unbound_mem_freed;
120         /* debug func in validator module */
121         size_t total, front, back, mesh, msg, rrset, infra, ac, superac;
122         size_t me, iter, val, anch;
123         int i;
124 #ifdef CLIENT_SUBNET
125         size_t subnet = 0;
126 #endif /* CLIENT_SUBNET */
127         if(verbosity < VERB_ALGO) 
128                 return;
129         front = listen_get_mem(worker->front);
130         back = outnet_get_mem(worker->back);
131         msg = slabhash_get_mem(worker->env.msg_cache);
132         rrset = slabhash_get_mem(&worker->env.rrset_cache->table);
133         infra = infra_get_mem(worker->env.infra_cache);
134         mesh = mesh_get_mem(worker->env.mesh);
135         ac = alloc_get_mem(&worker->alloc);
136         superac = alloc_get_mem(&worker->daemon->superalloc);
137         anch = anchors_get_mem(worker->env.anchors);
138         iter = 0;
139         val = 0;
140         for(i=0; i<worker->env.mesh->mods.num; i++) {
141                 fptr_ok(fptr_whitelist_mod_get_mem(worker->env.mesh->
142                         mods.mod[i]->get_mem));
143                 if(strcmp(worker->env.mesh->mods.mod[i]->name, "validator")==0)
144                         val += (*worker->env.mesh->mods.mod[i]->get_mem)
145                                 (&worker->env, i);
146 #ifdef CLIENT_SUBNET
147                 else if(strcmp(worker->env.mesh->mods.mod[i]->name,
148                         "subnet")==0)
149                         subnet += (*worker->env.mesh->mods.mod[i]->get_mem)
150                                 (&worker->env, i);
151 #endif /* CLIENT_SUBNET */
152                 else    iter += (*worker->env.mesh->mods.mod[i]->get_mem)
153                                 (&worker->env, i);
154         }
155         me = sizeof(*worker) + sizeof(*worker->base) + sizeof(*worker->comsig)
156                 + comm_point_get_mem(worker->cmd_com) 
157                 + sizeof(worker->rndstate) 
158                 + regional_get_mem(worker->scratchpad) 
159                 + sizeof(*worker->env.scratch_buffer) 
160                 + sldns_buffer_capacity(worker->env.scratch_buffer)
161                 + forwards_get_mem(worker->env.fwds)
162                 + hints_get_mem(worker->env.hints);
163         if(worker->thread_num == 0)
164                 me += acl_list_get_mem(worker->daemon->acl);
165         if(cur_serv) {
166                 me += serviced_get_mem(cur_serv);
167         }
168         total = front+back+mesh+msg+rrset+infra+iter+val+ac+superac+me;
169 #ifdef CLIENT_SUBNET
170         total += subnet;
171         log_info("Memory conditions: %u front=%u back=%u mesh=%u msg=%u "
172                 "rrset=%u infra=%u iter=%u val=%u subnet=%u anchors=%u "
173                 "alloccache=%u globalalloccache=%u me=%u",
174                 (unsigned)total, (unsigned)front, (unsigned)back, 
175                 (unsigned)mesh, (unsigned)msg, (unsigned)rrset, (unsigned)infra,
176                 (unsigned)iter, (unsigned)val,
177                 (unsigned)subnet, (unsigned)anch, (unsigned)ac,
178                 (unsigned)superac, (unsigned)me);
179 #else /* no CLIENT_SUBNET */
180         log_info("Memory conditions: %u front=%u back=%u mesh=%u msg=%u "
181                 "rrset=%u infra=%u iter=%u val=%u anchors=%u "
182                 "alloccache=%u globalalloccache=%u me=%u",
183                 (unsigned)total, (unsigned)front, (unsigned)back, 
184                 (unsigned)mesh, (unsigned)msg, (unsigned)rrset, 
185                 (unsigned)infra, (unsigned)iter, (unsigned)val, (unsigned)anch,
186                 (unsigned)ac, (unsigned)superac, (unsigned)me);
187 #endif /* CLIENT_SUBNET */
188         log_info("Total heap memory estimate: %u  total-alloc: %u  "
189                 "total-free: %u", (unsigned)total, 
190                 (unsigned)unbound_mem_alloc, (unsigned)unbound_mem_freed);
191 #else /* no UNBOUND_ALLOC_STATS */
192         size_t val = 0;
193 #ifdef CLIENT_SUBNET
194         size_t subnet = 0;
195 #endif /* CLIENT_SUBNET */
196         int i;
197         if(verbosity < VERB_QUERY)
198                 return;
199         for(i=0; i<worker->env.mesh->mods.num; i++) {
200                 fptr_ok(fptr_whitelist_mod_get_mem(worker->env.mesh->
201                         mods.mod[i]->get_mem));
202                 if(strcmp(worker->env.mesh->mods.mod[i]->name, "validator")==0)
203                         val += (*worker->env.mesh->mods.mod[i]->get_mem)
204                                 (&worker->env, i);
205 #ifdef CLIENT_SUBNET
206                 else if(strcmp(worker->env.mesh->mods.mod[i]->name,
207                         "subnet")==0)
208                         subnet += (*worker->env.mesh->mods.mod[i]->get_mem)
209                                 (&worker->env, i);
210 #endif /* CLIENT_SUBNET */
211         }
212 #ifdef CLIENT_SUBNET
213         verbose(VERB_QUERY, "cache memory msg=%u rrset=%u infra=%u val=%u "
214                 "subnet=%u",
215                 (unsigned)slabhash_get_mem(worker->env.msg_cache),
216                 (unsigned)slabhash_get_mem(&worker->env.rrset_cache->table),
217                 (unsigned)infra_get_mem(worker->env.infra_cache),
218                 (unsigned)val, (unsigned)subnet);
219 #else /* no CLIENT_SUBNET */
220         verbose(VERB_QUERY, "cache memory msg=%u rrset=%u infra=%u val=%u",
221                 (unsigned)slabhash_get_mem(worker->env.msg_cache),
222                 (unsigned)slabhash_get_mem(&worker->env.rrset_cache->table),
223                 (unsigned)infra_get_mem(worker->env.infra_cache),
224                 (unsigned)val);
225 #endif /* CLIENT_SUBNET */
226 #endif /* UNBOUND_ALLOC_STATS */
227 }
228
229 void 
230 worker_send_cmd(struct worker* worker, enum worker_commands cmd)
231 {
232         uint32_t c = (uint32_t)htonl(cmd);
233         if(!tube_write_msg(worker->cmd, (uint8_t*)&c, sizeof(c), 0)) {
234                 log_err("worker send cmd %d failed", (int)cmd);
235         }
236 }
237
238 int 
239 worker_handle_reply(struct comm_point* c, void* arg, int error, 
240         struct comm_reply* reply_info)
241 {
242         struct module_qstate* q = (struct module_qstate*)arg;
243         struct worker* worker = q->env->worker;
244         struct outbound_entry e;
245         e.qstate = q;
246         e.qsent = NULL;
247
248         if(error != 0) {
249                 mesh_report_reply(worker->env.mesh, &e, reply_info, error);
250                 worker_mem_report(worker, NULL);
251                 return 0;
252         }
253         /* sanity check. */
254         if(!LDNS_QR_WIRE(sldns_buffer_begin(c->buffer))
255                 || LDNS_OPCODE_WIRE(sldns_buffer_begin(c->buffer)) != 
256                         LDNS_PACKET_QUERY
257                 || LDNS_QDCOUNT(sldns_buffer_begin(c->buffer)) > 1) {
258                 /* error becomes timeout for the module as if this reply
259                  * never arrived. */
260                 mesh_report_reply(worker->env.mesh, &e, reply_info, 
261                         NETEVENT_TIMEOUT);
262                 worker_mem_report(worker, NULL);
263                 return 0;
264         }
265         mesh_report_reply(worker->env.mesh, &e, reply_info, NETEVENT_NOERROR);
266         worker_mem_report(worker, NULL);
267         return 0;
268 }
269
270 int 
271 worker_handle_service_reply(struct comm_point* c, void* arg, int error, 
272         struct comm_reply* reply_info)
273 {
274         struct outbound_entry* e = (struct outbound_entry*)arg;
275         struct worker* worker = e->qstate->env->worker;
276         struct serviced_query *sq = e->qsent;
277
278         verbose(VERB_ALGO, "worker svcd callback for qstate %p", e->qstate);
279         if(error != 0) {
280                 mesh_report_reply(worker->env.mesh, e, reply_info, error);
281                 worker_mem_report(worker, sq);
282                 return 0;
283         }
284         /* sanity check. */
285         if(!LDNS_QR_WIRE(sldns_buffer_begin(c->buffer))
286                 || LDNS_OPCODE_WIRE(sldns_buffer_begin(c->buffer)) != 
287                         LDNS_PACKET_QUERY
288                 || LDNS_QDCOUNT(sldns_buffer_begin(c->buffer)) > 1) {
289                 /* error becomes timeout for the module as if this reply
290                  * never arrived. */
291                 verbose(VERB_ALGO, "worker: bad reply handled as timeout");
292                 mesh_report_reply(worker->env.mesh, e, reply_info, 
293                         NETEVENT_TIMEOUT);
294                 worker_mem_report(worker, sq);
295                 return 0;
296         }
297         mesh_report_reply(worker->env.mesh, e, reply_info, NETEVENT_NOERROR);
298         worker_mem_report(worker, sq);
299         return 0;
300 }
301
302 /** ratelimit error replies
303  * @param worker: the worker struct with ratelimit counter
304  * @param err: error code that would be wanted.
305  * @return value of err if okay, or -1 if it should be discarded instead.
306  */
307 static int
308 worker_err_ratelimit(struct worker* worker, int err)
309 {
310         if(worker->err_limit_time == *worker->env.now) {
311                 /* see if limit is exceeded for this second */
312                 if(worker->err_limit_count++ > ERROR_RATELIMIT)
313                         return -1;
314         } else {
315                 /* new second, new limits */
316                 worker->err_limit_time = *worker->env.now;
317                 worker->err_limit_count = 1;
318         }
319         return err;
320 }
321
322 /** check request sanity.
323  * @param pkt: the wire packet to examine for sanity.
324  * @param worker: parameters for checking.
325  * @return error code, 0 OK, or -1 discard.
326 */
327 static int 
328 worker_check_request(sldns_buffer* pkt, struct worker* worker)
329 {
330         if(sldns_buffer_limit(pkt) < LDNS_HEADER_SIZE) {
331                 verbose(VERB_QUERY, "request too short, discarded");
332                 return -1;
333         }
334         if(sldns_buffer_limit(pkt) > NORMAL_UDP_SIZE && 
335                 worker->daemon->cfg->harden_large_queries) {
336                 verbose(VERB_QUERY, "request too large, discarded");
337                 return -1;
338         }
339         if(LDNS_QR_WIRE(sldns_buffer_begin(pkt))) {
340                 verbose(VERB_QUERY, "request has QR bit on, discarded");
341                 return -1;
342         }
343         if(LDNS_TC_WIRE(sldns_buffer_begin(pkt))) {
344                 LDNS_TC_CLR(sldns_buffer_begin(pkt));
345                 verbose(VERB_QUERY, "request bad, has TC bit on");
346                 return worker_err_ratelimit(worker, LDNS_RCODE_FORMERR);
347         }
348         if(LDNS_OPCODE_WIRE(sldns_buffer_begin(pkt)) != LDNS_PACKET_QUERY &&
349                 LDNS_OPCODE_WIRE(sldns_buffer_begin(pkt)) != LDNS_PACKET_NOTIFY) {
350                 verbose(VERB_QUERY, "request unknown opcode %d", 
351                         LDNS_OPCODE_WIRE(sldns_buffer_begin(pkt)));
352                 return worker_err_ratelimit(worker, LDNS_RCODE_NOTIMPL);
353         }
354         if(LDNS_QDCOUNT(sldns_buffer_begin(pkt)) != 1) {
355                 verbose(VERB_QUERY, "request wrong nr qd=%d", 
356                         LDNS_QDCOUNT(sldns_buffer_begin(pkt)));
357                 return worker_err_ratelimit(worker, LDNS_RCODE_FORMERR);
358         }
359         if(LDNS_ANCOUNT(sldns_buffer_begin(pkt)) != 0 && 
360                 (LDNS_ANCOUNT(sldns_buffer_begin(pkt)) != 1 ||
361                 LDNS_OPCODE_WIRE(sldns_buffer_begin(pkt)) != LDNS_PACKET_NOTIFY)) {
362                 verbose(VERB_QUERY, "request wrong nr an=%d", 
363                         LDNS_ANCOUNT(sldns_buffer_begin(pkt)));
364                 return worker_err_ratelimit(worker, LDNS_RCODE_FORMERR);
365         }
366         if(LDNS_NSCOUNT(sldns_buffer_begin(pkt)) != 0) {
367                 verbose(VERB_QUERY, "request wrong nr ns=%d", 
368                         LDNS_NSCOUNT(sldns_buffer_begin(pkt)));
369                 return worker_err_ratelimit(worker, LDNS_RCODE_FORMERR);
370         }
371         if(LDNS_ARCOUNT(sldns_buffer_begin(pkt)) > 1) {
372                 verbose(VERB_QUERY, "request wrong nr ar=%d", 
373                         LDNS_ARCOUNT(sldns_buffer_begin(pkt)));
374                 return worker_err_ratelimit(worker, LDNS_RCODE_FORMERR);
375         }
376         return 0;
377 }
378
379 void 
380 worker_handle_control_cmd(struct tube* ATTR_UNUSED(tube), uint8_t* msg,
381         size_t len, int error, void* arg)
382 {
383         struct worker* worker = (struct worker*)arg;
384         enum worker_commands cmd;
385         if(error != NETEVENT_NOERROR) {
386                 free(msg);
387                 if(error == NETEVENT_CLOSED)
388                         comm_base_exit(worker->base);
389                 else    log_info("control event: %d", error);
390                 return;
391         }
392         if(len != sizeof(uint32_t)) {
393                 fatal_exit("bad control msg length %d", (int)len);
394         }
395         cmd = sldns_read_uint32(msg);
396         free(msg);
397         switch(cmd) {
398         case worker_cmd_quit:
399                 verbose(VERB_ALGO, "got control cmd quit");
400                 comm_base_exit(worker->base);
401                 break;
402         case worker_cmd_stats:
403                 verbose(VERB_ALGO, "got control cmd stats");
404                 server_stats_reply(worker, 1);
405                 break;
406         case worker_cmd_stats_noreset:
407                 verbose(VERB_ALGO, "got control cmd stats_noreset");
408                 server_stats_reply(worker, 0);
409                 break;
410         case worker_cmd_remote:
411                 verbose(VERB_ALGO, "got control cmd remote");
412                 daemon_remote_exec(worker);
413                 break;
414         default:
415                 log_err("bad command %d", (int)cmd);
416                 break;
417         }
418 }
419
420 /** check if a delegation is secure */
421 static enum sec_status
422 check_delegation_secure(struct reply_info *rep) 
423 {
424         /* return smallest security status */
425         size_t i;
426         enum sec_status sec = sec_status_secure;
427         enum sec_status s;
428         size_t num = rep->an_numrrsets + rep->ns_numrrsets;
429         /* check if answer and authority are OK */
430         for(i=0; i<num; i++) {
431                 s = ((struct packed_rrset_data*)rep->rrsets[i]->entry.data)
432                         ->security;
433                 if(s < sec)
434                         sec = s;
435         }
436         /* in additional, only unchecked triggers revalidation */
437         for(i=num; i<rep->rrset_count; i++) {
438                 s = ((struct packed_rrset_data*)rep->rrsets[i]->entry.data)
439                         ->security;
440                 if(s == sec_status_unchecked)
441                         return s;
442         }
443         return sec;
444 }
445
446 /** remove nonsecure from a delegation referral additional section */
447 static void
448 deleg_remove_nonsecure_additional(struct reply_info* rep)
449 {
450         /* we can simply edit it, since we are working in the scratch region */
451         size_t i;
452         enum sec_status s;
453
454         for(i = rep->an_numrrsets+rep->ns_numrrsets; i<rep->rrset_count; i++) {
455                 s = ((struct packed_rrset_data*)rep->rrsets[i]->entry.data)
456                         ->security;
457                 if(s != sec_status_secure) {
458                         memmove(rep->rrsets+i, rep->rrsets+i+1, 
459                                 sizeof(struct ub_packed_rrset_key*)* 
460                                 (rep->rrset_count - i - 1));
461                         rep->ar_numrrsets--; 
462                         rep->rrset_count--;
463                         i--;
464                 }
465         }
466 }
467
468 /** answer nonrecursive query from the cache */
469 static int
470 answer_norec_from_cache(struct worker* worker, struct query_info* qinfo,
471         uint16_t id, uint16_t flags, struct comm_reply* repinfo, 
472         struct edns_data* edns)
473 {
474         /* for a nonrecursive query return either:
475          *      o an error (servfail; we try to avoid this)
476          *      o a delegation (closest we have; this routine tries that)
477          *      o the answer (checked by answer_from_cache) 
478          *
479          * So, grab a delegation from the rrset cache. 
480          * Then check if it needs validation, if so, this routine fails,
481          * so that iterator can prime and validator can verify rrsets.
482          */
483         struct edns_data edns_bak;
484         uint16_t udpsize = edns->udp_size;
485         int secure = 0;
486         time_t timenow = *worker->env.now;
487         int must_validate = (!(flags&BIT_CD) || worker->env.cfg->ignore_cd)
488                 && worker->env.need_to_validate;
489         struct dns_msg *msg = NULL;
490         struct delegpt *dp;
491
492         dp = dns_cache_find_delegation(&worker->env, qinfo->qname, 
493                 qinfo->qname_len, qinfo->qtype, qinfo->qclass,
494                 worker->scratchpad, &msg, timenow);
495         if(!dp) { /* no delegation, need to reprime */
496                 return 0;
497         }
498         /* In case we have a local alias, copy it into the delegation message.
499          * Shallow copy should be fine, as we'll be done with msg in this
500          * function. */
501         msg->qinfo.local_alias = qinfo->local_alias;
502         if(must_validate) {
503                 switch(check_delegation_secure(msg->rep)) {
504                 case sec_status_unchecked:
505                         /* some rrsets have not been verified yet, go and 
506                          * let validator do that */
507                         return 0;
508                 case sec_status_bogus:
509                 case sec_status_secure_sentinel_fail:
510                         /* some rrsets are bogus, reply servfail */
511                         edns->edns_version = EDNS_ADVERTISED_VERSION;
512                         edns->udp_size = EDNS_ADVERTISED_SIZE;
513                         edns->ext_rcode = 0;
514                         edns->bits &= EDNS_DO;
515                         if(!inplace_cb_reply_servfail_call(&worker->env, qinfo, NULL,
516                                 msg->rep, LDNS_RCODE_SERVFAIL, edns, repinfo, worker->scratchpad))
517                                         return 0;
518                         error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL, 
519                                 &msg->qinfo, id, flags, edns);
520                         if(worker->stats.extended) {
521                                 worker->stats.ans_bogus++;
522                                 worker->stats.ans_rcode[LDNS_RCODE_SERVFAIL]++;
523                         }
524                         return 1;
525                 case sec_status_secure:
526                         /* all rrsets are secure */
527                         /* remove non-secure rrsets from the add. section*/
528                         if(worker->env.cfg->val_clean_additional)
529                                 deleg_remove_nonsecure_additional(msg->rep);
530                         secure = 1;
531                         break;
532                 case sec_status_indeterminate:
533                 case sec_status_insecure:
534                 default:
535                         /* not secure */
536                         secure = 0;
537                         break;
538                 }
539         }
540         /* return this delegation from the cache */
541         edns_bak = *edns;
542         edns->edns_version = EDNS_ADVERTISED_VERSION;
543         edns->udp_size = EDNS_ADVERTISED_SIZE;
544         edns->ext_rcode = 0;
545         edns->bits &= EDNS_DO;
546         if(!inplace_cb_reply_cache_call(&worker->env, qinfo, NULL, msg->rep,
547                 (int)(flags&LDNS_RCODE_MASK), edns, repinfo, worker->scratchpad))
548                         return 0;
549         msg->rep->flags |= BIT_QR|BIT_RA;
550         if(!apply_edns_options(edns, &edns_bak, worker->env.cfg,
551                 repinfo->c, worker->scratchpad) ||
552                 !reply_info_answer_encode(&msg->qinfo, msg->rep, id, flags, 
553                 repinfo->c->buffer, 0, 1, worker->scratchpad,
554                 udpsize, edns, (int)(edns->bits & EDNS_DO), secure)) {
555                 if(!inplace_cb_reply_servfail_call(&worker->env, qinfo, NULL, NULL,
556                         LDNS_RCODE_SERVFAIL, edns, repinfo, worker->scratchpad))
557                                 edns->opt_list = NULL;
558                 error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL, 
559                         &msg->qinfo, id, flags, edns);
560         }
561         if(worker->stats.extended) {
562                 if(secure) worker->stats.ans_secure++;
563                 server_stats_insrcode(&worker->stats, repinfo->c->buffer);
564         }
565         return 1;
566 }
567
568 /** Apply, if applicable, a response IP action to a cached answer.
569  * If the answer is rewritten as a result of an action, '*encode_repp' will
570  * point to the reply info containing the modified answer.  '*encode_repp' will
571  * be intact otherwise.
572  * It returns 1 on success, 0 otherwise. */
573 static int
574 apply_respip_action(struct worker* worker, const struct query_info* qinfo,
575         struct respip_client_info* cinfo, struct reply_info* rep,
576         struct comm_reply* repinfo, struct ub_packed_rrset_key** alias_rrset,
577         struct reply_info** encode_repp, struct auth_zones* az)
578 {
579         struct respip_action_info actinfo = {0, 0, 0, 0, NULL, 0, NULL};
580         actinfo.action = respip_none;
581
582         if(qinfo->qtype != LDNS_RR_TYPE_A &&
583                 qinfo->qtype != LDNS_RR_TYPE_AAAA &&
584                 qinfo->qtype != LDNS_RR_TYPE_ANY)
585                 return 1;
586
587         if(!respip_rewrite_reply(qinfo, cinfo, rep, encode_repp, &actinfo,
588                 alias_rrset, 0, worker->scratchpad, az))
589                 return 0;
590
591         /* xxx_deny actions mean dropping the reply, unless the original reply
592          * was redirected to response-ip data. */
593         if((actinfo.action == respip_deny ||
594                 actinfo.action == respip_inform_deny) &&
595                 *encode_repp == rep)
596                 *encode_repp = NULL;
597
598         /* If address info is returned, it means the action should be an
599          * 'inform' variant and the information should be logged. */
600         if(actinfo.addrinfo) {
601                 respip_inform_print(&actinfo, qinfo->qname,
602                         qinfo->qtype, qinfo->qclass, qinfo->local_alias,
603                         repinfo);
604
605                 if(worker->stats.extended && actinfo.rpz_used) {
606                         if(actinfo.rpz_disabled)
607                                 worker->stats.rpz_action[RPZ_DISABLED_ACTION]++;
608                         if(actinfo.rpz_cname_override)
609                                 worker->stats.rpz_action[RPZ_CNAME_OVERRIDE_ACTION]++;
610                         else
611                                 worker->stats.rpz_action[
612                                         respip_action_to_rpz_action(actinfo.action)]++;
613                 }
614         }
615
616         return 1;
617 }
618
619 /** answer query from the cache.
620  * Normally, the answer message will be built in repinfo->c->buffer; if the
621  * answer is supposed to be suppressed or the answer is supposed to be an
622  * incomplete CNAME chain, the buffer is explicitly cleared to signal the
623  * caller as such.  In the latter case *partial_rep will point to the incomplete
624  * reply, and this function is (possibly) supposed to be called again with that
625  * *partial_rep value to complete the chain.  In addition, if the query should
626  * be completely dropped, '*need_drop' will be set to 1. */
627 static int
628 answer_from_cache(struct worker* worker, struct query_info* qinfo,
629         struct respip_client_info* cinfo, int* need_drop, int* is_expired_answer,
630         int* is_secure_answer, struct ub_packed_rrset_key** alias_rrset,
631         struct reply_info** partial_repp,
632         struct reply_info* rep, uint16_t id, uint16_t flags,
633         struct comm_reply* repinfo, struct edns_data* edns)
634 {
635         struct edns_data edns_bak;
636         time_t timenow = *worker->env.now;
637         uint16_t udpsize = edns->udp_size;
638         struct reply_info* encode_rep = rep;
639         struct reply_info* partial_rep = *partial_repp;
640         int must_validate = (!(flags&BIT_CD) || worker->env.cfg->ignore_cd)
641                 && worker->env.need_to_validate;
642         *partial_repp = NULL;  /* avoid accidental further pass */
643
644         /* Check TTL */
645         if(rep->ttl < timenow) {
646                 /* Check if we need to serve expired now */
647                 if(worker->env.cfg->serve_expired &&
648                         !worker->env.cfg->serve_expired_client_timeout) {
649                                 if(worker->env.cfg->serve_expired_ttl &&
650                                         rep->serve_expired_ttl < timenow)
651                                         return 0;
652                                 if(!rrset_array_lock(rep->ref, rep->rrset_count, 0))
653                                         return 0;
654                                 *is_expired_answer = 1;
655                 } else {
656                         /* the rrsets may have been updated in the meantime.
657                          * we will refetch the message format from the
658                          * authoritative server
659                          */
660                         return 0;
661                 }
662         } else {
663                 if(!rrset_array_lock(rep->ref, rep->rrset_count, timenow))
664                         return 0;
665         }
666         /* locked and ids and ttls are OK. */
667
668         /* check CNAME chain (if any) */
669         if(rep->an_numrrsets > 0 && (rep->rrsets[0]->rk.type ==
670                 htons(LDNS_RR_TYPE_CNAME) || rep->rrsets[0]->rk.type ==
671                 htons(LDNS_RR_TYPE_DNAME))) {
672                 if(!reply_check_cname_chain(qinfo, rep)) {
673                         /* cname chain invalid, redo iterator steps */
674                         verbose(VERB_ALGO, "Cache reply: cname chain broken");
675                         goto bail_out;
676                 }
677         }
678         /* check security status of the cached answer */
679         if(must_validate && (rep->security == sec_status_bogus ||
680                 rep->security == sec_status_secure_sentinel_fail)) {
681                 /* BAD cached */
682                 edns->edns_version = EDNS_ADVERTISED_VERSION;
683                 edns->udp_size = EDNS_ADVERTISED_SIZE;
684                 edns->ext_rcode = 0;
685                 edns->bits &= EDNS_DO;
686                 if(!inplace_cb_reply_servfail_call(&worker->env, qinfo, NULL, rep,
687                         LDNS_RCODE_SERVFAIL, edns, repinfo, worker->scratchpad))
688                         goto bail_out;
689                 error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL,
690                         qinfo, id, flags, edns);
691                 rrset_array_unlock_touch(worker->env.rrset_cache,
692                         worker->scratchpad, rep->ref, rep->rrset_count);
693                 if(worker->stats.extended) {
694                         worker->stats.ans_bogus ++;
695                         worker->stats.ans_rcode[LDNS_RCODE_SERVFAIL] ++;
696                 }
697                 return 1;
698         } else if(rep->security == sec_status_unchecked && must_validate) {
699                 verbose(VERB_ALGO, "Cache reply: unchecked entry needs "
700                         "validation");
701                 goto bail_out; /* need to validate cache entry first */
702         } else if(rep->security == sec_status_secure) {
703                 if(reply_all_rrsets_secure(rep)) {
704                         *is_secure_answer = 1;
705                 } else {
706                         if(must_validate) {
707                                 verbose(VERB_ALGO, "Cache reply: secure entry"
708                                         " changed status");
709                                 goto bail_out; /* rrset changed, re-verify */
710                         }
711                         *is_secure_answer = 0;
712                 }
713         } else *is_secure_answer = 0;
714
715         edns_bak = *edns;
716         edns->edns_version = EDNS_ADVERTISED_VERSION;
717         edns->udp_size = EDNS_ADVERTISED_SIZE;
718         edns->ext_rcode = 0;
719         edns->bits &= EDNS_DO;
720         if(!inplace_cb_reply_cache_call(&worker->env, qinfo, NULL, rep,
721                 (int)(flags&LDNS_RCODE_MASK), edns, repinfo, worker->scratchpad))
722                 goto bail_out;
723         *alias_rrset = NULL; /* avoid confusion if caller set it to non-NULL */
724         if((worker->daemon->use_response_ip || worker->daemon->use_rpz) &&
725                 !partial_rep && !apply_respip_action(worker, qinfo, cinfo, rep,
726                 repinfo, alias_rrset,
727                 &encode_rep, worker->env.auth_zones)) {
728                 goto bail_out;
729         } else if(partial_rep &&
730                 !respip_merge_cname(partial_rep, qinfo, rep, cinfo,
731                 must_validate, &encode_rep, worker->scratchpad,
732                 worker->env.auth_zones)) {
733                 goto bail_out;
734         }
735         if(encode_rep != rep) {
736                 /* if rewritten, it can't be considered "secure" */
737                 *is_secure_answer = 0;
738         }
739         if(!encode_rep || *alias_rrset) {
740                 if(!encode_rep)
741                         *need_drop = 1;
742                 else {
743                         /* If a partial CNAME chain is found, we first need to
744                          * make a copy of the reply in the scratchpad so we
745                          * can release the locks and lookup the cache again. */
746                         *partial_repp = reply_info_copy(encode_rep, NULL,
747                                 worker->scratchpad);
748                         if(!*partial_repp)
749                                 goto bail_out;
750                 }
751         } else if(!apply_edns_options(edns, &edns_bak, worker->env.cfg,
752                 repinfo->c, worker->scratchpad) ||
753                 !reply_info_answer_encode(qinfo, encode_rep, id, flags,
754                 repinfo->c->buffer, timenow, 1, worker->scratchpad,
755                 udpsize, edns, (int)(edns->bits & EDNS_DO), *is_secure_answer)) {
756                 if(!inplace_cb_reply_servfail_call(&worker->env, qinfo, NULL, NULL,
757                         LDNS_RCODE_SERVFAIL, edns, repinfo, worker->scratchpad))
758                                 edns->opt_list = NULL;
759                 error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL, 
760                         qinfo, id, flags, edns);
761         }
762         /* cannot send the reply right now, because blocking network syscall
763          * is bad while holding locks. */
764         rrset_array_unlock_touch(worker->env.rrset_cache, worker->scratchpad,
765                 rep->ref, rep->rrset_count);
766         /* go and return this buffer to the client */
767         return 1;
768
769 bail_out:
770         rrset_array_unlock_touch(worker->env.rrset_cache, 
771                 worker->scratchpad, rep->ref, rep->rrset_count);
772         return 0;
773 }
774
775 /** Reply to client and perform prefetch to keep cache up to date. */
776 static void
777 reply_and_prefetch(struct worker* worker, struct query_info* qinfo, 
778         uint16_t flags, struct comm_reply* repinfo, time_t leeway, int noreply)
779 {
780         /* first send answer to client to keep its latency 
781          * as small as a cachereply */
782         if(!noreply) {
783                 if(repinfo->c->tcp_req_info) {
784                         sldns_buffer_copy(
785                                 repinfo->c->tcp_req_info->spool_buffer,
786                                 repinfo->c->buffer);
787                 }
788                 comm_point_send_reply(repinfo);
789         }
790         server_stats_prefetch(&worker->stats, worker);
791         
792         /* create the prefetch in the mesh as a normal lookup without
793          * client addrs waiting, which has the cache blacklisted (to bypass
794          * the cache and go to the network for the data). */
795         /* this (potentially) runs the mesh for the new query */
796         mesh_new_prefetch(worker->env.mesh, qinfo, flags, leeway + 
797                 PREFETCH_EXPIRY_ADD);
798 }
799
800 /**
801  * Fill CH class answer into buffer. Keeps query.
802  * @param pkt: buffer
803  * @param str: string to put into text record (<255).
804  *      array of strings, every string becomes a text record.
805  * @param num: number of strings in array.
806  * @param edns: edns reply information.
807  * @param worker: worker with scratch region.
808  * @param repinfo: reply information for a communication point.
809  */
810 static void
811 chaos_replystr(sldns_buffer* pkt, char** str, int num, struct edns_data* edns,
812         struct worker* worker, struct comm_reply* repinfo)
813 {
814         int i;
815         unsigned int rd = LDNS_RD_WIRE(sldns_buffer_begin(pkt));
816         unsigned int cd = LDNS_CD_WIRE(sldns_buffer_begin(pkt));
817         sldns_buffer_clear(pkt);
818         sldns_buffer_skip(pkt, (ssize_t)sizeof(uint16_t)); /* skip id */
819         sldns_buffer_write_u16(pkt, (uint16_t)(BIT_QR|BIT_RA));
820         if(rd) LDNS_RD_SET(sldns_buffer_begin(pkt));
821         if(cd) LDNS_CD_SET(sldns_buffer_begin(pkt));
822         sldns_buffer_write_u16(pkt, 1); /* qdcount */
823         sldns_buffer_write_u16(pkt, (uint16_t)num); /* ancount */
824         sldns_buffer_write_u16(pkt, 0); /* nscount */
825         sldns_buffer_write_u16(pkt, 0); /* arcount */
826         (void)query_dname_len(pkt); /* skip qname */
827         sldns_buffer_skip(pkt, (ssize_t)sizeof(uint16_t)); /* skip qtype */
828         sldns_buffer_skip(pkt, (ssize_t)sizeof(uint16_t)); /* skip qclass */
829         for(i=0; i<num; i++) {
830                 size_t len = strlen(str[i]);
831                 if(len>255) len=255; /* cap size of TXT record */
832                 sldns_buffer_write_u16(pkt, 0xc00c); /* compr ptr to query */
833                 sldns_buffer_write_u16(pkt, LDNS_RR_TYPE_TXT);
834                 sldns_buffer_write_u16(pkt, LDNS_RR_CLASS_CH);
835                 sldns_buffer_write_u32(pkt, 0); /* TTL */
836                 sldns_buffer_write_u16(pkt, sizeof(uint8_t) + len);
837                 sldns_buffer_write_u8(pkt, len);
838                 sldns_buffer_write(pkt, str[i], len);
839         }
840         sldns_buffer_flip(pkt);
841         edns->edns_version = EDNS_ADVERTISED_VERSION;
842         edns->udp_size = EDNS_ADVERTISED_SIZE;
843         edns->bits &= EDNS_DO;
844         if(!inplace_cb_reply_local_call(&worker->env, NULL, NULL, NULL,
845                 LDNS_RCODE_NOERROR, edns, repinfo, worker->scratchpad))
846                         edns->opt_list = NULL;
847         if(sldns_buffer_capacity(pkt) >=
848                 sldns_buffer_limit(pkt)+calc_edns_field_size(edns))
849                 attach_edns_record(pkt, edns);
850 }
851
852 /** Reply with one string */
853 static void
854 chaos_replyonestr(sldns_buffer* pkt, const char* str, struct edns_data* edns,
855         struct worker* worker, struct comm_reply* repinfo)
856 {
857         chaos_replystr(pkt, (char**)&str, 1, edns, worker, repinfo);
858 }
859
860 /**
861  * Create CH class trustanchor answer.
862  * @param pkt: buffer
863  * @param edns: edns reply information.
864  * @param w: worker with scratch region.
865  * @param repinfo: reply information for a communication point.
866  */
867 static void
868 chaos_trustanchor(sldns_buffer* pkt, struct edns_data* edns, struct worker* w,
869         struct comm_reply* repinfo)
870 {
871 #define TA_RESPONSE_MAX_TXT 16 /* max number of TXT records */
872 #define TA_RESPONSE_MAX_TAGS 32 /* max number of tags printed per zone */
873         char* str_array[TA_RESPONSE_MAX_TXT];
874         uint16_t tags[TA_RESPONSE_MAX_TAGS];
875         int num = 0;
876         struct trust_anchor* ta;
877
878         if(!w->env.need_to_validate) {
879                 /* no validator module, reply no trustanchors */
880                 chaos_replystr(pkt, NULL, 0, edns, w, repinfo);
881                 return;
882         }
883
884         /* fill the string with contents */
885         lock_basic_lock(&w->env.anchors->lock);
886         RBTREE_FOR(ta, struct trust_anchor*, w->env.anchors->tree) {
887                 char* str;
888                 size_t i, numtag, str_len = 255;
889                 if(num == TA_RESPONSE_MAX_TXT) continue;
890                 str = (char*)regional_alloc(w->scratchpad, str_len);
891                 if(!str) continue;
892                 lock_basic_lock(&ta->lock);
893                 numtag = anchor_list_keytags(ta, tags, TA_RESPONSE_MAX_TAGS);
894                 if(numtag == 0) {
895                         /* empty, insecure point */
896                         lock_basic_unlock(&ta->lock);
897                         continue;
898                 }
899                 str_array[num] = str;
900                 num++;
901
902                 /* spool name of anchor */
903                 (void)sldns_wire2str_dname_buf(ta->name, ta->namelen, str, str_len);
904                 str_len -= strlen(str); str += strlen(str);
905                 /* spool tags */
906                 for(i=0; i<numtag; i++) {
907                         snprintf(str, str_len, " %u", (unsigned)tags[i]);
908                         str_len -= strlen(str); str += strlen(str);
909                 }
910                 lock_basic_unlock(&ta->lock);
911         }
912         lock_basic_unlock(&w->env.anchors->lock);
913
914         chaos_replystr(pkt, str_array, num, edns, w, repinfo);
915         regional_free_all(w->scratchpad);
916 }
917
918 /**
919  * Answer CH class queries.
920  * @param w: worker
921  * @param qinfo: query info. Pointer into packet buffer.
922  * @param edns: edns info from query.
923  * @param repinfo: reply information for a communication point.
924  * @param pkt: packet buffer.
925  * @return: true if a reply is to be sent.
926  */
927 static int
928 answer_chaos(struct worker* w, struct query_info* qinfo,
929         struct edns_data* edns, struct comm_reply* repinfo, sldns_buffer* pkt)
930 {
931         struct config_file* cfg = w->env.cfg;
932         if(qinfo->qtype != LDNS_RR_TYPE_ANY && qinfo->qtype != LDNS_RR_TYPE_TXT)
933                 return 0;
934         if(query_dname_compare(qinfo->qname, 
935                 (uint8_t*)"\002id\006server") == 0 ||
936                 query_dname_compare(qinfo->qname, 
937                 (uint8_t*)"\010hostname\004bind") == 0)
938         {
939                 if(cfg->hide_identity) 
940                         return 0;
941                 if(cfg->identity==NULL || cfg->identity[0]==0) {
942                         char buf[MAXHOSTNAMELEN+1];
943                         if (gethostname(buf, MAXHOSTNAMELEN) == 0) {
944                                 buf[MAXHOSTNAMELEN] = 0;
945                                 chaos_replyonestr(pkt, buf, edns, w, repinfo);
946                         } else  {
947                                 log_err("gethostname: %s", strerror(errno));
948                                 chaos_replyonestr(pkt, "no hostname", edns, w, repinfo);
949                         }
950                 }
951                 else    chaos_replyonestr(pkt, cfg->identity, edns, w, repinfo);
952                 return 1;
953         }
954         if(query_dname_compare(qinfo->qname, 
955                 (uint8_t*)"\007version\006server") == 0 ||
956                 query_dname_compare(qinfo->qname, 
957                 (uint8_t*)"\007version\004bind") == 0)
958         {
959                 if(cfg->hide_version) 
960                         return 0;
961                 if(cfg->version==NULL || cfg->version[0]==0)
962                         chaos_replyonestr(pkt, PACKAGE_STRING, edns, w, repinfo);
963                 else    chaos_replyonestr(pkt, cfg->version, edns, w, repinfo);
964                 return 1;
965         }
966         if(query_dname_compare(qinfo->qname,
967                 (uint8_t*)"\013trustanchor\007unbound") == 0)
968         {
969                 if(cfg->hide_trustanchor)
970                         return 0;
971                 chaos_trustanchor(pkt, edns, w, repinfo);
972                 return 1;
973         }
974
975         return 0;
976 }
977
978 /**
979  * Answer notify queries.  These are notifies for authoritative zones,
980  * the reply is an ack that the notify has been received.  We need to check
981  * access permission here.
982  * @param w: worker
983  * @param qinfo: query info. Pointer into packet buffer.
984  * @param edns: edns info from query.
985  * @param repinfo: reply info with source address.
986  * @param pkt: packet buffer.
987  */
988 static void
989 answer_notify(struct worker* w, struct query_info* qinfo, 
990         struct edns_data* edns, sldns_buffer* pkt, struct comm_reply* repinfo)
991 {
992         int refused = 0;
993         int rcode = LDNS_RCODE_NOERROR;
994         uint32_t serial = 0;
995         int has_serial;
996         if(!w->env.auth_zones) return;
997         has_serial = auth_zone_parse_notify_serial(pkt, &serial);
998         if(auth_zones_notify(w->env.auth_zones, &w->env, qinfo->qname,
999                 qinfo->qname_len, qinfo->qclass, &repinfo->addr,
1000                 repinfo->addrlen, has_serial, serial, &refused)) {
1001                 rcode = LDNS_RCODE_NOERROR;
1002         } else {
1003                 if(refused)
1004                         rcode = LDNS_RCODE_REFUSED;
1005                 else    rcode = LDNS_RCODE_SERVFAIL;
1006         }
1007
1008         if(verbosity >= VERB_DETAIL) {
1009                 char buf[380];
1010                 char zname[255+1];
1011                 char sr[25];
1012                 dname_str(qinfo->qname, zname);
1013                 sr[0]=0;
1014                 if(has_serial)
1015                         snprintf(sr, sizeof(sr), "serial %u ",
1016                                 (unsigned)serial);
1017                 if(rcode == LDNS_RCODE_REFUSED)
1018                         snprintf(buf, sizeof(buf),
1019                                 "refused NOTIFY %sfor %s from", sr, zname);
1020                 else if(rcode == LDNS_RCODE_SERVFAIL)
1021                         snprintf(buf, sizeof(buf),
1022                                 "servfail for NOTIFY %sfor %s from", sr, zname);
1023                 else    snprintf(buf, sizeof(buf),
1024                                 "received NOTIFY %sfor %s from", sr, zname);
1025                 log_addr(VERB_DETAIL, buf, &repinfo->addr, repinfo->addrlen);
1026         }
1027         edns->edns_version = EDNS_ADVERTISED_VERSION;
1028         edns->udp_size = EDNS_ADVERTISED_SIZE;
1029         edns->ext_rcode = 0;
1030         edns->bits &= EDNS_DO;
1031         edns->opt_list = NULL;
1032         error_encode(pkt, rcode, qinfo,
1033                 *(uint16_t*)(void *)sldns_buffer_begin(pkt),
1034                 sldns_buffer_read_u16_at(pkt, 2), edns);
1035         LDNS_OPCODE_SET(sldns_buffer_begin(pkt), LDNS_PACKET_NOTIFY);
1036 }
1037
1038 static int
1039 deny_refuse(struct comm_point* c, enum acl_access acl,
1040         enum acl_access deny, enum acl_access refuse,
1041         struct worker* worker, struct comm_reply* repinfo)
1042 {
1043         if(acl == deny) {
1044                 comm_point_drop_reply(repinfo);
1045                 if(worker->stats.extended)
1046                         worker->stats.unwanted_queries++;
1047                 return 0;
1048         } else if(acl == refuse) {
1049                 log_addr(VERB_ALGO, "refused query from",
1050                         &repinfo->addr, repinfo->addrlen);
1051                 log_buf(VERB_ALGO, "refuse", c->buffer);
1052                 if(worker->stats.extended)
1053                         worker->stats.unwanted_queries++;
1054                 if(worker_check_request(c->buffer, worker) == -1) {
1055                         comm_point_drop_reply(repinfo);
1056                         return 0; /* discard this */
1057                 }
1058                 sldns_buffer_set_limit(c->buffer, LDNS_HEADER_SIZE);
1059                 sldns_buffer_write_at(c->buffer, 4, 
1060                         (uint8_t*)"\0\0\0\0\0\0\0\0", 8);
1061                 LDNS_QR_SET(sldns_buffer_begin(c->buffer));
1062                 LDNS_RCODE_SET(sldns_buffer_begin(c->buffer), 
1063                         LDNS_RCODE_REFUSED);
1064                 sldns_buffer_set_position(c->buffer, LDNS_HEADER_SIZE);
1065                 sldns_buffer_flip(c->buffer);
1066                 return 1;
1067         }
1068
1069         return -1;
1070 }
1071
1072 static int
1073 deny_refuse_all(struct comm_point* c, enum acl_access acl,
1074         struct worker* worker, struct comm_reply* repinfo)
1075 {
1076         return deny_refuse(c, acl, acl_deny, acl_refuse, worker, repinfo);
1077 }
1078
1079 static int
1080 deny_refuse_non_local(struct comm_point* c, enum acl_access acl,
1081         struct worker* worker, struct comm_reply* repinfo)
1082 {
1083         return deny_refuse(c, acl, acl_deny_non_local, acl_refuse_non_local, worker, repinfo);
1084 }
1085
1086 int 
1087 worker_handle_request(struct comm_point* c, void* arg, int error,
1088         struct comm_reply* repinfo)
1089 {
1090         struct worker* worker = (struct worker*)arg;
1091         int ret;
1092         hashvalue_type h;
1093         struct lruhash_entry* e;
1094         struct query_info qinfo;
1095         struct edns_data edns;
1096         enum acl_access acl;
1097         struct acl_addr* acladdr;
1098         int rc = 0;
1099         int need_drop = 0;
1100         int is_expired_answer = 0;
1101         int is_secure_answer = 0;
1102         /* We might have to chase a CNAME chain internally, in which case
1103          * we'll have up to two replies and combine them to build a complete
1104          * answer.  These variables control this case. */
1105         struct ub_packed_rrset_key* alias_rrset = NULL;
1106         struct reply_info* partial_rep = NULL;
1107         struct query_info* lookup_qinfo = &qinfo;
1108         struct query_info qinfo_tmp; /* placeholder for lookup_qinfo */
1109         struct respip_client_info* cinfo = NULL, cinfo_tmp;
1110         memset(&qinfo, 0, sizeof(qinfo));
1111
1112         if((error != NETEVENT_NOERROR && error != NETEVENT_DONE)|| !repinfo) {
1113                 /* some bad tcp query DNS formats give these error calls */
1114                 verbose(VERB_ALGO, "handle request called with err=%d", error);
1115                 return 0;
1116         }
1117 #ifdef USE_DNSCRYPT
1118         repinfo->max_udp_size = worker->daemon->cfg->max_udp_size;
1119         if(!dnsc_handle_curved_request(worker->daemon->dnscenv, repinfo)) {
1120                 worker->stats.num_query_dnscrypt_crypted_malformed++;
1121                 return 0;
1122         }
1123         if(c->dnscrypt && !repinfo->is_dnscrypted) {
1124                 char buf[LDNS_MAX_DOMAINLEN+1];
1125                 /* Check if this is unencrypted and asking for certs */
1126                 if(worker_check_request(c->buffer, worker) != 0) {
1127                         verbose(VERB_ALGO,
1128                                 "dnscrypt: worker check request: bad query.");
1129                         log_addr(VERB_CLIENT,"from",&repinfo->addr,
1130                                 repinfo->addrlen);
1131                         comm_point_drop_reply(repinfo);
1132                         return 0;
1133                 }
1134                 if(!query_info_parse(&qinfo, c->buffer)) {
1135                         verbose(VERB_ALGO,
1136                                 "dnscrypt: worker parse request: formerror.");
1137                         log_addr(VERB_CLIENT, "from", &repinfo->addr,
1138                                 repinfo->addrlen);
1139                         comm_point_drop_reply(repinfo);
1140                         return 0;
1141                 }
1142                 dname_str(qinfo.qname, buf);
1143                 if(!(qinfo.qtype == LDNS_RR_TYPE_TXT &&
1144                         strcasecmp(buf,
1145                         worker->daemon->dnscenv->provider_name) == 0)) {
1146                         verbose(VERB_ALGO,
1147                                 "dnscrypt: not TXT \"%s\". Received: %s \"%s\"",
1148                                 worker->daemon->dnscenv->provider_name,
1149                                 sldns_rr_descript(qinfo.qtype)->_name,
1150                                 buf);
1151                         comm_point_drop_reply(repinfo);
1152                         worker->stats.num_query_dnscrypt_cleartext++;
1153                         return 0;
1154                 }
1155                 worker->stats.num_query_dnscrypt_cert++;
1156                 sldns_buffer_rewind(c->buffer);
1157         } else if(c->dnscrypt && repinfo->is_dnscrypted) {
1158                 worker->stats.num_query_dnscrypt_crypted++;
1159         }
1160 #endif
1161 #ifdef USE_DNSTAP
1162         if(worker->dtenv.log_client_query_messages)
1163                 dt_msg_send_client_query(&worker->dtenv, &repinfo->addr, c->type,
1164                         c->buffer);
1165 #endif
1166         acladdr = acl_addr_lookup(worker->daemon->acl, &repinfo->addr, 
1167                 repinfo->addrlen);
1168         acl = acl_get_control(acladdr);
1169         if((ret=deny_refuse_all(c, acl, worker, repinfo)) != -1)
1170         {
1171                 if(ret == 1)
1172                         goto send_reply;
1173                 return ret;
1174         }
1175         if((ret=worker_check_request(c->buffer, worker)) != 0) {
1176                 verbose(VERB_ALGO, "worker check request: bad query.");
1177                 log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1178                 if(ret != -1) {
1179                         LDNS_QR_SET(sldns_buffer_begin(c->buffer));
1180                         LDNS_RCODE_SET(sldns_buffer_begin(c->buffer), ret);
1181                         return 1;
1182                 }
1183                 comm_point_drop_reply(repinfo);
1184                 return 0;
1185         }
1186
1187         worker->stats.num_queries++;
1188
1189         /* check if this query should be dropped based on source ip rate limiting */
1190         if(!infra_ip_ratelimit_inc(worker->env.infra_cache, repinfo,
1191                         *worker->env.now, c->buffer)) {
1192                 /* See if we are passed through with slip factor */
1193                 if(worker->env.cfg->ip_ratelimit_factor != 0 &&
1194                         ub_random_max(worker->env.rnd,
1195                                                   worker->env.cfg->ip_ratelimit_factor) == 0) {
1196
1197                         char addrbuf[128];
1198                         addr_to_str(&repinfo->addr, repinfo->addrlen,
1199                                                 addrbuf, sizeof(addrbuf));
1200                   verbose(VERB_QUERY, "ip_ratelimit allowed through for ip address %s because of slip in ip_ratelimit_factor",
1201                                   addrbuf);
1202                 } else {
1203                         worker->stats.num_queries_ip_ratelimited++;
1204                         comm_point_drop_reply(repinfo);
1205                         return 0;
1206                 }
1207         }
1208
1209         /* see if query is in the cache */
1210         if(!query_info_parse(&qinfo, c->buffer)) {
1211                 verbose(VERB_ALGO, "worker parse request: formerror.");
1212                 log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1213                 memset(&qinfo, 0, sizeof(qinfo)); /* zero qinfo.qname */
1214                 if(worker_err_ratelimit(worker, LDNS_RCODE_FORMERR) == -1) {
1215                         comm_point_drop_reply(repinfo);
1216                         return 0;
1217                 }
1218                 sldns_buffer_rewind(c->buffer);
1219                 LDNS_QR_SET(sldns_buffer_begin(c->buffer));
1220                 LDNS_RCODE_SET(sldns_buffer_begin(c->buffer), 
1221                         LDNS_RCODE_FORMERR);
1222                 goto send_reply;
1223         }
1224         if(worker->env.cfg->log_queries) {
1225                 char ip[128];
1226                 addr_to_str(&repinfo->addr, repinfo->addrlen, ip, sizeof(ip));
1227                 log_query_in(ip, qinfo.qname, qinfo.qtype, qinfo.qclass);
1228         }
1229         if(qinfo.qtype == LDNS_RR_TYPE_AXFR || 
1230                 qinfo.qtype == LDNS_RR_TYPE_IXFR) {
1231                 verbose(VERB_ALGO, "worker request: refused zone transfer.");
1232                 log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1233                 sldns_buffer_rewind(c->buffer);
1234                 LDNS_QR_SET(sldns_buffer_begin(c->buffer));
1235                 LDNS_RCODE_SET(sldns_buffer_begin(c->buffer), 
1236                         LDNS_RCODE_REFUSED);
1237                 if(worker->stats.extended) {
1238                         worker->stats.qtype[qinfo.qtype]++;
1239                 }
1240                 goto send_reply;
1241         }
1242         if(qinfo.qtype == LDNS_RR_TYPE_OPT || 
1243                 qinfo.qtype == LDNS_RR_TYPE_TSIG ||
1244                 qinfo.qtype == LDNS_RR_TYPE_TKEY ||
1245                 qinfo.qtype == LDNS_RR_TYPE_MAILA ||
1246                 qinfo.qtype == LDNS_RR_TYPE_MAILB ||
1247                 (qinfo.qtype >= 128 && qinfo.qtype <= 248)) {
1248                 verbose(VERB_ALGO, "worker request: formerror for meta-type.");
1249                 log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1250                 if(worker_err_ratelimit(worker, LDNS_RCODE_FORMERR) == -1) {
1251                         comm_point_drop_reply(repinfo);
1252                         return 0;
1253                 }
1254                 sldns_buffer_rewind(c->buffer);
1255                 LDNS_QR_SET(sldns_buffer_begin(c->buffer));
1256                 LDNS_RCODE_SET(sldns_buffer_begin(c->buffer), 
1257                         LDNS_RCODE_FORMERR);
1258                 if(worker->stats.extended) {
1259                         worker->stats.qtype[qinfo.qtype]++;
1260                 }
1261                 goto send_reply;
1262         }
1263         if((ret=parse_edns_from_pkt(c->buffer, &edns, worker->scratchpad)) != 0) {
1264                 struct edns_data reply_edns;
1265                 verbose(VERB_ALGO, "worker parse edns: formerror.");
1266                 log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1267                 memset(&reply_edns, 0, sizeof(reply_edns));
1268                 reply_edns.edns_present = 1;
1269                 reply_edns.udp_size = EDNS_ADVERTISED_SIZE;
1270                 LDNS_RCODE_SET(sldns_buffer_begin(c->buffer), ret);
1271                 error_encode(c->buffer, ret, &qinfo,
1272                         *(uint16_t*)(void *)sldns_buffer_begin(c->buffer),
1273                         sldns_buffer_read_u16_at(c->buffer, 2), &reply_edns);
1274                 regional_free_all(worker->scratchpad);
1275                 goto send_reply;
1276         }
1277         if(edns.edns_present) {
1278                 struct edns_option* edns_opt;
1279                 if(edns.edns_version != 0) {
1280                         edns.ext_rcode = (uint8_t)(EDNS_RCODE_BADVERS>>4);
1281                         edns.edns_version = EDNS_ADVERTISED_VERSION;
1282                         edns.udp_size = EDNS_ADVERTISED_SIZE;
1283                         edns.bits &= EDNS_DO;
1284                         edns.opt_list = NULL;
1285                         verbose(VERB_ALGO, "query with bad edns version.");
1286                         log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1287                         error_encode(c->buffer, EDNS_RCODE_BADVERS&0xf, &qinfo,
1288                                 *(uint16_t*)(void *)sldns_buffer_begin(c->buffer),
1289                                 sldns_buffer_read_u16_at(c->buffer, 2), NULL);
1290                         if(sldns_buffer_capacity(c->buffer) >=
1291                            sldns_buffer_limit(c->buffer)+calc_edns_field_size(&edns))
1292                                 attach_edns_record(c->buffer, &edns);
1293                         regional_free_all(worker->scratchpad);
1294                         goto send_reply;
1295                 }
1296                 if(edns.udp_size < NORMAL_UDP_SIZE &&
1297                    worker->daemon->cfg->harden_short_bufsize) {
1298                         verbose(VERB_QUERY, "worker request: EDNS bufsize %d ignored",
1299                                 (int)edns.udp_size);
1300                         log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1301                         edns.udp_size = NORMAL_UDP_SIZE;
1302                 }
1303                 if(c->type != comm_udp) {
1304                         edns_opt = edns_opt_list_find(edns.opt_list, LDNS_EDNS_KEEPALIVE);
1305                         if(edns_opt && edns_opt->opt_len > 0) {
1306                                 edns.ext_rcode = 0;
1307                                 edns.edns_version = EDNS_ADVERTISED_VERSION;
1308                                 edns.udp_size = EDNS_ADVERTISED_SIZE;
1309                                 edns.bits &= EDNS_DO;
1310                                 edns.opt_list = NULL;
1311                                 verbose(VERB_ALGO, "query with bad edns keepalive.");
1312                                 log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1313                                 error_encode(c->buffer, LDNS_RCODE_FORMERR, &qinfo,
1314                                         *(uint16_t*)(void *)sldns_buffer_begin(c->buffer),
1315                                         sldns_buffer_read_u16_at(c->buffer, 2), NULL);
1316                                 if(sldns_buffer_capacity(c->buffer) >=
1317                                    sldns_buffer_limit(c->buffer)+calc_edns_field_size(&edns))
1318                                         attach_edns_record(c->buffer, &edns);
1319                                 regional_free_all(worker->scratchpad);
1320                                 goto send_reply;
1321                         }
1322                 }
1323         }
1324         if(edns.udp_size > worker->daemon->cfg->max_udp_size &&
1325                 c->type == comm_udp) {
1326                 verbose(VERB_QUERY,
1327                         "worker request: max UDP reply size modified"
1328                         " (%d to max-udp-size)", (int)edns.udp_size);
1329                 log_addr(VERB_CLIENT,"from",&repinfo->addr, repinfo->addrlen);
1330                 edns.udp_size = worker->daemon->cfg->max_udp_size;
1331         }
1332         if(edns.udp_size < LDNS_HEADER_SIZE) {
1333                 verbose(VERB_ALGO, "worker request: edns is too small.");
1334                 log_addr(VERB_CLIENT, "from", &repinfo->addr, repinfo->addrlen);
1335                 LDNS_QR_SET(sldns_buffer_begin(c->buffer));
1336                 LDNS_TC_SET(sldns_buffer_begin(c->buffer));
1337                 LDNS_RCODE_SET(sldns_buffer_begin(c->buffer), 
1338                         LDNS_RCODE_SERVFAIL);
1339                 sldns_buffer_set_position(c->buffer, LDNS_HEADER_SIZE);
1340                 sldns_buffer_write_at(c->buffer, 4, 
1341                         (uint8_t*)"\0\0\0\0\0\0\0\0", 8);
1342                 sldns_buffer_flip(c->buffer);
1343                 regional_free_all(worker->scratchpad);
1344                 goto send_reply;
1345         }
1346         if(worker->stats.extended)
1347                 server_stats_insquery(&worker->stats, c, qinfo.qtype,
1348                         qinfo.qclass, &edns, repinfo);
1349         if(c->type != comm_udp)
1350                 edns.udp_size = 65535; /* max size for TCP replies */
1351         if(qinfo.qclass == LDNS_RR_CLASS_CH && answer_chaos(worker, &qinfo,
1352                 &edns, repinfo, c->buffer)) {
1353                 regional_free_all(worker->scratchpad);
1354                 goto send_reply;
1355         }
1356         if(LDNS_OPCODE_WIRE(sldns_buffer_begin(c->buffer)) ==
1357                 LDNS_PACKET_NOTIFY) {
1358                 answer_notify(worker, &qinfo, &edns, c->buffer, repinfo);
1359                 regional_free_all(worker->scratchpad);
1360                 goto send_reply;
1361         }
1362         if(local_zones_answer(worker->daemon->local_zones, &worker->env, &qinfo,
1363                 &edns, c->buffer, worker->scratchpad, repinfo, acladdr->taglist,
1364                 acladdr->taglen, acladdr->tag_actions,
1365                 acladdr->tag_actions_size, acladdr->tag_datas,
1366                 acladdr->tag_datas_size, worker->daemon->cfg->tagname,
1367                 worker->daemon->cfg->num_tags, acladdr->view)) {
1368                 regional_free_all(worker->scratchpad);
1369                 if(sldns_buffer_limit(c->buffer) == 0) {
1370                         comm_point_drop_reply(repinfo);
1371                         return 0;
1372                 }
1373                 goto send_reply;
1374         }
1375         if(worker->env.auth_zones &&
1376                 rpz_apply_qname_trigger(worker->env.auth_zones,
1377                 &worker->env, &qinfo, &edns, c->buffer, worker->scratchpad,
1378                 repinfo, acladdr->taglist, acladdr->taglen, &worker->stats)) {
1379                 regional_free_all(worker->scratchpad);
1380                 if(sldns_buffer_limit(c->buffer) == 0) {
1381                         comm_point_drop_reply(repinfo);
1382                         return 0;
1383                 }
1384                 goto send_reply;
1385         }
1386         if(worker->env.auth_zones &&
1387                 auth_zones_answer(worker->env.auth_zones, &worker->env,
1388                 &qinfo, &edns, repinfo, c->buffer, worker->scratchpad)) {
1389                 regional_free_all(worker->scratchpad);
1390                 if(sldns_buffer_limit(c->buffer) == 0) {
1391                         comm_point_drop_reply(repinfo);
1392                         return 0;
1393                 }
1394                 /* set RA for everyone that can have recursion (based on
1395                  * access control list) */
1396                 if(LDNS_RD_WIRE(sldns_buffer_begin(c->buffer)) &&
1397                    acl != acl_deny_non_local && acl != acl_refuse_non_local)
1398                         LDNS_RA_SET(sldns_buffer_begin(c->buffer));
1399                 goto send_reply;
1400         }
1401
1402         /* We've looked in our local zones. If the answer isn't there, we
1403          * might need to bail out based on ACLs now. */
1404         if((ret=deny_refuse_non_local(c, acl, worker, repinfo)) != -1)
1405         {
1406                 regional_free_all(worker->scratchpad);
1407                 if(ret == 1)
1408                         goto send_reply;
1409                 return ret;
1410         }
1411
1412         /* If this request does not have the recursion bit set, verify
1413          * ACLs allow the recursion bit to be treated as set. */
1414         if(!(LDNS_RD_WIRE(sldns_buffer_begin(c->buffer))) &&
1415                 acl == acl_allow_setrd ) {
1416                 LDNS_RD_SET(sldns_buffer_begin(c->buffer));
1417         }
1418
1419         /* If this request does not have the recursion bit set, verify
1420          * ACLs allow the snooping. */
1421         if(!(LDNS_RD_WIRE(sldns_buffer_begin(c->buffer))) &&
1422                 acl != acl_allow_snoop ) {
1423                 error_encode(c->buffer, LDNS_RCODE_REFUSED, &qinfo,
1424                         *(uint16_t*)(void *)sldns_buffer_begin(c->buffer),
1425                         sldns_buffer_read_u16_at(c->buffer, 2), NULL);
1426                 regional_free_all(worker->scratchpad);
1427                 log_addr(VERB_ALGO, "refused nonrec (cache snoop) query from",
1428                         &repinfo->addr, repinfo->addrlen);
1429                 goto send_reply;
1430         }
1431
1432         /* If we've found a local alias, replace the qname with the alias
1433          * target before resolving it. */
1434         if(qinfo.local_alias) {
1435                 struct ub_packed_rrset_key* rrset = qinfo.local_alias->rrset;
1436                 struct packed_rrset_data* d = rrset->entry.data;
1437
1438                 /* Sanity check: our current implementation only supports
1439                  * a single CNAME RRset as a local alias. */
1440                 if(qinfo.local_alias->next ||
1441                         rrset->rk.type != htons(LDNS_RR_TYPE_CNAME) ||
1442                         d->count != 1) {
1443                         log_err("assumption failure: unexpected local alias");
1444                         regional_free_all(worker->scratchpad);
1445                         return 0; /* drop it */
1446                 }
1447                 qinfo.qname = d->rr_data[0] + 2;
1448                 qinfo.qname_len = d->rr_len[0] - 2;
1449         }
1450
1451         /* If we may apply IP-based actions to the answer, build the client
1452          * information.  As this can be expensive, skip it if there is
1453          * absolutely no possibility of it. */
1454         if((worker->daemon->use_response_ip || worker->daemon->use_rpz) &&
1455                 (qinfo.qtype == LDNS_RR_TYPE_A ||
1456                 qinfo.qtype == LDNS_RR_TYPE_AAAA ||
1457                 qinfo.qtype == LDNS_RR_TYPE_ANY)) {
1458                 cinfo_tmp.taglist = acladdr->taglist;
1459                 cinfo_tmp.taglen = acladdr->taglen;
1460                 cinfo_tmp.tag_actions = acladdr->tag_actions;
1461                 cinfo_tmp.tag_actions_size = acladdr->tag_actions_size;
1462                 cinfo_tmp.tag_datas = acladdr->tag_datas;
1463                 cinfo_tmp.tag_datas_size = acladdr->tag_datas_size;
1464                 cinfo_tmp.view = acladdr->view;
1465                 cinfo_tmp.respip_set = worker->daemon->respip_set;
1466                 cinfo = &cinfo_tmp;
1467         }
1468
1469 lookup_cache:
1470         /* Lookup the cache.  In case we chase an intermediate CNAME chain
1471          * this is a two-pass operation, and lookup_qinfo is different for
1472          * each pass.  We should still pass the original qinfo to
1473          * answer_from_cache(), however, since it's used to build the reply. */
1474         if(!edns_bypass_cache_stage(edns.opt_list, &worker->env)) {
1475                 is_expired_answer = 0;
1476                 is_secure_answer = 0;
1477                 h = query_info_hash(lookup_qinfo, sldns_buffer_read_u16_at(c->buffer, 2));
1478                 if((e=slabhash_lookup(worker->env.msg_cache, h, lookup_qinfo, 0))) {
1479                         /* answer from cache - we have acquired a readlock on it */
1480                         if(answer_from_cache(worker, &qinfo,
1481                                 cinfo, &need_drop, &is_expired_answer, &is_secure_answer,
1482                                 &alias_rrset, &partial_rep, (struct reply_info*)e->data,
1483                                 *(uint16_t*)(void *)sldns_buffer_begin(c->buffer),
1484                                 sldns_buffer_read_u16_at(c->buffer, 2), repinfo,
1485                                 &edns)) {
1486                                 /* prefetch it if the prefetch TTL expired.
1487                                  * Note that if there is more than one pass
1488                                  * its qname must be that used for cache
1489                                  * lookup. */
1490                                 if((worker->env.cfg->prefetch && *worker->env.now >=
1491                                                         ((struct reply_info*)e->data)->prefetch_ttl) ||
1492                                                 (worker->env.cfg->serve_expired &&
1493                                                 *worker->env.now >= ((struct reply_info*)e->data)->ttl)) {
1494
1495                                         time_t leeway = ((struct reply_info*)e->
1496                                                 data)->ttl - *worker->env.now;
1497                                         if(((struct reply_info*)e->data)->ttl
1498                                                 < *worker->env.now)
1499                                                 leeway = 0;
1500                                         lock_rw_unlock(&e->lock);
1501                                         reply_and_prefetch(worker, lookup_qinfo,
1502                                                 sldns_buffer_read_u16_at(c->buffer, 2),
1503                                                 repinfo, leeway,
1504                                                 (partial_rep || need_drop));
1505                                         if(!partial_rep) {
1506                                                 rc = 0;
1507                                                 regional_free_all(worker->scratchpad);
1508                                                 goto send_reply_rc;
1509                                         }
1510                                 } else if(!partial_rep) {
1511                                         lock_rw_unlock(&e->lock);
1512                                         regional_free_all(worker->scratchpad);
1513                                         goto send_reply;
1514                                 } else {
1515                                         /* Note that we've already released the
1516                                          * lock if we're here after prefetch. */
1517                                         lock_rw_unlock(&e->lock);
1518                                 }
1519                                 /* We've found a partial reply ending with an
1520                                  * alias.  Replace the lookup qinfo for the
1521                                  * alias target and lookup the cache again to
1522                                  * (possibly) complete the reply.  As we're
1523                                  * passing the "base" reply, there will be no
1524                                  * more alias chasing. */
1525                                 memset(&qinfo_tmp, 0, sizeof(qinfo_tmp));
1526                                 get_cname_target(alias_rrset, &qinfo_tmp.qname,
1527                                         &qinfo_tmp.qname_len);
1528                                 if(!qinfo_tmp.qname) {
1529                                         log_err("unexpected: invalid answer alias");
1530                                         regional_free_all(worker->scratchpad);
1531                                         return 0; /* drop query */
1532                                 }
1533                                 qinfo_tmp.qtype = qinfo.qtype;
1534                                 qinfo_tmp.qclass = qinfo.qclass;
1535                                 lookup_qinfo = &qinfo_tmp;
1536                                 goto lookup_cache;
1537                         }
1538                         verbose(VERB_ALGO, "answer from the cache failed");
1539                         lock_rw_unlock(&e->lock);
1540                 }
1541                 if(!LDNS_RD_WIRE(sldns_buffer_begin(c->buffer))) {
1542                         if(answer_norec_from_cache(worker, &qinfo,
1543                                 *(uint16_t*)(void *)sldns_buffer_begin(c->buffer), 
1544                                 sldns_buffer_read_u16_at(c->buffer, 2), repinfo, 
1545                                 &edns)) {
1546                                 regional_free_all(worker->scratchpad);
1547                                 goto send_reply;
1548                         }
1549                         verbose(VERB_ALGO, "answer norec from cache -- "
1550                                 "need to validate or not primed");
1551                 }
1552         }
1553         sldns_buffer_rewind(c->buffer);
1554         server_stats_querymiss(&worker->stats, worker);
1555
1556         if(verbosity >= VERB_CLIENT) {
1557                 if(c->type == comm_udp)
1558                         log_addr(VERB_CLIENT, "udp request from",
1559                                 &repinfo->addr, repinfo->addrlen);
1560                 else    log_addr(VERB_CLIENT, "tcp request from",
1561                                 &repinfo->addr, repinfo->addrlen);
1562         }
1563
1564         /* grab a work request structure for this new request */
1565         mesh_new_client(worker->env.mesh, &qinfo, cinfo,
1566                 sldns_buffer_read_u16_at(c->buffer, 2),
1567                 &edns, repinfo, *(uint16_t*)(void *)sldns_buffer_begin(c->buffer));
1568         regional_free_all(worker->scratchpad);
1569         worker_mem_report(worker, NULL);
1570         return 0;
1571
1572 send_reply:
1573         rc = 1;
1574 send_reply_rc:
1575         if(need_drop) {
1576                 comm_point_drop_reply(repinfo);
1577                 return 0;
1578         }
1579         if(is_expired_answer) {
1580                 worker->stats.ans_expired++;
1581         }
1582         server_stats_insrcode(&worker->stats, c->buffer);
1583         if(worker->stats.extended) {
1584                 if(is_secure_answer) worker->stats.ans_secure++;
1585         }
1586 #ifdef USE_DNSTAP
1587         if(worker->dtenv.log_client_response_messages)
1588                 dt_msg_send_client_response(&worker->dtenv, &repinfo->addr,
1589                         c->type, c->buffer);
1590 #endif
1591         if(worker->env.cfg->log_replies)
1592         {
1593                 struct timeval tv;
1594                 memset(&tv, 0, sizeof(tv));
1595                 if(qinfo.local_alias && qinfo.local_alias->rrset &&
1596                         qinfo.local_alias->rrset->rk.dname) {
1597                         /* log original qname, before the local alias was
1598                          * used to resolve that CNAME to something else */
1599                         qinfo.qname = qinfo.local_alias->rrset->rk.dname;
1600                         log_reply_info(NO_VERBOSE, &qinfo, &repinfo->addr, repinfo->addrlen,
1601                                 tv, 1, c->buffer);
1602                 } else {
1603                         log_reply_info(NO_VERBOSE, &qinfo, &repinfo->addr, repinfo->addrlen,
1604                                 tv, 1, c->buffer);
1605                 }
1606         }
1607 #ifdef USE_DNSCRYPT
1608         if(!dnsc_handle_uncurved_request(repinfo)) {
1609                 return 0;
1610         }
1611 #endif
1612         return rc;
1613 }
1614
1615 void 
1616 worker_sighandler(int sig, void* arg)
1617 {
1618         /* note that log, print, syscalls here give race conditions. 
1619          * And cause hangups if the log-lock is held by the application. */
1620         struct worker* worker = (struct worker*)arg;
1621         switch(sig) {
1622 #ifdef SIGHUP
1623                 case SIGHUP:
1624                         comm_base_exit(worker->base);
1625                         break;
1626 #endif
1627                 case SIGINT:
1628                         worker->need_to_exit = 1;
1629                         comm_base_exit(worker->base);
1630                         break;
1631 #ifdef SIGQUIT
1632                 case SIGQUIT:
1633                         worker->need_to_exit = 1;
1634                         comm_base_exit(worker->base);
1635                         break;
1636 #endif
1637                 case SIGTERM:
1638                         worker->need_to_exit = 1;
1639                         comm_base_exit(worker->base);
1640                         break;
1641                 default:
1642                         /* unknown signal, ignored */
1643                         break;
1644         }
1645 }
1646
1647 /** restart statistics timer for worker, if enabled */
1648 static void
1649 worker_restart_timer(struct worker* worker)
1650 {
1651         if(worker->env.cfg->stat_interval > 0) {
1652                 struct timeval tv;
1653 #ifndef S_SPLINT_S
1654                 tv.tv_sec = worker->env.cfg->stat_interval;
1655                 tv.tv_usec = 0;
1656 #endif
1657                 comm_timer_set(worker->stat_timer, &tv);
1658         }
1659 }
1660
1661 void worker_stat_timer_cb(void* arg)
1662 {
1663         struct worker* worker = (struct worker*)arg;
1664         server_stats_log(&worker->stats, worker, worker->thread_num);
1665         mesh_stats(worker->env.mesh, "mesh has");
1666         worker_mem_report(worker, NULL);
1667         /* SHM is enabled, process data to SHM */
1668         if (worker->daemon->cfg->shm_enable) {
1669                 shm_main_run(worker);
1670         }
1671         if(!worker->daemon->cfg->stat_cumulative) {
1672                 worker_stats_clear(worker);
1673         }
1674         /* start next timer */
1675         worker_restart_timer(worker);
1676 }
1677
1678 void worker_probe_timer_cb(void* arg)
1679 {
1680         struct worker* worker = (struct worker*)arg;
1681         struct timeval tv;
1682 #ifndef S_SPLINT_S
1683         tv.tv_sec = (time_t)autr_probe_timer(&worker->env);
1684         tv.tv_usec = 0;
1685 #endif
1686         if(tv.tv_sec != 0)
1687                 comm_timer_set(worker->env.probe_timer, &tv);
1688 }
1689
1690 struct worker* 
1691 worker_create(struct daemon* daemon, int id, int* ports, int n)
1692 {
1693         unsigned int seed;
1694         struct worker* worker = (struct worker*)calloc(1, 
1695                 sizeof(struct worker));
1696         if(!worker) 
1697                 return NULL;
1698         worker->numports = n;
1699         worker->ports = (int*)memdup(ports, sizeof(int)*n);
1700         if(!worker->ports) {
1701                 free(worker);
1702                 return NULL;
1703         }
1704         worker->daemon = daemon;
1705         worker->thread_num = id;
1706         if(!(worker->cmd = tube_create())) {
1707                 free(worker->ports);
1708                 free(worker);
1709                 return NULL;
1710         }
1711         /* create random state here to avoid locking trouble in RAND_bytes */
1712         if(!(worker->rndstate = ub_initstate(daemon->rand))) {
1713                 log_err("could not init random numbers.");
1714                 tube_delete(worker->cmd);
1715                 free(worker->ports);
1716                 free(worker);
1717                 return NULL;
1718         }
1719         explicit_bzero(&seed, sizeof(seed));
1720         return worker;
1721 }
1722
1723 int
1724 worker_init(struct worker* worker, struct config_file *cfg, 
1725         struct listen_port* ports, int do_sigs)
1726 {
1727 #ifdef USE_DNSTAP
1728         struct dt_env* dtenv = &worker->dtenv;
1729 #else
1730         void* dtenv = NULL;
1731 #endif
1732         worker->need_to_exit = 0;
1733         worker->base = comm_base_create(do_sigs);
1734         if(!worker->base) {
1735                 log_err("could not create event handling base");
1736                 worker_delete(worker);
1737                 return 0;
1738         }
1739         comm_base_set_slow_accept_handlers(worker->base, &worker_stop_accept,
1740                 &worker_start_accept, worker);
1741         if(do_sigs) {
1742 #ifdef SIGHUP
1743                 ub_thread_sig_unblock(SIGHUP);
1744 #endif
1745                 ub_thread_sig_unblock(SIGINT);
1746 #ifdef SIGQUIT
1747                 ub_thread_sig_unblock(SIGQUIT);
1748 #endif
1749                 ub_thread_sig_unblock(SIGTERM);
1750 #ifndef LIBEVENT_SIGNAL_PROBLEM
1751                 worker->comsig = comm_signal_create(worker->base, 
1752                         worker_sighandler, worker);
1753                 if(!worker->comsig 
1754 #ifdef SIGHUP
1755                         || !comm_signal_bind(worker->comsig, SIGHUP)
1756 #endif
1757 #ifdef SIGQUIT
1758                         || !comm_signal_bind(worker->comsig, SIGQUIT)
1759 #endif
1760                         || !comm_signal_bind(worker->comsig, SIGTERM)
1761                         || !comm_signal_bind(worker->comsig, SIGINT)) {
1762                         log_err("could not create signal handlers");
1763                         worker_delete(worker);
1764                         return 0;
1765                 }
1766 #endif /* LIBEVENT_SIGNAL_PROBLEM */
1767                 if(!daemon_remote_open_accept(worker->daemon->rc, 
1768                         worker->daemon->rc_ports, worker)) {
1769                         worker_delete(worker);
1770                         return 0;
1771                 }
1772 #ifdef UB_ON_WINDOWS
1773                 wsvc_setup_worker(worker);
1774 #endif /* UB_ON_WINDOWS */
1775         } else { /* !do_sigs */
1776                 worker->comsig = NULL;
1777         }
1778 #ifdef USE_DNSTAP
1779         if(cfg->dnstap) {
1780                 log_assert(worker->daemon->dtenv != NULL);
1781                 memcpy(&worker->dtenv, worker->daemon->dtenv, sizeof(struct dt_env));
1782                 if(!dt_init(&worker->dtenv, worker->base))
1783                         fatal_exit("dt_init failed");
1784         }
1785 #endif
1786         worker->front = listen_create(worker->base, ports,
1787                 cfg->msg_buffer_size, (int)cfg->incoming_num_tcp,
1788                 cfg->do_tcp_keepalive
1789                         ? cfg->tcp_keepalive_timeout
1790                         : cfg->tcp_idle_timeout,
1791                 cfg->harden_large_queries, cfg->http_max_streams,
1792                 cfg->http_endpoint, cfg->http_notls_downstream,
1793                 worker->daemon->tcl, worker->daemon->listen_sslctx,
1794                 dtenv, worker_handle_request, worker);
1795         if(!worker->front) {
1796                 log_err("could not create listening sockets");
1797                 worker_delete(worker);
1798                 return 0;
1799         }
1800         worker->back = outside_network_create(worker->base,
1801                 cfg->msg_buffer_size, (size_t)cfg->outgoing_num_ports, 
1802                 cfg->out_ifs, cfg->num_out_ifs, cfg->do_ip4, cfg->do_ip6, 
1803                 cfg->do_tcp?cfg->outgoing_num_tcp:0, cfg->ip_dscp,
1804                 worker->daemon->env->infra_cache, worker->rndstate,
1805                 cfg->use_caps_bits_for_id, worker->ports, worker->numports,
1806                 cfg->unwanted_threshold, cfg->outgoing_tcp_mss,
1807                 &worker_alloc_cleanup, worker,
1808                 cfg->do_udp || cfg->udp_upstream_without_downstream,
1809                 worker->daemon->connect_sslctx, cfg->delay_close,
1810                 cfg->tls_use_sni, dtenv, cfg->udp_connect);
1811         if(!worker->back) {
1812                 log_err("could not create outgoing sockets");
1813                 worker_delete(worker);
1814                 return 0;
1815         }
1816         /* start listening to commands */
1817         if(!tube_setup_bg_listen(worker->cmd, worker->base,
1818                 &worker_handle_control_cmd, worker)) {
1819                 log_err("could not create control compt.");
1820                 worker_delete(worker);
1821                 return 0;
1822         }
1823         worker->stat_timer = comm_timer_create(worker->base, 
1824                 worker_stat_timer_cb, worker);
1825         if(!worker->stat_timer) {
1826                 log_err("could not create statistics timer");
1827         }
1828
1829         /* we use the msg_buffer_size as a good estimate for what the 
1830          * user wants for memory usage sizes */
1831         worker->scratchpad = regional_create_custom(cfg->msg_buffer_size);
1832         if(!worker->scratchpad) {
1833                 log_err("malloc failure");
1834                 worker_delete(worker);
1835                 return 0;
1836         }
1837
1838         server_stats_init(&worker->stats, cfg);
1839         alloc_init(&worker->alloc, &worker->daemon->superalloc, 
1840                 worker->thread_num);
1841         alloc_set_id_cleanup(&worker->alloc, &worker_alloc_cleanup, worker);
1842         worker->env = *worker->daemon->env;
1843         comm_base_timept(worker->base, &worker->env.now, &worker->env.now_tv);
1844         worker->env.worker = worker;
1845         worker->env.worker_base = worker->base;
1846         worker->env.send_query = &worker_send_query;
1847         worker->env.alloc = &worker->alloc;
1848         worker->env.outnet = worker->back;
1849         worker->env.rnd = worker->rndstate;
1850         /* If case prefetch is triggered, the corresponding mesh will clear
1851          * the scratchpad for the module env in the middle of request handling.
1852          * It would be prone to a use-after-free kind of bug, so we avoid
1853          * sharing it with worker's own scratchpad at the cost of having
1854          * one more pad per worker. */
1855         worker->env.scratch = regional_create_custom(cfg->msg_buffer_size);
1856         if(!worker->env.scratch) {
1857                 log_err("malloc failure");
1858                 worker_delete(worker);
1859                 return 0;
1860         }
1861         worker->env.mesh = mesh_create(&worker->daemon->mods, &worker->env);
1862         /* Pass on daemon variables that we would need in the mesh area */
1863         worker->env.mesh->use_response_ip = worker->daemon->use_response_ip;
1864         worker->env.mesh->use_rpz = worker->daemon->use_rpz;
1865
1866         worker->env.detach_subs = &mesh_detach_subs;
1867         worker->env.attach_sub = &mesh_attach_sub;
1868         worker->env.add_sub = &mesh_add_sub;
1869         worker->env.kill_sub = &mesh_state_delete;
1870         worker->env.detect_cycle = &mesh_detect_cycle;
1871         worker->env.scratch_buffer = sldns_buffer_new(cfg->msg_buffer_size);
1872         if(!(worker->env.fwds = forwards_create()) ||
1873                 !forwards_apply_cfg(worker->env.fwds, cfg)) {
1874                 log_err("Could not set forward zones");
1875                 worker_delete(worker);
1876                 return 0;
1877         }
1878         if(!(worker->env.hints = hints_create()) ||
1879                 !hints_apply_cfg(worker->env.hints, cfg)) {
1880                 log_err("Could not set root or stub hints");
1881                 worker_delete(worker);
1882                 return 0;
1883         }
1884         /* one probe timer per process -- if we have 5011 anchors */
1885         if(autr_get_num_anchors(worker->env.anchors) > 0
1886 #ifndef THREADS_DISABLED
1887                 && worker->thread_num == 0
1888 #endif
1889                 ) {
1890                 struct timeval tv;
1891                 tv.tv_sec = 0;
1892                 tv.tv_usec = 0;
1893                 worker->env.probe_timer = comm_timer_create(worker->base,
1894                         worker_probe_timer_cb, worker);
1895                 if(!worker->env.probe_timer) {
1896                         log_err("could not create 5011-probe timer");
1897                 } else {
1898                         /* let timer fire, then it can reset itself */
1899                         comm_timer_set(worker->env.probe_timer, &tv);
1900                 }
1901         }
1902         /* zone transfer tasks, setup once per process, if any */
1903         if(worker->env.auth_zones
1904 #ifndef THREADS_DISABLED
1905                 && worker->thread_num == 0
1906 #endif
1907                 ) {
1908                 auth_xfer_pickup_initial(worker->env.auth_zones, &worker->env);
1909         }
1910 #ifdef USE_DNSTAP
1911         if(worker->daemon->cfg->dnstap
1912 #ifndef THREADS_DISABLED
1913                 && worker->thread_num == 0
1914 #endif
1915                 ) {
1916                 if(!dt_io_thread_start(dtenv->dtio, comm_base_internal(
1917                         worker->base), worker->daemon->num)) {
1918                         log_err("could not start dnstap io thread");
1919                         worker_delete(worker);
1920                         return 0;
1921                 }
1922         }
1923 #endif /* USE_DNSTAP */
1924         if(!worker->env.mesh || !worker->env.scratch_buffer) {
1925                 worker_delete(worker);
1926                 return 0;
1927         }
1928         worker_mem_report(worker, NULL);
1929         /* if statistics enabled start timer */
1930         if(worker->env.cfg->stat_interval > 0) {
1931                 verbose(VERB_ALGO, "set statistics interval %d secs", 
1932                         worker->env.cfg->stat_interval);
1933                 worker_restart_timer(worker);
1934         }
1935         return 1;
1936 }
1937
1938 void 
1939 worker_work(struct worker* worker)
1940 {
1941         comm_base_dispatch(worker->base);
1942 }
1943
1944 void 
1945 worker_delete(struct worker* worker)
1946 {
1947         if(!worker) 
1948                 return;
1949         if(worker->env.mesh && verbosity >= VERB_OPS) {
1950                 server_stats_log(&worker->stats, worker, worker->thread_num);
1951                 mesh_stats(worker->env.mesh, "mesh has");
1952                 worker_mem_report(worker, NULL);
1953         }
1954         outside_network_quit_prepare(worker->back);
1955         mesh_delete(worker->env.mesh);
1956         sldns_buffer_free(worker->env.scratch_buffer);
1957         forwards_delete(worker->env.fwds);
1958         hints_delete(worker->env.hints);
1959         listen_delete(worker->front);
1960         outside_network_delete(worker->back);
1961         comm_signal_delete(worker->comsig);
1962         tube_delete(worker->cmd);
1963         comm_timer_delete(worker->stat_timer);
1964         comm_timer_delete(worker->env.probe_timer);
1965         free(worker->ports);
1966         if(worker->thread_num == 0) {
1967 #ifdef UB_ON_WINDOWS
1968                 wsvc_desetup_worker(worker);
1969 #endif /* UB_ON_WINDOWS */
1970         }
1971 #ifdef USE_DNSTAP
1972         if(worker->daemon->cfg->dnstap
1973 #ifndef THREADS_DISABLED
1974                 && worker->thread_num == 0
1975 #endif
1976                 ) {
1977                 dt_io_thread_stop(worker->dtenv.dtio);
1978         }
1979         dt_deinit(&worker->dtenv);
1980 #endif /* USE_DNSTAP */
1981         comm_base_delete(worker->base);
1982         ub_randfree(worker->rndstate);
1983         alloc_clear(&worker->alloc);
1984         regional_destroy(worker->env.scratch);
1985         regional_destroy(worker->scratchpad);
1986         free(worker);
1987 }
1988
1989 struct outbound_entry*
1990 worker_send_query(struct query_info* qinfo, uint16_t flags, int dnssec,
1991         int want_dnssec, int nocaps, struct sockaddr_storage* addr,
1992         socklen_t addrlen, uint8_t* zone, size_t zonelen, int ssl_upstream,
1993         char* tls_auth_name, struct module_qstate* q)
1994 {
1995         struct worker* worker = q->env->worker;
1996         struct outbound_entry* e = (struct outbound_entry*)regional_alloc(
1997                 q->region, sizeof(*e));
1998         if(!e) 
1999                 return NULL;
2000         e->qstate = q;
2001         e->qsent = outnet_serviced_query(worker->back, qinfo, flags, dnssec,
2002                 want_dnssec, nocaps, q->env->cfg->tcp_upstream,
2003                 ssl_upstream, tls_auth_name, addr, addrlen, zone, zonelen, q,
2004                 worker_handle_service_reply, e, worker->back->udp_buff, q->env);
2005         if(!e->qsent) {
2006                 return NULL;
2007         }
2008         return e;
2009 }
2010
2011 void 
2012 worker_alloc_cleanup(void* arg)
2013 {
2014         struct worker* worker = (struct worker*)arg;
2015         slabhash_clear(&worker->env.rrset_cache->table);
2016         slabhash_clear(worker->env.msg_cache);
2017 }
2018
2019 void worker_stats_clear(struct worker* worker)
2020 {
2021         server_stats_init(&worker->stats, worker->env.cfg);
2022         mesh_stats_clear(worker->env.mesh);
2023         worker->back->unwanted_replies = 0;
2024         worker->back->num_tcp_outgoing = 0;
2025 }
2026
2027 void worker_start_accept(void* arg)
2028 {
2029         struct worker* worker = (struct worker*)arg;
2030         listen_start_accept(worker->front);
2031         if(worker->thread_num == 0)
2032                 daemon_remote_start_accept(worker->daemon->rc);
2033 }
2034
2035 void worker_stop_accept(void* arg)
2036 {
2037         struct worker* worker = (struct worker*)arg;
2038         listen_stop_accept(worker->front);
2039         if(worker->thread_num == 0)
2040                 daemon_remote_stop_accept(worker->daemon->rc);
2041 }
2042
2043 /* --- fake callbacks for fptr_wlist to work --- */
2044 struct outbound_entry* libworker_send_query(
2045         struct query_info* ATTR_UNUSED(qinfo),
2046         uint16_t ATTR_UNUSED(flags), int ATTR_UNUSED(dnssec),
2047         int ATTR_UNUSED(want_dnssec), int ATTR_UNUSED(nocaps),
2048         struct sockaddr_storage* ATTR_UNUSED(addr), socklen_t ATTR_UNUSED(addrlen),
2049         uint8_t* ATTR_UNUSED(zone), size_t ATTR_UNUSED(zonelen),
2050         int ATTR_UNUSED(ssl_upstream), char* ATTR_UNUSED(tls_auth_name),
2051         struct module_qstate* ATTR_UNUSED(q))
2052 {
2053         log_assert(0);
2054         return 0;
2055 }
2056
2057 int libworker_handle_reply(struct comm_point* ATTR_UNUSED(c), 
2058         void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
2059         struct comm_reply* ATTR_UNUSED(reply_info))
2060 {
2061         log_assert(0);
2062         return 0;
2063 }
2064
2065 int libworker_handle_service_reply(struct comm_point* ATTR_UNUSED(c), 
2066         void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
2067         struct comm_reply* ATTR_UNUSED(reply_info))
2068 {
2069         log_assert(0);
2070         return 0;
2071 }
2072
2073 void libworker_handle_control_cmd(struct tube* ATTR_UNUSED(tube),
2074         uint8_t* ATTR_UNUSED(buffer), size_t ATTR_UNUSED(len),
2075         int ATTR_UNUSED(error), void* ATTR_UNUSED(arg))
2076 {
2077         log_assert(0);
2078 }
2079
2080 void libworker_fg_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
2081         sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
2082         char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
2083 {
2084         log_assert(0);
2085 }
2086
2087 void libworker_bg_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
2088         sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
2089         char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
2090 {
2091         log_assert(0);
2092 }
2093
2094 void libworker_event_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
2095         sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
2096         char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
2097 {
2098         log_assert(0);
2099 }
2100
2101 int context_query_cmp(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
2102 {
2103         log_assert(0);
2104         return 0;
2105 }
2106
2107 int order_lock_cmp(const void* ATTR_UNUSED(e1), const void* ATTR_UNUSED(e2))
2108 {
2109         log_assert(0);
2110         return 0;
2111 }
2112
2113 int codeline_cmp(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
2114 {
2115         log_assert(0);
2116         return 0;
2117 }
2118
2119 #ifdef USE_DNSTAP
2120 void dtio_tap_callback(int ATTR_UNUSED(fd), short ATTR_UNUSED(ev),
2121         void* ATTR_UNUSED(arg))
2122 {
2123         log_assert(0);
2124 }
2125 #endif
2126
2127 #ifdef USE_DNSTAP
2128 void dtio_mainfdcallback(int ATTR_UNUSED(fd), short ATTR_UNUSED(ev),
2129         void* ATTR_UNUSED(arg))
2130 {
2131         log_assert(0);
2132 }
2133 #endif