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