xref: /freebsd/contrib/unbound/util/data/msgparse.c (revision d15f2551b25f79ddcbe289faa95e655100b952da)
1 /*
2  * util/data/msgparse.c - parse wireformat DNS messages.
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  * \file
37  * Routines for message parsing a packet buffer to a descriptive structure.
38  */
39 #include "config.h"
40 #include "util/config_file.h"
41 #include "util/data/msgparse.h"
42 #include "util/data/msgreply.h"
43 #include "util/data/dname.h"
44 #include "util/data/packed_rrset.h"
45 #include "util/netevent.h"
46 #include "util/storage/lookup3.h"
47 #include "util/regional.h"
48 #include "util/rfc_1982.h"
49 #include "util/edns.h"
50 #include "util/net_help.h"
51 #include "sldns/rrdef.h"
52 #include "sldns/sbuffer.h"
53 #include "sldns/parseutil.h"
54 #include "sldns/wire2str.h"
55 
56 #define MAX_PARSED_EDNS_OPTIONS 100
57 
58 /** smart comparison of (compressed, valid) dnames from packet */
59 static int
60 smart_compare(sldns_buffer* pkt, uint8_t* dnow,
61 	uint8_t* dprfirst, uint8_t* dprlast)
62 {
63 	if(LABEL_IS_PTR(*dnow)) {
64 		/* ptr points to a previous dname */
65 		uint8_t* p;
66 		if((size_t)PTR_OFFSET(dnow[0], dnow[1])
67 			>= sldns_buffer_limit(pkt))
68 			return -1;
69 		p = sldns_buffer_at(pkt, PTR_OFFSET(dnow[0], dnow[1]));
70 		if( p == dprfirst || p == dprlast )
71 			return 0;
72 		/* prev dname is also a ptr, both ptrs are the same. */
73 		if(LABEL_IS_PTR(*dprlast) &&
74 			dprlast[0] == dnow[0] && dprlast[1] == dnow[1])
75 			return 0;
76 	}
77 	return dname_pkt_compare(pkt, dnow, dprlast);
78 }
79 
80 /**
81  * Allocate new rrset in region, fill with data.
82  */
83 static struct rrset_parse*
84 new_rrset(struct msg_parse* msg, uint8_t* dname, size_t dnamelen,
85 	uint16_t type, uint16_t dclass, hashvalue_type hash,
86 	uint32_t rrset_flags, sldns_pkt_section section,
87 	struct regional* region)
88 {
89 	struct rrset_parse* p = regional_alloc(region, sizeof(*p));
90 	if(!p) return NULL;
91 	p->rrset_bucket_next = msg->hashtable[hash & (PARSE_TABLE_SIZE-1)];
92 	msg->hashtable[hash & (PARSE_TABLE_SIZE-1)] = p;
93 	p->rrset_all_next = 0;
94 	if(msg->rrset_last)
95 		msg->rrset_last->rrset_all_next = p;
96 	else 	msg->rrset_first = p;
97 	msg->rrset_last = p;
98 	p->hash = hash;
99 	p->section = section;
100 	p->dname = dname;
101 	p->dname_len = dnamelen;
102 	p->type = type;
103 	p->rrset_class = dclass;
104 	p->flags = rrset_flags;
105 	p->rr_count = 0;
106 	p->size = 0;
107 	p->rr_first = 0;
108 	p->rr_last = 0;
109 	p->rrsig_count = 0;
110 	p->rrsig_first = 0;
111 	p->rrsig_last = 0;
112 	return p;
113 }
114 
115 /** See if next rrset is nsec at zone apex */
116 static int
117 nsec_at_apex(sldns_buffer* pkt)
118 {
119 	/* we are at ttl position in packet. */
120 	size_t pos = sldns_buffer_position(pkt);
121 	uint16_t rdatalen;
122 	if(sldns_buffer_remaining(pkt) < 7) /* ttl+len+root */
123 		return 0; /* eek! */
124 	sldns_buffer_skip(pkt, 4); /* ttl */;
125 	rdatalen = sldns_buffer_read_u16(pkt);
126 	if(sldns_buffer_remaining(pkt) < rdatalen) {
127 		sldns_buffer_set_position(pkt, pos);
128 		return 0; /* parse error happens later */
129 	}
130 	/* must validate the nsec next domain name format */
131 	if(pkt_dname_len(pkt) == 0) {
132 		sldns_buffer_set_position(pkt, pos);
133 		return 0; /* parse error */
134 	}
135 
136 	/* see if SOA bit is set. */
137 	if(sldns_buffer_position(pkt) < pos+4+rdatalen) {
138 		/* nsec type bitmap contains items */
139 		uint8_t win, blen, bits;
140 		/* need: windownum, bitmap len, firstbyte */
141 		if(sldns_buffer_position(pkt)+3 > pos+4+rdatalen) {
142 			sldns_buffer_set_position(pkt, pos);
143 			return 0; /* malformed nsec */
144 		}
145 		win = sldns_buffer_read_u8(pkt);
146 		blen = sldns_buffer_read_u8(pkt);
147 		bits = sldns_buffer_read_u8(pkt);
148 		/* 0window always first window. bitlen >=1 or parse
149 		   error really. bit 0x2 is SOA. */
150 		if(win == 0 && blen >= 1 && (bits & 0x02)) {
151 			sldns_buffer_set_position(pkt, pos);
152 			return 1;
153 		}
154 	}
155 
156 	sldns_buffer_set_position(pkt, pos);
157 	return 0;
158 }
159 
160 /** Calculate rrset flags */
161 static uint32_t
162 pkt_rrset_flags(sldns_buffer* pkt, uint16_t type, sldns_pkt_section sec)
163 {
164 	uint32_t f = 0;
165 	if(type == LDNS_RR_TYPE_NSEC && nsec_at_apex(pkt)) {
166 		f |= PACKED_RRSET_NSEC_AT_APEX;
167 	} else if(type == LDNS_RR_TYPE_SOA && sec == LDNS_SECTION_AUTHORITY) {
168 		f |= PACKED_RRSET_SOA_NEG;
169 	}
170 	return f;
171 }
172 
173 hashvalue_type
174 pkt_hash_rrset(sldns_buffer* pkt, uint8_t* dname, uint16_t type,
175 	uint16_t dclass, uint32_t rrset_flags)
176 {
177 	/* note this MUST be identical to rrset_key_hash in packed_rrset.c */
178 	/* this routine handles compressed names */
179 	hashvalue_type h = 0xab;
180 	h = dname_pkt_hash(pkt, dname, h);
181 	h = hashlittle(&type, sizeof(type), h);		/* host order */
182 	h = hashlittle(&dclass, sizeof(dclass), h);	/* netw order */
183 	h = hashlittle(&rrset_flags, sizeof(uint32_t), h);
184 	return h;
185 }
186 
187 /** create partial dname hash for rrset hash */
188 static hashvalue_type
189 pkt_hash_rrset_first(sldns_buffer* pkt, uint8_t* dname)
190 {
191 	/* works together with pkt_hash_rrset_rest */
192 	/* note this MUST be identical to rrset_key_hash in packed_rrset.c */
193 	/* this routine handles compressed names */
194 	hashvalue_type h = 0xab;
195 	h = dname_pkt_hash(pkt, dname, h);
196 	return h;
197 }
198 
199 /** create a rrset hash from a partial dname hash */
200 static hashvalue_type
201 pkt_hash_rrset_rest(hashvalue_type dname_h, uint16_t type, uint16_t dclass,
202 	uint32_t rrset_flags)
203 {
204 	/* works together with pkt_hash_rrset_first */
205 	/* note this MUST be identical to rrset_key_hash in packed_rrset.c */
206 	hashvalue_type h;
207 	h = hashlittle(&type, sizeof(type), dname_h);	/* host order */
208 	h = hashlittle(&dclass, sizeof(dclass), h);	/* netw order */
209 	h = hashlittle(&rrset_flags, sizeof(uint32_t), h);
210 	return h;
211 }
212 
213 /** compare rrset_parse with data */
214 static int
215 rrset_parse_equals(struct rrset_parse* p, sldns_buffer* pkt, hashvalue_type h,
216 	uint32_t rrset_flags, uint8_t* dname, size_t dnamelen,
217 	uint16_t type, uint16_t dclass)
218 {
219 	if(p->hash == h && p->dname_len == dnamelen && p->type == type &&
220 		p->rrset_class == dclass && p->flags == rrset_flags &&
221 		dname_pkt_compare(pkt, dname, p->dname) == 0)
222 		return 1;
223 	return 0;
224 }
225 
226 
227 struct rrset_parse*
228 msgparse_hashtable_lookup(struct msg_parse* msg, sldns_buffer* pkt,
229 	hashvalue_type h, uint32_t rrset_flags, uint8_t* dname,
230 	size_t dnamelen, uint16_t type, uint16_t dclass)
231 {
232 	struct rrset_parse* p = msg->hashtable[h & (PARSE_TABLE_SIZE-1)];
233 	while(p) {
234 		if(rrset_parse_equals(p, pkt, h, rrset_flags, dname, dnamelen,
235 			type, dclass))
236 			return p;
237 		p = p->rrset_bucket_next;
238 	}
239 	return NULL;
240 }
241 
242 /** return type networkformat that rrsig in packet covers */
243 static int
244 pkt_rrsig_covered(sldns_buffer* pkt, uint8_t* here, uint16_t* type)
245 {
246 	size_t pos = sldns_buffer_position(pkt);
247 	sldns_buffer_set_position(pkt, (size_t)(here-sldns_buffer_begin(pkt)));
248 	/* ttl + len + size of small rrsig(rootlabel, no signature) */
249 	if(sldns_buffer_remaining(pkt) < 4+2+19)
250 		return 0;
251 	sldns_buffer_skip(pkt, 4); /* ttl */
252 	if(sldns_buffer_read_u16(pkt) < 19) /* too short */ {
253 		sldns_buffer_set_position(pkt, pos);
254 		return 0;
255 	}
256 	*type = sldns_buffer_read_u16(pkt);
257 	sldns_buffer_set_position(pkt, pos);
258 	return 1;
259 }
260 
261 /** true if covered type equals prevtype */
262 static int
263 pkt_rrsig_covered_equals(sldns_buffer* pkt, uint8_t* here, uint16_t type)
264 {
265 	uint16_t t;
266 	if(pkt_rrsig_covered(pkt, here, &t) && t == type)
267 		return 1;
268 	return 0;
269 }
270 
271 void
272 msgparse_bucket_remove(struct msg_parse* msg, struct rrset_parse* rrset)
273 {
274 	struct rrset_parse** p;
275 	p = &msg->hashtable[ rrset->hash & (PARSE_TABLE_SIZE-1) ];
276 	while(*p) {
277 		if(*p == rrset) {
278 			*p = rrset->rrset_bucket_next;
279 			return;
280 		}
281 		p = &( (*p)->rrset_bucket_next );
282 	}
283 }
284 
285 /** change section of rrset from previous to current section */
286 static void
287 change_section(struct msg_parse* msg, struct rrset_parse* rrset,
288 	sldns_pkt_section section)
289 {
290 	struct rrset_parse *p, *prev;
291 	/* remove from list */
292 	if(section == rrset->section)
293 		return;
294 	p = msg->rrset_first;
295 	prev = 0;
296 	while(p) {
297 		if(p == rrset) {
298 			if(prev) prev->rrset_all_next = p->rrset_all_next;
299 			else	msg->rrset_first = p->rrset_all_next;
300 			if(msg->rrset_last == rrset)
301 				msg->rrset_last = prev;
302 			break;
303 		}
304 		prev = p;
305 		p = p->rrset_all_next;
306 	}
307 	/* remove from count */
308 	switch(rrset->section) {
309 		case LDNS_SECTION_ANSWER: msg->an_rrsets--; break;
310 		case LDNS_SECTION_AUTHORITY: msg->ns_rrsets--; break;
311 		case LDNS_SECTION_ADDITIONAL: msg->ar_rrsets--; break;
312 		default: log_assert(0);
313 	}
314 	/* insert at end of list */
315 	rrset->rrset_all_next = 0;
316 	if(msg->rrset_last)
317 		msg->rrset_last->rrset_all_next = rrset;
318 	else	msg->rrset_first = rrset;
319 	msg->rrset_last = rrset;
320 	/* up count of new section */
321 	switch(section) {
322 		case LDNS_SECTION_AUTHORITY: msg->ns_rrsets++; break;
323 		case LDNS_SECTION_ADDITIONAL: msg->ar_rrsets++; break;
324 		default: log_assert(0);
325 	}
326 	rrset->section = section;
327 }
328 
329 /** see if rrset of type RRSIG contains sig over given type */
330 static int
331 rrset_has_sigover(sldns_buffer* pkt, struct rrset_parse* rrset, uint16_t type,
332 	int* hasother)
333 {
334 	int res = 0;
335 	struct rr_parse* rr = rrset->rr_first;
336 	log_assert( rrset->type == LDNS_RR_TYPE_RRSIG );
337 	while(rr) {
338 		if(pkt_rrsig_covered_equals(pkt, rr->ttl_data, type))
339 			res = 1;
340 		else	*hasother = 1;
341 		rr = rr->next;
342 	}
343 	return res;
344 }
345 
346 /** move rrsigs from sigset to dataset */
347 static int
348 moveover_rrsigs(sldns_buffer* pkt, struct regional* region,
349 	struct rrset_parse* sigset, struct rrset_parse* dataset, int duplicate)
350 {
351 	struct rr_parse* sig = sigset->rr_first;
352 	struct rr_parse* prev = NULL;
353 	struct rr_parse* insert;
354 	struct rr_parse* nextsig;
355 	while(sig) {
356 		nextsig = sig->next;
357 		if(pkt_rrsig_covered_equals(pkt, sig->ttl_data,
358 			dataset->type)) {
359 			if(duplicate) {
360 				/* new */
361 				insert = (struct rr_parse*)regional_alloc(
362 					region, sizeof(struct rr_parse));
363 				if(!insert) return 0;
364 				insert->outside_packet = 0;
365 				insert->ttl_data = sig->ttl_data;
366 				insert->size = sig->size;
367 				/* prev not used */
368 			} else {
369 				/* remove from sigset */
370 				if(prev) prev->next = sig->next;
371 				else	sigset->rr_first = sig->next;
372 				if(sigset->rr_last == sig)
373 					sigset->rr_last = prev;
374 				sigset->rr_count--;
375 				sigset->size -= sig->size;
376 				insert = sig;
377 				/* prev not changed */
378 			}
379 			/* add to dataset */
380 			dataset->rrsig_count++;
381 			insert->next = 0;
382 			if(dataset->rrsig_last)
383 				dataset->rrsig_last->next = insert;
384 			else	dataset->rrsig_first = insert;
385 			dataset->rrsig_last = insert;
386 			dataset->size += insert->size;
387 		} else  {
388 			prev = sig;
389 		}
390 		sig = nextsig;
391 	}
392 	return 1;
393 }
394 
395 /** change an rrsig rrset for use as data rrset */
396 static struct rrset_parse*
397 change_rrsig_rrset(struct rrset_parse* sigset, struct msg_parse* msg,
398 	sldns_buffer* pkt, uint16_t datatype, uint32_t rrset_flags,
399 	int hasother, sldns_pkt_section section, struct regional* region)
400 {
401 	struct rrset_parse* dataset = sigset;
402 	hashvalue_type hash = pkt_hash_rrset(pkt, sigset->dname, datatype,
403 		sigset->rrset_class, rrset_flags);
404 	log_assert( sigset->type == LDNS_RR_TYPE_RRSIG );
405 	log_assert( datatype != LDNS_RR_TYPE_RRSIG );
406 	if(hasother) {
407 		/* need to make new rrset to hold data type */
408 		dataset = new_rrset(msg, sigset->dname, sigset->dname_len,
409 			datatype, sigset->rrset_class, hash, rrset_flags,
410 			section, region);
411 		if(!dataset)
412 			return NULL;
413 		switch(section) {
414 			case LDNS_SECTION_ANSWER: msg->an_rrsets++; break;
415 			case LDNS_SECTION_AUTHORITY: msg->ns_rrsets++; break;
416 			case LDNS_SECTION_ADDITIONAL: msg->ar_rrsets++; break;
417 			default: log_assert(0);
418 		}
419 		if(!moveover_rrsigs(pkt, region, sigset, dataset,
420 			msg->qtype == LDNS_RR_TYPE_RRSIG ||
421 			(msg->qtype == LDNS_RR_TYPE_ANY &&
422 			section != LDNS_SECTION_ANSWER) ))
423 			return NULL;
424 		return dataset;
425 	}
426 	/* changeover the type of the rrset to data set */
427 	msgparse_bucket_remove(msg, dataset);
428 	/* insert into new hash bucket */
429 	dataset->rrset_bucket_next = msg->hashtable[hash&(PARSE_TABLE_SIZE-1)];
430 	msg->hashtable[hash&(PARSE_TABLE_SIZE-1)] = dataset;
431 	dataset->hash = hash;
432 	/* use section of data item for result */
433 	change_section(msg, dataset, section);
434 	dataset->type = datatype;
435 	dataset->flags = rrset_flags;
436 	dataset->rrsig_count += dataset->rr_count;
437 	dataset->rr_count = 0;
438 	/* move sigs to end of siglist */
439 	if(dataset->rrsig_last)
440 		dataset->rrsig_last->next = dataset->rr_first;
441 	else	dataset->rrsig_first = dataset->rr_first;
442 	dataset->rrsig_last = dataset->rr_last;
443 	dataset->rr_first = 0;
444 	dataset->rr_last = 0;
445 	return dataset;
446 }
447 
448 /** Find rrset. If equal to previous it is fast. hash if not so.
449  * @param msg: the message with hash table.
450  * @param pkt: the packet in wireformat (needed for compression ptrs).
451  * @param dname: pointer to start of dname (compressed) in packet.
452  * @param dnamelen: uncompressed wirefmt length of dname.
453  * @param type: type of current rr.
454  * @param dclass: class of current rr.
455  * @param hash: hash value is returned if the rrset could not be found.
456  * @param rrset_flags: is returned if the rrset could not be found.
457  * @param prev_dname_first: dname of last seen RR. First seen dname.
458  * @param prev_dname_last: dname of last seen RR. Last seen dname.
459  * @param prev_dnamelen: dname len of last seen RR.
460  * @param prev_type: type of last seen RR.
461  * @param prev_dclass: class of last seen RR.
462  * @param rrset_prev: last seen RRset.
463  * @param section: the current section in the packet.
464  * @param region: used to allocate temporary parsing data.
465  * @return 0 on out of memory.
466  */
467 static int
468 find_rrset(struct msg_parse* msg, sldns_buffer* pkt, uint8_t* dname,
469 	size_t dnamelen, uint16_t type, uint16_t dclass, hashvalue_type* hash,
470 	uint32_t* rrset_flags,
471 	uint8_t** prev_dname_first, uint8_t** prev_dname_last,
472 	size_t* prev_dnamelen, uint16_t* prev_type,
473 	uint16_t* prev_dclass, struct rrset_parse** rrset_prev,
474 	sldns_pkt_section section, struct regional* region)
475 {
476 	hashvalue_type dname_h = pkt_hash_rrset_first(pkt, dname);
477 	uint16_t covtype;
478 	if(*rrset_prev) {
479 		/* check if equal to previous item */
480 		if(type == *prev_type && dclass == *prev_dclass &&
481 			dnamelen == *prev_dnamelen &&
482 			smart_compare(pkt, dname, *prev_dname_first,
483 				*prev_dname_last) == 0 &&
484 			type != LDNS_RR_TYPE_RRSIG) {
485 			/* same as previous */
486 			*prev_dname_last = dname;
487 			return 1;
488 		}
489 		/* check if rrsig over previous item */
490 		if(type == LDNS_RR_TYPE_RRSIG && dclass == *prev_dclass &&
491 			pkt_rrsig_covered_equals(pkt, sldns_buffer_current(pkt),
492 				*prev_type) &&
493 			smart_compare(pkt, dname, *prev_dname_first,
494 				*prev_dname_last) == 0) {
495 			/* covers previous */
496 			*prev_dname_last = dname;
497 			return 1;
498 		}
499 	}
500 	/* find by hashing and lookup in hashtable */
501 	*rrset_flags = pkt_rrset_flags(pkt, type, section);
502 
503 	/* if rrsig - try to lookup matching data set first */
504 	if(type == LDNS_RR_TYPE_RRSIG && pkt_rrsig_covered(pkt,
505 		sldns_buffer_current(pkt), &covtype)) {
506 		*hash = pkt_hash_rrset_rest(dname_h, covtype, dclass,
507 			*rrset_flags);
508 		*rrset_prev = msgparse_hashtable_lookup(msg, pkt, *hash,
509 			*rrset_flags, dname, dnamelen, covtype, dclass);
510 		if(!*rrset_prev && covtype == LDNS_RR_TYPE_NSEC) {
511 			/* if NSEC try with NSEC apex bit twiddled */
512 			*rrset_flags ^= PACKED_RRSET_NSEC_AT_APEX;
513 			*hash = pkt_hash_rrset_rest(dname_h, covtype, dclass,
514 				*rrset_flags);
515 			*rrset_prev = msgparse_hashtable_lookup(msg, pkt,
516 				*hash, *rrset_flags, dname, dnamelen, covtype,
517 				dclass);
518 			if(!*rrset_prev) /* untwiddle if not found */
519 				*rrset_flags ^= PACKED_RRSET_NSEC_AT_APEX;
520 		}
521 		if(!*rrset_prev && covtype == LDNS_RR_TYPE_SOA) {
522 			/* if SOA try with SOA neg flag twiddled */
523 			*rrset_flags ^= PACKED_RRSET_SOA_NEG;
524 			*hash = pkt_hash_rrset_rest(dname_h, covtype, dclass,
525 				*rrset_flags);
526 			*rrset_prev = msgparse_hashtable_lookup(msg, pkt,
527 				*hash, *rrset_flags, dname, dnamelen, covtype,
528 				dclass);
529 			if(!*rrset_prev) /* untwiddle if not found */
530 				*rrset_flags ^= PACKED_RRSET_SOA_NEG;
531 		}
532 		if(*rrset_prev) {
533 			*prev_dname_first = (*rrset_prev)->dname;
534 			*prev_dname_last = dname;
535 			*prev_dnamelen = dnamelen;
536 			*prev_type = covtype;
537 			*prev_dclass = dclass;
538 			return 1;
539 		}
540 	}
541 	if(type != LDNS_RR_TYPE_RRSIG) {
542 		int hasother = 0;
543 		/* find matching rrsig */
544 		*hash = pkt_hash_rrset_rest(dname_h, LDNS_RR_TYPE_RRSIG,
545 			dclass, 0);
546 		*rrset_prev = msgparse_hashtable_lookup(msg, pkt, *hash,
547 			0, dname, dnamelen, LDNS_RR_TYPE_RRSIG,
548 			dclass);
549 		if(*rrset_prev && rrset_has_sigover(pkt, *rrset_prev, type,
550 			&hasother)) {
551 			/* yes! */
552 			*prev_dname_first = (*rrset_prev)->dname;
553 			*prev_dname_last = dname;
554 			*prev_dnamelen = dnamelen;
555 			*prev_type = type;
556 			*prev_dclass = dclass;
557 			*rrset_prev = change_rrsig_rrset(*rrset_prev, msg,
558 				pkt, type, *rrset_flags, hasother, section,
559 				region);
560 			if(!*rrset_prev) return 0;
561 			return 1;
562 		}
563 	}
564 
565 	*hash = pkt_hash_rrset_rest(dname_h, type, dclass, *rrset_flags);
566 	*rrset_prev = msgparse_hashtable_lookup(msg, pkt, *hash, *rrset_flags,
567 		dname, dnamelen, type, dclass);
568 	if(*rrset_prev)
569 		*prev_dname_first = (*rrset_prev)->dname;
570 	else 	*prev_dname_first = dname;
571 	*prev_dname_last = dname;
572 	*prev_dnamelen = dnamelen;
573 	*prev_type = type;
574 	*prev_dclass = dclass;
575 	return 1;
576 }
577 
578 /**
579  * Parse query section.
580  * @param pkt: packet, position at call must be at start of query section.
581  *	at end position is after query section.
582  * @param msg: store results here.
583  * @return: 0 if OK, or rcode on error.
584  */
585 static int
586 parse_query_section(sldns_buffer* pkt, struct msg_parse* msg)
587 {
588 	if(msg->qdcount == 0)
589 		return 0;
590 	if(msg->qdcount > 1)
591 		return LDNS_RCODE_FORMERR;
592 	log_assert(msg->qdcount == 1);
593 	if(sldns_buffer_remaining(pkt) <= 0)
594 		return LDNS_RCODE_FORMERR;
595 	msg->qname = sldns_buffer_current(pkt);
596 	if((msg->qname_len = pkt_dname_len(pkt)) == 0)
597 		return LDNS_RCODE_FORMERR;
598 	if(sldns_buffer_remaining(pkt) < sizeof(uint16_t)*2)
599 		return LDNS_RCODE_FORMERR;
600 	msg->qtype = sldns_buffer_read_u16(pkt);
601 	msg->qclass = sldns_buffer_read_u16(pkt);
602 	return 0;
603 }
604 
605 size_t
606 get_rdf_size(sldns_rdf_type rdf)
607 {
608 	switch(rdf) {
609 		case LDNS_RDF_TYPE_CLASS:
610 		case LDNS_RDF_TYPE_ALG:
611 		case LDNS_RDF_TYPE_INT8:
612 			return 1;
613 			break;
614 		case LDNS_RDF_TYPE_INT16:
615 		case LDNS_RDF_TYPE_TYPE:
616 		case LDNS_RDF_TYPE_CERT_ALG:
617 			return 2;
618 			break;
619 		case LDNS_RDF_TYPE_INT32:
620 		case LDNS_RDF_TYPE_TIME:
621 		case LDNS_RDF_TYPE_A:
622 		case LDNS_RDF_TYPE_PERIOD:
623 			return 4;
624 			break;
625 		case LDNS_RDF_TYPE_TSIGTIME:
626 			return 6;
627 			break;
628 		case LDNS_RDF_TYPE_AAAA:
629 			return 16;
630 			break;
631 		default:
632 			log_assert(0); /* add type above */
633 			/* only types that appear before a domain  *
634 			 * name are needed. rest is simply copied. */
635 	}
636 	return 0;
637 }
638 
639 /** calculate the size of one rr */
640 static int
641 calc_size(sldns_buffer* pkt, uint16_t type, struct rr_parse* rr)
642 {
643 	const sldns_rr_descriptor* desc;
644 	uint16_t pkt_len; /* length of rr inside the packet */
645 	rr->size = sizeof(uint16_t); /* the rdatalen */
646 	sldns_buffer_skip(pkt, 4); /* skip ttl */
647 	pkt_len = sldns_buffer_read_u16(pkt);
648 	if(sldns_buffer_remaining(pkt) < pkt_len)
649 		return 0;
650 	desc = sldns_rr_descript(type);
651 	if(pkt_len > 0 && desc && desc->_dname_count > 0) {
652 		int count = (int)desc->_dname_count;
653 		int rdf = 0;
654 		size_t len;
655 		size_t oldpos;
656 		/* skip first part. */
657 		while(pkt_len > 0 && count) {
658 			switch(desc->_wireformat[rdf]) {
659 			case LDNS_RDF_TYPE_DNAME:
660 				/* decompress every domain name */
661 				oldpos = sldns_buffer_position(pkt);
662 				if((len = pkt_dname_len(pkt)) == 0)
663 					return 0; /* malformed dname */
664 				if(sldns_buffer_position(pkt)-oldpos > pkt_len)
665 					return 0; /* dname exceeds rdata */
666 				pkt_len -= sldns_buffer_position(pkt)-oldpos;
667 				rr->size += len;
668 				count--;
669 				len = 0;
670 				break;
671 			case LDNS_RDF_TYPE_STR:
672 				if(pkt_len < 1) {
673 					/* NOTREACHED, due to 'while(>0)' */
674 					return 0; /* len byte exceeds rdata */
675 				}
676 				len = sldns_buffer_current(pkt)[0] + 1;
677 				break;
678 			default:
679 				len = get_rdf_size(desc->_wireformat[rdf]);
680 			}
681 			if(len) {
682 				if(pkt_len < len)
683 					return 0; /* exceeds rdata */
684 				pkt_len -= len;
685 				sldns_buffer_skip(pkt, (ssize_t)len);
686 				rr->size += len;
687 			}
688 			rdf++;
689 		}
690 		/* rdata ended before all _dname_count names were seen */
691 		if(count != 0)
692 			return 0; /* the rdata is too short. */
693 	}
694 	/* remaining rdata */
695 	rr->size += pkt_len;
696 	sldns_buffer_skip(pkt, (ssize_t)pkt_len);
697 	return 1;
698 }
699 
700 /** skip rr ttl and rdata */
701 static int
702 skip_ttl_rdata(sldns_buffer* pkt)
703 {
704 	uint16_t rdatalen;
705 	if(sldns_buffer_remaining(pkt) < 6) /* ttl + rdatalen */
706 		return 0;
707 	sldns_buffer_skip(pkt, 4); /* ttl */
708 	rdatalen = sldns_buffer_read_u16(pkt);
709 	if(sldns_buffer_remaining(pkt) < rdatalen)
710 		return 0;
711 	sldns_buffer_skip(pkt, (ssize_t)rdatalen);
712 	return 1;
713 }
714 
715 /** see if RRSIG is a duplicate of another */
716 static int
717 sig_is_double(sldns_buffer* pkt, struct rrset_parse* rrset, uint8_t* ttldata)
718 {
719 	uint16_t rlen, siglen;
720 	size_t pos = sldns_buffer_position(pkt);
721 	struct rr_parse* sig;
722 	if(sldns_buffer_remaining(pkt) < 6)
723 		return 0;
724 	sldns_buffer_skip(pkt, 4); /* ttl */
725 	rlen = sldns_buffer_read_u16(pkt);
726 	if(sldns_buffer_remaining(pkt) < rlen) {
727 		sldns_buffer_set_position(pkt, pos);
728 		return 0;
729 	}
730 	sldns_buffer_set_position(pkt, pos);
731 
732 	sig = rrset->rrsig_first;
733 	while(sig) {
734 		/* check if rdatalen is same */
735 		memmove(&siglen, sig->ttl_data+4, sizeof(siglen));
736 		siglen = ntohs(siglen);
737 		/* checks if data in packet is exactly the same, this means
738 		 * also dname in rdata is the same, but rrsig is not allowed
739 		 * to have compressed dnames anyway. If it is compressed anyway
740 		 * it will lead to duplicate rrs for qtype=RRSIG. (or ANY).
741 		 *
742 		 * Cannot use sig->size because size of the other one is not
743 		 * calculated yet.
744 		 */
745 		if(siglen == rlen) {
746 			if(siglen>0 && memcmp(sig->ttl_data+6, ttldata+6,
747 				siglen) == 0) {
748 				/* same! */
749 				return 1;
750 			}
751 		}
752 		sig = sig->next;
753 	}
754 	return 0;
755 }
756 
757 /** Add rr (from packet here) to rrset, skips rr */
758 static int
759 add_rr_to_rrset(struct rrset_parse* rrset, sldns_buffer* pkt,
760 	struct msg_parse* msg, struct regional* region,
761 	sldns_pkt_section section, uint16_t type)
762 {
763 	struct rr_parse* rr;
764 	/* check section of rrset. */
765 	if(rrset->section != section && type != LDNS_RR_TYPE_RRSIG &&
766 		rrset->type != LDNS_RR_TYPE_RRSIG) {
767 		/* silently drop it - we drop the last part, since
768 		 * trust in rr data depends on the section it is in.
769 		 * the less trustworthy part is discarded.
770 		 * also the last part is more likely to be incomplete.
771 		 * RFC 2181: must put RRset only once in response. */
772 		/*
773 		verbose(VERB_QUERY, "Packet contains rrset data in "
774 			"multiple sections, dropped last part.");
775 		log_buf(VERB_QUERY, "packet was", pkt);
776 		*/
777 		/* forwards */
778 		if(!skip_ttl_rdata(pkt))
779 			return LDNS_RCODE_FORMERR;
780 		return 0;
781 	}
782 
783 	if( (msg->qtype == LDNS_RR_TYPE_RRSIG ||
784 	     msg->qtype == LDNS_RR_TYPE_ANY)
785 	    && sig_is_double(pkt, rrset, sldns_buffer_current(pkt))) {
786 		if(!skip_ttl_rdata(pkt))
787 			return LDNS_RCODE_FORMERR;
788 		return 0;
789 	}
790 
791 	/* create rr */
792 	if(!(rr = (struct rr_parse*)regional_alloc(region, sizeof(*rr))))
793 		return LDNS_RCODE_SERVFAIL;
794 	rr->outside_packet = 0;
795 	rr->ttl_data = sldns_buffer_current(pkt);
796 	rr->next = 0;
797 	if(type == LDNS_RR_TYPE_RRSIG && rrset->type != LDNS_RR_TYPE_RRSIG) {
798 		if(rrset->rrsig_last)
799 			rrset->rrsig_last->next = rr;
800 		else	rrset->rrsig_first = rr;
801 		rrset->rrsig_last = rr;
802 		rrset->rrsig_count++;
803 	} else {
804 		if(rrset->rr_last)
805 			rrset->rr_last->next = rr;
806 		else	rrset->rr_first = rr;
807 		rrset->rr_last = rr;
808 		rrset->rr_count++;
809 	}
810 
811 	/* calc decompressed size */
812 	if(!calc_size(pkt, type, rr))
813 		return LDNS_RCODE_FORMERR;
814 	rrset->size += rr->size;
815 
816 	return 0;
817 }
818 
819 /**
820  * Parse packet RR section, for answer, authority and additional sections.
821  * @param pkt: packet, position at call must be at start of section.
822  *	at end position is after section.
823  * @param msg: store results here.
824  * @param region: how to alloc results.
825  * @param section: section enum.
826  * @param num_rrs: how many rrs are in the section.
827  * @param num_rrsets: returns number of rrsets in the section.
828  * @return: 0 if OK, or rcode on error.
829  */
830 static int
831 parse_section(sldns_buffer* pkt, struct msg_parse* msg,
832 	struct regional* region, sldns_pkt_section section,
833 	uint16_t num_rrs, size_t* num_rrsets)
834 {
835 	uint16_t i;
836 	uint8_t* dname, *prev_dname_f = NULL, *prev_dname_l = NULL;
837 	size_t dnamelen, prev_dnamelen = 0;
838 	uint16_t type, prev_type = 0;
839 	uint16_t dclass, prev_dclass = 0;
840 	uint32_t rrset_flags = 0;
841 	hashvalue_type hash = 0;
842 	struct rrset_parse* rrset = NULL;
843 	int r;
844 
845 	if(num_rrs == 0)
846 		return 0;
847 	if(sldns_buffer_remaining(pkt) <= 0)
848 		return LDNS_RCODE_FORMERR;
849 	for(i=0; i<num_rrs; i++) {
850 		/* parse this RR. */
851 		dname = sldns_buffer_current(pkt);
852 		if((dnamelen = pkt_dname_len(pkt)) == 0)
853 			return LDNS_RCODE_FORMERR;
854 		if(sldns_buffer_remaining(pkt) < 10) /* type, class, ttl, len */
855 			return LDNS_RCODE_FORMERR;
856 		type = sldns_buffer_read_u16(pkt);
857 		sldns_buffer_read(pkt, &dclass, sizeof(dclass));
858 
859 		if(0) { /* debug show what is being parsed. */
860 			if(type == LDNS_RR_TYPE_RRSIG) {
861 				uint16_t t;
862 				if(pkt_rrsig_covered(pkt,
863 					sldns_buffer_current(pkt), &t))
864 					fprintf(stderr, "parse of %s(%d) [%s(%d)]",
865 					sldns_rr_descript(type)?
866 					sldns_rr_descript(type)->_name: "??",
867 					(int)type,
868 					sldns_rr_descript(t)?
869 					sldns_rr_descript(t)->_name: "??",
870 					(int)t);
871 			} else
872 			  fprintf(stderr, "parse of %s(%d)",
873 				sldns_rr_descript(type)?
874 				sldns_rr_descript(type)->_name: "??",
875 				(int)type);
876 			fprintf(stderr, " %s(%d) ",
877 				sldns_lookup_by_id(sldns_rr_classes,
878 				(int)ntohs(dclass))?sldns_lookup_by_id(
879 				sldns_rr_classes, (int)ntohs(dclass))->name:
880 				"??", (int)ntohs(dclass));
881 			dname_print(stderr, pkt, dname);
882 			fprintf(stderr, "\n");
883 		}
884 
885 		/* see if it is part of an existing RR set */
886 		if(!find_rrset(msg, pkt, dname, dnamelen, type, dclass, &hash,
887 			&rrset_flags, &prev_dname_f, &prev_dname_l,
888 			&prev_dnamelen, &prev_type, &prev_dclass, &rrset,
889 			section, region))
890 			return LDNS_RCODE_SERVFAIL;
891 		if(!rrset) {
892 			/* it is a new RR set. hash&flags already calculated.*/
893 			(*num_rrsets)++;
894 			rrset = new_rrset(msg, dname, dnamelen, type, dclass,
895 				hash, rrset_flags, section, region);
896 			if(!rrset)
897 				return LDNS_RCODE_SERVFAIL;
898 		}
899 		else if(0)	{
900 			fprintf(stderr, "is part of existing: ");
901 			dname_print(stderr, pkt, rrset->dname);
902 			fprintf(stderr, " type %s(%d)\n",
903 				sldns_rr_descript(rrset->type)?
904 				sldns_rr_descript(rrset->type)->_name: "??",
905 				(int)rrset->type);
906 		}
907 		/* add to rrset. */
908 		if((r=add_rr_to_rrset(rrset, pkt, msg, region, section,
909 			type)) != 0)
910 			return r;
911 	}
912 	return 0;
913 }
914 
915 int
916 parse_packet(sldns_buffer* pkt, struct msg_parse* msg, struct regional* region)
917 {
918 	int ret;
919 	if(sldns_buffer_remaining(pkt) < LDNS_HEADER_SIZE)
920 		return LDNS_RCODE_FORMERR;
921 	/* read the header */
922 	sldns_buffer_read(pkt, &msg->id, sizeof(uint16_t));
923 	msg->flags = sldns_buffer_read_u16(pkt);
924 	msg->qdcount = sldns_buffer_read_u16(pkt);
925 	msg->ancount = sldns_buffer_read_u16(pkt);
926 	msg->nscount = sldns_buffer_read_u16(pkt);
927 	msg->arcount = sldns_buffer_read_u16(pkt);
928 	if(msg->qdcount > 1)
929 		return LDNS_RCODE_FORMERR;
930 	if((ret = parse_query_section(pkt, msg)) != 0)
931 		return ret;
932 	if((ret = parse_section(pkt, msg, region, LDNS_SECTION_ANSWER,
933 		msg->ancount, &msg->an_rrsets)) != 0)
934 		return ret;
935 	if((ret = parse_section(pkt, msg, region, LDNS_SECTION_AUTHORITY,
936 		msg->nscount, &msg->ns_rrsets)) != 0)
937 		return ret;
938 	if(sldns_buffer_remaining(pkt) == 0 && msg->arcount == 1) {
939 		/* BIND accepts leniently that an EDNS record is missing.
940 		 * so, we do too. */
941 	} else if((ret = parse_section(pkt, msg, region,
942 		LDNS_SECTION_ADDITIONAL, msg->arcount, &msg->ar_rrsets)) != 0)
943 		return ret;
944 	/* if(sldns_buffer_remaining(pkt) > 0) { */
945 		/* there is spurious data at end of packet. ignore */
946 	/* } */
947 	msg->rrset_count = msg->an_rrsets + msg->ns_rrsets + msg->ar_rrsets;
948 	return 0;
949 }
950 
951 /** parse EDNS options from EDNS wireformat rdata */
952 static int
953 parse_edns_options_from_query(uint8_t* rdata_ptr, size_t rdata_len,
954 	struct edns_data* edns, struct config_file* cfg, struct comm_point* c,
955 	struct comm_reply* repinfo, uint32_t now, struct regional* region,
956 	struct cookie_secrets* cookie_secrets)
957 {
958 	int i = 0, nsid_seen = 0, cookie_seen = 0, padding_seen = 0;
959 	/* To respond with a Keepalive option, the client connection must have
960 	 * received one message with a TCP Keepalive EDNS option, and that
961 	 * option must have 0 length data. Subsequent messages sent on that
962 	 * connection will have a TCP Keepalive option.
963 	 *
964 	 * In the if-statement below, the option is added unsolicited. This
965 	 * means that the client has sent an KEEPALIVE option earlier. We know
966 	 * here this is true, because c->tcp_keepalive is set.
967 	 */
968 	if (cfg && cfg->do_tcp_keepalive && c && c->type != comm_udp && c->tcp_keepalive) {
969 		if(!edns_opt_list_append_keepalive(&edns->opt_list_out,
970 					c->tcp_timeout_msec / 100, region)) {
971 			log_err("out of memory");
972 			return LDNS_RCODE_SERVFAIL;
973 		}
974 	}
975 
976 	/* while still more options, and have code+len to read */
977 	/* ignores partial content (i.e. rdata len 3) */
978 	while(rdata_len >= 4 && i < MAX_PARSED_EDNS_OPTIONS) {
979 		uint16_t opt_code = sldns_read_uint16(rdata_ptr);
980 		uint16_t opt_len = sldns_read_uint16(rdata_ptr+2);
981 		uint8_t server_cookie[40];
982 		enum edns_cookie_val_status cookie_val_status;
983 		int cookie_is_v4 = 1;
984 
985 		rdata_ptr += 4;
986 		rdata_len -= 4;
987 		if(opt_len > rdata_len)
988 			break; /* option code partial */
989 
990 		/* handle parse time edns options here */
991 		switch(opt_code) {
992 		case LDNS_EDNS_NSID:
993 			if (!cfg || !cfg->nsid || nsid_seen)
994 				break;
995 			nsid_seen = 1;
996 			if(!edns_opt_list_append(&edns->opt_list_out,
997 						LDNS_EDNS_NSID, cfg->nsid_len,
998 						cfg->nsid, region)) {
999 				log_err("out of memory");
1000 				return LDNS_RCODE_SERVFAIL;
1001 			}
1002 			break;
1003 
1004 		case LDNS_EDNS_KEEPALIVE:
1005 			/* To respond with a Keepalive option, the client
1006 			 * connection must have received one message with a TCP
1007 			 * Keepalive EDNS option, and that option must have 0
1008 			 * length data. Subsequent messages sent on that
1009 			 * connection will have a TCP Keepalive option.
1010 			 *
1011 			 * This should be the first time the client sends this
1012 			 * option, so c->tcp_keepalive is not set.
1013 			 * Besides adding the reply KEEPALIVE option,
1014 			 * c->tcp_keepalive will be set so that the
1015 			 * option will be added unsolicited in subsequent
1016 			 * responses (see the comment above the if-statement
1017 			 * at the start of this function).
1018 			 */
1019 			if (!cfg || !cfg->do_tcp_keepalive || !c ||
1020 					c->type == comm_udp || c->tcp_keepalive)
1021 				break;
1022 			if(opt_len) {
1023 				verbose(VERB_ALGO, "query with bad edns keepalive.");
1024 				return LDNS_RCODE_FORMERR;
1025 			}
1026 			if(!edns_opt_list_append_keepalive(&edns->opt_list_out,
1027 						c->tcp_timeout_msec / 100,
1028 						region)) {
1029 				log_err("out of memory");
1030 				return LDNS_RCODE_SERVFAIL;
1031 			}
1032 			c->tcp_keepalive = 1;
1033 			break;
1034 
1035 		case LDNS_EDNS_PADDING:
1036 			if(!cfg || !cfg->pad_responses || !c || padding_seen)
1037 				break;
1038 			if(!((c->type == comm_tcp && c->ssl) ||
1039 				(c->type == comm_http && c->ssl) ||
1040 				c->type == comm_doq))
1041 				break;
1042 			padding_seen = 1;
1043 			if(!edns_opt_list_append(&edns->opt_list_out,
1044 						LDNS_EDNS_PADDING,
1045 						0, NULL, region)) {
1046 				log_err("out of memory");
1047 				return LDNS_RCODE_SERVFAIL;
1048 			}
1049 			edns->padding_block_size = cfg->pad_responses_block_size;
1050 			break;
1051 
1052 		case LDNS_EDNS_COOKIE:
1053 			if(!cfg || !cfg->do_answer_cookie || !repinfo || cookie_seen)
1054 				break;
1055 			cookie_seen = 1;
1056 			if(opt_len != 8 && (opt_len < 16 || opt_len > 40)) {
1057 				verbose(VERB_ALGO, "worker request: "
1058 					"badly formatted cookie");
1059 				return LDNS_RCODE_FORMERR;
1060 			}
1061 			edns->cookie_present = 1;
1062 
1063 			/* Copy client cookie, version and timestamp for
1064 			 * validation and creation purposes.
1065 			 */
1066 			if(opt_len >= 16) {
1067 				memmove(server_cookie, rdata_ptr, 16);
1068 			} else {
1069 				memset(server_cookie, 0, 16);
1070 				memmove(server_cookie, rdata_ptr, opt_len);
1071 			}
1072 
1073 			/* Copy client ip for validation and creation
1074 			 * purposes. It will be overwritten if (re)creation
1075 			 * is needed.
1076 			 */
1077 			if(repinfo->client_addr.ss_family == AF_INET) {
1078 				memcpy(server_cookie + 16,
1079 					&((struct sockaddr_in*)&repinfo->client_addr)->sin_addr, 4);
1080 			} else {
1081 				cookie_is_v4 = 0;
1082 				memcpy(server_cookie + 16,
1083 					&((struct sockaddr_in6*)&repinfo->client_addr)->sin6_addr, 16);
1084 			}
1085 
1086 			if(cfg->cookie_secret_file &&
1087 				cfg->cookie_secret_file[0]) {
1088 				/* Loop over the active and staging cookies. */
1089 				cookie_val_status =
1090 					cookie_secrets_server_validate(
1091 					rdata_ptr, opt_len, cookie_secrets,
1092 					cookie_is_v4, server_cookie, now);
1093 			} else {
1094 				/* Use the cookie option value to validate. */
1095 				cookie_val_status = edns_cookie_server_validate(
1096 					rdata_ptr, opt_len, cfg->cookie_secret,
1097 					cfg->cookie_secret_len, cookie_is_v4,
1098 					server_cookie, now);
1099 			}
1100 			if(cookie_val_status == COOKIE_STATUS_VALID_RENEW)
1101 				edns->cookie_valid = 1;
1102 			switch(cookie_val_status) {
1103 			case COOKIE_STATUS_VALID:
1104 				edns->cookie_valid = 1;
1105 				/* Reuse cookie */
1106 				if(!edns_opt_list_append(
1107 					&edns->opt_list_out, LDNS_EDNS_COOKIE,
1108 					opt_len, rdata_ptr, region)) {
1109 					log_err("out of memory");
1110 					return LDNS_RCODE_SERVFAIL;
1111 				}
1112 				/* Cookie to be reused added to outgoing
1113 				 * options. Done!
1114 				 */
1115 				break;
1116 			case COOKIE_STATUS_CLIENT_ONLY:
1117 				edns->cookie_client = 1;
1118 				ATTR_FALLTHROUGH
1119 				/* fallthrough */
1120 			case COOKIE_STATUS_VALID_RENEW:
1121 			case COOKIE_STATUS_FUTURE:
1122 			case COOKIE_STATUS_EXPIRED:
1123 			case COOKIE_STATUS_INVALID:
1124 			default:
1125 				if(cfg->cookie_secret_file &&
1126 					cfg->cookie_secret_file[0]) {
1127 					if(!cookie_secrets)
1128 						break;
1129 					lock_basic_lock(&cookie_secrets->lock);
1130 					if(cookie_secrets->cookie_count < 1) {
1131 						lock_basic_unlock(&cookie_secrets->lock);
1132 						break;
1133 					}
1134 					edns_cookie_server_write(server_cookie,
1135 						cookie_secrets->cookie_secrets[0].cookie_secret,
1136 						cookie_is_v4, now);
1137 					lock_basic_unlock(&cookie_secrets->lock);
1138 				} else {
1139 					edns_cookie_server_write(server_cookie,
1140 						cfg->cookie_secret, cookie_is_v4, now);
1141 				}
1142 				if(!edns_opt_list_append(&edns->opt_list_out,
1143 					LDNS_EDNS_COOKIE, 24, server_cookie,
1144 					region)) {
1145 					log_err("out of memory");
1146 					return LDNS_RCODE_SERVFAIL;
1147 				}
1148 				break;
1149 			}
1150 			break;
1151 		default:
1152 			break;
1153 		}
1154 		if(!edns_opt_list_append(&edns->opt_list_in,
1155 				opt_code, opt_len, rdata_ptr, region)) {
1156 			log_err("out of memory");
1157 			return LDNS_RCODE_SERVFAIL;
1158 		}
1159 		rdata_ptr += opt_len;
1160 		rdata_len -= opt_len;
1161 		i++;
1162 	}
1163 	return LDNS_RCODE_NOERROR;
1164 }
1165 
1166 int
1167 parse_extract_edns_from_response_msg(struct msg_parse* msg,
1168 	struct edns_data* edns, struct regional* region)
1169 {
1170 	struct rrset_parse* rrset = msg->rrset_first;
1171 	struct rrset_parse* prev = 0;
1172 	struct rrset_parse* found = 0;
1173 	struct rrset_parse* found_prev = 0;
1174 	size_t rdata_len;
1175 	uint8_t* rdata_ptr;
1176 	int i = 0;
1177 	/* since the class encodes the UDP size, we cannot use hash table to
1178 	 * find the EDNS OPT record. Scan the packet. */
1179 	while(rrset) {
1180 		if(rrset->type == LDNS_RR_TYPE_OPT) {
1181 			/* only one OPT RR allowed. */
1182 			if(found) return LDNS_RCODE_FORMERR;
1183 			/* found it! */
1184 			found_prev = prev;
1185 			found = rrset;
1186 		}
1187 		prev = rrset;
1188 		rrset = rrset->rrset_all_next;
1189 	}
1190 	if(!found) {
1191 		memset(edns, 0, sizeof(*edns));
1192 		edns->udp_size = 512;
1193 		return 0;
1194 	}
1195 	/* check the found RRset */
1196 	/* most lenient check possible. ignore dname, use last opt */
1197 	if(found->section != LDNS_SECTION_ADDITIONAL)
1198 		return LDNS_RCODE_FORMERR;
1199 	if(found->rr_count == 0)
1200 		return LDNS_RCODE_FORMERR;
1201 	if(0) { /* strict checking of dname and RRcount */
1202 		if(found->dname_len != 1 || !found->dname
1203 			|| found->dname[0] != 0) return LDNS_RCODE_FORMERR;
1204 		if(found->rr_count != 1) return LDNS_RCODE_FORMERR;
1205 	}
1206 	log_assert(found->rr_first && found->rr_last);
1207 
1208 	/* remove from packet */
1209 	if(found_prev)	found_prev->rrset_all_next = found->rrset_all_next;
1210 	else	msg->rrset_first = found->rrset_all_next;
1211 	if(found == msg->rrset_last)
1212 		msg->rrset_last = found_prev;
1213 	msg->arcount --;
1214 	msg->ar_rrsets --;
1215 	msg->rrset_count --;
1216 
1217 	/* take the data ! */
1218 	edns->edns_present = 1;
1219 	edns->ext_rcode = found->rr_last->ttl_data[0];
1220 	edns->edns_version = found->rr_last->ttl_data[1];
1221 	edns->bits = sldns_read_uint16(&found->rr_last->ttl_data[2]);
1222 	edns->udp_size = ntohs(found->rrset_class);
1223 	edns->opt_list_in = NULL;
1224 	edns->opt_list_out = NULL;
1225 	edns->opt_list_inplace_cb_out = NULL;
1226 	edns->padding_block_size = 0;
1227 	edns->cookie_present = 0;
1228 	edns->cookie_valid = 0;
1229 
1230 	/* take the options */
1231 	rdata_len = found->rr_first->size-2;
1232 	rdata_ptr = found->rr_first->ttl_data+6;
1233 
1234 	/* while still more options, and have code+len to read */
1235 	/* ignores partial content (i.e. rdata len 3) */
1236 	while(rdata_len >= 4 && i < MAX_PARSED_EDNS_OPTIONS) {
1237 		uint16_t opt_code = sldns_read_uint16(rdata_ptr);
1238 		uint16_t opt_len = sldns_read_uint16(rdata_ptr+2);
1239 		rdata_ptr += 4;
1240 		rdata_len -= 4;
1241 		if(opt_len > rdata_len)
1242 			break; /* option code partial */
1243 
1244 		if(!edns_opt_list_append(&edns->opt_list_in,
1245 				opt_code, opt_len, rdata_ptr, region)) {
1246 			log_err("out of memory");
1247 			break;
1248 		}
1249 		rdata_ptr += opt_len;
1250 		rdata_len -= opt_len;
1251 		i++;
1252 	}
1253 	/* ignore rrsigs */
1254 	return LDNS_RCODE_NOERROR;
1255 }
1256 
1257 /** skip RR in packet */
1258 static int
1259 skip_pkt_rr(sldns_buffer* pkt)
1260 {
1261 	if(sldns_buffer_remaining(pkt) < 1) return 0;
1262 	if(!pkt_dname_len(pkt))
1263 		return 0;
1264 	if(sldns_buffer_remaining(pkt) < 4) return 0;
1265 	sldns_buffer_skip(pkt, 4); /* type and class */
1266 	if(!skip_ttl_rdata(pkt))
1267 		return 0;
1268 	return 1;
1269 }
1270 
1271 /** skip RRs from packet */
1272 int
1273 skip_pkt_rrs(sldns_buffer* pkt, int num)
1274 {
1275 	int i;
1276 	for(i=0; i<num; i++) {
1277 		if(!skip_pkt_rr(pkt))
1278 			return 0;
1279 	}
1280 	return 1;
1281 }
1282 
1283 int
1284 parse_edns_from_query_pkt(sldns_buffer* pkt, struct edns_data* edns,
1285 	struct config_file* cfg, struct comm_point* c,
1286 	struct comm_reply* repinfo, time_t now, struct regional* region,
1287 	struct cookie_secrets* cookie_secrets)
1288 {
1289 	size_t rdata_len;
1290 	uint8_t* rdata_ptr;
1291 	log_assert(LDNS_QDCOUNT(sldns_buffer_begin(pkt)) == 1);
1292 	memset(edns, 0, sizeof(*edns));
1293 	if(LDNS_ANCOUNT(sldns_buffer_begin(pkt)) != 0 ||
1294 		LDNS_NSCOUNT(sldns_buffer_begin(pkt)) != 0) {
1295 		if(!skip_pkt_rrs(pkt, ((int)LDNS_ANCOUNT(sldns_buffer_begin(pkt)))+
1296 			((int)LDNS_NSCOUNT(sldns_buffer_begin(pkt)))))
1297 			return LDNS_RCODE_FORMERR;
1298 	}
1299 	/* check edns section is present */
1300 	if(LDNS_ARCOUNT(sldns_buffer_begin(pkt)) > 1) {
1301 		return LDNS_RCODE_FORMERR;
1302 	}
1303 	if(LDNS_ARCOUNT(sldns_buffer_begin(pkt)) == 0) {
1304 		edns->udp_size = 512;
1305 		return 0;
1306 	}
1307 	/* domain name must be the root of length 1. */
1308 	if(pkt_dname_len(pkt) != 1)
1309 		return LDNS_RCODE_FORMERR;
1310 	if(sldns_buffer_remaining(pkt) < 10) /* type, class, ttl, rdatalen */
1311 		return LDNS_RCODE_FORMERR;
1312 	if(sldns_buffer_read_u16(pkt) != LDNS_RR_TYPE_OPT)
1313 		return LDNS_RCODE_FORMERR;
1314 	edns->edns_present = 1;
1315 	edns->udp_size = sldns_buffer_read_u16(pkt); /* class is udp size */
1316 	edns->ext_rcode = sldns_buffer_read_u8(pkt); /* ttl used for bits */
1317 	edns->edns_version = sldns_buffer_read_u8(pkt);
1318 	edns->bits = sldns_buffer_read_u16(pkt);
1319 	edns->opt_list_in = NULL;
1320 	edns->opt_list_out = NULL;
1321 	edns->opt_list_inplace_cb_out = NULL;
1322 	edns->padding_block_size = 0;
1323 	edns->cookie_present = 0;
1324 	edns->cookie_valid = 0;
1325 
1326 	/* take the options */
1327 	rdata_len = sldns_buffer_read_u16(pkt);
1328 	if(sldns_buffer_remaining(pkt) < rdata_len)
1329 		return LDNS_RCODE_FORMERR;
1330 	rdata_ptr = sldns_buffer_current(pkt);
1331 	/* ignore rrsigs */
1332 	return parse_edns_options_from_query(rdata_ptr, rdata_len, edns, cfg,
1333 		c, repinfo, now, region, cookie_secrets);
1334 }
1335 
1336 void
1337 log_edns_opt_list(enum verbosity_value level, const char* info_str,
1338 	struct edns_option* list)
1339 {
1340 	if(verbosity >= level && list) {
1341 		char str[128], *s;
1342 		size_t slen;
1343 		verbose(level, "%s", info_str);
1344 		while(list) {
1345 			s = str;
1346 			slen = sizeof(str);
1347 			(void)sldns_wire2str_edns_option_print(&s, &slen, list->opt_code,
1348 				list->opt_data, list->opt_len);
1349 			verbose(level, "  %s", str);
1350 			list = list->next;
1351 		}
1352 	}
1353 }
1354 
1355 /** remove RR from msgparse RRset, return true if rrset is entirely bad */
1356 int
1357 msgparse_rrset_remove_rr(const char* str, sldns_buffer* pkt, struct rrset_parse* rrset,
1358 	struct rr_parse* prev, struct rr_parse* rr, struct sockaddr_storage* addr, socklen_t addrlen)
1359 {
1360 	if(verbosity >= VERB_QUERY && rrset->dname_len <= LDNS_MAX_DOMAINLEN && str) {
1361 		uint8_t buf[LDNS_MAX_DOMAINLEN+1];
1362 		dname_pkt_copy(pkt, buf, rrset->dname);
1363 		if(addr)
1364 			log_name_addr(VERB_QUERY, str, buf, addr, addrlen);
1365 		else	log_nametypeclass(VERB_QUERY, str, buf,
1366 				rrset->type, ntohs(rrset->rrset_class));
1367 	}
1368 	if(prev)
1369 		prev->next = rr->next;
1370 	else	rrset->rr_first = rr->next;
1371 	if(rrset->rr_last == rr)
1372 		rrset->rr_last = prev;
1373 	rrset->rr_count --;
1374 	rrset->size -= rr->size;
1375 	/* rr struct still exists, but is unlinked, so that in the for loop
1376 	 * the rr->next works fine to continue. */
1377 	return rrset->rr_count == 0;
1378 }
1379 
1380 #ifdef UNBOUND_DEBUG
1381 time_t debug_expired_reply_ttl_calc(time_t ttl, time_t ttl_add) {
1382 	/* Check that we are serving expired when this is called */
1383 	/* ttl (absolute) should be later than ttl_add */
1384 	/* It is also called during the grace period for type DNAME,
1385 	 * and then the 'SERVE_EXPIRED' boolean may not be on. */
1386 	log_assert(ttl_add <= ttl);
1387 	return (SERVE_EXPIRED_REPLY_TTL < (ttl) - (ttl_add) ?
1388 		SERVE_EXPIRED_REPLY_TTL : (ttl) - (ttl_add));
1389 }
1390 #endif
1391