Coverage Report

Created: 2026-12-01 06:34

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/unbound/libunbound/libunbound.c
Line
Count
Source
1
/*
2
 * unbound.c - unbound validating resolver public API implementation
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 functions to resolve DNS queries and 
40
 * validate the answers. Synchronously and asynchronously.
41
 *
42
 */
43
44
/* include the public api first, it should be able to stand alone */
45
#include "libunbound/unbound.h"
46
#include "libunbound/unbound-event.h"
47
#include "config.h"
48
#include <ctype.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"
56
#include "util/log.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 "util/edns.h"
62
#include "services/modstack.h"
63
#include "services/localzone.h"
64
#include "services/cache/infra.h"
65
#include "services/cache/rrset.h"
66
#include "services/authzone.h"
67
#include "services/listen_dnsport.h"
68
#include "sldns/sbuffer.h"
69
#include "iterator/iter_fwd.h"
70
#include "iterator/iter_hints.h"
71
#ifdef HAVE_PTHREAD
72
#include <signal.h>
73
#endif
74
#ifdef HAVE_SYS_WAIT_H
75
#include <sys/wait.h>
76
#endif
77
#ifdef HAVE_TIME_H
78
#include <time.h>
79
#endif
80
81
#if defined(UB_ON_WINDOWS) && defined (HAVE_WINDOWS_H)
82
#include <windows.h>
83
#include <iphlpapi.h>
84
#endif /* UB_ON_WINDOWS */
85
86
/** store that the logfile has a debug override */
87
int ctx_logfile_overridden = 0;
88
89
/** create context functionality, but no pipes */
90
static struct ub_ctx* ub_ctx_create_nopipe(void)
91
0
{
92
0
  struct ub_ctx* ctx;
93
#ifdef USE_WINSOCK
94
  int r;
95
  WSADATA wsa_data;
96
#endif
97
  
98
0
  checklock_start();
99
0
  if(!ctx_logfile_overridden)
100
0
    log_init(NULL, 0, NULL); /* logs to stderr */
101
0
  log_ident_set("libunbound");
102
#ifdef USE_WINSOCK
103
  if((r = WSAStartup(MAKEWORD(2,2), &wsa_data)) != 0) {
104
    log_err("could not init winsock. WSAStartup: %s",
105
      wsa_strerror(r));
106
    return NULL;
107
  }
108
#endif
109
0
  verbosity = NO_VERBOSE; /* errors only */
110
0
  checklock_start();
111
0
  ctx = (struct ub_ctx*)calloc(1, sizeof(*ctx));
112
0
  if(!ctx) {
113
0
    errno = ENOMEM;
114
0
    return NULL;
115
0
  }
116
0
  alloc_init(&ctx->superalloc, NULL, 0);
117
0
  if(!(ctx->seed_rnd = ub_initstate(NULL))) {
118
0
    ub_randfree(ctx->seed_rnd);
119
0
    free(ctx);
120
0
    errno = ENOMEM;
121
0
    return NULL;
122
0
  }
123
0
  lock_basic_init(&ctx->qqpipe_lock);
124
0
  lock_basic_init(&ctx->rrpipe_lock);
125
0
  lock_basic_init(&ctx->cfglock);
126
0
  ctx->env = (struct module_env*)calloc(1, sizeof(*ctx->env));
127
0
  if(!ctx->env) {
128
0
    ub_randfree(ctx->seed_rnd);
129
0
    free(ctx);
130
0
    errno = ENOMEM;
131
0
    return NULL;
132
0
  }
133
0
  ctx->env->cfg = config_create_forlib();
134
0
  if(!ctx->env->cfg) {
135
0
    free(ctx->env);
136
0
    ub_randfree(ctx->seed_rnd);
137
0
    free(ctx);
138
0
    errno = ENOMEM;
139
0
    return NULL;
140
0
  }
141
  /* init edns_known_options */
142
0
  if(!edns_known_options_init(ctx->env)) {
143
0
    config_delete(ctx->env->cfg);
144
0
    free(ctx->env);
145
0
    ub_randfree(ctx->seed_rnd);
146
0
    free(ctx);
147
0
    errno = ENOMEM;
148
0
    return NULL;
149
0
  }
150
0
  ctx->env->auth_zones = auth_zones_create();
151
0
  if(!ctx->env->auth_zones) {
152
0
    edns_known_options_delete(ctx->env);
153
0
    config_delete(ctx->env->cfg);
154
0
    free(ctx->env);
155
0
    ub_randfree(ctx->seed_rnd);
156
0
    free(ctx);
157
0
    errno = ENOMEM;
158
0
    return NULL;
159
0
  }
160
0
  ctx->env->edns_strings = edns_strings_create();
161
0
  if(!ctx->env->edns_strings) {
162
0
    auth_zones_delete(ctx->env->auth_zones);
163
0
    edns_known_options_delete(ctx->env);
164
0
    config_delete(ctx->env->cfg);
165
0
    free(ctx->env);
166
0
    ub_randfree(ctx->seed_rnd);
167
0
    free(ctx);
168
0
    errno = ENOMEM;
169
0
    return NULL;
170
0
  }
171
172
0
  ctx->env->alloc = &ctx->superalloc;
173
0
  ctx->env->worker = NULL;
174
0
  ctx->env->need_to_validate = 0;
175
0
  modstack_init(&ctx->mods);
176
0
  ctx->env->modstack = &ctx->mods;
177
0
  rbtree_init(&ctx->queries, &context_query_cmp);
178
0
  return ctx;
179
0
}
180
181
struct ub_ctx* 
182
ub_ctx_create(void)
183
0
{
184
0
  struct ub_ctx* ctx = ub_ctx_create_nopipe();
185
0
  if(!ctx)
186
0
    return NULL;
187
0
  if((ctx->qq_pipe = tube_create()) == NULL) {
188
0
    int e = errno;
189
0
    ub_randfree(ctx->seed_rnd);
190
0
    config_delete(ctx->env->cfg);
191
0
    modstack_call_deinit(&ctx->mods, ctx->env);
192
0
    modstack_call_destartup(&ctx->mods, ctx->env);
193
0
    modstack_free(&ctx->mods);
194
0
    listen_desetup_locks();
195
0
    edns_known_options_delete(ctx->env);
196
0
    edns_strings_delete(ctx->env->edns_strings);
197
0
    free(ctx->env);
198
0
    free(ctx);
199
0
    errno = e;
200
0
    return NULL;
201
0
  }
202
0
  if((ctx->rr_pipe = tube_create()) == NULL) {
203
0
    int e = errno;
204
0
    tube_delete(ctx->qq_pipe);
205
0
    ub_randfree(ctx->seed_rnd);
206
0
    config_delete(ctx->env->cfg);
207
0
    modstack_call_deinit(&ctx->mods, ctx->env);
208
0
    modstack_call_destartup(&ctx->mods, ctx->env);
209
0
    modstack_free(&ctx->mods);
210
0
    listen_desetup_locks();
211
0
    edns_known_options_delete(ctx->env);
212
0
    edns_strings_delete(ctx->env->edns_strings);
213
0
    free(ctx->env);
214
0
    free(ctx);
215
0
    errno = e;
216
0
    return NULL;
217
0
  }
218
0
  return ctx;
219
0
}
220
221
struct ub_ctx* 
222
ub_ctx_create_ub_event(struct ub_event_base* ueb)
223
0
{
224
0
  struct ub_ctx* ctx = ub_ctx_create_nopipe();
225
0
  if(!ctx)
226
0
    return NULL;
227
  /* no pipes, but we have the locks to make sure everything works */
228
0
  ctx->created_bg = 0;
229
0
  ctx->dothread = 1; /* the processing is in the same process,
230
    makes ub_cancel and ub_ctx_delete do the right thing */
231
0
  ctx->event_base = ueb;
232
0
  return ctx;
233
0
}
234
235
struct ub_ctx* 
236
ub_ctx_create_event(struct event_base* eb)
237
0
{
238
0
  struct ub_ctx* ctx = ub_ctx_create_nopipe();
239
0
  if(!ctx)
240
0
    return NULL;
241
  /* no pipes, but we have the locks to make sure everything works */
242
0
  ctx->created_bg = 0;
243
0
  ctx->dothread = 1; /* the processing is in the same process,
244
    makes ub_cancel and ub_ctx_delete do the right thing */
245
0
  ctx->event_base = ub_libevent_event_base(eb);
246
0
  if (!ctx->event_base) {
247
0
    ub_ctx_delete(ctx);
248
0
    return NULL;
249
0
  }
250
0
  ctx->event_base_malloced = 1;
251
0
  return ctx;
252
0
}
253
  
254
/** delete q */
255
static void
256
delq(rbnode_type* n, void* ATTR_UNUSED(arg))
257
0
{
258
0
  struct ctx_query* q = (struct ctx_query*)n;
259
0
  context_query_delete(q);
260
0
}
261
262
/** stop the bg thread */
263
static void ub_stop_bg(struct ub_ctx* ctx)
264
0
{
265
  /* stop the bg thread */
266
0
  lock_basic_lock(&ctx->cfglock);
267
0
  if(ctx->created_bg) {
268
0
    uint8_t* msg;
269
0
    uint32_t len;
270
0
    uint32_t cmd = UB_LIBCMD_QUIT;
271
0
    lock_basic_unlock(&ctx->cfglock);
272
0
    lock_basic_lock(&ctx->qqpipe_lock);
273
0
    (void)tube_write_msg(ctx->qq_pipe, (uint8_t*)&cmd, 
274
0
      (uint32_t)sizeof(cmd), 0);
275
0
    lock_basic_unlock(&ctx->qqpipe_lock);
276
0
    lock_basic_lock(&ctx->rrpipe_lock);
277
0
    while(tube_read_msg(ctx->rr_pipe, &msg, &len, 0)) {
278
      /* discard all results except a quit confirm */
279
0
      if(context_serial_getcmd(msg, len) == UB_LIBCMD_QUIT) {
280
0
        free(msg);
281
0
        break;
282
0
      }
283
0
      free(msg);
284
0
    }
285
0
    lock_basic_unlock(&ctx->rrpipe_lock);
286
287
    /* if bg worker is a thread, wait for it to exit, so that all
288
     * resources are really gone. */
289
0
    lock_basic_lock(&ctx->cfglock);
290
0
    if(ctx->dothread) {
291
0
      lock_basic_unlock(&ctx->cfglock);
292
0
      ub_thread_join(ctx->bg_tid);
293
0
    } else {
294
0
      lock_basic_unlock(&ctx->cfglock);
295
0
#ifndef UB_ON_WINDOWS
296
0
      if(waitpid(ctx->bg_pid, NULL, 0) == -1) {
297
0
        if(verbosity > 2)
298
0
          log_err("waitpid: %s", strerror(errno));
299
0
      }
300
0
#endif
301
0
    }
302
0
  }
303
0
  else {
304
0
    lock_basic_unlock(&ctx->cfglock);
305
0
  }
306
0
}
307
308
void 
309
ub_ctx_delete(struct ub_ctx* ctx)
310
0
{
311
0
  struct alloc_cache* a, *na;
312
0
  int do_stop = 1;
313
0
  if(!ctx) return;
314
315
  /* if the delete is called but it has forked, and before the fork
316
   * the context was finalized, then the bg worker is not stopped
317
   * from here. There is one worker, but two contexts that refer to
318
   * it and only one should clean up, the one with getpid == pipe_pid.*/
319
0
  if(ctx->created_bg && ctx->pipe_pid != getpid()) {
320
0
    do_stop = 0;
321
0
#ifndef USE_WINSOCK
322
    /* Stop events from getting deregistered, if the backend is
323
     * epoll, the epoll fd is the same as the other process.
324
     * That process should deregister them. */
325
0
    if(ctx->qq_pipe->listen_com)
326
0
      ctx->qq_pipe->listen_com->event_added = 0;
327
0
    if(ctx->qq_pipe->res_com)
328
0
      ctx->qq_pipe->res_com->event_added = 0;
329
0
    if(ctx->rr_pipe->listen_com)
330
0
      ctx->rr_pipe->listen_com->event_added = 0;
331
0
    if(ctx->rr_pipe->res_com)
332
0
      ctx->rr_pipe->res_com->event_added = 0;
333
0
#endif
334
0
  }
335
  /* see if bg thread is created and if threads have been killed */
336
  /* no locks, because those may be held by terminated threads */
337
  /* for processes the read pipe is closed and we see that on read */
338
0
#ifdef HAVE_PTHREAD
339
0
  if(ctx->created_bg && ctx->dothread && do_stop) {
340
0
    if(pthread_kill(ctx->bg_tid, 0) == ESRCH) {
341
      /* thread has been killed */
342
0
      do_stop = 0;
343
0
    }
344
0
  }
345
0
#endif /* HAVE_PTHREAD */
346
0
  if(do_stop)
347
0
    ub_stop_bg(ctx);
348
0
  if(ctx->created_bg && ctx->pipe_pid != getpid() && ctx->thread_worker) {
349
    /* This delete is happening from a different process. Delete
350
     * the thread worker from this process memory space. The
351
     * thread is not there to do so, so it is freed here. */
352
0
    struct ub_event_base* evbase = comm_base_internal(
353
0
      ctx->thread_worker->base);
354
0
    libworker_delete_event(ctx->thread_worker);
355
0
    ctx->thread_worker = NULL;
356
0
#ifdef USE_MINI_EVENT
357
0
    ub_event_base_free(evbase);
358
#else
359
    /* cannot event_base_free, because the epoll_fd cleanup
360
     * in libevent could stop the original event_base in the
361
     * other process from working. */
362
    free(evbase);
363
#endif
364
0
  }
365
0
  libworker_delete_event(ctx->event_worker);
366
367
0
  modstack_call_deinit(&ctx->mods, ctx->env);
368
0
  modstack_call_destartup(&ctx->mods, ctx->env);
369
0
  modstack_free(&ctx->mods);
370
0
  a = ctx->alloc_list;
371
0
  while(a) {
372
0
    na = a->super;
373
0
    a->super = &ctx->superalloc;
374
0
    alloc_clear(a);
375
0
    free(a);
376
0
    a = na;
377
0
  }
378
0
  local_zones_delete(ctx->local_zones);
379
0
  lock_basic_destroy(&ctx->qqpipe_lock);
380
0
  lock_basic_destroy(&ctx->rrpipe_lock);
381
0
  lock_basic_destroy(&ctx->cfglock);
382
0
  tube_delete(ctx->qq_pipe);
383
0
  tube_delete(ctx->rr_pipe);
384
0
  if(ctx->env) {
385
0
    slabhash_delete(ctx->env->msg_cache);
386
0
    rrset_cache_delete(ctx->env->rrset_cache);
387
0
    infra_delete(ctx->env->infra_cache);
388
0
    config_delete(ctx->env->cfg);
389
0
    edns_known_options_delete(ctx->env);
390
0
    edns_strings_delete(ctx->env->edns_strings);
391
0
    forwards_delete(ctx->env->fwds);
392
0
    hints_delete(ctx->env->hints);
393
0
    auth_zones_delete(ctx->env->auth_zones);
394
0
    free(ctx->env);
395
0
  }
396
0
  ub_randfree(ctx->seed_rnd);
397
0
  alloc_clear(&ctx->superalloc);
398
0
  listen_desetup_locks();
399
0
  traverse_postorder(&ctx->queries, delq, NULL);
400
0
  if(ctx_logfile_overridden) {
401
0
    log_file(NULL);
402
0
    ctx_logfile_overridden = 0;
403
0
  }
404
0
  if(ctx->event_base_malloced)
405
0
    free(ctx->event_base);
406
0
  free(ctx);
407
#ifdef USE_WINSOCK
408
  WSACleanup();
409
#endif
410
0
}
411
412
int 
413
ub_ctx_set_option(struct ub_ctx* ctx, const char* opt, const char* val)
414
0
{
415
0
  lock_basic_lock(&ctx->cfglock);
416
0
  if(ctx->finalized) {
417
0
    lock_basic_unlock(&ctx->cfglock);
418
0
    return UB_AFTERFINAL;
419
0
  }
420
0
  if(!config_set_option(ctx->env->cfg, opt, val)) {
421
0
    lock_basic_unlock(&ctx->cfglock);
422
0
    return UB_SYNTAX;
423
0
  }
424
0
  lock_basic_unlock(&ctx->cfglock);
425
0
  return UB_NOERROR;
426
0
}
427
428
int
429
ub_ctx_get_option(struct ub_ctx* ctx, const char* opt, char** str)
430
0
{
431
0
  int r;
432
0
  lock_basic_lock(&ctx->cfglock);
433
0
  r = config_get_option_collate(ctx->env->cfg, opt, str);
434
0
  lock_basic_unlock(&ctx->cfglock);
435
0
  if(r == 0) r = UB_NOERROR;
436
0
  else if(r == 1) r = UB_SYNTAX;
437
0
  else if(r == 2) r = UB_NOMEM;
438
0
  return r;
439
0
}
440
441
int 
442
ub_ctx_config(struct ub_ctx* ctx, const char* fname)
443
0
{
444
0
  lock_basic_lock(&ctx->cfglock);
445
0
  if(ctx->finalized) {
446
0
    lock_basic_unlock(&ctx->cfglock);
447
0
    return UB_AFTERFINAL;
448
0
  }
449
0
  if(!config_read(ctx->env->cfg, fname, NULL)) {
450
0
    lock_basic_unlock(&ctx->cfglock);
451
0
    return UB_SYNTAX;
452
0
  }
453
0
  lock_basic_unlock(&ctx->cfglock);
454
0
  return UB_NOERROR;
455
0
}
456
457
int 
458
ub_ctx_add_ta(struct ub_ctx* ctx, const char* ta)
459
0
{
460
0
  char* dup = strdup(ta);
461
0
  if(!dup) return UB_NOMEM;
462
0
  lock_basic_lock(&ctx->cfglock);
463
0
  if(ctx->finalized) {
464
0
    lock_basic_unlock(&ctx->cfglock);
465
0
    free(dup);
466
0
    return UB_AFTERFINAL;
467
0
  }
468
0
  if(!cfg_strlist_insert(&ctx->env->cfg->trust_anchor_list, dup)) {
469
0
    lock_basic_unlock(&ctx->cfglock);
470
0
    return UB_NOMEM;
471
0
  }
472
0
  lock_basic_unlock(&ctx->cfglock);
473
0
  return UB_NOERROR;
474
0
}
475
476
int 
477
ub_ctx_add_ta_file(struct ub_ctx* ctx, const char* fname)
478
0
{
479
0
  char* dup = strdup(fname);
480
0
  if(!dup) return UB_NOMEM;
481
0
  lock_basic_lock(&ctx->cfglock);
482
0
  if(ctx->finalized) {
483
0
    lock_basic_unlock(&ctx->cfglock);
484
0
    free(dup);
485
0
    return UB_AFTERFINAL;
486
0
  }
487
0
  if(!cfg_strlist_insert(&ctx->env->cfg->trust_anchor_file_list, dup)) {
488
0
    lock_basic_unlock(&ctx->cfglock);
489
0
    return UB_NOMEM;
490
0
  }
491
0
  lock_basic_unlock(&ctx->cfglock);
492
0
  return UB_NOERROR;
493
0
}
494
495
int ub_ctx_add_ta_autr(struct ub_ctx* ctx, const char* fname)
496
0
{
497
0
  char* dup = strdup(fname);
498
0
  if(!dup) return UB_NOMEM;
499
0
  lock_basic_lock(&ctx->cfglock);
500
0
  if(ctx->finalized) {
501
0
    lock_basic_unlock(&ctx->cfglock);
502
0
    free(dup);
503
0
    return UB_AFTERFINAL;
504
0
  }
505
0
  if(!cfg_strlist_insert(&ctx->env->cfg->auto_trust_anchor_file_list,
506
0
    dup)) {
507
0
    lock_basic_unlock(&ctx->cfglock);
508
0
    return UB_NOMEM;
509
0
  }
510
0
  lock_basic_unlock(&ctx->cfglock);
511
0
  return UB_NOERROR;
512
0
}
513
514
int 
515
ub_ctx_trustedkeys(struct ub_ctx* ctx, const char* fname)
516
0
{
517
0
  char* dup = strdup(fname);
518
0
  if(!dup) return UB_NOMEM;
519
0
  lock_basic_lock(&ctx->cfglock);
520
0
  if(ctx->finalized) {
521
0
    lock_basic_unlock(&ctx->cfglock);
522
0
    free(dup);
523
0
    return UB_AFTERFINAL;
524
0
  }
525
0
  if(!cfg_strlist_insert(&ctx->env->cfg->trusted_keys_file_list, dup)) {
526
0
    lock_basic_unlock(&ctx->cfglock);
527
0
    return UB_NOMEM;
528
0
  }
529
0
  lock_basic_unlock(&ctx->cfglock);
530
0
  return UB_NOERROR;
531
0
}
532
533
int
534
ub_ctx_debuglevel(struct ub_ctx* ctx, int d)
535
0
{
536
0
  lock_basic_lock(&ctx->cfglock);
537
0
  verbosity = d;
538
0
  ctx->env->cfg->verbosity = d;
539
0
  lock_basic_unlock(&ctx->cfglock);
540
0
  return UB_NOERROR;
541
0
}
542
543
int ub_ctx_debugout(struct ub_ctx* ctx, void* out)
544
0
{
545
0
  lock_basic_lock(&ctx->cfglock);
546
0
  log_file((FILE*)out);
547
0
  ctx_logfile_overridden = 1;
548
0
  ctx->logfile_override = 1;
549
0
  ctx->log_out = out;
550
0
  lock_basic_unlock(&ctx->cfglock);
551
0
  return UB_NOERROR;
552
0
}
553
554
int 
555
ub_ctx_async(struct ub_ctx* ctx, int dothread)
556
0
{
557
#ifdef THREADS_DISABLED
558
  if(dothread) /* cannot do threading */
559
    return UB_NOERROR;
560
#endif
561
0
  lock_basic_lock(&ctx->cfglock);
562
0
  if(ctx->finalized) {
563
0
    lock_basic_unlock(&ctx->cfglock);
564
0
    return UB_AFTERFINAL;
565
0
  }
566
0
  ctx->dothread = dothread;
567
0
  lock_basic_unlock(&ctx->cfglock);
568
0
  return UB_NOERROR;
569
0
}
570
571
int 
572
ub_poll(struct ub_ctx* ctx)
573
0
{
574
0
  if(!ctx || ctx->event_base)
575
0
    return UB_INITFAIL;
576
  /* no need to hold lock while testing for readability. */
577
0
  return tube_poll(ctx->rr_pipe);
578
0
}
579
580
int 
581
ub_fd(struct ub_ctx* ctx)
582
0
{
583
0
  if(!ctx || ctx->event_base)
584
0
    return -1;
585
0
  return tube_read_fd(ctx->rr_pipe);
586
0
}
587
588
/** process answer from bg worker */
589
static int
590
process_answer_detail(struct ub_ctx* ctx, uint8_t* msg, uint32_t len,
591
  ub_callback_type* cb, void** cbarg, int* err,
592
  struct ub_result** res)
593
0
{
594
0
  struct ctx_query* q;
595
0
  if(context_serial_getcmd(msg, len) != UB_LIBCMD_ANSWER) {
596
0
    log_err("error: bad data from bg worker %d",
597
0
      (int)context_serial_getcmd(msg, len));
598
0
    return 0;
599
0
  }
600
601
0
  lock_basic_lock(&ctx->cfglock);
602
0
  q = context_deserialize_answer(ctx, msg, len, err);
603
0
  if(!q) {
604
0
    lock_basic_unlock(&ctx->cfglock);
605
    /* probably simply the lookup that failed, i.e.
606
     * response returned before cancel was sent out, so noerror */
607
0
    return 1;
608
0
  }
609
0
  log_assert(q->async);
610
611
  /* grab cb while locked */
612
0
  if(q->cancelled) {
613
0
    *cb = NULL;
614
0
    *cbarg = NULL;
615
0
  } else {
616
0
    *cb = q->cb;
617
0
    *cbarg = q->cb_arg;
618
0
  }
619
0
  if(*err) {
620
0
    *res = NULL;
621
0
    ub_resolve_free(q->res);
622
0
  } else {
623
    /* parse the message, extract rcode, fill result */
624
0
    sldns_buffer* buf = sldns_buffer_new(q->msg_len);
625
0
    struct regional* region = regional_create();
626
0
    *res = q->res;
627
0
    (*res)->rcode = LDNS_RCODE_SERVFAIL;
628
0
    if(region && buf) {
629
0
      sldns_buffer_clear(buf);
630
0
      sldns_buffer_write(buf, q->msg, q->msg_len);
631
0
      sldns_buffer_flip(buf);
632
0
      libworker_enter_result(*res, buf, region,
633
0
        q->msg_security);
634
0
    }
635
0
    (*res)->answer_packet = q->msg;
636
0
    (*res)->answer_len = (int)q->msg_len;
637
0
    q->msg = NULL;
638
0
    sldns_buffer_free(buf);
639
0
    regional_destroy(region);
640
0
  }
641
0
  q->res = NULL;
642
  /* delete the q from list */
643
0
  (void)rbtree_delete(&ctx->queries, q->node.key);
644
0
  ctx->num_async--;
645
0
  context_query_delete(q);
646
0
  lock_basic_unlock(&ctx->cfglock);
647
648
0
  if(*cb) return 2;
649
0
  ub_resolve_free(*res);
650
0
  return 1;
651
0
}
652
653
/** process answer from bg worker */
654
static int
655
process_answer(struct ub_ctx* ctx, uint8_t* msg, uint32_t len)
656
0
{
657
0
  int err;
658
0
  ub_callback_type cb;
659
0
  void* cbarg;
660
0
  struct ub_result* res;
661
0
  int r;
662
663
0
  r = process_answer_detail(ctx, msg, len, &cb, &cbarg, &err, &res);
664
665
  /* no locks held while calling callback, so that library is
666
   * re-entrant. */
667
0
  if(r == 2)
668
0
    (*cb)(cbarg, err, res);
669
670
0
  return r;
671
0
}
672
673
int 
674
ub_process(struct ub_ctx* ctx)
675
0
{
676
0
  int r;
677
0
  uint8_t* msg;
678
0
  uint32_t len;
679
0
  if(!ctx || ctx->event_base)
680
0
    return UB_INITFAIL;
681
0
  while(1) {
682
0
    msg = NULL;
683
0
    lock_basic_lock(&ctx->rrpipe_lock);
684
0
    r = tube_read_msg(ctx->rr_pipe, &msg, &len, 1);
685
0
    lock_basic_unlock(&ctx->rrpipe_lock);
686
0
    if(r == 0)
687
0
      return UB_PIPE;
688
0
    else if(r == -1)
689
0
      break;
690
0
    if(!process_answer(ctx, msg, len)) {
691
0
      free(msg);
692
0
      return UB_PIPE;
693
0
    }
694
0
    free(msg);
695
0
  }
696
0
  return UB_NOERROR;
697
0
}
698
699
int 
700
ub_wait(struct ub_ctx* ctx)
701
0
{
702
0
  int err;
703
0
  ub_callback_type cb;
704
0
  void* cbarg;
705
0
  struct ub_result* res;
706
0
  int r;
707
0
  uint8_t* msg;
708
0
  uint32_t len;
709
0
  if(!ctx || ctx->event_base)
710
0
    return UB_INITFAIL;
711
  /* this is basically the same loop as _process(), but with changes.
712
   * holds the rrpipe lock and waits with tube_wait */
713
0
  while(1) {
714
0
    lock_basic_lock(&ctx->rrpipe_lock);
715
0
    lock_basic_lock(&ctx->cfglock);
716
0
    if(ctx->num_async == 0) {
717
0
      lock_basic_unlock(&ctx->cfglock);
718
0
      lock_basic_unlock(&ctx->rrpipe_lock);
719
0
      break;
720
0
    }
721
0
    lock_basic_unlock(&ctx->cfglock);
722
723
    /* keep rrpipe locked, while
724
     *  o waiting for pipe readable
725
     *  o parsing message
726
     *  o possibly decrementing num_async
727
     * do callback without lock
728
     */
729
0
    r = tube_wait(ctx->rr_pipe);
730
0
    if(r) {
731
0
      r = tube_read_msg(ctx->rr_pipe, &msg, &len, 1);
732
0
      if(r == 0) {
733
0
        lock_basic_unlock(&ctx->rrpipe_lock);
734
0
        return UB_PIPE;
735
0
      }
736
0
      if(r == -1) {
737
0
        lock_basic_unlock(&ctx->rrpipe_lock);
738
0
        continue;
739
0
      }
740
0
      r = process_answer_detail(ctx, msg, len, 
741
0
        &cb, &cbarg, &err, &res);
742
0
      lock_basic_unlock(&ctx->rrpipe_lock);
743
0
      free(msg);
744
0
      if(r == 0)
745
0
        return UB_PIPE;
746
0
      if(r == 2)
747
0
        (*cb)(cbarg, err, res);
748
0
    } else {
749
0
      lock_basic_unlock(&ctx->rrpipe_lock);
750
0
    }
751
0
  }
752
0
  return UB_NOERROR;
753
0
}
754
755
int 
756
ub_resolve(struct ub_ctx* ctx, const char* name, int rrtype, 
757
  int rrclass, struct ub_result** result)
758
0
{
759
0
  struct ctx_query* q;
760
0
  int r;
761
0
  *result = NULL;
762
763
0
  lock_basic_lock(&ctx->cfglock);
764
0
  if(!ctx->finalized) {
765
0
    r = context_finalize(ctx);
766
0
    if(r) {
767
0
      lock_basic_unlock(&ctx->cfglock);
768
0
      return r;
769
0
    }
770
0
  }
771
  /* create new ctx_query and attempt to add to the list */
772
0
  lock_basic_unlock(&ctx->cfglock);
773
0
  q = context_new(ctx, name, rrtype, rrclass, NULL, NULL, NULL);
774
0
  if(!q)
775
0
    return UB_NOMEM;
776
  /* become a resolver thread for a bit */
777
778
0
  r = libworker_fg(ctx, q);
779
0
  if(r) {
780
0
    lock_basic_lock(&ctx->cfglock);
781
0
    (void)rbtree_delete(&ctx->queries, q->node.key);
782
0
    context_query_delete(q);
783
0
    lock_basic_unlock(&ctx->cfglock);
784
0
    return r;
785
0
  }
786
0
  q->res->answer_packet = q->msg;
787
0
  q->res->answer_len = (int)q->msg_len;
788
0
  q->msg = NULL;
789
0
  *result = q->res;
790
0
  q->res = NULL;
791
792
0
  lock_basic_lock(&ctx->cfglock);
793
0
  (void)rbtree_delete(&ctx->queries, q->node.key);
794
0
  context_query_delete(q);
795
0
  lock_basic_unlock(&ctx->cfglock);
796
0
  return UB_NOERROR;
797
0
}
798
799
int 
800
ub_resolve_event(struct ub_ctx* ctx, const char* name, int rrtype, 
801
  int rrclass, void* mydata, ub_event_callback_type callback,
802
  int* async_id)
803
0
{
804
0
  struct ctx_query* q;
805
0
  int r;
806
807
0
  if(async_id)
808
0
    *async_id = 0;
809
0
  lock_basic_lock(&ctx->cfglock);
810
0
  if(!ctx->finalized) {
811
0
    r = context_finalize(ctx);
812
0
    if(r) {
813
0
      lock_basic_unlock(&ctx->cfglock);
814
0
      return r;
815
0
    }
816
0
  }
817
0
  lock_basic_unlock(&ctx->cfglock);
818
0
  if(!ctx->event_worker) {
819
0
    ctx->event_worker = libworker_create_event(ctx,
820
0
      ctx->event_base);
821
0
    if(!ctx->event_worker) {
822
0
      return UB_INITFAIL;
823
0
    }
824
0
  }
825
826
  /* set time in case answer comes from cache */
827
0
  ub_comm_base_now(ctx->event_worker->base);
828
829
  /* create new ctx_query and attempt to add to the list */
830
0
  q = context_new(ctx, name, rrtype, rrclass, NULL, callback, mydata);
831
0
  if(!q)
832
0
    return UB_NOMEM;
833
834
  /* attach to mesh */
835
0
  if((r=libworker_attach_mesh(ctx, q, async_id)) != 0)
836
0
    return r;
837
0
  return UB_NOERROR;
838
0
}
839
840
841
int 
842
ub_resolve_async(struct ub_ctx* ctx, const char* name, int rrtype, 
843
  int rrclass, void* mydata, ub_callback_type callback, int* async_id)
844
0
{
845
0
  struct ctx_query* q;
846
0
  uint8_t* msg = NULL;
847
0
  uint32_t len = 0;
848
0
  if(!ctx || ctx->event_base)
849
0
    return UB_INITFAIL;
850
851
0
  if(async_id)
852
0
    *async_id = 0;
853
0
  lock_basic_lock(&ctx->cfglock);
854
0
  if(!ctx->finalized) {
855
0
    int r = context_finalize(ctx);
856
0
    if(r) {
857
0
      lock_basic_unlock(&ctx->cfglock);
858
0
      return r;
859
0
    }
860
0
  }
861
0
  if(!ctx->created_bg) {
862
0
    int r;
863
0
    ctx->created_bg = 1;
864
0
    lock_basic_unlock(&ctx->cfglock);
865
0
    r = libworker_bg(ctx);
866
0
    if(r) {
867
0
      lock_basic_lock(&ctx->cfglock);
868
0
      ctx->created_bg = 0;
869
0
      lock_basic_unlock(&ctx->cfglock);
870
0
      return r;
871
0
    }
872
0
  } else {
873
0
    lock_basic_unlock(&ctx->cfglock);
874
0
  }
875
876
  /* create new ctx_query and attempt to add to the list */
877
0
  q = context_new(ctx, name, rrtype, rrclass, callback, NULL, mydata);
878
0
  if(!q)
879
0
    return UB_NOMEM;
880
881
  /* write over pipe to background worker */
882
0
  lock_basic_lock(&ctx->cfglock);
883
0
  msg = context_serialize_new_query(q, &len);
884
0
  if(!msg) {
885
0
    (void)rbtree_delete(&ctx->queries, q->node.key);
886
0
    ctx->num_async--;
887
0
    context_query_delete(q);
888
0
    lock_basic_unlock(&ctx->cfglock);
889
0
    return UB_NOMEM;
890
0
  }
891
0
  if(async_id)
892
0
    *async_id = q->querynum;
893
0
  lock_basic_unlock(&ctx->cfglock);
894
  
895
0
  lock_basic_lock(&ctx->qqpipe_lock);
896
0
  if(!tube_write_msg(ctx->qq_pipe, msg, len, 0)) {
897
0
    lock_basic_unlock(&ctx->qqpipe_lock);
898
0
    free(msg);
899
0
    return UB_PIPE;
900
0
  }
901
0
  lock_basic_unlock(&ctx->qqpipe_lock);
902
0
  free(msg);
903
0
  return UB_NOERROR;
904
0
}
905
906
int 
907
ub_cancel(struct ub_ctx* ctx, int async_id)
908
0
{
909
0
  struct ctx_query* q;
910
0
  uint8_t* msg = NULL;
911
0
  uint32_t len = 0;
912
0
  lock_basic_lock(&ctx->cfglock);
913
0
  q = (struct ctx_query*)rbtree_search(&ctx->queries, &async_id);
914
0
  if(!q || !q->async) {
915
    /* it is not there, so nothing to do */
916
0
    lock_basic_unlock(&ctx->cfglock);
917
0
    return UB_NOID;
918
0
  }
919
0
  log_assert(q->async);
920
0
  q->cancelled = 1;
921
  
922
  /* delete it */
923
0
  if(!ctx->dothread) { /* if forked */
924
0
    (void)rbtree_delete(&ctx->queries, q->node.key);
925
0
    ctx->num_async--;
926
0
    msg = context_serialize_cancel(q, &len);
927
0
    context_query_delete(q);
928
0
    lock_basic_unlock(&ctx->cfglock);
929
0
    if(!msg) {
930
0
      return UB_NOMEM;
931
0
    }
932
    /* send cancel to background worker */
933
0
    lock_basic_lock(&ctx->qqpipe_lock);
934
0
    if(!tube_write_msg(ctx->qq_pipe, msg, len, 0)) {
935
0
      lock_basic_unlock(&ctx->qqpipe_lock);
936
0
      free(msg);
937
0
      return UB_PIPE;
938
0
    }
939
0
    lock_basic_unlock(&ctx->qqpipe_lock);
940
0
    free(msg);
941
0
  } else {
942
0
    lock_basic_unlock(&ctx->cfglock);
943
0
  }
944
0
  return UB_NOERROR;
945
0
}
946
947
void 
948
ub_resolve_free(struct ub_result* result)
949
0
{
950
0
  char** p;
951
0
  if(!result) return;
952
0
  free(result->qname);
953
0
  if(result->canonname != result->qname)
954
0
    free(result->canonname);
955
0
  if(result->data)
956
0
    for(p = result->data; *p; p++)
957
0
      free(*p);
958
0
  free(result->data);
959
0
  free(result->len);
960
0
  free(result->answer_packet);
961
0
  free(result->why_bogus);
962
0
  free(result);
963
0
}
964
965
const char* 
966
ub_strerror(int err)
967
0
{
968
0
  switch(err) {
969
0
    case UB_NOERROR: return "no error";
970
0
    case UB_SOCKET: return "socket io error";
971
0
    case UB_NOMEM: return "out of memory";
972
0
    case UB_SYNTAX: return "syntax error";
973
0
    case UB_SERVFAIL: return "server failure";
974
0
    case UB_FORKFAIL: return "could not fork";
975
0
    case UB_INITFAIL: return "initialization failure";
976
0
    case UB_AFTERFINAL: return "setting change after finalize";
977
0
    case UB_PIPE: return "error in pipe communication with async";
978
0
    case UB_READFILE: return "error reading file";
979
0
    case UB_NOID: return "error async_id does not exist";
980
0
    default: return "unknown error";
981
0
  }
982
0
}
983
984
int 
985
ub_ctx_set_fwd(struct ub_ctx* ctx, const char* addr)
986
0
{
987
0
  struct sockaddr_storage storage;
988
0
  socklen_t stlen;
989
0
  struct config_stub* s;
990
0
  char* dupl;
991
0
  lock_basic_lock(&ctx->cfglock);
992
0
  if(ctx->finalized) {
993
0
    lock_basic_unlock(&ctx->cfglock);
994
0
    errno=EINVAL;
995
0
    return UB_AFTERFINAL;
996
0
  }
997
0
  if(!addr) {
998
    /* disable fwd mode - the root stub should be first. */
999
0
    if(ctx->env->cfg->forwards &&
1000
0
      (ctx->env->cfg->forwards->name &&
1001
0
      strcmp(ctx->env->cfg->forwards->name, ".") == 0)) {
1002
0
      s = ctx->env->cfg->forwards;
1003
0
      ctx->env->cfg->forwards = s->next;
1004
0
      s->next = NULL;
1005
0
      config_delstubs(s);
1006
0
    }
1007
0
    lock_basic_unlock(&ctx->cfglock);
1008
0
    return UB_NOERROR;
1009
0
  }
1010
0
  lock_basic_unlock(&ctx->cfglock);
1011
1012
  /* check syntax for addr */
1013
0
  if(!extstrtoaddr(addr, &storage, &stlen, UNBOUND_DNS_PORT)) {
1014
0
    errno=EINVAL;
1015
0
    return UB_SYNTAX;
1016
0
  }
1017
  
1018
  /* it parses, add root stub in front of list */
1019
0
  lock_basic_lock(&ctx->cfglock);
1020
0
  if(!ctx->env->cfg->forwards ||
1021
0
    (ctx->env->cfg->forwards->name &&
1022
0
    strcmp(ctx->env->cfg->forwards->name, ".") != 0)) {
1023
0
    s = calloc(1, sizeof(*s));
1024
0
    if(!s) {
1025
0
      lock_basic_unlock(&ctx->cfglock);
1026
0
      errno=ENOMEM;
1027
0
      return UB_NOMEM;
1028
0
    }
1029
0
    s->name = strdup(".");
1030
0
    if(!s->name) {
1031
0
      free(s);
1032
0
      lock_basic_unlock(&ctx->cfglock);
1033
0
      errno=ENOMEM;
1034
0
      return UB_NOMEM;
1035
0
    }
1036
0
    s->next = ctx->env->cfg->forwards;
1037
0
    ctx->env->cfg->forwards = s;
1038
0
  } else {
1039
0
    log_assert(ctx->env->cfg->forwards);
1040
0
    log_assert(ctx->env->cfg->forwards->name);
1041
0
    s = ctx->env->cfg->forwards;
1042
0
  }
1043
0
  dupl = strdup(addr);
1044
0
  if(!dupl) {
1045
0
    lock_basic_unlock(&ctx->cfglock);
1046
0
    errno=ENOMEM;
1047
0
    return UB_NOMEM;
1048
0
  }
1049
0
  if(!cfg_strlist_insert(&s->addrs, dupl)) {
1050
0
    lock_basic_unlock(&ctx->cfglock);
1051
0
    errno=ENOMEM;
1052
0
    return UB_NOMEM;
1053
0
  }
1054
0
  lock_basic_unlock(&ctx->cfglock);
1055
0
  return UB_NOERROR;
1056
0
}
1057
1058
int ub_ctx_set_tls(struct ub_ctx* ctx, int tls)
1059
0
{
1060
0
  lock_basic_lock(&ctx->cfglock);
1061
0
  if(ctx->finalized) {
1062
0
    lock_basic_unlock(&ctx->cfglock);
1063
0
    errno=EINVAL;
1064
0
    return UB_AFTERFINAL;
1065
0
  }
1066
0
  ctx->env->cfg->ssl_upstream = tls;
1067
0
  lock_basic_unlock(&ctx->cfglock);
1068
0
  return UB_NOERROR;
1069
0
}
1070
1071
int ub_ctx_set_stub(struct ub_ctx* ctx, const char* zone, const char* addr,
1072
  int isprime)
1073
0
{
1074
0
  char* a;
1075
0
  struct config_stub **prev, *elem;
1076
1077
  /* check syntax for zone name */
1078
0
  if(zone) {
1079
0
    uint8_t* nm;
1080
0
    int nmlabs;
1081
0
    size_t nmlen;
1082
0
    if(!parse_dname(zone, &nm, &nmlen, &nmlabs)) {
1083
0
      errno=EINVAL;
1084
0
      return UB_SYNTAX;
1085
0
    }
1086
0
    free(nm);
1087
0
  } else {
1088
0
    zone = ".";
1089
0
  }
1090
1091
  /* check syntax for addr (if not NULL) */
1092
0
  if(addr) {
1093
0
    struct sockaddr_storage storage;
1094
0
    socklen_t stlen;
1095
0
    if(!extstrtoaddr(addr, &storage, &stlen, UNBOUND_DNS_PORT)) {
1096
0
      errno=EINVAL;
1097
0
      return UB_SYNTAX;
1098
0
    }
1099
0
  }
1100
1101
0
  lock_basic_lock(&ctx->cfglock);
1102
0
  if(ctx->finalized) {
1103
0
    lock_basic_unlock(&ctx->cfglock);
1104
0
    errno=EINVAL;
1105
0
    return UB_AFTERFINAL;
1106
0
  }
1107
1108
  /* arguments all right, now find or add the stub */
1109
0
  prev = &ctx->env->cfg->stubs;
1110
0
  elem = cfg_stub_find(&prev, zone);
1111
0
  if(!elem && !addr) {
1112
    /* not found and we want to delete, nothing to do */
1113
0
    lock_basic_unlock(&ctx->cfglock);
1114
0
    return UB_NOERROR;
1115
0
  } else if(elem && !addr) {
1116
    /* found, and we want to delete */
1117
0
    *prev = elem->next;
1118
0
    config_delstub(elem);
1119
0
    lock_basic_unlock(&ctx->cfglock);
1120
0
    return UB_NOERROR;
1121
0
  } else if(!elem) {
1122
    /* not found, create the stub entry */
1123
0
    elem=(struct config_stub*)calloc(1, sizeof(struct config_stub));
1124
0
    if(elem) elem->name = strdup(zone);
1125
0
    if(!elem || !elem->name) {
1126
0
      free(elem);
1127
0
      lock_basic_unlock(&ctx->cfglock);
1128
0
      errno = ENOMEM;
1129
0
      return UB_NOMEM;
1130
0
    }
1131
0
    elem->next = ctx->env->cfg->stubs;
1132
0
    ctx->env->cfg->stubs = elem;
1133
0
  }
1134
1135
  /* add the address to the list and set settings */
1136
0
  elem->isprime = isprime;
1137
0
  a = strdup(addr);
1138
0
  if(!a) {
1139
0
    lock_basic_unlock(&ctx->cfglock);
1140
0
    errno = ENOMEM;
1141
0
    return UB_NOMEM;
1142
0
  }
1143
0
  if(!cfg_strlist_insert(&elem->addrs, a)) {
1144
0
    lock_basic_unlock(&ctx->cfglock);
1145
0
    errno = ENOMEM;
1146
0
    return UB_NOMEM;
1147
0
  }
1148
0
  lock_basic_unlock(&ctx->cfglock);
1149
0
  return UB_NOERROR;
1150
0
}
1151
1152
int 
1153
ub_ctx_resolvconf(struct ub_ctx* ctx, const char* fname)
1154
0
{
1155
0
  FILE* in;
1156
0
  int numserv = 0;
1157
0
  char buf[1024];
1158
0
  char* parse, *addr;
1159
0
  int r;
1160
1161
0
  if(fname == NULL) {
1162
0
#if !defined(UB_ON_WINDOWS) || !defined(HAVE_WINDOWS_H)
1163
0
    fname = "/etc/resolv.conf";
1164
#else
1165
    FIXED_INFO *info;
1166
    ULONG buflen = sizeof(*info);
1167
    IP_ADDR_STRING *ptr;
1168
1169
    info = (FIXED_INFO *) malloc(sizeof (FIXED_INFO));
1170
    if (info == NULL) 
1171
      return UB_READFILE;
1172
1173
    if (GetNetworkParams(info, &buflen) == ERROR_BUFFER_OVERFLOW) {
1174
      free(info);
1175
      info = (FIXED_INFO *) malloc(buflen);
1176
      if (info == NULL)
1177
        return UB_READFILE;
1178
    }
1179
1180
    if (GetNetworkParams(info, &buflen) == NO_ERROR) {
1181
      int retval=0;
1182
      ptr = &(info->DnsServerList);
1183
      while (ptr) {
1184
        numserv++;
1185
        if((retval=ub_ctx_set_fwd(ctx, 
1186
          ptr->IpAddress.String))!=0) {
1187
          free(info);
1188
          return retval;
1189
        }
1190
        ptr = ptr->Next;
1191
      }
1192
      free(info);
1193
      if (numserv==0)
1194
        return UB_READFILE;
1195
      return UB_NOERROR;
1196
    }
1197
    free(info);
1198
    return UB_READFILE;
1199
#endif /* WINDOWS */
1200
0
  }
1201
0
  in = fopen(fname, "r");
1202
0
  if(!in) {
1203
    /* error in errno! perror(fname) */
1204
0
    return UB_READFILE;
1205
0
  }
1206
0
  while(fgets(buf, (int)sizeof(buf), in)) {
1207
0
    buf[sizeof(buf)-1] = 0;
1208
0
    parse=buf;
1209
0
    while(*parse == ' ' || *parse == '\t')
1210
0
      parse++;
1211
0
    if(strncmp(parse, "nameserver", 10) == 0) {
1212
0
      numserv++;
1213
0
      parse += 10; /* skip 'nameserver' */
1214
      /* skip whitespace */
1215
0
      while(*parse == ' ' || *parse == '\t')
1216
0
        parse++;
1217
0
      addr = parse;
1218
      /* skip [0-9a-fA-F.:]*, i.e. IP4 and IP6 address */
1219
0
      while(isxdigit((unsigned char)*parse) || *parse=='.' || *parse==':')
1220
0
        parse++;
1221
      /* terminate after the address, remove newline */
1222
0
      *parse = 0;
1223
      
1224
0
      if((r = ub_ctx_set_fwd(ctx, addr)) != UB_NOERROR) {
1225
0
        fclose(in);
1226
0
        return r;
1227
0
      }
1228
0
    }
1229
0
  }
1230
0
  fclose(in);
1231
0
  if(numserv == 0) {
1232
    /* from resolv.conf(5) if none given, use localhost */
1233
0
    return ub_ctx_set_fwd(ctx, "127.0.0.1");
1234
0
  }
1235
0
  return UB_NOERROR;
1236
0
}
1237
1238
int
1239
ub_ctx_hosts(struct ub_ctx* ctx, const char* fname)
1240
0
{
1241
0
  FILE* in;
1242
0
  char buf[1024], ldata[2048];
1243
0
  char* parse, *addr, *name, *ins;
1244
0
  lock_basic_lock(&ctx->cfglock);
1245
0
  if(ctx->finalized) {
1246
0
    lock_basic_unlock(&ctx->cfglock);
1247
0
    errno=EINVAL;
1248
0
    return UB_AFTERFINAL;
1249
0
  }
1250
0
  lock_basic_unlock(&ctx->cfglock);
1251
0
  if(fname == NULL) {
1252
#if defined(UB_ON_WINDOWS) && defined(HAVE_WINDOWS_H)
1253
    /*
1254
     * If this is Windows NT/XP/2K it's in
1255
     * %WINDIR%\system32\drivers\etc\hosts.
1256
     * If this is Windows 95/98/Me it's in %WINDIR%\hosts.
1257
     */
1258
    name = getenv("WINDIR");
1259
    if (name != NULL) {
1260
      int retval=0;
1261
      snprintf(buf, sizeof(buf), "%s%s", name, 
1262
        "\\system32\\drivers\\etc\\hosts");
1263
      if((retval=ub_ctx_hosts(ctx, buf)) !=0 ) {
1264
        snprintf(buf, sizeof(buf), "%s%s", name, 
1265
          "\\hosts");
1266
        retval=ub_ctx_hosts(ctx, buf);
1267
      }
1268
      return retval;
1269
    }
1270
    return UB_READFILE;
1271
#else
1272
0
    fname = "/etc/hosts";
1273
0
#endif /* WIN32 */
1274
0
  }
1275
0
  in = fopen(fname, "r");
1276
0
  if(!in) {
1277
    /* error in errno! perror(fname) */
1278
0
    return UB_READFILE;
1279
0
  }
1280
0
  while(fgets(buf, (int)sizeof(buf), in)) {
1281
0
    buf[sizeof(buf)-1] = 0;
1282
0
    parse=buf;
1283
0
    while(*parse == ' ' || *parse == '\t')
1284
0
      parse++;
1285
0
    if(*parse == '#')
1286
0
      continue; /* skip comment */
1287
    /* format: <addr> spaces <name> spaces <name> ... */
1288
0
    addr = parse;
1289
    /* skip addr */
1290
0
    while(isxdigit((unsigned char)*parse) || *parse == '.' || *parse == ':')
1291
0
      parse++;
1292
0
    if(*parse == '\r')
1293
0
      parse++;
1294
0
    if(*parse == '\n' || *parse == 0)
1295
0
      continue;
1296
0
    if(*parse == '%') 
1297
0
      continue; /* ignore macOSX fe80::1%lo0 localhost */
1298
0
    if(*parse != ' ' && *parse != '\t') {
1299
      /* must have whitespace after address */
1300
0
      fclose(in);
1301
0
      errno=EINVAL;
1302
0
      return UB_SYNTAX;
1303
0
    }
1304
0
    *parse++ = 0; /* end delimiter for addr ... */
1305
    /* go to names and add them */
1306
0
    while(*parse) {
1307
0
      while(*parse == ' ' || *parse == '\t' || *parse=='\n'
1308
0
        || *parse=='\r')
1309
0
        parse++;
1310
0
      if(*parse == 0 || *parse == '#')
1311
0
        break;
1312
      /* skip name, allows (too) many printable characters */
1313
0
      name = parse;
1314
0
      while('!' <= *parse && *parse <= '~')
1315
0
        parse++;
1316
0
      if(*parse)
1317
0
        *parse++ = 0; /* end delimiter for name */
1318
0
      snprintf(ldata, sizeof(ldata), "%s %s %s",
1319
0
        name, str_is_ip6(addr)?"AAAA":"A", addr);
1320
0
      ins = strdup(ldata);
1321
0
      if(!ins) {
1322
        /* out of memory */
1323
0
        fclose(in);
1324
0
        errno=ENOMEM;
1325
0
        return UB_NOMEM;
1326
0
      }
1327
0
      lock_basic_lock(&ctx->cfglock);
1328
0
      if(!cfg_strlist_insert(&ctx->env->cfg->local_data, 
1329
0
        ins)) {
1330
0
        lock_basic_unlock(&ctx->cfglock);
1331
0
        fclose(in);
1332
0
        errno=ENOMEM;
1333
0
        return UB_NOMEM;
1334
0
      }
1335
0
      lock_basic_unlock(&ctx->cfglock);
1336
0
    }
1337
0
  }
1338
0
  fclose(in);
1339
0
  return UB_NOERROR;
1340
0
}
1341
1342
/** finalize the context, if not already finalized */
1343
static int ub_ctx_finalize(struct ub_ctx* ctx)
1344
0
{
1345
0
  int res = 0;
1346
0
  lock_basic_lock(&ctx->cfglock);
1347
0
  if (!ctx->finalized) {
1348
0
    res = context_finalize(ctx);
1349
0
  }
1350
0
  lock_basic_unlock(&ctx->cfglock);
1351
0
  return res;
1352
0
}
1353
1354
/* Print local zones and RR data */
1355
int ub_ctx_print_local_zones(struct ub_ctx* ctx)
1356
0
{   
1357
0
  int res = ub_ctx_finalize(ctx);
1358
0
  if (res) return res;
1359
1360
0
  local_zones_print(ctx->local_zones);
1361
1362
0
  return UB_NOERROR;
1363
0
}
1364
1365
/* Add a new zone */
1366
int ub_ctx_zone_add(struct ub_ctx* ctx, const char *zone_name, 
1367
  const char *zone_type)
1368
0
{
1369
0
  enum localzone_type t;
1370
0
  struct local_zone* z;
1371
0
  uint8_t* nm;
1372
0
  int nmlabs;
1373
0
  size_t nmlen;
1374
1375
0
  int res = ub_ctx_finalize(ctx);
1376
0
  if (res) return res;
1377
1378
0
  if(!local_zone_str2type(zone_type, &t)) {
1379
0
    return UB_SYNTAX;
1380
0
  }
1381
1382
0
  if(!parse_dname(zone_name, &nm, &nmlen, &nmlabs)) {
1383
0
    return UB_SYNTAX;
1384
0
  }
1385
1386
0
  lock_rw_wrlock(&ctx->local_zones->lock);
1387
0
  if((z=local_zones_find(ctx->local_zones, nm, nmlen, nmlabs, 
1388
0
    LDNS_RR_CLASS_IN))) {
1389
    /* already present in tree */
1390
0
    lock_rw_wrlock(&z->lock);
1391
0
    z->type = t; /* update type anyway */
1392
0
    lock_rw_unlock(&z->lock);
1393
0
    lock_rw_unlock(&ctx->local_zones->lock);
1394
0
    free(nm);
1395
0
    return UB_NOERROR;
1396
0
  }
1397
0
  if(!local_zones_add_zone(ctx->local_zones, nm, nmlen, nmlabs, 
1398
0
    LDNS_RR_CLASS_IN, t)) {
1399
0
    lock_rw_unlock(&ctx->local_zones->lock);
1400
0
    return UB_NOMEM;
1401
0
  }
1402
0
  lock_rw_unlock(&ctx->local_zones->lock);
1403
0
  return UB_NOERROR;
1404
0
}
1405
1406
/* Remove zone */
1407
int ub_ctx_zone_remove(struct ub_ctx* ctx, const char *zone_name)
1408
0
{   
1409
0
  struct local_zone* z;
1410
0
  uint8_t* nm;
1411
0
  int nmlabs;
1412
0
  size_t nmlen;
1413
1414
0
  int res = ub_ctx_finalize(ctx);
1415
0
  if (res) return res;
1416
1417
0
  if(!parse_dname(zone_name, &nm, &nmlen, &nmlabs)) {
1418
0
    return UB_SYNTAX;
1419
0
  }
1420
1421
0
  lock_rw_wrlock(&ctx->local_zones->lock);
1422
0
  if((z=local_zones_find(ctx->local_zones, nm, nmlen, nmlabs, 
1423
0
    LDNS_RR_CLASS_IN))) {
1424
    /* present in tree */
1425
0
    local_zones_del_zone(ctx->local_zones, z);
1426
0
  }
1427
0
  lock_rw_unlock(&ctx->local_zones->lock);
1428
0
  free(nm);
1429
0
  return UB_NOERROR;
1430
0
}
1431
1432
/* Add new RR data */
1433
int ub_ctx_data_add(struct ub_ctx* ctx, const char *data)
1434
0
{
1435
0
  int res = ub_ctx_finalize(ctx);
1436
0
  if (res) return res;
1437
1438
0
  res = local_zones_add_RR(ctx->local_zones, data);
1439
0
  return (!res) ? UB_NOMEM : UB_NOERROR;
1440
0
}
1441
1442
/* Remove RR data */
1443
int ub_ctx_data_remove(struct ub_ctx* ctx, const char *data)
1444
0
{
1445
0
  uint8_t* nm;
1446
0
  int nmlabs;
1447
0
  size_t nmlen;
1448
0
  int res = ub_ctx_finalize(ctx);
1449
0
  if (res) return res;
1450
1451
0
  if(!parse_dname(data, &nm, &nmlen, &nmlabs)) 
1452
0
    return UB_SYNTAX;
1453
1454
0
  local_zones_del_data(ctx->local_zones, nm, nmlen, nmlabs, 
1455
0
    LDNS_RR_CLASS_IN);
1456
1457
0
  free(nm);
1458
0
  return UB_NOERROR;
1459
0
}
1460
1461
const char* ub_version(void)
1462
0
{
1463
0
  return PACKAGE_VERSION;
1464
0
}
1465
1466
int 
1467
0
ub_ctx_set_event(struct ub_ctx* ctx, struct event_base* base) {
1468
0
  struct ub_event_base* new_base;
1469
1470
0
  if (!ctx || !ctx->event_base || !base) {
1471
0
    return UB_INITFAIL;
1472
0
  }
1473
0
  if (ub_libevent_get_event_base(ctx->event_base) == base) {
1474
    /* already set */
1475
0
    return UB_NOERROR;
1476
0
  }
1477
  
1478
0
  lock_basic_lock(&ctx->cfglock);
1479
  /* destroy the current worker - safe to pass in NULL */
1480
1481
  /* Unlock the cfglock during libworker_delete_event, since it
1482
   * calls context_release_alloc, that wants to lock cfglock again.
1483
   * Since the event base is used from one thread, the one that
1484
   * called this function, it is safe to do so. */
1485
0
  lock_basic_unlock(&ctx->cfglock);
1486
0
  libworker_delete_event(ctx->event_worker);
1487
0
  ctx->event_worker = NULL;
1488
0
  lock_basic_lock(&ctx->cfglock);
1489
0
  new_base = ub_libevent_event_base(base);
1490
0
  if (new_base)
1491
0
    ctx->event_base = new_base; 
1492
0
  ctx->created_bg = 0;
1493
0
  ctx->dothread = 1;
1494
0
  lock_basic_unlock(&ctx->cfglock);
1495
0
  return new_base ? UB_NOERROR : UB_INITFAIL;
1496
0
}