]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - util/data/msgreply.c
Vendor import of Unbound 1.6.2.
[FreeBSD/FreeBSD.git] / util / data / msgreply.c
1 /*
2  * util/data/msgreply.c - store message and reply data. 
3  *
4  * Copyright (c) 2007, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  * 
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  * 
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  * 
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  * 
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35
36 /**
37  * \file
38  *
39  * This file contains a data structure to store a message and its reply.
40  */
41
42 #include "config.h"
43 #include "util/data/msgreply.h"
44 #include "util/storage/lookup3.h"
45 #include "util/log.h"
46 #include "util/alloc.h"
47 #include "util/netevent.h"
48 #include "util/net_help.h"
49 #include "util/data/dname.h"
50 #include "util/regional.h"
51 #include "util/data/msgparse.h"
52 #include "util/data/msgencode.h"
53 #include "sldns/sbuffer.h"
54 #include "sldns/wire2str.h"
55 #include "util/module.h"
56 #include "util/fptr_wlist.h"
57
58 /** MAX TTL default for messages and rrsets */
59 time_t MAX_TTL = 3600 * 24 * 10; /* ten days */
60 /** MIN TTL default for messages and rrsets */
61 time_t MIN_TTL = 0;
62 /** MAX Negative TTL, for SOA records in authority section */
63 time_t MAX_NEG_TTL = 3600; /* one hour */
64
65 /** allocate qinfo, return 0 on error */
66 static int
67 parse_create_qinfo(sldns_buffer* pkt, struct msg_parse* msg, 
68         struct query_info* qinf, struct regional* region)
69 {
70         if(msg->qname) {
71                 if(region)
72                         qinf->qname = (uint8_t*)regional_alloc(region, 
73                                 msg->qname_len);
74                 else    qinf->qname = (uint8_t*)malloc(msg->qname_len);
75                 if(!qinf->qname) return 0;
76                 dname_pkt_copy(pkt, qinf->qname, msg->qname);
77         } else  qinf->qname = 0;
78         qinf->qname_len = msg->qname_len;
79         qinf->qtype = msg->qtype;
80         qinf->qclass = msg->qclass;
81         qinf->local_alias = NULL;
82         return 1;
83 }
84
85 /** constructor for replyinfo */
86 struct reply_info*
87 construct_reply_info_base(struct regional* region, uint16_t flags, size_t qd,
88         time_t ttl, time_t prettl, size_t an, size_t ns, size_t ar, 
89         size_t total, enum sec_status sec)
90 {
91         struct reply_info* rep;
92         /* rrset_count-1 because the first ref is part of the struct. */
93         size_t s = sizeof(struct reply_info) - sizeof(struct rrset_ref) +
94                 sizeof(struct ub_packed_rrset_key*) * total;
95         if(total >= RR_COUNT_MAX) return NULL; /* sanity check on numRRS*/
96         if(region)
97                 rep = (struct reply_info*)regional_alloc(region, s);
98         else    rep = (struct reply_info*)malloc(s + 
99                         sizeof(struct rrset_ref) * (total));
100         if(!rep) 
101                 return NULL;
102         rep->flags = flags;
103         rep->qdcount = qd;
104         rep->ttl = ttl;
105         rep->prefetch_ttl = prettl;
106         rep->an_numrrsets = an;
107         rep->ns_numrrsets = ns;
108         rep->ar_numrrsets = ar;
109         rep->rrset_count = total;
110         rep->security = sec;
111         rep->authoritative = 0;
112         /* array starts after the refs */
113         if(region)
114                 rep->rrsets = (struct ub_packed_rrset_key**)&(rep->ref[0]);
115         else    rep->rrsets = (struct ub_packed_rrset_key**)&(rep->ref[total]);
116         /* zero the arrays to assist cleanup in case of malloc failure */
117         memset( rep->rrsets, 0, sizeof(struct ub_packed_rrset_key*) * total);
118         if(!region)
119                 memset( &rep->ref[0], 0, sizeof(struct rrset_ref) * total);
120         return rep;
121 }
122
123 /** allocate replyinfo, return 0 on error */
124 static int
125 parse_create_repinfo(struct msg_parse* msg, struct reply_info** rep,
126         struct regional* region)
127 {
128         *rep = construct_reply_info_base(region, msg->flags, msg->qdcount, 0, 
129                 0, msg->an_rrsets, msg->ns_rrsets, msg->ar_rrsets, 
130                 msg->rrset_count, sec_status_unchecked);
131         if(!*rep)
132                 return 0;
133         return 1;
134 }
135
136 int
137 reply_info_alloc_rrset_keys(struct reply_info* rep, struct alloc_cache* alloc,
138         struct regional* region)
139 {
140         size_t i;
141         for(i=0; i<rep->rrset_count; i++) {
142                 if(region) {
143                         rep->rrsets[i] = (struct ub_packed_rrset_key*)
144                                 regional_alloc(region, 
145                                 sizeof(struct ub_packed_rrset_key));
146                         if(rep->rrsets[i]) {
147                                 memset(rep->rrsets[i], 0, 
148                                         sizeof(struct ub_packed_rrset_key));
149                                 rep->rrsets[i]->entry.key = rep->rrsets[i];
150                         }
151                 }
152                 else    rep->rrsets[i] = alloc_special_obtain(alloc);
153                 if(!rep->rrsets[i])
154                         return 0;
155                 rep->rrsets[i]->entry.data = NULL;
156         }
157         return 1;
158 }
159
160 /** find the minimumttl in the rdata of SOA record */
161 static time_t
162 soa_find_minttl(struct rr_parse* rr)
163 {
164         uint16_t rlen = sldns_read_uint16(rr->ttl_data+4);
165         if(rlen < 20)
166                 return 0; /* rdata too small for SOA (dname, dname, 5*32bit) */
167         /* minimum TTL is the last 32bit value in the rdata of the record */
168         /* at position ttl_data + 4(ttl) + 2(rdatalen) + rdatalen - 4(timeval)*/
169         return (time_t)sldns_read_uint32(rr->ttl_data+6+rlen-4);
170 }
171
172 /** do the rdata copy */
173 static int
174 rdata_copy(sldns_buffer* pkt, struct packed_rrset_data* data, uint8_t* to, 
175         struct rr_parse* rr, time_t* rr_ttl, uint16_t type,
176         sldns_pkt_section section)
177 {
178         uint16_t pkt_len;
179         const sldns_rr_descriptor* desc;
180
181         *rr_ttl = sldns_read_uint32(rr->ttl_data);
182         /* RFC 2181 Section 8. if msb of ttl is set treat as if zero. */
183         if(*rr_ttl & 0x80000000U)
184                 *rr_ttl = 0;
185         if(type == LDNS_RR_TYPE_SOA && section == LDNS_SECTION_AUTHORITY) {
186                 /* negative response. see if TTL of SOA record larger than the
187                  * minimum-ttl in the rdata of the SOA record */
188                 if(*rr_ttl > soa_find_minttl(rr))
189                         *rr_ttl = soa_find_minttl(rr);
190                 if(*rr_ttl > MAX_NEG_TTL)
191                         *rr_ttl = MAX_NEG_TTL;
192         }
193         if(*rr_ttl < MIN_TTL)
194                 *rr_ttl = MIN_TTL;
195         if(*rr_ttl < data->ttl)
196                 data->ttl = *rr_ttl;
197
198         if(rr->outside_packet) {
199                 /* uncompressed already, only needs copy */
200                 memmove(to, rr->ttl_data+sizeof(uint32_t), rr->size);
201                 return 1;
202         }
203
204         sldns_buffer_set_position(pkt, (size_t)
205                 (rr->ttl_data - sldns_buffer_begin(pkt) + sizeof(uint32_t)));
206         /* insert decompressed size into rdata len stored in memory */
207         /* -2 because rdatalen bytes are not included. */
208         pkt_len = htons(rr->size - 2);
209         memmove(to, &pkt_len, sizeof(uint16_t));
210         to += 2;
211         /* read packet rdata len */
212         pkt_len = sldns_buffer_read_u16(pkt);
213         if(sldns_buffer_remaining(pkt) < pkt_len)
214                 return 0;
215         desc = sldns_rr_descript(type);
216         if(pkt_len > 0 && desc && desc->_dname_count > 0) {
217                 int count = (int)desc->_dname_count;
218                 int rdf = 0;
219                 size_t len;
220                 size_t oldpos;
221                 /* decompress dnames. */
222                 while(pkt_len > 0 && count) {
223                         switch(desc->_wireformat[rdf]) {
224                         case LDNS_RDF_TYPE_DNAME:
225                                 oldpos = sldns_buffer_position(pkt);
226                                 dname_pkt_copy(pkt, to, 
227                                         sldns_buffer_current(pkt));
228                                 to += pkt_dname_len(pkt);
229                                 pkt_len -= sldns_buffer_position(pkt)-oldpos;
230                                 count--;
231                                 len = 0;
232                                 break;
233                         case LDNS_RDF_TYPE_STR:
234                                 len = sldns_buffer_current(pkt)[0] + 1;
235                                 break;
236                         default:
237                                 len = get_rdf_size(desc->_wireformat[rdf]);
238                                 break;
239                         }
240                         if(len) {
241                                 memmove(to, sldns_buffer_current(pkt), len);
242                                 to += len;
243                                 sldns_buffer_skip(pkt, (ssize_t)len);
244                                 log_assert(len <= pkt_len);
245                                 pkt_len -= len;
246                         }
247                         rdf++;
248                 }
249         }
250         /* copy remaining rdata */
251         if(pkt_len >  0)
252                 memmove(to, sldns_buffer_current(pkt), pkt_len);
253         
254         return 1;
255 }
256
257 /** copy over the data into packed rrset */
258 static int
259 parse_rr_copy(sldns_buffer* pkt, struct rrset_parse* pset, 
260         struct packed_rrset_data* data)
261 {
262         size_t i;
263         struct rr_parse* rr = pset->rr_first;
264         uint8_t* nextrdata;
265         size_t total = pset->rr_count + pset->rrsig_count;
266         data->ttl = MAX_TTL;
267         data->count = pset->rr_count;
268         data->rrsig_count = pset->rrsig_count;
269         data->trust = rrset_trust_none;
270         data->security = sec_status_unchecked;
271         /* layout: struct - rr_len - rr_data - rr_ttl - rdata - rrsig */
272         data->rr_len = (size_t*)((uint8_t*)data + 
273                 sizeof(struct packed_rrset_data));
274         data->rr_data = (uint8_t**)&(data->rr_len[total]);
275         data->rr_ttl = (time_t*)&(data->rr_data[total]);
276         nextrdata = (uint8_t*)&(data->rr_ttl[total]);
277         for(i=0; i<data->count; i++) {
278                 data->rr_len[i] = rr->size;
279                 data->rr_data[i] = nextrdata;
280                 nextrdata += rr->size;
281                 if(!rdata_copy(pkt, data, data->rr_data[i], rr, 
282                         &data->rr_ttl[i], pset->type, pset->section))
283                         return 0;
284                 rr = rr->next;
285         }
286         /* if rrsig, its rdata is at nextrdata */
287         rr = pset->rrsig_first;
288         for(i=data->count; i<total; i++) {
289                 data->rr_len[i] = rr->size;
290                 data->rr_data[i] = nextrdata;
291                 nextrdata += rr->size;
292                 if(!rdata_copy(pkt, data, data->rr_data[i], rr, 
293                         &data->rr_ttl[i], LDNS_RR_TYPE_RRSIG, pset->section))
294                         return 0;
295                 rr = rr->next;
296         }
297         return 1;
298 }
299
300 /** create rrset return 0 on failure */
301 static int
302 parse_create_rrset(sldns_buffer* pkt, struct rrset_parse* pset,
303         struct packed_rrset_data** data, struct regional* region)
304 {
305         /* allocate */
306         size_t s;
307         if(pset->rr_count > RR_COUNT_MAX || pset->rrsig_count > RR_COUNT_MAX ||
308                 pset->size > RR_COUNT_MAX)
309                 return 0; /* protect against integer overflow */
310         s = sizeof(struct packed_rrset_data) + 
311                 (pset->rr_count + pset->rrsig_count) * 
312                 (sizeof(size_t)+sizeof(uint8_t*)+sizeof(time_t)) + 
313                 pset->size;
314         if(region)
315                 *data = regional_alloc(region, s);
316         else    *data = malloc(s);
317         if(!*data)
318                 return 0;
319         /* copy & decompress */
320         if(!parse_rr_copy(pkt, pset, *data)) {
321                 if(!region) free(*data);
322                 return 0;
323         }
324         return 1;
325 }
326
327 /** get trust value for rrset */
328 static enum rrset_trust
329 get_rrset_trust(struct msg_parse* msg, struct rrset_parse* rrset)
330 {
331         uint16_t AA = msg->flags & BIT_AA;
332         if(rrset->section == LDNS_SECTION_ANSWER) {
333                 if(AA) {
334                         /* RFC2181 says remainder of CNAME chain is nonauth*/
335                         if(msg->rrset_first && 
336                                 msg->rrset_first->section==LDNS_SECTION_ANSWER
337                                 && msg->rrset_first->type==LDNS_RR_TYPE_CNAME){
338                                 if(rrset == msg->rrset_first)
339                                         return rrset_trust_ans_AA;
340                                 else    return rrset_trust_ans_noAA;
341                         }
342                         if(msg->rrset_first && 
343                                 msg->rrset_first->section==LDNS_SECTION_ANSWER
344                                 && msg->rrset_first->type==LDNS_RR_TYPE_DNAME){
345                                 if(rrset == msg->rrset_first ||
346                                    rrset == msg->rrset_first->rrset_all_next)
347                                         return rrset_trust_ans_AA;
348                                 else    return rrset_trust_ans_noAA;
349                         }
350                         return rrset_trust_ans_AA;
351                 }
352                 else    return rrset_trust_ans_noAA;
353         } else if(rrset->section == LDNS_SECTION_AUTHORITY) {
354                 if(AA)  return rrset_trust_auth_AA;
355                 else    return rrset_trust_auth_noAA;
356         } else {
357                 /* addit section */
358                 if(AA)  return rrset_trust_add_AA;
359                 else    return rrset_trust_add_noAA;
360         }
361         /* NOTREACHED */
362         return rrset_trust_none;
363 }
364
365 int
366 parse_copy_decompress_rrset(sldns_buffer* pkt, struct msg_parse* msg,
367         struct rrset_parse *pset, struct regional* region, 
368         struct ub_packed_rrset_key* pk)
369 {
370         struct packed_rrset_data* data;
371         pk->rk.flags = pset->flags;
372         pk->rk.dname_len = pset->dname_len;
373         if(region)
374                 pk->rk.dname = (uint8_t*)regional_alloc(
375                         region, pset->dname_len);
376         else    pk->rk.dname = 
377                         (uint8_t*)malloc(pset->dname_len);
378         if(!pk->rk.dname)
379                 return 0;
380         /** copy & decompress dname */
381         dname_pkt_copy(pkt, pk->rk.dname, pset->dname);
382         /** copy over type and class */
383         pk->rk.type = htons(pset->type);
384         pk->rk.rrset_class = pset->rrset_class;
385         /** read data part. */
386         if(!parse_create_rrset(pkt, pset, &data, region))
387                 return 0;
388         pk->entry.data = (void*)data;
389         pk->entry.key = (void*)pk;
390         pk->entry.hash = pset->hash;
391         data->trust = get_rrset_trust(msg, pset);
392         return 1;
393 }
394
395 /** 
396  * Copy and decompress rrs
397  * @param pkt: the packet for compression pointer resolution.
398  * @param msg: the parsed message
399  * @param rep: reply info to put rrs into.
400  * @param region: if not NULL, used for allocation.
401  * @return 0 on failure.
402  */
403 static int
404 parse_copy_decompress(sldns_buffer* pkt, struct msg_parse* msg,
405         struct reply_info* rep, struct regional* region)
406 {
407         size_t i;
408         struct rrset_parse *pset = msg->rrset_first;
409         struct packed_rrset_data* data;
410         log_assert(rep);
411         rep->ttl = MAX_TTL;
412         rep->security = sec_status_unchecked;
413         if(rep->rrset_count == 0)
414                 rep->ttl = NORR_TTL;
415
416         for(i=0; i<rep->rrset_count; i++) {
417                 if(!parse_copy_decompress_rrset(pkt, msg, pset, region,
418                         rep->rrsets[i]))
419                         return 0;
420                 data = (struct packed_rrset_data*)rep->rrsets[i]->entry.data;
421                 if(data->ttl < rep->ttl)
422                         rep->ttl = data->ttl;
423
424                 pset = pset->rrset_all_next;
425         }
426         rep->prefetch_ttl = PREFETCH_TTL_CALC(rep->ttl);
427         return 1;
428 }
429
430 int 
431 parse_create_msg(sldns_buffer* pkt, struct msg_parse* msg,
432         struct alloc_cache* alloc, struct query_info* qinf, 
433         struct reply_info** rep, struct regional* region)
434 {
435         log_assert(pkt && msg);
436         if(!parse_create_qinfo(pkt, msg, qinf, region))
437                 return 0;
438         if(!parse_create_repinfo(msg, rep, region))
439                 return 0;
440         if(!reply_info_alloc_rrset_keys(*rep, alloc, region))
441                 return 0;
442         if(!parse_copy_decompress(pkt, msg, *rep, region))
443                 return 0;
444         return 1;
445 }
446
447 int reply_info_parse(sldns_buffer* pkt, struct alloc_cache* alloc,
448         struct query_info* qinf, struct reply_info** rep, 
449         struct regional* region, struct edns_data* edns)
450 {
451         /* use scratch pad region-allocator during parsing. */
452         struct msg_parse* msg;
453         int ret;
454         
455         qinf->qname = NULL;
456         qinf->local_alias = NULL;
457         *rep = NULL;
458         if(!(msg = regional_alloc(region, sizeof(*msg)))) {
459                 return LDNS_RCODE_SERVFAIL;
460         }
461         memset(msg, 0, sizeof(*msg));
462         
463         sldns_buffer_set_position(pkt, 0);
464         if((ret = parse_packet(pkt, msg, region)) != 0) {
465                 return ret;
466         }
467         if((ret = parse_extract_edns(msg, edns, region)) != 0)
468                 return ret;
469
470         /* parse OK, allocate return structures */
471         /* this also performs dname decompression */
472         if(!parse_create_msg(pkt, msg, alloc, qinf, rep, NULL)) {
473                 query_info_clear(qinf);
474                 reply_info_parsedelete(*rep, alloc);
475                 *rep = NULL;
476                 return LDNS_RCODE_SERVFAIL;
477         }
478         return 0;
479 }
480
481 /** helper compare function to sort in lock order */
482 static int
483 reply_info_sortref_cmp(const void* a, const void* b)
484 {
485         struct rrset_ref* x = (struct rrset_ref*)a;
486         struct rrset_ref* y = (struct rrset_ref*)b;
487         if(x->key < y->key) return -1;
488         if(x->key > y->key) return 1;
489         return 0;
490 }
491
492 void 
493 reply_info_sortref(struct reply_info* rep)
494 {
495         qsort(&rep->ref[0], rep->rrset_count, sizeof(struct rrset_ref),
496                 reply_info_sortref_cmp);
497 }
498
499 void 
500 reply_info_set_ttls(struct reply_info* rep, time_t timenow)
501 {
502         size_t i, j;
503         rep->ttl += timenow;
504         rep->prefetch_ttl += timenow;
505         for(i=0; i<rep->rrset_count; i++) {
506                 struct packed_rrset_data* data = (struct packed_rrset_data*)
507                         rep->ref[i].key->entry.data;
508                 if(i>0 && rep->ref[i].key == rep->ref[i-1].key)
509                         continue;
510                 data->ttl += timenow;
511                 for(j=0; j<data->count + data->rrsig_count; j++) {
512                         data->rr_ttl[j] += timenow;
513                 }
514         }
515 }
516
517 void 
518 reply_info_parsedelete(struct reply_info* rep, struct alloc_cache* alloc)
519 {
520         size_t i;
521         if(!rep) 
522                 return;
523         /* no need to lock, since not shared in hashtables. */
524         for(i=0; i<rep->rrset_count; i++) {
525                 ub_packed_rrset_parsedelete(rep->rrsets[i], alloc);
526         }
527         free(rep);
528 }
529
530 int 
531 query_info_parse(struct query_info* m, sldns_buffer* query)
532 {
533         uint8_t* q = sldns_buffer_begin(query);
534         /* minimum size: header + \0 + qtype + qclass */
535         if(sldns_buffer_limit(query) < LDNS_HEADER_SIZE + 5)
536                 return 0;
537         if(LDNS_OPCODE_WIRE(q) != LDNS_PACKET_QUERY || 
538                 LDNS_QDCOUNT(q) != 1 || sldns_buffer_position(query) != 0)
539                 return 0;
540         sldns_buffer_skip(query, LDNS_HEADER_SIZE);
541         m->qname = sldns_buffer_current(query);
542         if((m->qname_len = query_dname_len(query)) == 0)
543                 return 0; /* parse error */
544         if(sldns_buffer_remaining(query) < 4)
545                 return 0; /* need qtype, qclass */
546         m->qtype = sldns_buffer_read_u16(query);
547         m->qclass = sldns_buffer_read_u16(query);
548         m->local_alias = NULL;
549         return 1;
550 }
551
552 /** tiny subroutine for msgreply_compare */
553 #define COMPARE_IT(x, y) \
554         if( (x) < (y) ) return -1; \
555         else if( (x) > (y) ) return +1; \
556         log_assert( (x) == (y) );
557
558 int 
559 query_info_compare(void* m1, void* m2)
560 {
561         struct query_info* msg1 = (struct query_info*)m1;
562         struct query_info* msg2 = (struct query_info*)m2;
563         int mc;
564         /* from most different to least different for speed */
565         COMPARE_IT(msg1->qtype, msg2->qtype);
566         if((mc = query_dname_compare(msg1->qname, msg2->qname)) != 0)
567                 return mc;
568         log_assert(msg1->qname_len == msg2->qname_len);
569         COMPARE_IT(msg1->qclass, msg2->qclass);
570         return 0;
571 #undef COMPARE_IT
572 }
573
574 void 
575 query_info_clear(struct query_info* m)
576 {
577         free(m->qname);
578         m->qname = NULL;
579 }
580
581 size_t 
582 msgreply_sizefunc(void* k, void* d)
583 {
584         struct msgreply_entry* q = (struct msgreply_entry*)k;
585         struct reply_info* r = (struct reply_info*)d;
586         size_t s = sizeof(struct msgreply_entry) + sizeof(struct reply_info)
587                 + q->key.qname_len + lock_get_mem(&q->entry.lock)
588                 - sizeof(struct rrset_ref);
589         s += r->rrset_count * sizeof(struct rrset_ref);
590         s += r->rrset_count * sizeof(struct ub_packed_rrset_key*);
591         return s;
592 }
593
594 void 
595 query_entry_delete(void *k, void* ATTR_UNUSED(arg))
596 {
597         struct msgreply_entry* q = (struct msgreply_entry*)k;
598         lock_rw_destroy(&q->entry.lock);
599         query_info_clear(&q->key);
600         free(q);
601 }
602
603 void 
604 reply_info_delete(void* d, void* ATTR_UNUSED(arg))
605 {
606         struct reply_info* r = (struct reply_info*)d;
607         free(r);
608 }
609
610 hashvalue_type
611 query_info_hash(struct query_info *q, uint16_t flags)
612 {
613         hashvalue_type h = 0xab;
614         h = hashlittle(&q->qtype, sizeof(q->qtype), h);
615         if(q->qtype == LDNS_RR_TYPE_AAAA && (flags&BIT_CD))
616                 h++;
617         h = hashlittle(&q->qclass, sizeof(q->qclass), h);
618         h = dname_query_hash(q->qname, h);
619         return h;
620 }
621
622 struct msgreply_entry* 
623 query_info_entrysetup(struct query_info* q, struct reply_info* r, 
624         hashvalue_type h)
625 {
626         struct msgreply_entry* e = (struct msgreply_entry*)malloc( 
627                 sizeof(struct msgreply_entry));
628         if(!e) return NULL;
629         memcpy(&e->key, q, sizeof(*q));
630         e->entry.hash = h;
631         e->entry.key = e;
632         e->entry.data = r;
633         lock_rw_init(&e->entry.lock);
634         lock_protect(&e->entry.lock, &e->key, sizeof(e->key));
635         lock_protect(&e->entry.lock, &e->entry.hash, sizeof(e->entry.hash) +
636                 sizeof(e->entry.key) + sizeof(e->entry.data));
637         lock_protect(&e->entry.lock, e->key.qname, e->key.qname_len);
638         q->qname = NULL;
639         return e;
640 }
641
642 /** copy rrsets from replyinfo to dest replyinfo */
643 static int
644 repinfo_copy_rrsets(struct reply_info* dest, struct reply_info* from, 
645         struct regional* region)
646 {
647         size_t i, s;
648         struct packed_rrset_data* fd, *dd;
649         struct ub_packed_rrset_key* fk, *dk;
650         for(i=0; i<dest->rrset_count; i++) {
651                 fk = from->rrsets[i];
652                 dk = dest->rrsets[i];
653                 fd = (struct packed_rrset_data*)fk->entry.data;
654                 dk->entry.hash = fk->entry.hash;
655                 dk->rk = fk->rk;
656                 if(region) {
657                         dk->id = fk->id;
658                         dk->rk.dname = (uint8_t*)regional_alloc_init(region,
659                                 fk->rk.dname, fk->rk.dname_len);
660                 } else  
661                         dk->rk.dname = (uint8_t*)memdup(fk->rk.dname, 
662                                 fk->rk.dname_len);
663                 if(!dk->rk.dname)
664                         return 0;
665                 s = packed_rrset_sizeof(fd);
666                 if(region)
667                         dd = (struct packed_rrset_data*)regional_alloc_init(
668                                 region, fd, s);
669                 else    dd = (struct packed_rrset_data*)memdup(fd, s);
670                 if(!dd) 
671                         return 0;
672                 packed_rrset_ptr_fixup(dd);
673                 dk->entry.data = (void*)dd;
674         }
675         return 1;
676 }
677
678 struct reply_info* 
679 reply_info_copy(struct reply_info* rep, struct alloc_cache* alloc, 
680         struct regional* region)
681 {
682         struct reply_info* cp;
683         cp = construct_reply_info_base(region, rep->flags, rep->qdcount, 
684                 rep->ttl, rep->prefetch_ttl, rep->an_numrrsets, 
685                 rep->ns_numrrsets, rep->ar_numrrsets, rep->rrset_count, 
686                 rep->security);
687         if(!cp)
688                 return NULL;
689         /* allocate ub_key structures special or not */
690         if(!reply_info_alloc_rrset_keys(cp, alloc, region)) {
691                 if(!region)
692                         reply_info_parsedelete(cp, alloc);
693                 return NULL;
694         }
695         if(!repinfo_copy_rrsets(cp, rep, region)) {
696                 if(!region)
697                         reply_info_parsedelete(cp, alloc);
698                 return NULL;
699         }
700         return cp;
701 }
702
703 uint8_t* 
704 reply_find_final_cname_target(struct query_info* qinfo, struct reply_info* rep)
705 {
706         uint8_t* sname = qinfo->qname;
707         size_t snamelen = qinfo->qname_len;
708         size_t i;
709         for(i=0; i<rep->an_numrrsets; i++) {
710                 struct ub_packed_rrset_key* s = rep->rrsets[i];
711                 /* follow CNAME chain (if any) */
712                 if(ntohs(s->rk.type) == LDNS_RR_TYPE_CNAME && 
713                         ntohs(s->rk.rrset_class) == qinfo->qclass && 
714                         snamelen == s->rk.dname_len &&
715                         query_dname_compare(sname, s->rk.dname) == 0) {
716                         get_cname_target(s, &sname, &snamelen);
717                 }
718         }
719         if(sname != qinfo->qname)
720                 return sname;
721         return NULL;
722 }
723
724 struct ub_packed_rrset_key* 
725 reply_find_answer_rrset(struct query_info* qinfo, struct reply_info* rep)
726 {
727         uint8_t* sname = qinfo->qname;
728         size_t snamelen = qinfo->qname_len;
729         size_t i;
730         for(i=0; i<rep->an_numrrsets; i++) {
731                 struct ub_packed_rrset_key* s = rep->rrsets[i];
732                 /* first match type, for query of qtype cname */
733                 if(ntohs(s->rk.type) == qinfo->qtype && 
734                         ntohs(s->rk.rrset_class) == qinfo->qclass && 
735                         snamelen == s->rk.dname_len &&
736                         query_dname_compare(sname, s->rk.dname) == 0) {
737                         return s;
738                 }
739                 /* follow CNAME chain (if any) */
740                 if(ntohs(s->rk.type) == LDNS_RR_TYPE_CNAME && 
741                         ntohs(s->rk.rrset_class) == qinfo->qclass && 
742                         snamelen == s->rk.dname_len &&
743                         query_dname_compare(sname, s->rk.dname) == 0) {
744                         get_cname_target(s, &sname, &snamelen);
745                 }
746         }
747         return NULL;
748 }
749
750 struct ub_packed_rrset_key* reply_find_rrset_section_an(struct reply_info* rep,
751         uint8_t* name, size_t namelen, uint16_t type, uint16_t dclass)
752 {
753         size_t i;
754         for(i=0; i<rep->an_numrrsets; i++) {
755                 struct ub_packed_rrset_key* s = rep->rrsets[i];
756                 if(ntohs(s->rk.type) == type && 
757                         ntohs(s->rk.rrset_class) == dclass && 
758                         namelen == s->rk.dname_len &&
759                         query_dname_compare(name, s->rk.dname) == 0) {
760                         return s;
761                 }
762         }
763         return NULL;
764 }
765
766 struct ub_packed_rrset_key* reply_find_rrset_section_ns(struct reply_info* rep,
767         uint8_t* name, size_t namelen, uint16_t type, uint16_t dclass)
768 {
769         size_t i;
770         for(i=rep->an_numrrsets; i<rep->an_numrrsets+rep->ns_numrrsets; i++) {
771                 struct ub_packed_rrset_key* s = rep->rrsets[i];
772                 if(ntohs(s->rk.type) == type && 
773                         ntohs(s->rk.rrset_class) == dclass && 
774                         namelen == s->rk.dname_len &&
775                         query_dname_compare(name, s->rk.dname) == 0) {
776                         return s;
777                 }
778         }
779         return NULL;
780 }
781
782 struct ub_packed_rrset_key* reply_find_rrset(struct reply_info* rep,
783         uint8_t* name, size_t namelen, uint16_t type, uint16_t dclass)
784 {
785         size_t i;
786         for(i=0; i<rep->rrset_count; i++) {
787                 struct ub_packed_rrset_key* s = rep->rrsets[i];
788                 if(ntohs(s->rk.type) == type && 
789                         ntohs(s->rk.rrset_class) == dclass && 
790                         namelen == s->rk.dname_len &&
791                         query_dname_compare(name, s->rk.dname) == 0) {
792                         return s;
793                 }
794         }
795         return NULL;
796 }
797
798 void 
799 log_dns_msg(const char* str, struct query_info* qinfo, struct reply_info* rep)
800 {
801         /* not particularly fast but flexible, make wireformat and print */
802         sldns_buffer* buf = sldns_buffer_new(65535);
803         struct regional* region = regional_create();
804         if(!reply_info_encode(qinfo, rep, 0, rep->flags, buf, 0, 
805                 region, 65535, 1)) {
806                 log_info("%s: log_dns_msg: out of memory", str);
807         } else {
808                 char* s = sldns_wire2str_pkt(sldns_buffer_begin(buf),
809                         sldns_buffer_limit(buf));
810                 if(!s) {
811                         log_info("%s: log_dns_msg: ldns tostr failed", str);
812                 } else {
813                         log_info("%s %s", str, s);
814                 }
815                 free(s);
816         }
817         sldns_buffer_free(buf);
818         regional_destroy(region);
819 }
820
821 void
822 log_reply_info(enum verbosity_value v, struct query_info *qinf,
823         struct sockaddr_storage *addr, socklen_t addrlen, struct timeval dur,
824         int cached, struct sldns_buffer *rmsg)
825 {
826         char qname_buf[LDNS_MAX_DOMAINLEN+1];
827         char clientip_buf[128];
828         char rcode_buf[16];
829         char type_buf[16];
830         char class_buf[16];
831         size_t pktlen;
832         uint16_t rcode = FLAGS_GET_RCODE(sldns_buffer_read_u16_at(rmsg, 2));
833
834         if(verbosity < v)
835           return;
836
837         sldns_wire2str_rcode_buf((int)rcode, rcode_buf, sizeof(rcode_buf));
838         addr_to_str(addr, addrlen, clientip_buf, sizeof(clientip_buf));
839         if(rcode == LDNS_RCODE_FORMERR)
840         {
841                 log_info("%s - - - %s - - - ", clientip_buf, rcode_buf);
842         } else {
843                 dname_str(qinf->qname, qname_buf);
844                 pktlen = sldns_buffer_limit(rmsg);
845                 sldns_wire2str_type_buf(qinf->qtype, type_buf, sizeof(type_buf));
846                 sldns_wire2str_class_buf(qinf->qclass, class_buf, sizeof(class_buf));
847                 log_info("%s %s %s %s %s " ARG_LL "d.%6.6d %d %d",
848                         clientip_buf, qname_buf, type_buf, class_buf,
849                         rcode_buf, (long long)dur.tv_sec, (int)dur.tv_usec, cached, (int)pktlen);
850         }
851 }
852
853 void
854 log_query_info(enum verbosity_value v, const char* str, 
855         struct query_info* qinf)
856 {
857         log_nametypeclass(v, str, qinf->qname, qinf->qtype, qinf->qclass);
858 }
859
860 int
861 reply_check_cname_chain(struct query_info* qinfo, struct reply_info* rep) 
862 {
863         /* check only answer section rrs for matching cname chain.
864          * the cache may return changed rdata, but owner names are untouched.*/
865         size_t i;
866         uint8_t* sname = qinfo->qname;
867         size_t snamelen = qinfo->qname_len;
868         for(i=0; i<rep->an_numrrsets; i++) {
869                 uint16_t t = ntohs(rep->rrsets[i]->rk.type);
870                 if(t == LDNS_RR_TYPE_DNAME)
871                         continue; /* skip dnames; note TTL 0 not cached */
872                 /* verify that owner matches current sname */
873                 if(query_dname_compare(sname, rep->rrsets[i]->rk.dname) != 0){
874                         /* cname chain broken */
875                         return 0;
876                 }
877                 /* if this is a cname; move on */
878                 if(t == LDNS_RR_TYPE_CNAME) {
879                         get_cname_target(rep->rrsets[i], &sname, &snamelen);
880                 }
881         }
882         return 1;
883 }
884
885 int
886 reply_all_rrsets_secure(struct reply_info* rep) 
887 {
888         size_t i;
889         for(i=0; i<rep->rrset_count; i++) {
890                 if( ((struct packed_rrset_data*)rep->rrsets[i]->entry.data)
891                         ->security != sec_status_secure )
892                 return 0;
893         }
894         return 1;
895 }
896
897 int edns_opt_append(struct edns_data* edns, struct regional* region,
898         uint16_t code, size_t len, uint8_t* data)
899 {
900         struct edns_option** prevp;
901         struct edns_option* opt;
902
903         /* allocate new element */
904         opt = (struct edns_option*)regional_alloc(region, sizeof(*opt));
905         if(!opt)
906                 return 0;
907         opt->next = NULL;
908         opt->opt_code = code;
909         opt->opt_len = len;
910         opt->opt_data = NULL;
911         if(len > 0) {
912                 opt->opt_data = regional_alloc_init(region, data, len);
913                 if(!opt->opt_data)
914                         return 0;
915         }
916         
917         /* append at end of list */
918         prevp = &edns->opt_list;
919         while(*prevp != NULL)
920                 prevp = &((*prevp)->next);
921         *prevp = opt;
922         return 1;
923 }
924
925 int edns_opt_list_append(struct edns_option** list, uint16_t code, size_t len,
926         uint8_t* data, struct regional* region)
927 {
928         struct edns_option** prevp;
929         struct edns_option* opt;
930
931         /* allocate new element */
932         opt = (struct edns_option*)regional_alloc(region, sizeof(*opt));
933         if(!opt)
934                 return 0;
935         opt->next = NULL;
936         opt->opt_code = code;
937         opt->opt_len = len;
938         opt->opt_data = NULL;
939         if(len > 0) {
940                 opt->opt_data = regional_alloc_init(region, data, len);
941                 if(!opt->opt_data)
942                         return 0;
943         }
944
945         /* append at end of list */
946         prevp = list;
947         while(*prevp != NULL) {
948                 prevp = &((*prevp)->next);
949         }
950         *prevp = opt;
951         return 1;
952 }
953
954 int edns_opt_list_remove(struct edns_option** list, uint16_t code)
955 {
956         /* The list should already be allocated in a region. Freeing the
957          * allocated space in a region is not possible. We just unlink the
958          * required elements and they will be freed together with the region. */
959
960         struct edns_option* prev;
961         struct edns_option* curr;
962         if(!list || !(*list)) return 0;
963
964         /* Unlink and repoint if the element(s) are first in list */
965         while(list && *list && (*list)->opt_code == code) {
966                 *list = (*list)->next;
967         }
968
969         if(!list || !(*list)) return 1;
970         /* Unlink elements and reattach the list */
971         prev = *list;
972         curr = (*list)->next;
973         while(curr != NULL) {
974                 if(curr->opt_code == code) {
975                         prev->next = curr->next;
976                         curr = curr->next;
977                 } else {
978                         prev = curr;
979                         curr = curr->next;
980                 }
981         }
982         return 1;
983 }
984
985 static int inplace_cb_reply_call_generic(
986     struct inplace_cb* callback_list, enum inplace_cb_list_type type,
987         struct query_info* qinfo, struct module_qstate* qstate,
988         struct reply_info* rep, int rcode, struct edns_data* edns,
989         struct regional* region)
990 {
991         struct inplace_cb* cb;
992         struct edns_option* opt_list_out = NULL;
993         if(qstate)
994                 opt_list_out = qstate->edns_opts_front_out;
995         for(cb=callback_list; cb; cb=cb->next) {
996                 fptr_ok(fptr_whitelist_inplace_cb_reply_generic(
997                         (inplace_cb_reply_func_type*)cb->cb, type));
998                 (void)(*(inplace_cb_reply_func_type*)cb->cb)(qinfo, qstate, rep,
999                         rcode, edns, &opt_list_out, region, cb->id, cb->cb_arg);
1000         }
1001         edns->opt_list = opt_list_out;
1002         return 1;
1003 }
1004
1005 int inplace_cb_reply_call(struct module_env* env, struct query_info* qinfo,
1006         struct module_qstate* qstate, struct reply_info* rep, int rcode,
1007         struct edns_data* edns, struct regional* region)
1008 {
1009         return inplace_cb_reply_call_generic(
1010                 env->inplace_cb_lists[inplace_cb_reply], inplace_cb_reply, qinfo,
1011                 qstate, rep, rcode, edns, region);
1012 }
1013
1014 int inplace_cb_reply_cache_call(struct module_env* env,
1015         struct query_info* qinfo, struct module_qstate* qstate,
1016         struct reply_info* rep, int rcode, struct edns_data* edns,
1017         struct regional* region)
1018 {
1019         return inplace_cb_reply_call_generic(
1020                 env->inplace_cb_lists[inplace_cb_reply_cache], inplace_cb_reply_cache,
1021                 qinfo, qstate, rep, rcode, edns, region);
1022 }
1023
1024 int inplace_cb_reply_local_call(struct module_env* env,
1025         struct query_info* qinfo, struct module_qstate* qstate,
1026         struct reply_info* rep, int rcode, struct edns_data* edns,
1027         struct regional* region)
1028 {
1029         return inplace_cb_reply_call_generic(
1030                 env->inplace_cb_lists[inplace_cb_reply_local], inplace_cb_reply_local,
1031                 qinfo, qstate, rep, rcode, edns, region);
1032 }
1033
1034 int inplace_cb_reply_servfail_call(struct module_env* env,
1035         struct query_info* qinfo, struct module_qstate* qstate,
1036         struct reply_info* rep, int rcode, struct edns_data* edns,
1037         struct regional* region)
1038 {
1039         /* We are going to servfail. Remove any potential edns options. */
1040         if(qstate)
1041                 qstate->edns_opts_front_out = NULL;
1042         return inplace_cb_reply_call_generic(
1043                 env->inplace_cb_lists[inplace_cb_reply_servfail],
1044                 inplace_cb_reply_servfail, qinfo, qstate, rep, rcode, edns, region);
1045 }
1046
1047 int inplace_cb_query_call(struct module_env* env, struct query_info* qinfo,
1048         uint16_t flags, struct sockaddr_storage* addr, socklen_t addrlen,
1049         uint8_t* zone, size_t zonelen, struct module_qstate* qstate,
1050         struct regional* region)
1051 {
1052         struct inplace_cb* cb = env->inplace_cb_lists[inplace_cb_query];
1053         for(; cb; cb=cb->next) {
1054                 fptr_ok(fptr_whitelist_inplace_cb_query(
1055                         (inplace_cb_query_func_type*)cb->cb));
1056                 (void)(*(inplace_cb_query_func_type*)cb->cb)(qinfo, flags,
1057                         qstate, addr, addrlen, zone, zonelen, region,
1058                         cb->id, cb->cb_arg);
1059         }
1060         return 1;
1061 }
1062
1063 int inplace_cb_edns_back_parsed_call(struct module_env* env, 
1064         struct module_qstate* qstate)
1065 {
1066         struct inplace_cb* cb =
1067                 env->inplace_cb_lists[inplace_cb_edns_back_parsed];
1068         for(; cb; cb=cb->next) {
1069                 fptr_ok(fptr_whitelist_inplace_cb_edns_back_parsed(
1070                         (inplace_cb_edns_back_parsed_func_type*)cb->cb));
1071                 (void)(*(inplace_cb_edns_back_parsed_func_type*)cb->cb)(qstate,
1072                         cb->id, cb->cb_arg);
1073         }
1074         return 1;
1075 }
1076
1077 int inplace_cb_query_response_call(struct module_env* env,
1078         struct module_qstate* qstate, struct dns_msg* response) {
1079         struct inplace_cb* cb =
1080                 env->inplace_cb_lists[inplace_cb_query_response];
1081         for(; cb; cb=cb->next) {
1082                 fptr_ok(fptr_whitelist_inplace_cb_query_response(
1083                         (inplace_cb_query_response_func_type*)cb->cb));
1084                 (void)(*(inplace_cb_query_response_func_type*)cb->cb)(qstate,
1085                         response, cb->id, cb->cb_arg);
1086         }
1087         return 1;
1088 }
1089
1090 struct edns_option* edns_opt_copy_region(struct edns_option* list,
1091         struct regional* region)
1092 {
1093         struct edns_option* result = NULL, *cur = NULL, *s;
1094         while(list) {
1095                 /* copy edns option structure */
1096                 s = regional_alloc_init(region, list, sizeof(*list));
1097                 if(!s) return NULL;
1098                 s->next = NULL;
1099
1100                 /* copy option data */
1101                 if(s->opt_data) {
1102                         s->opt_data = regional_alloc_init(region, s->opt_data,
1103                                 s->opt_len);
1104                         if(!s->opt_data)
1105                                 return NULL;
1106                 }
1107
1108                 /* link into list */
1109                 if(cur)
1110                         cur->next = s;
1111                 else    result = s;
1112                 cur = s;
1113
1114                 /* examine next element */
1115                 list = list->next;
1116         }
1117         return result;
1118 }
1119
1120 int edns_opt_compare(struct edns_option* p, struct edns_option* q)
1121 {
1122         if(!p && !q) return 0;
1123         if(!p) return -1;
1124         if(!q) return 1;
1125         log_assert(p && q);
1126         if(p->opt_code != q->opt_code)
1127                 return (int)q->opt_code - (int)p->opt_code;
1128         if(p->opt_len != q->opt_len)
1129                 return (int)q->opt_len - (int)p->opt_len;
1130         if(p->opt_len != 0)
1131                 return memcmp(p->opt_data, q->opt_data, p->opt_len);
1132         return 0;
1133 }
1134
1135 int edns_opt_list_compare(struct edns_option* p, struct edns_option* q)
1136 {
1137         int r;
1138         while(p && q) {
1139                 r = edns_opt_compare(p, q);
1140                 if(r != 0)
1141                         return r;
1142                 p = p->next;
1143                 q = q->next;
1144         }
1145         if(p || q) {
1146                 /* uneven length lists */
1147                 if(p) return 1;
1148                 if(q) return -1;
1149         }
1150         return 0;
1151 }
1152
1153 void edns_opt_list_free(struct edns_option* list)
1154 {
1155         struct edns_option* n;
1156         while(list) {
1157                 free(list->opt_data);
1158                 n = list->next;
1159                 free(list);
1160                 list = n;
1161         }
1162 }
1163
1164 struct edns_option* edns_opt_copy_alloc(struct edns_option* list)
1165 {
1166         struct edns_option* result = NULL, *cur = NULL, *s;
1167         while(list) {
1168                 /* copy edns option structure */
1169                 s = memdup(list, sizeof(*list));
1170                 if(!s) {
1171                         edns_opt_list_free(result);
1172                         return NULL;
1173                 }
1174                 s->next = NULL;
1175
1176                 /* copy option data */
1177                 if(s->opt_data) {
1178                         s->opt_data = memdup(s->opt_data, s->opt_len);
1179                         if(!s->opt_data) {
1180                                 free(s);
1181                                 edns_opt_list_free(result);
1182                                 return NULL;
1183                         }
1184                 }
1185
1186                 /* link into list */
1187                 if(cur)
1188                         cur->next = s;
1189                 else    result = s;
1190                 cur = s;
1191
1192                 /* examine next element */
1193                 list = list->next;
1194         }
1195         return result;
1196 }
1197
1198 struct edns_option* edns_opt_list_find(struct edns_option* list, uint16_t code)
1199 {
1200         struct edns_option* p;
1201         for(p=list; p; p=p->next) {
1202                 if(p->opt_code == code)
1203                         return p;
1204         }
1205         return NULL;
1206 }