xref: /freebsd/contrib/unbound/libunbound/libworker.c (revision 1349891a0eed79625faafa5ad354d65ff9ea6012)
1 /*
2  * libunbound/worker.c - worker thread or process that resolves
3  *
4  * Copyright (c) 2007, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 /**
37  * \file
38  *
39  * This file contains the worker process or thread that performs
40  * the DNS resolving and validation. The worker is called by a procedure
41  * and if in the background continues until exit, if in the foreground
42  * returns from the procedure when done.
43  */
44 #include "config.h"
45 #ifdef HAVE_SSL
46 #include <openssl/ssl.h>
47 #endif
48 #include "libunbound/libworker.h"
49 #include "libunbound/context.h"
50 #include "libunbound/unbound.h"
51 #include "libunbound/worker.h"
52 #include "libunbound/unbound-event.h"
53 #include "services/outside_network.h"
54 #include "services/mesh.h"
55 #include "services/localzone.h"
56 #include "services/cache/rrset.h"
57 #include "services/outbound_list.h"
58 #include "services/authzone.h"
59 #include "util/fptr_wlist.h"
60 #include "util/module.h"
61 #include "util/regional.h"
62 #include "util/random.h"
63 #include "util/config_file.h"
64 #include "util/netevent.h"
65 #include "util/storage/lookup3.h"
66 #include "util/storage/slabhash.h"
67 #include "util/net_help.h"
68 #include "util/data/dname.h"
69 #include "util/data/msgreply.h"
70 #include "util/data/msgencode.h"
71 #include "util/tube.h"
72 #include "iterator/iter_fwd.h"
73 #include "iterator/iter_hints.h"
74 #include "sldns/sbuffer.h"
75 #include "sldns/str2wire.h"
76 #ifdef USE_DNSTAP
77 #include "dnstap/dtstream.h"
78 #endif
79 
80 #ifdef HAVE_TARGETCONDITIONALS_H
81 #include <TargetConditionals.h>
82 #endif
83 
84 #if (defined(TARGET_OS_TV) && TARGET_OS_TV) || (defined(TARGET_OS_WATCH) && TARGET_OS_WATCH)
85 #undef HAVE_FORK
86 #endif
87 
88 /** handle new query command for bg worker */
89 static void handle_newq(struct libworker* w, uint8_t* buf, uint32_t len);
90 
91 /** delete libworker env */
92 static void
93 libworker_delete_env(struct libworker* w)
94 {
95 	if(w->env) {
96 		outside_network_quit_prepare(w->back);
97 		mesh_delete(w->env->mesh);
98 		context_release_alloc(w->ctx, w->env->alloc,
99 			!w->is_bg || w->is_bg_thread);
100 		sldns_buffer_free(w->env->scratch_buffer);
101 		regional_destroy(w->env->scratch);
102 		forwards_delete(w->env->fwds);
103 		hints_delete(w->env->hints);
104 		ub_randfree(w->env->rnd);
105 		free(w->env);
106 	}
107 #ifdef HAVE_SSL
108 	SSL_CTX_free(w->sslctx);
109 #endif
110 	outside_network_delete(w->back);
111 }
112 
113 /** delete libworker struct */
114 static void
115 libworker_delete(struct libworker* w)
116 {
117 	if(!w) return;
118 	libworker_delete_env(w);
119 	comm_base_delete(w->base);
120 	free(w);
121 }
122 
123 void
124 libworker_delete_event(struct libworker* w)
125 {
126 	if(!w) return;
127 	libworker_delete_env(w);
128 	comm_base_delete_no_base(w->base);
129 	free(w);
130 }
131 
132 /** setup fresh libworker struct */
133 static struct libworker*
134 libworker_setup(struct ub_ctx* ctx, int is_bg, struct ub_event_base* eb)
135 {
136 	struct libworker* w = (struct libworker*)calloc(1, sizeof(*w));
137 	struct config_file* cfg = ctx->env->cfg;
138 	int* ports;
139 	int numports;
140 	if(!w) return NULL;
141 	w->is_bg = is_bg;
142 	w->ctx = ctx;
143 	w->env = (struct module_env*)malloc(sizeof(*w->env));
144 	if(!w->env) {
145 		free(w);
146 		return NULL;
147 	}
148 	*w->env = *ctx->env;
149 	w->env->alloc = context_obtain_alloc(ctx, !w->is_bg || w->is_bg_thread);
150 	if(!w->env->alloc) {
151 		libworker_delete(w);
152 		return NULL;
153 	}
154 	w->thread_num = w->env->alloc->thread_num;
155 	alloc_set_id_cleanup(w->env->alloc, &libworker_alloc_cleanup, w);
156 	if(!w->is_bg || w->is_bg_thread) {
157 		lock_basic_lock(&ctx->cfglock);
158 	}
159 	w->env->scratch = regional_create_custom(cfg->msg_buffer_size);
160 	w->env->scratch_buffer = sldns_buffer_new(cfg->msg_buffer_size);
161 	w->env->fwds = forwards_create();
162 	if(w->env->fwds && !forwards_apply_cfg(w->env->fwds, cfg)) {
163 		forwards_delete(w->env->fwds);
164 		w->env->fwds = NULL;
165 	}
166 	w->env->hints = hints_create();
167 	if(w->env->hints && !hints_apply_cfg(w->env->hints, cfg)) {
168 		hints_delete(w->env->hints);
169 		w->env->hints = NULL;
170 	}
171 	if(cfg->ssl_upstream || (cfg->tls_cert_bundle && cfg->tls_cert_bundle[0]) || cfg->tls_win_cert) {
172 		w->sslctx = connect_sslctx_create(NULL, NULL,
173 			cfg->tls_cert_bundle, cfg->tls_win_cert);
174 		if(!w->sslctx) {
175 			/* to make the setup fail after unlock */
176 			hints_delete(w->env->hints);
177 			w->env->hints = NULL;
178 		}
179 	}
180 	if(!w->is_bg || w->is_bg_thread) {
181 		lock_basic_unlock(&ctx->cfglock);
182 	}
183 	if(!w->env->scratch || !w->env->scratch_buffer || !w->env->fwds ||
184 		!w->env->hints) {
185 		libworker_delete(w);
186 		return NULL;
187 	}
188 	w->env->worker = (struct worker*)w;
189 	w->env->probe_timer = NULL;
190 	if(!w->is_bg || w->is_bg_thread) {
191 		lock_basic_lock(&ctx->cfglock);
192 	}
193 	if(!(w->env->rnd = ub_initstate(ctx->seed_rnd))) {
194 		if(!w->is_bg || w->is_bg_thread) {
195 			lock_basic_unlock(&ctx->cfglock);
196 		}
197 		libworker_delete(w);
198 		return NULL;
199 	}
200 	if(!w->is_bg || w->is_bg_thread) {
201 		lock_basic_unlock(&ctx->cfglock);
202 	}
203 	if(1) {
204 		/* primitive lockout for threading: if it overwrites another
205 		 * thread it is like wiping the cache (which is likely empty
206 		 * at the start) */
207 		/* note we are holding the ctx lock in normal threaded
208 		 * cases so that is solved properly, it is only for many ctx
209 		 * in different threads that this may clash */
210 		static int done_raninit = 0;
211 		if(!done_raninit) {
212 			done_raninit = 1;
213 			hash_set_raninit((uint32_t)ub_random(w->env->rnd));
214 		}
215 	}
216 
217 	if(eb)
218 		w->base = comm_base_create_event(eb);
219 	else	w->base = comm_base_create(0);
220 	if(!w->base) {
221 		libworker_delete(w);
222 		return NULL;
223 	}
224 	w->env->worker_base = w->base;
225 	if(!w->is_bg || w->is_bg_thread) {
226 		lock_basic_lock(&ctx->cfglock);
227 	}
228 	numports = cfg_condense_ports(cfg, &ports);
229 	if(numports == 0) {
230 		if(!w->is_bg || w->is_bg_thread) {
231 			lock_basic_unlock(&ctx->cfglock);
232 		}
233 		libworker_delete(w);
234 		return NULL;
235 	}
236 	w->back = outside_network_create(w->base, cfg->msg_buffer_size,
237 		(size_t)cfg->outgoing_num_ports, cfg->out_ifs,
238 		cfg->num_out_ifs, cfg->do_ip4, cfg->do_ip6,
239 		cfg->do_tcp?cfg->outgoing_num_tcp:0, cfg->ip_dscp,
240 		w->env->infra_cache, w->env->rnd, cfg->use_caps_bits_for_id,
241 		ports, numports, cfg->unwanted_threshold,
242 		cfg->outgoing_tcp_mss, &libworker_alloc_cleanup, w,
243 		cfg->do_udp || cfg->udp_upstream_without_downstream, w->sslctx,
244 		cfg->delay_close, cfg->tls_use_sni, NULL, cfg->udp_connect,
245 		cfg->max_reuse_tcp_queries, cfg->tcp_reuse_timeout,
246 		cfg->tcp_auth_query_timeout);
247 	w->env->outnet = w->back;
248 	if(!w->is_bg || w->is_bg_thread) {
249 		lock_basic_unlock(&ctx->cfglock);
250 	}
251 	free(ports);
252 	if(!w->back) {
253 		libworker_delete(w);
254 		return NULL;
255 	}
256 	w->env->mesh = mesh_create(&ctx->mods, w->env);
257 	if(!w->env->mesh) {
258 		libworker_delete(w);
259 		return NULL;
260 	}
261 	w->env->send_query = &libworker_send_query;
262 	w->env->detach_subs = &mesh_detach_subs;
263 	w->env->attach_sub = &mesh_attach_sub;
264 	w->env->add_sub = &mesh_add_sub;
265 	w->env->kill_sub = &mesh_state_delete;
266 	w->env->detect_cycle = &mesh_detect_cycle;
267 	comm_base_timept(w->base, &w->env->now, &w->env->now_tv);
268 	return w;
269 }
270 
271 struct libworker* libworker_create_event(struct ub_ctx* ctx,
272 	struct ub_event_base* eb)
273 {
274 	return libworker_setup(ctx, 0, eb);
275 }
276 
277 /** handle cancel command for bg worker */
278 static void
279 handle_cancel(struct libworker* w, uint8_t* buf, uint32_t len)
280 {
281 	struct ctx_query* q;
282 	if(w->is_bg_thread) {
283 		lock_basic_lock(&w->ctx->cfglock);
284 		q = context_deserialize_cancel(w->ctx, buf, len);
285 		lock_basic_unlock(&w->ctx->cfglock);
286 	} else {
287 		q = context_deserialize_cancel(w->ctx, buf, len);
288 	}
289 	if(!q) {
290 		/* probably simply lookup failed, i.e. the message had been
291 		 * processed and answered before the cancel arrived */
292 		return;
293 	}
294 	q->cancelled = 1;
295 	free(buf);
296 }
297 
298 /** do control command coming into bg server */
299 static void
300 libworker_do_cmd(struct libworker* w, uint8_t* msg, uint32_t len)
301 {
302 	switch(context_serial_getcmd(msg, len)) {
303 		default:
304 		case UB_LIBCMD_ANSWER:
305 			log_err("unknown command for bg worker %d",
306 				(int)context_serial_getcmd(msg, len));
307 			/* and fall through to quit */
308 			/* fallthrough */
309 		case UB_LIBCMD_QUIT:
310 			free(msg);
311 			comm_base_exit(w->base);
312 			break;
313 		case UB_LIBCMD_NEWQUERY:
314 			handle_newq(w, msg, len);
315 			break;
316 		case UB_LIBCMD_CANCEL:
317 			handle_cancel(w, msg, len);
318 			break;
319 	}
320 }
321 
322 /** handle control command coming into server */
323 void
324 libworker_handle_control_cmd(struct tube* ATTR_UNUSED(tube),
325 	uint8_t* msg, size_t len, int err, void* arg)
326 {
327 	struct libworker* w = (struct libworker*)arg;
328 
329 	if(err != 0) {
330 		free(msg);
331 		/* it is of no use to go on, exit */
332 		comm_base_exit(w->base);
333 		return;
334 	}
335 	libworker_do_cmd(w, msg, len); /* also frees the buf */
336 }
337 
338 /** the background thread func */
339 static void*
340 libworker_dobg(void* arg)
341 {
342 	/* setup */
343 	uint32_t m;
344 	struct libworker* w = (struct libworker*)arg;
345 	struct ub_ctx* ctx;
346 	if(!w) {
347 		log_err("libunbound bg worker init failed, nomem");
348 		return NULL;
349 	}
350 	ctx = w->ctx;
351 	log_thread_set(&w->thread_num);
352 #ifdef THREADS_DISABLED
353 	/* we are forked */
354 	w->is_bg_thread = 0;
355 	/* close non-used parts of the pipes */
356 	tube_close_write(ctx->qq_pipe);
357 	tube_close_read(ctx->rr_pipe);
358 #endif
359 	if(!tube_setup_bg_listen(ctx->qq_pipe, w->base,
360 		libworker_handle_control_cmd, w)) {
361 		log_err("libunbound bg worker init failed, no bglisten");
362 		return NULL;
363 	}
364 	if(!tube_setup_bg_write(ctx->rr_pipe, w->base)) {
365 		log_err("libunbound bg worker init failed, no bgwrite");
366 		return NULL;
367 	}
368 
369 	/* do the work */
370 	comm_base_dispatch(w->base);
371 
372 	/* cleanup */
373 	m = UB_LIBCMD_QUIT;
374 	w->want_quit = 1;
375 	tube_remove_bg_listen(w->ctx->qq_pipe);
376 	tube_remove_bg_write(w->ctx->rr_pipe);
377 	libworker_delete(w);
378 	(void)tube_write_msg(ctx->rr_pipe, (uint8_t*)&m,
379 		(uint32_t)sizeof(m), 0);
380 #ifdef THREADS_DISABLED
381 	/* close pipes from forked process before exit */
382 	tube_close_read(ctx->qq_pipe);
383 	tube_close_write(ctx->rr_pipe);
384 #endif
385 	return NULL;
386 }
387 
388 int libworker_bg(struct ub_ctx* ctx)
389 {
390 	struct libworker* w;
391 	/* fork or threadcreate */
392 	lock_basic_lock(&ctx->cfglock);
393 	if(ctx->dothread) {
394 		lock_basic_unlock(&ctx->cfglock);
395 		w = libworker_setup(ctx, 1, NULL);
396 		if(!w) return UB_NOMEM;
397 		w->is_bg_thread = 1;
398 #ifdef ENABLE_LOCK_CHECKS
399 		w->thread_num = 1; /* for nicer DEBUG checklocks */
400 #endif
401 		ub_thread_create(&ctx->bg_tid, libworker_dobg, w);
402 	} else {
403 		lock_basic_unlock(&ctx->cfglock);
404 #ifndef HAVE_FORK
405 		/* no fork on windows */
406 		return UB_FORKFAIL;
407 #else /* HAVE_FORK */
408 		switch((ctx->bg_pid=fork())) {
409 			case 0:
410 				w = libworker_setup(ctx, 1, NULL);
411 				if(!w) fatal_exit("out of memory");
412 				/* close non-used parts of the pipes */
413 				tube_close_write(ctx->qq_pipe);
414 				tube_close_read(ctx->rr_pipe);
415 				(void)libworker_dobg(w);
416 				exit(0);
417 				break;
418 			case -1:
419 				return UB_FORKFAIL;
420 			default:
421 				/* close non-used parts, so that the worker
422 				 * bgprocess gets 'pipe closed' when the
423 				 * main process exits */
424 				tube_close_read(ctx->qq_pipe);
425 				tube_close_write(ctx->rr_pipe);
426 				break;
427 		}
428 #endif /* HAVE_FORK */
429 	}
430 	return UB_NOERROR;
431 }
432 
433 /** insert canonname */
434 static int
435 fill_canon(struct ub_result* res, uint8_t* s)
436 {
437 	char buf[255+2];
438 	dname_str(s, buf);
439 	res->canonname = strdup(buf);
440 	return res->canonname != 0;
441 }
442 
443 /** fill data into result */
444 static int
445 fill_res(struct ub_result* res, struct ub_packed_rrset_key* answer,
446 	uint8_t* finalcname, struct query_info* rq, struct reply_info* rep)
447 {
448 	size_t i;
449 	struct packed_rrset_data* data;
450 	res->ttl = 0;
451 	if(!answer) {
452 		if(finalcname) {
453 			if(!fill_canon(res, finalcname))
454 				return 0; /* out of memory */
455 		}
456 		if(rep->rrset_count != 0)
457 			res->ttl = (int)rep->ttl;
458 		res->data = (char**)calloc(1, sizeof(char*));
459 		if(!res->data)
460 			return 0; /* out of memory */
461 		res->len = (int*)calloc(1, sizeof(int));
462 		if(!res->len) {
463 			free(res->data);
464 			res->data = NULL;
465 			return 0; /* out of memory */
466 		}
467 		return 1;
468 	}
469 	data = (struct packed_rrset_data*)answer->entry.data;
470 	if(query_dname_compare(rq->qname, answer->rk.dname) != 0) {
471 		if(!fill_canon(res, answer->rk.dname))
472 			return 0; /* out of memory */
473 	} else	res->canonname = NULL;
474 	res->data = (char**)calloc(data->count+1, sizeof(char*));
475 	if(!res->data)
476 		return 0; /* out of memory */
477 	res->len = (int*)calloc(data->count+1, sizeof(int));
478 	if(!res->len) {
479 		free(res->data);
480 		res->data = NULL;
481 		return 0; /* out of memory */
482 	}
483 	for(i=0; i<data->count; i++) {
484 		/* remove rdlength from rdata */
485 		res->len[i] = (int)(data->rr_len[i] - 2);
486 		res->data[i] = memdup(data->rr_data[i]+2, (size_t)res->len[i]);
487 		if(!res->data[i]) {
488 			size_t j;
489 			for(j=0; j<i; j++) {
490 				free(res->data[j]);
491 				res->data[j] = NULL;
492 			}
493 			free(res->data);
494 			res->data = NULL;
495 			free(res->len);
496 			res->len = NULL;
497 			return 0; /* out of memory */
498 		}
499 	}
500 	/* ttl for positive answers, from CNAME and answer RRs */
501 	if(data->count != 0) {
502 		size_t j;
503 		res->ttl = (int)data->ttl;
504 		for(j=0; j<rep->an_numrrsets; j++) {
505 			struct packed_rrset_data* d =
506 				(struct packed_rrset_data*)rep->rrsets[j]->
507 				entry.data;
508 			if((int)d->ttl < res->ttl)
509 				res->ttl = (int)d->ttl;
510 		}
511 	}
512 	/* ttl for negative answers */
513 	if(data->count == 0 && rep->rrset_count != 0)
514 		res->ttl = (int)rep->ttl;
515 	res->data[data->count] = NULL;
516 	res->len[data->count] = 0;
517 	return 1;
518 }
519 
520 /** fill result from parsed message, on error fills servfail */
521 void
522 libworker_enter_result(struct ub_result* res, sldns_buffer* buf,
523 	struct regional* temp, enum sec_status msg_security)
524 {
525 	struct query_info rq;
526 	struct reply_info* rep;
527 	res->rcode = LDNS_RCODE_SERVFAIL;
528 	rep = parse_reply_in_temp_region(buf, temp, &rq);
529 	if(!rep) {
530 		log_err("cannot parse buf");
531 		return; /* error parsing buf, or out of memory */
532 	}
533 	if(!fill_res(res, reply_find_answer_rrset(&rq, rep),
534 		reply_find_final_cname_target(&rq, rep), &rq, rep))
535 		return; /* out of memory */
536 	/* rcode, havedata, nxdomain, secure, bogus */
537 	res->rcode = (int)FLAGS_GET_RCODE(rep->flags);
538 	if(res->data && res->data[0])
539 		res->havedata = 1;
540 	if(res->rcode == LDNS_RCODE_NXDOMAIN)
541 		res->nxdomain = 1;
542 	if(msg_security == sec_status_secure)
543 		res->secure = 1;
544 	if(msg_security == sec_status_bogus ||
545 		msg_security == sec_status_secure_sentinel_fail)
546 		res->bogus = 1;
547 }
548 
549 /** fillup fg results */
550 static void
551 libworker_fillup_fg(struct ctx_query* q, int rcode, sldns_buffer* buf,
552 	enum sec_status s, char* why_bogus, int was_ratelimited)
553 {
554 	q->res->was_ratelimited = was_ratelimited;
555 	if(why_bogus)
556 		q->res->why_bogus = strdup(why_bogus);
557 	if(rcode != 0) {
558 		q->res->rcode = rcode;
559 		q->msg_security = s;
560 		return;
561 	}
562 
563 	q->res->rcode = LDNS_RCODE_SERVFAIL;
564 	q->msg_security = sec_status_unchecked;
565 	q->msg = memdup(sldns_buffer_begin(buf), sldns_buffer_limit(buf));
566 	q->msg_len = sldns_buffer_limit(buf);
567 	if(!q->msg) {
568 		return; /* the error is in the rcode */
569 	}
570 
571 	/* canonname and results */
572 	q->msg_security = s;
573 	libworker_enter_result(q->res, buf, q->w->env->scratch, s);
574 }
575 
576 void
577 libworker_fg_done_cb(void* arg, int rcode, sldns_buffer* buf, enum sec_status s,
578 	char* why_bogus, int was_ratelimited)
579 {
580 	struct ctx_query* q = (struct ctx_query*)arg;
581 	/* fg query is done; exit comm base */
582 	comm_base_exit(q->w->base);
583 
584 	libworker_fillup_fg(q, rcode, buf, s, why_bogus, was_ratelimited);
585 }
586 
587 /** setup qinfo and edns */
588 static int
589 setup_qinfo_edns(struct libworker* w, struct ctx_query* q,
590 	struct query_info* qinfo, struct edns_data* edns)
591 {
592 	qinfo->qtype = (uint16_t)q->res->qtype;
593 	qinfo->qclass = (uint16_t)q->res->qclass;
594 	qinfo->local_alias = NULL;
595 	qinfo->qname = sldns_str2wire_dname(q->res->qname, &qinfo->qname_len);
596 	if(!qinfo->qname) {
597 		return 0;
598 	}
599 	edns->edns_present = 1;
600 	edns->ext_rcode = 0;
601 	edns->edns_version = 0;
602 	edns->bits = EDNS_DO;
603 	edns->opt_list = NULL;
604 	edns->padding_block_size = 0;
605 	if(sldns_buffer_capacity(w->back->udp_buff) < 65535)
606 		edns->udp_size = (uint16_t)sldns_buffer_capacity(
607 			w->back->udp_buff);
608 	else	edns->udp_size = 65535;
609 	return 1;
610 }
611 
612 int libworker_fg(struct ub_ctx* ctx, struct ctx_query* q)
613 {
614 	struct libworker* w = libworker_setup(ctx, 0, NULL);
615 	uint16_t qflags, qid;
616 	struct query_info qinfo;
617 	struct edns_data edns;
618 	if(!w)
619 		return UB_INITFAIL;
620 	if(!setup_qinfo_edns(w, q, &qinfo, &edns)) {
621 		libworker_delete(w);
622 		return UB_SYNTAX;
623 	}
624 	qid = 0;
625 	qflags = BIT_RD;
626 	q->w = w;
627 	/* see if there is a fixed answer */
628 	sldns_buffer_write_u16_at(w->back->udp_buff, 0, qid);
629 	sldns_buffer_write_u16_at(w->back->udp_buff, 2, qflags);
630 	if(local_zones_answer(ctx->local_zones, w->env, &qinfo, &edns,
631 		w->back->udp_buff, w->env->scratch, NULL, NULL, 0, NULL, 0,
632 		NULL, 0, NULL, 0, NULL)) {
633 		regional_free_all(w->env->scratch);
634 		libworker_fillup_fg(q, LDNS_RCODE_NOERROR,
635 			w->back->udp_buff, sec_status_insecure, NULL, 0);
636 		libworker_delete(w);
637 		free(qinfo.qname);
638 		return UB_NOERROR;
639 	}
640 	if(ctx->env->auth_zones && auth_zones_answer(ctx->env->auth_zones,
641 		w->env, &qinfo, &edns, NULL, w->back->udp_buff, w->env->scratch)) {
642 		regional_free_all(w->env->scratch);
643 		libworker_fillup_fg(q, LDNS_RCODE_NOERROR,
644 			w->back->udp_buff, sec_status_insecure, NULL, 0);
645 		libworker_delete(w);
646 		free(qinfo.qname);
647 		return UB_NOERROR;
648 	}
649 	/* process new query */
650 	if(!mesh_new_callback(w->env->mesh, &qinfo, qflags, &edns,
651 		w->back->udp_buff, qid, libworker_fg_done_cb, q)) {
652 		free(qinfo.qname);
653 		return UB_NOMEM;
654 	}
655 	free(qinfo.qname);
656 
657 	/* wait for reply */
658 	comm_base_dispatch(w->base);
659 
660 	libworker_delete(w);
661 	return UB_NOERROR;
662 }
663 
664 void
665 libworker_event_done_cb(void* arg, int rcode, sldns_buffer* buf,
666 	enum sec_status s, char* why_bogus, int was_ratelimited)
667 {
668 	struct ctx_query* q = (struct ctx_query*)arg;
669 	ub_event_callback_type cb = q->cb_event;
670 	void* cb_arg = q->cb_arg;
671 	int cancelled = q->cancelled;
672 
673 	/* delete it now */
674 	struct ub_ctx* ctx = q->w->ctx;
675 	lock_basic_lock(&ctx->cfglock);
676 	(void)rbtree_delete(&ctx->queries, q->node.key);
677 	ctx->num_async--;
678 	context_query_delete(q);
679 	lock_basic_unlock(&ctx->cfglock);
680 
681 	if(!cancelled) {
682 		/* call callback */
683 		int sec = 0;
684 		if(s == sec_status_bogus)
685 			sec = 1;
686 		else if(s == sec_status_secure)
687 			sec = 2;
688 		(*cb)(cb_arg, rcode, (buf?(void*)sldns_buffer_begin(buf):NULL),
689 			(buf?(int)sldns_buffer_limit(buf):0), sec, why_bogus, was_ratelimited);
690 	}
691 }
692 
693 int libworker_attach_mesh(struct ub_ctx* ctx, struct ctx_query* q,
694 	int* async_id)
695 {
696 	struct libworker* w = ctx->event_worker;
697 	uint16_t qflags, qid;
698 	struct query_info qinfo;
699 	struct edns_data edns;
700 	if(!w)
701 		return UB_INITFAIL;
702 	if(!setup_qinfo_edns(w, q, &qinfo, &edns))
703 		return UB_SYNTAX;
704 	qid = 0;
705 	qflags = BIT_RD;
706 	q->w = w;
707 	/* see if there is a fixed answer */
708 	sldns_buffer_write_u16_at(w->back->udp_buff, 0, qid);
709 	sldns_buffer_write_u16_at(w->back->udp_buff, 2, qflags);
710 	if(local_zones_answer(ctx->local_zones, w->env, &qinfo, &edns,
711 		w->back->udp_buff, w->env->scratch, NULL, NULL, 0, NULL, 0,
712 		NULL, 0, NULL, 0, NULL)) {
713 		regional_free_all(w->env->scratch);
714 		free(qinfo.qname);
715 		libworker_event_done_cb(q, LDNS_RCODE_NOERROR,
716 			w->back->udp_buff, sec_status_insecure, NULL, 0);
717 		return UB_NOERROR;
718 	}
719 	if(ctx->env->auth_zones && auth_zones_answer(ctx->env->auth_zones,
720 		w->env, &qinfo, &edns, NULL, w->back->udp_buff, w->env->scratch)) {
721 		regional_free_all(w->env->scratch);
722 		free(qinfo.qname);
723 		libworker_event_done_cb(q, LDNS_RCODE_NOERROR,
724 			w->back->udp_buff, sec_status_insecure, NULL, 0);
725 		return UB_NOERROR;
726 	}
727 	/* process new query */
728 	if(async_id)
729 		*async_id = q->querynum;
730 	if(!mesh_new_callback(w->env->mesh, &qinfo, qflags, &edns,
731 		w->back->udp_buff, qid, libworker_event_done_cb, q)) {
732 		free(qinfo.qname);
733 		return UB_NOMEM;
734 	}
735 	free(qinfo.qname);
736 	return UB_NOERROR;
737 }
738 
739 /** add result to the bg worker result queue */
740 static void
741 add_bg_result(struct libworker* w, struct ctx_query* q, sldns_buffer* pkt,
742 	int err, char* reason, int was_ratelimited)
743 {
744 	uint8_t* msg = NULL;
745 	uint32_t len = 0;
746 
747 	if(w->want_quit) {
748 		context_query_delete(q);
749 		return;
750 	}
751 	/* serialize and delete unneeded q */
752 	if(w->is_bg_thread) {
753 		lock_basic_lock(&w->ctx->cfglock);
754 		if(reason)
755 			q->res->why_bogus = strdup(reason);
756 		q->res->was_ratelimited = was_ratelimited;
757 		if(pkt) {
758 			q->msg_len = sldns_buffer_remaining(pkt);
759 			q->msg = memdup(sldns_buffer_begin(pkt), q->msg_len);
760 			if(!q->msg) {
761 				msg = context_serialize_answer(q, UB_NOMEM, NULL, &len);
762 			} else {
763 				msg = context_serialize_answer(q, err, NULL, &len);
764 			}
765 		} else {
766 			msg = context_serialize_answer(q, err, NULL, &len);
767 		}
768 		lock_basic_unlock(&w->ctx->cfglock);
769 	} else {
770 		if(reason)
771 			q->res->why_bogus = strdup(reason);
772 		q->res->was_ratelimited = was_ratelimited;
773 		msg = context_serialize_answer(q, err, pkt, &len);
774 		(void)rbtree_delete(&w->ctx->queries, q->node.key);
775 		w->ctx->num_async--;
776 		context_query_delete(q);
777 	}
778 
779 	if(!msg) {
780 		log_err("out of memory for async answer");
781 		return;
782 	}
783 	if(!tube_queue_item(w->ctx->rr_pipe, msg, len)) {
784 		log_err("out of memory for async answer");
785 		return;
786 	}
787 }
788 
789 void
790 libworker_bg_done_cb(void* arg, int rcode, sldns_buffer* buf, enum sec_status s,
791 	char* why_bogus, int was_ratelimited)
792 {
793 	struct ctx_query* q = (struct ctx_query*)arg;
794 
795 	if(q->cancelled || q->w->back->want_to_quit) {
796 		if(q->w->is_bg_thread) {
797 			/* delete it now */
798 			struct ub_ctx* ctx = q->w->ctx;
799 			lock_basic_lock(&ctx->cfglock);
800 			(void)rbtree_delete(&ctx->queries, q->node.key);
801 			ctx->num_async--;
802 			context_query_delete(q);
803 			lock_basic_unlock(&ctx->cfglock);
804 		}
805 		/* cancelled, do not give answer */
806 		return;
807 	}
808 	q->msg_security = s;
809 	if(!buf) {
810 		buf = q->w->env->scratch_buffer;
811 	}
812 	if(rcode != 0) {
813 		error_encode(buf, rcode, NULL, 0, BIT_RD, NULL);
814 	}
815 	add_bg_result(q->w, q, buf, UB_NOERROR, why_bogus, was_ratelimited);
816 }
817 
818 
819 /** handle new query command for bg worker */
820 static void
821 handle_newq(struct libworker* w, uint8_t* buf, uint32_t len)
822 {
823 	uint16_t qflags, qid;
824 	struct query_info qinfo;
825 	struct edns_data edns;
826 	struct ctx_query* q;
827 	if(w->is_bg_thread) {
828 		lock_basic_lock(&w->ctx->cfglock);
829 		q = context_lookup_new_query(w->ctx, buf, len);
830 		lock_basic_unlock(&w->ctx->cfglock);
831 	} else {
832 		q = context_deserialize_new_query(w->ctx, buf, len);
833 	}
834 	free(buf);
835 	if(!q) {
836 		log_err("failed to deserialize newq");
837 		return;
838 	}
839 	if(!setup_qinfo_edns(w, q, &qinfo, &edns)) {
840 		add_bg_result(w, q, NULL, UB_SYNTAX, NULL, 0);
841 		return;
842 	}
843 	qid = 0;
844 	qflags = BIT_RD;
845 	/* see if there is a fixed answer */
846 	sldns_buffer_write_u16_at(w->back->udp_buff, 0, qid);
847 	sldns_buffer_write_u16_at(w->back->udp_buff, 2, qflags);
848 	if(local_zones_answer(w->ctx->local_zones, w->env, &qinfo, &edns,
849 		w->back->udp_buff, w->env->scratch, NULL, NULL, 0, NULL, 0,
850 		NULL, 0, NULL, 0, NULL)) {
851 		regional_free_all(w->env->scratch);
852 		q->msg_security = sec_status_insecure;
853 		add_bg_result(w, q, w->back->udp_buff, UB_NOERROR, NULL, 0);
854 		free(qinfo.qname);
855 		return;
856 	}
857 	if(w->ctx->env->auth_zones && auth_zones_answer(w->ctx->env->auth_zones,
858 		w->env, &qinfo, &edns, NULL, w->back->udp_buff, w->env->scratch)) {
859 		regional_free_all(w->env->scratch);
860 		q->msg_security = sec_status_insecure;
861 		add_bg_result(w, q, w->back->udp_buff, UB_NOERROR, NULL, 0);
862 		free(qinfo.qname);
863 		return;
864 	}
865 	q->w = w;
866 	/* process new query */
867 	if(!mesh_new_callback(w->env->mesh, &qinfo, qflags, &edns,
868 		w->back->udp_buff, qid, libworker_bg_done_cb, q)) {
869 		add_bg_result(w, q, NULL, UB_NOMEM, NULL, 0);
870 	}
871 	free(qinfo.qname);
872 }
873 
874 void libworker_alloc_cleanup(void* arg)
875 {
876 	struct libworker* w = (struct libworker*)arg;
877 	slabhash_clear(&w->env->rrset_cache->table);
878         slabhash_clear(w->env->msg_cache);
879 }
880 
881 struct outbound_entry* libworker_send_query(struct query_info* qinfo,
882 	uint16_t flags, int dnssec, int want_dnssec, int nocaps,
883 	struct sockaddr_storage* addr, socklen_t addrlen, uint8_t* zone,
884 	size_t zonelen, int ssl_upstream, char* tls_auth_name,
885 	struct module_qstate* q)
886 {
887 	struct libworker* w = (struct libworker*)q->env->worker;
888 	struct outbound_entry* e = (struct outbound_entry*)regional_alloc(
889 		q->region, sizeof(*e));
890 	if(!e)
891 		return NULL;
892 	e->qstate = q;
893 	e->qsent = outnet_serviced_query(w->back, qinfo, flags, dnssec,
894 		want_dnssec, nocaps, q->env->cfg->tcp_upstream, ssl_upstream,
895 		tls_auth_name, addr, addrlen, zone, zonelen, q,
896 		libworker_handle_service_reply, e, w->back->udp_buff, q->env);
897 	if(!e->qsent) {
898 		return NULL;
899 	}
900 	return e;
901 }
902 
903 int
904 libworker_handle_service_reply(struct comm_point* c, void* arg, int error,
905         struct comm_reply* reply_info)
906 {
907 	struct outbound_entry* e = (struct outbound_entry*)arg;
908 	struct libworker* lw = (struct libworker*)e->qstate->env->worker;
909 
910 	if(error != 0) {
911 		mesh_report_reply(lw->env->mesh, e, reply_info, error);
912 		return 0;
913 	}
914 	/* sanity check. */
915 	if(!LDNS_QR_WIRE(sldns_buffer_begin(c->buffer))
916 		|| LDNS_OPCODE_WIRE(sldns_buffer_begin(c->buffer)) !=
917 			LDNS_PACKET_QUERY
918 		|| LDNS_QDCOUNT(sldns_buffer_begin(c->buffer)) > 1) {
919 		/* error becomes timeout for the module as if this reply
920 		 * never arrived. */
921 		mesh_report_reply(lw->env->mesh, e, reply_info,
922 			NETEVENT_TIMEOUT);
923 		return 0;
924 	}
925 	mesh_report_reply(lw->env->mesh,  e, reply_info, NETEVENT_NOERROR);
926 	return 0;
927 }
928 
929 /* --- fake callbacks for fptr_wlist to work --- */
930 void worker_handle_control_cmd(struct tube* ATTR_UNUSED(tube),
931 	uint8_t* ATTR_UNUSED(buffer), size_t ATTR_UNUSED(len),
932 	int ATTR_UNUSED(error), void* ATTR_UNUSED(arg))
933 {
934 	log_assert(0);
935 }
936 
937 int worker_handle_request(struct comm_point* ATTR_UNUSED(c),
938 	void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
939         struct comm_reply* ATTR_UNUSED(repinfo))
940 {
941 	log_assert(0);
942 	return 0;
943 }
944 
945 int worker_handle_service_reply(struct comm_point* ATTR_UNUSED(c),
946 	void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
947         struct comm_reply* ATTR_UNUSED(reply_info))
948 {
949 	log_assert(0);
950 	return 0;
951 }
952 
953 int remote_accept_callback(struct comm_point* ATTR_UNUSED(c),
954 	void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
955         struct comm_reply* ATTR_UNUSED(repinfo))
956 {
957 	log_assert(0);
958 	return 0;
959 }
960 
961 int remote_control_callback(struct comm_point* ATTR_UNUSED(c),
962 	void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
963         struct comm_reply* ATTR_UNUSED(repinfo))
964 {
965 	log_assert(0);
966 	return 0;
967 }
968 
969 void worker_sighandler(int ATTR_UNUSED(sig), void* ATTR_UNUSED(arg))
970 {
971 	log_assert(0);
972 }
973 
974 struct outbound_entry* worker_send_query(struct query_info* ATTR_UNUSED(qinfo),
975 	uint16_t ATTR_UNUSED(flags), int ATTR_UNUSED(dnssec),
976 	int ATTR_UNUSED(want_dnssec), int ATTR_UNUSED(nocaps),
977 	struct sockaddr_storage* ATTR_UNUSED(addr), socklen_t ATTR_UNUSED(addrlen),
978 	uint8_t* ATTR_UNUSED(zone), size_t ATTR_UNUSED(zonelen),
979 	int ATTR_UNUSED(ssl_upstream), char* ATTR_UNUSED(tls_auth_name),
980 	struct module_qstate* ATTR_UNUSED(q))
981 {
982 	log_assert(0);
983 	return 0;
984 }
985 
986 void
987 worker_alloc_cleanup(void* ATTR_UNUSED(arg))
988 {
989 	log_assert(0);
990 }
991 
992 void worker_stat_timer_cb(void* ATTR_UNUSED(arg))
993 {
994 	log_assert(0);
995 }
996 
997 void worker_probe_timer_cb(void* ATTR_UNUSED(arg))
998 {
999 	log_assert(0);
1000 }
1001 
1002 void worker_start_accept(void* ATTR_UNUSED(arg))
1003 {
1004 	log_assert(0);
1005 }
1006 
1007 void worker_stop_accept(void* ATTR_UNUSED(arg))
1008 {
1009 	log_assert(0);
1010 }
1011 
1012 int order_lock_cmp(const void* ATTR_UNUSED(e1), const void* ATTR_UNUSED(e2))
1013 {
1014 	log_assert(0);
1015 	return 0;
1016 }
1017 
1018 int
1019 codeline_cmp(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
1020 {
1021 	log_assert(0);
1022 	return 0;
1023 }
1024 
1025 int replay_var_compare(const void* ATTR_UNUSED(a), const void* ATTR_UNUSED(b))
1026 {
1027         log_assert(0);
1028         return 0;
1029 }
1030 
1031 void remote_get_opt_ssl(char* ATTR_UNUSED(str), void* ATTR_UNUSED(arg))
1032 {
1033         log_assert(0);
1034 }
1035 
1036 #ifdef UB_ON_WINDOWS
1037 void
1038 worker_win_stop_cb(int ATTR_UNUSED(fd), short ATTR_UNUSED(ev), void*
1039         ATTR_UNUSED(arg)) {
1040         log_assert(0);
1041 }
1042 
1043 void
1044 wsvc_cron_cb(void* ATTR_UNUSED(arg))
1045 {
1046         log_assert(0);
1047 }
1048 #endif /* UB_ON_WINDOWS */
1049 
1050 #ifdef USE_DNSTAP
1051 void dtio_tap_callback(int ATTR_UNUSED(fd), short ATTR_UNUSED(ev),
1052 	void* ATTR_UNUSED(arg))
1053 {
1054 	log_assert(0);
1055 }
1056 #endif
1057 
1058 #ifdef USE_DNSTAP
1059 void dtio_mainfdcallback(int ATTR_UNUSED(fd), short ATTR_UNUSED(ev),
1060 	void* ATTR_UNUSED(arg))
1061 {
1062 	log_assert(0);
1063 }
1064 #endif
1065