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