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_setup(&ctx->mods, cfg->module_conf, ctx->env))
79 		return UB_INITFAIL;
80 	listen_setup_locks();
81 	log_edns_known_options(VERB_ALGO, ctx->env);
82 	ctx->local_zones = local_zones_create();
83 	if(!ctx->local_zones)
84 		return UB_NOMEM;
85 	if(!local_zones_apply_cfg(ctx->local_zones, cfg))
86 		return UB_INITFAIL;
87 	if(!auth_zones_apply_cfg(ctx->env->auth_zones, cfg, 1, &is_rpz,
88 		ctx->env, &ctx->mods))
89 		return UB_INITFAIL;
90 	if(!(ctx->env->fwds = forwards_create()) ||
91 		!forwards_apply_cfg(ctx->env->fwds, cfg))
92 		return UB_INITFAIL;
93 	if(!(ctx->env->hints = hints_create()) ||
94 		!hints_apply_cfg(ctx->env->hints, cfg))
95 		return UB_INITFAIL;
96 	if(!edns_strings_apply_cfg(ctx->env->edns_strings, cfg))
97 		return UB_INITFAIL;
98 	if(!slabhash_is_size(ctx->env->msg_cache, cfg->msg_cache_size,
99 		cfg->msg_cache_slabs)) {
100 		slabhash_delete(ctx->env->msg_cache);
101 		ctx->env->msg_cache = slabhash_create(cfg->msg_cache_slabs,
102 			HASH_DEFAULT_STARTARRAY, cfg->msg_cache_size,
103 			msgreply_sizefunc, query_info_compare,
104 			query_entry_delete, reply_info_delete, NULL);
105 		if(!ctx->env->msg_cache)
106 			return UB_NOMEM;
107 	}
108 	ctx->env->rrset_cache = rrset_cache_adjust(ctx->env->rrset_cache,
109 		ctx->env->cfg, ctx->env->alloc);
110 	if(!ctx->env->rrset_cache)
111 		return UB_NOMEM;
112 	ctx->env->infra_cache = infra_adjust(ctx->env->infra_cache, cfg);
113 	if(!ctx->env->infra_cache)
114 		return UB_NOMEM;
115 	ctx->finalized = 1;
116 	return UB_NOERROR;
117 }
118 
context_query_cmp(const void * a,const void * b)119 int context_query_cmp(const void* a, const void* b)
120 {
121 	if( *(int*)a < *(int*)b )
122 		return -1;
123 	if( *(int*)a > *(int*)b )
124 		return 1;
125 	return 0;
126 }
127 
128 void
context_query_delete(struct ctx_query * q)129 context_query_delete(struct ctx_query* q)
130 {
131 	if(!q) return;
132 	ub_resolve_free(q->res);
133 	free(q->msg);
134 	free(q);
135 }
136 
137 /** How many times to try to find an unused query-id-number for async */
138 #define NUM_ID_TRIES 100000
139 /** find next useful id number of 0 on error */
140 static int
find_id(struct ub_ctx * ctx,int * id)141 find_id(struct ub_ctx* ctx, int* id)
142 {
143 	size_t tries = 0;
144 	ctx->next_querynum++;
145 	while(rbtree_search(&ctx->queries, &ctx->next_querynum)) {
146 		ctx->next_querynum++; /* numerical wraparound is fine */
147 		if(tries++ > NUM_ID_TRIES)
148 			return 0;
149 	}
150 	*id = ctx->next_querynum;
151 	return 1;
152 }
153 
154 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)155 context_new(struct ub_ctx* ctx, const char* name, int rrtype, int rrclass,
156 	ub_callback_type cb, ub_event_callback_type cb_event, void* cbarg)
157 {
158 	struct ctx_query* q = (struct ctx_query*)calloc(1, sizeof(*q));
159 	if(!q) return NULL;
160 	lock_basic_lock(&ctx->cfglock);
161 	if(!find_id(ctx, &q->querynum)) {
162 		lock_basic_unlock(&ctx->cfglock);
163 		free(q);
164 		return NULL;
165 	}
166 	lock_basic_unlock(&ctx->cfglock);
167 	q->node.key = &q->querynum;
168 	q->async = (cb != NULL || cb_event != NULL);
169 	q->cb = cb;
170 	q->cb_event = cb_event;
171 	q->cb_arg = cbarg;
172 	q->res = (struct ub_result*)calloc(1, sizeof(*q->res));
173 	if(!q->res) {
174 		free(q);
175 		return NULL;
176 	}
177 	q->res->qname = strdup(name);
178 	if(!q->res->qname) {
179 		free(q->res);
180 		free(q);
181 		return NULL;
182 	}
183 	q->res->qtype = rrtype;
184 	q->res->qclass = rrclass;
185 
186 	/* add to query list */
187 	lock_basic_lock(&ctx->cfglock);
188 	if(q->async)
189 		ctx->num_async ++;
190 	(void)rbtree_insert(&ctx->queries, &q->node);
191 	lock_basic_unlock(&ctx->cfglock);
192 	return q;
193 }
194 
195 struct alloc_cache*
context_obtain_alloc(struct ub_ctx * ctx,int locking)196 context_obtain_alloc(struct ub_ctx* ctx, int locking)
197 {
198 	struct alloc_cache* a;
199 	int tnum = 0;
200 	if(locking) {
201 		lock_basic_lock(&ctx->cfglock);
202 	}
203 	a = ctx->alloc_list;
204 	if(a)
205 		ctx->alloc_list = a->super; /* snip off list */
206 	else	tnum = ctx->thr_next_num++;
207 	if(locking) {
208 		lock_basic_unlock(&ctx->cfglock);
209 	}
210 	if(a) {
211 		a->super = &ctx->superalloc;
212 		return a;
213 	}
214 	a = (struct alloc_cache*)calloc(1, sizeof(*a));
215 	if(!a)
216 		return NULL;
217 	alloc_init(a, &ctx->superalloc, tnum);
218 	return a;
219 }
220 
221 void
context_release_alloc(struct ub_ctx * ctx,struct alloc_cache * alloc,int locking)222 context_release_alloc(struct ub_ctx* ctx, struct alloc_cache* alloc,
223 	int locking)
224 {
225 	if(!ctx || !alloc)
226 		return;
227 	if(locking) {
228 		lock_basic_lock(&ctx->cfglock);
229 	}
230 	alloc->super = ctx->alloc_list;
231 	ctx->alloc_list = alloc;
232 	if(locking) {
233 		lock_basic_unlock(&ctx->cfglock);
234 	}
235 }
236 
237 uint8_t*
context_serialize_new_query(struct ctx_query * q,uint32_t * len)238 context_serialize_new_query(struct ctx_query* q, uint32_t* len)
239 {
240 	/* format for new query is
241 	 * 	o uint32 cmd
242 	 * 	o uint32 id
243 	 * 	o uint32 type
244 	 * 	o uint32 class
245 	 * 	o rest queryname (string)
246 	 */
247 	uint8_t* p;
248 	size_t slen = strlen(q->res->qname) + 1/*end of string*/;
249 	*len = sizeof(uint32_t)*4 + slen;
250 	p = (uint8_t*)malloc(*len);
251 	if(!p) return NULL;
252 	sldns_write_uint32(p, UB_LIBCMD_NEWQUERY);
253 	sldns_write_uint32(p+sizeof(uint32_t), (uint32_t)q->querynum);
254 	sldns_write_uint32(p+2*sizeof(uint32_t), (uint32_t)q->res->qtype);
255 	sldns_write_uint32(p+3*sizeof(uint32_t), (uint32_t)q->res->qclass);
256 	memmove(p+4*sizeof(uint32_t), q->res->qname, slen);
257 	return p;
258 }
259 
260 struct ctx_query*
context_deserialize_new_query(struct ub_ctx * ctx,uint8_t * p,uint32_t len)261 context_deserialize_new_query(struct ub_ctx* ctx, uint8_t* p, uint32_t len)
262 {
263 	struct ctx_query* q = (struct ctx_query*)calloc(1, sizeof(*q));
264 	if(!q) return NULL;
265 	if(len < 4*sizeof(uint32_t)+1) {
266 		free(q);
267 		return NULL;
268 	}
269 	log_assert( sldns_read_uint32(p) == UB_LIBCMD_NEWQUERY);
270 	q->querynum = (int)sldns_read_uint32(p+sizeof(uint32_t));
271 	q->node.key = &q->querynum;
272 	q->async = 1;
273 	q->res = (struct ub_result*)calloc(1, sizeof(*q->res));
274 	if(!q->res) {
275 		free(q);
276 		return NULL;
277 	}
278 	q->res->qtype = (int)sldns_read_uint32(p+2*sizeof(uint32_t));
279 	q->res->qclass = (int)sldns_read_uint32(p+3*sizeof(uint32_t));
280 	q->res->qname = strdup((char*)(p+4*sizeof(uint32_t)));
281 	if(!q->res->qname) {
282 		free(q->res);
283 		free(q);
284 		return NULL;
285 	}
286 
287 	/** add to query list */
288 	ctx->num_async++;
289 	(void)rbtree_insert(&ctx->queries, &q->node);
290 	return q;
291 }
292 
293 struct ctx_query*
context_lookup_new_query(struct ub_ctx * ctx,uint8_t * p,uint32_t len)294 context_lookup_new_query(struct ub_ctx* ctx, uint8_t* p, uint32_t len)
295 {
296 	struct ctx_query* q;
297 	int querynum;
298 	if(len < 4*sizeof(uint32_t)+1) {
299 		return NULL;
300 	}
301 	log_assert( sldns_read_uint32(p) == UB_LIBCMD_NEWQUERY);
302 	querynum = (int)sldns_read_uint32(p+sizeof(uint32_t));
303 	q = (struct ctx_query*)rbtree_search(&ctx->queries, &querynum);
304 	if(!q) {
305 		return NULL;
306 	}
307 	log_assert(q->async);
308 	return q;
309 }
310 
311 uint8_t*
context_serialize_answer(struct ctx_query * q,int err,sldns_buffer * pkt,uint32_t * len)312 context_serialize_answer(struct ctx_query* q, int err, sldns_buffer* pkt,
313 	uint32_t* len)
314 {
315 	/* answer format
316 	 * 	o uint32 cmd
317 	 * 	o uint32 id
318 	 * 	o uint32 error_code
319 	 * 	o uint32 msg_security
320 	 * 	o uint32 was_ratelimited
321 	 * 	o uint32 length of why_bogus string (+1 for eos); 0 absent.
322 	 * 	o why_bogus_string
323 	 * 	o the remainder is the answer msg from resolver lookup.
324 	 * 	  remainder can be length 0.
325 	 */
326 	size_t size_of_uint32s = 6 * sizeof(uint32_t);
327 	size_t pkt_len = pkt?sldns_buffer_remaining(pkt):0;
328 	size_t wlen = (pkt&&q->res->why_bogus)?strlen(q->res->why_bogus)+1:0;
329 	uint8_t* p;
330 	*len = size_of_uint32s + pkt_len + wlen;
331 	p = (uint8_t*)malloc(*len);
332 	if(!p) return NULL;
333 	sldns_write_uint32(p, UB_LIBCMD_ANSWER);
334 	sldns_write_uint32(p+sizeof(uint32_t), (uint32_t)q->querynum);
335 	sldns_write_uint32(p+2*sizeof(uint32_t), (uint32_t)err);
336 	sldns_write_uint32(p+3*sizeof(uint32_t), (uint32_t)q->msg_security);
337 	sldns_write_uint32(p+4*sizeof(uint32_t), (uint32_t)q->res->was_ratelimited);
338 	sldns_write_uint32(p+5*sizeof(uint32_t), (uint32_t)wlen);
339 	if(wlen > 0)
340 		memmove(p+size_of_uint32s, q->res->why_bogus, wlen);
341 	if(pkt_len > 0)
342 		memmove(p+size_of_uint32s+wlen,
343 			sldns_buffer_begin(pkt), pkt_len);
344 	return p;
345 }
346 
347 struct ctx_query*
context_deserialize_answer(struct ub_ctx * ctx,uint8_t * p,uint32_t len,int * err)348 context_deserialize_answer(struct ub_ctx* ctx,
349         uint8_t* p, uint32_t len, int* err)
350 {
351 	size_t size_of_uint32s = 6 * sizeof(uint32_t);
352 	struct ctx_query* q = NULL ;
353 	int id;
354 	size_t wlen;
355 	if(len < size_of_uint32s) return NULL;
356 	log_assert( sldns_read_uint32(p) == UB_LIBCMD_ANSWER);
357 	id = (int)sldns_read_uint32(p+sizeof(uint32_t));
358 	q = (struct ctx_query*)rbtree_search(&ctx->queries, &id);
359 	if(!q) return NULL;
360 	*err = (int)sldns_read_uint32(p+2*sizeof(uint32_t));
361 	q->msg_security = sldns_read_uint32(p+3*sizeof(uint32_t));
362 	q->res->was_ratelimited = (int)sldns_read_uint32(p+4*sizeof(uint32_t));
363 	wlen = (size_t)sldns_read_uint32(p+5*sizeof(uint32_t));
364 	if(len > size_of_uint32s && wlen > 0) {
365 		if(len >= size_of_uint32s+wlen)
366 			q->res->why_bogus = (char*)memdup(
367 				p+size_of_uint32s, wlen);
368 		if(!q->res->why_bogus) {
369 			/* pass malloc failure to the user callback */
370 			q->msg_len = 0;
371 			*err = UB_NOMEM;
372 			return q;
373 		}
374 		q->res->why_bogus[wlen-1] = 0; /* zero terminated for sure */
375 	}
376 	if(len > size_of_uint32s+wlen) {
377 		q->msg_len = len - size_of_uint32s - wlen;
378 		q->msg = (uint8_t*)memdup(p+size_of_uint32s+wlen,
379 			q->msg_len);
380 		if(!q->msg) {
381 			/* pass malloc failure to the user callback */
382 			q->msg_len = 0;
383 			*err = UB_NOMEM;
384 			return q;
385 		}
386 	}
387 	return q;
388 }
389 
390 uint8_t*
context_serialize_cancel(struct ctx_query * q,uint32_t * len)391 context_serialize_cancel(struct ctx_query* q, uint32_t* len)
392 {
393 	/* format of cancel:
394 	 * 	o uint32 cmd
395 	 * 	o uint32 async-id */
396 	uint8_t* p = (uint8_t*)reallocarray(NULL, sizeof(uint32_t), 2);
397 	if(!p) return NULL;
398 	*len = 2*sizeof(uint32_t);
399 	sldns_write_uint32(p, UB_LIBCMD_CANCEL);
400 	sldns_write_uint32(p+sizeof(uint32_t), (uint32_t)q->querynum);
401 	return p;
402 }
403 
context_deserialize_cancel(struct ub_ctx * ctx,uint8_t * p,uint32_t len)404 struct ctx_query* context_deserialize_cancel(struct ub_ctx* ctx,
405         uint8_t* p, uint32_t len)
406 {
407 	struct ctx_query* q;
408 	int id;
409 	if(len != 2*sizeof(uint32_t)) return NULL;
410 	log_assert( sldns_read_uint32(p) == UB_LIBCMD_CANCEL);
411 	id = (int)sldns_read_uint32(p+sizeof(uint32_t));
412 	q = (struct ctx_query*)rbtree_search(&ctx->queries, &id);
413 	return q;
414 }
415 
416 uint8_t*
context_serialize_quit(uint32_t * len)417 context_serialize_quit(uint32_t* len)
418 {
419 	uint32_t* p = (uint32_t*)malloc(sizeof(uint32_t));
420 	if(!p)
421 		return NULL;
422 	*len = sizeof(uint32_t);
423 	sldns_write_uint32(p, UB_LIBCMD_QUIT);
424 	return (uint8_t*)p;
425 }
426 
context_serial_getcmd(uint8_t * p,uint32_t len)427 enum ub_ctx_cmd context_serial_getcmd(uint8_t* p, uint32_t len)
428 {
429 	uint32_t v;
430 	if((size_t)len < sizeof(v))
431 		return UB_LIBCMD_QUIT;
432 	v = sldns_read_uint32(p);
433 	return v;
434 }
435