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 /** create context functionality, but no pipes */
83 static struct ub_ctx* ub_ctx_create_nopipe(void)
93 log_init(NULL, 0, NULL); /* logs to stderr */
94 log_ident_set("libunbound");
96 if((r = WSAStartup(MAKEWORD(2,2), &wsa_data)) != 0) {
97 log_err("could not init winsock. WSAStartup: %s",
102 verbosity = 0; /* errors only */
104 ctx = (struct ub_ctx*)calloc(1, sizeof(*ctx));
109 alloc_init(&ctx->superalloc, NULL, 0);
110 seed = (unsigned int)time(NULL) ^ (unsigned int)getpid();
111 if(!(ctx->seed_rnd = ub_initstate(seed, NULL))) {
113 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) {
230 delq(rbnode_type* n, void* ATTR_UNUSED(arg))
232 struct ctx_query* q = (struct ctx_query*)n;
233 context_query_delete(q);
236 /** stop the bg thread */
237 static void ub_stop_bg(struct ub_ctx* ctx)
239 /* stop the bg thread */
240 lock_basic_lock(&ctx->cfglock);
241 if(ctx->created_bg) {
244 uint32_t cmd = UB_LIBCMD_QUIT;
245 lock_basic_unlock(&ctx->cfglock);
246 lock_basic_lock(&ctx->qqpipe_lock);
247 (void)tube_write_msg(ctx->qq_pipe, (uint8_t*)&cmd,
248 (uint32_t)sizeof(cmd), 0);
249 lock_basic_unlock(&ctx->qqpipe_lock);
250 lock_basic_lock(&ctx->rrpipe_lock);
251 while(tube_read_msg(ctx->rr_pipe, &msg, &len, 0)) {
252 /* discard all results except a quit confirm */
253 if(context_serial_getcmd(msg, len) == UB_LIBCMD_QUIT) {
259 lock_basic_unlock(&ctx->rrpipe_lock);
261 /* if bg worker is a thread, wait for it to exit, so that all
262 * resources are really gone. */
263 lock_basic_lock(&ctx->cfglock);
265 lock_basic_unlock(&ctx->cfglock);
266 ub_thread_join(ctx->bg_tid);
268 lock_basic_unlock(&ctx->cfglock);
269 #ifndef UB_ON_WINDOWS
270 if(waitpid(ctx->bg_pid, NULL, 0) == -1) {
272 log_err("waitpid: %s", strerror(errno));
278 lock_basic_unlock(&ctx->cfglock);
283 ub_ctx_delete(struct ub_ctx* ctx)
285 struct alloc_cache* a, *na;
289 /* see if bg thread is created and if threads have been killed */
290 /* no locks, because those may be held by terminated threads */
291 /* for processes the read pipe is closed and we see that on read */
293 if(ctx->created_bg && ctx->dothread) {
294 if(pthread_kill(ctx->bg_tid, 0) == ESRCH) {
295 /* thread has been killed */
299 #endif /* HAVE_PTHREAD */
302 libworker_delete_event(ctx->event_worker);
304 modstack_desetup(&ctx->mods, ctx->env);
308 a->super = &ctx->superalloc;
313 local_zones_delete(ctx->local_zones);
314 lock_basic_destroy(&ctx->qqpipe_lock);
315 lock_basic_destroy(&ctx->rrpipe_lock);
316 lock_basic_destroy(&ctx->cfglock);
317 tube_delete(ctx->qq_pipe);
318 tube_delete(ctx->rr_pipe);
320 slabhash_delete(ctx->env->msg_cache);
321 rrset_cache_delete(ctx->env->rrset_cache);
322 infra_delete(ctx->env->infra_cache);
323 config_delete(ctx->env->cfg);
324 edns_known_options_delete(ctx->env);
325 auth_zones_delete(ctx->env->auth_zones);
328 ub_randfree(ctx->seed_rnd);
329 alloc_clear(&ctx->superalloc);
330 traverse_postorder(&ctx->queries, delq, NULL);
338 ub_ctx_set_option(struct ub_ctx* ctx, const char* opt, const char* val)
340 lock_basic_lock(&ctx->cfglock);
342 lock_basic_unlock(&ctx->cfglock);
343 return UB_AFTERFINAL;
345 if(!config_set_option(ctx->env->cfg, opt, val)) {
346 lock_basic_unlock(&ctx->cfglock);
349 lock_basic_unlock(&ctx->cfglock);
354 ub_ctx_get_option(struct ub_ctx* ctx, const char* opt, char** str)
357 lock_basic_lock(&ctx->cfglock);
358 r = config_get_option_collate(ctx->env->cfg, opt, str);
359 lock_basic_unlock(&ctx->cfglock);
360 if(r == 0) r = UB_NOERROR;
361 else if(r == 1) r = UB_SYNTAX;
362 else if(r == 2) r = UB_NOMEM;
367 ub_ctx_config(struct ub_ctx* ctx, const char* fname)
369 lock_basic_lock(&ctx->cfglock);
371 lock_basic_unlock(&ctx->cfglock);
372 return UB_AFTERFINAL;
374 if(!config_read(ctx->env->cfg, fname, NULL)) {
375 lock_basic_unlock(&ctx->cfglock);
378 lock_basic_unlock(&ctx->cfglock);
383 ub_ctx_add_ta(struct ub_ctx* ctx, const char* ta)
385 char* dup = strdup(ta);
386 if(!dup) return UB_NOMEM;
387 lock_basic_lock(&ctx->cfglock);
389 lock_basic_unlock(&ctx->cfglock);
391 return UB_AFTERFINAL;
393 if(!cfg_strlist_insert(&ctx->env->cfg->trust_anchor_list, dup)) {
394 lock_basic_unlock(&ctx->cfglock);
398 lock_basic_unlock(&ctx->cfglock);
403 ub_ctx_add_ta_file(struct ub_ctx* ctx, const char* fname)
405 char* dup = strdup(fname);
406 if(!dup) return UB_NOMEM;
407 lock_basic_lock(&ctx->cfglock);
409 lock_basic_unlock(&ctx->cfglock);
411 return UB_AFTERFINAL;
413 if(!cfg_strlist_insert(&ctx->env->cfg->trust_anchor_file_list, dup)) {
414 lock_basic_unlock(&ctx->cfglock);
418 lock_basic_unlock(&ctx->cfglock);
422 int ub_ctx_add_ta_autr(struct ub_ctx* ctx, const char* fname)
424 char* dup = strdup(fname);
425 if(!dup) return UB_NOMEM;
426 lock_basic_lock(&ctx->cfglock);
428 lock_basic_unlock(&ctx->cfglock);
430 return UB_AFTERFINAL;
432 if(!cfg_strlist_insert(&ctx->env->cfg->auto_trust_anchor_file_list,
434 lock_basic_unlock(&ctx->cfglock);
438 lock_basic_unlock(&ctx->cfglock);
443 ub_ctx_trustedkeys(struct ub_ctx* ctx, const char* fname)
445 char* dup = strdup(fname);
446 if(!dup) return UB_NOMEM;
447 lock_basic_lock(&ctx->cfglock);
449 lock_basic_unlock(&ctx->cfglock);
451 return UB_AFTERFINAL;
453 if(!cfg_strlist_insert(&ctx->env->cfg->trusted_keys_file_list, dup)) {
454 lock_basic_unlock(&ctx->cfglock);
458 lock_basic_unlock(&ctx->cfglock);
463 ub_ctx_debuglevel(struct ub_ctx* ctx, int d)
465 lock_basic_lock(&ctx->cfglock);
467 ctx->env->cfg->verbosity = d;
468 lock_basic_unlock(&ctx->cfglock);
472 int ub_ctx_debugout(struct ub_ctx* ctx, void* out)
474 lock_basic_lock(&ctx->cfglock);
475 log_file((FILE*)out);
476 ctx->logfile_override = 1;
478 lock_basic_unlock(&ctx->cfglock);
483 ub_ctx_async(struct ub_ctx* ctx, int dothread)
485 #ifdef THREADS_DISABLED
486 if(dothread) /* cannot do threading */
489 lock_basic_lock(&ctx->cfglock);
491 lock_basic_unlock(&ctx->cfglock);
492 return UB_AFTERFINAL;
494 ctx->dothread = dothread;
495 lock_basic_unlock(&ctx->cfglock);
500 ub_poll(struct ub_ctx* ctx)
502 /* no need to hold lock while testing for readability. */
503 return tube_poll(ctx->rr_pipe);
507 ub_fd(struct ub_ctx* ctx)
509 return tube_read_fd(ctx->rr_pipe);
512 /** process answer from bg worker */
514 process_answer_detail(struct ub_ctx* ctx, uint8_t* msg, uint32_t len,
515 ub_callback_type* cb, void** cbarg, int* err,
516 struct ub_result** res)
519 if(context_serial_getcmd(msg, len) != UB_LIBCMD_ANSWER) {
520 log_err("error: bad data from bg worker %d",
521 (int)context_serial_getcmd(msg, len));
525 lock_basic_lock(&ctx->cfglock);
526 q = context_deserialize_answer(ctx, msg, len, err);
528 lock_basic_unlock(&ctx->cfglock);
529 /* probably simply the lookup that failed, i.e.
530 * response returned before cancel was sent out, so noerror */
533 log_assert(q->async);
535 /* grab cb while locked */
545 ub_resolve_free(q->res);
547 /* parse the message, extract rcode, fill result */
548 sldns_buffer* buf = sldns_buffer_new(q->msg_len);
549 struct regional* region = regional_create();
551 (*res)->rcode = LDNS_RCODE_SERVFAIL;
553 sldns_buffer_clear(buf);
554 sldns_buffer_write(buf, q->msg, q->msg_len);
555 sldns_buffer_flip(buf);
556 libworker_enter_result(*res, buf, region,
559 (*res)->answer_packet = q->msg;
560 (*res)->answer_len = (int)q->msg_len;
562 sldns_buffer_free(buf);
563 regional_destroy(region);
566 /* delete the q from list */
567 (void)rbtree_delete(&ctx->queries, q->node.key);
569 context_query_delete(q);
570 lock_basic_unlock(&ctx->cfglock);
573 ub_resolve_free(*res);
577 /** process answer from bg worker */
579 process_answer(struct ub_ctx* ctx, uint8_t* msg, uint32_t len)
584 struct ub_result* res;
587 r = process_answer_detail(ctx, msg, len, &cb, &cbarg, &err, &res);
589 /* no locks held while calling callback, so that library is
592 (*cb)(cbarg, err, res);
598 ub_process(struct ub_ctx* ctx)
605 lock_basic_lock(&ctx->rrpipe_lock);
606 r = tube_read_msg(ctx->rr_pipe, &msg, &len, 1);
607 lock_basic_unlock(&ctx->rrpipe_lock);
612 if(!process_answer(ctx, msg, len)) {
622 ub_wait(struct ub_ctx* ctx)
627 struct ub_result* res;
631 /* this is basically the same loop as _process(), but with changes.
632 * holds the rrpipe lock and waits with tube_wait */
634 lock_basic_lock(&ctx->rrpipe_lock);
635 lock_basic_lock(&ctx->cfglock);
636 if(ctx->num_async == 0) {
637 lock_basic_unlock(&ctx->cfglock);
638 lock_basic_unlock(&ctx->rrpipe_lock);
641 lock_basic_unlock(&ctx->cfglock);
643 /* keep rrpipe locked, while
644 * o waiting for pipe readable
646 * o possibly decrementing num_async
647 * do callback without lock
649 r = tube_wait(ctx->rr_pipe);
651 r = tube_read_msg(ctx->rr_pipe, &msg, &len, 1);
653 lock_basic_unlock(&ctx->rrpipe_lock);
657 lock_basic_unlock(&ctx->rrpipe_lock);
660 r = process_answer_detail(ctx, msg, len,
661 &cb, &cbarg, &err, &res);
662 lock_basic_unlock(&ctx->rrpipe_lock);
667 (*cb)(cbarg, err, res);
669 lock_basic_unlock(&ctx->rrpipe_lock);
676 ub_resolve(struct ub_ctx* ctx, const char* name, int rrtype,
677 int rrclass, struct ub_result** result)
683 lock_basic_lock(&ctx->cfglock);
684 if(!ctx->finalized) {
685 r = context_finalize(ctx);
687 lock_basic_unlock(&ctx->cfglock);
691 /* create new ctx_query and attempt to add to the list */
692 lock_basic_unlock(&ctx->cfglock);
693 q = context_new(ctx, name, rrtype, rrclass, NULL, NULL);
696 /* become a resolver thread for a bit */
698 r = libworker_fg(ctx, q);
700 lock_basic_lock(&ctx->cfglock);
701 (void)rbtree_delete(&ctx->queries, q->node.key);
702 context_query_delete(q);
703 lock_basic_unlock(&ctx->cfglock);
706 q->res->answer_packet = q->msg;
707 q->res->answer_len = (int)q->msg_len;
712 lock_basic_lock(&ctx->cfglock);
713 (void)rbtree_delete(&ctx->queries, q->node.key);
714 context_query_delete(q);
715 lock_basic_unlock(&ctx->cfglock);
720 ub_resolve_event(struct ub_ctx* ctx, const char* name, int rrtype,
721 int rrclass, void* mydata, ub_event_callback_type callback,
729 lock_basic_lock(&ctx->cfglock);
730 if(!ctx->finalized) {
731 int r = context_finalize(ctx);
733 lock_basic_unlock(&ctx->cfglock);
737 lock_basic_unlock(&ctx->cfglock);
738 if(!ctx->event_worker) {
739 ctx->event_worker = libworker_create_event(ctx,
741 if(!ctx->event_worker) {
746 /* set time in case answer comes from cache */
747 ub_comm_base_now(ctx->event_worker->base);
749 /* create new ctx_query and attempt to add to the list */
750 q = context_new(ctx, name, rrtype, rrclass, (ub_callback_type)callback,
756 if((r=libworker_attach_mesh(ctx, q, async_id)) != 0)
763 ub_resolve_async(struct ub_ctx* ctx, const char* name, int rrtype,
764 int rrclass, void* mydata, ub_callback_type callback, int* async_id)
772 lock_basic_lock(&ctx->cfglock);
773 if(!ctx->finalized) {
774 int r = context_finalize(ctx);
776 lock_basic_unlock(&ctx->cfglock);
780 if(!ctx->created_bg) {
783 lock_basic_unlock(&ctx->cfglock);
784 r = libworker_bg(ctx);
786 lock_basic_lock(&ctx->cfglock);
788 lock_basic_unlock(&ctx->cfglock);
792 lock_basic_unlock(&ctx->cfglock);
795 /* create new ctx_query and attempt to add to the list */
796 q = context_new(ctx, name, rrtype, rrclass, callback, mydata);
800 /* write over pipe to background worker */
801 lock_basic_lock(&ctx->cfglock);
802 msg = context_serialize_new_query(q, &len);
804 (void)rbtree_delete(&ctx->queries, q->node.key);
806 context_query_delete(q);
807 lock_basic_unlock(&ctx->cfglock);
811 *async_id = q->querynum;
812 lock_basic_unlock(&ctx->cfglock);
814 lock_basic_lock(&ctx->qqpipe_lock);
815 if(!tube_write_msg(ctx->qq_pipe, msg, len, 0)) {
816 lock_basic_unlock(&ctx->qqpipe_lock);
820 lock_basic_unlock(&ctx->qqpipe_lock);
826 ub_cancel(struct ub_ctx* ctx, int async_id)
831 lock_basic_lock(&ctx->cfglock);
832 q = (struct ctx_query*)rbtree_search(&ctx->queries, &async_id);
833 if(!q || !q->async) {
834 /* it is not there, so nothing to do */
835 lock_basic_unlock(&ctx->cfglock);
838 log_assert(q->async);
842 if(!ctx->dothread) { /* if forked */
843 (void)rbtree_delete(&ctx->queries, q->node.key);
845 msg = context_serialize_cancel(q, &len);
846 context_query_delete(q);
847 lock_basic_unlock(&ctx->cfglock);
851 /* send cancel to background worker */
852 lock_basic_lock(&ctx->qqpipe_lock);
853 if(!tube_write_msg(ctx->qq_pipe, msg, len, 0)) {
854 lock_basic_unlock(&ctx->qqpipe_lock);
858 lock_basic_unlock(&ctx->qqpipe_lock);
861 lock_basic_unlock(&ctx->cfglock);
867 ub_resolve_free(struct ub_result* result)
872 if(result->canonname != result->qname)
873 free(result->canonname);
875 for(p = result->data; *p; p++)
879 free(result->answer_packet);
880 free(result->why_bogus);
888 case UB_NOERROR: return "no error";
889 case UB_SOCKET: return "socket io error";
890 case UB_NOMEM: return "out of memory";
891 case UB_SYNTAX: return "syntax error";
892 case UB_SERVFAIL: return "server failure";
893 case UB_FORKFAIL: return "could not fork";
894 case UB_INITFAIL: return "initialization failure";
895 case UB_AFTERFINAL: return "setting change after finalize";
896 case UB_PIPE: return "error in pipe communication with async";
897 case UB_READFILE: return "error reading file";
898 case UB_NOID: return "error async_id does not exist";
899 default: return "unknown error";
904 ub_ctx_set_fwd(struct ub_ctx* ctx, const char* addr)
906 struct sockaddr_storage storage;
908 struct config_stub* s;
910 lock_basic_lock(&ctx->cfglock);
912 lock_basic_unlock(&ctx->cfglock);
914 return UB_AFTERFINAL;
917 /* disable fwd mode - the root stub should be first. */
918 if(ctx->env->cfg->forwards &&
919 strcmp(ctx->env->cfg->forwards->name, ".") == 0) {
920 s = ctx->env->cfg->forwards;
921 ctx->env->cfg->forwards = s->next;
925 lock_basic_unlock(&ctx->cfglock);
928 lock_basic_unlock(&ctx->cfglock);
930 /* check syntax for addr */
931 if(!extstrtoaddr(addr, &storage, &stlen)) {
936 /* it parses, add root stub in front of list */
937 lock_basic_lock(&ctx->cfglock);
938 if(!ctx->env->cfg->forwards ||
939 strcmp(ctx->env->cfg->forwards->name, ".") != 0) {
940 s = calloc(1, sizeof(*s));
942 lock_basic_unlock(&ctx->cfglock);
946 s->name = strdup(".");
949 lock_basic_unlock(&ctx->cfglock);
953 s->next = ctx->env->cfg->forwards;
954 ctx->env->cfg->forwards = s;
956 log_assert(ctx->env->cfg->forwards);
957 s = ctx->env->cfg->forwards;
961 lock_basic_unlock(&ctx->cfglock);
965 if(!cfg_strlist_insert(&s->addrs, dupl)) {
967 lock_basic_unlock(&ctx->cfglock);
971 lock_basic_unlock(&ctx->cfglock);
975 int ub_ctx_set_stub(struct ub_ctx* ctx, const char* zone, const char* addr,
979 struct config_stub **prev, *elem;
981 /* check syntax for zone name */
986 if(!parse_dname(zone, &nm, &nmlen, &nmlabs)) {
995 /* check syntax for addr (if not NULL) */
997 struct sockaddr_storage storage;
999 if(!extstrtoaddr(addr, &storage, &stlen)) {
1005 lock_basic_lock(&ctx->cfglock);
1006 if(ctx->finalized) {
1007 lock_basic_unlock(&ctx->cfglock);
1009 return UB_AFTERFINAL;
1012 /* arguments all right, now find or add the stub */
1013 prev = &ctx->env->cfg->stubs;
1014 elem = cfg_stub_find(&prev, zone);
1015 if(!elem && !addr) {
1016 /* not found and we want to delete, nothing to do */
1017 lock_basic_unlock(&ctx->cfglock);
1019 } else if(elem && !addr) {
1020 /* found, and we want to delete */
1022 config_delstub(elem);
1023 lock_basic_unlock(&ctx->cfglock);
1026 /* not found, create the stub entry */
1027 elem=(struct config_stub*)calloc(1, sizeof(struct config_stub));
1028 if(elem) elem->name = strdup(zone);
1029 if(!elem || !elem->name) {
1031 lock_basic_unlock(&ctx->cfglock);
1035 elem->next = ctx->env->cfg->stubs;
1036 ctx->env->cfg->stubs = elem;
1039 /* add the address to the list and set settings */
1040 elem->isprime = isprime;
1043 lock_basic_unlock(&ctx->cfglock);
1047 if(!cfg_strlist_insert(&elem->addrs, a)) {
1048 lock_basic_unlock(&ctx->cfglock);
1053 lock_basic_unlock(&ctx->cfglock);
1058 ub_ctx_resolvconf(struct ub_ctx* ctx, const char* fname)
1067 #if !defined(UB_ON_WINDOWS) || !defined(HAVE_WINDOWS_H)
1068 fname = "/etc/resolv.conf";
1071 ULONG buflen = sizeof(*info);
1072 IP_ADDR_STRING *ptr;
1074 info = (FIXED_INFO *) malloc(sizeof (FIXED_INFO));
1078 if (GetNetworkParams(info, &buflen) == ERROR_BUFFER_OVERFLOW) {
1080 info = (FIXED_INFO *) malloc(buflen);
1085 if (GetNetworkParams(info, &buflen) == NO_ERROR) {
1087 ptr = &(info->DnsServerList);
1090 if((retval=ub_ctx_set_fwd(ctx,
1091 ptr->IpAddress.String))!=0) {
1104 #endif /* WINDOWS */
1106 in = fopen(fname, "r");
1108 /* error in errno! perror(fname) */
1111 while(fgets(buf, (int)sizeof(buf), in)) {
1112 buf[sizeof(buf)-1] = 0;
1114 while(*parse == ' ' || *parse == '\t')
1116 if(strncmp(parse, "nameserver", 10) == 0) {
1118 parse += 10; /* skip 'nameserver' */
1119 /* skip whitespace */
1120 while(*parse == ' ' || *parse == '\t')
1123 /* skip [0-9a-fA-F.:]*, i.e. IP4 and IP6 address */
1124 while(isxdigit((unsigned char)*parse) || *parse=='.' || *parse==':')
1126 /* terminate after the address, remove newline */
1129 if((r = ub_ctx_set_fwd(ctx, addr)) != UB_NOERROR) {
1137 /* from resolv.conf(5) if none given, use localhost */
1138 return ub_ctx_set_fwd(ctx, "127.0.0.1");
1144 ub_ctx_hosts(struct ub_ctx* ctx, const char* fname)
1147 char buf[1024], ldata[1024];
1148 char* parse, *addr, *name, *ins;
1149 lock_basic_lock(&ctx->cfglock);
1150 if(ctx->finalized) {
1151 lock_basic_unlock(&ctx->cfglock);
1153 return UB_AFTERFINAL;
1155 lock_basic_unlock(&ctx->cfglock);
1157 #if defined(UB_ON_WINDOWS) && defined(HAVE_WINDOWS_H)
1159 * If this is Windows NT/XP/2K it's in
1160 * %WINDIR%\system32\drivers\etc\hosts.
1161 * If this is Windows 95/98/Me it's in %WINDIR%\hosts.
1163 name = getenv("WINDIR");
1166 snprintf(buf, sizeof(buf), "%s%s", name,
1167 "\\system32\\drivers\\etc\\hosts");
1168 if((retval=ub_ctx_hosts(ctx, buf)) !=0 ) {
1169 snprintf(buf, sizeof(buf), "%s%s", name,
1171 retval=ub_ctx_hosts(ctx, buf);
1177 fname = "/etc/hosts";
1180 in = fopen(fname, "r");
1182 /* error in errno! perror(fname) */
1185 while(fgets(buf, (int)sizeof(buf), in)) {
1186 buf[sizeof(buf)-1] = 0;
1188 while(*parse == ' ' || *parse == '\t')
1191 continue; /* skip comment */
1192 /* format: <addr> spaces <name> spaces <name> ... */
1195 while(isxdigit((unsigned char)*parse) || *parse == '.' || *parse == ':')
1199 if(*parse == '\n' || *parse == 0)
1202 continue; /* ignore macOSX fe80::1%lo0 localhost */
1203 if(*parse != ' ' && *parse != '\t') {
1204 /* must have whitespace after address */
1209 *parse++ = 0; /* end delimiter for addr ... */
1210 /* go to names and add them */
1212 while(*parse == ' ' || *parse == '\t' || *parse=='\n'
1215 if(*parse == 0 || *parse == '#')
1217 /* skip name, allows (too) many printable characters */
1219 while('!' <= *parse && *parse <= '~')
1222 *parse++ = 0; /* end delimiter for name */
1223 snprintf(ldata, sizeof(ldata), "%s %s %s",
1224 name, str_is_ip6(addr)?"AAAA":"A", addr);
1225 ins = strdup(ldata);
1232 lock_basic_lock(&ctx->cfglock);
1233 if(!cfg_strlist_insert(&ctx->env->cfg->local_data,
1235 lock_basic_unlock(&ctx->cfglock);
1241 lock_basic_unlock(&ctx->cfglock);
1248 /** finalize the context, if not already finalized */
1249 static int ub_ctx_finalize(struct ub_ctx* ctx)
1252 lock_basic_lock(&ctx->cfglock);
1253 if (!ctx->finalized) {
1254 res = context_finalize(ctx);
1256 lock_basic_unlock(&ctx->cfglock);
1260 /* Print local zones and RR data */
1261 int ub_ctx_print_local_zones(struct ub_ctx* ctx)
1263 int res = ub_ctx_finalize(ctx);
1264 if (res) return res;
1266 local_zones_print(ctx->local_zones);
1271 /* Add a new zone */
1272 int ub_ctx_zone_add(struct ub_ctx* ctx, const char *zone_name,
1273 const char *zone_type)
1275 enum localzone_type t;
1276 struct local_zone* z;
1281 int res = ub_ctx_finalize(ctx);
1282 if (res) return res;
1284 if(!local_zone_str2type(zone_type, &t)) {
1288 if(!parse_dname(zone_name, &nm, &nmlen, &nmlabs)) {
1292 lock_rw_wrlock(&ctx->local_zones->lock);
1293 if((z=local_zones_find(ctx->local_zones, nm, nmlen, nmlabs,
1294 LDNS_RR_CLASS_IN))) {
1295 /* already present in tree */
1296 lock_rw_wrlock(&z->lock);
1297 z->type = t; /* update type anyway */
1298 lock_rw_unlock(&z->lock);
1299 lock_rw_unlock(&ctx->local_zones->lock);
1303 if(!local_zones_add_zone(ctx->local_zones, nm, nmlen, nmlabs,
1304 LDNS_RR_CLASS_IN, t)) {
1305 lock_rw_unlock(&ctx->local_zones->lock);
1308 lock_rw_unlock(&ctx->local_zones->lock);
1313 int ub_ctx_zone_remove(struct ub_ctx* ctx, const char *zone_name)
1315 struct local_zone* z;
1320 int res = ub_ctx_finalize(ctx);
1321 if (res) return res;
1323 if(!parse_dname(zone_name, &nm, &nmlen, &nmlabs)) {
1327 lock_rw_wrlock(&ctx->local_zones->lock);
1328 if((z=local_zones_find(ctx->local_zones, nm, nmlen, nmlabs,
1329 LDNS_RR_CLASS_IN))) {
1330 /* present in tree */
1331 local_zones_del_zone(ctx->local_zones, z);
1333 lock_rw_unlock(&ctx->local_zones->lock);
1338 /* Add new RR data */
1339 int ub_ctx_data_add(struct ub_ctx* ctx, const char *data)
1341 int res = ub_ctx_finalize(ctx);
1342 if (res) return res;
1344 res = local_zones_add_RR(ctx->local_zones, data);
1345 return (!res) ? UB_NOMEM : UB_NOERROR;
1348 /* Remove RR data */
1349 int ub_ctx_data_remove(struct ub_ctx* ctx, const char *data)
1354 int res = ub_ctx_finalize(ctx);
1355 if (res) return res;
1357 if(!parse_dname(data, &nm, &nmlen, &nmlabs))
1360 local_zones_del_data(ctx->local_zones, nm, nmlen, nmlabs,
1367 const char* ub_version(void)
1369 return PACKAGE_VERSION;
1373 ub_ctx_set_event(struct ub_ctx* ctx, struct event_base* base) {
1374 struct ub_event_base* new_base;
1376 if (!ctx || !ctx->event_base || !base) {
1379 if (ub_libevent_get_event_base(ctx->event_base) == base) {
1384 lock_basic_lock(&ctx->cfglock);
1385 /* destroy the current worker - safe to pass in NULL */
1386 libworker_delete_event(ctx->event_worker);
1387 ctx->event_worker = NULL;
1388 new_base = ub_libevent_event_base(base);
1390 ctx->event_base = new_base;
1391 ctx->created_bg = 0;
1393 lock_basic_unlock(&ctx->cfglock);
1394 return new_base ? UB_NOERROR : UB_INITFAIL;