xref: /freebsd/contrib/unbound/util/data/msgreply.c (revision 7a789145f88a6aceacc59029a0cafe7de7aeefea)
1 /*
2  * util/data/msgreply.c - store message and reply data.
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 a data structure to store a message and its reply.
40  */
41 
42 #include "config.h"
43 #include "util/data/msgreply.h"
44 #include "util/storage/lookup3.h"
45 #include "util/log.h"
46 #include "util/alloc.h"
47 #include "util/netevent.h"
48 #include "util/net_help.h"
49 #include "util/data/dname.h"
50 #include "util/regional.h"
51 #include "util/data/msgparse.h"
52 #include "util/data/msgencode.h"
53 #include "sldns/sbuffer.h"
54 #include "sldns/wire2str.h"
55 #include "util/module.h"
56 #include "util/fptr_wlist.h"
57 
58 /** MAX TTL default for messages and rrsets */
59 time_t MAX_TTL = 3600 * 24 * 10; /* ten days */
60 /** MIN TTL default for messages and rrsets */
61 time_t MIN_TTL = 0;
62 /** MAX Negative TTL, for SOA records in authority section */
63 time_t MAX_NEG_TTL = 3600; /* one hour */
64 /** MIN Negative TTL, for SOA records in authority section */
65 time_t MIN_NEG_TTL = 0;
66 /** If we serve expired entries and prefetch them */
67 int SERVE_EXPIRED = 0;
68 /** Time to serve records after expiration */
69 time_t SERVE_EXPIRED_TTL = 86400;
70 /** Reset serve expired TTL after failed update attempt */
71 time_t SERVE_EXPIRED_TTL_RESET = 0;
72 /** TTL to use for expired records */
73 time_t SERVE_EXPIRED_REPLY_TTL = 30;
74 /** If we serve the original TTL or decrementing TTLs */
75 int SERVE_ORIGINAL_TTL = 0;
76 
77 /** allocate qinfo, return 0 on error */
78 static int
parse_create_qinfo(sldns_buffer * pkt,struct msg_parse * msg,struct query_info * qinf,struct regional * region)79 parse_create_qinfo(sldns_buffer* pkt, struct msg_parse* msg,
80 	struct query_info* qinf, struct regional* region)
81 {
82 	if(msg->qname) {
83 		if(region)
84 			qinf->qname = (uint8_t*)regional_alloc(region,
85 				msg->qname_len);
86 		else	qinf->qname = (uint8_t*)malloc(msg->qname_len);
87 		if(!qinf->qname) return 0;
88 		dname_pkt_copy(pkt, qinf->qname, msg->qname);
89 	} else	qinf->qname = 0;
90 	qinf->qname_len = msg->qname_len;
91 	qinf->qtype = msg->qtype;
92 	qinf->qclass = msg->qclass;
93 	qinf->local_alias = NULL;
94 	return 1;
95 }
96 
97 /** constructor for replyinfo */
98 struct reply_info*
construct_reply_info_base(struct regional * region,uint16_t flags,size_t qd,time_t ttl,time_t prettl,time_t expttl,time_t norecttl,size_t an,size_t ns,size_t ar,size_t total,enum sec_status sec,sldns_ede_code reason_bogus)99 construct_reply_info_base(struct regional* region, uint16_t flags, size_t qd,
100 	time_t ttl, time_t prettl, time_t expttl, time_t norecttl, size_t an,
101 	size_t ns, size_t ar, size_t total, enum sec_status sec,
102 	sldns_ede_code reason_bogus)
103 {
104 	struct reply_info* rep;
105 	/* rrset_count-1 because the first ref is part of the struct. */
106 	size_t s = sizeof(struct reply_info) - sizeof(struct rrset_ref) +
107 		sizeof(struct ub_packed_rrset_key*) * total;
108 	if(total >= RR_COUNT_MAX) return NULL; /* sanity check on numRRS*/
109 	if(region)
110 		rep = (struct reply_info*)regional_alloc(region, s);
111 	else	rep = (struct reply_info*)malloc(s +
112 			sizeof(struct rrset_ref) * (total));
113 	if(!rep)
114 		return NULL;
115 	rep->flags = flags;
116 	rep->qdcount = qd;
117 	rep->ttl = ttl;
118 	rep->prefetch_ttl = prettl;
119 	rep->serve_expired_ttl = expttl;
120 	rep->serve_expired_norec_ttl = norecttl;
121 	rep->an_numrrsets = an;
122 	rep->ns_numrrsets = ns;
123 	rep->ar_numrrsets = ar;
124 	rep->rrset_count = total;
125 	rep->security = sec;
126 	rep->reason_bogus = reason_bogus;
127 	/* this is only allocated and used for caching on copy */
128 	rep->reason_bogus_str = NULL;
129 	rep->authoritative = 0;
130 	/* array starts after the refs */
131 	if(region)
132 		rep->rrsets = (struct ub_packed_rrset_key**)&(rep->ref[0]);
133 	else	rep->rrsets = (struct ub_packed_rrset_key**)&(rep->ref[total]);
134 	/* zero the arrays to assist cleanup in case of malloc failure */
135 	memset( rep->rrsets, 0, sizeof(struct ub_packed_rrset_key*) * total);
136 	if(!region)
137 		memset( &rep->ref[0], 0, sizeof(struct rrset_ref) * total);
138 	return rep;
139 }
140 
141 /** allocate replyinfo, return 0 on error */
142 static int
parse_create_repinfo(struct msg_parse * msg,struct reply_info ** rep,struct regional * region)143 parse_create_repinfo(struct msg_parse* msg, struct reply_info** rep,
144 	struct regional* region)
145 {
146 	*rep = construct_reply_info_base(region, msg->flags, msg->qdcount, 0,
147 		0, 0, 0, msg->an_rrsets, msg->ns_rrsets, msg->ar_rrsets,
148 		msg->rrset_count, sec_status_unchecked, LDNS_EDE_NONE);
149 	if(!*rep)
150 		return 0;
151 	return 1;
152 }
153 
154 int
reply_info_alloc_rrset_keys(struct reply_info * rep,struct alloc_cache * alloc,struct regional * region)155 reply_info_alloc_rrset_keys(struct reply_info* rep, struct alloc_cache* alloc,
156 	struct regional* region)
157 {
158 	size_t i;
159 	for(i=0; i<rep->rrset_count; i++) {
160 		if(region) {
161 			rep->rrsets[i] = (struct ub_packed_rrset_key*)
162 				regional_alloc(region,
163 				sizeof(struct ub_packed_rrset_key));
164 			if(rep->rrsets[i]) {
165 				memset(rep->rrsets[i], 0,
166 					sizeof(struct ub_packed_rrset_key));
167 				rep->rrsets[i]->entry.key = rep->rrsets[i];
168 			}
169 		}
170 		else	rep->rrsets[i] = alloc_special_obtain(alloc);
171 		if(!rep->rrsets[i])
172 			return 0;
173 		rep->rrsets[i]->entry.data = NULL;
174 	}
175 	return 1;
176 }
177 
178 int
reply_info_can_answer_expired(struct reply_info * rep,time_t timenow)179 reply_info_can_answer_expired(struct reply_info* rep, time_t timenow)
180 {
181 	log_assert(TTL_IS_EXPIRED(rep->ttl, timenow));
182 	/* Really expired */
183 	if(SERVE_EXPIRED_TTL && TTL_IS_EXPIRED(rep->serve_expired_ttl, timenow)) return 0;
184 	/* Ignore expired failure answers */
185 	if(FLAGS_GET_RCODE(rep->flags) != LDNS_RCODE_NOERROR &&
186 		FLAGS_GET_RCODE(rep->flags) != LDNS_RCODE_NXDOMAIN &&
187 		FLAGS_GET_RCODE(rep->flags) != LDNS_RCODE_YXDOMAIN) return 0;
188 	return 1;
189 }
190 
191 int
reply_info_could_use_expired(struct reply_info * rep,time_t timenow)192 reply_info_could_use_expired(struct reply_info* rep, time_t timenow)
193 {
194 	log_assert(TTL_IS_EXPIRED(rep->ttl, timenow));
195 	/* Really expired */
196 	if(SERVE_EXPIRED_TTL && TTL_IS_EXPIRED(rep->serve_expired_ttl, timenow)
197 		&& !SERVE_EXPIRED_TTL_RESET) return 0;
198 	/* Ignore expired failure answers */
199 	if(FLAGS_GET_RCODE(rep->flags) != LDNS_RCODE_NOERROR &&
200 		FLAGS_GET_RCODE(rep->flags) != LDNS_RCODE_NXDOMAIN &&
201 		FLAGS_GET_RCODE(rep->flags) != LDNS_RCODE_YXDOMAIN) return 0;
202 	return 1;
203 }
204 
205 struct reply_info *
make_new_reply_info(const struct reply_info * rep,struct regional * region,size_t an_numrrsets,size_t copy_rrsets)206 make_new_reply_info(const struct reply_info* rep, struct regional* region,
207 	size_t an_numrrsets, size_t copy_rrsets)
208 {
209 	struct reply_info* new_rep;
210 	size_t i;
211 
212 	/* create a base struct.  we specify 'insecure' security status as
213 	 * the modified response won't be DNSSEC-valid.  In our faked response
214 	 * the authority and additional sections will be empty (except possible
215 	 * EDNS0 OPT RR in the additional section appended on sending it out),
216 	 * so the total number of RRsets is an_numrrsets. */
217 	new_rep = construct_reply_info_base(region, rep->flags,
218 		rep->qdcount, rep->ttl, rep->prefetch_ttl,
219 		rep->serve_expired_ttl, rep->serve_expired_norec_ttl,
220 		an_numrrsets, 0, 0, an_numrrsets,
221 		sec_status_insecure, LDNS_EDE_NONE);
222 	if(!new_rep)
223 		return NULL;
224 	if(!reply_info_alloc_rrset_keys(new_rep, NULL, region))
225 		return NULL;
226 	for(i=0; i<copy_rrsets; i++)
227 		new_rep->rrsets[i] = rep->rrsets[i];
228 
229 	return new_rep;
230 }
231 
232 /** find the minimumttl in the rdata of SOA record */
233 static uint32_t
soa_find_minttl(struct rr_parse * rr)234 soa_find_minttl(struct rr_parse* rr)
235 {
236 	uint16_t rlen = sldns_read_uint16(rr->ttl_data+4);
237 	if(rlen < 20)
238 		return 0; /* rdata too small for SOA (dname, dname, 5*32bit) */
239 	/* minimum TTL is the last 32bit value in the rdata of the record */
240 	/* at position ttl_data + 4(ttl) + 2(rdatalen) + rdatalen - 4(timeval)*/
241 	return sldns_read_uint32(rr->ttl_data+6+rlen-4);
242 }
243 
244 /** do the rdata copy */
245 static int
rdata_copy(sldns_buffer * pkt,struct packed_rrset_data * data,uint8_t * to,struct rr_parse * rr,time_t * rr_ttl,uint16_t type,sldns_pkt_section section)246 rdata_copy(sldns_buffer* pkt, struct packed_rrset_data* data, uint8_t* to,
247 	struct rr_parse* rr, time_t* rr_ttl, uint16_t type,
248 	sldns_pkt_section section)
249 {
250 	uint16_t pkt_len;
251 	uint32_t ttl;
252 	const sldns_rr_descriptor* desc;
253 
254 	ttl = sldns_read_uint32(rr->ttl_data);
255 	/* RFC 2181 Section 8. if msb of ttl is set treat as if zero. */
256 	/* RFC 8767 Section 4. values with high-order bit as positive, not 0.
257 +	 *	As such, it will be capped by MAX_TTL below. */
258 	if(type == LDNS_RR_TYPE_SOA && section == LDNS_SECTION_AUTHORITY) {
259 		/* negative response. see if TTL of SOA record larger than the
260 		 * minimum-ttl in the rdata of the SOA record */
261 		if(ttl > soa_find_minttl(rr)) ttl = soa_find_minttl(rr);
262 		if(!SERVE_ORIGINAL_TTL) {
263 			/* If MIN_NEG_TTL is configured skip setting MIN_TTL */
264 			if(MIN_NEG_TTL <= 0 && ttl < (uint32_t)MIN_TTL) {
265 				ttl = (uint32_t)MIN_TTL;
266 			}
267 			if(ttl > (uint32_t)MAX_TTL) ttl = (uint32_t)MAX_TTL;
268 		}
269 		/* MAX_NEG_TTL overrides the min and max ttl of everything
270 		 * else; it is for a more specific record */
271 		if(ttl > (uint32_t)MAX_NEG_TTL) ttl = (uint32_t)MAX_NEG_TTL;
272 		/* MIN_NEG_TTL overrides the min and max ttl of everything
273 		 * else if configured; it is for a more specific record */
274 		if(MIN_NEG_TTL > 0 && ttl < (uint32_t)MIN_NEG_TTL) {
275 			ttl = (uint32_t)MIN_NEG_TTL;
276 		}
277 	} else if(!SERVE_ORIGINAL_TTL) {
278 		if(ttl < (uint32_t)MIN_TTL) ttl = (uint32_t)MIN_TTL;
279 		if(ttl > (uint32_t)MAX_TTL) ttl = (uint32_t)MAX_TTL;
280 	}
281 	if((time_t)ttl < data->ttl)
282 		data->ttl = (time_t)ttl;
283 	/* We have concluded the TTL checks */
284 	*rr_ttl = (time_t)ttl;
285 
286 	if(rr->outside_packet) {
287 		/* uncompressed already, only needs copy */
288 		memmove(to, rr->ttl_data+sizeof(uint32_t), rr->size);
289 		return 1;
290 	}
291 
292 	sldns_buffer_set_position(pkt, (size_t)
293 		(rr->ttl_data - sldns_buffer_begin(pkt) + sizeof(uint32_t)));
294 	/* insert decompressed size into rdata len stored in memory */
295 	/* -2 because rdatalen bytes are not included. */
296 	pkt_len = htons(rr->size - 2);
297 	memmove(to, &pkt_len, sizeof(uint16_t));
298 	to += 2;
299 	/* read packet rdata len */
300 	pkt_len = sldns_buffer_read_u16(pkt);
301 	if(sldns_buffer_remaining(pkt) < pkt_len)
302 		return 0;
303 	desc = sldns_rr_descript(type);
304 	if(pkt_len > 0 && desc && desc->_dname_count > 0) {
305 		int count = (int)desc->_dname_count;
306 		int rdf = 0;
307 		size_t len;
308 		size_t oldpos;
309 		/* decompress dnames. */
310 		while(pkt_len > 0 && count) {
311 			switch(desc->_wireformat[rdf]) {
312 			case LDNS_RDF_TYPE_DNAME:
313 				oldpos = sldns_buffer_position(pkt);
314 				dname_pkt_copy(pkt, to,
315 					sldns_buffer_current(pkt));
316 				to += pkt_dname_len(pkt);
317 				pkt_len -= sldns_buffer_position(pkt)-oldpos;
318 				count--;
319 				len = 0;
320 				break;
321 			case LDNS_RDF_TYPE_STR:
322 				len = sldns_buffer_current(pkt)[0] + 1;
323 				break;
324 			default:
325 				len = get_rdf_size(desc->_wireformat[rdf]);
326 				break;
327 			}
328 			if(len) {
329 				log_assert(len <= pkt_len);
330 				memmove(to, sldns_buffer_current(pkt), len);
331 				to += len;
332 				sldns_buffer_skip(pkt, (ssize_t)len);
333 				pkt_len -= len;
334 			}
335 			rdf++;
336 		}
337 	}
338 	/* copy remaining rdata */
339 	if(pkt_len >  0)
340 		memmove(to, sldns_buffer_current(pkt), pkt_len);
341 
342 	return 1;
343 }
344 
345 /** copy over the data into packed rrset */
346 static int
parse_rr_copy(sldns_buffer * pkt,struct rrset_parse * pset,struct packed_rrset_data * data)347 parse_rr_copy(sldns_buffer* pkt, struct rrset_parse* pset,
348 	struct packed_rrset_data* data)
349 {
350 	size_t i;
351 	struct rr_parse* rr = pset->rr_first;
352 	uint8_t* nextrdata;
353 	size_t total = pset->rr_count + pset->rrsig_count;
354 	data->ttl = MAX_TTL;
355 	data->count = pset->rr_count;
356 	data->rrsig_count = pset->rrsig_count;
357 	data->trust = rrset_trust_none;
358 	data->security = sec_status_unchecked;
359 	/* layout: struct - rr_len - rr_data - rr_ttl - rdata - rrsig */
360 	data->rr_len = (size_t*)((uint8_t*)data +
361 		sizeof(struct packed_rrset_data));
362 	data->rr_data = (uint8_t**)&(data->rr_len[total]);
363 	data->rr_ttl = (time_t*)&(data->rr_data[total]);
364 	nextrdata = (uint8_t*)&(data->rr_ttl[total]);
365 	for(i=0; i<data->count; i++) {
366 		data->rr_len[i] = rr->size;
367 		data->rr_data[i] = nextrdata;
368 		nextrdata += rr->size;
369 		if(!rdata_copy(pkt, data, data->rr_data[i], rr,
370 			&data->rr_ttl[i], pset->type, pset->section))
371 			return 0;
372 		rr = rr->next;
373 	}
374 	/* if rrsig, its rdata is at nextrdata */
375 	rr = pset->rrsig_first;
376 	for(i=data->count; i<total; i++) {
377 		data->rr_len[i] = rr->size;
378 		data->rr_data[i] = nextrdata;
379 		nextrdata += rr->size;
380 		if(!rdata_copy(pkt, data, data->rr_data[i], rr,
381 			&data->rr_ttl[i], LDNS_RR_TYPE_RRSIG, pset->section))
382 			return 0;
383 		rr = rr->next;
384 	}
385 	return 1;
386 }
387 
388 /** create rrset return 0 on failure */
389 static int
parse_create_rrset(sldns_buffer * pkt,struct rrset_parse * pset,struct packed_rrset_data ** data,struct regional * region)390 parse_create_rrset(sldns_buffer* pkt, struct rrset_parse* pset,
391 	struct packed_rrset_data** data, struct regional* region)
392 {
393 	/* allocate */
394 	size_t s;
395 	if(pset->rr_count > RR_COUNT_MAX || pset->rrsig_count > RR_COUNT_MAX ||
396 		pset->size > RR_COUNT_MAX)
397 		return 0; /* protect against integer overflow */
398 	s = sizeof(struct packed_rrset_data) +
399 		(pset->rr_count + pset->rrsig_count) *
400 		(sizeof(size_t)+sizeof(uint8_t*)+sizeof(time_t)) +
401 		pset->size;
402 	if(region)
403 		*data = regional_alloc_zero(region, s);
404 	else	*data = calloc(1, s);
405 	if(!*data)
406 		return 0;
407 	/* copy & decompress */
408 	if(!parse_rr_copy(pkt, pset, *data)) {
409 		if(!region) {
410 			free(*data);
411 			*data = NULL;
412 		}
413 		return 0;
414 	}
415 	return 1;
416 }
417 
418 /** get trust value for rrset */
419 static enum rrset_trust
get_rrset_trust(struct msg_parse * msg,struct rrset_parse * rrset)420 get_rrset_trust(struct msg_parse* msg, struct rrset_parse* rrset)
421 {
422 	uint16_t AA = msg->flags & BIT_AA;
423 	if(rrset->section == LDNS_SECTION_ANSWER) {
424 		if(AA) {
425 			/* RFC2181 says remainder of CNAME chain is nonauth*/
426 			if(msg->rrset_first &&
427 				msg->rrset_first->section==LDNS_SECTION_ANSWER
428 				&& msg->rrset_first->type==LDNS_RR_TYPE_CNAME){
429 				if(rrset == msg->rrset_first)
430 					return rrset_trust_ans_AA;
431 				else 	return rrset_trust_ans_noAA;
432 			}
433 			if(msg->rrset_first &&
434 				msg->rrset_first->section==LDNS_SECTION_ANSWER
435 				&& msg->rrset_first->type==LDNS_RR_TYPE_DNAME){
436 				if(rrset == msg->rrset_first ||
437 				   rrset == msg->rrset_first->rrset_all_next)
438 					return rrset_trust_ans_AA;
439 				else 	return rrset_trust_ans_noAA;
440 			}
441 			return rrset_trust_ans_AA;
442 		}
443 		else	return rrset_trust_ans_noAA;
444 	} else if(rrset->section == LDNS_SECTION_AUTHORITY) {
445 		if(AA)	return rrset_trust_auth_AA;
446 		else	return rrset_trust_auth_noAA;
447 	} else {
448 		/* addit section */
449 		if(AA)	return rrset_trust_add_AA;
450 		else	return rrset_trust_add_noAA;
451 	}
452 	/* NOTREACHED */
453 	return rrset_trust_none;
454 }
455 
456 int
parse_copy_decompress_rrset(sldns_buffer * pkt,struct msg_parse * msg,struct rrset_parse * pset,struct regional * region,struct ub_packed_rrset_key * pk)457 parse_copy_decompress_rrset(sldns_buffer* pkt, struct msg_parse* msg,
458 	struct rrset_parse *pset, struct regional* region,
459 	struct ub_packed_rrset_key* pk)
460 {
461 	struct packed_rrset_data* data;
462 	pk->rk.flags = pset->flags;
463 	pk->rk.dname_len = pset->dname_len;
464 	if(region)
465 		pk->rk.dname = (uint8_t*)regional_alloc(
466 			region, pset->dname_len);
467 	else	pk->rk.dname =
468 			(uint8_t*)malloc(pset->dname_len);
469 	if(!pk->rk.dname)
470 		return 0;
471 	/** copy & decompress dname */
472 	dname_pkt_copy(pkt, pk->rk.dname, pset->dname);
473 	/** copy over type and class */
474 	pk->rk.type = htons(pset->type);
475 	pk->rk.rrset_class = pset->rrset_class;
476 	/** read data part. */
477 	if(!parse_create_rrset(pkt, pset, &data, region)) {
478 		if(!region) {
479 			free(pk->rk.dname);
480 			pk->rk.dname = NULL;
481 		}
482 		return 0;
483 	}
484 	pk->entry.data = (void*)data;
485 	pk->entry.key = (void*)pk;
486 	pk->rk.flags |= (data->ttl == 0) ? PACKED_RRSET_UPSTREAM_0TTL : 0;
487 	if( (pk->rk.flags & PACKED_RRSET_UPSTREAM_0TTL) != 0)
488 		pk->entry.hash = rrset_key_hash(&pk->rk);
489 	else
490 		pk->entry.hash = pset->hash;
491 	data->trust = get_rrset_trust(msg, pset);
492 	return 1;
493 }
494 
495 /**
496  * Copy and decompress rrs
497  * @param pkt: the packet for compression pointer resolution.
498  * @param msg: the parsed message
499  * @param rep: reply info to put rrs into.
500  * @param region: if not NULL, used for allocation.
501  * @return 0 on failure.
502  */
503 static int
parse_copy_decompress(sldns_buffer * pkt,struct msg_parse * msg,struct reply_info * rep,struct regional * region)504 parse_copy_decompress(sldns_buffer* pkt, struct msg_parse* msg,
505 	struct reply_info* rep, struct regional* region)
506 {
507 	size_t i;
508 	struct rrset_parse *pset = msg->rrset_first;
509 	struct packed_rrset_data* data;
510 	log_assert(rep);
511 	rep->ttl = MAX_TTL;
512 	rep->security = sec_status_unchecked;
513 	if(rep->rrset_count == 0)
514 		rep->ttl = NORR_TTL;
515 
516 	for(i=0; i<rep->rrset_count; i++) {
517 		if(!parse_copy_decompress_rrset(pkt, msg, pset, region,
518 			rep->rrsets[i]))
519 			return 0;
520 		data = (struct packed_rrset_data*)rep->rrsets[i]->entry.data;
521 		if(data->ttl < rep->ttl)
522 			rep->ttl = data->ttl;
523 
524 		pset = pset->rrset_all_next;
525 	}
526 	rep->prefetch_ttl = PREFETCH_TTL_CALC(rep->ttl);
527 	rep->serve_expired_ttl = rep->ttl + SERVE_EXPIRED_TTL;
528 	/* rep->serve_expired_norec_ttl should stay at 0 */
529 	log_assert(rep->serve_expired_norec_ttl == 0);
530 	return 1;
531 }
532 
533 int
parse_create_msg(sldns_buffer * pkt,struct msg_parse * msg,struct alloc_cache * alloc,struct query_info * qinf,struct reply_info ** rep,struct regional * region)534 parse_create_msg(sldns_buffer* pkt, struct msg_parse* msg,
535 	struct alloc_cache* alloc, struct query_info* qinf,
536 	struct reply_info** rep, struct regional* region)
537 {
538 	log_assert(pkt && msg);
539 	if(!parse_create_qinfo(pkt, msg, qinf, region))
540 		return 0;
541 	if(!parse_create_repinfo(msg, rep, region))
542 		return 0;
543 	if(!reply_info_alloc_rrset_keys(*rep, alloc, region)) {
544 		if(!region) reply_info_parsedelete(*rep, alloc);
545 		return 0;
546 	}
547 	if(!parse_copy_decompress(pkt, msg, *rep, region)) {
548 		if(!region) reply_info_parsedelete(*rep, alloc);
549 		return 0;
550 	}
551 	return 1;
552 }
553 
reply_info_parse(sldns_buffer * pkt,struct alloc_cache * alloc,struct query_info * qinf,struct reply_info ** rep,struct regional * region,struct edns_data * edns)554 int reply_info_parse(sldns_buffer* pkt, struct alloc_cache* alloc,
555         struct query_info* qinf, struct reply_info** rep,
556 	struct regional* region, struct edns_data* edns)
557 {
558 	/* use scratch pad region-allocator during parsing. */
559 	struct msg_parse* msg;
560 	int ret;
561 
562 	qinf->qname = NULL;
563 	qinf->local_alias = NULL;
564 	*rep = NULL;
565 	if(!(msg = regional_alloc(region, sizeof(*msg)))) {
566 		return LDNS_RCODE_SERVFAIL;
567 	}
568 	memset(msg, 0, sizeof(*msg));
569 
570 	sldns_buffer_set_position(pkt, 0);
571 	if((ret = parse_packet(pkt, msg, region)) != 0) {
572 		return ret;
573 	}
574 	if((ret = parse_extract_edns_from_response_msg(msg, edns, region)) != 0)
575 		return ret;
576 
577 	/* parse OK, allocate return structures */
578 	/* this also performs dname decompression */
579 	if(!parse_create_msg(pkt, msg, alloc, qinf, rep, NULL)) {
580 		query_info_clear(qinf);
581 		*rep = NULL;
582 		return LDNS_RCODE_SERVFAIL;
583 	}
584 	return 0;
585 }
586 
587 /** helper compare function to sort in lock order */
588 static int
reply_info_sortref_cmp(const void * a,const void * b)589 reply_info_sortref_cmp(const void* a, const void* b)
590 {
591 	struct rrset_ref* x = (struct rrset_ref*)a;
592 	struct rrset_ref* y = (struct rrset_ref*)b;
593 	if(x->key < y->key) return -1;
594 	if(x->key > y->key) return 1;
595 	return 0;
596 }
597 
598 void
reply_info_sortref(struct reply_info * rep)599 reply_info_sortref(struct reply_info* rep)
600 {
601 	qsort(&rep->ref[0], rep->rrset_count, sizeof(struct rrset_ref),
602 		reply_info_sortref_cmp);
603 }
604 
605 void
reply_info_set_ttls(struct reply_info * rep,time_t timenow)606 reply_info_set_ttls(struct reply_info* rep, time_t timenow)
607 {
608 	size_t i, j;
609 	rep->ttl += timenow;
610 	rep->prefetch_ttl += timenow;
611 	rep->serve_expired_ttl += timenow;
612 	/* Don't set rep->serve_expired_norec_ttl; this should only be set
613 	 * on cached records when encountering an error */
614 	log_assert(rep->serve_expired_norec_ttl == 0);
615 	for(i=0; i<rep->rrset_count; i++) {
616 		struct packed_rrset_data* data = (struct packed_rrset_data*)
617 			rep->ref[i].key->entry.data;
618 		if(i>0 && rep->ref[i].key == rep->ref[i-1].key)
619 			continue;
620 		data->ttl += timenow;
621 		for(j=0; j<data->count + data->rrsig_count; j++) {
622 			data->rr_ttl[j] += timenow;
623 		}
624 		data->ttl_add = timenow;
625 	}
626 }
627 
628 void
reply_info_absolute_ttls(struct reply_info * rep,time_t ttl,time_t ttl_add)629 reply_info_absolute_ttls(struct reply_info* rep, time_t ttl, time_t ttl_add)
630 {
631 	size_t i, j;
632 	rep->ttl = ttl;
633 	rep->prefetch_ttl = PREFETCH_TTL_CALC(ttl);
634 	rep->serve_expired_ttl = ttl + SERVE_EXPIRED_TTL;
635 	/* Don't set rep->serve_expired_norec_ttl; this should only be set
636 	 * on cached records when encountering an error */
637 	log_assert(rep->serve_expired_norec_ttl == 0);
638 	for(i=0; i<rep->rrset_count; i++) {
639 		struct packed_rrset_data* data = (struct packed_rrset_data*)
640 			rep->ref[i].key->entry.data;
641 		if(i>0 && rep->ref[i].key == rep->ref[i-1].key)
642 			continue;
643 		data->ttl = ttl;
644 		for(j=0; j<data->count + data->rrsig_count; j++) {
645 			data->rr_ttl[j] = ttl;
646 		}
647 		data->ttl_add = ttl_add;
648 	}
649 }
650 
651 void
reply_info_parsedelete(struct reply_info * rep,struct alloc_cache * alloc)652 reply_info_parsedelete(struct reply_info* rep, struct alloc_cache* alloc)
653 {
654 	size_t i;
655 	if(!rep)
656 		return;
657 	/* no need to lock, since not shared in hashtables. */
658 	for(i=0; i<rep->rrset_count; i++) {
659 		ub_packed_rrset_parsedelete(rep->rrsets[i], alloc);
660 	}
661 	if(rep->reason_bogus_str) {
662 		free(rep->reason_bogus_str);
663 		rep->reason_bogus_str = NULL;
664 	}
665 	free(rep);
666 }
667 
668 int
query_info_parse(struct query_info * m,sldns_buffer * query)669 query_info_parse(struct query_info* m, sldns_buffer* query)
670 {
671 	uint8_t* q = sldns_buffer_begin(query);
672 	/* minimum size: header + \0 + qtype + qclass */
673 	if(sldns_buffer_limit(query) < LDNS_HEADER_SIZE + 5)
674 		return 0;
675 	if((LDNS_OPCODE_WIRE(q) != LDNS_PACKET_QUERY && LDNS_OPCODE_WIRE(q) !=
676 		LDNS_PACKET_NOTIFY) || LDNS_QDCOUNT(q) != 1 ||
677 		sldns_buffer_position(query) != 0)
678 		return 0;
679 	sldns_buffer_skip(query, LDNS_HEADER_SIZE);
680 	m->qname = sldns_buffer_current(query);
681 	if((m->qname_len = query_dname_len(query)) == 0)
682 		return 0; /* parse error */
683 	if(sldns_buffer_remaining(query) < 4)
684 		return 0; /* need qtype, qclass */
685 	m->qtype = sldns_buffer_read_u16(query);
686 	m->qclass = sldns_buffer_read_u16(query);
687 	m->local_alias = NULL;
688 	return 1;
689 }
690 
691 /** tiny subroutine for msgreply_compare */
692 #define COMPARE_IT(x, y) \
693 	if( (x) < (y) ) return -1; \
694 	else if( (x) > (y) ) return +1; \
695 	log_assert( (x) == (y) );
696 
697 int
query_info_compare(void * m1,void * m2)698 query_info_compare(void* m1, void* m2)
699 {
700 	struct query_info* msg1 = (struct query_info*)m1;
701 	struct query_info* msg2 = (struct query_info*)m2;
702 	int mc;
703 	/* from most different to least different for speed */
704 	COMPARE_IT(msg1->qtype, msg2->qtype);
705 	if((mc = query_dname_compare(msg1->qname, msg2->qname)) != 0)
706 		return mc;
707 	log_assert(msg1->qname_len == msg2->qname_len);
708 	COMPARE_IT(msg1->qclass, msg2->qclass);
709 	return 0;
710 #undef COMPARE_IT
711 }
712 
713 void
query_info_clear(struct query_info * m)714 query_info_clear(struct query_info* m)
715 {
716 	free(m->qname);
717 	m->qname = NULL;
718 }
719 
720 size_t
msgreply_sizefunc(void * k,void * d)721 msgreply_sizefunc(void* k, void* d)
722 {
723 	struct msgreply_entry* q = (struct msgreply_entry*)k;
724 	struct reply_info* r = (struct reply_info*)d;
725 	size_t s = sizeof(struct msgreply_entry) + sizeof(struct reply_info)
726 		+ q->key.qname_len + lock_get_mem(&q->entry.lock)
727 		- sizeof(struct rrset_ref);
728 	s += r->rrset_count * sizeof(struct rrset_ref);
729 	s += r->rrset_count * sizeof(struct ub_packed_rrset_key*);
730 	return s;
731 }
732 
733 void
query_entry_delete(void * k,void * ATTR_UNUSED (arg))734 query_entry_delete(void *k, void* ATTR_UNUSED(arg))
735 {
736 	struct msgreply_entry* q = (struct msgreply_entry*)k;
737 	lock_rw_destroy(&q->entry.lock);
738 	query_info_clear(&q->key);
739 	free(q);
740 }
741 
742 void
reply_info_delete(void * d,void * ATTR_UNUSED (arg))743 reply_info_delete(void* d, void* ATTR_UNUSED(arg))
744 {
745 	struct reply_info* r = (struct reply_info*)d;
746 	if(r->reason_bogus_str) {
747 		free(r->reason_bogus_str);
748 		r->reason_bogus_str = NULL;
749 	}
750 	free(r);
751 }
752 
753 hashvalue_type
query_info_hash(struct query_info * q,uint16_t flags)754 query_info_hash(struct query_info *q, uint16_t flags)
755 {
756 	hashvalue_type h = 0xab;
757 	h = hashlittle(&q->qtype, sizeof(q->qtype), h);
758 	if(q->qtype == LDNS_RR_TYPE_AAAA && (flags&BIT_CD))
759 		h++;
760 	h = hashlittle(&q->qclass, sizeof(q->qclass), h);
761 	h = dname_query_hash(q->qname, h);
762 	return h;
763 }
764 
765 struct msgreply_entry*
query_info_entrysetup(struct query_info * q,struct reply_info * r,hashvalue_type h)766 query_info_entrysetup(struct query_info* q, struct reply_info* r,
767 	hashvalue_type h)
768 {
769 	struct msgreply_entry* e = (struct msgreply_entry*)malloc(
770 		sizeof(struct msgreply_entry));
771 	if(!e) return NULL;
772 	memcpy(&e->key, q, sizeof(*q));
773 	e->entry.hash = h;
774 	e->entry.key = e;
775 	e->entry.data = r;
776 	lock_rw_init(&e->entry.lock);
777 	lock_protect(&e->entry.lock, &e->key.qname, sizeof(e->key.qname));
778 	lock_protect(&e->entry.lock, &e->key.qname_len, sizeof(e->key.qname_len));
779 	lock_protect(&e->entry.lock, &e->key.qtype, sizeof(e->key.qtype));
780 	lock_protect(&e->entry.lock, &e->key.qclass, sizeof(e->key.qclass));
781 	lock_protect(&e->entry.lock, &e->key.local_alias, sizeof(e->key.local_alias));
782 	lock_protect(&e->entry.lock, &e->entry.hash, sizeof(e->entry.hash));
783 	lock_protect(&e->entry.lock, &e->entry.key, sizeof(e->entry.key));
784 	lock_protect(&e->entry.lock, &e->entry.data, sizeof(e->entry.data));
785 	lock_protect(&e->entry.lock, e->key.qname, e->key.qname_len);
786 	q->qname = NULL;
787 	return e;
788 }
789 
790 /** copy rrsets from replyinfo to dest replyinfo */
791 static int
repinfo_copy_rrsets(struct reply_info * dest,struct reply_info * from,struct regional * region)792 repinfo_copy_rrsets(struct reply_info* dest, struct reply_info* from,
793 	struct regional* region)
794 {
795 	size_t i, s;
796 	struct packed_rrset_data* fd, *dd;
797 	struct ub_packed_rrset_key* fk, *dk;
798 	for(i=0; i<dest->rrset_count; i++) {
799 		fk = from->rrsets[i];
800 		dk = dest->rrsets[i];
801 		fd = (struct packed_rrset_data*)fk->entry.data;
802 		dk->entry.hash = fk->entry.hash;
803 		dk->rk = fk->rk;
804 		if(region) {
805 			dk->id = fk->id;
806 			dk->rk.dname = (uint8_t*)regional_alloc_init(region,
807 				fk->rk.dname, fk->rk.dname_len);
808 		} else
809 			dk->rk.dname = (uint8_t*)memdup(fk->rk.dname,
810 				fk->rk.dname_len);
811 		if(!dk->rk.dname)
812 			return 0;
813 		s = packed_rrset_sizeof(fd);
814 		if(region)
815 			dd = (struct packed_rrset_data*)regional_alloc_init(
816 				region, fd, s);
817 		else	dd = (struct packed_rrset_data*)memdup(fd, s);
818 		if(!dd)
819 			return 0;
820 		packed_rrset_ptr_fixup(dd);
821 		dk->entry.data = (void*)dd;
822 	}
823 	return 1;
824 }
825 
826 struct reply_info*
reply_info_copy(struct reply_info * rep,struct alloc_cache * alloc,struct regional * region)827 reply_info_copy(struct reply_info* rep, struct alloc_cache* alloc,
828 	struct regional* region)
829 {
830 	struct reply_info* cp;
831 	cp = construct_reply_info_base(region, rep->flags, rep->qdcount,
832 		rep->ttl, rep->prefetch_ttl, rep->serve_expired_ttl,
833 		rep->serve_expired_norec_ttl,
834 		rep->an_numrrsets, rep->ns_numrrsets, rep->ar_numrrsets,
835 		rep->rrset_count, rep->security, rep->reason_bogus);
836 	if(!cp)
837 		return NULL;
838 
839 	if(rep->reason_bogus_str && *rep->reason_bogus_str != 0) {
840 		if(region) {
841 			cp->reason_bogus_str = (char*)regional_alloc(region,
842 				sizeof(char)
843 				* (strlen(rep->reason_bogus_str)+1));
844 		} else {
845 			cp->reason_bogus_str = malloc(sizeof(char)
846 				* (strlen(rep->reason_bogus_str)+1));
847 		}
848 		if(!cp->reason_bogus_str) {
849 			if(!region)
850 				reply_info_parsedelete(cp, alloc);
851 			return NULL;
852 		}
853 		memcpy(cp->reason_bogus_str, rep->reason_bogus_str,
854 			strlen(rep->reason_bogus_str)+1);
855 	}
856 
857 	/* allocate ub_key structures special or not */
858 	if(!reply_info_alloc_rrset_keys(cp, alloc, region)) {
859 		if(!region)
860 			reply_info_parsedelete(cp, alloc);
861 		return NULL;
862 	}
863 	if(!repinfo_copy_rrsets(cp, rep, region)) {
864 		if(!region)
865 			reply_info_parsedelete(cp, alloc);
866 		return NULL;
867 	}
868 	return cp;
869 }
870 
871 uint8_t*
reply_find_final_cname_target(struct query_info * qinfo,struct reply_info * rep)872 reply_find_final_cname_target(struct query_info* qinfo, struct reply_info* rep)
873 {
874 	uint8_t* sname = qinfo->qname;
875 	size_t snamelen = qinfo->qname_len;
876 	size_t i;
877 	for(i=0; i<rep->an_numrrsets; i++) {
878 		struct ub_packed_rrset_key* s = rep->rrsets[i];
879 		/* follow CNAME chain (if any) */
880 		if(ntohs(s->rk.type) == LDNS_RR_TYPE_CNAME &&
881 			ntohs(s->rk.rrset_class) == qinfo->qclass &&
882 			snamelen == s->rk.dname_len &&
883 			query_dname_compare(sname, s->rk.dname) == 0) {
884 			get_cname_target(s, &sname, &snamelen);
885 		}
886 	}
887 	if(sname != qinfo->qname)
888 		return sname;
889 	return NULL;
890 }
891 
892 struct ub_packed_rrset_key*
reply_find_answer_rrset(struct query_info * qinfo,struct reply_info * rep)893 reply_find_answer_rrset(struct query_info* qinfo, struct reply_info* rep)
894 {
895 	uint8_t* sname = qinfo->qname;
896 	size_t snamelen = qinfo->qname_len;
897 	size_t i;
898 	for(i=0; i<rep->an_numrrsets; i++) {
899 		struct ub_packed_rrset_key* s = rep->rrsets[i];
900 		/* first match type, for query of qtype cname */
901 		if(ntohs(s->rk.type) == qinfo->qtype &&
902 			ntohs(s->rk.rrset_class) == qinfo->qclass &&
903 			snamelen == s->rk.dname_len &&
904 			query_dname_compare(sname, s->rk.dname) == 0) {
905 			return s;
906 		}
907 		/* follow CNAME chain (if any) */
908 		if(ntohs(s->rk.type) == LDNS_RR_TYPE_CNAME &&
909 			ntohs(s->rk.rrset_class) == qinfo->qclass &&
910 			snamelen == s->rk.dname_len &&
911 			query_dname_compare(sname, s->rk.dname) == 0) {
912 			get_cname_target(s, &sname, &snamelen);
913 		}
914 	}
915 	return NULL;
916 }
917 
reply_find_rrset_section_an(struct reply_info * rep,uint8_t * name,size_t namelen,uint16_t type,uint16_t dclass)918 struct ub_packed_rrset_key* reply_find_rrset_section_an(struct reply_info* rep,
919 	uint8_t* name, size_t namelen, uint16_t type, uint16_t dclass)
920 {
921 	size_t i;
922 	for(i=0; i<rep->an_numrrsets; i++) {
923 		struct ub_packed_rrset_key* s = rep->rrsets[i];
924 		if(ntohs(s->rk.type) == type &&
925 			ntohs(s->rk.rrset_class) == dclass &&
926 			namelen == s->rk.dname_len &&
927 			query_dname_compare(name, s->rk.dname) == 0) {
928 			return s;
929 		}
930 	}
931 	return NULL;
932 }
933 
reply_find_rrset_section_ns(struct reply_info * rep,uint8_t * name,size_t namelen,uint16_t type,uint16_t dclass)934 struct ub_packed_rrset_key* reply_find_rrset_section_ns(struct reply_info* rep,
935 	uint8_t* name, size_t namelen, uint16_t type, uint16_t dclass)
936 {
937 	size_t i;
938 	for(i=rep->an_numrrsets; i<rep->an_numrrsets+rep->ns_numrrsets; i++) {
939 		struct ub_packed_rrset_key* s = rep->rrsets[i];
940 		if(ntohs(s->rk.type) == type &&
941 			ntohs(s->rk.rrset_class) == dclass &&
942 			namelen == s->rk.dname_len &&
943 			query_dname_compare(name, s->rk.dname) == 0) {
944 			return s;
945 		}
946 	}
947 	return NULL;
948 }
949 
reply_find_rrset(struct reply_info * rep,uint8_t * name,size_t namelen,uint16_t type,uint16_t dclass)950 struct ub_packed_rrset_key* reply_find_rrset(struct reply_info* rep,
951 	uint8_t* name, size_t namelen, uint16_t type, uint16_t dclass)
952 {
953 	size_t i;
954 	for(i=0; i<rep->rrset_count; i++) {
955 		struct ub_packed_rrset_key* s = rep->rrsets[i];
956 		if(ntohs(s->rk.type) == type &&
957 			ntohs(s->rk.rrset_class) == dclass &&
958 			namelen == s->rk.dname_len &&
959 			query_dname_compare(name, s->rk.dname) == 0) {
960 			return s;
961 		}
962 	}
963 	return NULL;
964 }
965 
966 void
log_dns_msg(const char * str,struct query_info * qinfo,struct reply_info * rep)967 log_dns_msg(const char* str, struct query_info* qinfo, struct reply_info* rep)
968 {
969 	/* not particularly fast but flexible, make wireformat and print */
970 	sldns_buffer* buf = sldns_buffer_new(65535);
971 	struct regional* region = regional_create();
972 	if(!(buf && region)) {
973 		log_err("%s: log_dns_msg: out of memory", str);
974 		sldns_buffer_free(buf);
975 		regional_destroy(region);
976 		return;
977 	}
978 	if(!reply_info_encode(qinfo, rep, 0, rep->flags, buf, 0,
979 		region, 65535, 1, 0)) {
980 		log_err("%s: log_dns_msg: out of memory", str);
981 	} else {
982 		char* s = sldns_wire2str_pkt(sldns_buffer_begin(buf),
983 			sldns_buffer_limit(buf));
984 		if(!s) {
985 			log_info("%s: log_dns_msg: ldns tostr failed", str);
986 		} else {
987 			log_info("%s %s", str, s);
988 		}
989 		free(s);
990 	}
991 	sldns_buffer_free(buf);
992 	regional_destroy(region);
993 }
994 
995 void
log_reply_info(enum verbosity_value v,struct query_info * qinf,struct sockaddr_storage * addr,socklen_t addrlen,struct timeval dur,int cached,struct sldns_buffer * rmsg,struct sockaddr_storage * daddr,enum comm_point_type tp,void * ssl)996 log_reply_info(enum verbosity_value v, struct query_info *qinf,
997 	struct sockaddr_storage *addr, socklen_t addrlen, struct timeval dur,
998 	int cached, struct sldns_buffer *rmsg, struct sockaddr_storage* daddr,
999 	enum comm_point_type tp, void* ssl)
1000 {
1001 	char clientip_buf[128];
1002 	char rcode_buf[16];
1003 	char dest_buf[160];
1004 	uint16_t rcode = FLAGS_GET_RCODE(sldns_buffer_read_u16_at(rmsg, 2));
1005 
1006 	if(verbosity < v)
1007 	  return;
1008 
1009 	sldns_wire2str_rcode_buf((int)rcode, rcode_buf, sizeof(rcode_buf));
1010 	addr_to_str(addr, addrlen, clientip_buf, sizeof(clientip_buf));
1011 	if(daddr) {
1012 		char da[128];
1013 		int port = 0;
1014 		char* comm;
1015 		if(daddr->ss_family == AF_INET6) {
1016 			struct sockaddr_in6 *d = (struct sockaddr_in6 *)daddr;
1017 			if(inet_ntop(d->sin6_family, &d->sin6_addr, da,
1018 				sizeof(da)) == 0)
1019 				snprintf(dest_buf, sizeof(dest_buf),
1020 					"(inet_ntop_error)");
1021 			port = ntohs(d->sin6_port);
1022 		} else if(daddr->ss_family == AF_INET) {
1023 			struct sockaddr_in *d = (struct sockaddr_in *)daddr;
1024 			if(inet_ntop(d->sin_family, &d->sin_addr, da,
1025 				sizeof(da)) == 0)
1026 				snprintf(dest_buf, sizeof(dest_buf),
1027 					"(inet_ntop_error)");
1028 			port = ntohs(d->sin_port);
1029 		} else {
1030 			snprintf(da, sizeof(da), "socket%d",
1031 				(int)daddr->ss_family);
1032 		}
1033 		comm = "udp";
1034 		if(tp == comm_tcp) comm = (ssl?"dot":"tcp");
1035 		else if(tp == comm_tcp_accept) comm = (ssl?"dot":"tcp");
1036 		else if(tp == comm_http) comm = "doh";
1037 		else if(tp == comm_local) comm = "unix";
1038 		else if(tp == comm_raw) comm = "raw";
1039 		snprintf(dest_buf, sizeof(dest_buf), " on %s %s %d",
1040 			comm, da, port);
1041 	} else {
1042 		dest_buf[0]=0;
1043 	}
1044 	if(rcode == LDNS_RCODE_FORMERR)
1045 	{
1046 		if(LOG_TAG_QUERYREPLY)
1047 			log_reply("%s - - - %s - - -%s", clientip_buf,
1048 				rcode_buf, dest_buf);
1049 		else	log_info("%s - - - %s - - -%s", clientip_buf,
1050 				rcode_buf, dest_buf);
1051 	} else {
1052 		char qname_buf[LDNS_MAX_DOMAINLEN];
1053 		char type_buf[16];
1054 		char class_buf[16];
1055 		size_t pktlen;
1056 		if(qinf->qname)
1057 			dname_str(qinf->qname, qname_buf);
1058 		else	snprintf(qname_buf, sizeof(qname_buf), "null");
1059 		pktlen = sldns_buffer_limit(rmsg);
1060 		sldns_wire2str_type_buf(qinf->qtype, type_buf, sizeof(type_buf));
1061 		sldns_wire2str_class_buf(qinf->qclass, class_buf, sizeof(class_buf));
1062 		if(LOG_TAG_QUERYREPLY)
1063 		     log_reply("%s %s %s %s %s " ARG_LL "d.%6.6d %d %d%s",
1064 			clientip_buf, qname_buf, type_buf, class_buf,
1065 			rcode_buf, (long long)dur.tv_sec, (int)dur.tv_usec,
1066 			cached, (int)pktlen, dest_buf);
1067 		else log_info("%s %s %s %s %s " ARG_LL "d.%6.6d %d %d%s",
1068 			clientip_buf, qname_buf, type_buf, class_buf,
1069 			rcode_buf, (long long)dur.tv_sec, (int)dur.tv_usec,
1070 			cached, (int)pktlen, dest_buf);
1071 	}
1072 }
1073 
1074 void
log_query_info(enum verbosity_value v,const char * str,struct query_info * qinf)1075 log_query_info(enum verbosity_value v, const char* str,
1076 	struct query_info* qinf)
1077 {
1078 	log_nametypeclass(v, str, qinf->qname, qinf->qtype, qinf->qclass);
1079 }
1080 
1081 int
reply_check_cname_chain(struct query_info * qinfo,struct reply_info * rep)1082 reply_check_cname_chain(struct query_info* qinfo, struct reply_info* rep)
1083 {
1084 	/* check only answer section rrs for matching cname chain.
1085 	 * the cache may return changed rdata, but owner names are untouched.*/
1086 	size_t i;
1087 	uint8_t* sname = qinfo->qname;
1088 	size_t snamelen = qinfo->qname_len;
1089 	for(i=0; i<rep->an_numrrsets; i++) {
1090 		uint16_t t = ntohs(rep->rrsets[i]->rk.type);
1091 		if(t == LDNS_RR_TYPE_DNAME)
1092 			continue; /* skip dnames; note TTL 0 not cached */
1093 		/* verify that owner matches current sname */
1094 		if(query_dname_compare(sname, rep->rrsets[i]->rk.dname) != 0){
1095 			/* cname chain broken */
1096 			return 0;
1097 		}
1098 		/* if this is a cname; move on */
1099 		if(t == LDNS_RR_TYPE_CNAME) {
1100 			get_cname_target(rep->rrsets[i], &sname, &snamelen);
1101 		}
1102 	}
1103 	return 1;
1104 }
1105 
1106 int
reply_all_rrsets_secure(struct reply_info * rep)1107 reply_all_rrsets_secure(struct reply_info* rep)
1108 {
1109 	size_t i;
1110 	for(i=0; i<rep->rrset_count; i++) {
1111 		if( ((struct packed_rrset_data*)rep->rrsets[i]->entry.data)
1112 			->security != sec_status_secure )
1113 		return 0;
1114 	}
1115 	return 1;
1116 }
1117 
1118 struct reply_info*
parse_reply_in_temp_region(sldns_buffer * pkt,struct regional * region,struct query_info * qi)1119 parse_reply_in_temp_region(sldns_buffer* pkt, struct regional* region,
1120 	struct query_info* qi)
1121 {
1122 	struct reply_info* rep;
1123 	struct msg_parse* msg;
1124 	if(!(msg = regional_alloc(region, sizeof(*msg)))) {
1125 		return NULL;
1126 	}
1127 	memset(msg, 0, sizeof(*msg));
1128 	sldns_buffer_set_position(pkt, 0);
1129 	if(parse_packet(pkt, msg, region) != 0){
1130 		return 0;
1131 	}
1132 	if(!parse_create_msg(pkt, msg, NULL, qi, &rep, region)) {
1133 		return 0;
1134 	}
1135 	return rep;
1136 }
1137 
edns_opt_list_append_ede(struct edns_option ** list,struct regional * region,sldns_ede_code code,const char * txt)1138 int edns_opt_list_append_ede(struct edns_option** list, struct regional* region,
1139 	sldns_ede_code code, const char *txt)
1140 {
1141 	struct edns_option** prevp;
1142 	struct edns_option* opt;
1143 	size_t txt_len = txt ? strlen(txt) : 0;
1144 
1145 	/* allocate new element */
1146 	opt = (struct edns_option*)regional_alloc(region, sizeof(*opt));
1147 	if(!opt)
1148 		return 0;
1149 	opt->next = NULL;
1150 	opt->opt_code = LDNS_EDNS_EDE;
1151 	opt->opt_len = txt_len + sizeof(uint16_t);
1152 	opt->opt_data = regional_alloc(region, txt_len + sizeof(uint16_t));
1153 	if(!opt->opt_data)
1154 		return 0;
1155 	sldns_write_uint16(opt->opt_data, (uint16_t)code);
1156 	if (txt_len)
1157 		memmove(opt->opt_data + 2, txt, txt_len);
1158 
1159 	/* append at end of list */
1160 	prevp = list;
1161 	while(*prevp != NULL)
1162 		prevp = &((*prevp)->next);
1163 	verbose(VERB_ALGO, "attached EDE code: %d with message: '%s'", code, (txt?txt:""));
1164 	*prevp = opt;
1165 	return 1;
1166 }
1167 
edns_opt_list_append_keepalive(struct edns_option ** list,int msec,struct regional * region)1168 int edns_opt_list_append_keepalive(struct edns_option** list, int msec,
1169 	struct regional* region)
1170 {
1171 	uint8_t data[2]; /* For keepalive value */
1172 	data[0] = (uint8_t)((msec >> 8) & 0xff);
1173 	data[1] = (uint8_t)(msec & 0xff);
1174 	return edns_opt_list_append(list, LDNS_EDNS_KEEPALIVE, sizeof(data),
1175 		data, region);
1176 }
1177 
edns_opt_list_append(struct edns_option ** list,uint16_t code,size_t len,uint8_t * data,struct regional * region)1178 int edns_opt_list_append(struct edns_option** list, uint16_t code, size_t len,
1179 	uint8_t* data, struct regional* region)
1180 {
1181 	struct edns_option** prevp;
1182 	struct edns_option* opt;
1183 
1184 	/* allocate new element */
1185 	opt = (struct edns_option*)regional_alloc(region, sizeof(*opt));
1186 	if(!opt)
1187 		return 0;
1188 	opt->next = NULL;
1189 	opt->opt_code = code;
1190 	opt->opt_len = len;
1191 	opt->opt_data = NULL;
1192 	if(len > 0) {
1193 		opt->opt_data = regional_alloc_init(region, data, len);
1194 		if(!opt->opt_data)
1195 			return 0;
1196 	}
1197 
1198 	/* append at end of list */
1199 	prevp = list;
1200 	while(*prevp != NULL) {
1201 		prevp = &((*prevp)->next);
1202 	}
1203 	*prevp = opt;
1204 	return 1;
1205 }
1206 
edns_opt_list_remove(struct edns_option ** list,uint16_t code)1207 int edns_opt_list_remove(struct edns_option** list, uint16_t code)
1208 {
1209 	/* The list should already be allocated in a region. Freeing the
1210 	 * allocated space in a region is not possible. We just unlink the
1211 	 * required elements and they will be freed together with the region. */
1212 
1213 	struct edns_option* prev;
1214 	struct edns_option* curr;
1215 	if(!list || !(*list)) return 0;
1216 
1217 	/* Unlink and repoint if the element(s) are first in list */
1218 	while(list && *list && (*list)->opt_code == code) {
1219 		*list = (*list)->next;
1220 	}
1221 
1222 	if(!list || !(*list)) return 1;
1223 	/* Unlink elements and reattach the list */
1224 	prev = *list;
1225 	curr = (*list)->next;
1226 	while(curr != NULL) {
1227 		if(curr->opt_code == code) {
1228 			prev->next = curr->next;
1229 			curr = curr->next;
1230 		} else {
1231 			prev = curr;
1232 			curr = curr->next;
1233 		}
1234 	}
1235 	return 1;
1236 }
1237 
inplace_cb_reply_call_generic(struct inplace_cb * callback_list,enum inplace_cb_list_type type,struct query_info * qinfo,struct module_qstate * qstate,struct reply_info * rep,int rcode,struct edns_data * edns,struct comm_reply * repinfo,struct regional * region,struct timeval * start_time)1238 static int inplace_cb_reply_call_generic(
1239     struct inplace_cb* callback_list, enum inplace_cb_list_type type,
1240 	struct query_info* qinfo, struct module_qstate* qstate,
1241 	struct reply_info* rep, int rcode, struct edns_data* edns,
1242 	struct comm_reply* repinfo, struct regional* region,
1243 	struct timeval* start_time)
1244 {
1245 	struct inplace_cb* cb;
1246 	struct edns_option* opt_list_out = NULL;
1247 #if defined(EXPORT_ALL_SYMBOLS)
1248 	(void)type; /* param not used when fptr_ok disabled */
1249 #endif
1250 	if(qstate)
1251 		opt_list_out = qstate->edns_opts_front_out;
1252 	for(cb=callback_list; cb; cb=cb->next) {
1253 		fptr_ok(fptr_whitelist_inplace_cb_reply_generic(
1254 			(inplace_cb_reply_func_type*)cb->cb, type));
1255 		(void)(*(inplace_cb_reply_func_type*)cb->cb)(qinfo, qstate, rep,
1256 			rcode, edns, &opt_list_out, repinfo, region, start_time, cb->id, cb->cb_arg);
1257 	}
1258 	edns->opt_list_inplace_cb_out = opt_list_out;
1259 	return 1;
1260 }
1261 
inplace_cb_reply_call(struct module_env * env,struct query_info * qinfo,struct module_qstate * qstate,struct reply_info * rep,int rcode,struct edns_data * edns,struct comm_reply * repinfo,struct regional * region,struct timeval * start_time)1262 int inplace_cb_reply_call(struct module_env* env, struct query_info* qinfo,
1263 	struct module_qstate* qstate, struct reply_info* rep, int rcode,
1264 	struct edns_data* edns, struct comm_reply* repinfo, struct regional* region,
1265 	struct timeval* start_time)
1266 {
1267 	return inplace_cb_reply_call_generic(
1268 		env->inplace_cb_lists[inplace_cb_reply], inplace_cb_reply, qinfo,
1269 		qstate, rep, rcode, edns, repinfo, region, start_time);
1270 }
1271 
inplace_cb_reply_cache_call(struct module_env * env,struct query_info * qinfo,struct module_qstate * qstate,struct reply_info * rep,int rcode,struct edns_data * edns,struct comm_reply * repinfo,struct regional * region,struct timeval * start_time)1272 int inplace_cb_reply_cache_call(struct module_env* env,
1273 	struct query_info* qinfo, struct module_qstate* qstate,
1274 	struct reply_info* rep, int rcode, struct edns_data* edns,
1275 	struct comm_reply* repinfo, struct regional* region,
1276 	struct timeval* start_time)
1277 {
1278 	return inplace_cb_reply_call_generic(
1279 		env->inplace_cb_lists[inplace_cb_reply_cache], inplace_cb_reply_cache,
1280 		qinfo, qstate, rep, rcode, edns, repinfo, region, start_time);
1281 }
1282 
inplace_cb_reply_local_call(struct module_env * env,struct query_info * qinfo,struct module_qstate * qstate,struct reply_info * rep,int rcode,struct edns_data * edns,struct comm_reply * repinfo,struct regional * region,struct timeval * start_time)1283 int inplace_cb_reply_local_call(struct module_env* env,
1284 	struct query_info* qinfo, struct module_qstate* qstate,
1285 	struct reply_info* rep, int rcode, struct edns_data* edns,
1286 	struct comm_reply* repinfo, struct regional* region,
1287 	struct timeval* start_time)
1288 {
1289 	return inplace_cb_reply_call_generic(
1290 		env->inplace_cb_lists[inplace_cb_reply_local], inplace_cb_reply_local,
1291 		qinfo, qstate, rep, rcode, edns, repinfo, region, start_time);
1292 }
1293 
inplace_cb_reply_servfail_call(struct module_env * env,struct query_info * qinfo,struct module_qstate * qstate,struct reply_info * rep,int rcode,struct edns_data * edns,struct comm_reply * repinfo,struct regional * region,struct timeval * start_time)1294 int inplace_cb_reply_servfail_call(struct module_env* env,
1295 	struct query_info* qinfo, struct module_qstate* qstate,
1296 	struct reply_info* rep, int rcode, struct edns_data* edns,
1297 	struct comm_reply* repinfo, struct regional* region,
1298 	struct timeval* start_time)
1299 {
1300 	/* We are going to servfail. Remove any potential edns options. */
1301 	if(qstate)
1302 		qstate->edns_opts_front_out = NULL;
1303 	return inplace_cb_reply_call_generic(
1304 		env->inplace_cb_lists[inplace_cb_reply_servfail],
1305 		inplace_cb_reply_servfail, qinfo, qstate, rep, rcode, edns, repinfo,
1306 		region, start_time);
1307 }
1308 
inplace_cb_query_call(struct module_env * env,struct query_info * qinfo,uint16_t flags,struct sockaddr_storage * addr,socklen_t addrlen,uint8_t * zone,size_t zonelen,struct module_qstate * qstate,struct regional * region)1309 int inplace_cb_query_call(struct module_env* env, struct query_info* qinfo,
1310 	uint16_t flags, struct sockaddr_storage* addr, socklen_t addrlen,
1311 	uint8_t* zone, size_t zonelen, struct module_qstate* qstate,
1312 	struct regional* region)
1313 {
1314 	struct inplace_cb* cb = env->inplace_cb_lists[inplace_cb_query];
1315 	for(; cb; cb=cb->next) {
1316 		fptr_ok(fptr_whitelist_inplace_cb_query(
1317 			(inplace_cb_query_func_type*)cb->cb));
1318 		(void)(*(inplace_cb_query_func_type*)cb->cb)(qinfo, flags,
1319 			qstate, addr, addrlen, zone, zonelen, region,
1320 			cb->id, cb->cb_arg);
1321 	}
1322 	return 1;
1323 }
1324 
inplace_cb_edns_back_parsed_call(struct module_env * env,struct module_qstate * qstate)1325 int inplace_cb_edns_back_parsed_call(struct module_env* env,
1326 	struct module_qstate* qstate)
1327 {
1328 	struct inplace_cb* cb =
1329 		env->inplace_cb_lists[inplace_cb_edns_back_parsed];
1330 	for(; cb; cb=cb->next) {
1331 		fptr_ok(fptr_whitelist_inplace_cb_edns_back_parsed(
1332 			(inplace_cb_edns_back_parsed_func_type*)cb->cb));
1333 		(void)(*(inplace_cb_edns_back_parsed_func_type*)cb->cb)(qstate,
1334 			cb->id, cb->cb_arg);
1335 	}
1336 	return 1;
1337 }
1338 
inplace_cb_query_response_call(struct module_env * env,struct module_qstate * qstate,struct dns_msg * response)1339 int inplace_cb_query_response_call(struct module_env* env,
1340 	struct module_qstate* qstate, struct dns_msg* response) {
1341 	struct inplace_cb* cb =
1342 		env->inplace_cb_lists[inplace_cb_query_response];
1343 	for(; cb; cb=cb->next) {
1344 		fptr_ok(fptr_whitelist_inplace_cb_query_response(
1345 			(inplace_cb_query_response_func_type*)cb->cb));
1346 		(void)(*(inplace_cb_query_response_func_type*)cb->cb)(qstate,
1347 			response, cb->id, cb->cb_arg);
1348 	}
1349 	return 1;
1350 }
1351 
edns_opt_copy_region(struct edns_option * list,struct regional * region)1352 struct edns_option* edns_opt_copy_region(struct edns_option* list,
1353 	struct regional* region)
1354 {
1355 	struct edns_option* result = NULL, *cur = NULL, *s;
1356 	while(list) {
1357 		/* copy edns option structure */
1358 		s = regional_alloc_init(region, list, sizeof(*list));
1359 		if(!s) return NULL;
1360 		s->next = NULL;
1361 
1362 		/* copy option data */
1363 		if(s->opt_data) {
1364 			s->opt_data = regional_alloc_init(region, s->opt_data,
1365 				s->opt_len);
1366 			if(!s->opt_data)
1367 				return NULL;
1368 		}
1369 
1370 		/* link into list */
1371 		if(cur)
1372 			cur->next = s;
1373 		else	result = s;
1374 		cur = s;
1375 
1376 		/* examine next element */
1377 		list = list->next;
1378 	}
1379 	return result;
1380 }
1381 
edns_opt_copy_filter_region(struct edns_option * list,uint16_t * filter_list,size_t filter_list_len,struct regional * region)1382 struct edns_option* edns_opt_copy_filter_region(struct edns_option* list,
1383 	uint16_t* filter_list, size_t filter_list_len, struct regional* region)
1384 {
1385 	struct edns_option* result = NULL, *cur = NULL, *s;
1386 	size_t i;
1387 	while(list) {
1388 		for(i=0; i<filter_list_len; i++)
1389 			if(filter_list[i] == list->opt_code) goto found;
1390 		if(i == filter_list_len) goto next;
1391 found:
1392 		/* copy edns option structure */
1393 		s = regional_alloc_init(region, list, sizeof(*list));
1394 		if(!s) return NULL;
1395 		s->next = NULL;
1396 
1397 		/* copy option data */
1398 		if(s->opt_data) {
1399 			s->opt_data = regional_alloc_init(region, s->opt_data,
1400 				s->opt_len);
1401 			if(!s->opt_data)
1402 				return NULL;
1403 		}
1404 
1405 		/* link into list */
1406 		if(cur)
1407 			cur->next = s;
1408 		else	result = s;
1409 		cur = s;
1410 
1411 next:
1412 		/* examine next element */
1413 		list = list->next;
1414 	}
1415 	return result;
1416 }
1417 
edns_opt_compare(struct edns_option * p,struct edns_option * q)1418 int edns_opt_compare(struct edns_option* p, struct edns_option* q)
1419 {
1420 	if(!p && !q) return 0;
1421 	if(!p) return -1;
1422 	if(!q) return 1;
1423 	log_assert(p && q);
1424 	if(p->opt_code != q->opt_code)
1425 		return (int)q->opt_code - (int)p->opt_code;
1426 	if(p->opt_len != q->opt_len)
1427 		return (int)q->opt_len - (int)p->opt_len;
1428 	if(p->opt_len != 0)
1429 		return memcmp(p->opt_data, q->opt_data, p->opt_len);
1430 	return 0;
1431 }
1432 
edns_opt_list_compare(struct edns_option * p,struct edns_option * q)1433 int edns_opt_list_compare(struct edns_option* p, struct edns_option* q)
1434 {
1435 	int r;
1436 	while(p && q) {
1437 		r = edns_opt_compare(p, q);
1438 		if(r != 0)
1439 			return r;
1440 		p = p->next;
1441 		q = q->next;
1442 	}
1443 	if(p || q) {
1444 		/* uneven length lists */
1445 		if(p) return 1;
1446 		if(q) return -1;
1447 	}
1448 	return 0;
1449 }
1450 
edns_opt_list_free(struct edns_option * list)1451 void edns_opt_list_free(struct edns_option* list)
1452 {
1453 	struct edns_option* n;
1454 	while(list) {
1455 		free(list->opt_data);
1456 		n = list->next;
1457 		free(list);
1458 		list = n;
1459 	}
1460 }
1461 
edns_opt_copy_alloc(struct edns_option * list)1462 struct edns_option* edns_opt_copy_alloc(struct edns_option* list)
1463 {
1464 	struct edns_option* result = NULL, *cur = NULL, *s;
1465 	while(list) {
1466 		/* copy edns option structure */
1467 		s = memdup(list, sizeof(*list));
1468 		if(!s) {
1469 			edns_opt_list_free(result);
1470 			return NULL;
1471 		}
1472 		s->next = NULL;
1473 
1474 		/* copy option data */
1475 		if(s->opt_data) {
1476 			s->opt_data = memdup(s->opt_data, s->opt_len);
1477 			if(!s->opt_data) {
1478 				free(s);
1479 				edns_opt_list_free(result);
1480 				return NULL;
1481 			}
1482 		}
1483 
1484 		/* link into list */
1485 		if(cur)
1486 			cur->next = s;
1487 		else	result = s;
1488 		cur = s;
1489 
1490 		/* examine next element */
1491 		list = list->next;
1492 	}
1493 	return result;
1494 }
1495 
edns_opt_list_find(struct edns_option * list,uint16_t code)1496 struct edns_option* edns_opt_list_find(struct edns_option* list, uint16_t code)
1497 {
1498 	struct edns_option* p;
1499 	for(p=list; p; p=p->next) {
1500 		if(p->opt_code == code)
1501 			return p;
1502 	}
1503 	return NULL;
1504 }
1505 
local_alias_shallow_copy_qname(struct local_rrset * local_alias,uint8_t ** qname,size_t * qname_len)1506 int local_alias_shallow_copy_qname(struct local_rrset* local_alias, uint8_t** qname,
1507 	size_t* qname_len)
1508 {
1509 	struct ub_packed_rrset_key* rrset;
1510 	struct packed_rrset_data* d;
1511 	rrset = local_alias->rrset;
1512 	if(!rrset) return 0;
1513 	d = rrset->entry.data;
1514 	if(!d) return 0;
1515 
1516 	/* Sanity check: our current implementation only supports
1517 	    * a single CNAME RRset as a local alias. */
1518 	if(local_alias->next ||
1519 		rrset->rk.type != htons(LDNS_RR_TYPE_CNAME) ||
1520 		d->count != 1) {
1521 		log_err("assumption failure: unexpected local alias");
1522 		return 0;
1523 	}
1524 	*qname = d->rr_data[0] + 2;
1525 	*qname_len = d->rr_len[0] - 2;
1526 	return 1;
1527 }
1528