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