hello-dns/tdns/dnsmessages.hh

99 lines
2.2 KiB
C++
Raw Normal View History

2018-04-10 01:49:37 +07:00
#pragma once
2018-04-09 21:43:24 +07:00
#include "dns.hh"
#include "safearray.hh"
#include "dns-storage.hh"
2018-04-12 03:12:57 +07:00
#include <vector>
2018-04-09 21:43:24 +07:00
class DNSMessageReader
2018-04-09 21:43:24 +07:00
{
public:
DNSMessageReader(const char* input, uint16_t length);
DNSMessageReader(const std::string& str) : DNSMessageReader(str.c_str(), str.size()) {}
2018-04-09 21:43:24 +07:00
struct dnsheader dh=dnsheader{};
SafeArray<500> payload;
void getQuestion(DNSName& name, DNSType& type) const;
bool getEDNS(uint16_t* newsize, bool* doBit) const;
uint8_t d_ednsVersion{0};
private:
DNSName getName();
DNSName d_qname;
DNSType d_qtype;
DNSClass d_qclass;
uint16_t d_bufsize;
bool d_doBit{false};
bool d_haveEDNS{false};
2018-04-09 21:43:24 +07:00
};
class DNSMessageWriter
2018-04-09 21:43:24 +07:00
{
public:
2018-04-12 21:29:59 +07:00
struct dnsheader dh=dnsheader{};
std::vector<uint8_t> payload;
uint16_t payloadpos=0;
DNSName d_qname;
DNSType d_qtype;
DNSClass d_qclass;
bool haveEDNS{false};
bool d_doBit;
RCode d_ercode{(RCode)0};
2018-04-12 21:29:59 +07:00
DNSMessageWriter(const DNSName& name, DNSType type, int maxsize=500);
void clearRRs();
2018-04-12 21:31:43 +07:00
void putRR(DNSSection section, const DNSName& name, DNSType type, uint32_t ttl, const std::unique_ptr<RRGen>& rr);
void setEDNS(uint16_t bufsize, bool doBit, RCode ercode = (RCode)0);
2018-04-09 21:43:24 +07:00
std::string serialize() const;
2018-04-12 03:12:57 +07:00
void putUInt8(uint8_t val)
{
payload.at(payloadpos++)=val;
}
uint16_t putUInt16(uint16_t val)
{
val = htons(val);
memcpy(&payload.at(payloadpos+2)-2, &val, 2);
payloadpos+=2;
return payloadpos - 2;
}
void putUInt16At(uint16_t pos, uint16_t val)
{
val = htons(val);
memcpy(&payload.at(pos+2)-2, &val, 2);
}
void putUInt32(uint32_t val)
2018-04-09 21:43:24 +07:00
{
2018-04-12 03:12:57 +07:00
val = htonl(val);
memcpy(&payload.at(payloadpos+sizeof(val)) - sizeof(val), &val, sizeof(val));
payloadpos += sizeof(val);
2018-04-09 21:43:24 +07:00
}
2018-04-12 03:12:57 +07:00
void putBlob(const std::string& blob)
{
memcpy(&payload.at(payloadpos+blob.size()) - blob.size(), blob.c_str(), blob.size());
payloadpos += blob.size();;
}
void putBlob(const unsigned char* blob, int size)
{
memcpy(&payload.at(payloadpos+size) - size, blob, size);
payloadpos += size;
}
2018-04-12 21:31:43 +07:00
void putName(const DNSName& name)
2018-04-12 03:12:57 +07:00
{
for(const auto& l : name) {
putUInt8(l.size());
putBlob(l.d_s);
}
putUInt8(0);
}
private:
void putEDNS(uint16_t bufsize, RCode ercode, bool doBit);
2018-04-12 03:12:57 +07:00
};