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