1 /*
2  * libunbound/context.c - validating context for unbound internal use
3  *
4  * Copyright (c) 2007, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 /**
37  * \file
38  *
39  * This file contains the validator context structure.
40  */
41 #include "config.h"
42 #include "libunbound/context.h"
43 #include "util/module.h"
44 #include "util/config_file.h"
45 #include "util/net_help.h"
46 #include "services/modstack.h"
47 #include "services/localzone.h"
48 #include "services/cache/rrset.h"
49 #include "services/cache/infra.h"
50 #include "services/authzone.h"
51 #include "services/listen_dnsport.h"
52 #include "util/data/msgreply.h"
53 #include "util/storage/slabhash.h"
54 #include "util/edns.h"
55 #include "sldns/sbuffer.h"
56 #include "iterator/iter_fwd.h"
57 #include "iterator/iter_hints.h"
58 
59 int
context_finalize(struct ub_ctx * ctx)60 context_finalize(struct ub_ctx* ctx)
61 {
62 	int is_rpz = 0;
63 	struct config_file* cfg = ctx->env->cfg;
64 	verbosity = cfg->verbosity;
65 	if(ctx_logfile_overridden && !ctx->logfile_override) {
66 		log_file(NULL); /* clear that override */
67 		ctx_logfile_overridden = 0;
68 	}
69 	if(ctx->logfile_override) {
70 		ctx_logfile_overridden = 1;
71 		log_file(ctx->log_out);
72 	} else {
73 		log_init(cfg->logfile, cfg->use_syslog, NULL);
74 	}
75 	ctx->pipe_pid = getpid();
76 	cfg_apply_local_port_policy(cfg, 65536);
77 	config_apply(cfg);
78 	if(!modstack_call_startup(&ctx->mods, cfg->module_conf, ctx->env))
79 		return UB_INITFAIL;
80 	if(!modstack_call_init(&ctx->mods, cfg->module_conf, ctx->env))
81 		return UB_INITFAIL;
82 	listen_setup_locks();
83 	log_edns_known_options(VERB_ALGO, ctx->env);
84 	ctx->local_zones = local_zones_create();
85 	if(!ctx->local_zones)
86 		return UB_NOMEM;
87 	if(!local_zones_apply_cfg(ctx->local_zones, cfg))
88 		return UB_INITFAIL;
89 	if(!auth_zones_apply_cfg(ctx->env->auth_zones, cfg, 1, &is_rpz,
90 		ctx->env, &ctx->mods))
91 		return UB_INITFAIL;
92 	if(!(ctx->env->fwds = forwards_create()) ||
93 		!forwards_apply_cfg(ctx->env->fwds, cfg))
94 		return UB_INITFAIL;
95 	if(!(ctx->env->hints = hints_create()) ||
96 		!hints_apply_cfg(ctx->env->hints, cfg))
97 		return UB_INITFAIL;
98 	if(!edns_strings_apply_cfg(ctx->env->edns_strings, cfg))
99 		return UB_INITFAIL;
100 	if(!slabhash_is_size(ctx->env->msg_cache, cfg->msg_cache_size,
101 		cfg->msg_cache_slabs)) {
102 		slabhash_delete(ctx->env->msg_cache);
103 		ctx->env->msg_cache = slabhash_create(cfg->msg_cache_slabs,
104 			HASH_DEFAULT_STARTARRAY, cfg->msg_cache_size,
105 			msgreply_sizefunc, query_info_compare,
106 			query_entry_delete, reply_info_delete, NULL);
107 		if(!ctx->env->msg_cache)
108 			return UB_NOMEM;
109 	}
110 	ctx->env->rrset_cache = rrset_cache_adjust(ctx->env->rrset_cache,
111 		ctx->env->cfg, ctx->env->alloc);
112 	if(!ctx->env->rrset_cache)
113 		return UB_NOMEM;
114 	ctx->env->infra_cache = infra_adjust(ctx->env->infra_cache, cfg);
115 	if(!ctx->env->infra_cache)
116 		return UB_NOMEM;
117 	ctx->finalized = 1;
118 	return UB_NOERROR;
119 }
120 
context_query_cmp(const void * a,const void * b)121 int context_query_cmp(const void* a, const void* b)
122 {
123 	if( *(int*)a < *(int*)b )
124 		return -1;
125 	if( *(int*)a > *(int*)b )
126 		return 1;
127 	return 0;
128 }
129 
130 void
context_query_delete(struct ctx_query * q)131 context_query_delete(struct ctx_query* q)
132 {
133 	if(!q) return;
134 	ub_resolve_free(q->res);
135 	free(q->msg);
136 	free(q);
137 }
138 
139 /** How many times to try to find an unused query-id-number for async */
140 #define NUM_ID_TRIES 100000
141 /** find next useful id number of 0 on error */
142 static int
find_id(struct ub_ctx * ctx,int * id)143 find_id(struct ub_ctx* ctx, int* id)
144 {
145 	size_t tries = 0;
146 	ctx->next_querynum++;
147 	while(rbtree_search(&ctx->queries, &ctx->next_querynum)) {
148 		ctx->next_querynum++; /* numerical wraparound is fine */
149 		if(tries++ > NUM_ID_TRIES)
150 			return 0;
151 	}
152 	*id = ctx->next_querynum;
153 	return 1;
154 }
155 
156 struct ctx_query*
context_new(struct ub_ctx * ctx,const char * name,int rrtype,int rrclass,ub_callback_type cb,ub_event_callback_type cb_event,void * cbarg)157 context_new(struct ub_ctx* ctx, const char* name, int rrtype, int rrclass,
158 	ub_callback_type cb, ub_event_callback_type cb_event, void* cbarg)
159 {
160 	struct ctx_query* q = (struct ctx_query*)calloc(1, sizeof(*q));
161 	if(!q) return NULL;
162 	lock_basic_lock(&ctx->cfglock);
163 	if(!find_id(ctx, &q->querynum)) {
164 		lock_basic_unlock(&ctx->cfglock);
165 		free(q);
166 		return NULL;
167 	}
168 	lock_basic_unlock(&ctx->cfglock);
169 	q->node.key = &q->querynum;
170 	q->async = (cb != NULL || cb_event != NULL);
171 	q->cb = cb;
172 	q->cb_event = cb_event;
173 	q->cb_arg = cbarg;
174 	q->res = (struct ub_result*)calloc(1, sizeof(*q->res));
175 	if(!q->res) {
176 		free(q);
177 		return NULL;
178 	}
179 	q->res->qname = strdup(name);
180 	if(!q->res->qname) {
181 		free(q->res);
182 		free(q);
183 		return NULL;
184 	}
185 	q->res->qtype = rrtype;
186 	q->res->qclass = rrclass;
187 
188 	/* add to query list */
189 	lock_basic_lock(&ctx->cfglock);
190 	if(q->async)
191 		ctx->num_async ++;
192 	(void)rbtree_insert(&ctx->queries, &q->node);
193 	lock_basic_unlock(&ctx->cfglock);
194 	return q;
195 }
196 
197 struct alloc_cache*
context_obtain_alloc(struct ub_ctx * ctx,int locking)198 context_obtain_alloc(struct ub_ctx* ctx, int locking)
199 {
200 	struct alloc_cache* a;
201 	int tnum = 0;
202 	if(locking) {
203 		lock_basic_lock(&ctx->cfglock);
204 	}
205 	a = ctx->alloc_list;
206 	if(a)
207 		ctx->alloc_list = a->super; /* snip off list */
208 	else	tnum = ctx->thr_next_num++;
209 	if(locking) {
210 		lock_basic_unlock(&ctx->cfglock);
211 	}
212 	if(a) {
213 		a->super = &ctx->superalloc;
214 		return a;
215 	}
216 	a = (struct alloc_cache*)calloc(1, sizeof(*a));
217 	if(!a)
218 		return NULL;
219 	alloc_init(a, &ctx->superalloc, tnum);
220 	return a;
221 }
222 
223 void
context_release_alloc(struct ub_ctx * ctx,struct alloc_cache * alloc,int locking)224 context_release_alloc(struct ub_ctx* ctx, struct alloc_cache* alloc,
225 	int locking)
226 {
227 	if(!ctx || !alloc)
228 		return;
229 	if(locking) {
230 		lock_basic_lock(&ctx->cfglock);
231 	}
232 	alloc->super = ctx->alloc_list;
233 	ctx->alloc_list = alloc;
234 	if(locking) {
235 		lock_basic_unlock(&ctx->cfglock);
236 	}
237 }
238 
239 uint8_t*
context_serialize_new_query(struct ctx_query * q,uint32_t * len)240 context_serialize_new_query(struct ctx_query* q, uint32_t* len)
241 {
242 	/* format for new query is
243 	 * 	o uint32 cmd
244 	 * 	o uint32 id
245 	 * 	o uint32 type
246 	 * 	o uint32 class
247 	 * 	o rest queryname (string)
248 	 */
249 	uint8_t* p;
250 	size_t slen = strlen(q->res->qname) + 1/*end of string*/;
251 	*len = sizeof(uint32_t)*4 + slen;
252 	p = (uint8_t*)malloc(*len);
253 	if(!p) return NULL;
254 	sldns_write_uint32(p, UB_LIBCMD_NEWQUERY);
255 	sldns_write_uint32(p+sizeof(uint32_t), (uint32_t)q->querynum);
256 	sldns_write_uint32(p+2*sizeof(uint32_t), (uint32_t)q->res->qtype);
257 	sldns_write_uint32(p+3*sizeof(uint32_t), (uint32_t)q->res->qclass);
258 	memmove(p+4*sizeof(uint32_t), q->res->qname, slen);
259 	return p;
260 }
261 
262 struct ctx_query*
context_deserialize_new_query(struct ub_ctx * ctx,uint8_t * p,uint32_t len)263 context_deserialize_new_query(struct ub_ctx* ctx, uint8_t* p, uint32_t len)
264 {
265 	struct ctx_query* q = (struct ctx_query*)calloc(1, sizeof(*q));
266 	if(!q) return NULL;
267 	if(len < 4*sizeof(uint32_t)+1) {
268 		free(q);
269 		return NULL;
270 	}
271 	log_assert( sldns_read_uint32(p) == UB_LIBCMD_NEWQUERY);
272 	q->querynum = (int)sldns_read_uint32(p+sizeof(uint32_t));
273 	q->node.key = &q->querynum;
274 	q->async = 1;
275 	q->res = (struct ub_result*)calloc(1, sizeof(*q->res));
276 	if(!q->res) {
277 		free(q);
278 		return NULL;
279 	}
280 	q->res->qtype = (int)sldns_read_uint32(p+2*sizeof(uint32_t));
281 	q->res->qclass = (int)sldns_read_uint32(p+3*sizeof(uint32_t));
282 	q->res->qname = strdup((char*)(p+4*sizeof(uint32_t)));
283 	if(!q->res->qname) {
284 		free(q->res);
285 		free(q);
286 		return NULL;
287 	}
288 
289 	/** add to query list */
290 	ctx->num_async++;
291 	(void)rbtree_insert(&ctx->queries, &q->node);
292 	return q;
293 }
294 
295 struct ctx_query*
context_lookup_new_query(struct ub_ctx * ctx,uint8_t * p,uint32_t len)296 context_lookup_new_query(struct ub_ctx* ctx, uint8_t* p, uint32_t len)
297 {
298 	struct ctx_query* q;
299 	int querynum;
300 	if(len < 4*sizeof(uint32_t)+1) {
301 		return NULL;
302 	}
303 	log_assert( sldns_read_uint32(p) == UB_LIBCMD_NEWQUERY);
304 	querynum = (int)sldns_read_uint32(p+sizeof(uint32_t));
305 	q = (struct ctx_query*)rbtree_search(&ctx->queries, &querynum);
306 	if(!q) {
307 		return NULL;
308 	}
309 	log_assert(q->async);
310 	return q;
311 }
312 
313 uint8_t*
context_serialize_answer(struct ctx_query * q,int err,sldns_buffer * pkt,uint32_t * len)314 context_serialize_answer(struct ctx_query* q, int err, sldns_buffer* pkt,
315 	uint32_t* len)
316 {
317 	/* answer format
318 	 * 	o uint32 cmd
319 	 * 	o uint32 id
320 	 * 	o uint32 error_code
321 	 * 	o uint32 msg_security
322 	 * 	o uint32 was_ratelimited
323 	 * 	o uint32 length of why_bogus string (+1 for eos); 0 absent.
324 	 * 	o why_bogus_string
325 	 * 	o the remainder is the answer msg from resolver lookup.
326 	 * 	  remainder can be length 0.
327 	 */
328 	size_t size_of_uint32s = 6 * sizeof(uint32_t);
329 	size_t pkt_len = pkt?sldns_buffer_remaining(pkt):0;
330 	size_t wlen = (pkt&&q->res->why_bogus)?strlen(q->res->why_bogus)+1:0;
331 	uint8_t* p;
332 	*len = size_of_uint32s + pkt_len + wlen;
333 	p = (uint8_t*)malloc(*len);
334 	if(!p) return NULL;
335 	sldns_write_uint32(p, UB_LIBCMD_ANSWER);
336 	sldns_write_uint32(p+sizeof(uint32_t), (uint32_t)q->querynum);
337 	sldns_write_uint32(p+2*sizeof(uint32_t), (uint32_t)err);
338 	sldns_write_uint32(p+3*sizeof(uint32_t), (uint32_t)q->msg_security);
339 	sldns_write_uint32(p+4*sizeof(uint32_t), (uint32_t)q->res->was_ratelimited);
340 	sldns_write_uint32(p+5*sizeof(uint32_t), (uint32_t)wlen);
341 	if(wlen > 0)
342 		memmove(p+size_of_uint32s, q->res->why_bogus, wlen);
343 	if(pkt_len > 0)
344 		memmove(p+size_of_uint32s+wlen,
345 			sldns_buffer_begin(pkt), pkt_len);
346 	return p;
347 }
348 
349 struct ctx_query*
context_deserialize_answer(struct ub_ctx * ctx,uint8_t * p,uint32_t len,int * err)350 context_deserialize_answer(struct ub_ctx* ctx,
351         uint8_t* p, uint32_t len, int* err)
352 {
353 	size_t size_of_uint32s = 6 * sizeof(uint32_t);
354 	struct ctx_query* q = NULL ;
355 	int id;
356 	size_t wlen;
357 	if(len < size_of_uint32s) return NULL;
358 	log_assert( sldns_read_uint32(p) == UB_LIBCMD_ANSWER);
359 	id = (int)sldns_read_uint32(p+sizeof(uint32_t));
360 	q = (struct ctx_query*)rbtree_search(&ctx->queries, &id);
361 	if(!q) return NULL;
362 	*err = (int)sldns_read_uint32(p+2*sizeof(uint32_t));
363 	q->msg_security = sldns_read_uint32(p+3*sizeof(uint32_t));
364 	q->res->was_ratelimited = (int)sldns_read_uint32(p+4*sizeof(uint32_t));
365 	wlen = (size_t)sldns_read_uint32(p+5*sizeof(uint32_t));
366 	if(len > size_of_uint32s && wlen > 0) {
367 		if(len >= size_of_uint32s+wlen)
368 			q->res->why_bogus = (char*)memdup(
369 				p+size_of_uint32s, wlen);
370 		if(!q->res->why_bogus) {
371 			/* pass malloc failure to the user callback */
372 			q->msg_len = 0;
373 			*err = UB_NOMEM;
374 			return q;
375 		}
376 		q->res->why_bogus[wlen-1] = 0; /* zero terminated for sure */
377 	}
378 	if(len > size_of_uint32s+wlen) {
379 		q->msg_len = len - size_of_uint32s - wlen;
380 		q->msg = (uint8_t*)memdup(p+size_of_uint32s+wlen,
381 			q->msg_len);
382 		if(!q->msg) {
383 			/* pass malloc failure to the user callback */
384 			q->msg_len = 0;
385 			*err = UB_NOMEM;
386 			return q;
387 		}
388 	}
389 	return q;
390 }
391 
392 uint8_t*
context_serialize_cancel(struct ctx_query * q,uint32_t * len)393 context_serialize_cancel(struct ctx_query* q, uint32_t* len)
394 {
395 	/* format of cancel:
396 	 * 	o uint32 cmd
397 	 * 	o uint32 async-id */
398 	uint8_t* p = (uint8_t*)reallocarray(NULL, sizeof(uint32_t), 2);
399 	if(!p) return NULL;
400 	*len = 2*sizeof(uint32_t);
401 	sldns_write_uint32(p, UB_LIBCMD_CANCEL);
402 	sldns_write_uint32(p+sizeof(uint32_t), (uint32_t)q->querynum);
403 	return p;
404 }
405 
context_deserialize_cancel(struct ub_ctx * ctx,uint8_t * p,uint32_t len)406 struct ctx_query* context_deserialize_cancel(struct ub_ctx* ctx,
407         uint8_t* p, uint32_t len)
408 {
409 	struct ctx_query* q;
410 	int id;
411 	if(len != 2*sizeof(uint32_t)) return NULL;
412 	log_assert( sldns_read_uint32(p) == UB_LIBCMD_CANCEL);
413 	id = (int)sldns_read_uint32(p+sizeof(uint32_t));
414 	q = (struct ctx_query*)rbtree_search(&ctx->queries, &id);
415 	return q;
416 }
417 
418 uint8_t*
context_serialize_quit(uint32_t * len)419 context_serialize_quit(uint32_t* len)
420 {
421 	uint32_t* p = (uint32_t*)malloc(sizeof(uint32_t));
422 	if(!p)
423 		return NULL;
424 	*len = sizeof(uint32_t);
425 	sldns_write_uint32(p, UB_LIBCMD_QUIT);
426 	return (uint8_t*)p;
427 }
428 
context_serial_getcmd(uint8_t * p,uint32_t len)429 enum ub_ctx_cmd context_serial_getcmd(uint8_t* p, uint32_t len)
430 {
431 	uint32_t v;
432 	if((size_t)len < sizeof(v))
433 		return UB_LIBCMD_QUIT;
434 	v = sldns_read_uint32(p);
435 	return v;
436 }
437