Coverage Report

Created: 2026-11-20 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/pdns/pdns/dnsdistdist/dnsparser.hh
Line
Count
Source
1
/*
2
 * This file is part of PowerDNS or dnsdist.
3
 * Copyright -- PowerDNS.COM B.V. and its contributors
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of version 2 of the GNU General Public License as
7
 * published by the Free Software Foundation.
8
 *
9
 * In addition, for the avoidance of any doubt, permission is granted to
10
 * link this program with OpenSSL and to (re)distribute the binaries
11
 * produced as the result of such linking.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
 */
22
#pragma once
23
#include <atomic>
24
#include <map>
25
#include <sstream>
26
#include <stdexcept>
27
#include <iostream>
28
#include <unordered_set>
29
#include <utility>
30
#include <vector>
31
#include <cerrno>
32
// #include <netinet/in.h>
33
#include "misc.hh"
34
35
#include "dns.hh"
36
#include "dnswriter.hh"
37
#include "dnsname.hh"
38
#include "noinitvector.hh"
39
#include "pdnsexception.hh"
40
#include "iputils.hh"
41
#include "svc-records.hh"
42
43
/** DNS records have three representations:
44
    1) in the packet
45
    2) parsed in a class, ready for use
46
    3) in the zone
47
48
    We should implement bidirectional transitions between 1&2 and 2&3.
49
    Currently we have: 1 -> 2
50
                       2 -> 3
51
52
    We can add:        2 -> 1  easily by reversing the packetwriter
53
    And we might be able to reverse 2 -> 3 as well
54
*/
55
56
#include "namespaces.hh"
57
58
class MOADNSException : public runtime_error
59
{
60
public:
61
14.3k
  MOADNSException(const string& str) : runtime_error(str)
62
14.3k
  {}
63
};
64
65
66
class MOADNSParser;
67
68
class PacketReader
69
{
70
public:
71
  PacketReader(const std::string_view& content, uint16_t initialPos=sizeof(dnsheader), bool internalRepresentation = false, bool standalone = false)
72
43.8k
    : d_pos(initialPos), d_startrecordpos(initialPos), d_internal(internalRepresentation), d_standalone(standalone), d_content(content)
73
43.8k
  {
74
43.8k
    if (content.size() > std::numeric_limits<uint16_t>::max()) {
75
101
      throw std::out_of_range("packet too large");
76
101
    }
77
78
43.7k
    d_recordlen = static_cast<uint16_t>(content.size());
79
43.7k
    d_pointerBudget = static_cast<size_t>(d_recordlen) * s_MaxPointersPerByte;
80
43.7k
  }
81
82
  // Default is s_MaxPointersPerByte * packet size
83
  void setPointerBudget(size_t maxPointers)
84
0
  {
85
0
    d_pointerBudget = maxPointers;
86
0
  }
87
88
  uint32_t get32BitInt();
89
  uint16_t get16BitInt();
90
  uint8_t get8BitInt();
91
92
  void xfrNodeOrLocatorID(NodeOrLocatorID& val);
93
  void xfr48BitInt(uint64_t& val);
94
95
  void xfr32BitInt(uint32_t& val)
96
86.6k
  {
97
86.6k
    val=get32BitInt();
98
86.6k
  }
99
100
  void xfrIP(uint32_t& val)
101
  {
102
    xfr32BitInt(val);
103
    val=htonl(val);
104
  }
105
106
  void xfrIP6(std::string &val) {
107
    xfrBlob(val, 16);
108
  }
109
110
346k
  void xfrCAWithoutPort(uint8_t version, ComboAddress &val) {
111
346k
    string blob;
112
346k
    if (version == 4) xfrBlob(blob, 4);
113
85.7k
    else if (version == 6) xfrBlob(blob, 16);
114
0
    else throw runtime_error("invalid IP protocol");
115
346k
    val = makeComboAddressFromRaw(version, blob);
116
346k
  }
117
118
0
  void xfrCAPort(ComboAddress &val) {
119
0
    uint16_t port;
120
0
    xfr16BitInt(port);
121
0
    val.sin4.sin_port = port;
122
0
  }
123
124
  void xfrTime(uint32_t& val)
125
  {
126
    xfr32BitInt(val);
127
  }
128
129
130
  void xfr16BitInt(uint16_t& val)
131
1.26M
  {
132
1.26M
    val=get16BitInt();
133
1.26M
  }
134
135
  void xfrType(uint16_t& val)
136
138k
  {
137
138k
    xfr16BitInt(val);
138
138k
  }
139
140
141
  void xfr8BitInt(uint8_t& val)
142
603k
  {
143
603k
    val=get8BitInt();
144
603k
  }
145
146
  void xfrName(DNSName& name, bool /* compress */ = false)
147
113k
  {
148
113k
    name = getName();
149
113k
  }
150
151
  void xfrText(string &text, bool multi=false, bool lenField=true)
152
  {
153
    text=getText(multi, lenField);
154
  }
155
156
  void xfrUnquotedText(string &text, bool lenField){
157
    text=getUnquotedText(lenField);
158
  }
159
160
  void xfrBlob(string& blob);
161
  void xfrBlobNoSpaces(string& blob, int len);
162
  void xfrBlob(string& blob, int length);
163
  void xfrHexBlob(string& blob, bool keepReading=false);
164
  void xfrSvcParamKeyVals(set<SvcParam> &kvs);
165
166
  void getDnsrecordheader(struct dnsrecordheader &ah);
167
  void copyRecord(vector<unsigned char>& dest, uint16_t len);
168
  void copyRecord(unsigned char* dest, uint16_t len);
169
170
  DNSName getName();
171
  string getText(bool multi, bool lenField);
172
  string getUnquotedText(bool lenField);
173
174
  /* Whether the current position is at (or after, which would indicate a problem
175
     and should have been detected earlier) the end of wire data corresponding to
176
     the current DNS record */
177
  [[nodiscard]] bool eof() const
178
  {
179
    const auto endOfRecordContent = d_startrecordpos + d_recordlen;
180
    if (d_pos > endOfRecordContent) {
181
      throw std::out_of_range("Looking for EOF in PacketReader but we are already beyond the record content's end (" + std::to_string(d_pos) + " while the record content starts at " + std::to_string(d_startrecordpos) + " with a size of " + std::to_string(d_recordlen) + ")");
182
    }
183
    return d_pos == endOfRecordContent;
184
  }
185
186
  /* Returns a string, formatted for human/log consumption, containing information
187
     about the wire data from the current position to the end of the current DNS record */
188
  [[nodiscard]] std::string getRemaining() const {
189
    return "Remaining data from PacketReader, current position " + std::to_string(d_pos) + " in packet of size " + std::to_string(d_content.size()) + ", end of record expected at " + std::to_string(d_startrecordpos + d_recordlen) + ": " + makeHexDump(std::string(d_content.begin() + d_pos, d_content.begin() + d_startrecordpos + d_recordlen));
190
  };
191
192
#if defined(PDNS_AUTH) // [
193
  /* This method moves the position to the end of the current DNS record.
194
     The only case where it makes sense to call this method is when processing ENT
195
     records, and only because of a bug in the authoritative server used to insert
196
     non-empty content for some ENT records (see https://github.com/PowerDNS/pdns/pull/17000)
197
  */
198
  void consumeRemaining()
199
  {
200
    d_pos = (d_startrecordpos + d_recordlen);
201
  }
202
#endif // ]
203
204
  [[nodiscard]] uint16_t getPosition() const
205
697k
  {
206
697k
    return d_pos;
207
697k
  }
208
209
  void skip(uint16_t n)
210
137k
  {
211
137k
    size_t stop = d_pos;
212
137k
    stop += n;
213
137k
    if (!isWithinRecordBoundaries(d_pos, d_pos + n)) {
214
1.04k
      throw std::out_of_range("Attempt to skip bytes (" + std::to_string(n) + " starting at " + std::to_string(d_pos) + ") farther than the record's end (" + std::to_string(d_startrecordpos + d_recordlen) + ")");
215
1.04k
    }
216
136k
    if (stop > d_content.size()) {
217
115
      throw std::out_of_range("Attempt to skip bytes (" + std::to_string(n) + " starting at " + std::to_string(d_pos) + ") farther than the packet's end (" + std::to_string(d_content.size()) + ")");
218
115
    }
219
220
136k
    d_pos += n;
221
136k
  }
222
223
  static size_t s_MaxPointersPerByte;
224
225
private:
226
  [[nodiscard]] bool isWithinRecordBoundaries(size_t initialPosition, size_t endPosition, bool canBeOutsideRecordContent = false) const
227
3.89M
  {
228
3.89M
    if (initialPosition > endPosition) {
229
0
      return false;
230
0
    }
231
3.89M
    if (canBeOutsideRecordContent && d_recordlen == 0) {
232
      // we don't know the record's length, nothing to check
233
183k
      return true;
234
183k
    }
235
3.71M
    const size_t endOfRecordContent = d_startrecordpos + d_recordlen;
236
3.71M
    if (canBeOutsideRecordContent && initialPosition >= endOfRecordContent) {
237
      // our initial position is after the last known record content,
238
      // we are probably parsing the owner name of the next record,
239
      // nothing to check
240
243k
      return true;
241
243k
    }
242
    // are we still inside the record's content?
243
3.47M
    return initialPosition >= d_startrecordpos && initialPosition <= endOfRecordContent && endPosition <= endOfRecordContent;
244
3.71M
  }
245
246
  size_t d_pointerBudget{0};
247
  uint16_t d_pos;
248
  uint16_t d_startrecordpos; // needed for getBlob later on
249
  uint16_t d_recordlen; // ditto
250
  bool d_internal;
251
  bool d_standalone; // no dnsheader at the beginning of content
252
  const std::string_view d_content;
253
};
254
255
struct DNSRecord;
256
257
class DNSRecordContent
258
{
259
public:
260
  static std::shared_ptr<DNSRecordContent> make(const DNSRecord& dr, PacketReader& pr);
261
  static std::shared_ptr<DNSRecordContent> make(const DNSRecord& dr, PacketReader& pr, uint16_t opcode);
262
  static std::shared_ptr<DNSRecordContent> make(uint16_t qtype, uint16_t qclass, const string& zone);
263
  static string upgradeContent(const DNSName& qname, const QType& qtype, const string& content);
264
265
  virtual std::string getZoneRepresentation(bool noDot=false) const = 0;
266
224k
  virtual ~DNSRecordContent() = default;
267
  virtual void toPacket(DNSPacketWriter& pw) const = 0;
268
  // returns the wire format of the content or the full record, possibly including compressed pointers pointing to the owner name (unless canonic or lowerCase are set)
269
  [[nodiscard]] string serialize(const DNSName& qname, bool canonic = false, bool lowerCase = false, bool full = false) const
270
4.04k
  {
271
4.04k
    vector<uint8_t> packet;
272
4.04k
    DNSPacketWriter packetWriter(packet, g_rootdnsname, QType::A);
273
274
4.04k
    if (canonic) {
275
4.04k
      packetWriter.setCanonic(true);
276
4.04k
    }
277
4.04k
    if (lowerCase) {
278
0
      packetWriter.setLowercase(true);
279
0
    }
280
281
4.04k
    packetWriter.startRecord(qname, getType());
282
4.04k
    toPacket(packetWriter);
283
284
4.04k
    string record;
285
4.04k
    if (full) {
286
0
      packetWriter.getWireFormatContent(record); // needs to be called before commit()
287
4.04k
    } else {
288
4.04k
      packetWriter.getRecordPayload(record); // needs to be called before commit()
289
4.04k
    }
290
4.04k
    return record;
291
4.04k
  }
292
293
  virtual bool operator==(const DNSRecordContent& rhs) const
294
0
  {
295
0
    return typeid(*this)==typeid(rhs) && this->getZoneRepresentation() == rhs.getZoneRepresentation();
296
0
  }
297
298
  // parse the content in wire format, possibly including compressed pointers pointing to the owner name.
299
  // internalRepresentation is set when the data comes from an internal source,
300
  // such as the LMDB backend.
301
  static shared_ptr<DNSRecordContent> deserialize(const DNSName& qname, uint16_t qtype, const string& serialized, uint16_t qclass=QClass::IN, bool internalRepresentation = false);
302
303
  void doRecordCheck(const struct DNSRecord&){}
304
305
  typedef std::shared_ptr<DNSRecordContent> makerfunc_t(const struct DNSRecord& dr, PacketReader& pr);
306
  typedef std::shared_ptr<DNSRecordContent> zmakerfunc_t(const string& str);
307
308
  static void regist(uint16_t cl, uint16_t ty, makerfunc_t* f, zmakerfunc_t* z, const char* name)
309
  {
310
    assert(!d_locked.load()); // NOLINT: it's the API
311
    if(f)
312
      getTypemap()[pair(cl,ty)]=f;
313
    if(z)
314
      getZmakermap()[pair(cl,ty)]=z;
315
316
    getT2Namemap().emplace(pair(cl, ty), name);
317
    getN2Typemap().emplace(name, pair(cl, ty));
318
  }
319
320
  static bool isUnknownType(const string& name)
321
  {
322
    return boost::starts_with(name, "TYPE") || boost::starts_with(name, "type");
323
  }
324
325
  static uint16_t TypeToNumber(const string& name)
326
  {
327
    n2typemap_t::const_iterator iter = getN2Typemap().find(toUpper(name));
328
    if(iter != getN2Typemap().end())
329
      return iter->second.second;
330
331
    if (isUnknownType(name)) {
332
      return pdns::checked_stoi<uint16_t>(name.substr(4));
333
    }
334
335
    throw runtime_error("Unknown DNS type '"+name+"'");
336
  }
337
338
  static const string NumberToType(uint16_t num, uint16_t classnum = QClass::IN)
339
  {
340
    auto iter = getT2Namemap().find(pair(classnum, num));
341
    if(iter == getT2Namemap().end())
342
      return "TYPE" + std::to_string(num);
343
      //      throw runtime_error("Unknown DNS type with numerical id "+std::to_string(num));
344
    return iter->second;
345
  }
346
347
  /**
348
   * \brief Return whether we have implemented a content representation for this type
349
   */
350
  static bool isRegisteredType(uint16_t rtype, uint16_t rclass = QClass::IN);
351
352
  virtual uint16_t getType() const = 0;
353
354
  static void lock()
355
  {
356
    d_locked.store(true);
357
  }
358
359
  [[nodiscard]] virtual size_t sizeEstimate() const = 0;
360
361
protected:
362
  typedef std::map<std::pair<uint16_t, uint16_t>, makerfunc_t* > typemap_t;
363
  typedef std::map<std::pair<uint16_t, uint16_t>, zmakerfunc_t* > zmakermap_t;
364
  typedef std::map<std::pair<uint16_t, uint16_t>, string > t2namemap_t;
365
  typedef std::map<string, std::pair<uint16_t, uint16_t> > n2typemap_t;
366
  static typemap_t& getTypemap();
367
  static t2namemap_t& getT2Namemap();
368
  static n2typemap_t& getN2Typemap();
369
  static zmakermap_t& getZmakermap();
370
  static std::atomic<bool> d_locked;
371
};
372
373
struct DNSRecord
374
{
375
  DNSRecord() :
376
221k
    d_class(QClass::IN)
377
221k
  {}
378
  explicit DNSRecord(const DNSResourceRecord& rr);
379
  DNSRecord(const std::string& name,
380
            std::shared_ptr<DNSRecordContent> content,
381
            const uint16_t type,
382
            const uint16_t qclass = QClass::IN,
383
            const uint32_t ttl = 86400,
384
            const uint16_t clen = 0,
385
            const DNSResourceRecord::Place place = DNSResourceRecord::ANSWER) :
386
    d_name(DNSName(name)),
387
    d_content(std::move(content)),
388
    d_type(type),
389
    d_class(qclass),
390
    d_ttl(ttl),
391
    d_clen(clen),
392
0
    d_place(place) {}
393
394
  DNSName d_name;
395
private:
396
  std::shared_ptr<const DNSRecordContent> d_content;
397
public:
398
  uint16_t d_type{};
399
  uint16_t d_class{};
400
  uint32_t d_ttl{};
401
  uint16_t d_clen{};
402
  DNSResourceRecord::Place d_place{DNSResourceRecord::ANSWER};
403
404
  [[nodiscard]] std::string print(const std::string& indent = "") const
405
0
  {
406
0
    std::stringstream s;
407
0
    s << indent << "Content = " << d_content->getZoneRepresentation() << std::endl;
408
0
    s << indent << "Type = " << d_type << std::endl;
409
0
    s << indent << "Class = " << d_class << std::endl;
410
0
    s << indent << "TTL = " << d_ttl << std::endl;
411
0
    s << indent << "clen = " << d_clen << std::endl;
412
0
    s << indent << "Place = " << std::to_string(d_place) << std::endl;
413
0
    return s.str();
414
0
  }
415
416
  [[nodiscard]] std::string toString() const
417
0
  {
418
0
    std::string ret(d_name.toLogString());
419
0
    ret += '|';
420
0
    ret += QType(d_type).toString();
421
0
    ret += '|';
422
0
    ret += getContent()->getZoneRepresentation();
423
0
    return ret;
424
0
  }
425
426
  void setContent(const std::shared_ptr<const DNSRecordContent>& content)
427
0
  {
428
0
    d_content = content;
429
0
  }
430
431
  void setContent(std::shared_ptr<const DNSRecordContent>&& content)
432
197k
  {
433
197k
    d_content = std::move(content);
434
197k
  }
435
436
  [[nodiscard]] const std::shared_ptr<const DNSRecordContent>& getContent() const
437
0
  {
438
0
    return d_content;
439
0
  }
440
441
  bool operator<(const DNSRecord& rhs) const
442
0
  {
443
0
    if(std::tie(d_name, d_type, d_class, d_ttl) < std::tie(rhs.d_name, rhs.d_type, rhs.d_class, rhs.d_ttl))
444
0
      return true;
445
0
446
0
    if(std::tie(d_name, d_type, d_class, d_ttl) != std::tie(rhs.d_name, rhs.d_type, rhs.d_class, rhs.d_ttl))
447
0
      return false;
448
0
449
0
    string lzrp, rzrp;
450
0
    if(d_content)
451
0
      lzrp=toLower(d_content->getZoneRepresentation());
452
0
    if(rhs.d_content)
453
0
      rzrp=toLower(rhs.d_content->getZoneRepresentation());
454
0
455
0
    return lzrp < rzrp;
456
0
  }
457
458
  // this orders in canonical order and keeps the SOA record on top
459
  static bool prettyCompare(const DNSRecord& a, const DNSRecord& b)
460
0
  {
461
0
    auto aType = (a.d_type == QType::SOA) ? 0 : a.d_type;
462
0
    auto bType = (b.d_type == QType::SOA) ? 0 : b.d_type;
463
0
464
0
    int res = a.d_name.canonCompare_three_way(b.d_name, true);
465
0
    if (res < 0) {
466
0
      return true;
467
0
    }
468
0
    if (res > 0) {
469
0
      return false;
470
0
    }
471
0
472
0
    if(std::tie(aType, a.d_class, a.d_ttl) < std::tie(bType, b.d_class, b.d_ttl))
473
0
      return true;
474
0
475
0
    if(std::tie(aType, a.d_class, a.d_ttl) != std::tie(bType, b.d_class, b.d_ttl))
476
0
      return false;
477
0
478
0
    string lzrp, rzrp;
479
0
    if(a.d_content)
480
0
      lzrp = a.d_content->getZoneRepresentation();
481
0
    if(b.d_content)
482
0
      rzrp = b.d_content->getZoneRepresentation();
483
0
484
0
    switch (a.d_type) {
485
0
    case QType::TXT:
486
0
    case QType::SPF:
487
0
#if !defined(RECURSOR)
488
0
    case QType::LUA:
489
0
#endif
490
0
      return lzrp < rzrp;
491
0
    default:
492
0
      return toLower(lzrp) < toLower(rzrp);
493
0
    }
494
0
  }
495
496
  bool operator==(const DNSRecord& rhs) const
497
0
  {
498
0
    if (d_type != rhs.d_type || d_class != rhs.d_class || d_name != rhs.d_name) {
499
0
      return false;
500
0
    }
501
0
502
0
    return *d_content == *rhs.d_content;
503
0
  }
504
505
  [[nodiscard]] size_t sizeEstimate() const
506
0
  {
507
0
    return sizeof(*this) + d_name.sizeEstimate() + (d_content ? d_content->sizeEstimate() : 0U);
508
0
  }
509
};
510
511
struct DNSZoneRecord
512
{
513
  domainid_t domain_id{UnknownDomainID};
514
  uint8_t scopeMask{0};
515
  int signttl{0};
516
  DNSName wildcardname;
517
  bool auth{true};
518
  bool disabled{false};
519
  DNSRecord dr;
520
521
0
  bool operator<(const DNSZoneRecord& other) const {
522
0
    return dr.d_ttl < other.dr.d_ttl;
523
0
  }
524
};
525
526
class UnknownRecordContent : public DNSRecordContent
527
{
528
public:
529
  UnknownRecordContent(const DNSRecord& dr, PacketReader& pr)
530
131k
    : d_dr(dr)
531
131k
  {
532
131k
    pr.copyRecord(d_record, dr.d_clen);
533
131k
  }
534
535
  UnknownRecordContent(const string& zone);
536
537
  string getZoneRepresentation(bool noDot) const override;
538
  void toPacket(DNSPacketWriter& pw) const override;
539
  uint16_t getType() const override
540
31
  {
541
31
    return d_dr.d_type;
542
31
  }
543
544
  const vector<uint8_t>& getRawContent() const
545
242
  {
546
242
    return d_record;
547
242
  }
548
549
  [[nodiscard]] size_t sizeEstimate() const override
550
0
  {
551
0
    return sizeof(*this) + d_dr.sizeEstimate() + d_record.size();
552
0
  }
553
554
private:
555
  DNSRecord d_dr;
556
  vector<uint8_t> d_record;
557
};
558
559
//! This class can be used to parse incoming packets, and is copyable
560
class MOADNSParser : public boost::noncopyable
561
{
562
public:
563
  //! Parse from a string
564
  MOADNSParser(bool query, const string& buffer): d_tsigPos(0)
565
0
  {
566
0
    init(query, buffer);
567
0
  }
568
569
  //! Parse from a pointer and length
570
13.3k
  MOADNSParser(bool query, const char *packet, unsigned int len, size_t pointerBudget = 0) : d_tsigPos(0)
571
13.3k
  {
572
13.3k
    init(query, std::string_view(packet, len), pointerBudget);
573
13.3k
  }
574
575
  DNSName d_qname;
576
  uint16_t d_qclass, d_qtype;
577
  dnsheader d_header;
578
579
  using answers_t = vector<DNSRecord>;
580
581
  //! All answers contained in this packet (everything *but* the question section)
582
  answers_t d_answers;
583
584
  uint16_t getTSIGPos() const
585
0
  {
586
0
    return d_tsigPos;
587
0
  }
588
589
  bool hasEDNS() const;
590
591
private:
592
  void init(bool query, const std::string_view& packet, size_t pointerBudget = 0);
593
  uint16_t d_tsigPos;
594
};
595
596
string simpleCompress(const string& label, const string& root="");
597
void shuffleDNSPacket(char* packet, size_t length, const dnsheader_aligned& aligned_dh);
598
void ageDNSPacket(char* packet, size_t length, uint32_t seconds, const dnsheader_aligned&);
599
void ageDNSPacket(std::string& packet, uint32_t seconds, const dnsheader_aligned&);
600
void editDNSPacketTTL(char* packet, size_t length, const std::function<uint32_t(uint8_t, uint16_t, uint16_t, uint32_t)>& visitor);
601
void clearDNSPacketRecordTypes(vector<uint8_t>& packet, const std::unordered_set<QType>& qtypes);
602
void clearDNSPacketRecordTypes(PacketBuffer& packet, const std::unordered_set<QType>& qtypes);
603
void clearDNSPacketRecordTypes(char* packet, size_t& length, const std::unordered_set<QType>& qtypes);
604
uint32_t getDNSPacketMinTTL(const char* packet, size_t length, bool* seenAuthSOA=nullptr);
605
uint32_t getDNSPacketLength(const char* packet, size_t length);
606
uint16_t getRecordsOfTypeCount(const char* packet, size_t length, uint8_t section, uint16_t type);
607
bool getEDNSUDPPayloadSizeAndZ(const char* packet, size_t length, uint16_t* payloadSize, uint16_t* z);
608
/* call the visitor for every records in the answer, authority and additional sections, passing the section, class, type, ttl, rdatalength and rdata
609
   to the visitor. Stops whenever the visitor returns false or at the end of the packet */
610
bool visitDNSPacket(const std::string_view& packet, const std::function<bool(uint8_t, uint16_t, uint16_t, uint32_t, uint16_t, const char*)>& visitor);
611
612
template<typename T>
613
std::shared_ptr<const T> getRR(const DNSRecord& dr)
614
0
{
615
0
  return std::dynamic_pointer_cast<const T>(dr.getContent());
616
0
}
617
618
/** Simple DNSPacketMangler. Ritual is: get a pointer into the packet and moveOffset() to beyond your needs
619
 *  If you survive that, feel free to read from the pointer */
620
class DNSPacketMangler
621
{
622
public:
623
  explicit DNSPacketMangler(std::string& packet)
624
    : d_packet(packet.data()), d_length(packet.length()), d_notyouroffset(12), d_offset(d_notyouroffset)
625
0
  {}
626
  DNSPacketMangler(char* packet, size_t length)
627
5.65k
    : d_packet(packet), d_length(length), d_notyouroffset(12), d_offset(d_notyouroffset)
628
5.65k
  {}
629
630
  /*! Advances past a wire-format domain name
631
   * The name is not checked for adherence to length restrictions.
632
   * Compression pointers are not followed.
633
   */
634
  bool skipDomainName()
635
268k
  {
636
268k
    uint8_t len{};
637
268k
    bool isRoot = true;
638
370k
    while ((len = get8BitInt()) != 0) {
639
134k
      isRoot = false;
640
134k
      if (len >= 0xc0) { // extended label
641
31.6k
        get8BitInt();
642
31.6k
        return false;
643
31.6k
      }
644
102k
      skipBytes(len);
645
102k
    }
646
236k
    return isRoot;
647
268k
  }
648
649
  void skipBytes(uint16_t bytes)
650
252k
  {
651
252k
    moveOffset(bytes);
652
252k
  }
653
  void rewindBytes(uint16_t by)
654
109k
  {
655
109k
    rewindOffset(by);
656
109k
  }
657
  uint32_t get32BitInt()
658
117k
  {
659
117k
    const char* p = d_packet + d_offset;
660
117k
    moveOffset(4);
661
117k
    uint32_t ret;
662
117k
    memcpy(&ret, p, sizeof(ret));
663
117k
    return ntohl(ret);
664
117k
  }
665
  uint16_t get16BitInt()
666
351k
  {
667
351k
    const char* p = d_packet + d_offset;
668
351k
    moveOffset(2);
669
351k
    uint16_t ret;
670
351k
    memcpy(&ret, p, sizeof(ret));
671
351k
    return ntohs(ret);
672
351k
  }
673
674
  uint8_t get8BitInt()
675
401k
  {
676
401k
    const char* p = d_packet + d_offset;
677
401k
    moveOffset(1);
678
401k
    return *p;
679
401k
  }
680
681
  void skipRData()
682
117k
  {
683
117k
    auto toskip = get16BitInt();
684
117k
    moveOffset(toskip);
685
117k
  }
686
687
  std::pair<uint32_t, uint32_t> skipRDataAndReturnOffsets()
688
0
  {
689
0
    auto toskip = get16BitInt();
690
0
    uint32_t start = d_offset;
691
0
    moveOffset(toskip);
692
0
    uint32_t end = d_offset;
693
0
    return std::pair<uint32_t,uint32_t>(start, end);
694
0
  }
695
696
  void decreaseAndSkip32BitInt(uint32_t decrease)
697
0
  {
698
0
    const char *p = d_packet + d_offset;
699
0
    moveOffset(4);
700
701
0
    uint32_t tmp;
702
0
    memcpy(&tmp, p, sizeof(tmp));
703
0
    tmp = ntohl(tmp);
704
0
    if (tmp > decrease) {
705
0
      tmp -= decrease;
706
0
    } else {
707
0
      tmp = 0;
708
0
    }
709
0
    tmp = htonl(tmp);
710
0
    memcpy(d_packet + d_offset-4, (const char*)&tmp, sizeof(tmp));
711
0
  }
712
713
  void setAndSkip32BitInt(uint32_t value)
714
109k
  {
715
109k
    moveOffset(4);
716
717
109k
    value = htonl(value);
718
109k
    memcpy(d_packet + d_offset-4, (const char*)&value, sizeof(value));
719
109k
  }
720
721
  uint32_t getOffset() const
722
193
  {
723
193
    return d_offset;
724
193
  }
725
726
0
  void swapInPlace(std::pair<uint32_t, uint32_t> a, std::pair<uint32_t, uint32_t> b) {
727
    // some basic range checks
728
0
    if (b.first < a.first) {
729
0
      std::swap(a, b);
730
0
    }
731
0
    if (a.second-a.first != b.second-b.first) {
732
0
      throw std::out_of_range("swap: segments have different lengths");
733
0
    }
734
0
    if (a.second <= a.first) {
735
0
      throw std::out_of_range("swap: ending of segment before start of segment");
736
0
    }
737
0
    if (a.second > b.first) {
738
0
      throw std::out_of_range("swap: overlapping segments");
739
0
    }
740
0
    if (b.second > d_length) {
741
0
      throw std::out_of_range("swap: ending of segment after end of array");
742
0
    }
743
    // don't allow to swap what we haven't read yet
744
0
    if (b.second > d_offset) {
745
0
      throw std::out_of_range("swap: ending of segment after current offset");
746
0
    }
747
0
    std::swap_ranges(d_packet+a.first, d_packet+a.second, d_packet+b.first);
748
0
  }
749
750
private:
751
  void moveOffset(uint16_t by)
752
1.34M
  {
753
1.34M
    d_notyouroffset += by;
754
1.34M
    if(d_notyouroffset > d_length)
755
4.93k
      throw std::out_of_range("dns packet out of range: "+std::to_string(d_notyouroffset) +" > "
756
4.93k
      + std::to_string(d_length) );
757
1.34M
  }
758
759
  void rewindOffset(uint16_t by)
760
109k
  {
761
109k
    if(d_notyouroffset < by)
762
0
      throw std::out_of_range("Rewinding dns packet out of range: "+std::to_string(d_notyouroffset) +" < "
763
0
                              + std::to_string(by));
764
109k
    d_notyouroffset -= by;
765
109k
    if(d_notyouroffset < 12)
766
0
      throw std::out_of_range("Rewinding dns packet out of range: "+std::to_string(d_notyouroffset) +" < "
767
0
                              + std::to_string(12));
768
109k
  }
769
770
  char* d_packet;
771
  size_t d_length;
772
773
  uint32_t d_notyouroffset;  // only 'moveOffset' can touch this
774
  const uint32_t&  d_offset; // look.. but don't touch
775
};
776
777
string txtEscape(const string &name);