2 * unbound.c - unbound validating resolver public API implementation
4 * Copyright (c) 2007, NLnet Labs. All rights reserved.
6 * This software is open source.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * Redistributions of source code must retain the above copyright notice,
13 * this list of conditions and the following disclaimer.
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.
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.
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.
39 * This file contains functions to resolve DNS queries and
40 * validate the answers. Synchronously and asynchronously.
44 /* include the public api first, it should be able to stand alone */
45 #include "libunbound/unbound.h"
46 #include "libunbound/unbound-event.h"
49 #include "libunbound/context.h"
50 #include "libunbound/libworker.h"
51 #include "util/locks.h"
52 #include "util/config_file.h"
53 #include "util/alloc.h"
54 #include "util/module.h"
55 #include "util/regional.h"
57 #include "util/random.h"
58 #include "util/net_help.h"
59 #include "util/tube.h"
60 #include "util/ub_event.h"
61 #include "services/modstack.h"
62 #include "services/localzone.h"
63 #include "services/cache/infra.h"
64 #include "services/cache/rrset.h"
65 #include "services/authzone.h"
66 #include "sldns/sbuffer.h"
70 #ifdef HAVE_SYS_WAIT_H
77 #if defined(UB_ON_WINDOWS) && defined (HAVE_WINDOWS_H)
80 #endif /* UB_ON_WINDOWS */
82 /** store that the logfile has a debug override */
83 int ctx_logfile_overridden = 0;
85 /** create context functionality, but no pipes */
86 static struct ub_ctx* ub_ctx_create_nopipe(void)
95 if(!ctx_logfile_overridden)
96 log_init(NULL, 0, NULL); /* logs to stderr */
97 log_ident_set("libunbound");
99 if((r = WSAStartup(MAKEWORD(2,2), &wsa_data)) != 0) {
100 log_err("could not init winsock. WSAStartup: %s",
105 verbosity = NO_VERBOSE; /* errors only */
107 ctx = (struct ub_ctx*)calloc(1, sizeof(*ctx));
112 alloc_init(&ctx->superalloc, NULL, 0);
113 if(!(ctx->seed_rnd = ub_initstate(NULL))) {
114 ub_randfree(ctx->seed_rnd);
119 lock_basic_init(&ctx->qqpipe_lock);
120 lock_basic_init(&ctx->rrpipe_lock);
121 lock_basic_init(&ctx->cfglock);
122 ctx->env = (struct module_env*)calloc(1, sizeof(*ctx->env));
124 ub_randfree(ctx->seed_rnd);
129 ctx->env->cfg = config_create_forlib();
132 ub_randfree(ctx->seed_rnd);
137 /* init edns_known_options */
138 if(!edns_known_options_init(ctx->env)) {
139 config_delete(ctx->env->cfg);
141 ub_randfree(ctx->seed_rnd);
146 ctx->env->auth_zones = auth_zones_create();
147 if(!ctx->env->auth_zones) {
148 edns_known_options_delete(ctx->env);
149 config_delete(ctx->env->cfg);
151 ub_randfree(ctx->seed_rnd);
156 ctx->env->alloc = &ctx->superalloc;
157 ctx->env->worker = NULL;
158 ctx->env->need_to_validate = 0;
159 modstack_init(&ctx->mods);
160 rbtree_init(&ctx->queries, &context_query_cmp);
167 struct ub_ctx* ctx = ub_ctx_create_nopipe();
170 if((ctx->qq_pipe = tube_create()) == NULL) {
172 ub_randfree(ctx->seed_rnd);
173 config_delete(ctx->env->cfg);
174 modstack_desetup(&ctx->mods, ctx->env);
175 edns_known_options_delete(ctx->env);
181 if((ctx->rr_pipe = tube_create()) == NULL) {
183 tube_delete(ctx->qq_pipe);
184 ub_randfree(ctx->seed_rnd);
185 config_delete(ctx->env->cfg);
186 modstack_desetup(&ctx->mods, ctx->env);
187 edns_known_options_delete(ctx->env);
197 ub_ctx_create_ub_event(struct ub_event_base* ueb)
199 struct ub_ctx* ctx = ub_ctx_create_nopipe();
202 /* no pipes, but we have the locks to make sure everything works */
204 ctx->dothread = 1; /* the processing is in the same process,
205 makes ub_cancel and ub_ctx_delete do the right thing */
206 ctx->event_base = ueb;
211 ub_ctx_create_event(struct event_base* eb)
213 struct ub_ctx* ctx = ub_ctx_create_nopipe();
216 /* no pipes, but we have the locks to make sure everything works */
218 ctx->dothread = 1; /* the processing is in the same process,
219 makes ub_cancel and ub_ctx_delete do the right thing */
220 ctx->event_base = ub_libevent_event_base(eb);
221 if (!ctx->event_base) {
225 ctx->event_base_malloced = 1;
231 delq(rbnode_type* n, void* ATTR_UNUSED(arg))
233 struct ctx_query* q = (struct ctx_query*)n;
234 context_query_delete(q);
237 /** stop the bg thread */
238 static void ub_stop_bg(struct ub_ctx* ctx)
240 /* stop the bg thread */
241 lock_basic_lock(&ctx->cfglock);
242 if(ctx->created_bg) {
245 uint32_t cmd = UB_LIBCMD_QUIT;
246 lock_basic_unlock(&ctx->cfglock);
247 lock_basic_lock(&ctx->qqpipe_lock);
248 (void)tube_write_msg(ctx->qq_pipe, (uint8_t*)&cmd,
249 (uint32_t)sizeof(cmd), 0);
250 lock_basic_unlock(&ctx->qqpipe_lock);
251 lock_basic_lock(&ctx->rrpipe_lock);
252 while(tube_read_msg(ctx->rr_pipe, &msg, &len, 0)) {
253 /* discard all results except a quit confirm */
254 if(context_serial_getcmd(msg, len) == UB_LIBCMD_QUIT) {
260 lock_basic_unlock(&ctx->rrpipe_lock);
262 /* if bg worker is a thread, wait for it to exit, so that all
263 * resources are really gone. */
264 lock_basic_lock(&ctx->cfglock);
266 lock_basic_unlock(&ctx->cfglock);
267 ub_thread_join(ctx->bg_tid);
269 lock_basic_unlock(&ctx->cfglock);
270 #ifndef UB_ON_WINDOWS
271 if(waitpid(ctx->bg_pid, NULL, 0) == -1) {
273 log_err("waitpid: %s", strerror(errno));
279 lock_basic_unlock(&ctx->cfglock);
284 ub_ctx_delete(struct ub_ctx* ctx)
286 struct alloc_cache* a, *na;
290 /* see if bg thread is created and if threads have been killed */
291 /* no locks, because those may be held by terminated threads */
292 /* for processes the read pipe is closed and we see that on read */
294 if(ctx->created_bg && ctx->dothread) {
295 if(pthread_kill(ctx->bg_tid, 0) == ESRCH) {
296 /* thread has been killed */
300 #endif /* HAVE_PTHREAD */
303 libworker_delete_event(ctx->event_worker);
305 modstack_desetup(&ctx->mods, ctx->env);
309 a->super = &ctx->superalloc;
314 local_zones_delete(ctx->local_zones);
315 lock_basic_destroy(&ctx->qqpipe_lock);
316 lock_basic_destroy(&ctx->rrpipe_lock);
317 lock_basic_destroy(&ctx->cfglock);
318 tube_delete(ctx->qq_pipe);
319 tube_delete(ctx->rr_pipe);
321 slabhash_delete(ctx->env->msg_cache);
322 rrset_cache_delete(ctx->env->rrset_cache);
323 infra_delete(ctx->env->infra_cache);
324 config_delete(ctx->env->cfg);
325 edns_known_options_delete(ctx->env);
326 auth_zones_delete(ctx->env->auth_zones);
329 ub_randfree(ctx->seed_rnd);
330 alloc_clear(&ctx->superalloc);
331 traverse_postorder(&ctx->queries, delq, NULL);
332 if(ctx_logfile_overridden) {
334 ctx_logfile_overridden = 0;
336 if(ctx->event_base_malloced)
337 free(ctx->event_base);
345 ub_ctx_set_option(struct ub_ctx* ctx, const char* opt, const char* val)
347 lock_basic_lock(&ctx->cfglock);
349 lock_basic_unlock(&ctx->cfglock);
350 return UB_AFTERFINAL;
352 if(!config_set_option(ctx->env->cfg, opt, val)) {
353 lock_basic_unlock(&ctx->cfglock);
356 lock_basic_unlock(&ctx->cfglock);
361 ub_ctx_get_option(struct ub_ctx* ctx, const char* opt, char** str)
364 lock_basic_lock(&ctx->cfglock);
365 r = config_get_option_collate(ctx->env->cfg, opt, str);
366 lock_basic_unlock(&ctx->cfglock);
367 if(r == 0) r = UB_NOERROR;
368 else if(r == 1) r = UB_SYNTAX;
369 else if(r == 2) r = UB_NOMEM;
374 ub_ctx_config(struct ub_ctx* ctx, const char* fname)
376 lock_basic_lock(&ctx->cfglock);
378 lock_basic_unlock(&ctx->cfglock);
379 return UB_AFTERFINAL;
381 if(!config_read(ctx->env->cfg, fname, NULL)) {
382 lock_basic_unlock(&ctx->cfglock);
385 lock_basic_unlock(&ctx->cfglock);
390 ub_ctx_add_ta(struct ub_ctx* ctx, const char* ta)
392 char* dup = strdup(ta);
393 if(!dup) return UB_NOMEM;
394 lock_basic_lock(&ctx->cfglock);
396 lock_basic_unlock(&ctx->cfglock);
398 return UB_AFTERFINAL;
400 if(!cfg_strlist_insert(&ctx->env->cfg->trust_anchor_list, dup)) {
401 lock_basic_unlock(&ctx->cfglock);
404 lock_basic_unlock(&ctx->cfglock);
409 ub_ctx_add_ta_file(struct ub_ctx* ctx, const char* fname)
411 char* dup = strdup(fname);
412 if(!dup) return UB_NOMEM;
413 lock_basic_lock(&ctx->cfglock);
415 lock_basic_unlock(&ctx->cfglock);
417 return UB_AFTERFINAL;
419 if(!cfg_strlist_insert(&ctx->env->cfg->trust_anchor_file_list, dup)) {
420 lock_basic_unlock(&ctx->cfglock);
423 lock_basic_unlock(&ctx->cfglock);
427 int ub_ctx_add_ta_autr(struct ub_ctx* ctx, const char* fname)
429 char* dup = strdup(fname);
430 if(!dup) return UB_NOMEM;
431 lock_basic_lock(&ctx->cfglock);
433 lock_basic_unlock(&ctx->cfglock);
435 return UB_AFTERFINAL;
437 if(!cfg_strlist_insert(&ctx->env->cfg->auto_trust_anchor_file_list,
439 lock_basic_unlock(&ctx->cfglock);
442 lock_basic_unlock(&ctx->cfglock);
447 ub_ctx_trustedkeys(struct ub_ctx* ctx, const char* fname)
449 char* dup = strdup(fname);
450 if(!dup) return UB_NOMEM;
451 lock_basic_lock(&ctx->cfglock);
453 lock_basic_unlock(&ctx->cfglock);
455 return UB_AFTERFINAL;
457 if(!cfg_strlist_insert(&ctx->env->cfg->trusted_keys_file_list, dup)) {
458 lock_basic_unlock(&ctx->cfglock);
461 lock_basic_unlock(&ctx->cfglock);
466 ub_ctx_debuglevel(struct ub_ctx* ctx, int d)
468 lock_basic_lock(&ctx->cfglock);
470 ctx->env->cfg->verbosity = d;
471 lock_basic_unlock(&ctx->cfglock);
475 int ub_ctx_debugout(struct ub_ctx* ctx, void* out)
477 lock_basic_lock(&ctx->cfglock);
478 log_file((FILE*)out);
479 ctx_logfile_overridden = 1;
480 ctx->logfile_override = 1;
482 lock_basic_unlock(&ctx->cfglock);
487 ub_ctx_async(struct ub_ctx* ctx, int dothread)
489 #ifdef THREADS_DISABLED
490 if(dothread) /* cannot do threading */
493 lock_basic_lock(&ctx->cfglock);
495 lock_basic_unlock(&ctx->cfglock);
496 return UB_AFTERFINAL;
498 ctx->dothread = dothread;
499 lock_basic_unlock(&ctx->cfglock);
504 ub_poll(struct ub_ctx* ctx)
506 /* no need to hold lock while testing for readability. */
507 return tube_poll(ctx->rr_pipe);
511 ub_fd(struct ub_ctx* ctx)
513 return tube_read_fd(ctx->rr_pipe);
516 /** process answer from bg worker */
518 process_answer_detail(struct ub_ctx* ctx, uint8_t* msg, uint32_t len,
519 ub_callback_type* cb, void** cbarg, int* err,
520 struct ub_result** res)
523 if(context_serial_getcmd(msg, len) != UB_LIBCMD_ANSWER) {
524 log_err("error: bad data from bg worker %d",
525 (int)context_serial_getcmd(msg, len));
529 lock_basic_lock(&ctx->cfglock);
530 q = context_deserialize_answer(ctx, msg, len, err);
532 lock_basic_unlock(&ctx->cfglock);
533 /* probably simply the lookup that failed, i.e.
534 * response returned before cancel was sent out, so noerror */
537 log_assert(q->async);
539 /* grab cb while locked */
549 ub_resolve_free(q->res);
551 /* parse the message, extract rcode, fill result */
552 sldns_buffer* buf = sldns_buffer_new(q->msg_len);
553 struct regional* region = regional_create();
555 (*res)->rcode = LDNS_RCODE_SERVFAIL;
557 sldns_buffer_clear(buf);
558 sldns_buffer_write(buf, q->msg, q->msg_len);
559 sldns_buffer_flip(buf);
560 libworker_enter_result(*res, buf, region,
563 (*res)->answer_packet = q->msg;
564 (*res)->answer_len = (int)q->msg_len;
566 sldns_buffer_free(buf);
567 regional_destroy(region);
570 /* delete the q from list */
571 (void)rbtree_delete(&ctx->queries, q->node.key);
573 context_query_delete(q);
574 lock_basic_unlock(&ctx->cfglock);
577 ub_resolve_free(*res);
581 /** process answer from bg worker */
583 process_answer(struct ub_ctx* ctx, uint8_t* msg, uint32_t len)
588 struct ub_result* res;
591 r = process_answer_detail(ctx, msg, len, &cb, &cbarg, &err, &res);
593 /* no locks held while calling callback, so that library is
596 (*cb)(cbarg, err, res);
602 ub_process(struct ub_ctx* ctx)
609 lock_basic_lock(&ctx->rrpipe_lock);
610 r = tube_read_msg(ctx->rr_pipe, &msg, &len, 1);
611 lock_basic_unlock(&ctx->rrpipe_lock);
616 if(!process_answer(ctx, msg, len)) {
626 ub_wait(struct ub_ctx* ctx)
631 struct ub_result* res;
635 /* this is basically the same loop as _process(), but with changes.
636 * holds the rrpipe lock and waits with tube_wait */
638 lock_basic_lock(&ctx->rrpipe_lock);
639 lock_basic_lock(&ctx->cfglock);
640 if(ctx->num_async == 0) {
641 lock_basic_unlock(&ctx->cfglock);
642 lock_basic_unlock(&ctx->rrpipe_lock);
645 lock_basic_unlock(&ctx->cfglock);
647 /* keep rrpipe locked, while
648 * o waiting for pipe readable
650 * o possibly decrementing num_async
651 * do callback without lock
653 r = tube_wait(ctx->rr_pipe);
655 r = tube_read_msg(ctx->rr_pipe, &msg, &len, 1);
657 lock_basic_unlock(&ctx->rrpipe_lock);
661 lock_basic_unlock(&ctx->rrpipe_lock);
664 r = process_answer_detail(ctx, msg, len,
665 &cb, &cbarg, &err, &res);
666 lock_basic_unlock(&ctx->rrpipe_lock);
671 (*cb)(cbarg, err, res);
673 lock_basic_unlock(&ctx->rrpipe_lock);
680 ub_resolve(struct ub_ctx* ctx, const char* name, int rrtype,
681 int rrclass, struct ub_result** result)
687 lock_basic_lock(&ctx->cfglock);
688 if(!ctx->finalized) {
689 r = context_finalize(ctx);
691 lock_basic_unlock(&ctx->cfglock);
695 /* create new ctx_query and attempt to add to the list */
696 lock_basic_unlock(&ctx->cfglock);
697 q = context_new(ctx, name, rrtype, rrclass, NULL, NULL, NULL);
700 /* become a resolver thread for a bit */
702 r = libworker_fg(ctx, q);
704 lock_basic_lock(&ctx->cfglock);
705 (void)rbtree_delete(&ctx->queries, q->node.key);
706 context_query_delete(q);
707 lock_basic_unlock(&ctx->cfglock);
710 q->res->answer_packet = q->msg;
711 q->res->answer_len = (int)q->msg_len;
716 lock_basic_lock(&ctx->cfglock);
717 (void)rbtree_delete(&ctx->queries, q->node.key);
718 context_query_delete(q);
719 lock_basic_unlock(&ctx->cfglock);
724 ub_resolve_event(struct ub_ctx* ctx, const char* name, int rrtype,
725 int rrclass, void* mydata, ub_event_callback_type callback,
733 lock_basic_lock(&ctx->cfglock);
734 if(!ctx->finalized) {
735 r = context_finalize(ctx);
737 lock_basic_unlock(&ctx->cfglock);
741 lock_basic_unlock(&ctx->cfglock);
742 if(!ctx->event_worker) {
743 ctx->event_worker = libworker_create_event(ctx,
745 if(!ctx->event_worker) {
750 /* set time in case answer comes from cache */
751 ub_comm_base_now(ctx->event_worker->base);
753 /* create new ctx_query and attempt to add to the list */
754 q = context_new(ctx, name, rrtype, rrclass, NULL, callback, mydata);
759 if((r=libworker_attach_mesh(ctx, q, async_id)) != 0)
766 ub_resolve_async(struct ub_ctx* ctx, const char* name, int rrtype,
767 int rrclass, void* mydata, ub_callback_type callback, int* async_id)
775 lock_basic_lock(&ctx->cfglock);
776 if(!ctx->finalized) {
777 int r = context_finalize(ctx);
779 lock_basic_unlock(&ctx->cfglock);
783 if(!ctx->created_bg) {
786 lock_basic_unlock(&ctx->cfglock);
787 r = libworker_bg(ctx);
789 lock_basic_lock(&ctx->cfglock);
791 lock_basic_unlock(&ctx->cfglock);
795 lock_basic_unlock(&ctx->cfglock);
798 /* create new ctx_query and attempt to add to the list */
799 q = context_new(ctx, name, rrtype, rrclass, callback, NULL, mydata);
803 /* write over pipe to background worker */
804 lock_basic_lock(&ctx->cfglock);
805 msg = context_serialize_new_query(q, &len);
807 (void)rbtree_delete(&ctx->queries, q->node.key);
809 context_query_delete(q);
810 lock_basic_unlock(&ctx->cfglock);
814 *async_id = q->querynum;
815 lock_basic_unlock(&ctx->cfglock);
817 lock_basic_lock(&ctx->qqpipe_lock);
818 if(!tube_write_msg(ctx->qq_pipe, msg, len, 0)) {
819 lock_basic_unlock(&ctx->qqpipe_lock);
823 lock_basic_unlock(&ctx->qqpipe_lock);
829 ub_cancel(struct ub_ctx* ctx, int async_id)
834 lock_basic_lock(&ctx->cfglock);
835 q = (struct ctx_query*)rbtree_search(&ctx->queries, &async_id);
836 if(!q || !q->async) {
837 /* it is not there, so nothing to do */
838 lock_basic_unlock(&ctx->cfglock);
841 log_assert(q->async);
845 if(!ctx->dothread) { /* if forked */
846 (void)rbtree_delete(&ctx->queries, q->node.key);
848 msg = context_serialize_cancel(q, &len);
849 context_query_delete(q);
850 lock_basic_unlock(&ctx->cfglock);
854 /* send cancel to background worker */
855 lock_basic_lock(&ctx->qqpipe_lock);
856 if(!tube_write_msg(ctx->qq_pipe, msg, len, 0)) {
857 lock_basic_unlock(&ctx->qqpipe_lock);
861 lock_basic_unlock(&ctx->qqpipe_lock);
864 lock_basic_unlock(&ctx->cfglock);
870 ub_resolve_free(struct ub_result* result)
875 if(result->canonname != result->qname)
876 free(result->canonname);
878 for(p = result->data; *p; p++)
882 free(result->answer_packet);
883 free(result->why_bogus);
891 case UB_NOERROR: return "no error";
892 case UB_SOCKET: return "socket io error";
893 case UB_NOMEM: return "out of memory";
894 case UB_SYNTAX: return "syntax error";
895 case UB_SERVFAIL: return "server failure";
896 case UB_FORKFAIL: return "could not fork";
897 case UB_INITFAIL: return "initialization failure";
898 case UB_AFTERFINAL: return "setting change after finalize";
899 case UB_PIPE: return "error in pipe communication with async";
900 case UB_READFILE: return "error reading file";
901 case UB_NOID: return "error async_id does not exist";
902 default: return "unknown error";
907 ub_ctx_set_fwd(struct ub_ctx* ctx, const char* addr)
909 struct sockaddr_storage storage;
911 struct config_stub* s;
913 lock_basic_lock(&ctx->cfglock);
915 lock_basic_unlock(&ctx->cfglock);
917 return UB_AFTERFINAL;
920 /* disable fwd mode - the root stub should be first. */
921 if(ctx->env->cfg->forwards &&
922 strcmp(ctx->env->cfg->forwards->name, ".") == 0) {
923 s = ctx->env->cfg->forwards;
924 ctx->env->cfg->forwards = s->next;
928 lock_basic_unlock(&ctx->cfglock);
931 lock_basic_unlock(&ctx->cfglock);
933 /* check syntax for addr */
934 if(!extstrtoaddr(addr, &storage, &stlen)) {
939 /* it parses, add root stub in front of list */
940 lock_basic_lock(&ctx->cfglock);
941 if(!ctx->env->cfg->forwards ||
942 strcmp(ctx->env->cfg->forwards->name, ".") != 0) {
943 s = calloc(1, sizeof(*s));
945 lock_basic_unlock(&ctx->cfglock);
949 s->name = strdup(".");
952 lock_basic_unlock(&ctx->cfglock);
956 s->next = ctx->env->cfg->forwards;
957 ctx->env->cfg->forwards = s;
959 log_assert(ctx->env->cfg->forwards);
960 s = ctx->env->cfg->forwards;
964 lock_basic_unlock(&ctx->cfglock);
968 if(!cfg_strlist_insert(&s->addrs, dupl)) {
969 lock_basic_unlock(&ctx->cfglock);
973 lock_basic_unlock(&ctx->cfglock);
977 int ub_ctx_set_tls(struct ub_ctx* ctx, int tls)
979 lock_basic_lock(&ctx->cfglock);
981 lock_basic_unlock(&ctx->cfglock);
983 return UB_AFTERFINAL;
985 ctx->env->cfg->ssl_upstream = tls;
986 lock_basic_unlock(&ctx->cfglock);
990 int ub_ctx_set_stub(struct ub_ctx* ctx, const char* zone, const char* addr,
994 struct config_stub **prev, *elem;
996 /* check syntax for zone name */
1001 if(!parse_dname(zone, &nm, &nmlen, &nmlabs)) {
1010 /* check syntax for addr (if not NULL) */
1012 struct sockaddr_storage storage;
1014 if(!extstrtoaddr(addr, &storage, &stlen)) {
1020 lock_basic_lock(&ctx->cfglock);
1021 if(ctx->finalized) {
1022 lock_basic_unlock(&ctx->cfglock);
1024 return UB_AFTERFINAL;
1027 /* arguments all right, now find or add the stub */
1028 prev = &ctx->env->cfg->stubs;
1029 elem = cfg_stub_find(&prev, zone);
1030 if(!elem && !addr) {
1031 /* not found and we want to delete, nothing to do */
1032 lock_basic_unlock(&ctx->cfglock);
1034 } else if(elem && !addr) {
1035 /* found, and we want to delete */
1037 config_delstub(elem);
1038 lock_basic_unlock(&ctx->cfglock);
1041 /* not found, create the stub entry */
1042 elem=(struct config_stub*)calloc(1, sizeof(struct config_stub));
1043 if(elem) elem->name = strdup(zone);
1044 if(!elem || !elem->name) {
1046 lock_basic_unlock(&ctx->cfglock);
1050 elem->next = ctx->env->cfg->stubs;
1051 ctx->env->cfg->stubs = elem;
1054 /* add the address to the list and set settings */
1055 elem->isprime = isprime;
1058 lock_basic_unlock(&ctx->cfglock);
1062 if(!cfg_strlist_insert(&elem->addrs, a)) {
1063 lock_basic_unlock(&ctx->cfglock);
1067 lock_basic_unlock(&ctx->cfglock);
1072 ub_ctx_resolvconf(struct ub_ctx* ctx, const char* fname)
1081 #if !defined(UB_ON_WINDOWS) || !defined(HAVE_WINDOWS_H)
1082 fname = "/etc/resolv.conf";
1085 ULONG buflen = sizeof(*info);
1086 IP_ADDR_STRING *ptr;
1088 info = (FIXED_INFO *) malloc(sizeof (FIXED_INFO));
1092 if (GetNetworkParams(info, &buflen) == ERROR_BUFFER_OVERFLOW) {
1094 info = (FIXED_INFO *) malloc(buflen);
1099 if (GetNetworkParams(info, &buflen) == NO_ERROR) {
1101 ptr = &(info->DnsServerList);
1104 if((retval=ub_ctx_set_fwd(ctx,
1105 ptr->IpAddress.String))!=0) {
1118 #endif /* WINDOWS */
1120 in = fopen(fname, "r");
1122 /* error in errno! perror(fname) */
1125 while(fgets(buf, (int)sizeof(buf), in)) {
1126 buf[sizeof(buf)-1] = 0;
1128 while(*parse == ' ' || *parse == '\t')
1130 if(strncmp(parse, "nameserver", 10) == 0) {
1132 parse += 10; /* skip 'nameserver' */
1133 /* skip whitespace */
1134 while(*parse == ' ' || *parse == '\t')
1137 /* skip [0-9a-fA-F.:]*, i.e. IP4 and IP6 address */
1138 while(isxdigit((unsigned char)*parse) || *parse=='.' || *parse==':')
1140 /* terminate after the address, remove newline */
1143 if((r = ub_ctx_set_fwd(ctx, addr)) != UB_NOERROR) {
1151 /* from resolv.conf(5) if none given, use localhost */
1152 return ub_ctx_set_fwd(ctx, "127.0.0.1");
1158 ub_ctx_hosts(struct ub_ctx* ctx, const char* fname)
1161 char buf[1024], ldata[2048];
1162 char* parse, *addr, *name, *ins;
1163 lock_basic_lock(&ctx->cfglock);
1164 if(ctx->finalized) {
1165 lock_basic_unlock(&ctx->cfglock);
1167 return UB_AFTERFINAL;
1169 lock_basic_unlock(&ctx->cfglock);
1171 #if defined(UB_ON_WINDOWS) && defined(HAVE_WINDOWS_H)
1173 * If this is Windows NT/XP/2K it's in
1174 * %WINDIR%\system32\drivers\etc\hosts.
1175 * If this is Windows 95/98/Me it's in %WINDIR%\hosts.
1177 name = getenv("WINDIR");
1180 snprintf(buf, sizeof(buf), "%s%s", name,
1181 "\\system32\\drivers\\etc\\hosts");
1182 if((retval=ub_ctx_hosts(ctx, buf)) !=0 ) {
1183 snprintf(buf, sizeof(buf), "%s%s", name,
1185 retval=ub_ctx_hosts(ctx, buf);
1191 fname = "/etc/hosts";
1194 in = fopen(fname, "r");
1196 /* error in errno! perror(fname) */
1199 while(fgets(buf, (int)sizeof(buf), in)) {
1200 buf[sizeof(buf)-1] = 0;
1202 while(*parse == ' ' || *parse == '\t')
1205 continue; /* skip comment */
1206 /* format: <addr> spaces <name> spaces <name> ... */
1209 while(isxdigit((unsigned char)*parse) || *parse == '.' || *parse == ':')
1213 if(*parse == '\n' || *parse == 0)
1216 continue; /* ignore macOSX fe80::1%lo0 localhost */
1217 if(*parse != ' ' && *parse != '\t') {
1218 /* must have whitespace after address */
1223 *parse++ = 0; /* end delimiter for addr ... */
1224 /* go to names and add them */
1226 while(*parse == ' ' || *parse == '\t' || *parse=='\n'
1229 if(*parse == 0 || *parse == '#')
1231 /* skip name, allows (too) many printable characters */
1233 while('!' <= *parse && *parse <= '~')
1236 *parse++ = 0; /* end delimiter for name */
1237 snprintf(ldata, sizeof(ldata), "%s %s %s",
1238 name, str_is_ip6(addr)?"AAAA":"A", addr);
1239 ins = strdup(ldata);
1246 lock_basic_lock(&ctx->cfglock);
1247 if(!cfg_strlist_insert(&ctx->env->cfg->local_data,
1249 lock_basic_unlock(&ctx->cfglock);
1254 lock_basic_unlock(&ctx->cfglock);
1261 /** finalize the context, if not already finalized */
1262 static int ub_ctx_finalize(struct ub_ctx* ctx)
1265 lock_basic_lock(&ctx->cfglock);
1266 if (!ctx->finalized) {
1267 res = context_finalize(ctx);
1269 lock_basic_unlock(&ctx->cfglock);
1273 /* Print local zones and RR data */
1274 int ub_ctx_print_local_zones(struct ub_ctx* ctx)
1276 int res = ub_ctx_finalize(ctx);
1277 if (res) return res;
1279 local_zones_print(ctx->local_zones);
1284 /* Add a new zone */
1285 int ub_ctx_zone_add(struct ub_ctx* ctx, const char *zone_name,
1286 const char *zone_type)
1288 enum localzone_type t;
1289 struct local_zone* z;
1294 int res = ub_ctx_finalize(ctx);
1295 if (res) return res;
1297 if(!local_zone_str2type(zone_type, &t)) {
1301 if(!parse_dname(zone_name, &nm, &nmlen, &nmlabs)) {
1305 lock_rw_wrlock(&ctx->local_zones->lock);
1306 if((z=local_zones_find(ctx->local_zones, nm, nmlen, nmlabs,
1307 LDNS_RR_CLASS_IN))) {
1308 /* already present in tree */
1309 lock_rw_wrlock(&z->lock);
1310 z->type = t; /* update type anyway */
1311 lock_rw_unlock(&z->lock);
1312 lock_rw_unlock(&ctx->local_zones->lock);
1316 if(!local_zones_add_zone(ctx->local_zones, nm, nmlen, nmlabs,
1317 LDNS_RR_CLASS_IN, t)) {
1318 lock_rw_unlock(&ctx->local_zones->lock);
1321 lock_rw_unlock(&ctx->local_zones->lock);
1326 int ub_ctx_zone_remove(struct ub_ctx* ctx, const char *zone_name)
1328 struct local_zone* z;
1333 int res = ub_ctx_finalize(ctx);
1334 if (res) return res;
1336 if(!parse_dname(zone_name, &nm, &nmlen, &nmlabs)) {
1340 lock_rw_wrlock(&ctx->local_zones->lock);
1341 if((z=local_zones_find(ctx->local_zones, nm, nmlen, nmlabs,
1342 LDNS_RR_CLASS_IN))) {
1343 /* present in tree */
1344 local_zones_del_zone(ctx->local_zones, z);
1346 lock_rw_unlock(&ctx->local_zones->lock);
1351 /* Add new RR data */
1352 int ub_ctx_data_add(struct ub_ctx* ctx, const char *data)
1354 int res = ub_ctx_finalize(ctx);
1355 if (res) return res;
1357 res = local_zones_add_RR(ctx->local_zones, data);
1358 return (!res) ? UB_NOMEM : UB_NOERROR;
1361 /* Remove RR data */
1362 int ub_ctx_data_remove(struct ub_ctx* ctx, const char *data)
1367 int res = ub_ctx_finalize(ctx);
1368 if (res) return res;
1370 if(!parse_dname(data, &nm, &nmlen, &nmlabs))
1373 local_zones_del_data(ctx->local_zones, nm, nmlen, nmlabs,
1380 const char* ub_version(void)
1382 return PACKAGE_VERSION;
1386 ub_ctx_set_event(struct ub_ctx* ctx, struct event_base* base) {
1387 struct ub_event_base* new_base;
1389 if (!ctx || !ctx->event_base || !base) {
1392 if (ub_libevent_get_event_base(ctx->event_base) == base) {
1397 lock_basic_lock(&ctx->cfglock);
1398 /* destroy the current worker - safe to pass in NULL */
1399 libworker_delete_event(ctx->event_worker);
1400 ctx->event_worker = NULL;
1401 new_base = ub_libevent_event_base(base);
1403 ctx->event_base = new_base;
1404 ctx->created_bg = 0;
1406 lock_basic_unlock(&ctx->cfglock);
1407 return new_base ? UB_NOERROR : UB_INITFAIL;