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