Home | History | Annotate | Line # | Download | only in daemon
      1 /*
      2  * daemon/worker.c - worker that handles a pending list of requests.
      3  *
      4  * Copyright (c) 2007, NLnet Labs. All rights reserved.
      5  *
      6  * This software is open source.
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     11  *
     12  * Redistributions of source code must retain the above copyright notice,
     13  * this list of conditions and the following disclaimer.
     14  *
     15  * Redistributions in binary form must reproduce the above copyright notice,
     16  * this list of conditions and the following disclaimer in the documentation
     17  * and/or other materials provided with the distribution.
     18  *
     19  * Neither the name of the NLNET LABS nor the names of its contributors may
     20  * be used to endorse or promote products derived from this software without
     21  * specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
     26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
     27  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
     29  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
     30  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
     31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
     32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
     33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     34  */
     35 
     36 /**
     37  * \file
     38  *
     39  * This file implements the worker that handles callbacks on events, for
     40  * pending requests.
     41  */
     42 #include "config.h"
     43 #include "util/log.h"
     44 #include "util/net_help.h"
     45 #include "util/random.h"
     46 #include "daemon/worker.h"
     47 #include "daemon/daemon.h"
     48 #include "daemon/remote.h"
     49 #include "daemon/acl_list.h"
     50 #include "util/netevent.h"
     51 #include "util/config_file.h"
     52 #include "util/module.h"
     53 #include "util/regional.h"
     54 #include "util/storage/slabhash.h"
     55 #include "services/listen_dnsport.h"
     56 #include "services/outside_network.h"
     57 #include "services/outbound_list.h"
     58 #include "services/cache/rrset.h"
     59 #include "services/cache/infra.h"
     60 #include "services/cache/dns.h"
     61 #include "services/authzone.h"
     62 #include "services/mesh.h"
     63 #include "services/localzone.h"
     64 #include "services/rpz.h"
     65 #include "util/data/msgparse.h"
     66 #include "util/data/msgencode.h"
     67 #include "util/data/dname.h"
     68 #include "util/fptr_wlist.h"
     69 #include "util/proxy_protocol.h"
     70 #include "util/tube.h"
     71 #include "util/edns.h"
     72 #include "util/timeval_func.h"
     73 #include "iterator/iter_fwd.h"
     74 #include "iterator/iter_hints.h"
     75 #include "iterator/iter_utils.h"
     76 #include "validator/autotrust.h"
     77 #include "validator/val_anchor.h"
     78 #include "respip/respip.h"
     79 #include "libunbound/context.h"
     80 #include "libunbound/libworker.h"
     81 #include "sldns/sbuffer.h"
     82 #include "sldns/wire2str.h"
     83 #include "util/shm_side/shm_main.h"
     84 #include "dnscrypt/dnscrypt.h"
     85 #include "dnstap/dtstream.h"
     86 
     87 #ifdef HAVE_SYS_TYPES_H
     88 #  include <sys/types.h>
     89 #endif
     90 #ifdef HAVE_NETDB_H
     91 #include <netdb.h>
     92 #endif
     93 #include <signal.h>
     94 #ifdef UB_ON_WINDOWS
     95 #include "winrc/win_svc.h"
     96 #endif
     97 
     98 /** Size of an UDP datagram */
     99 #define NORMAL_UDP_SIZE	512 /* bytes */
    100 /** ratelimit for error responses */
    101 #define ERROR_RATELIMIT 100 /* qps */
    102 
    103 /**
    104  * seconds to add to prefetch leeway.  This is a TTL that expires old rrsets
    105  * earlier than they should in order to put the new update into the cache.
    106  * This additional value is to make sure that if not all TTLs are equal in
    107  * the message to be updated(and replaced), that rrsets with up to this much
    108  * extra TTL are also replaced.  This means that the resulting new message
    109  * will have (most likely) this TTL at least, avoiding very small 'split
    110  * second' TTLs due to operators choosing relative primes for TTLs (or so).
    111  * Also has to be at least one to break ties (and overwrite cached entry).
    112  */
    113 #define PREFETCH_EXPIRY_ADD 60
    114 
    115 /** Report on memory usage by this thread and global */
    116 static void
    117 worker_mem_report(struct worker* ATTR_UNUSED(worker),
    118 	struct serviced_query* ATTR_UNUSED(cur_serv))
    119 {
    120 #ifdef UNBOUND_ALLOC_STATS
    121 	/* measure memory leakage */
    122 	extern size_t unbound_mem_alloc, unbound_mem_freed;
    123 	/* debug func in validator module */
    124 	size_t total, front, back, mesh, msg, rrset, infra, ac, superac;
    125 	size_t me, iter, val, anch;
    126 	int i;
    127 #ifdef CLIENT_SUBNET
    128 	size_t subnet = 0;
    129 #endif /* CLIENT_SUBNET */
    130 	if(verbosity < VERB_ALGO)
    131 		return;
    132 	front = listen_get_mem(worker->front);
    133 	back = outnet_get_mem(worker->back);
    134 	msg = slabhash_get_mem(worker->env.msg_cache);
    135 	rrset = slabhash_get_mem(&worker->env.rrset_cache->table);
    136 	infra = infra_get_mem(worker->env.infra_cache);
    137 	mesh = mesh_get_mem(worker->env.mesh);
    138 	ac = alloc_get_mem(worker->alloc);
    139 	superac = alloc_get_mem(&worker->daemon->superalloc);
    140 	anch = anchors_get_mem(worker->env.anchors);
    141 	iter = 0;
    142 	val = 0;
    143 	for(i=0; i<worker->env.mesh->mods.num; i++) {
    144 		fptr_ok(fptr_whitelist_mod_get_mem(worker->env.mesh->
    145 			mods.mod[i]->get_mem));
    146 		if(strcmp(worker->env.mesh->mods.mod[i]->name, "validator")==0)
    147 			val += (*worker->env.mesh->mods.mod[i]->get_mem)
    148 				(&worker->env, i);
    149 #ifdef CLIENT_SUBNET
    150 		else if(strcmp(worker->env.mesh->mods.mod[i]->name,
    151 			"subnetcache")==0)
    152 			subnet += (*worker->env.mesh->mods.mod[i]->get_mem)
    153 				(&worker->env, i);
    154 #endif /* CLIENT_SUBNET */
    155 		else	iter += (*worker->env.mesh->mods.mod[i]->get_mem)
    156 				(&worker->env, i);
    157 	}
    158 	me = sizeof(*worker) + sizeof(*worker->base) + sizeof(*worker->comsig)
    159 		+ comm_point_get_mem(worker->cmd_com)
    160 		+ sizeof(worker->rndstate)
    161 		+ regional_get_mem(worker->scratchpad)
    162 		+ sizeof(*worker->env.scratch_buffer)
    163 		+ sldns_buffer_capacity(worker->env.scratch_buffer);
    164 	if(worker->daemon->env->fwds)
    165 		log_info("forwards=%u", (unsigned)forwards_get_mem(worker->env.fwds));
    166 	if(worker->daemon->env->hints)
    167 		log_info("hints=%u", (unsigned)hints_get_mem(worker->env.hints));
    168 	if(worker->thread_num == 0)
    169 		me += acl_list_get_mem(worker->daemon->acl);
    170 	if(cur_serv) {
    171 		me += serviced_get_mem(cur_serv);
    172 	}
    173 	total = front+back+mesh+msg+rrset+infra+iter+val+ac+superac+me;
    174 #ifdef CLIENT_SUBNET
    175 	total += subnet;
    176 	log_info("Memory conditions: %u front=%u back=%u mesh=%u msg=%u "
    177 		"rrset=%u infra=%u iter=%u val=%u subnet=%u anchors=%u "
    178 		"alloccache=%u globalalloccache=%u me=%u",
    179 		(unsigned)total, (unsigned)front, (unsigned)back,
    180 		(unsigned)mesh, (unsigned)msg, (unsigned)rrset, (unsigned)infra,
    181 		(unsigned)iter, (unsigned)val,
    182 		(unsigned)subnet, (unsigned)anch, (unsigned)ac,
    183 		(unsigned)superac, (unsigned)me);
    184 #else /* no CLIENT_SUBNET */
    185 	log_info("Memory conditions: %u front=%u back=%u mesh=%u msg=%u "
    186 		"rrset=%u infra=%u iter=%u val=%u anchors=%u "
    187 		"alloccache=%u globalalloccache=%u me=%u",
    188 		(unsigned)total, (unsigned)front, (unsigned)back,
    189 		(unsigned)mesh, (unsigned)msg, (unsigned)rrset,
    190 		(unsigned)infra, (unsigned)iter, (unsigned)val, (unsigned)anch,
    191 		(unsigned)ac, (unsigned)superac, (unsigned)me);
    192 #endif /* CLIENT_SUBNET */
    193 	log_info("Total heap memory estimate: %u  total-alloc: %u  "
    194 		"total-free: %u", (unsigned)total,
    195 		(unsigned)unbound_mem_alloc, (unsigned)unbound_mem_freed);
    196 #else /* no UNBOUND_ALLOC_STATS */
    197 	size_t val = 0;
    198 #ifdef CLIENT_SUBNET
    199 	size_t subnet = 0;
    200 #endif /* CLIENT_SUBNET */
    201 	int i;
    202 	if(verbosity < VERB_QUERY)
    203 		return;
    204 	for(i=0; i<worker->env.mesh->mods.num; i++) {
    205 		fptr_ok(fptr_whitelist_mod_get_mem(worker->env.mesh->
    206 			mods.mod[i]->get_mem));
    207 		if(strcmp(worker->env.mesh->mods.mod[i]->name, "validator")==0)
    208 			val += (*worker->env.mesh->mods.mod[i]->get_mem)
    209 				(&worker->env, i);
    210 #ifdef CLIENT_SUBNET
    211 		else if(strcmp(worker->env.mesh->mods.mod[i]->name,
    212 			"subnetcache")==0)
    213 			subnet += (*worker->env.mesh->mods.mod[i]->get_mem)
    214 				(&worker->env, i);
    215 #endif /* CLIENT_SUBNET */
    216 	}
    217 #ifdef CLIENT_SUBNET
    218 	verbose(VERB_QUERY, "cache memory msg=%u rrset=%u infra=%u val=%u "
    219 		"subnet=%u",
    220 		(unsigned)slabhash_get_mem(worker->env.msg_cache),
    221 		(unsigned)slabhash_get_mem(&worker->env.rrset_cache->table),
    222 		(unsigned)infra_get_mem(worker->env.infra_cache),
    223 		(unsigned)val, (unsigned)subnet);
    224 #else /* no CLIENT_SUBNET */
    225 	verbose(VERB_QUERY, "cache memory msg=%u rrset=%u infra=%u val=%u",
    226 		(unsigned)slabhash_get_mem(worker->env.msg_cache),
    227 		(unsigned)slabhash_get_mem(&worker->env.rrset_cache->table),
    228 		(unsigned)infra_get_mem(worker->env.infra_cache),
    229 		(unsigned)val);
    230 #endif /* CLIENT_SUBNET */
    231 #endif /* UNBOUND_ALLOC_STATS */
    232 }
    233 
    234 void
    235 worker_send_cmd(struct worker* worker, enum worker_commands cmd)
    236 {
    237 	uint32_t c = (uint32_t)htonl(cmd);
    238 	if(!tube_write_msg(worker->cmd, (uint8_t*)&c, sizeof(c), 0)) {
    239 		log_err("worker send cmd %d failed", (int)cmd);
    240 	}
    241 }
    242 
    243 int
    244 worker_handle_service_reply(struct comm_point* c, void* arg, int error,
    245 	struct comm_reply* reply_info)
    246 {
    247 	struct outbound_entry* e = (struct outbound_entry*)arg;
    248 	struct worker* worker = e->qstate->env->worker;
    249 	struct serviced_query *sq = e->qsent;
    250 
    251 	verbose(VERB_ALGO, "worker svcd callback for qstate %p", e->qstate);
    252 	if(error != 0) {
    253 		mesh_report_reply(worker->env.mesh, e, reply_info, error);
    254 		worker_mem_report(worker, sq);
    255 		return 0;
    256 	}
    257 	/* sanity check. */
    258 	if(sldns_buffer_limit(c->buffer) < LDNS_HEADER_SIZE
    259 		|| !LDNS_QR_WIRE(sldns_buffer_begin(c->buffer))
    260 		|| LDNS_OPCODE_WIRE(sldns_buffer_begin(c->buffer)) !=
    261 			LDNS_PACKET_QUERY
    262 		|| LDNS_QDCOUNT(sldns_buffer_begin(c->buffer)) > 1) {
    263 		/* error becomes timeout for the module as if this reply
    264 		 * never arrived. */
    265 		verbose(VERB_ALGO, "worker: bad reply handled as timeout");
    266 		mesh_report_reply(worker->env.mesh, e, reply_info,
    267 			NETEVENT_TIMEOUT);
    268 		worker_mem_report(worker, sq);
    269 		return 0;
    270 	}
    271 	mesh_report_reply(worker->env.mesh, e, reply_info, NETEVENT_NOERROR);
    272 	worker_mem_report(worker, sq);
    273 	return 0;
    274 }
    275 
    276 /** ratelimit error replies
    277  * @param worker: the worker struct with ratelimit counter
    278  * @param err: error code that would be wanted.
    279  * @return value of err if okay, or -1 if it should be discarded instead.
    280  */
    281 static int
    282 worker_err_ratelimit(struct worker* worker, int err)
    283 {
    284 	if(worker->err_limit_time == *worker->env.now) {
    285 		/* see if limit is exceeded for this second */
    286 		if(worker->err_limit_count++ > ERROR_RATELIMIT)
    287 			return -1;
    288 	} else {
    289 		/* new second, new limits */
    290 		worker->err_limit_time = *worker->env.now;
    291 		worker->err_limit_count = 1;
    292 	}
    293 	return err;
    294 }
    295 
    296 /**
    297  * Reply with an error.
    298  * This reply includes the qname if it has been parsed.
    299  * For error ratelimiting, the err ratelimit routine should be checked
    300  * beforehand. The reply is without EDNS, and copies RD and sets QR flag.
    301  * @param pkt: the packet buffer from the comm point.
    302  * @param err: the error code that would be wanted.
    303  * @param qname_len: 0 if not parsed, and the qname length in packet.
    304  */
    305 static void
    306 query_error(sldns_buffer* pkt, int err, size_t qname_len)
    307 {
    308 	/* Preserve the RD flag.
    309 	 * The CD flag must be cleared in authoritative answers,
    310 	 * also the AD flag need not be copied into answers.
    311 	 * The other flags need not be copied into the answer. */
    312 	sldns_buffer_write_u16_at(pkt, 2,
    313 		sldns_buffer_read_u16_at(pkt, 2)&0x0100U);
    314 	LDNS_QR_SET(sldns_buffer_begin(pkt)); /* Set QR flag. */
    315 	LDNS_RCODE_SET(sldns_buffer_begin(pkt), err); /* Set rcode */
    316 
    317 	if(qname_len && LDNS_QDCOUNT(sldns_buffer_begin(pkt))>=1 &&
    318 		qname_len <= LDNS_MAX_DOMAINLEN) {
    319 		/* Copy query into the answer. */
    320 		LDNS_QDCOUNT_SET(sldns_buffer_begin(pkt), 1);
    321 		sldns_buffer_set_position(pkt, LDNS_HEADER_SIZE +
    322 			qname_len + 2 /* type */ + 2 /* class */ );
    323 	} else {
    324 		/* No query section in answer. */
    325 		LDNS_QDCOUNT_SET(sldns_buffer_begin(pkt), 0);
    326 		sldns_buffer_set_position(pkt, LDNS_HEADER_SIZE);
    327 	}
    328 	LDNS_ANCOUNT_SET(sldns_buffer_begin(pkt), 0);
    329 	LDNS_NSCOUNT_SET(sldns_buffer_begin(pkt), 0);
    330 	LDNS_ARCOUNT_SET(sldns_buffer_begin(pkt), 0);
    331 	sldns_buffer_flip(pkt);
    332 }
    333 
    334 /**
    335  * Structure holding the result of the worker_check_request function.
    336  * Based on configuration it could be called up to four times; ideally should
    337  * be called once.
    338  */
    339 struct check_request_result {
    340 	int checked;
    341 	int value;
    342 };
    343 /** check request sanity.
    344  * @param pkt: the wire packet to examine for sanity.
    345  * @param worker: parameters for checking.
    346  * @param out: struct to update with the result.
    347 */
    348 static void
    349 worker_check_request(sldns_buffer* pkt, struct worker* worker,
    350 	struct check_request_result* out)
    351 {
    352 	if(out->checked) return;
    353 	out->checked = 1;
    354 	if(sldns_buffer_limit(pkt) < LDNS_HEADER_SIZE) {
    355 		verbose(VERB_QUERY, "request too short, discarded");
    356 		out->value = -1;
    357 		return;
    358 	}
    359 	if(sldns_buffer_limit(pkt) > NORMAL_UDP_SIZE &&
    360 		worker->daemon->cfg->harden_large_queries) {
    361 		verbose(VERB_QUERY, "request too large, discarded");
    362 		out->value = -1;
    363 		return;
    364 	}
    365 	if(LDNS_QR_WIRE(sldns_buffer_begin(pkt))) {
    366 		verbose(VERB_QUERY, "request has QR bit on, discarded");
    367 		out->value = -1;
    368 		return;
    369 	}
    370 	if(LDNS_TC_WIRE(sldns_buffer_begin(pkt))) {
    371 		verbose(VERB_QUERY, "request bad, has TC bit on");
    372 		out->value = worker_err_ratelimit(worker, LDNS_RCODE_FORMERR);
    373 		return;
    374 	}
    375 	if(LDNS_OPCODE_WIRE(sldns_buffer_begin(pkt)) != LDNS_PACKET_QUERY &&
    376 		LDNS_OPCODE_WIRE(sldns_buffer_begin(pkt)) != LDNS_PACKET_NOTIFY) {
    377 		verbose(VERB_QUERY, "request unknown opcode %d",
    378 			LDNS_OPCODE_WIRE(sldns_buffer_begin(pkt)));
    379 		out->value = worker_err_ratelimit(worker, LDNS_RCODE_NOTIMPL);
    380 		return;
    381 	}
    382 	if(LDNS_QDCOUNT(sldns_buffer_begin(pkt)) != 1) {
    383 		verbose(VERB_QUERY, "request wrong nr qd=%d",
    384 			LDNS_QDCOUNT(sldns_buffer_begin(pkt)));
    385 		out->value = worker_err_ratelimit(worker, LDNS_RCODE_FORMERR);
    386 		return;
    387 	}
    388 	if(LDNS_ANCOUNT(sldns_buffer_begin(pkt)) != 0 &&
    389 		(LDNS_ANCOUNT(sldns_buffer_begin(pkt)) != 1 ||
    390 		LDNS_OPCODE_WIRE(sldns_buffer_begin(pkt)) != LDNS_PACKET_NOTIFY)) {
    391 		verbose(VERB_QUERY, "request wrong nr an=%d",
    392 			LDNS_ANCOUNT(sldns_buffer_begin(pkt)));
    393 		out->value = worker_err_ratelimit(worker, LDNS_RCODE_FORMERR);
    394 		return;
    395 	}
    396 	if(LDNS_NSCOUNT(sldns_buffer_begin(pkt)) != 0) {
    397 		verbose(VERB_QUERY, "request wrong nr ns=%d",
    398 			LDNS_NSCOUNT(sldns_buffer_begin(pkt)));
    399 		out->value = worker_err_ratelimit(worker, LDNS_RCODE_FORMERR);
    400 		return;
    401 	}
    402 	if(LDNS_ARCOUNT(sldns_buffer_begin(pkt)) > 1) {
    403 		verbose(VERB_QUERY, "request wrong nr ar=%d",
    404 			LDNS_ARCOUNT(sldns_buffer_begin(pkt)));
    405 		out->value = worker_err_ratelimit(worker, LDNS_RCODE_FORMERR);
    406 		return;
    407 	}
    408 	out->value = 0;
    409 	return;
    410 }
    411 
    412 /**
    413  * Send fast-reload acknowledgement to the mainthread in one byte.
    414  * This signals that this worker has received the previous command.
    415  * The worker is waiting if that is after a reload_stop command.
    416  * Or the worker has briefly processed the event itself, and in doing so
    417  * released data pointers to old config, after a reload_poll command.
    418  */
    419 static void
    420 worker_send_reload_ack(struct worker* worker)
    421 {
    422 	/* If this is clipped to 8 bits because thread_num>255, then that
    423 	 * is not a problem, the receiver counts the number of bytes received.
    424 	 * The number is informative only. */
    425 	uint8_t c = (uint8_t)worker->thread_num;
    426 	ssize_t ret;
    427 	while(1) {
    428 		ret = send(worker->daemon->fast_reload_thread->commreload[1],
    429 			(void*)&c, 1, 0);
    430 		if(ret == -1) {
    431 			if(
    432 #ifndef USE_WINSOCK
    433 				errno == EINTR || errno == EAGAIN
    434 #  ifdef EWOULDBLOCK
    435 				|| errno == EWOULDBLOCK
    436 #  endif
    437 #else
    438 				WSAGetLastError() == WSAEINTR ||
    439 				WSAGetLastError() == WSAEINPROGRESS ||
    440 				WSAGetLastError() == WSAEWOULDBLOCK
    441 #endif
    442 				)
    443 				continue; /* Try again. */
    444 			log_err("worker reload ack reply: send failed: %s",
    445 				sock_strerror(errno));
    446 			break;
    447 		}
    448 		break;
    449 	}
    450 }
    451 
    452 /** stop and wait to resume the worker */
    453 static void
    454 worker_stop_and_wait(struct worker* worker)
    455 {
    456 	uint8_t* buf = NULL;
    457 	uint32_t len = 0, cmd;
    458 	worker_send_reload_ack(worker);
    459 	/* wait for reload */
    460 	if(!tube_read_msg(worker->cmd, &buf, &len, 0)) {
    461 		log_err("worker reload read reply failed");
    462 		return;
    463 	}
    464 	if(len != sizeof(uint32_t)) {
    465 		log_err("worker reload reply, bad control msg length %d",
    466 			(int)len);
    467 		free(buf);
    468 		return;
    469 	}
    470 	cmd = sldns_read_uint32(buf);
    471 	free(buf);
    472 	if(cmd == worker_cmd_quit) {
    473 		/* quit anyway */
    474 		verbose(VERB_ALGO, "reload reply, control cmd quit");
    475 		comm_base_exit(worker->base);
    476 		return;
    477 	}
    478 	if(cmd != worker_cmd_reload_start) {
    479 		log_err("worker reload reply, wrong reply command");
    480 	}
    481 	if(worker->daemon->fast_reload_drop_mesh) {
    482 		verbose(VERB_ALGO, "worker: drop mesh queries after reload");
    483 		mesh_delete_all(worker->env.mesh);
    484 	}
    485 	fast_reload_worker_pickup_changes(worker);
    486 	worker_send_reload_ack(worker);
    487 	verbose(VERB_ALGO, "worker resume after reload");
    488 }
    489 
    490 void
    491 worker_handle_control_cmd(struct tube* ATTR_UNUSED(tube), uint8_t* msg,
    492 	size_t len, int error, void* arg)
    493 {
    494 	struct worker* worker = (struct worker*)arg;
    495 	enum worker_commands cmd;
    496 	if(error != NETEVENT_NOERROR) {
    497 		free(msg);
    498 		if(error == NETEVENT_CLOSED)
    499 			comm_base_exit(worker->base);
    500 		else	log_info("control event: %d", error);
    501 		return;
    502 	}
    503 	if(len != sizeof(uint32_t)) {
    504 		fatal_exit("bad control msg length %d", (int)len);
    505 	}
    506 	cmd = sldns_read_uint32(msg);
    507 	free(msg);
    508 	switch(cmd) {
    509 	case worker_cmd_quit:
    510 		verbose(VERB_ALGO, "got control cmd quit");
    511 		comm_base_exit(worker->base);
    512 		break;
    513 	case worker_cmd_stats:
    514 		verbose(VERB_ALGO, "got control cmd stats");
    515 		server_stats_reply(worker, 1);
    516 		break;
    517 	case worker_cmd_stats_noreset:
    518 		verbose(VERB_ALGO, "got control cmd stats_noreset");
    519 		server_stats_reply(worker, 0);
    520 		break;
    521 	case worker_cmd_remote:
    522 		verbose(VERB_ALGO, "got control cmd remote");
    523 		daemon_remote_exec(worker);
    524 		break;
    525 	case worker_cmd_reload_stop:
    526 		verbose(VERB_ALGO, "got control cmd reload_stop");
    527 		worker_stop_and_wait(worker);
    528 		break;
    529 	case worker_cmd_reload_poll:
    530 		verbose(VERB_ALGO, "got control cmd reload_poll");
    531 		fast_reload_worker_pickup_changes(worker);
    532 		worker_send_reload_ack(worker);
    533 		break;
    534 	default:
    535 		log_err("bad command %d", (int)cmd);
    536 		break;
    537 	}
    538 }
    539 
    540 /** check if a delegation is secure */
    541 static enum sec_status
    542 check_delegation_secure(struct reply_info *rep)
    543 {
    544 	/* return smallest security status */
    545 	size_t i;
    546 	enum sec_status sec = sec_status_secure;
    547 	enum sec_status s;
    548 	size_t num = rep->an_numrrsets + rep->ns_numrrsets;
    549 	/* check if answer and authority are OK */
    550 	for(i=0; i<num; i++) {
    551 		s = ((struct packed_rrset_data*)rep->rrsets[i]->entry.data)
    552 			->security;
    553 		if(s < sec)
    554 			sec = s;
    555 	}
    556 	/* in additional, only unchecked triggers revalidation */
    557 	for(i=num; i<rep->rrset_count; i++) {
    558 		s = ((struct packed_rrset_data*)rep->rrsets[i]->entry.data)
    559 			->security;
    560 		if(s == sec_status_unchecked)
    561 			return s;
    562 	}
    563 	return sec;
    564 }
    565 
    566 /** remove nonsecure from a delegation referral additional section */
    567 static void
    568 deleg_remove_nonsecure_additional(struct reply_info* rep)
    569 {
    570 	/* we can simply edit it, since we are working in the scratch region */
    571 	size_t i;
    572 	enum sec_status s;
    573 
    574 	for(i = rep->an_numrrsets+rep->ns_numrrsets; i<rep->rrset_count; i++) {
    575 		s = ((struct packed_rrset_data*)rep->rrsets[i]->entry.data)
    576 			->security;
    577 		if(s != sec_status_secure) {
    578 			memmove(rep->rrsets+i, rep->rrsets+i+1,
    579 				sizeof(struct ub_packed_rrset_key*)*
    580 				(rep->rrset_count - i - 1));
    581 			rep->ar_numrrsets--;
    582 			rep->rrset_count--;
    583 			i--;
    584 		}
    585 	}
    586 }
    587 
    588 /** answer nonrecursive query from the cache */
    589 static int
    590 answer_norec_from_cache(struct worker* worker, struct query_info* qinfo,
    591 	uint16_t id, uint16_t flags, struct comm_reply* repinfo,
    592 	struct edns_data* edns)
    593 {
    594 	/* for a nonrecursive query return either:
    595 	 * 	o an error (servfail; we try to avoid this)
    596 	 * 	o a delegation (closest we have; this routine tries that)
    597 	 * 	o the answer (checked by answer_from_cache)
    598 	 *
    599 	 * So, grab a delegation from the rrset cache.
    600 	 * Then check if it needs validation, if so, this routine fails,
    601 	 * so that iterator can prime and validator can verify rrsets.
    602 	 */
    603 	uint16_t udpsize = edns->udp_size;
    604 	int secure = 0;
    605 	time_t timenow = *worker->env.now;
    606 	int has_cd_bit = (flags&BIT_CD);
    607 	int must_validate = (!has_cd_bit || worker->env.cfg->ignore_cd)
    608 		&& worker->env.need_to_validate;
    609 	struct dns_msg *msg = NULL;
    610 	struct delegpt *dp;
    611 
    612 	dp = dns_cache_find_delegation(&worker->env, qinfo->qname,
    613 		qinfo->qname_len, qinfo->qtype, qinfo->qclass,
    614 		worker->scratchpad, &msg, timenow, 0, NULL, 0);
    615 	if(!dp) { /* no delegation, need to reprime */
    616 		return 0;
    617 	}
    618 	/* In case we have a local alias, copy it into the delegation message.
    619 	 * Shallow copy should be fine, as we'll be done with msg in this
    620 	 * function. */
    621 	msg->qinfo.local_alias = qinfo->local_alias;
    622 	if(must_validate) {
    623 		switch(check_delegation_secure(msg->rep)) {
    624 		case sec_status_unchecked:
    625 			/* some rrsets have not been verified yet, go and
    626 			 * let validator do that */
    627 			return 0;
    628 		case sec_status_bogus:
    629 		case sec_status_secure_sentinel_fail:
    630 			/* some rrsets are bogus, reply servfail */
    631 			edns->edns_version = EDNS_ADVERTISED_VERSION;
    632 			edns->udp_size = EDNS_ADVERTISED_SIZE;
    633 			edns->ext_rcode = 0;
    634 			edns->bits &= EDNS_DO;
    635 			if(!inplace_cb_reply_servfail_call(&worker->env, qinfo, NULL,
    636 				msg->rep, LDNS_RCODE_SERVFAIL, edns, repinfo, worker->scratchpad,
    637 				worker->env.now_tv))
    638 					return 0;
    639 			/* Attach the cached EDE (RFC8914) */
    640 			if(worker->env.cfg->ede &&
    641 				msg->rep->reason_bogus != LDNS_EDE_NONE) {
    642 				edns_opt_list_append_ede(&edns->opt_list_out,
    643 					worker->scratchpad, msg->rep->reason_bogus,
    644 					msg->rep->reason_bogus_str);
    645 			}
    646 			error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL,
    647 				&msg->qinfo, id, flags, edns);
    648 			if(worker->stats.extended) {
    649 				worker->stats.ans_bogus++;
    650 				worker->stats.ans_rcode[LDNS_RCODE_SERVFAIL]++;
    651 			}
    652 			return 1;
    653 		case sec_status_secure:
    654 			/* all rrsets are secure */
    655 			/* remove non-secure rrsets from the add. section*/
    656 			if(worker->env.cfg->val_clean_additional)
    657 				deleg_remove_nonsecure_additional(msg->rep);
    658 			secure = 1;
    659 			break;
    660 		case sec_status_indeterminate:
    661 		case sec_status_insecure:
    662 		default:
    663 			/* not secure */
    664 			secure = 0;
    665 			break;
    666 		}
    667 	}
    668 	/* return this delegation from the cache */
    669 	edns->edns_version = EDNS_ADVERTISED_VERSION;
    670 	edns->udp_size = EDNS_ADVERTISED_SIZE;
    671 	edns->ext_rcode = 0;
    672 	edns->bits &= EDNS_DO;
    673 	if(worker->env.cfg->disable_edns_do && (edns->bits & EDNS_DO))
    674 		edns->edns_present = 0;
    675 	if(!inplace_cb_reply_cache_call(&worker->env, qinfo, NULL, msg->rep,
    676 		(int)(flags&LDNS_RCODE_MASK), edns, repinfo, worker->scratchpad,
    677 		worker->env.now_tv))
    678 			return 0;
    679 	msg->rep->flags |= BIT_QR|BIT_RA;
    680 	/* Attach the cached EDE (RFC8914) if CD bit is set and the answer is
    681 	 * bogus. */
    682 	if(worker->env.cfg->ede && has_cd_bit &&
    683 		(check_delegation_secure(msg->rep) == sec_status_bogus ||
    684 		check_delegation_secure(msg->rep) == sec_status_secure_sentinel_fail) &&
    685 		msg->rep->reason_bogus != LDNS_EDE_NONE) {
    686 		edns_opt_list_append_ede(&edns->opt_list_out,
    687 			worker->scratchpad, msg->rep->reason_bogus,
    688 			msg->rep->reason_bogus_str);
    689 	}
    690 	if(!reply_info_answer_encode(&msg->qinfo, msg->rep, id, flags,
    691 		repinfo->c->buffer, 0, 1, worker->scratchpad,
    692 		udpsize, edns, (int)(edns->bits & EDNS_DO), secure)) {
    693 		if(!inplace_cb_reply_servfail_call(&worker->env, qinfo, NULL, NULL,
    694 			LDNS_RCODE_SERVFAIL, edns, repinfo, worker->scratchpad,
    695 			worker->env.now_tv))
    696 				edns->opt_list_inplace_cb_out = NULL;
    697 		error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL,
    698 			&msg->qinfo, id, flags, edns);
    699 	}
    700 	if(worker->stats.extended) {
    701 		if(secure) worker->stats.ans_secure++;
    702 		server_stats_insrcode(&worker->stats, repinfo->c->buffer);
    703 	}
    704 	return 1;
    705 }
    706 
    707 /** Apply, if applicable, a response IP action to a cached answer.
    708  * If the answer is rewritten as a result of an action, '*encode_repp' will
    709  * point to the reply info containing the modified answer.  '*encode_repp' will
    710  * be intact otherwise.
    711  * It returns 1 on success, 0 otherwise. */
    712 static int
    713 apply_respip_action(struct worker* worker, const struct query_info* qinfo,
    714 	struct respip_client_info* cinfo, struct reply_info* rep,
    715 	struct sockaddr_storage* addr, socklen_t addrlen,
    716 	struct ub_packed_rrset_key** alias_rrset,
    717 	struct reply_info** encode_repp, struct auth_zones* az)
    718 {
    719 	struct respip_action_info actinfo = {0, 0, 0, 0, NULL, 0, NULL};
    720 	actinfo.action = respip_none;
    721 
    722 	if(qinfo->qtype != LDNS_RR_TYPE_A &&
    723 		qinfo->qtype != LDNS_RR_TYPE_AAAA &&
    724 		qinfo->qtype != LDNS_RR_TYPE_ANY)
    725 		return 1;
    726 
    727 	if(!respip_rewrite_reply(qinfo, cinfo, rep, encode_repp, &actinfo,
    728 		alias_rrset, 0, worker->scratchpad, az, NULL,
    729 		worker->env.views, worker->env.respip_set))
    730 		return 0;
    731 
    732 	/* xxx_deny actions mean dropping the reply, unless the original reply
    733 	 * was redirected to response-ip data. */
    734 	if(actinfo.action == respip_always_deny ||
    735 		((actinfo.action == respip_deny ||
    736 		actinfo.action == respip_inform_deny) &&
    737 		*encode_repp == rep))
    738 		*encode_repp = NULL;
    739 
    740 	/* If address info is returned, it means the action should be an
    741 	 * 'inform' variant and the information should be logged. */
    742 	if(actinfo.addrinfo) {
    743 		respip_inform_print(&actinfo, qinfo->qname,
    744 			qinfo->qtype, qinfo->qclass, qinfo->local_alias,
    745 			addr, addrlen);
    746 
    747 		if(worker->stats.extended && actinfo.rpz_used) {
    748 			if(actinfo.rpz_disabled)
    749 				worker->stats.rpz_action[RPZ_DISABLED_ACTION]++;
    750 			if(actinfo.rpz_cname_override)
    751 				worker->stats.rpz_action[RPZ_CNAME_OVERRIDE_ACTION]++;
    752 			else
    753 				worker->stats.rpz_action[
    754 					respip_action_to_rpz_action(actinfo.action)]++;
    755 		}
    756 	}
    757 
    758 	return 1;
    759 }
    760 
    761 /** answer query from the cache.
    762  * Normally, the answer message will be built in repinfo->c->buffer; if the
    763  * answer is supposed to be suppressed or the answer is supposed to be an
    764  * incomplete CNAME chain, the buffer is explicitly cleared to signal the
    765  * caller as such.  In the latter case *partial_rep will point to the incomplete
    766  * reply, and this function is (possibly) supposed to be called again with that
    767  * *partial_rep value to complete the chain.  In addition, if the query should
    768  * be completely dropped, '*need_drop' will be set to 1. */
    769 static int
    770 answer_from_cache(struct worker* worker, struct query_info* qinfo,
    771 	struct respip_client_info* cinfo, int* need_drop, int* is_expired_answer,
    772 	int* is_secure_answer, struct ub_packed_rrset_key** alias_rrset,
    773 	struct reply_info** partial_repp,
    774 	struct reply_info* rep, uint16_t id, uint16_t flags,
    775 	struct comm_reply* repinfo, struct edns_data* edns)
    776 {
    777 	time_t timenow = *worker->env.now;
    778 	uint16_t udpsize = edns->udp_size;
    779 	struct reply_info* encode_rep = rep;
    780 	struct reply_info* partial_rep = *partial_repp;
    781 	int has_cd_bit = (flags&BIT_CD);
    782 	int must_validate = (!has_cd_bit || worker->env.cfg->ignore_cd)
    783 		&& worker->env.need_to_validate;
    784 	*partial_repp = NULL;  /* avoid accidental further pass */
    785 
    786 	/* Check TTL */
    787 	if(TTL_IS_EXPIRED(rep->ttl, timenow)) {
    788 		/* Check if we need to serve expired now */
    789 		if(worker->env.cfg->serve_expired &&
    790 			/* if serve-expired-client-timeout is set, serve
    791 			 * an expired record without attempting recursion
    792 			 * if the serve_expired_norec_ttl is set for the record
    793 			 * as we know that recursion is currently failing. */
    794 			(!worker->env.cfg->serve_expired_client_timeout ||
    795 			 timenow < rep->serve_expired_norec_ttl)
    796 #ifdef USE_CACHEDB
    797 			&& !(worker->env.cachedb_enabled &&
    798 			  worker->env.cfg->cachedb_check_when_serve_expired)
    799 #endif
    800 			) {
    801 				if(!reply_info_can_answer_expired(rep, timenow))
    802 					return 0;
    803 				if(!rrset_array_lock(rep->ref, rep->rrset_count, 0))
    804 					return 0;
    805 				*is_expired_answer = 1;
    806 		} else {
    807 			/* the rrsets may have been updated in the meantime.
    808 			 * we will refetch the message format from the
    809 			 * authoritative server
    810 			 */
    811 			return 0;
    812 		}
    813 	} else {
    814 		if(!rrset_array_lock(rep->ref, rep->rrset_count, timenow))
    815 			return 0;
    816 	}
    817 	/* locked and ids and ttls are OK. */
    818 
    819 	/* check CNAME chain (if any) */
    820 	if(rep->an_numrrsets > 0 && (rep->rrsets[0]->rk.type ==
    821 		htons(LDNS_RR_TYPE_CNAME) || rep->rrsets[0]->rk.type ==
    822 		htons(LDNS_RR_TYPE_DNAME))) {
    823 		if(!reply_check_cname_chain(qinfo, rep)) {
    824 			/* cname chain invalid, redo iterator steps */
    825 			verbose(VERB_ALGO, "Cache reply: cname chain broken");
    826 			goto bail_out;
    827 		}
    828 	}
    829 	/* check security status of the cached answer */
    830 	if(must_validate && (rep->security == sec_status_bogus ||
    831 		rep->security == sec_status_secure_sentinel_fail)) {
    832 		/* BAD cached */
    833 		edns->edns_version = EDNS_ADVERTISED_VERSION;
    834 		edns->udp_size = EDNS_ADVERTISED_SIZE;
    835 		edns->ext_rcode = 0;
    836 		edns->bits &= EDNS_DO;
    837 		if(worker->env.cfg->disable_edns_do && (edns->bits & EDNS_DO))
    838 			edns->edns_present = 0;
    839 		if(!inplace_cb_reply_servfail_call(&worker->env, qinfo, NULL, rep,
    840 			LDNS_RCODE_SERVFAIL, edns, repinfo, worker->scratchpad,
    841 			worker->env.now_tv))
    842 			goto bail_out;
    843 		/* Attach the cached EDE (RFC8914) */
    844 		if(worker->env.cfg->ede && rep->reason_bogus != LDNS_EDE_NONE) {
    845 			edns_opt_list_append_ede(&edns->opt_list_out,
    846 					worker->scratchpad, rep->reason_bogus,
    847 					rep->reason_bogus_str);
    848 		}
    849 		error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL,
    850 			qinfo, id, flags, edns);
    851 		rrset_array_unlock_touch(worker->env.rrset_cache,
    852 			worker->scratchpad, rep->ref, rep->rrset_count);
    853 		if(worker->stats.extended) {
    854 			worker->stats.ans_bogus ++;
    855 			worker->stats.ans_rcode[LDNS_RCODE_SERVFAIL] ++;
    856 		}
    857 		return 1;
    858 	} else if(rep->security == sec_status_unchecked && must_validate) {
    859 		verbose(VERB_ALGO, "Cache reply: unchecked entry needs "
    860 			"validation");
    861 		goto bail_out; /* need to validate cache entry first */
    862 	} else if(rep->security == sec_status_secure) {
    863 		if(reply_all_rrsets_secure(rep)) {
    864 			*is_secure_answer = 1;
    865 		} else {
    866 			if(must_validate) {
    867 				verbose(VERB_ALGO, "Cache reply: secure entry"
    868 					" changed status");
    869 				goto bail_out; /* rrset changed, re-verify */
    870 			}
    871 			*is_secure_answer = 0;
    872 		}
    873 	} else *is_secure_answer = 0;
    874 
    875 	edns->edns_version = EDNS_ADVERTISED_VERSION;
    876 	edns->udp_size = EDNS_ADVERTISED_SIZE;
    877 	edns->ext_rcode = 0;
    878 	edns->bits &= EDNS_DO;
    879 	if(worker->env.cfg->disable_edns_do && (edns->bits & EDNS_DO))
    880 		edns->edns_present = 0;
    881 	*alias_rrset = NULL; /* avoid confusion if caller set it to non-NULL */
    882 	if((worker->daemon->use_response_ip || worker->daemon->use_rpz) &&
    883 		!partial_rep && !apply_respip_action(worker, qinfo, cinfo, rep,
    884 		&repinfo->client_addr, repinfo->client_addrlen, alias_rrset,
    885 		&encode_rep, worker->env.auth_zones)) {
    886 		goto bail_out;
    887 	} else if(partial_rep &&
    888 		!respip_merge_cname(partial_rep, qinfo, rep, cinfo,
    889 		must_validate, &encode_rep, worker->scratchpad,
    890 		worker->env.auth_zones, worker->env.views,
    891 		worker->env.respip_set)) {
    892 		goto bail_out;
    893 	}
    894 	if(encode_rep != rep) {
    895 		/* if rewritten, it can't be considered "secure" */
    896 		*is_secure_answer = 0;
    897 	}
    898 	if(!encode_rep || *alias_rrset) {
    899 		if(!encode_rep)
    900 			*need_drop = 1;
    901 		else {
    902 			/* If a partial CNAME chain is found, we first need to
    903 			 * make a copy of the reply in the scratchpad so we
    904 			 * can release the locks and lookup the cache again. */
    905 			*partial_repp = reply_info_copy(encode_rep, NULL,
    906 				worker->scratchpad);
    907 			if(!*partial_repp)
    908 				goto bail_out;
    909 		}
    910 	} else {
    911 		if(*is_expired_answer == 1 &&
    912 			worker->env.cfg->ede_serve_expired && worker->env.cfg->ede) {
    913 			EDNS_OPT_LIST_APPEND_EDE(&edns->opt_list_out,
    914 				worker->scratchpad, LDNS_EDE_STALE_ANSWER, "");
    915 		}
    916 		/* Attach the cached EDE (RFC8914) if CD bit is set and the
    917 		 * answer is bogus. */
    918 		if(*is_secure_answer == 0 &&
    919 			worker->env.cfg->ede && has_cd_bit &&
    920 			encode_rep->reason_bogus != LDNS_EDE_NONE) {
    921 			edns_opt_list_append_ede(&edns->opt_list_out,
    922 				worker->scratchpad, encode_rep->reason_bogus,
    923 				encode_rep->reason_bogus_str);
    924 		}
    925 		if(!inplace_cb_reply_cache_call(&worker->env, qinfo, NULL, encode_rep,
    926 			(int)(flags&LDNS_RCODE_MASK), edns, repinfo, worker->scratchpad,
    927 			worker->env.now_tv))
    928 			goto bail_out;
    929 		if(!reply_info_answer_encode(qinfo, encode_rep, id, flags,
    930 			repinfo->c->buffer, timenow, 1, worker->scratchpad,
    931 			udpsize, edns, (int)(edns->bits & EDNS_DO),
    932 			*is_secure_answer)) {
    933 			if(!inplace_cb_reply_servfail_call(&worker->env, qinfo,
    934 				NULL, NULL, LDNS_RCODE_SERVFAIL, edns, repinfo,
    935 				worker->scratchpad, worker->env.now_tv))
    936 					edns->opt_list_inplace_cb_out = NULL;
    937 			error_encode(repinfo->c->buffer, LDNS_RCODE_SERVFAIL,
    938 				qinfo, id, flags, edns);
    939 		}
    940 	}
    941 	/* cannot send the reply right now, because blocking network syscall
    942 	 * is bad while holding locks. */
    943 	rrset_array_unlock_touch(worker->env.rrset_cache, worker->scratchpad,
    944 		rep->ref, rep->rrset_count);
    945 	/* go and return this buffer to the client */
    946 	return 1;
    947 
    948 bail_out:
    949 	rrset_array_unlock_touch(worker->env.rrset_cache,
    950 		worker->scratchpad, rep->ref, rep->rrset_count);
    951 	return 0;
    952 }
    953 
    954 /** Reply to client and perform prefetch to keep cache up to date. */
    955 static void
    956 reply_and_prefetch(struct worker* worker, struct query_info* qinfo,
    957 	uint16_t flags, struct comm_reply* repinfo, time_t leeway, int noreply,
    958 	int rpz_passthru, struct edns_option* opt_list)
    959 {
    960 	(void)opt_list;
    961 	/* first send answer to client to keep its latency
    962 	 * as small as a cachereply */
    963 	if(!noreply) {
    964 		if(repinfo->c->tcp_req_info) {
    965 			sldns_buffer_copy(
    966 				repinfo->c->tcp_req_info->spool_buffer,
    967 				repinfo->c->buffer);
    968 		}
    969 		comm_point_send_reply(repinfo);
    970 	}
    971 	server_stats_prefetch(&worker->stats, worker);
    972 #ifdef CLIENT_SUBNET
    973 	/* Check if the subnet module is enabled. In that case pass over the
    974 	 * comm_reply information for ECS generation later. The mesh states are
    975 	 * unique when subnet is enabled. */
    976 	if(modstack_find(&worker->env.mesh->mods, "subnetcache") != -1
    977 		&& worker->env.unique_mesh) {
    978 		mesh_new_prefetch(worker->env.mesh, qinfo, flags, leeway +
    979 			PREFETCH_EXPIRY_ADD, rpz_passthru,
    980 			&repinfo->client_addr, opt_list);
    981 		return;
    982 	}
    983 #endif
    984 	/* create the prefetch in the mesh as a normal lookup without
    985 	 * client addrs waiting, which has the cache blacklisted (to bypass
    986 	 * the cache and go to the network for the data). */
    987 	/* this (potentially) runs the mesh for the new query */
    988 	mesh_new_prefetch(worker->env.mesh, qinfo, flags, leeway +
    989 		PREFETCH_EXPIRY_ADD, rpz_passthru, NULL, NULL);
    990 }
    991 
    992 /**
    993  * Fill CH class answer into buffer. Keeps query.
    994  * @param pkt: buffer
    995  * @param str: string to put into text record (<255).
    996  * 	array of strings, every string becomes a text record.
    997  * @param num: number of strings in array.
    998  * @param edns: edns reply information.
    999  * @param worker: worker with scratch region.
   1000  * @param repinfo: reply information for a communication point.
   1001  */
   1002 static void
   1003 chaos_replystr(sldns_buffer* pkt, char** str, int num, struct edns_data* edns,
   1004 	struct worker* worker, struct comm_reply* repinfo)
   1005 {
   1006 	int i;
   1007 	unsigned int rd = LDNS_RD_WIRE(sldns_buffer_begin(pkt));
   1008 	unsigned int cd = LDNS_CD_WIRE(sldns_buffer_begin(pkt));
   1009 	size_t udpsize = edns->udp_size;
   1010 	edns->edns_version = EDNS_ADVERTISED_VERSION;
   1011 	edns->udp_size = EDNS_ADVERTISED_SIZE;
   1012 	edns->ext_rcode = 0;
   1013 	edns->bits &= EDNS_DO;
   1014 	if(!inplace_cb_reply_local_call(&worker->env, NULL, NULL, NULL,
   1015 		LDNS_RCODE_NOERROR, edns, repinfo, worker->scratchpad,
   1016 		worker->env.now_tv))
   1017 			edns->opt_list_inplace_cb_out = NULL;
   1018 	sldns_buffer_clear(pkt);
   1019 	sldns_buffer_skip(pkt, (ssize_t)sizeof(uint16_t)); /* skip id */
   1020 	sldns_buffer_write_u16(pkt, (uint16_t)(BIT_QR|BIT_RA));
   1021 	if(rd) LDNS_RD_SET(sldns_buffer_begin(pkt));
   1022 	if(cd) LDNS_CD_SET(sldns_buffer_begin(pkt));
   1023 	sldns_buffer_write_u16(pkt, 1); /* qdcount */
   1024 	sldns_buffer_write_u16(pkt, (uint16_t)num); /* ancount */
   1025 	sldns_buffer_write_u16(pkt, 0); /* nscount */
   1026 	sldns_buffer_write_u16(pkt, 0); /* arcount */
   1027 	(void)query_dname_len(pkt); /* skip qname */
   1028 	sldns_buffer_skip(pkt, (ssize_t)sizeof(uint16_t)); /* skip qtype */
   1029 	sldns_buffer_skip(pkt, (ssize_t)sizeof(uint16_t)); /* skip qclass */
   1030 	for(i=0; i<num; i++) {
   1031 		size_t len = strlen(str[i]);
   1032 		if(len>255) len=255; /* cap size of TXT record */
   1033 		if(sldns_buffer_position(pkt)+2+2+2+4+2+1+len+
   1034 			calc_edns_field_size(edns) > udpsize) {
   1035 			sldns_buffer_write_u16_at(pkt, 6, i); /* ANCOUNT */
   1036 			LDNS_TC_SET(sldns_buffer_begin(pkt));
   1037 			break;
   1038 		}
   1039 		sldns_buffer_write_u16(pkt, 0xc00c); /* compr ptr to query */
   1040 		sldns_buffer_write_u16(pkt, LDNS_RR_TYPE_TXT);
   1041 		sldns_buffer_write_u16(pkt, LDNS_RR_CLASS_CH);
   1042 		sldns_buffer_write_u32(pkt, 0); /* TTL */
   1043 		sldns_buffer_write_u16(pkt, sizeof(uint8_t) + len);
   1044 		sldns_buffer_write_u8(pkt, len);
   1045 		sldns_buffer_write(pkt, str[i], len);
   1046 	}
   1047 	sldns_buffer_flip(pkt);
   1048 	if(sldns_buffer_capacity(pkt) >=
   1049 		sldns_buffer_limit(pkt)+calc_edns_field_size(edns))
   1050 		attach_edns_record(pkt, edns);
   1051 }
   1052 
   1053 /** Reply with one string */
   1054 static void
   1055 chaos_replyonestr(sldns_buffer* pkt, const char* str, struct edns_data* edns,
   1056 	struct worker* worker, struct comm_reply* repinfo)
   1057 {
   1058 	chaos_replystr(pkt, (char**)&str, 1, edns, worker, repinfo);
   1059 }
   1060 
   1061 /**
   1062  * Create CH class trustanchor answer.
   1063  * @param pkt: buffer
   1064  * @param edns: edns reply information.
   1065  * @param w: worker with scratch region.
   1066  * @param repinfo: reply information for a communication point.
   1067  */
   1068 static void
   1069 chaos_trustanchor(sldns_buffer* pkt, struct edns_data* edns, struct worker* w,
   1070 	struct comm_reply* repinfo)
   1071 {
   1072 #define TA_RESPONSE_MAX_TXT 16 /* max number of TXT records */
   1073 #define TA_RESPONSE_MAX_TAGS 32 /* max number of tags printed per zone */
   1074 	char* str_array[TA_RESPONSE_MAX_TXT];
   1075 	uint16_t tags[TA_RESPONSE_MAX_TAGS];
   1076 	int num = 0;
   1077 	struct trust_anchor* ta;
   1078 
   1079 	if(!w->env.need_to_validate) {
   1080 		/* no validator module, reply no trustanchors */
   1081 		chaos_replystr(pkt, NULL, 0, edns, w, repinfo);
   1082 		return;
   1083 	}
   1084 
   1085 	/* fill the string with contents */
   1086 	lock_basic_lock(&w->env.anchors->lock);
   1087 	RBTREE_FOR(ta, struct trust_anchor*, w->env.anchors->tree) {
   1088 		char* str;
   1089 		size_t i, numtag, str_len = 255;
   1090 		if(num == TA_RESPONSE_MAX_TXT) continue;
   1091 		str = (char*)regional_alloc(w->scratchpad, str_len);
   1092 		if(!str) continue;
   1093 		lock_basic_lock(&ta->lock);
   1094 		numtag = anchor_list_keytags(ta, tags, TA_RESPONSE_MAX_TAGS);
   1095 		if(numtag == 0) {
   1096 			/* empty, insecure point */
   1097 			lock_basic_unlock(&ta->lock);
   1098 			continue;
   1099 		}
   1100 		str_array[num] = str;
   1101 		num++;
   1102 
   1103 		/* spool name of anchor */
   1104 		(void)sldns_wire2str_dname_buf(ta->name, ta->namelen, str, str_len);
   1105 		str_len -= strlen(str); str += strlen(str);
   1106 		/* spool tags */
   1107 		for(i=0; i<numtag; i++) {
   1108 			snprintf(str, str_len, " %u", (unsigned)tags[i]);
   1109 			str_len -= strlen(str); str += strlen(str);
   1110 		}
   1111 		lock_basic_unlock(&ta->lock);
   1112 	}
   1113 	lock_basic_unlock(&w->env.anchors->lock);
   1114 
   1115 	chaos_replystr(pkt, str_array, num, edns, w, repinfo);
   1116 	regional_free_all(w->scratchpad);
   1117 }
   1118 
   1119 /**
   1120  * Answer CH class queries.
   1121  * @param w: worker
   1122  * @param qinfo: query info. Pointer into packet buffer.
   1123  * @param edns: edns info from query.
   1124  * @param repinfo: reply information for a communication point.
   1125  * @param pkt: packet buffer.
   1126  * @return: true if a reply is to be sent.
   1127  */
   1128 static int
   1129 answer_chaos(struct worker* w, struct query_info* qinfo,
   1130 	struct edns_data* edns, struct comm_reply* repinfo, sldns_buffer* pkt)
   1131 {
   1132 	struct config_file* cfg = w->env.cfg;
   1133 	if(qinfo->qtype != LDNS_RR_TYPE_ANY && qinfo->qtype != LDNS_RR_TYPE_TXT)
   1134 		return 0;
   1135 	if(query_dname_compare(qinfo->qname,
   1136 		(uint8_t*)"\002id\006server") == 0 ||
   1137 		query_dname_compare(qinfo->qname,
   1138 		(uint8_t*)"\010hostname\004bind") == 0)
   1139 	{
   1140 		if(cfg->hide_identity)
   1141 			return 0;
   1142 		if(cfg->identity==NULL || cfg->identity[0]==0) {
   1143 			char buf[MAXHOSTNAMELEN+1];
   1144 			if (gethostname(buf, MAXHOSTNAMELEN) == 0) {
   1145 				buf[MAXHOSTNAMELEN] = 0;
   1146 				chaos_replyonestr(pkt, buf, edns, w, repinfo);
   1147 			} else 	{
   1148 				log_err("gethostname: %s", strerror(errno));
   1149 				chaos_replyonestr(pkt, "no hostname", edns, w, repinfo);
   1150 			}
   1151 		}
   1152 		else 	chaos_replyonestr(pkt, cfg->identity, edns, w, repinfo);
   1153 		return 1;
   1154 	}
   1155 	if(query_dname_compare(qinfo->qname,
   1156 		(uint8_t*)"\007version\006server") == 0 ||
   1157 		query_dname_compare(qinfo->qname,
   1158 		(uint8_t*)"\007version\004bind") == 0)
   1159 	{
   1160 		if(cfg->hide_version)
   1161 			return 0;
   1162 		if(cfg->version==NULL || cfg->version[0]==0)
   1163 			chaos_replyonestr(pkt, PACKAGE_STRING, edns, w, repinfo);
   1164 		else 	chaos_replyonestr(pkt, cfg->version, edns, w, repinfo);
   1165 		return 1;
   1166 	}
   1167 	if(query_dname_compare(qinfo->qname,
   1168 		(uint8_t*)"\013trustanchor\007unbound") == 0)
   1169 	{
   1170 		if(cfg->hide_trustanchor)
   1171 			return 0;
   1172 		chaos_trustanchor(pkt, edns, w, repinfo);
   1173 		return 1;
   1174 	}
   1175 
   1176 	return 0;
   1177 }
   1178 
   1179 /**
   1180  * Answer notify queries.  These are notifies for authoritative zones,
   1181  * the reply is an ack that the notify has been received.  We need to check
   1182  * access permission here.
   1183  * @param w: worker
   1184  * @param qinfo: query info. Pointer into packet buffer.
   1185  * @param edns: edns info from query.
   1186  * @param addr: client address.
   1187  * @param addrlen: client address length.
   1188  * @param pkt: packet buffer.
   1189  */
   1190 static void
   1191 answer_notify(struct worker* w, struct query_info* qinfo,
   1192 	struct edns_data* edns, sldns_buffer* pkt,
   1193 	struct sockaddr_storage* addr, socklen_t addrlen)
   1194 {
   1195 	int refused = 0;
   1196 	int rcode = LDNS_RCODE_NOERROR;
   1197 	uint32_t serial = 0;
   1198 	int has_serial;
   1199 	if(!w->env.auth_zones) return;
   1200 	has_serial = auth_zone_parse_notify_serial(pkt, &serial);
   1201 	if(auth_zones_notify(w->env.auth_zones, &w->env, qinfo->qname,
   1202 		qinfo->qname_len, qinfo->qclass, addr,
   1203 		addrlen, has_serial, serial, &refused)) {
   1204 		rcode = LDNS_RCODE_NOERROR;
   1205 	} else {
   1206 		if(refused)
   1207 			rcode = LDNS_RCODE_REFUSED;
   1208 		else	rcode = LDNS_RCODE_SERVFAIL;
   1209 	}
   1210 
   1211 	if(verbosity >= VERB_DETAIL) {
   1212 		char buf[380];
   1213 		char zname[LDNS_MAX_DOMAINLEN];
   1214 		char sr[25];
   1215 		dname_str(qinfo->qname, zname);
   1216 		sr[0]=0;
   1217 		if(has_serial)
   1218 			snprintf(sr, sizeof(sr), "serial %u ",
   1219 				(unsigned)serial);
   1220 		if(rcode == LDNS_RCODE_REFUSED)
   1221 			snprintf(buf, sizeof(buf),
   1222 				"refused NOTIFY %sfor %s from", sr, zname);
   1223 		else if(rcode == LDNS_RCODE_SERVFAIL)
   1224 			snprintf(buf, sizeof(buf),
   1225 				"servfail for NOTIFY %sfor %s from", sr, zname);
   1226 		else	snprintf(buf, sizeof(buf),
   1227 				"received NOTIFY %sfor %s from", sr, zname);
   1228 		log_addr(VERB_DETAIL, buf, addr, addrlen);
   1229 	}
   1230 	edns->edns_version = EDNS_ADVERTISED_VERSION;
   1231 	edns->udp_size = EDNS_ADVERTISED_SIZE;
   1232 	edns->ext_rcode = 0;
   1233 	edns->bits &= EDNS_DO;
   1234 	error_encode(pkt, rcode, qinfo,
   1235 		*(uint16_t*)(void *)sldns_buffer_begin(pkt),
   1236 		sldns_buffer_read_u16_at(pkt, 2), edns);
   1237 	LDNS_OPCODE_SET(sldns_buffer_begin(pkt), LDNS_PACKET_NOTIFY);
   1238 }
   1239 
   1240 static int
   1241 deny_refuse(struct comm_point* c, enum acl_access acl,
   1242 	enum acl_access deny, enum acl_access refuse,
   1243 	struct worker* worker, struct comm_reply* repinfo,
   1244 	struct acl_addr* acladdr, int ede,
   1245 	struct check_request_result* check_result)
   1246 {
   1247 	if(acl == deny) {
   1248 		if(verbosity >= VERB_ALGO) {
   1249 			log_acl_action("dropped", &repinfo->client_addr,
   1250 				repinfo->client_addrlen, acl, acladdr);
   1251 			log_buf(VERB_ALGO, "dropped", c->buffer);
   1252 		}
   1253 		comm_point_drop_reply(repinfo);
   1254 		if(worker->stats.extended)
   1255 			worker->stats.unwanted_queries++;
   1256 		return 0;
   1257 	} else if(acl == refuse) {
   1258 		size_t opt_rr_mark;
   1259 
   1260 		if(verbosity >= VERB_ALGO) {
   1261 			log_acl_action("refused", &repinfo->client_addr,
   1262 				repinfo->client_addrlen, acl, acladdr);
   1263 			log_buf(VERB_ALGO, "refuse", c->buffer);
   1264 		}
   1265 
   1266 		if(worker->stats.extended)
   1267 			worker->stats.unwanted_queries++;
   1268 		worker_check_request(c->buffer, worker, check_result);
   1269 		if(check_result->value != 0) {
   1270 			if(check_result->value != -1) {
   1271 				query_error(c->buffer, check_result->value, 0);
   1272 				return 1;
   1273 			}
   1274 			comm_point_drop_reply(repinfo);
   1275 			return 0;
   1276 		}
   1277 		/* worker_check_request() above guarantees that the buffer contains at
   1278 		 * least a header and that qdcount == 1
   1279 		 */
   1280 		log_assert(sldns_buffer_limit(c->buffer) >= LDNS_HEADER_SIZE
   1281 			&& LDNS_QDCOUNT(sldns_buffer_begin(c->buffer)) == 1);
   1282 
   1283 		sldns_buffer_set_position(c->buffer, LDNS_HEADER_SIZE); /* skip header */
   1284 
   1285 		/* check additional section is present and that we respond with EDEs */
   1286 		if(LDNS_ARCOUNT(sldns_buffer_begin(c->buffer)) != 1
   1287 			|| !ede) {
   1288 			query_error(c->buffer, LDNS_RCODE_REFUSED, 0);
   1289 			return 1;
   1290 		}
   1291 
   1292 		if (!query_dname_len(c->buffer)) {
   1293 			query_error(c->buffer, LDNS_RCODE_FORMERR, 0);
   1294 			return 1;
   1295 		}
   1296 		/* space available for query type and class? */
   1297 		if (sldns_buffer_remaining(c->buffer) < 2 * sizeof(uint16_t)) {
   1298 			query_error(c->buffer, LDNS_RCODE_FORMERR, 0);
   1299 			return 1;
   1300 		}
   1301 		LDNS_QR_SET(sldns_buffer_begin(c->buffer));
   1302 		LDNS_RCODE_SET(sldns_buffer_begin(c->buffer),
   1303 			LDNS_RCODE_REFUSED);
   1304 
   1305 		sldns_buffer_skip(c->buffer, (ssize_t)sizeof(uint16_t)); /* skip qtype */
   1306 
   1307 		sldns_buffer_skip(c->buffer, (ssize_t)sizeof(uint16_t)); /* skip qclass */
   1308 
   1309 		/* The OPT RR to be returned should come directly after
   1310 		 * the query, so mark this spot.
   1311 		 */
   1312 		opt_rr_mark = sldns_buffer_position(c->buffer);
   1313 
   1314 		/* Skip through the RR records */
   1315 		if(LDNS_ANCOUNT(sldns_buffer_begin(c->buffer)) != 0 ||
   1316 			LDNS_NSCOUNT(sldns_buffer_begin(c->buffer)) != 0) {
   1317 			if(!skip_pkt_rrs(c->buffer,
   1318 				((int)LDNS_ANCOUNT(sldns_buffer_begin(c->buffer)))+
   1319 				((int)LDNS_NSCOUNT(sldns_buffer_begin(c->buffer))))) {
   1320 				query_error(c->buffer, LDNS_RCODE_FORMERR,
   1321 					opt_rr_mark - LDNS_HEADER_SIZE
   1322 					- 2 /* qtype */ - 2 /* qclass */);
   1323 				return 1;
   1324 			}
   1325 		}
   1326 		/* Do we have a valid OPT RR here? If not return REFUSED (could be a valid TSIG or something so no FORMERR) */
   1327 		/* domain name must be the root of length 1. */
   1328 		if(sldns_buffer_remaining(c->buffer) < 1 || *sldns_buffer_current(c->buffer) != 0) {
   1329 			query_error(c->buffer, LDNS_RCODE_REFUSED,
   1330 				opt_rr_mark - LDNS_HEADER_SIZE
   1331 				- 2 /* qtype */ - 2 /* qclass */);
   1332 			return 1;
   1333 		} else {
   1334 			sldns_buffer_skip(c->buffer, 1); /* skip root label */
   1335 		}
   1336 		if(sldns_buffer_remaining(c->buffer) < 2 ||
   1337 			sldns_buffer_read_u16(c->buffer) != LDNS_RR_TYPE_OPT) {
   1338 			query_error(c->buffer, LDNS_RCODE_REFUSED,
   1339 				opt_rr_mark - LDNS_HEADER_SIZE
   1340 				- 2 /* qtype */ - 2 /* qclass */);
   1341 			return 1;
   1342 		}
   1343 		/* Write OPT RR directly after the query,
   1344 		 * so without the (possibly skipped) Answer and NS RRs
   1345 		 */
   1346 		LDNS_ANCOUNT_SET(sldns_buffer_begin(c->buffer), 0);
   1347 		LDNS_NSCOUNT_SET(sldns_buffer_begin(c->buffer), 0);
   1348 		sldns_buffer_clear(c->buffer); /* reset write limit */
   1349 		sldns_buffer_set_position(c->buffer, opt_rr_mark);
   1350 
   1351 		/* Check if OPT record can be written
   1352 		 * 17 == root label (1) + RR type (2) + UDP Size (2)
   1353 		 *     + Fields (4) + rdata len (2) + EDE Option code (2)
   1354 		 *     + EDE Option length (2) + EDE info-code (2)
   1355 		 */
   1356 		if (sldns_buffer_available(c->buffer, 17) == 0) {
   1357 			LDNS_ARCOUNT_SET(sldns_buffer_begin(c->buffer), 0);
   1358 			sldns_buffer_flip(c->buffer);
   1359 			return 1;
   1360 		}
   1361 
   1362 		LDNS_ARCOUNT_SET(sldns_buffer_begin(c->buffer), 1);
   1363 
   1364 		/* root label */
   1365 		sldns_buffer_write_u8(c->buffer, 0);
   1366 		sldns_buffer_write_u16(c->buffer, LDNS_RR_TYPE_OPT);
   1367 		sldns_buffer_write_u16(c->buffer, EDNS_ADVERTISED_SIZE);
   1368 
   1369 		/* write OPT Record TTL Field */
   1370 		sldns_buffer_write_u32(c->buffer, 0);
   1371 
   1372 		/* write rdata len: EDE option + length + info-code */
   1373 		sldns_buffer_write_u16(c->buffer, 6);
   1374 
   1375 		/* write OPTIONS; add EDE option code */
   1376 		sldns_buffer_write_u16(c->buffer, LDNS_EDNS_EDE);
   1377 
   1378 		/* write single EDE option length (for just 1 info-code) */
   1379 		sldns_buffer_write_u16(c->buffer, 2);
   1380 
   1381 		/* write single EDE info-code */
   1382 		sldns_buffer_write_u16(c->buffer, LDNS_EDE_PROHIBITED);
   1383 
   1384 		sldns_buffer_flip(c->buffer);
   1385 
   1386 		verbose(VERB_ALGO, "attached EDE code: %d", LDNS_EDE_PROHIBITED);
   1387 
   1388 		return 1;
   1389 
   1390 	}
   1391 
   1392 	return -1;
   1393 }
   1394 
   1395 static int
   1396 deny_refuse_all(struct comm_point* c, enum acl_access* acl,
   1397 	struct worker* worker, struct comm_reply* repinfo,
   1398 	struct acl_addr** acladdr, int ede, int check_proxy,
   1399 	struct check_request_result* check_result)
   1400 {
   1401 	if(check_proxy) {
   1402 		*acladdr = acl_addr_lookup(worker->daemon->acl,
   1403 			&repinfo->remote_addr, repinfo->remote_addrlen);
   1404 	} else {
   1405 		*acladdr = acl_addr_lookup(worker->daemon->acl,
   1406 			&repinfo->client_addr, repinfo->client_addrlen);
   1407 	}
   1408 	/* If there is no ACL based on client IP use the interface ACL. */
   1409 	if(!(*acladdr) && c->socket) {
   1410 		*acladdr = c->socket->acl;
   1411 	}
   1412 	*acl = acl_get_control(*acladdr);
   1413 	return deny_refuse(c, *acl, acl_deny, acl_refuse, worker, repinfo,
   1414 		*acladdr, ede, check_result);
   1415 }
   1416 
   1417 static int
   1418 deny_refuse_non_local(struct comm_point* c, enum acl_access acl,
   1419 	struct worker* worker, struct comm_reply* repinfo,
   1420 	struct acl_addr* acladdr, int ede,
   1421 	struct check_request_result* check_result)
   1422 {
   1423 	return deny_refuse(c, acl, acl_deny_non_local, acl_refuse_non_local,
   1424 		worker, repinfo, acladdr, ede, check_result);
   1425 }
   1426 
   1427 /* Check if the query is blocked by source IP rate limiting.
   1428  * Returns 1 if it passes the check, 0 otherwise. */
   1429 static int
   1430 check_ip_ratelimit(struct worker* worker, struct sockaddr_storage* addr,
   1431 	socklen_t addrlen, int has_cookie, sldns_buffer* pkt)
   1432 {
   1433 	if(!infra_ip_ratelimit_inc(worker->env.infra_cache, addr, addrlen,
   1434 			*worker->env.now, has_cookie,
   1435 			worker->env.cfg->ip_ratelimit_backoff, pkt)) {
   1436 		/* See if we can pass through with slip factor */
   1437 		if(!has_cookie && worker->env.cfg->ip_ratelimit_factor != 0 &&
   1438 			ub_random_max(worker->env.rnd,
   1439 			worker->env.cfg->ip_ratelimit_factor) == 0) {
   1440 			char addrbuf[128];
   1441 			addr_to_str(addr, addrlen, addrbuf, sizeof(addrbuf));
   1442 			verbose(VERB_QUERY, "ip_ratelimit allowed through for "
   1443 				"ip address %s because of slip in "
   1444 				"ip_ratelimit_factor", addrbuf);
   1445 			return 1;
   1446 		}
   1447 		return 0;
   1448 	}
   1449 	return 1;
   1450 }
   1451 
   1452 /*
   1453  * This is the callback function when a request arrives. It is passed
   1454  * the packet and user argument. Return true to send a reply.
   1455  * This is of type comm_point_callback_type. The struct comm_point contains
   1456  * more comments on the comm_point.callback member about the function.
   1457  * @param c: the comm_point where the request arrives on.
   1458  * @param arg: the user argument for the callback, the worker.
   1459  * @param error: This can be NETEVENT_NOERROR, NETEVENT_TIMEOUT,
   1460  *	NETEVENT_CLOSED or other comm point callback error values.
   1461  * @param repinfo: The reply info, use it to send a reply. If the reply
   1462  *	is immediate, return 1. If the reply is later on return 0 and save
   1463  *	the repinfo, to call comm_point_send_reply on.
   1464  * @return 1 to sent a reply straight away, for like cache response so that
   1465  *	no allocation needs to be done. And only internal preallocated buffers
   1466  *	are used. Return 0 and save the repinfo to reply later, for responses
   1467  *	that need to be looked up. Return 0 and call comm_point_drop_reply on
   1468  *	the repinfo to drop the response.
   1469  */
   1470 int
   1471 worker_handle_request(struct comm_point* c, void* arg, int error,
   1472 	struct comm_reply* repinfo)
   1473 {
   1474 	struct worker* worker = (struct worker*)arg;
   1475 	int ret;
   1476 	hashvalue_type h;
   1477 	struct lruhash_entry* e;
   1478 	struct query_info qinfo;
   1479 	struct edns_data edns;
   1480 	struct edns_option* original_edns_list = NULL;
   1481 	enum acl_access acl;
   1482 	struct acl_addr* acladdr;
   1483 	int pre_edns_ip_ratelimit = 1;
   1484 	int rc = 0;
   1485 	int need_drop = 0;
   1486 	int is_expired_answer = 0;
   1487 	int is_secure_answer = 0;
   1488 	int rpz_passthru = 0;
   1489 	long long wait_queue_time = 0;
   1490 	/* We might have to chase a CNAME chain internally, in which case
   1491 	 * we'll have up to two replies and combine them to build a complete
   1492 	 * answer.  These variables control this case. */
   1493 	struct ub_packed_rrset_key* alias_rrset = NULL;
   1494 	struct reply_info* partial_rep = NULL;
   1495 	struct query_info* lookup_qinfo = &qinfo;
   1496 	struct query_info qinfo_tmp; /* placeholder for lookup_qinfo */
   1497 	struct respip_client_info* cinfo = NULL, cinfo_tmp;
   1498 	struct timeval wait_time;
   1499 	struct check_request_result check_result = {0,0};
   1500 	memset(&qinfo, 0, sizeof(qinfo));
   1501 
   1502 	if((error != NETEVENT_NOERROR && error != NETEVENT_DONE)|| !repinfo) {
   1503 		/* some bad tcp query DNS formats give these error calls */
   1504 		verbose(VERB_ALGO, "handle request called with err=%d", error);
   1505 		return 0;
   1506 	}
   1507 
   1508 	if (worker->env.cfg->sock_queue_timeout && timeval_isset(&c->recv_tv)) {
   1509 		timeval_subtract(&wait_time, worker->env.now_tv, &c->recv_tv);
   1510 		wait_queue_time = wait_time.tv_sec * 1000000 +  wait_time.tv_usec;
   1511 		if (worker->stats.max_query_time_us < wait_queue_time)
   1512 			worker->stats.max_query_time_us = wait_queue_time;
   1513 		if(wait_queue_time >
   1514 			(long long)(worker->env.cfg->sock_queue_timeout * 1000000)) {
   1515 			/* count and drop queries that were sitting in the socket queue too long */
   1516 			worker->stats.num_queries_timed_out++;
   1517 			return 0;
   1518 		}
   1519 	}
   1520 
   1521 #ifdef USE_DNSCRYPT
   1522 	repinfo->max_udp_size = worker->daemon->cfg->max_udp_size;
   1523 	if(!dnsc_handle_curved_request(worker->daemon->dnscenv, repinfo)) {
   1524 		worker->stats.num_query_dnscrypt_crypted_malformed++;
   1525 		return 0;
   1526 	}
   1527 	if(c->dnscrypt && !repinfo->is_dnscrypted) {
   1528 		char buf[LDNS_MAX_DOMAINLEN];
   1529 		/* Check if this is unencrypted and asking for certs */
   1530 		worker_check_request(c->buffer, worker, &check_result);
   1531 		if(check_result.value != 0) {
   1532 			verbose(VERB_ALGO,
   1533 				"dnscrypt: worker check request: bad query.");
   1534 			log_addr(VERB_CLIENT,"from",&repinfo->client_addr,
   1535 				repinfo->client_addrlen);
   1536 			if(check_result.value != -1) {
   1537 				query_error(c->buffer, check_result.value, 0);
   1538 				return 1;
   1539 			}
   1540 			comm_point_drop_reply(repinfo);
   1541 			return 0;
   1542 		}
   1543 		if(!query_info_parse(&qinfo, c->buffer)) {
   1544 			verbose(VERB_ALGO,
   1545 				"dnscrypt: worker parse request: formerror.");
   1546 			log_addr(VERB_CLIENT, "from", &repinfo->client_addr,
   1547 				repinfo->client_addrlen);
   1548 			if(worker_err_ratelimit(worker, LDNS_RCODE_FORMERR) == -1) {
   1549 				comm_point_drop_reply(repinfo);
   1550 				return 0;
   1551 			}
   1552 			query_error(c->buffer, LDNS_RCODE_FORMERR, 0);
   1553 			return 1;
   1554 		}
   1555 		dname_str(qinfo.qname, buf);
   1556 		if(!(qinfo.qtype == LDNS_RR_TYPE_TXT &&
   1557 			strcasecmp(buf,
   1558 			worker->daemon->dnscenv->provider_name) == 0)) {
   1559 			verbose(VERB_ALGO,
   1560 				"dnscrypt: not TXT \"%s\". Received: %s \"%s\"",
   1561 				worker->daemon->dnscenv->provider_name,
   1562 				sldns_rr_descript(qinfo.qtype)->_name,
   1563 				buf);
   1564 			if(worker_err_ratelimit(worker, LDNS_RCODE_SERVFAIL) == -1) {
   1565 				comm_point_drop_reply(repinfo);
   1566 				return 0;
   1567 			}
   1568 			query_error(c->buffer, LDNS_RCODE_SERVFAIL,
   1569 				qinfo.qname_len);
   1570 			worker->stats.num_query_dnscrypt_cleartext++;
   1571 			return 1;
   1572 		}
   1573 		worker->stats.num_query_dnscrypt_cert++;
   1574 		sldns_buffer_rewind(c->buffer);
   1575 	} else if(c->dnscrypt && repinfo->is_dnscrypted) {
   1576 		worker->stats.num_query_dnscrypt_crypted++;
   1577 	}
   1578 #endif
   1579 #ifdef USE_DNSTAP
   1580 	/*
   1581 	 * sending src (client)/dst (local service) addresses over DNSTAP from incoming request handler
   1582 	 */
   1583 	if(worker->dtenv.log_client_query_messages) {
   1584 		log_addr(VERB_ALGO, "request from client", &repinfo->client_addr, repinfo->client_addrlen);
   1585 		log_addr(VERB_ALGO, "to local addr", (void*)repinfo->c->socket->addr, repinfo->c->socket->addrlen);
   1586 		dt_msg_send_client_query(&worker->dtenv, &repinfo->client_addr, (void*)repinfo->c->socket->addr, c->type, c->ssl, c->buffer,
   1587 		((worker->env.cfg->sock_queue_timeout && timeval_isset(&c->recv_tv))?&c->recv_tv:NULL));
   1588 	}
   1589 #endif
   1590 	/* Check deny/refuse ACLs */
   1591 	if(repinfo->is_proxied) {
   1592 		if((ret=deny_refuse_all(c, &acl, worker, repinfo, &acladdr,
   1593 			worker->env.cfg->ede, 1, &check_result)) != -1) {
   1594 			if(ret == 1)
   1595 				goto send_reply;
   1596 			return ret;
   1597 		}
   1598 	}
   1599 	if((ret=deny_refuse_all(c, &acl, worker, repinfo, &acladdr,
   1600 		worker->env.cfg->ede, 0, &check_result)) != -1) {
   1601 		if(ret == 1)
   1602 			goto send_reply;
   1603 		return ret;
   1604 	}
   1605 
   1606 	worker_check_request(c->buffer, worker, &check_result);
   1607 	if(check_result.value != 0) {
   1608 		verbose(VERB_ALGO, "worker check request: bad query.");
   1609 		log_addr(VERB_CLIENT,"from",&repinfo->client_addr, repinfo->client_addrlen);
   1610 		if(check_result.value != -1) {
   1611 			query_error(c->buffer, check_result.value, 0);
   1612 			return 1;
   1613 		}
   1614 		comm_point_drop_reply(repinfo);
   1615 		return 0;
   1616 	}
   1617 
   1618 	worker->stats.num_queries++;
   1619 	pre_edns_ip_ratelimit = !worker->env.cfg->do_answer_cookie
   1620 		|| sldns_buffer_limit(c->buffer) < LDNS_HEADER_SIZE
   1621 		|| LDNS_ARCOUNT(sldns_buffer_begin(c->buffer)) == 0;
   1622 
   1623 	/* If the IP rate limiting check needs extra EDNS information (e.g.,
   1624 	 * DNS Cookies) postpone the check until after EDNS is parsed. */
   1625 	if(pre_edns_ip_ratelimit) {
   1626 		/* NOTE: we always check the repinfo->client_address.
   1627 		 *       IP ratelimiting is implicitly disabled for proxies. */
   1628 		if(!check_ip_ratelimit(worker, &repinfo->client_addr,
   1629 			repinfo->client_addrlen, 0, c->buffer)) {
   1630 			worker->stats.num_queries_ip_ratelimited++;
   1631 			comm_point_drop_reply(repinfo);
   1632 			return 0;
   1633 		}
   1634 	}
   1635 
   1636 	if(!query_info_parse(&qinfo, c->buffer)) {
   1637 		verbose(VERB_ALGO, "worker parse request: formerror.");
   1638 		log_addr(VERB_CLIENT, "from", &repinfo->client_addr,
   1639 			repinfo->client_addrlen);
   1640 		memset(&qinfo, 0, sizeof(qinfo)); /* zero qinfo.qname */
   1641 		if(worker_err_ratelimit(worker, LDNS_RCODE_FORMERR) == -1) {
   1642 			comm_point_drop_reply(repinfo);
   1643 			return 0;
   1644 		}
   1645 		query_error(c->buffer, LDNS_RCODE_FORMERR, 0);
   1646 		goto send_reply;
   1647 	}
   1648 	if(worker->env.cfg->log_queries) {
   1649 		char ip[128];
   1650 		addr_to_str(&repinfo->client_addr, repinfo->client_addrlen, ip, sizeof(ip));
   1651 		log_query_in(ip, qinfo.qname, qinfo.qtype, qinfo.qclass);
   1652 	}
   1653 	if(qinfo.qtype == LDNS_RR_TYPE_AXFR ||
   1654 		qinfo.qtype == LDNS_RR_TYPE_IXFR) {
   1655 		verbose(VERB_ALGO, "worker request: refused zone transfer.");
   1656 		log_addr(VERB_CLIENT, "from", &repinfo->client_addr,
   1657 			repinfo->client_addrlen);
   1658 		if(worker_err_ratelimit(worker, LDNS_RCODE_REFUSED) == -1) {
   1659 			comm_point_drop_reply(repinfo);
   1660 			return 0;
   1661 		}
   1662 		query_error(c->buffer, LDNS_RCODE_REFUSED, qinfo.qname_len);
   1663 		if(worker->stats.extended) {
   1664 			worker->stats.qtype[qinfo.qtype]++;
   1665 		}
   1666 		goto send_reply;
   1667 	}
   1668 	if(qinfo.qtype == LDNS_RR_TYPE_OPT ||
   1669 		qinfo.qtype == LDNS_RR_TYPE_TSIG ||
   1670 		qinfo.qtype == LDNS_RR_TYPE_TKEY ||
   1671 		qinfo.qtype == LDNS_RR_TYPE_MAILA ||
   1672 		qinfo.qtype == LDNS_RR_TYPE_MAILB ||
   1673 		(qinfo.qtype >= 128 && qinfo.qtype <= 248)) {
   1674 		verbose(VERB_ALGO, "worker request: formerror for meta-type.");
   1675 		log_addr(VERB_CLIENT, "from", &repinfo->client_addr,
   1676 			repinfo->client_addrlen);
   1677 		if(worker_err_ratelimit(worker, LDNS_RCODE_FORMERR) == -1) {
   1678 			comm_point_drop_reply(repinfo);
   1679 			return 0;
   1680 		}
   1681 		query_error(c->buffer, LDNS_RCODE_FORMERR, qinfo.qname_len);
   1682 		if(worker->stats.extended) {
   1683 			worker->stats.qtype[qinfo.qtype]++;
   1684 		}
   1685 		goto send_reply;
   1686 	}
   1687 	if((ret=parse_edns_from_query_pkt(
   1688 			c->buffer, &edns, worker->env.cfg, c, repinfo,
   1689 			*worker->env.now, worker->scratchpad,
   1690 			worker->daemon->cookie_secrets)) != 0) {
   1691 		struct edns_data reply_edns;
   1692 		verbose(VERB_ALGO, "worker parse edns: formerror.");
   1693 		log_addr(VERB_CLIENT, "from", &repinfo->client_addr,
   1694 			repinfo->client_addrlen);
   1695 		if(worker_err_ratelimit(worker, ret) == -1) {
   1696 			comm_point_drop_reply(repinfo);
   1697 			regional_free_all(worker->scratchpad);
   1698 			return 0;
   1699 		}
   1700 		memset(&reply_edns, 0, sizeof(reply_edns));
   1701 		reply_edns.edns_present = 1;
   1702 		error_encode(c->buffer, ret, &qinfo,
   1703 			*(uint16_t*)(void *)sldns_buffer_begin(c->buffer),
   1704 			sldns_buffer_read_u16_at(c->buffer, 2), &reply_edns);
   1705 		regional_free_all(worker->scratchpad);
   1706 		goto send_reply;
   1707 	}
   1708 	if(edns.edns_present) {
   1709 		if(edns.edns_version != 0) {
   1710 			edns.opt_list_in = NULL;
   1711 			edns.opt_list_out = NULL;
   1712 			edns.opt_list_inplace_cb_out = NULL;
   1713 			verbose(VERB_ALGO, "query with bad edns version.");
   1714 			log_addr(VERB_CLIENT, "from", &repinfo->client_addr,
   1715 				repinfo->client_addrlen);
   1716 			if(worker_err_ratelimit(worker, EDNS_RCODE_BADVERS) == -1) {
   1717 				comm_point_drop_reply(repinfo);
   1718 				regional_free_all(worker->scratchpad);
   1719 				return 0;
   1720 			}
   1721 			extended_error_encode(c->buffer, EDNS_RCODE_BADVERS, &qinfo,
   1722 				*(uint16_t*)(void *)sldns_buffer_begin(c->buffer),
   1723 				sldns_buffer_read_u16_at(c->buffer, 2), 0, &edns);
   1724 			regional_free_all(worker->scratchpad);
   1725 			goto send_reply;
   1726 		}
   1727 		if(edns.udp_size < NORMAL_UDP_SIZE &&
   1728 		   worker->daemon->cfg->harden_short_bufsize) {
   1729 			verbose(VERB_QUERY, "worker request: EDNS bufsize %d ignored",
   1730 				(int)edns.udp_size);
   1731 			log_addr(VERB_CLIENT, "from", &repinfo->client_addr,
   1732 				repinfo->client_addrlen);
   1733 			edns.udp_size = NORMAL_UDP_SIZE;
   1734 		}
   1735 	}
   1736 
   1737 	/* Get stats for cookies */
   1738 	server_stats_downstream_cookie(&worker->stats, &edns);
   1739 
   1740 	/* If the IP rate limiting check was postponed, check now. */
   1741 	if(!pre_edns_ip_ratelimit) {
   1742 		/* NOTE: we always check the repinfo->client_address.
   1743 		 *       IP ratelimiting is implicitly disabled for proxies. */
   1744 		if(!check_ip_ratelimit(worker, &repinfo->client_addr,
   1745 			repinfo->client_addrlen, edns.cookie_valid,
   1746 			c->buffer)) {
   1747 			worker->stats.num_queries_ip_ratelimited++;
   1748 			regional_free_all(worker->scratchpad);
   1749 			comm_point_drop_reply(repinfo);
   1750 			return 0;
   1751 		}
   1752 	}
   1753 
   1754 	/* "if, else if" sequence below deals with downstream DNS Cookies */
   1755 	if(acl != acl_allow_cookie)
   1756 		; /* pass; No cookie downstream processing whatsoever */
   1757 
   1758 	else if(edns.cookie_valid)
   1759 		; /* pass; Valid cookie is good! */
   1760 
   1761 	else if(c->type != comm_udp)
   1762 		; /* pass; Stateful transport */
   1763 
   1764 	else if(edns.cookie_present) {
   1765 		/* Cookie present, but not valid: Cookie was bad! */
   1766 		if(worker_err_ratelimit(worker, LDNS_EXT_RCODE_BADCOOKIE) == -1) {
   1767 			comm_point_drop_reply(repinfo);
   1768 			regional_free_all(worker->scratchpad);
   1769 			return 0;
   1770 		}
   1771 		extended_error_encode(c->buffer,
   1772 			LDNS_EXT_RCODE_BADCOOKIE, &qinfo,
   1773 			*(uint16_t*)(void *)
   1774 			sldns_buffer_begin(c->buffer),
   1775 			sldns_buffer_read_u16_at(c->buffer, 2),
   1776 			0, &edns);
   1777 		regional_free_all(worker->scratchpad);
   1778 		goto send_reply;
   1779 	} else {
   1780 		/* Cookie required, but no cookie present on UDP */
   1781 		verbose(VERB_ALGO, "worker request: "
   1782 			"need cookie or stateful transport");
   1783 		log_addr(VERB_ALGO, "from",&repinfo->remote_addr
   1784 		                          , repinfo->remote_addrlen);
   1785 		if(worker_err_ratelimit(worker, LDNS_RCODE_REFUSED) == -1) {
   1786 			comm_point_drop_reply(repinfo);
   1787 			regional_free_all(worker->scratchpad);
   1788 			return 0;
   1789 		}
   1790 		EDNS_OPT_LIST_APPEND_EDE(&edns.opt_list_out,
   1791 			worker->scratchpad, LDNS_EDE_OTHER,
   1792 			"DNS Cookie needed for UDP replies");
   1793 		error_encode(c->buffer,
   1794 			(LDNS_RCODE_REFUSED|BIT_TC), &qinfo,
   1795 			*(uint16_t*)(void *)
   1796 			sldns_buffer_begin(c->buffer),
   1797 			sldns_buffer_read_u16_at(c->buffer, 2),
   1798 			&edns);
   1799 		regional_free_all(worker->scratchpad);
   1800 		goto send_reply;
   1801 	}
   1802 
   1803 	if(edns.udp_size > worker->daemon->cfg->max_udp_size &&
   1804 		c->type == comm_udp) {
   1805 		verbose(VERB_QUERY,
   1806 			"worker request: max UDP reply size modified"
   1807 			" (%d to max-udp-size)", (int)edns.udp_size);
   1808 		log_addr(VERB_CLIENT, "from", &repinfo->client_addr,
   1809 			repinfo->client_addrlen);
   1810 		edns.udp_size = worker->daemon->cfg->max_udp_size;
   1811 	}
   1812 	if(edns.udp_size < LDNS_HEADER_SIZE) {
   1813 		verbose(VERB_ALGO, "worker request: edns is too small.");
   1814 		log_addr(VERB_CLIENT, "from", &repinfo->client_addr,
   1815 			repinfo->client_addrlen);
   1816 		if(worker_err_ratelimit(worker, LDNS_RCODE_SERVFAIL) == -1) {
   1817 			comm_point_drop_reply(repinfo);
   1818 			regional_free_all(worker->scratchpad);
   1819 			return 0;
   1820 		}
   1821 		/* A small error without qname, and TC flag on. */
   1822 		query_error(c->buffer, LDNS_RCODE_SERVFAIL, 0);
   1823 		LDNS_TC_SET(sldns_buffer_begin(c->buffer));
   1824 		regional_free_all(worker->scratchpad);
   1825 		goto send_reply;
   1826 	}
   1827 	if(worker->stats.extended)
   1828 		server_stats_insquery(&worker->stats, c, qinfo.qtype,
   1829 			qinfo.qclass, &edns, repinfo);
   1830 	if(c->type != comm_udp)
   1831 		edns.udp_size = 65535; /* max size for TCP replies */
   1832 	if(qinfo.qclass == LDNS_RR_CLASS_CH && answer_chaos(worker, &qinfo,
   1833 		&edns, repinfo, c->buffer)) {
   1834 		regional_free_all(worker->scratchpad);
   1835 		goto send_reply;
   1836 	}
   1837 	if(LDNS_OPCODE_WIRE(sldns_buffer_begin(c->buffer)) ==
   1838 		LDNS_PACKET_NOTIFY) {
   1839 		answer_notify(worker, &qinfo, &edns, c->buffer,
   1840 			&repinfo->client_addr, repinfo->client_addrlen);
   1841 		regional_free_all(worker->scratchpad);
   1842 		goto send_reply;
   1843 	}
   1844 	if(local_zones_answer(worker->daemon->local_zones, &worker->env, &qinfo,
   1845 		&edns, c->buffer, worker->scratchpad, repinfo, acladdr->taglist,
   1846 		acladdr->taglen, acladdr->tag_actions,
   1847 		acladdr->tag_actions_size, acladdr->tag_datas,
   1848 		acladdr->tag_datas_size, worker->daemon->cfg->tagname,
   1849 		worker->daemon->cfg->num_tags, acladdr->view)) {
   1850 		regional_free_all(worker->scratchpad);
   1851 		if(sldns_buffer_limit(c->buffer) == 0) {
   1852 			comm_point_drop_reply(repinfo);
   1853 			return 0;
   1854 		}
   1855 		goto send_reply;
   1856 	}
   1857 	if(worker->env.auth_zones &&
   1858 		rpz_callback_from_worker_request(worker->env.auth_zones,
   1859 		&worker->env, &qinfo, &edns, c->buffer, worker->scratchpad,
   1860 		repinfo, acladdr->taglist, acladdr->taglen, &worker->stats,
   1861 		&rpz_passthru)) {
   1862 		regional_free_all(worker->scratchpad);
   1863 		if(sldns_buffer_limit(c->buffer) == 0) {
   1864 			comm_point_drop_reply(repinfo);
   1865 			return 0;
   1866 		}
   1867 		goto send_reply;
   1868 	}
   1869 	if(worker->env.auth_zones &&
   1870 		auth_zones_downstream_answer(worker->env.auth_zones,
   1871 		&worker->env, &qinfo, &edns, repinfo, c->buffer,
   1872 		worker->scratchpad)) {
   1873 		regional_free_all(worker->scratchpad);
   1874 		if(sldns_buffer_limit(c->buffer) == 0) {
   1875 			comm_point_drop_reply(repinfo);
   1876 			return 0;
   1877 		}
   1878 		/* set RA for everyone that can have recursion (based on
   1879 		 * access control list) */
   1880 		if(LDNS_RD_WIRE(sldns_buffer_begin(c->buffer)) &&
   1881 		   acl != acl_deny_non_local && acl != acl_refuse_non_local)
   1882 			LDNS_RA_SET(sldns_buffer_begin(c->buffer));
   1883 		goto send_reply;
   1884 	}
   1885 
   1886 	/* We've looked in our local zones. If the answer isn't there, we
   1887 	 * might need to bail out based on ACLs now. */
   1888 	if((ret=deny_refuse_non_local(c, acl, worker, repinfo, acladdr,
   1889 		worker->env.cfg->ede, &check_result)) != -1)
   1890 	{
   1891 		regional_free_all(worker->scratchpad);
   1892 		if(ret == 1)
   1893 			goto send_reply;
   1894 		return ret;
   1895 	}
   1896 
   1897 	/* If this request does not have the recursion bit set, verify
   1898 	 * ACLs allow the recursion bit to be treated as set. */
   1899 	if(!(LDNS_RD_WIRE(sldns_buffer_begin(c->buffer))) &&
   1900 		acl == acl_allow_setrd ) {
   1901 		LDNS_RD_SET(sldns_buffer_begin(c->buffer));
   1902 	}
   1903 
   1904 	/* If this request does not have the recursion bit set, verify
   1905 	 * ACLs allow the snooping. */
   1906 	if(!(LDNS_RD_WIRE(sldns_buffer_begin(c->buffer))) &&
   1907 		acl != acl_allow_snoop ) {
   1908 		log_addr(VERB_ALGO, "refused nonrec (cache snoop) query from",
   1909 			&repinfo->client_addr, repinfo->client_addrlen);
   1910 		/* This ratelimited error query is accounted in the stats,
   1911 		 * as an incoming query. */
   1912 		if(worker_err_ratelimit(worker, LDNS_RCODE_REFUSED) == -1) {
   1913 			comm_point_drop_reply(repinfo);
   1914 			regional_free_all(worker->scratchpad);
   1915 			return 0;
   1916 		}
   1917 		if(worker->env.cfg->ede) {
   1918 			EDNS_OPT_LIST_APPEND_EDE(&edns.opt_list_out,
   1919 				worker->scratchpad, LDNS_EDE_NOT_AUTHORITATIVE, "");
   1920 		}
   1921 		error_encode(c->buffer, LDNS_RCODE_REFUSED, &qinfo,
   1922 			*(uint16_t*)(void *)sldns_buffer_begin(c->buffer),
   1923 			sldns_buffer_read_u16_at(c->buffer, 2), &edns);
   1924 		regional_free_all(worker->scratchpad);
   1925 		goto send_reply;
   1926 	}
   1927 
   1928 	/* If we've found a local alias, replace the qname with the alias
   1929 	 * target before resolving it. */
   1930 	if(qinfo.local_alias) {
   1931 		if(!local_alias_shallow_copy_qname(qinfo.local_alias, &qinfo.qname,
   1932 			&qinfo.qname_len)) {
   1933 			regional_free_all(worker->scratchpad);
   1934 			return 0; /* drop it */
   1935 		}
   1936 	}
   1937 
   1938 	/* If we may apply IP-based actions to the answer, build the client
   1939 	 * information.  As this can be expensive, skip it if there is
   1940 	 * absolutely no possibility of it. */
   1941 	if((worker->daemon->use_response_ip || worker->daemon->use_rpz) &&
   1942 		(qinfo.qtype == LDNS_RR_TYPE_A ||
   1943 		qinfo.qtype == LDNS_RR_TYPE_AAAA ||
   1944 		qinfo.qtype == LDNS_RR_TYPE_ANY)) {
   1945 		cinfo_tmp.taglist = acladdr->taglist;
   1946 		cinfo_tmp.taglen = acladdr->taglen;
   1947 		cinfo_tmp.tag_actions = acladdr->tag_actions;
   1948 		cinfo_tmp.tag_actions_size = acladdr->tag_actions_size;
   1949 		cinfo_tmp.tag_datas = acladdr->tag_datas;
   1950 		cinfo_tmp.tag_datas_size = acladdr->tag_datas_size;
   1951 		cinfo_tmp.view = acladdr->view;
   1952 		cinfo_tmp.view_name = NULL;
   1953 		cinfo = &cinfo_tmp;
   1954 	}
   1955 
   1956 	/* Keep the original edns list around. The pointer could change if there is
   1957 	 * a cached answer (through the inplace callback function there).
   1958 	 * No need to actually copy the contents as they shouldn't change.
   1959 	 * Used while prefetching and subnet is enabled. */
   1960 	original_edns_list = edns.opt_list_in;
   1961 lookup_cache:
   1962 	/* Lookup the cache.  In case we chase an intermediate CNAME chain
   1963 	 * this is a two-pass operation, and lookup_qinfo is different for
   1964 	 * each pass.  We should still pass the original qinfo to
   1965 	 * answer_from_cache(), however, since it's used to build the reply. */
   1966 	if(!edns_bypass_cache_stage(edns.opt_list_in, &worker->env)) {
   1967 		is_expired_answer = 0;
   1968 		is_secure_answer = 0;
   1969 		h = query_info_hash(lookup_qinfo, sldns_buffer_read_u16_at(c->buffer, 2));
   1970 		if((e=slabhash_lookup(worker->env.msg_cache, h, lookup_qinfo, 0))) {
   1971 			struct reply_info* rep = (struct reply_info*)e->data;
   1972 			/* answer from cache - we have acquired a readlock on it */
   1973 			if(answer_from_cache(worker, &qinfo, cinfo, &need_drop,
   1974 				&is_expired_answer, &is_secure_answer,
   1975 				&alias_rrset, &partial_rep, rep,
   1976 				*(uint16_t*)(void *)sldns_buffer_begin(c->buffer),
   1977 				sldns_buffer_read_u16_at(c->buffer, 2), repinfo,
   1978 				&edns)) {
   1979 				/* prefetch it if the prefetch TTL expired.
   1980 				 * Note that if there is more than one pass
   1981 				 * its qname must be that used for cache
   1982 				 * lookup. */
   1983 				if((worker->env.cfg->prefetch &&
   1984 					rep->prefetch_ttl <= *worker->env.now) ||
   1985 					(worker->env.cfg->serve_expired &&
   1986 					TTL_IS_EXPIRED(rep->ttl, *worker->env.now) &&
   1987 					!(*worker->env.now < rep->serve_expired_norec_ttl))) {
   1988 					time_t leeway =
   1989 						TTL_IS_EXPIRED(rep->ttl, *worker->env.now)
   1990 						? 0 : rep->ttl - *worker->env.now;
   1991 					lock_rw_unlock(&e->lock);
   1992 
   1993 					reply_and_prefetch(worker, lookup_qinfo,
   1994 						sldns_buffer_read_u16_at(c->buffer, 2),
   1995 						repinfo, leeway,
   1996 						(partial_rep || need_drop),
   1997 						rpz_passthru,
   1998 						original_edns_list);
   1999 					if(!partial_rep) {
   2000 						rc = 0;
   2001 						regional_free_all(worker->scratchpad);
   2002 						goto send_reply_rc;
   2003 					}
   2004 				} else if(!partial_rep) {
   2005 					lock_rw_unlock(&e->lock);
   2006 					regional_free_all(worker->scratchpad);
   2007 					goto send_reply;
   2008 				} else {
   2009 					/* Note that we've already released the
   2010 					 * lock if we're here after prefetch. */
   2011 					lock_rw_unlock(&e->lock);
   2012 				}
   2013 				/* We've found a partial reply ending with an
   2014 				 * alias.  Replace the lookup qinfo for the
   2015 				 * alias target and lookup the cache again to
   2016 				 * (possibly) complete the reply.  As we're
   2017 				 * passing the "base" reply, there will be no
   2018 				 * more alias chasing. */
   2019 				memset(&qinfo_tmp, 0, sizeof(qinfo_tmp));
   2020 				get_cname_target(alias_rrset, &qinfo_tmp.qname,
   2021 					&qinfo_tmp.qname_len);
   2022 				if(!qinfo_tmp.qname) {
   2023 					log_err("unexpected: invalid answer alias");
   2024 					regional_free_all(worker->scratchpad);
   2025 					return 0; /* drop query */
   2026 				}
   2027 				qinfo_tmp.qtype = qinfo.qtype;
   2028 				qinfo_tmp.qclass = qinfo.qclass;
   2029 				lookup_qinfo = &qinfo_tmp;
   2030 				goto lookup_cache;
   2031 			}
   2032 			verbose(VERB_ALGO, "answer from the cache failed");
   2033 			lock_rw_unlock(&e->lock);
   2034 		}
   2035 
   2036 		if(!LDNS_RD_WIRE(sldns_buffer_begin(c->buffer))) {
   2037 			if(answer_norec_from_cache(worker, &qinfo,
   2038 				*(uint16_t*)(void *)sldns_buffer_begin(c->buffer),
   2039 				sldns_buffer_read_u16_at(c->buffer, 2), repinfo,
   2040 				&edns)) {
   2041 				regional_free_all(worker->scratchpad);
   2042 				goto send_reply;
   2043 			}
   2044 			verbose(VERB_ALGO, "answer norec from cache -- "
   2045 				"need to validate or not primed");
   2046 		}
   2047 	}
   2048 	sldns_buffer_rewind(c->buffer);
   2049 	server_stats_querymiss(&worker->stats, worker);
   2050 
   2051 	if(verbosity >= VERB_CLIENT) {
   2052 		if(c->type == comm_udp)
   2053 			log_addr(VERB_CLIENT, "udp request from",
   2054 				&repinfo->client_addr, repinfo->client_addrlen);
   2055 		else	log_addr(VERB_CLIENT, "tcp request from",
   2056 				&repinfo->client_addr, repinfo->client_addrlen);
   2057 	}
   2058 
   2059 	/* grab a work request structure for this new request */
   2060 	mesh_new_client(worker->env.mesh, &qinfo, cinfo,
   2061 		sldns_buffer_read_u16_at(c->buffer, 2),
   2062 		&edns, repinfo, *(uint16_t*)(void *)sldns_buffer_begin(c->buffer),
   2063 		rpz_passthru);
   2064 	regional_free_all(worker->scratchpad);
   2065 	worker_mem_report(worker, NULL);
   2066 	return 0;
   2067 
   2068 send_reply:
   2069 	rc = 1;
   2070 send_reply_rc:
   2071 	if(need_drop) {
   2072 		comm_point_drop_reply(repinfo);
   2073 		return 0;
   2074 	}
   2075 	if(is_expired_answer) {
   2076 		worker->stats.ans_expired++;
   2077 	}
   2078 	server_stats_insrcode(&worker->stats, c->buffer);
   2079 	if(worker->stats.extended) {
   2080 		if(is_secure_answer) worker->stats.ans_secure++;
   2081 	}
   2082 #ifdef USE_DNSTAP
   2083 	/*
   2084 	 * sending src (client)/dst (local service) addresses over DNSTAP from send_reply code label (when we serviced local zone for ex.)
   2085 	 */
   2086 	if(worker->dtenv.log_client_response_messages && rc !=0) {
   2087 		log_addr(VERB_ALGO, "from local addr", (void*)repinfo->c->socket->addr, repinfo->c->socket->addrlen);
   2088 		log_addr(VERB_ALGO, "response to client", &repinfo->client_addr, repinfo->client_addrlen);
   2089 		dt_msg_send_client_response(&worker->dtenv, &repinfo->client_addr, (void*)repinfo->c->socket->addr, c->type, c->ssl, c->buffer);
   2090 	}
   2091 #endif
   2092 	if(worker->env.cfg->log_replies)
   2093 	{
   2094 		struct timeval tv;
   2095 		memset(&tv, 0, sizeof(tv));
   2096 		if(qinfo.local_alias && qinfo.local_alias->rrset &&
   2097 			qinfo.local_alias->rrset->rk.dname) {
   2098 			/* log original qname, before the local alias was
   2099 			 * used to resolve that CNAME to something else */
   2100 			qinfo.qname = qinfo.local_alias->rrset->rk.dname;
   2101 			log_reply_info(NO_VERBOSE, &qinfo,
   2102 				&repinfo->client_addr, repinfo->client_addrlen,
   2103 				tv, 1, c->buffer,
   2104 				(worker->env.cfg->log_destaddr?(void*)repinfo->c->socket->addr:NULL),
   2105 				c->type, c->ssl);
   2106 		} else {
   2107 			log_reply_info(NO_VERBOSE, &qinfo,
   2108 				&repinfo->client_addr, repinfo->client_addrlen,
   2109 				tv, 1, c->buffer,
   2110 				(worker->env.cfg->log_destaddr?(void*)repinfo->c->socket->addr:NULL),
   2111 				c->type, c->ssl);
   2112 		}
   2113 	}
   2114 #ifdef USE_DNSCRYPT
   2115 	if(!dnsc_handle_uncurved_request(repinfo)) {
   2116 		return 0;
   2117 	}
   2118 #endif
   2119 	return rc;
   2120 }
   2121 
   2122 void
   2123 worker_sighandler(int sig, void* arg)
   2124 {
   2125 	/* note that log, print, syscalls here give race conditions.
   2126 	 * And cause hangups if the log-lock is held by the application. */
   2127 	struct worker* worker = (struct worker*)arg;
   2128 	switch(sig) {
   2129 #ifdef SIGHUP
   2130 		case SIGHUP:
   2131 			comm_base_exit(worker->base);
   2132 			break;
   2133 #endif
   2134 #ifdef SIGBREAK
   2135 		case SIGBREAK:
   2136 #endif
   2137 		case SIGINT:
   2138 			worker->need_to_exit = 1;
   2139 			comm_base_exit(worker->base);
   2140 			break;
   2141 #ifdef SIGQUIT
   2142 		case SIGQUIT:
   2143 			worker->need_to_exit = 1;
   2144 			comm_base_exit(worker->base);
   2145 			break;
   2146 #endif
   2147 		case SIGTERM:
   2148 			worker->need_to_exit = 1;
   2149 			comm_base_exit(worker->base);
   2150 			break;
   2151 		default:
   2152 			/* unknown signal, ignored */
   2153 			break;
   2154 	}
   2155 }
   2156 
   2157 /** restart statistics timer for worker, if enabled */
   2158 static void
   2159 worker_restart_timer(struct worker* worker)
   2160 {
   2161 	if(worker->env.cfg->stat_interval > 0) {
   2162 		struct timeval tv;
   2163 		if(worker->daemon->stat_time_specific) {
   2164 			struct timeval dest, now;
   2165 			int interval = worker->env.cfg->stat_interval;
   2166 			int offset = worker->daemon->stat_time_offset;
   2167 			int nows, spec;
   2168 			if(gettimeofday(&now, NULL) < 0)
   2169 				log_err("gettimeofday: %s", strerror(errno));
   2170 #ifndef S_SPLINT_S
   2171 			nows = (int)now.tv_sec;
   2172 			/* The next time is on the timer interval, at the
   2173 			 * specific offset, time value % interval = offset. */
   2174 			/* It relies on the integer division below to drop the
   2175 			 * remainder in order to calculate the expected
   2176 			 * result. */
   2177 			spec = ((nows-offset)/interval+1)*interval+offset;
   2178 			/* This is instead of an assertion, and should not
   2179 			 * be needed. So assert(spec > nows), tv is going to
   2180 			 * be positive. */
   2181 			if(spec<=nows) spec += interval;
   2182 			dest.tv_sec = spec;
   2183 			dest.tv_usec = 0;
   2184 #endif
   2185 			/* Subtract in timeval, so the fractions of a second
   2186 			 * are rounded to the whole specific time. */
   2187 			timeval_subtract(&tv, &dest, &now);
   2188 		} else {
   2189 #ifndef S_SPLINT_S
   2190 			tv.tv_sec = worker->env.cfg->stat_interval;
   2191 			tv.tv_usec = 0;
   2192 #endif
   2193 		}
   2194 		comm_timer_set(worker->stat_timer, &tv);
   2195 	}
   2196 }
   2197 
   2198 void worker_stat_timer_cb(void* arg)
   2199 {
   2200 	struct worker* worker = (struct worker*)arg;
   2201 	server_stats_log(&worker->stats, worker, worker->thread_num);
   2202 	mesh_stats(worker->env.mesh, "mesh has");
   2203 	worker_mem_report(worker, NULL);
   2204 	/* SHM is enabled, process data to SHM */
   2205 	if (worker->daemon->cfg->shm_enable) {
   2206 		shm_main_run(worker);
   2207 	}
   2208 	if(!worker->daemon->cfg->stat_cumulative) {
   2209 		worker_stats_clear(worker);
   2210 	}
   2211 	/* start next timer */
   2212 	worker_restart_timer(worker);
   2213 }
   2214 
   2215 void worker_probe_timer_cb(void* arg)
   2216 {
   2217 	struct worker* worker = (struct worker*)arg;
   2218 	struct timeval tv;
   2219 #ifndef S_SPLINT_S
   2220 	tv.tv_sec = (time_t)autr_probe_timer(&worker->env);
   2221 	tv.tv_usec = 0;
   2222 #endif
   2223 	if(tv.tv_sec != 0)
   2224 		comm_timer_set(worker->env.probe_timer, &tv);
   2225 }
   2226 
   2227 struct worker*
   2228 worker_create(struct daemon* daemon, int id, int* ports, int n)
   2229 {
   2230 	unsigned int seed;
   2231 	struct worker* worker = (struct worker*)calloc(1,
   2232 		sizeof(struct worker));
   2233 	if(!worker)
   2234 		return NULL;
   2235 	worker->numports = n;
   2236 	worker->ports = (int*)memdup(ports, sizeof(int)*n);
   2237 	if(!worker->ports) {
   2238 		free(worker);
   2239 		return NULL;
   2240 	}
   2241 	worker->daemon = daemon;
   2242 	worker->thread_num = id;
   2243 	if(!(worker->cmd = tube_create())) {
   2244 		free(worker->ports);
   2245 		free(worker);
   2246 		return NULL;
   2247 	}
   2248 	/* create random state here to avoid locking trouble in RAND_bytes */
   2249 	if(!(worker->rndstate = ub_initstate(daemon->rand))) {
   2250 		log_err("could not init random numbers.");
   2251 		tube_delete(worker->cmd);
   2252 		free(worker->ports);
   2253 		free(worker);
   2254 		return NULL;
   2255 	}
   2256 	explicit_bzero(&seed, sizeof(seed));
   2257 	return worker;
   2258 }
   2259 
   2260 int
   2261 worker_init(struct worker* worker, struct config_file *cfg,
   2262 	struct listen_port* ports, int do_sigs)
   2263 {
   2264 #ifdef USE_DNSTAP
   2265 	struct dt_env* dtenv = &worker->dtenv;
   2266 #else
   2267 	void* dtenv = NULL;
   2268 #endif
   2269 	worker->need_to_exit = 0;
   2270 	worker->base = comm_base_create(do_sigs);
   2271 	if(!worker->base) {
   2272 		log_err("could not create event handling base");
   2273 		worker_delete(worker);
   2274 		return 0;
   2275 	}
   2276 	comm_base_set_slow_accept_handlers(worker->base, &worker_stop_accept,
   2277 		&worker_start_accept, worker);
   2278 	if(do_sigs) {
   2279 #ifdef SIGHUP
   2280 		ub_thread_sig_unblock(SIGHUP);
   2281 #endif
   2282 #ifdef SIGBREAK
   2283 		ub_thread_sig_unblock(SIGBREAK);
   2284 #endif
   2285 		ub_thread_sig_unblock(SIGINT);
   2286 #ifdef SIGQUIT
   2287 		ub_thread_sig_unblock(SIGQUIT);
   2288 #endif
   2289 		ub_thread_sig_unblock(SIGTERM);
   2290 #ifndef LIBEVENT_SIGNAL_PROBLEM
   2291 		worker->comsig = comm_signal_create(worker->base,
   2292 			worker_sighandler, worker);
   2293 		if(!worker->comsig
   2294 #ifdef SIGHUP
   2295 			|| !comm_signal_bind(worker->comsig, SIGHUP)
   2296 #endif
   2297 #ifdef SIGQUIT
   2298 			|| !comm_signal_bind(worker->comsig, SIGQUIT)
   2299 #endif
   2300 			|| !comm_signal_bind(worker->comsig, SIGTERM)
   2301 #ifdef SIGBREAK
   2302 			|| !comm_signal_bind(worker->comsig, SIGBREAK)
   2303 #endif
   2304 			|| !comm_signal_bind(worker->comsig, SIGINT)) {
   2305 			log_err("could not create signal handlers");
   2306 			worker_delete(worker);
   2307 			return 0;
   2308 		}
   2309 #endif /* LIBEVENT_SIGNAL_PROBLEM */
   2310 		if(!daemon_remote_open_accept(worker->daemon->rc,
   2311 			worker->daemon->rc_ports, worker)) {
   2312 			worker_delete(worker);
   2313 			return 0;
   2314 		}
   2315 #ifdef UB_ON_WINDOWS
   2316 		wsvc_setup_worker(worker);
   2317 #endif /* UB_ON_WINDOWS */
   2318 	} else { /* !do_sigs */
   2319 		worker->comsig = NULL;
   2320 	}
   2321 #ifdef USE_DNSTAP
   2322 	if(cfg->dnstap) {
   2323 		log_assert(worker->daemon->dtenv != NULL);
   2324 		memcpy(&worker->dtenv, worker->daemon->dtenv, sizeof(struct dt_env));
   2325 		if(!dt_init(&worker->dtenv, worker->base))
   2326 			fatal_exit("dt_init failed");
   2327 	}
   2328 #endif
   2329 	worker->front = listen_create(worker->base, ports,
   2330 		cfg->msg_buffer_size, (int)cfg->incoming_num_tcp,
   2331 		cfg->do_tcp_keepalive
   2332 			? cfg->tcp_keepalive_timeout
   2333 			: cfg->tcp_idle_timeout,
   2334 		cfg->harden_large_queries, cfg->http_max_streams,
   2335 		cfg->http_endpoint, cfg->http_notls_downstream,
   2336 		worker->daemon->tcl, worker->daemon->listen_dot_sslctx,
   2337 		worker->daemon->listen_doh_sslctx,
   2338 		worker->daemon->listen_quic_sslctx,
   2339 		dtenv, worker->daemon->doq_table, worker->env.rnd,
   2340 		cfg, worker_handle_request, worker);
   2341 	if(!worker->front) {
   2342 		log_err("could not create listening sockets");
   2343 		worker_delete(worker);
   2344 		return 0;
   2345 	}
   2346 	worker->back = outside_network_create(worker->base,
   2347 		cfg->msg_buffer_size, (size_t)cfg->outgoing_num_ports,
   2348 		cfg->out_ifs, cfg->num_out_ifs, cfg->do_ip4, cfg->do_ip6,
   2349 		cfg->do_tcp?cfg->outgoing_num_tcp:0, cfg->ip_dscp,
   2350 		worker->daemon->env->infra_cache, worker->rndstate,
   2351 		cfg->use_caps_bits_for_id, worker->ports, worker->numports,
   2352 		cfg->unwanted_threshold, cfg->outgoing_tcp_mss,
   2353 		&worker_alloc_cleanup, worker,
   2354 		cfg->do_udp || cfg->udp_upstream_without_downstream,
   2355 		worker->daemon->connect_dot_sslctx, cfg->delay_close,
   2356 		cfg->tls_use_sni, dtenv, cfg->udp_connect,
   2357 		cfg->max_reuse_tcp_queries, cfg->tcp_reuse_timeout,
   2358 		cfg->tcp_auth_query_timeout);
   2359 	if(!worker->back) {
   2360 		log_err("could not create outgoing sockets");
   2361 		worker_delete(worker);
   2362 		return 0;
   2363 	}
   2364 	iterator_set_ip46_support(&worker->daemon->mods, worker->daemon->env,
   2365 		worker->back);
   2366 	/* start listening to commands */
   2367 	if(!tube_setup_bg_listen(worker->cmd, worker->base,
   2368 		&worker_handle_control_cmd, worker)) {
   2369 		log_err("could not create control compt.");
   2370 		worker_delete(worker);
   2371 		return 0;
   2372 	}
   2373 	worker->stat_timer = comm_timer_create(worker->base,
   2374 		worker_stat_timer_cb, worker);
   2375 	if(!worker->stat_timer) {
   2376 		log_err("could not create statistics timer");
   2377 	}
   2378 
   2379 	/* we use the msg_buffer_size as a good estimate for what the
   2380 	 * user wants for memory usage sizes */
   2381 	worker->scratchpad = regional_create_custom(cfg->msg_buffer_size);
   2382 	if(!worker->scratchpad) {
   2383 		log_err("malloc failure");
   2384 		worker_delete(worker);
   2385 		return 0;
   2386 	}
   2387 
   2388 	server_stats_init(&worker->stats, cfg);
   2389 	worker->alloc = worker->daemon->worker_allocs[worker->thread_num];
   2390 	alloc_set_id_cleanup(worker->alloc, &worker_alloc_cleanup, worker);
   2391 	worker->env = *worker->daemon->env;
   2392 	comm_base_timept(worker->base, &worker->env.now, &worker->env.now_tv);
   2393 	worker->env.worker = worker;
   2394 	worker->env.worker_base = worker->base;
   2395 	worker->env.send_query = &worker_send_query;
   2396 	worker->env.alloc = worker->alloc;
   2397 	worker->env.outnet = worker->back;
   2398 	worker->env.rnd = worker->rndstate;
   2399 	/* If case prefetch is triggered, the corresponding mesh will clear
   2400 	 * the scratchpad for the module env in the middle of request handling.
   2401 	 * It would be prone to a use-after-free kind of bug, so we avoid
   2402 	 * sharing it with worker's own scratchpad at the cost of having
   2403 	 * one more pad per worker. */
   2404 	worker->env.scratch = regional_create_custom(cfg->msg_buffer_size);
   2405 	if(!worker->env.scratch) {
   2406 		log_err("malloc failure");
   2407 		worker_delete(worker);
   2408 		return 0;
   2409 	}
   2410 	worker->env.mesh = mesh_create(&worker->daemon->mods, &worker->env);
   2411 	if(!worker->env.mesh) {
   2412 		log_err("malloc failure");
   2413 		worker_delete(worker);
   2414 		return 0;
   2415 	}
   2416 	/* Pass on daemon variables that we would need in the mesh area */
   2417 	worker->env.mesh->use_response_ip = worker->daemon->use_response_ip;
   2418 	worker->env.mesh->use_rpz = worker->daemon->use_rpz;
   2419 
   2420 	worker->env.detach_subs = &mesh_detach_subs;
   2421 	worker->env.attach_sub = &mesh_attach_sub;
   2422 	worker->env.add_sub = &mesh_add_sub;
   2423 	worker->env.kill_sub = &mesh_state_delete;
   2424 	worker->env.detect_cycle = &mesh_detect_cycle;
   2425 	worker->env.scratch_buffer = sldns_buffer_new(cfg->msg_buffer_size);
   2426 	if(!worker->env.scratch_buffer) {
   2427 		log_err("malloc failure");
   2428 		worker_delete(worker);
   2429 		return 0;
   2430 	}
   2431 	/* one probe timer per process -- if we have 5011 anchors */
   2432 	if(autr_get_num_anchors(worker->env.anchors) > 0
   2433 #ifndef THREADS_DISABLED
   2434 		&& worker->thread_num == 0
   2435 #endif
   2436 		) {
   2437 		struct timeval tv;
   2438 		tv.tv_sec = 0;
   2439 		tv.tv_usec = 0;
   2440 		worker->env.probe_timer = comm_timer_create(worker->base,
   2441 			worker_probe_timer_cb, worker);
   2442 		if(!worker->env.probe_timer) {
   2443 			log_err("could not create 5011-probe timer");
   2444 		} else {
   2445 			/* let timer fire, then it can reset itself */
   2446 			comm_timer_set(worker->env.probe_timer, &tv);
   2447 		}
   2448 	}
   2449 	/* zone transfer tasks, setup once per process, if any */
   2450 	if(worker->env.auth_zones
   2451 #ifndef THREADS_DISABLED
   2452 		&& worker->thread_num == 0
   2453 #endif
   2454 		) {
   2455 		auth_xfer_pickup_initial(worker->env.auth_zones, &worker->env);
   2456 		auth_zones_pickup_zonemd_verify(worker->env.auth_zones,
   2457 			&worker->env);
   2458 	}
   2459 #ifdef USE_DNSTAP
   2460 	if(worker->daemon->cfg->dnstap
   2461 #ifndef THREADS_DISABLED
   2462 		&& worker->thread_num == 0
   2463 #endif
   2464 		) {
   2465 		if(!dt_io_thread_start(dtenv->dtio, comm_base_internal(
   2466 			worker->base), worker->daemon->num)) {
   2467 			log_err("could not start dnstap io thread");
   2468 			worker_delete(worker);
   2469 			return 0;
   2470 		}
   2471 	}
   2472 #endif /* USE_DNSTAP */
   2473 	worker_mem_report(worker, NULL);
   2474 	/* if statistics enabled start timer */
   2475 	if(worker->env.cfg->stat_interval > 0) {
   2476 		verbose(VERB_ALGO, "set statistics interval %d secs",
   2477 			worker->env.cfg->stat_interval);
   2478 		worker_restart_timer(worker);
   2479 	}
   2480 	pp_init(&sldns_write_uint16, &sldns_write_uint32);
   2481 	return 1;
   2482 }
   2483 
   2484 void
   2485 worker_work(struct worker* worker)
   2486 {
   2487 	comm_base_dispatch(worker->base);
   2488 }
   2489 
   2490 void
   2491 worker_delete(struct worker* worker)
   2492 {
   2493 	if(!worker)
   2494 		return;
   2495 	if(worker->env.mesh && verbosity >= VERB_OPS) {
   2496 		server_stats_log(&worker->stats, worker, worker->thread_num);
   2497 		mesh_stats(worker->env.mesh, "mesh has");
   2498 		worker_mem_report(worker, NULL);
   2499 	}
   2500 	outside_network_quit_prepare(worker->back);
   2501 	mesh_delete(worker->env.mesh);
   2502 	sldns_buffer_free(worker->env.scratch_buffer);
   2503 	listen_delete(worker->front);
   2504 	outside_network_delete(worker->back);
   2505 	comm_signal_delete(worker->comsig);
   2506 	tube_delete(worker->cmd);
   2507 	comm_timer_delete(worker->stat_timer);
   2508 	comm_timer_delete(worker->env.probe_timer);
   2509 	free(worker->ports);
   2510 	if(worker->thread_num == 0) {
   2511 #ifdef UB_ON_WINDOWS
   2512 		wsvc_desetup_worker(worker);
   2513 #endif /* UB_ON_WINDOWS */
   2514 	}
   2515 #ifdef USE_DNSTAP
   2516 	if(worker->daemon->cfg->dnstap
   2517 #ifndef THREADS_DISABLED
   2518 		&& worker->thread_num == 0
   2519 #endif
   2520 		) {
   2521 		dt_io_thread_stop(worker->dtenv.dtio);
   2522 	}
   2523 	dt_deinit(&worker->dtenv);
   2524 #endif /* USE_DNSTAP */
   2525 	comm_base_delete(worker->base);
   2526 	ub_randfree(worker->rndstate);
   2527 	/* don't touch worker->alloc, as it's maintained in daemon */
   2528 	regional_destroy(worker->env.scratch);
   2529 	regional_destroy(worker->scratchpad);
   2530 	free(worker);
   2531 }
   2532 
   2533 struct outbound_entry*
   2534 worker_send_query(struct query_info* qinfo, uint16_t flags, int dnssec,
   2535 	int want_dnssec, int nocaps, int check_ratelimit,
   2536 	struct sockaddr_storage* addr, socklen_t addrlen, uint8_t* zone,
   2537 	size_t zonelen, int tcp_upstream, int ssl_upstream, char* tls_auth_name,
   2538 	struct module_qstate* q, int* was_ratelimited)
   2539 {
   2540 	struct worker* worker = q->env->worker;
   2541 	struct outbound_entry* e = (struct outbound_entry*)regional_alloc(
   2542 		q->region, sizeof(*e));
   2543 	if(!e)
   2544 		return NULL;
   2545 	e->qstate = q;
   2546 	e->qsent = outnet_serviced_query(worker->back, qinfo, flags, dnssec,
   2547 		want_dnssec, nocaps, check_ratelimit, tcp_upstream,
   2548 		ssl_upstream, tls_auth_name, addr, addrlen, zone, zonelen, q,
   2549 		worker_handle_service_reply, e, worker->back->udp_buff, q->env,
   2550 		was_ratelimited);
   2551 	if(!e->qsent) {
   2552 		return NULL;
   2553 	}
   2554 	return e;
   2555 }
   2556 
   2557 void
   2558 worker_alloc_cleanup(void* arg)
   2559 {
   2560 	struct worker* worker = (struct worker*)arg;
   2561 	slabhash_clear(&worker->env.rrset_cache->table);
   2562 	slabhash_clear(worker->env.msg_cache);
   2563 }
   2564 
   2565 void worker_stats_clear(struct worker* worker)
   2566 {
   2567 	server_stats_init(&worker->stats, worker->env.cfg);
   2568 	mesh_stats_clear(worker->env.mesh);
   2569 	worker->back->unwanted_replies = 0;
   2570 	worker->back->num_tcp_outgoing = 0;
   2571 	worker->back->num_udp_outgoing = 0;
   2572 }
   2573 
   2574 void worker_start_accept(void* arg)
   2575 {
   2576 	struct worker* worker = (struct worker*)arg;
   2577 	listen_start_accept(worker->front);
   2578 	if(worker->thread_num == 0)
   2579 		daemon_remote_start_accept(worker->daemon->rc);
   2580 }
   2581 
   2582 void worker_stop_accept(void* arg)
   2583 {
   2584 	struct worker* worker = (struct worker*)arg;
   2585 	listen_stop_accept(worker->front);
   2586 	if(worker->thread_num == 0)
   2587 		daemon_remote_stop_accept(worker->daemon->rc);
   2588 }
   2589 
   2590 /* --- fake callbacks for fptr_wlist to work --- */
   2591 struct outbound_entry* libworker_send_query(
   2592 	struct query_info* ATTR_UNUSED(qinfo),
   2593 	uint16_t ATTR_UNUSED(flags), int ATTR_UNUSED(dnssec),
   2594 	int ATTR_UNUSED(want_dnssec), int ATTR_UNUSED(nocaps),
   2595 	int ATTR_UNUSED(check_ratelimit),
   2596 	struct sockaddr_storage* ATTR_UNUSED(addr), socklen_t ATTR_UNUSED(addrlen),
   2597 	uint8_t* ATTR_UNUSED(zone), size_t ATTR_UNUSED(zonelen), int ATTR_UNUSED(tcp_upstream),
   2598 	int ATTR_UNUSED(ssl_upstream), char* ATTR_UNUSED(tls_auth_name),
   2599 	struct module_qstate* ATTR_UNUSED(q), int* ATTR_UNUSED(was_ratelimited))
   2600 {
   2601 	log_assert(0);
   2602 	return 0;
   2603 }
   2604 
   2605 int libworker_handle_service_reply(struct comm_point* ATTR_UNUSED(c),
   2606 	void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
   2607         struct comm_reply* ATTR_UNUSED(reply_info))
   2608 {
   2609 	log_assert(0);
   2610 	return 0;
   2611 }
   2612 
   2613 void libworker_handle_control_cmd(struct tube* ATTR_UNUSED(tube),
   2614         uint8_t* ATTR_UNUSED(buffer), size_t ATTR_UNUSED(len),
   2615         int ATTR_UNUSED(error), void* ATTR_UNUSED(arg))
   2616 {
   2617 	log_assert(0);
   2618 }
   2619 
   2620 void libworker_fg_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
   2621 	sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
   2622 	char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
   2623 {
   2624 	log_assert(0);
   2625 }
   2626 
   2627 void libworker_bg_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
   2628 	sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
   2629 	char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
   2630 {
   2631 	log_assert(0);
   2632 }
   2633 
   2634 void libworker_event_done_cb(void* ATTR_UNUSED(arg), int ATTR_UNUSED(rcode),
   2635 	sldns_buffer* ATTR_UNUSED(buf), enum sec_status ATTR_UNUSED(s),
   2636 	char* ATTR_UNUSED(why_bogus), int ATTR_UNUSED(was_ratelimited))
   2637 {
   2638 	log_assert(0);
   2639 }
   2640 
   2641 int context_query_cmp(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
   2642 {
   2643 	log_assert(0);
   2644 	return 0;
   2645 }
   2646 
   2647 int order_lock_cmp(const void* ATTR_UNUSED(e1), const void* ATTR_UNUSED(e2))
   2648 {
   2649 	log_assert(0);
   2650 	return 0;
   2651 }
   2652 
   2653 int codeline_cmp(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
   2654 {
   2655 	log_assert(0);
   2656 	return 0;
   2657 }
   2658 
   2659 #ifdef USE_DNSTAP
   2660 void dtio_tap_callback(int ATTR_UNUSED(fd), short ATTR_UNUSED(ev),
   2661 	void* ATTR_UNUSED(arg))
   2662 {
   2663 	log_assert(0);
   2664 }
   2665 #endif
   2666 
   2667 #ifdef USE_DNSTAP
   2668 void dtio_mainfdcallback(int ATTR_UNUSED(fd), short ATTR_UNUSED(ev),
   2669 	void* ATTR_UNUSED(arg))
   2670 {
   2671 	log_assert(0);
   2672 }
   2673 #endif
   2674 
   2675 #ifdef HAVE_NGTCP2
   2676 void doq_client_event_cb(int ATTR_UNUSED(fd), short ATTR_UNUSED(ev),
   2677 	void* ATTR_UNUSED(arg))
   2678 {
   2679 	log_assert(0);
   2680 }
   2681 #endif
   2682 
   2683 #ifdef HAVE_NGTCP2
   2684 void doq_client_timer_cb(int ATTR_UNUSED(fd), short ATTR_UNUSED(ev),
   2685 	void* ATTR_UNUSED(arg))
   2686 {
   2687 	log_assert(0);
   2688 }
   2689 #endif
   2690