Coverage Report

Created: 2025-07-11 06:08

/src/unbound/util/data/msgencode.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * util/data/msgencode.c - Encode DNS messages, queries and replies.
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 routines to encode DNS messages.
40
 */
41
42
#include "config.h"
43
#include "util/data/msgencode.h"
44
#include "util/data/msgreply.h"
45
#include "util/data/msgparse.h"
46
#include "util/data/dname.h"
47
#include "util/log.h"
48
#include "util/regional.h"
49
#include "util/net_help.h"
50
#include "sldns/sbuffer.h"
51
#include "services/localzone.h"
52
53
#ifdef HAVE_TIME_H
54
#include <time.h>
55
#endif
56
#include <sys/time.h>
57
58
/** return code that means the function ran out of memory. negative so it does
59
 * not conflict with DNS rcodes. */
60
0
#define RETVAL_OUTMEM -2
61
/** return code that means the data did not fit (completely) in the packet */
62
0
#define RETVAL_TRUNC  -4
63
/** return code that means all is peachy keen. Equal to DNS rcode NOERROR */
64
0
#define RETVAL_OK 0
65
/** Max compressions we are willing to perform; more than that will result
66
 *  in semi-compressed messages, or truncated even on TCP for huge messages, to
67
 *  avoid locking the CPU for long */
68
0
#define MAX_COMPRESSION_PER_MESSAGE 120
69
70
/**
71
 * Data structure to help domain name compression in outgoing messages.
72
 * A tree of dnames and their offsets in the packet is kept.
73
 * It is kept sorted, not canonical, but by label at least, so that after
74
 * a lookup of a name you know its closest match, and the parent from that
75
 * closest match. These are possible compression targets.
76
 *
77
 * It is a binary tree, not a rbtree or balanced tree, as the effort
78
 * of keeping it balanced probably outweighs usefulness (given typical
79
 * DNS packet size).
80
 */
81
struct compress_tree_node {
82
  /** left node in tree, all smaller to this */
83
  struct compress_tree_node* left;
84
  /** right node in tree, all larger than this */
85
  struct compress_tree_node* right;
86
87
  /** the parent node - not for tree, but zone parent. One less label */
88
  struct compress_tree_node* parent;
89
  /** the domain name for this node. Pointer to uncompressed memory. */
90
  uint8_t* dname;
91
  /** number of labels in domain name, kept to help compare func. */
92
  int labs;
93
  /** offset in packet that points to this dname */
94
  size_t offset;
95
};
96
97
/**
98
 * Find domain name in tree, returns exact and closest match.
99
 * @param tree: root of tree.
100
 * @param dname: pointer to uncompressed dname.
101
 * @param labs: number of labels in domain name.
102
 * @param match: closest or exact match.
103
 *  guaranteed to be smaller or equal to the sought dname.
104
 *  can be null if the tree is empty.
105
 * @param matchlabels: number of labels that match with closest match.
106
 *  can be zero is there is no match.
107
 * @param insertpt: insert location for dname, if not found.
108
 * @return: 0 if no exact match.
109
 */
110
static int
111
compress_tree_search(struct compress_tree_node** tree, uint8_t* dname,
112
  int labs, struct compress_tree_node** match, int* matchlabels,
113
  struct compress_tree_node*** insertpt)
114
0
{
115
0
  int c, n, closen=0;
116
0
  struct compress_tree_node* p = *tree;
117
0
  struct compress_tree_node* close = 0;
118
0
  struct compress_tree_node** prev = tree;
119
0
  while(p) {
120
0
    if((c = dname_lab_cmp(dname, labs, p->dname, p->labs, &n)) 
121
0
      == 0) {
122
0
      *matchlabels = n;
123
0
      *match = p;
124
0
      return 1;
125
0
    }
126
0
    if(c<0) {
127
0
      prev = &p->left;
128
0
      p = p->left;
129
0
    } else {
130
0
      closen = n;
131
0
      close = p; /* p->dname is smaller than dname */
132
0
      prev = &p->right;
133
0
      p = p->right;
134
0
    }
135
0
  }
136
0
  *insertpt = prev;
137
0
  *matchlabels = closen;
138
0
  *match = close;
139
0
  return 0;
140
0
}
141
142
/**
143
 * Lookup a domain name in compression tree.
144
 * @param tree: root of tree (not the node with '.').
145
 * @param dname: pointer to uncompressed dname.
146
 * @param labs: number of labels in domain name.
147
 * @param insertpt: insert location for dname, if not found.
148
 * @return: 0 if not found or compress treenode with best compression.
149
 */
150
static struct compress_tree_node*
151
compress_tree_lookup(struct compress_tree_node** tree, uint8_t* dname,
152
  int labs, struct compress_tree_node*** insertpt)
153
0
{
154
0
  struct compress_tree_node* p;
155
0
  int m;
156
0
  if(labs <= 1)
157
0
    return 0; /* do not compress root node */
158
0
  if(compress_tree_search(tree, dname, labs, &p, &m, insertpt)) {
159
    /* exact match */
160
0
    return p;
161
0
  }
162
  /* return some ancestor of p that compresses well. */
163
0
  if(m>1) {
164
    /* www.example.com. (labs=4) matched foo.example.com.(labs=4)
165
     * then matchcount = 3. need to go up. */
166
0
    while(p && p->labs > m)
167
0
      p = p->parent;
168
0
    return p;
169
0
  }
170
0
  return 0;
171
0
}
172
173
/**
174
 * Create node for domain name compression tree.
175
 * @param dname: pointer to uncompressed dname (stored in tree).
176
 * @param labs: number of labels in dname.
177
 * @param offset: offset into packet for dname.
178
 * @param region: how to allocate memory for new node.
179
 * @return new node or 0 on malloc failure.
180
 */
181
static struct compress_tree_node*
182
compress_tree_newnode(uint8_t* dname, int labs, size_t offset, 
183
  struct regional* region)
184
0
{
185
0
  struct compress_tree_node* n = (struct compress_tree_node*)
186
0
    regional_alloc(region, sizeof(struct compress_tree_node));
187
0
  if(!n) return 0;
188
0
  n->left = 0;
189
0
  n->right = 0;
190
0
  n->parent = 0;
191
0
  n->dname = dname;
192
0
  n->labs = labs;
193
0
  n->offset = offset;
194
0
  return n;
195
0
}
196
197
/**
198
 * Store domain name and ancestors into compression tree.
199
 * @param dname: pointer to uncompressed dname (stored in tree).
200
 * @param labs: number of labels in dname.
201
 * @param offset: offset into packet for dname.
202
 * @param region: how to allocate memory for new node.
203
 * @param closest: match from previous lookup, used to compress dname.
204
 *  may be NULL if no previous match.
205
 *  if the tree has an ancestor of dname already, this must be it.
206
 * @param insertpt: where to insert the dname in tree. 
207
 * @return: 0 on memory error.
208
 */
209
static int
210
compress_tree_store(uint8_t* dname, int labs, size_t offset, 
211
  struct regional* region, struct compress_tree_node* closest, 
212
  struct compress_tree_node** insertpt)
213
0
{
214
0
  uint8_t lablen;
215
0
  struct compress_tree_node* newnode;
216
0
  struct compress_tree_node* prevnode = NULL;
217
0
  int uplabs = labs-1; /* does not store root in tree */
218
0
  if(closest) uplabs = labs - closest->labs;
219
0
  log_assert(uplabs >= 0);
220
  /* algorithms builds up a vine of dname-labels to hang into tree */
221
0
  while(uplabs--) {
222
0
    if(offset > PTR_MAX_OFFSET) {
223
      /* insertion failed, drop vine */
224
0
      return 1; /* compression pointer no longer useful */
225
0
    }
226
0
    if(!(newnode = compress_tree_newnode(dname, labs, offset, 
227
0
      region))) {
228
      /* insertion failed, drop vine */
229
0
      return 0;
230
0
    }
231
232
0
    if(prevnode) {
233
      /* chain nodes together, last one has one label more,
234
       * so is larger than newnode, thus goes right. */
235
0
      newnode->right = prevnode;
236
0
      prevnode->parent = newnode;
237
0
    }
238
239
    /* next label */
240
0
    lablen = *dname++;
241
0
    dname += lablen;
242
0
    offset += lablen+1;
243
0
    prevnode = newnode;
244
0
    labs--;
245
0
  }
246
  /* if we have a vine, hang the vine into the tree */
247
0
  if(prevnode) {
248
0
    *insertpt = prevnode;
249
0
    prevnode->parent = closest;
250
0
  }
251
0
  return 1;
252
0
}
253
254
/** compress a domain name */
255
static int
256
write_compressed_dname(sldns_buffer* pkt, uint8_t* dname, int labs,
257
  struct compress_tree_node* p)
258
0
{
259
  /* compress it */
260
0
  int labcopy = labs - p->labs;
261
0
  uint8_t lablen;
262
0
  uint16_t ptr;
263
264
0
  if(labs == 1) {
265
    /* write root label */
266
0
    if(sldns_buffer_remaining(pkt) < 1)
267
0
      return 0;
268
0
    sldns_buffer_write_u8(pkt, 0);
269
0
    return 1;
270
0
  }
271
272
  /* copy the first couple of labels */
273
0
  while(labcopy--) {
274
0
    lablen = *dname++;
275
0
    if(sldns_buffer_remaining(pkt) < (size_t)lablen+1)
276
0
      return 0;
277
0
    sldns_buffer_write_u8(pkt, lablen);
278
0
    sldns_buffer_write(pkt, dname, lablen);
279
0
    dname += lablen;
280
0
  }
281
  /* insert compression ptr */
282
0
  if(sldns_buffer_remaining(pkt) < 2)
283
0
    return 0;
284
0
  ptr = PTR_CREATE(p->offset);
285
0
  sldns_buffer_write_u16(pkt, ptr);
286
0
  return 1;
287
0
}
288
289
/** compress owner name of RR, return RETVAL_OUTMEM RETVAL_TRUNC */
290
static int
291
compress_owner(struct ub_packed_rrset_key* key, sldns_buffer* pkt,
292
  struct regional* region, struct compress_tree_node** tree,
293
  size_t owner_pos, uint16_t* owner_ptr, int owner_labs,
294
  size_t* compress_count)
295
0
{
296
0
  struct compress_tree_node* p;
297
0
  struct compress_tree_node** insertpt = NULL;
298
0
  if(!*owner_ptr) {
299
    /* compress first time dname */
300
0
    if(*compress_count < MAX_COMPRESSION_PER_MESSAGE &&
301
0
      (p = compress_tree_lookup(tree, key->rk.dname,
302
0
      owner_labs, &insertpt))) {
303
0
      if(p->labs == owner_labs) 
304
        /* avoid ptr chains, since some software is
305
         * not capable of decoding ptr after a ptr. */
306
0
        *owner_ptr = htons(PTR_CREATE(p->offset));
307
0
      if(!write_compressed_dname(pkt, key->rk.dname, 
308
0
        owner_labs, p))
309
0
        return RETVAL_TRUNC;
310
0
      (*compress_count)++;
311
      /* check if typeclass+4 ttl + rdatalen is available */
312
0
      if(sldns_buffer_remaining(pkt) < 4+4+2)
313
0
        return RETVAL_TRUNC;
314
0
    } else {
315
      /* no compress */
316
0
      if(sldns_buffer_remaining(pkt) < key->rk.dname_len+4+4+2)
317
0
        return RETVAL_TRUNC;
318
0
      sldns_buffer_write(pkt, key->rk.dname, 
319
0
        key->rk.dname_len);
320
0
      if(owner_pos <= PTR_MAX_OFFSET)
321
0
        *owner_ptr = htons(PTR_CREATE(owner_pos));
322
0
    }
323
0
    if(*compress_count < MAX_COMPRESSION_PER_MESSAGE &&
324
0
      !compress_tree_store(key->rk.dname, owner_labs,
325
0
      owner_pos, region, p, insertpt))
326
0
      return RETVAL_OUTMEM;
327
0
  } else {
328
    /* always compress 2nd-further RRs in RRset */
329
0
    if(owner_labs == 1) {
330
0
      if(sldns_buffer_remaining(pkt) < 1+4+4+2) 
331
0
        return RETVAL_TRUNC;
332
0
      sldns_buffer_write_u8(pkt, 0);
333
0
    } else {
334
0
      if(sldns_buffer_remaining(pkt) < 2+4+4+2) 
335
0
        return RETVAL_TRUNC;
336
0
      sldns_buffer_write(pkt, owner_ptr, 2);
337
0
    }
338
0
  }
339
0
  return RETVAL_OK;
340
0
}
341
342
/** compress any domain name to the packet, return RETVAL_* */
343
static int
344
compress_any_dname(uint8_t* dname, sldns_buffer* pkt, int labs,
345
  struct regional* region, struct compress_tree_node** tree,
346
  size_t* compress_count)
347
0
{
348
0
  struct compress_tree_node* p;
349
0
  struct compress_tree_node** insertpt = NULL;
350
0
  size_t pos = sldns_buffer_position(pkt);
351
0
  if(*compress_count < MAX_COMPRESSION_PER_MESSAGE &&
352
0
    (p = compress_tree_lookup(tree, dname, labs, &insertpt))) {
353
0
    if(!write_compressed_dname(pkt, dname, labs, p))
354
0
      return RETVAL_TRUNC;
355
0
    (*compress_count)++;
356
0
  } else {
357
0
    if(!dname_buffer_write(pkt, dname))
358
0
      return RETVAL_TRUNC;
359
0
  }
360
0
  if(*compress_count < MAX_COMPRESSION_PER_MESSAGE &&
361
0
    !compress_tree_store(dname, labs, pos, region, p, insertpt))
362
0
    return RETVAL_OUTMEM;
363
0
  return RETVAL_OK;
364
0
}
365
366
/** return true if type needs domain name compression in rdata */
367
static const sldns_rr_descriptor*
368
type_rdata_compressible(struct ub_packed_rrset_key* key)
369
0
{
370
0
  uint16_t t = ntohs(key->rk.type);
371
0
  if(sldns_rr_descript(t) && 
372
0
    sldns_rr_descript(t)->_compress == LDNS_RR_COMPRESS)
373
0
    return sldns_rr_descript(t);
374
0
  return 0;
375
0
}
376
377
/** compress domain names in rdata, return RETVAL_* */
378
static int
379
compress_rdata(sldns_buffer* pkt, uint8_t* rdata, size_t todolen,
380
  struct regional* region, struct compress_tree_node** tree,
381
  const sldns_rr_descriptor* desc, size_t* compress_count)
382
0
{
383
0
  int labs, r, rdf = 0;
384
0
  size_t dname_len, len, pos = sldns_buffer_position(pkt);
385
0
  uint8_t count = desc->_dname_count;
386
387
0
  sldns_buffer_skip(pkt, 2); /* rdata len fill in later */
388
  /* space for rdatalen checked for already */
389
0
  rdata += 2;
390
0
  todolen -= 2;
391
0
  while(todolen > 0 && count) {
392
0
    switch(desc->_wireformat[rdf]) {
393
0
    case LDNS_RDF_TYPE_DNAME:
394
0
      labs = dname_count_size_labels(rdata, &dname_len);
395
0
      if((r=compress_any_dname(rdata, pkt, labs, region,
396
0
        tree, compress_count)) != RETVAL_OK)
397
0
        return r;
398
0
      rdata += dname_len;
399
0
      todolen -= dname_len;
400
0
      count--;
401
0
      len = 0;
402
0
      break;
403
0
    case LDNS_RDF_TYPE_STR:
404
0
      len = *rdata + 1;
405
0
      break;
406
0
    default:
407
0
      len = get_rdf_size(desc->_wireformat[rdf]);
408
0
    }
409
0
    if(len) {
410
      /* copy over */
411
0
      if(sldns_buffer_remaining(pkt) < len)
412
0
        return RETVAL_TRUNC;
413
0
      sldns_buffer_write(pkt, rdata, len);
414
0
      todolen -= len;
415
0
      rdata += len;
416
0
    }
417
0
    rdf++;
418
0
  }
419
  /* copy remainder */
420
0
  if(todolen > 0) {
421
0
    if(sldns_buffer_remaining(pkt) < todolen)
422
0
      return RETVAL_TRUNC;
423
0
    sldns_buffer_write(pkt, rdata, todolen);
424
0
  }
425
426
  /* set rdata len */
427
0
  sldns_buffer_write_u16_at(pkt, pos, sldns_buffer_position(pkt)-pos-2);
428
0
  return RETVAL_OK;
429
0
}
430
431
/** Returns true if RR type should be included */
432
static int
433
rrset_belongs_in_reply(sldns_pkt_section s, uint16_t rrtype, uint16_t qtype, 
434
  int dnssec)
435
0
{
436
0
  if(dnssec)
437
0
    return 1;
438
  /* skip non DNSSEC types, except if directly queried for */
439
0
  if(s == LDNS_SECTION_ANSWER) {
440
0
    if(qtype == LDNS_RR_TYPE_ANY || qtype == rrtype)
441
0
      return 1;
442
0
  }
443
  /* check DNSSEC-ness */
444
0
  switch(rrtype) {
445
0
    case LDNS_RR_TYPE_SIG:
446
0
    case LDNS_RR_TYPE_KEY:
447
0
    case LDNS_RR_TYPE_NXT:
448
0
    case LDNS_RR_TYPE_DS:
449
0
    case LDNS_RR_TYPE_RRSIG:
450
0
    case LDNS_RR_TYPE_NSEC:
451
0
    case LDNS_RR_TYPE_DNSKEY:
452
0
    case LDNS_RR_TYPE_NSEC3:
453
0
    case LDNS_RR_TYPE_NSEC3PARAMS:
454
0
      return 0;
455
0
  }
456
0
  return 1;
457
0
}
458
459
/** store rrset in buffer in wireformat, return RETVAL_* */
460
static int
461
packed_rrset_encode(struct ub_packed_rrset_key* key, sldns_buffer* pkt, 
462
  uint16_t* num_rrs, time_t timenow, struct regional* region,
463
  int do_data, int do_sig, struct compress_tree_node** tree,
464
  sldns_pkt_section s, uint16_t qtype, int dnssec, size_t rr_offset,
465
  size_t* compress_count)
466
0
{
467
0
  size_t i, j, owner_pos;
468
0
  int r, owner_labs;
469
0
  uint16_t owner_ptr = 0;
470
0
  time_t adjust = 0;
471
0
  struct packed_rrset_data* data = (struct packed_rrset_data*)
472
0
    key->entry.data;
473
  
474
  /* does this RR type belong in the answer? */
475
0
  if(!rrset_belongs_in_reply(s, ntohs(key->rk.type), qtype, dnssec))
476
0
    return RETVAL_OK;
477
478
0
  owner_labs = dname_count_labels(key->rk.dname);
479
0
  owner_pos = sldns_buffer_position(pkt);
480
481
  /** Determine relative time adjustment for TTL values.
482
   * For an rrset with a fixed TTL, use the rrset's TTL as given. */
483
0
  if((key->rk.flags & PACKED_RRSET_FIXEDTTL) != 0)
484
0
    adjust = 0;
485
0
  else
486
0
    adjust = SERVE_ORIGINAL_TTL ? data->ttl_add : timenow;
487
488
0
  if(do_data) {
489
0
    const sldns_rr_descriptor* c = type_rdata_compressible(key);
490
0
    for(i=0; i<data->count; i++) {
491
      /* rrset roundrobin */
492
0
      j = (i + rr_offset) % data->count;
493
0
      if((r=compress_owner(key, pkt, region, tree,
494
0
        owner_pos, &owner_ptr, owner_labs,
495
0
        compress_count)) != RETVAL_OK)
496
0
        return r;
497
0
      sldns_buffer_write(pkt, &key->rk.type, 2);
498
0
      sldns_buffer_write(pkt, &key->rk.rrset_class, 2);
499
0
      if(data->rr_ttl[j] < adjust)
500
0
        sldns_buffer_write_u32(pkt,
501
0
          SERVE_EXPIRED?SERVE_EXPIRED_REPLY_TTL:0);
502
0
      else  sldns_buffer_write_u32(pkt, data->rr_ttl[j]-adjust);
503
0
      if(c) {
504
0
        if((r=compress_rdata(pkt, data->rr_data[j],
505
0
          data->rr_len[j], region, tree, c,
506
0
          compress_count)) != RETVAL_OK)
507
0
          return r;
508
0
      } else {
509
0
        if(sldns_buffer_remaining(pkt) < data->rr_len[j])
510
0
          return RETVAL_TRUNC;
511
0
        sldns_buffer_write(pkt, data->rr_data[j],
512
0
          data->rr_len[j]);
513
0
      }
514
0
    }
515
0
  }
516
  /* insert rrsigs */
517
0
  if(do_sig && dnssec) {
518
0
    size_t total = data->count+data->rrsig_count;
519
0
    for(i=data->count; i<total; i++) {
520
0
      if(owner_ptr && owner_labs != 1) {
521
0
        if(sldns_buffer_remaining(pkt) <
522
0
          2+4+4+data->rr_len[i]) 
523
0
          return RETVAL_TRUNC;
524
0
        sldns_buffer_write(pkt, &owner_ptr, 2);
525
0
      } else {
526
0
        if((r=compress_any_dname(key->rk.dname,
527
0
          pkt, owner_labs, region, tree,
528
0
          compress_count)) != RETVAL_OK)
529
0
          return r;
530
0
        if(sldns_buffer_remaining(pkt) < 
531
0
          4+4+data->rr_len[i])
532
0
          return RETVAL_TRUNC;
533
0
      }
534
0
      sldns_buffer_write_u16(pkt, LDNS_RR_TYPE_RRSIG);
535
0
      sldns_buffer_write(pkt, &key->rk.rrset_class, 2);
536
0
      if(data->rr_ttl[i] < adjust)
537
0
        sldns_buffer_write_u32(pkt,
538
0
          SERVE_EXPIRED?SERVE_EXPIRED_REPLY_TTL:0);
539
0
      else  sldns_buffer_write_u32(pkt, data->rr_ttl[i]-adjust);
540
      /* rrsig rdata cannot be compressed, perform 100+ byte
541
       * memcopy. */
542
0
      sldns_buffer_write(pkt, data->rr_data[i],
543
0
        data->rr_len[i]);
544
0
    }
545
0
  }
546
  /* change rrnum only after we are sure it fits */
547
0
  if(do_data)
548
0
    *num_rrs += data->count;
549
0
  if(do_sig && dnssec)
550
0
    *num_rrs += data->rrsig_count;
551
552
0
  return RETVAL_OK;
553
0
}
554
555
/** store msg section in wireformat buffer, return RETVAL_* */
556
static int
557
insert_section(struct reply_info* rep, size_t num_rrsets, uint16_t* num_rrs,
558
  sldns_buffer* pkt, size_t rrsets_before, time_t timenow, 
559
  struct regional* region, struct compress_tree_node** tree,
560
  sldns_pkt_section s, uint16_t qtype, int dnssec, size_t rr_offset,
561
  size_t* compress_count)
562
0
{
563
0
  int r;
564
0
  size_t i, setstart;
565
  /* we now allow this function to be called multiple times for the
566
   * same section, incrementally updating num_rrs.  The caller is
567
   * responsible for initializing it (which is the case in the current
568
   * implementation). */
569
570
0
  if(s != LDNS_SECTION_ADDITIONAL) {
571
0
    if(s == LDNS_SECTION_ANSWER && qtype == LDNS_RR_TYPE_ANY)
572
0
      dnssec = 1; /* include all types in ANY answer */
573
0
      for(i=0; i<num_rrsets; i++) {
574
0
      setstart = sldns_buffer_position(pkt);
575
0
      if((r=packed_rrset_encode(rep->rrsets[rrsets_before+i], 
576
0
        pkt, num_rrs, timenow, region, 1, 1, tree,
577
0
        s, qtype, dnssec, rr_offset, compress_count))
578
0
        != RETVAL_OK) {
579
        /* Bad, but if due to size must set TC bit */
580
        /* trim off the rrset neatly. */
581
0
        sldns_buffer_set_position(pkt, setstart);
582
0
        return r;
583
0
      }
584
0
    }
585
0
  } else {
586
0
      for(i=0; i<num_rrsets; i++) {
587
0
      setstart = sldns_buffer_position(pkt);
588
0
      if((r=packed_rrset_encode(rep->rrsets[rrsets_before+i], 
589
0
        pkt, num_rrs, timenow, region, 1, 0, tree,
590
0
        s, qtype, dnssec, rr_offset, compress_count))
591
0
        != RETVAL_OK) {
592
0
        sldns_buffer_set_position(pkt, setstart);
593
0
        return r;
594
0
      }
595
0
    }
596
0
    if(dnssec)
597
0
        for(i=0; i<num_rrsets; i++) {
598
0
      setstart = sldns_buffer_position(pkt);
599
0
      if((r=packed_rrset_encode(rep->rrsets[rrsets_before+i], 
600
0
        pkt, num_rrs, timenow, region, 0, 1, tree,
601
0
        s, qtype, dnssec, rr_offset, compress_count))
602
0
        != RETVAL_OK) {
603
0
        sldns_buffer_set_position(pkt, setstart);
604
0
        return r;
605
0
      }
606
0
      }
607
0
  }
608
0
  return RETVAL_OK;
609
0
}
610
611
/** store query section in wireformat buffer, return RETVAL */
612
static int
613
insert_query(struct query_info* qinfo, struct compress_tree_node** tree, 
614
  sldns_buffer* buffer, struct regional* region)
615
0
{
616
0
  uint8_t* qname = qinfo->local_alias ?
617
0
    qinfo->local_alias->rrset->rk.dname : qinfo->qname;
618
0
  size_t qname_len = qinfo->local_alias ?
619
0
    qinfo->local_alias->rrset->rk.dname_len : qinfo->qname_len;
620
0
  if(sldns_buffer_remaining(buffer) < 
621
0
    qinfo->qname_len+sizeof(uint16_t)*2)
622
0
    return RETVAL_TRUNC; /* buffer too small */
623
  /* the query is the first name inserted into the tree */
624
0
  if(!compress_tree_store(qname, dname_count_labels(qname),
625
0
    sldns_buffer_position(buffer), region, NULL, tree))
626
0
    return RETVAL_OUTMEM;
627
0
  if(sldns_buffer_current(buffer) == qname)
628
0
    sldns_buffer_skip(buffer, (ssize_t)qname_len);
629
0
  else  sldns_buffer_write(buffer, qname, qname_len);
630
0
  sldns_buffer_write_u16(buffer, qinfo->qtype);
631
0
  sldns_buffer_write_u16(buffer, qinfo->qclass);
632
0
  return RETVAL_OK;
633
0
}
634
635
static int
636
0
positive_answer(struct reply_info* rep, uint16_t qtype) {
637
0
  size_t i;
638
0
  if (FLAGS_GET_RCODE(rep->flags) != LDNS_RCODE_NOERROR)
639
0
    return 0;
640
641
0
  for(i=0;i<rep->an_numrrsets; i++) {
642
0
    if(ntohs(rep->rrsets[i]->rk.type) == qtype) {
643
      /* for priming queries, type NS, include addresses */
644
0
      if(qtype == LDNS_RR_TYPE_NS)
645
0
        return 0;
646
      /* in case it is a wildcard with DNSSEC, there will
647
       * be NSEC/NSEC3 records in the authority section
648
       * that we cannot remove */
649
0
      for(i=rep->an_numrrsets; i<rep->an_numrrsets+
650
0
        rep->ns_numrrsets; i++) {
651
0
        if(ntohs(rep->rrsets[i]->rk.type) ==
652
0
          LDNS_RR_TYPE_NSEC ||
653
0
           ntohs(rep->rrsets[i]->rk.type) ==
654
0
            LDNS_RR_TYPE_NSEC3)
655
0
          return 0;
656
0
      }
657
0
      return 1;
658
0
    }
659
0
  }
660
0
  return 0;
661
0
}
662
663
static int
664
0
negative_answer(struct reply_info* rep) {
665
0
  size_t i;
666
0
  int ns_seen = 0;
667
0
  if(FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NXDOMAIN)
668
0
    return 1;
669
0
  if(FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NOERROR &&
670
0
    rep->an_numrrsets != 0)
671
0
    return 0; /* positive */
672
0
  if(FLAGS_GET_RCODE(rep->flags) != LDNS_RCODE_NOERROR &&
673
0
    FLAGS_GET_RCODE(rep->flags) != LDNS_RCODE_NXDOMAIN)
674
0
    return 0;
675
0
  for(i=rep->an_numrrsets; i<rep->an_numrrsets+rep->ns_numrrsets; i++){
676
0
    if(ntohs(rep->rrsets[i]->rk.type) == LDNS_RR_TYPE_SOA)
677
0
      return 1;
678
0
    if(ntohs(rep->rrsets[i]->rk.type) == LDNS_RR_TYPE_NS)
679
0
      ns_seen = 1;
680
0
  }
681
0
  if(ns_seen) return 0; /* could be referral, NS, but no SOA */
682
0
  return 1;
683
0
}
684
685
int
686
reply_info_encode(struct query_info* qinfo, struct reply_info* rep,
687
  uint16_t id, uint16_t flags, sldns_buffer* buffer, time_t timenow,
688
  struct regional* region, uint16_t udpsize, int dnssec, int minimise)
689
0
{
690
0
  uint16_t ancount=0, nscount=0, arcount=0;
691
0
  struct compress_tree_node* tree = 0;
692
0
  int r;
693
0
  size_t rr_offset;
694
0
  size_t compress_count=0;
695
696
0
  sldns_buffer_clear(buffer);
697
0
  if(udpsize < sldns_buffer_limit(buffer))
698
0
    sldns_buffer_set_limit(buffer, udpsize);
699
0
  if(sldns_buffer_remaining(buffer) < LDNS_HEADER_SIZE)
700
0
    return 0;
701
702
0
  sldns_buffer_write(buffer, &id, sizeof(uint16_t));
703
0
  sldns_buffer_write_u16(buffer, flags);
704
0
  sldns_buffer_write_u16(buffer, rep->qdcount);
705
  /* set an, ns, ar counts to zero in case of small packets */
706
0
  sldns_buffer_write(buffer, "\000\000\000\000\000\000", 6);
707
708
  /* insert query section */
709
0
  if(rep->qdcount) {
710
0
    if((r=insert_query(qinfo, &tree, buffer, region)) !=
711
0
      RETVAL_OK) {
712
0
      if(r == RETVAL_TRUNC) {
713
        /* create truncated message */
714
0
        sldns_buffer_write_u16_at(buffer, 4, 0);
715
0
        LDNS_TC_SET(sldns_buffer_begin(buffer));
716
0
        sldns_buffer_flip(buffer);
717
0
        return 1;
718
0
      }
719
0
      return 0;
720
0
    }
721
0
  }
722
  /* roundrobin offset. using query id for random number.  With ntohs
723
   * for different roundrobins for sequential id client senders. */
724
0
  rr_offset = RRSET_ROUNDROBIN?ntohs(id)+(timenow?timenow:time(NULL)):0;
725
726
  /* "prepend" any local alias records in the answer section if this
727
   * response is supposed to be authoritative.  Currently it should
728
   * be a single CNAME record (sanity-checked in worker_handle_request())
729
   * but it can be extended if and when we support more variations of
730
   * aliases. */
731
0
  if(qinfo->local_alias && (flags & BIT_AA)) {
732
0
    struct reply_info arep;
733
0
    time_t timezero = 0; /* to use the 'authoritative' TTL */
734
0
    memset(&arep, 0, sizeof(arep));
735
0
    arep.flags = rep->flags;
736
0
    arep.an_numrrsets = 1;
737
0
    arep.rrset_count = 1;
738
0
    arep.rrsets = &qinfo->local_alias->rrset;
739
0
    if((r=insert_section(&arep, 1, &ancount, buffer, 0,
740
0
      timezero, region, &tree, LDNS_SECTION_ANSWER,
741
0
      qinfo->qtype, dnssec, rr_offset, &compress_count)) != RETVAL_OK) {
742
0
      if(r == RETVAL_TRUNC) {
743
        /* create truncated message */
744
0
        sldns_buffer_write_u16_at(buffer, 6, ancount);
745
0
        LDNS_TC_SET(sldns_buffer_begin(buffer));
746
0
        sldns_buffer_flip(buffer);
747
0
        return 1;
748
0
      }
749
0
      return 0;
750
0
    }
751
0
  }
752
753
  /* insert answer section */
754
0
  if((r=insert_section(rep, rep->an_numrrsets, &ancount, buffer,
755
0
    0, timenow, region, &tree, LDNS_SECTION_ANSWER, qinfo->qtype,
756
0
    dnssec, rr_offset, &compress_count)) != RETVAL_OK) {
757
0
    if(r == RETVAL_TRUNC) {
758
      /* create truncated message */
759
0
      sldns_buffer_write_u16_at(buffer, 6, ancount);
760
0
      LDNS_TC_SET(sldns_buffer_begin(buffer));
761
0
      sldns_buffer_flip(buffer);
762
0
      return 1;
763
0
    }
764
0
    return 0;
765
0
  }
766
0
  sldns_buffer_write_u16_at(buffer, 6, ancount);
767
768
  /* if response is positive answer, auth/add sections are not required */
769
0
  if( ! (minimise && positive_answer(rep, qinfo->qtype)) ) {
770
    /* insert auth section */
771
0
    if((r=insert_section(rep, rep->ns_numrrsets, &nscount, buffer,
772
0
      rep->an_numrrsets, timenow, region, &tree,
773
0
      LDNS_SECTION_AUTHORITY, qinfo->qtype,
774
0
      dnssec, rr_offset, &compress_count)) != RETVAL_OK) {
775
0
      if(r == RETVAL_TRUNC) {
776
        /* create truncated message */
777
0
        sldns_buffer_write_u16_at(buffer, 8, nscount);
778
0
        LDNS_TC_SET(sldns_buffer_begin(buffer));
779
0
        sldns_buffer_flip(buffer);
780
0
        return 1;
781
0
      }
782
0
      return 0;
783
0
    }
784
0
    sldns_buffer_write_u16_at(buffer, 8, nscount);
785
786
0
    if(! (minimise && negative_answer(rep))) {
787
      /* insert add section */
788
0
      if((r=insert_section(rep, rep->ar_numrrsets, &arcount, buffer,
789
0
        rep->an_numrrsets + rep->ns_numrrsets, timenow, region,
790
0
        &tree, LDNS_SECTION_ADDITIONAL, qinfo->qtype,
791
0
        dnssec, rr_offset, &compress_count)) != RETVAL_OK) {
792
0
        if(r == RETVAL_TRUNC) {
793
          /* no need to set TC bit, this is the additional */
794
0
          sldns_buffer_write_u16_at(buffer, 10, arcount);
795
0
          sldns_buffer_flip(buffer);
796
0
          return 1;
797
0
        }
798
0
        return 0;
799
0
      }
800
0
      sldns_buffer_write_u16_at(buffer, 10, arcount);
801
0
    }
802
0
  }
803
0
  sldns_buffer_flip(buffer);
804
0
  return 1;
805
0
}
806
807
uint16_t
808
calc_edns_field_size(struct edns_data* edns)
809
0
{
810
0
  size_t rdatalen = 0;
811
0
  struct edns_option* opt;
812
0
  if(!edns || !edns->edns_present)
813
0
    return 0;
814
0
  for(opt = edns->opt_list_inplace_cb_out; opt; opt = opt->next) {
815
0
    rdatalen += 4 + opt->opt_len;
816
0
  }
817
0
  for(opt = edns->opt_list_out; opt; opt = opt->next) {
818
0
    rdatalen += 4 + opt->opt_len;
819
0
  }
820
  /* domain root '.' + type + class + ttl + rdatalen */
821
0
  return 1 + 2 + 2 + 4 + 2 + rdatalen;
822
0
}
823
824
uint16_t
825
calc_edns_option_size(struct edns_data* edns, uint16_t code)
826
0
{
827
0
  size_t rdatalen = 0;
828
0
  struct edns_option* opt;
829
0
  if(!edns || !edns->edns_present)
830
0
    return 0;
831
0
  for(opt = edns->opt_list_inplace_cb_out; opt; opt = opt->next) {
832
0
    if(opt->opt_code == code)
833
0
      rdatalen += 4 + opt->opt_len;
834
0
  }
835
0
  for(opt = edns->opt_list_out; opt; opt = opt->next) {
836
0
    if(opt->opt_code == code)
837
0
      rdatalen += 4 + opt->opt_len;
838
0
  }
839
0
  return rdatalen;
840
0
}
841
842
uint16_t
843
calc_ede_option_size(struct edns_data* edns, uint16_t* txt_size)
844
0
{
845
0
  size_t rdatalen = 0;
846
0
  struct edns_option* opt;
847
0
  *txt_size = 0;
848
0
  if(!edns || !edns->edns_present)
849
0
    return 0;
850
0
  for(opt = edns->opt_list_inplace_cb_out; opt; opt = opt->next) {
851
0
    if(opt->opt_code == LDNS_EDNS_EDE) {
852
0
      rdatalen += 4 + opt->opt_len;
853
0
      if(opt->opt_len > 2) *txt_size += opt->opt_len - 2;
854
0
      if(opt->opt_len >= 2 && sldns_read_uint16(
855
0
        opt->opt_data) == LDNS_EDE_OTHER) {
856
0
        *txt_size += 4 + 2;
857
0
      }
858
0
    }
859
0
  }
860
0
  for(opt = edns->opt_list_out; opt; opt = opt->next) {
861
0
    if(opt->opt_code == LDNS_EDNS_EDE) {
862
0
      rdatalen += 4 + opt->opt_len;
863
0
      if(opt->opt_len > 2) *txt_size += opt->opt_len - 2;
864
0
      if(opt->opt_len >= 2 && sldns_read_uint16(
865
0
        opt->opt_data) == LDNS_EDE_OTHER) {
866
0
        *txt_size += 4 + 2;
867
0
      }
868
0
    }
869
0
  }
870
0
  return rdatalen;
871
0
}
872
873
/* Trims the EDE OPTION-DATA to not include any EXTRA-TEXT data.
874
 * Also removes any LDNS_EDE_OTHER options from the list since they are useless
875
 * without the extra text. */
876
static void
877
ede_trim_text(struct edns_option** list)
878
0
{
879
0
  struct edns_option* curr, *prev = NULL;
880
0
  if(!list || !(*list)) return;
881
  /* Unlink and repoint if LDNS_EDE_OTHER are first in list */
882
0
  while(list && *list && (*list)->opt_code == LDNS_EDNS_EDE
883
0
    && (*list)->opt_len >= 2
884
0
    && sldns_read_uint16((*list)->opt_data) == LDNS_EDE_OTHER ) {
885
0
    *list = (*list)->next;
886
0
  }
887
0
  if(!list || !(*list)) return;
888
0
  curr = *list;
889
0
  while(curr) {
890
0
    if(curr->opt_code == LDNS_EDNS_EDE) {
891
0
      if(curr->opt_len >= 2 && sldns_read_uint16(
892
0
        curr->opt_data) == LDNS_EDE_OTHER) {
893
        /* LDNS_EDE_OTHER cannot be the first option in
894
         * this while, so prev is always initialized at
895
         * this point from the other branches;
896
         * cut this option off */
897
0
        prev->next = curr->next;
898
0
        curr = curr->next;
899
0
      } else if(curr->opt_len > 2) {
900
        /* trim this option's EXTRA-TEXT */
901
0
        curr->opt_len = 2;
902
0
        prev = curr;
903
0
        curr = curr->next;
904
0
      } else {
905
0
        prev = curr;
906
0
        curr = curr->next;
907
0
      }
908
0
    } else {
909
      /* continue */
910
0
      prev = curr;
911
0
      curr = curr->next;
912
0
    }
913
0
  }
914
0
}
915
916
static void
917
attach_edns_record_max_msg_sz(sldns_buffer* pkt, struct edns_data* edns,
918
  uint16_t max_msg_sz)
919
0
{
920
0
  size_t len;
921
0
  size_t rdatapos;
922
0
  struct edns_option* opt;
923
0
  struct edns_option* padding_option = NULL;
924
  /* inc additional count */
925
0
  sldns_buffer_write_u16_at(pkt, 10,
926
0
    sldns_buffer_read_u16_at(pkt, 10) + 1);
927
0
  len = sldns_buffer_limit(pkt);
928
0
  sldns_buffer_clear(pkt);
929
0
  sldns_buffer_set_position(pkt, len);
930
  /* write EDNS record */
931
0
  sldns_buffer_write_u8(pkt, 0); /* '.' label */
932
0
  sldns_buffer_write_u16(pkt, LDNS_RR_TYPE_OPT); /* type */
933
0
  sldns_buffer_write_u16(pkt, edns->udp_size); /* class */
934
0
  sldns_buffer_write_u8(pkt, edns->ext_rcode); /* ttl */
935
0
  sldns_buffer_write_u8(pkt, edns->edns_version);
936
0
  sldns_buffer_write_u16(pkt, edns->bits);
937
0
  rdatapos = sldns_buffer_position(pkt);
938
0
  sldns_buffer_write_u16(pkt, 0); /* rdatalen */
939
  /* write rdata */
940
0
  for(opt=edns->opt_list_inplace_cb_out; opt; opt=opt->next) {
941
0
    if (opt->opt_code == LDNS_EDNS_PADDING) {
942
0
      padding_option = opt;
943
0
      continue;
944
0
    }
945
0
    sldns_buffer_write_u16(pkt, opt->opt_code);
946
0
    sldns_buffer_write_u16(pkt, opt->opt_len);
947
0
    if(opt->opt_len != 0)
948
0
      sldns_buffer_write(pkt, opt->opt_data, opt->opt_len);
949
0
  }
950
0
  for(opt=edns->opt_list_out; opt; opt=opt->next) {
951
0
    if (opt->opt_code == LDNS_EDNS_PADDING) {
952
0
      padding_option = opt;
953
0
      continue;
954
0
    }
955
0
    sldns_buffer_write_u16(pkt, opt->opt_code);
956
0
    sldns_buffer_write_u16(pkt, opt->opt_len);
957
0
    if(opt->opt_len != 0)
958
0
      sldns_buffer_write(pkt, opt->opt_data, opt->opt_len);
959
0
  }
960
0
  if (padding_option && edns->padding_block_size ) {
961
0
    size_t pad_pos = sldns_buffer_position(pkt);
962
0
    size_t msg_sz = ((pad_pos + 3) / edns->padding_block_size + 1)
963
0
                                   * edns->padding_block_size;
964
0
    size_t pad_sz;
965
    
966
0
    if (msg_sz > max_msg_sz)
967
0
      msg_sz = max_msg_sz;
968
969
    /* By use of calc_edns_field_size, calling functions should
970
     * have made sure that there is enough space for at least a
971
     * zero sized padding option.
972
     */
973
0
    log_assert(pad_pos + 4 <= msg_sz);
974
975
0
    pad_sz = msg_sz - pad_pos - 4;
976
0
    sldns_buffer_write_u16(pkt, LDNS_EDNS_PADDING);
977
0
    sldns_buffer_write_u16(pkt, pad_sz);
978
0
    if (pad_sz) {
979
0
      memset(sldns_buffer_current(pkt), 0, pad_sz);
980
0
      sldns_buffer_skip(pkt, pad_sz);
981
0
    }
982
0
  }
983
0
  sldns_buffer_write_u16_at(pkt, rdatapos, 
984
0
      sldns_buffer_position(pkt)-rdatapos-2);
985
0
  sldns_buffer_flip(pkt);
986
0
}
987
988
void
989
attach_edns_record(sldns_buffer* pkt, struct edns_data* edns)
990
0
{
991
0
  if(!edns || !edns->edns_present)
992
0
    return;
993
0
  attach_edns_record_max_msg_sz(pkt, edns, edns->udp_size);
994
0
}
995
996
int 
997
reply_info_answer_encode(struct query_info* qinf, struct reply_info* rep, 
998
  uint16_t id, uint16_t qflags, sldns_buffer* pkt, time_t timenow,
999
  int cached, struct regional* region, uint16_t udpsize, 
1000
  struct edns_data* edns, int dnssec, int secure)
1001
0
{
1002
0
  uint16_t flags;
1003
0
  unsigned int attach_edns = 0;
1004
0
  uint16_t edns_field_size, ede_size, ede_txt_size;
1005
1006
0
  if(!cached || rep->authoritative) {
1007
    /* original flags, copy RD and CD bits from query. */
1008
0
    flags = rep->flags | (qflags & (BIT_RD|BIT_CD)); 
1009
0
  } else {
1010
    /* remove AA bit, copy RD and CD bits from query. */
1011
0
    flags = (rep->flags & ~BIT_AA) | (qflags & (BIT_RD|BIT_CD)); 
1012
0
  }
1013
0
  if(secure && (dnssec || (qflags&BIT_AD)))
1014
0
    flags |= BIT_AD;
1015
  /* restore AA bit if we have a local alias and the response can be
1016
   * authoritative.  Also clear AD bit if set as the local data is the
1017
   * primary answer. */
1018
0
  if(qinf->local_alias &&
1019
0
    (FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NOERROR ||
1020
0
    FLAGS_GET_RCODE(rep->flags) == LDNS_RCODE_NXDOMAIN)) {
1021
0
    flags |= BIT_AA;
1022
0
    flags &= ~BIT_AD;
1023
0
  }
1024
0
  log_assert((flags & BIT_QR)); /* QR bit must be on in our replies */
1025
0
  if(udpsize < LDNS_HEADER_SIZE)
1026
0
    return 0;
1027
  /* currently edns does not change during calculations;
1028
   * calculate sizes once here */
1029
0
  edns_field_size = calc_edns_field_size(edns);
1030
0
  ede_size = calc_ede_option_size(edns, &ede_txt_size);
1031
0
  if(sldns_buffer_capacity(pkt) < udpsize)
1032
0
    udpsize = sldns_buffer_capacity(pkt);
1033
0
  if(!edns || !edns->edns_present) {
1034
0
    attach_edns = 0;
1035
  /* EDEs are optional, try to fit anything else before them */
1036
0
  } else if(udpsize < LDNS_HEADER_SIZE + edns_field_size - ede_size) {
1037
    /* packet too small to contain edns, omit it. */
1038
0
    attach_edns = 0;
1039
0
  } else {
1040
    /* reserve space for edns record */
1041
0
    attach_edns = (unsigned int)edns_field_size - ede_size;
1042
0
  }
1043
1044
0
  if(!reply_info_encode(qinf, rep, id, flags, pkt, timenow, region,
1045
0
    udpsize - attach_edns, dnssec, MINIMAL_RESPONSES)) {
1046
0
    log_err("reply encode: out of memory");
1047
0
    return 0;
1048
0
  }
1049
0
  if(attach_edns) {
1050
0
    if(udpsize >= sldns_buffer_limit(pkt) + edns_field_size)
1051
0
      attach_edns_record_max_msg_sz(pkt, edns, udpsize);
1052
0
    else if(udpsize >= sldns_buffer_limit(pkt) + edns_field_size - ede_txt_size) {
1053
0
      ede_trim_text(&edns->opt_list_inplace_cb_out);
1054
0
      ede_trim_text(&edns->opt_list_out);
1055
0
      attach_edns_record_max_msg_sz(pkt, edns, udpsize);
1056
0
    } else if(udpsize >= sldns_buffer_limit(pkt) + edns_field_size - ede_size) {
1057
0
      edns_opt_list_remove(&edns->opt_list_inplace_cb_out, LDNS_EDNS_EDE);
1058
0
      edns_opt_list_remove(&edns->opt_list_out, LDNS_EDNS_EDE);
1059
0
      attach_edns_record_max_msg_sz(pkt, edns, udpsize);
1060
0
    }
1061
0
  }
1062
0
  return 1;
1063
0
}
1064
1065
void 
1066
qinfo_query_encode(sldns_buffer* pkt, struct query_info* qinfo)
1067
0
{
1068
0
  uint16_t flags = 0; /* QUERY, NOERROR */
1069
0
  const uint8_t* qname = qinfo->local_alias ?
1070
0
    qinfo->local_alias->rrset->rk.dname : qinfo->qname;
1071
0
  size_t qname_len = qinfo->local_alias ?
1072
0
    qinfo->local_alias->rrset->rk.dname_len : qinfo->qname_len;
1073
0
  sldns_buffer_clear(pkt);
1074
0
  log_assert(sldns_buffer_remaining(pkt) >= 12+255+4/*max query*/);
1075
0
  sldns_buffer_skip(pkt, 2); /* id done later */
1076
0
  sldns_buffer_write_u16(pkt, flags);
1077
0
  sldns_buffer_write_u16(pkt, 1); /* query count */
1078
0
  sldns_buffer_write(pkt, "\000\000\000\000\000\000", 6); /* counts */
1079
0
  sldns_buffer_write(pkt, qname, qname_len);
1080
0
  sldns_buffer_write_u16(pkt, qinfo->qtype);
1081
0
  sldns_buffer_write_u16(pkt, qinfo->qclass);
1082
0
  sldns_buffer_flip(pkt);
1083
0
}
1084
1085
void
1086
extended_error_encode(sldns_buffer* buf, uint16_t rcode,
1087
  struct query_info* qinfo, uint16_t qid, uint16_t qflags,
1088
  uint16_t xflags, struct edns_data* edns)
1089
0
{
1090
0
  uint16_t flags;
1091
1092
0
  sldns_buffer_clear(buf);
1093
0
  sldns_buffer_write(buf, &qid, sizeof(uint16_t));
1094
0
  flags = (uint16_t)(BIT_QR | BIT_RA | (rcode & 0xF)); /* QR and retcode*/
1095
0
  flags |= xflags;
1096
0
  flags |= (qflags & (BIT_RD|BIT_CD)); /* copy RD and CD bit */
1097
0
  sldns_buffer_write_u16(buf, flags);
1098
0
  if(qinfo) flags = 1;
1099
0
  else  flags = 0;
1100
0
  sldns_buffer_write_u16(buf, flags);
1101
0
  flags = 0;
1102
0
  sldns_buffer_write(buf, &flags, sizeof(uint16_t));
1103
0
  sldns_buffer_write(buf, &flags, sizeof(uint16_t));
1104
0
  sldns_buffer_write(buf, &flags, sizeof(uint16_t));
1105
0
  if(qinfo) {
1106
0
    const uint8_t* qname = qinfo->local_alias ?
1107
0
      qinfo->local_alias->rrset->rk.dname : qinfo->qname;
1108
0
    size_t qname_len = qinfo->local_alias ?
1109
0
      qinfo->local_alias->rrset->rk.dname_len :
1110
0
      qinfo->qname_len;
1111
0
    if(sldns_buffer_current(buf) == qname)
1112
0
      sldns_buffer_skip(buf, (ssize_t)qname_len);
1113
0
    else  sldns_buffer_write(buf, qname, qname_len);
1114
0
    sldns_buffer_write_u16(buf, qinfo->qtype);
1115
0
    sldns_buffer_write_u16(buf, qinfo->qclass);
1116
0
  }
1117
0
  sldns_buffer_flip(buf);
1118
0
  if(edns) {
1119
0
    struct edns_data es = *edns;
1120
0
    es.edns_version = EDNS_ADVERTISED_VERSION;
1121
0
    es.udp_size = EDNS_ADVERTISED_SIZE;
1122
0
    es.ext_rcode = (uint8_t)(rcode >> 4);
1123
0
    es.bits &= EDNS_DO;
1124
0
    if(sldns_buffer_limit(buf) + calc_edns_field_size(&es) >
1125
0
      edns->udp_size) {
1126
0
      edns_opt_list_remove(&es.opt_list_inplace_cb_out, LDNS_EDNS_EDE);
1127
0
      edns_opt_list_remove(&es.opt_list_out, LDNS_EDNS_EDE);
1128
0
      if(sldns_buffer_limit(buf) + calc_edns_field_size(&es) >
1129
0
        edns->udp_size) {
1130
0
        return;
1131
0
      }
1132
0
    }
1133
0
    attach_edns_record(buf, &es);
1134
0
  }
1135
0
}
1136
1137
void
1138
error_encode(sldns_buffer* buf, int r, struct query_info* qinfo,
1139
  uint16_t qid, uint16_t qflags, struct edns_data* edns)
1140
0
{
1141
0
  extended_error_encode(buf, (r & 0x000F), qinfo, qid, qflags,
1142
0
    (r & 0xFFF0), edns);
1143
0
}