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