lokinet/llarp/dns/message.cpp

384 lines
9.7 KiB
C++
Raw Normal View History

#include <dns/message.hpp>
#include <dns/dns.hpp>
#include <dns/srv_data.hpp>
#include <util/buffer.hpp>
#include <util/endian.hpp>
2019-09-01 12:10:49 +00:00
#include <util/logging/logger.hpp>
2019-02-24 23:46:37 +00:00
#include <util/printer.hpp>
2019-06-11 16:44:05 +00:00
#include <net/ip.hpp>
2018-12-04 16:16:43 +00:00
2019-02-02 23:12:42 +00:00
#include <array>
2018-12-03 22:22:59 +00:00
namespace llarp
{
namespace dns
{
bool
MessageHeader::Encode(llarp_buffer_t* buf) const
{
if (!buf->put_uint16(id))
2018-12-03 22:22:59 +00:00
return false;
if (!buf->put_uint16(fields))
2018-12-03 22:22:59 +00:00
return false;
if (!buf->put_uint16(qd_count))
2018-12-03 22:22:59 +00:00
return false;
if (!buf->put_uint16(an_count))
2018-12-03 22:22:59 +00:00
return false;
if (!buf->put_uint16(ns_count))
2018-12-03 22:22:59 +00:00
return false;
return buf->put_uint16(ar_count);
2018-12-03 22:22:59 +00:00
}
bool
MessageHeader::Decode(llarp_buffer_t* buf)
{
if (!buf->read_uint16(id))
2018-12-03 22:22:59 +00:00
return false;
if (!buf->read_uint16(fields))
2018-12-03 22:22:59 +00:00
return false;
if (!buf->read_uint16(qd_count))
2018-12-03 22:22:59 +00:00
return false;
if (!buf->read_uint16(an_count))
2018-12-03 22:22:59 +00:00
return false;
if (!buf->read_uint16(ns_count))
2018-12-03 22:22:59 +00:00
return false;
if (!buf->read_uint16(ar_count))
return false;
return true;
2018-12-04 16:16:43 +00:00
}
Message::Message(Message&& other)
: hdr_id(std::move(other.hdr_id))
, hdr_fields(std::move(other.hdr_fields))
, questions(std::move(other.questions))
, answers(std::move(other.answers))
, authorities(std::move(other.authorities))
, additional(std::move(other.additional))
Config file improvements (#1397) * Config file API/comment improvements API improvements: ================= Make the config API use position-independent tag parameters (Required, Default{123}, MultiValue) rather than a sequence of bools with overloads. For example, instead of: conf.defineOption<int>("a", "b", false, true, 123, [] { ... }); you now write: conf.defineOption<int>("a", "b", MultiValue, Default{123}, [] { ... }); The tags are: - Required - MultiValue - Default{value} plus new abilities (see below): - Hidden - RelayOnly - ClientOnly - Comment{"line1", "line2", "line3"} Made option definition more powerful: ===================================== - `Hidden` allows you to define an option that won't show up in the generated config file if it isn't set. - `RelayOnly`/`ClientOnly` sets up an option that is only accepted and only shows up for relay or client configs. (If neither is specified the option shows up in both modes). - `Comment{...}` lets the option comments be specified as part of the defineOption. Comment improvements ==================== - Rewrote comments for various options to expand on details. - Inlined all the comments with the option definitions. - Several options that were missing comments got comments added. - Made various options for deprecated and or internal options hidden by default so that they don't show up in a default config file. - show the section comment (but not option comments) *after* the [section] tag instead of before it as it makes more sense that way (particularly for the [bind] section which has a new long comment to describe how it works). Disable profiling by default ============================ We had this weird state where we use and store profiling by default but never *load* it when starting up. This commit makes us just not use profiling at all unless explicitly enabled. Other misc changes: =================== - change default worker threads to 0 (= num cpus) instead of 1, and fix it to allow 0. - Actually apply worker-threads option - fixed default data-dir value erroneously having quotes around it - reordered ifname/ifaddr/mapaddr (was previously mapaddr/ifaddr/ifname) as mapaddr is a sort of specialization of ifaddr and so makes more sense to come after it (particularly because it now references ifaddr in its help message). - removed peer-stats option (since we always require it for relays and never use it for clients) - removed router profiles filename option (this doesn't need to be configurable) - removed defunct `service-node-seed` option - Change default logging output file to "" (which means stdout), and also made "-" work for stdout. * Router hive compilation fixes * Comments for SNApp SRV settings in ini file * Add extra blank line after section comments * Better deprecated option handling Allow {client,relay}-only options in {relay,client} configs to be specified as implicitly deprecated options: they warn, and don't set anything. Add an explicit `Deprecated` tag and move deprecated option handling into definition.cpp. * Move backwards compat options into section definitions Keep the "addBackwardsCompatibleConfigOptions" only for options in sections that no longer exist. * Fix INI parsing issues & C++17-ify - don't allow inline comments because it seems they aren't allowed in ini formats in general, and is going to cause problems if there is a comment character in a value (e.g. an exit auth string). Additionally it was breaking on a line such as: # some comment; see? because it was treating only `; see?` as the comment and then producing an error message about the rest of the line being invalid. - make section parsing stricter: the `[` and `]` have to be at the beginning at end of the line now (after stripping whitespace). - Move whitespace stripping to the top since everything in here does it. - chop off string_view suffix/prefix rather than maintaining position values - fix potential infinite loop/segfault when given a line such as `]foo[` * Make config parsing failure fatal Load() LogError's and returns false on failure, so we weren't aborting on config file errors. * Formatting: allow `{}` for empty functions/structs Instead of using two lines when empty: { } * Make default dns bind 127.0.0.1 on non-Linux * Don't show empty section; fix tests We can conceivably have sections that only make sense for clients or relays, and so want to completely omit that section if we have no options for the type of config being generated. Also fixes missing empty lines between tests. Co-authored-by: Thomas Winget <tewinget@gmail.com>
2020-10-07 22:22:58 +00:00
{}
2018-12-04 16:16:43 +00:00
Message::Message(const Message& other)
: hdr_id(other.hdr_id)
, hdr_fields(other.hdr_fields)
, questions(other.questions)
, answers(other.answers)
, authorities(other.authorities)
, additional(other.additional)
Config file improvements (#1397) * Config file API/comment improvements API improvements: ================= Make the config API use position-independent tag parameters (Required, Default{123}, MultiValue) rather than a sequence of bools with overloads. For example, instead of: conf.defineOption<int>("a", "b", false, true, 123, [] { ... }); you now write: conf.defineOption<int>("a", "b", MultiValue, Default{123}, [] { ... }); The tags are: - Required - MultiValue - Default{value} plus new abilities (see below): - Hidden - RelayOnly - ClientOnly - Comment{"line1", "line2", "line3"} Made option definition more powerful: ===================================== - `Hidden` allows you to define an option that won't show up in the generated config file if it isn't set. - `RelayOnly`/`ClientOnly` sets up an option that is only accepted and only shows up for relay or client configs. (If neither is specified the option shows up in both modes). - `Comment{...}` lets the option comments be specified as part of the defineOption. Comment improvements ==================== - Rewrote comments for various options to expand on details. - Inlined all the comments with the option definitions. - Several options that were missing comments got comments added. - Made various options for deprecated and or internal options hidden by default so that they don't show up in a default config file. - show the section comment (but not option comments) *after* the [section] tag instead of before it as it makes more sense that way (particularly for the [bind] section which has a new long comment to describe how it works). Disable profiling by default ============================ We had this weird state where we use and store profiling by default but never *load* it when starting up. This commit makes us just not use profiling at all unless explicitly enabled. Other misc changes: =================== - change default worker threads to 0 (= num cpus) instead of 1, and fix it to allow 0. - Actually apply worker-threads option - fixed default data-dir value erroneously having quotes around it - reordered ifname/ifaddr/mapaddr (was previously mapaddr/ifaddr/ifname) as mapaddr is a sort of specialization of ifaddr and so makes more sense to come after it (particularly because it now references ifaddr in its help message). - removed peer-stats option (since we always require it for relays and never use it for clients) - removed router profiles filename option (this doesn't need to be configurable) - removed defunct `service-node-seed` option - Change default logging output file to "" (which means stdout), and also made "-" work for stdout. * Router hive compilation fixes * Comments for SNApp SRV settings in ini file * Add extra blank line after section comments * Better deprecated option handling Allow {client,relay}-only options in {relay,client} configs to be specified as implicitly deprecated options: they warn, and don't set anything. Add an explicit `Deprecated` tag and move deprecated option handling into definition.cpp. * Move backwards compat options into section definitions Keep the "addBackwardsCompatibleConfigOptions" only for options in sections that no longer exist. * Fix INI parsing issues & C++17-ify - don't allow inline comments because it seems they aren't allowed in ini formats in general, and is going to cause problems if there is a comment character in a value (e.g. an exit auth string). Additionally it was breaking on a line such as: # some comment; see? because it was treating only `; see?` as the comment and then producing an error message about the rest of the line being invalid. - make section parsing stricter: the `[` and `]` have to be at the beginning at end of the line now (after stripping whitespace). - Move whitespace stripping to the top since everything in here does it. - chop off string_view suffix/prefix rather than maintaining position values - fix potential infinite loop/segfault when given a line such as `]foo[` * Make config parsing failure fatal Load() LogError's and returns false on failure, so we weren't aborting on config file errors. * Formatting: allow `{}` for empty functions/structs Instead of using two lines when empty: { } * Make default dns bind 127.0.0.1 on non-Linux * Don't show empty section; fix tests We can conceivably have sections that only make sense for clients or relays, and so want to completely omit that section if we have no options for the type of config being generated. Also fixes missing empty lines between tests. Co-authored-by: Thomas Winget <tewinget@gmail.com>
2020-10-07 22:22:58 +00:00
{}
2018-12-04 16:16:43 +00:00
Message::Message(const MessageHeader& hdr) : hdr_id(hdr.id), hdr_fields(hdr.fields)
2018-12-04 16:16:43 +00:00
{
questions.resize(size_t(hdr.qd_count));
answers.resize(size_t(hdr.an_count));
authorities.resize(size_t(hdr.ns_count));
additional.resize(size_t(hdr.ar_count));
2018-12-03 22:22:59 +00:00
}
bool
Message::Encode(llarp_buffer_t* buf) const
{
2018-12-04 16:16:43 +00:00
MessageHeader hdr;
hdr.id = hdr_id;
hdr.fields = hdr_fields;
2018-12-04 16:16:43 +00:00
hdr.qd_count = questions.size();
hdr.an_count = answers.size();
hdr.ns_count = 0;
hdr.ar_count = 0;
2018-12-04 16:16:43 +00:00
if (!hdr.Encode(buf))
2018-12-03 22:22:59 +00:00
return false;
for (const auto& question : questions)
if (!question.Encode(buf))
2018-12-03 22:22:59 +00:00
return false;
for (const auto& answer : answers)
if (!answer.Encode(buf))
2018-12-03 22:22:59 +00:00
return false;
return true;
}
bool
Message::Decode(llarp_buffer_t* buf)
{
for (auto& qd : questions)
2018-12-04 16:16:43 +00:00
{
if (!qd.Decode(buf))
2018-12-04 16:16:43 +00:00
{
llarp::LogError("failed to decode question");
2018-12-03 22:22:59 +00:00
return false;
2018-12-04 16:16:43 +00:00
}
llarp::LogDebug(qd);
}
for (auto& an : answers)
2018-12-04 16:16:43 +00:00
{
if (not an.Decode(buf))
2018-12-04 16:16:43 +00:00
{
llarp::LogDebug("failed to decode answer");
2018-12-03 22:22:59 +00:00
return false;
2018-12-04 16:16:43 +00:00
}
}
2018-12-03 22:22:59 +00:00
return true;
}
2019-04-12 12:20:03 +00:00
void Message::AddServFail(RR_TTL_t)
{
if (questions.size())
{
hdr_fields |= flags_RCODEServFail;
// authorative response with recursion available
hdr_fields |= flags_QR | flags_AA | flags_RA;
// don't allow recursion on this request
hdr_fields &= ~flags_RD;
}
}
static constexpr uint16_t
reply_flags(uint16_t setbits)
{
return setbits | flags_QR | flags_AA | flags_RA;
}
2018-12-03 22:22:59 +00:00
void
2019-06-11 16:44:05 +00:00
Message::AddINReply(llarp::huint128_t ip, bool isV6, RR_TTL_t ttl)
2018-12-03 22:22:59 +00:00
{
if (questions.size())
2018-12-03 22:22:59 +00:00
{
hdr_fields = reply_flags(hdr_fields);
2018-12-04 16:16:43 +00:00
ResourceRecord rec;
rec.rr_name = questions[0].qname;
rec.rr_class = qClassIN;
rec.ttl = ttl;
if (isV6)
{
rec.rr_type = qTypeAAAA;
ip.ToV6(rec.rData);
}
else
{
const auto addr = net::TruncateV6(ip);
rec.rr_type = qTypeA;
rec.rData.resize(4);
2019-06-11 16:44:05 +00:00
htobe32buf(rec.rData.data(), addr.h);
}
2018-12-04 16:16:43 +00:00
answers.emplace_back(std::move(rec));
2018-12-03 22:22:59 +00:00
}
}
2018-12-04 16:16:43 +00:00
void
Message::AddAReply(std::string name, RR_TTL_t ttl)
2018-12-03 22:22:59 +00:00
{
if (questions.size())
2018-12-03 22:22:59 +00:00
{
hdr_fields = reply_flags(hdr_fields);
2018-12-03 22:22:59 +00:00
const auto& question = questions[0];
answers.emplace_back();
auto& rec = answers.back();
rec.rr_name = question.qname;
rec.rr_type = question.qtype;
rec.rr_class = qClassIN;
rec.ttl = ttl;
std::array<byte_t, 512> tmp = {{0}};
2019-02-02 23:12:42 +00:00
llarp_buffer_t buf(tmp);
if (EncodeName(&buf, name))
2018-12-04 17:02:13 +00:00
{
buf.sz = buf.cur - buf.base;
rec.rData.resize(buf.sz);
memcpy(rec.rData.data(), buf.base, buf.sz);
}
2018-12-03 22:22:59 +00:00
}
}
void
Message::AddNSReply(std::string name, RR_TTL_t ttl)
{
if (not questions.empty())
{
hdr_fields = reply_flags(hdr_fields);
const auto& question = questions[0];
answers.emplace_back();
auto& rec = answers.back();
rec.rr_name = question.qname;
rec.rr_type = qTypeNS;
rec.rr_class = qClassIN;
rec.ttl = ttl;
std::array<byte_t, 512> tmp = {{0}};
llarp_buffer_t buf(tmp);
if (EncodeName(&buf, name))
{
buf.sz = buf.cur - buf.base;
rec.rData.resize(buf.sz);
memcpy(rec.rData.data(), buf.base, buf.sz);
}
}
}
2018-12-13 00:03:19 +00:00
void
Message::AddCNAMEReply(std::string name, RR_TTL_t ttl)
2018-12-13 00:03:19 +00:00
{
if (questions.size())
2018-12-13 00:03:19 +00:00
{
hdr_fields = reply_flags(hdr_fields);
2018-12-13 00:03:19 +00:00
const auto& question = questions[0];
answers.emplace_back();
auto& rec = answers.back();
rec.rr_name = question.qname;
rec.rr_type = qTypeCNAME;
rec.rr_class = qClassIN;
rec.ttl = ttl;
std::array<byte_t, 512> tmp = {{0}};
2019-02-02 23:12:42 +00:00
llarp_buffer_t buf(tmp);
if (EncodeName(&buf, name))
2018-12-13 00:03:19 +00:00
{
buf.sz = buf.cur - buf.base;
rec.rData.resize(buf.sz);
memcpy(rec.rData.data(), buf.base, buf.sz);
}
}
}
2018-12-07 21:52:19 +00:00
void
Message::AddMXReply(std::string name, uint16_t priority, RR_TTL_t ttl)
2018-12-07 21:52:19 +00:00
{
if (questions.size())
2018-12-07 21:52:19 +00:00
{
hdr_fields = reply_flags(hdr_fields);
2018-12-07 21:52:19 +00:00
const auto& question = questions[0];
answers.emplace_back();
auto& rec = answers.back();
rec.rr_name = question.qname;
rec.rr_type = qTypeMX;
rec.rr_class = qClassIN;
rec.ttl = ttl;
std::array<byte_t, 512> tmp = {{0}};
2019-02-02 23:12:42 +00:00
llarp_buffer_t buf(tmp);
buf.put_uint16(priority);
if (EncodeName(&buf, name))
2018-12-07 21:52:19 +00:00
{
buf.sz = buf.cur - buf.base;
rec.rData.resize(buf.sz);
memcpy(rec.rData.data(), buf.base, buf.sz);
}
}
}
void
Message::AddSRVReply(std::vector<SRVData> records, RR_TTL_t ttl)
{
hdr_fields = reply_flags(hdr_fields);
const auto& question = questions[0];
for (const auto& srv : records)
{
if (not srv.IsValid())
{
AddNXReply();
return;
}
answers.emplace_back();
auto& rec = answers.back();
rec.rr_name = question.qname;
rec.rr_type = qTypeSRV;
rec.rr_class = qClassIN;
rec.ttl = ttl;
std::array<byte_t, 512> tmp = {{0}};
llarp_buffer_t buf(tmp);
buf.put_uint16(srv.priority);
buf.put_uint16(srv.weight);
buf.put_uint16(srv.port);
std::string target;
if (srv.target == "")
{
// get location of second dot (after service.proto) in qname
size_t pos = question.qname.find(".");
pos = question.qname.find(".", pos + 1);
target = question.qname.substr(pos + 1);
}
else
{
target = srv.target;
}
if (not EncodeName(&buf, target))
{
AddNXReply();
return;
}
buf.sz = buf.cur - buf.base;
rec.rData.resize(buf.sz);
memcpy(rec.rData.data(), buf.base, buf.sz);
}
}
void
Message::AddTXTReply(std::string str, RR_TTL_t ttl)
{
auto& rec = answers.emplace_back();
rec.rr_name = questions[0].qname;
rec.rr_class = qClassIN;
rec.rr_type = qTypeTXT;
rec.ttl = ttl;
std::array<byte_t, 1024> tmp{};
llarp_buffer_t buf(tmp);
while (not str.empty())
{
const auto left = std::min(str.size(), size_t{256});
const auto sub = str.substr(0, left);
uint8_t byte = left;
*buf.cur = byte;
buf.cur++;
if (not buf.write(sub.begin(), sub.end()))
throw std::length_error("text record too big");
str = str.substr(left);
}
buf.sz = buf.cur - buf.base;
rec.rData.resize(buf.sz);
std::copy_n(buf.base, buf.sz, rec.rData.data());
}
2019-04-12 15:26:20 +00:00
void Message::AddNXReply(RR_TTL_t)
2018-12-03 22:22:59 +00:00
{
if (questions.size())
2018-12-03 22:22:59 +00:00
{
answers.clear();
authorities.clear();
additional.clear();
2019-02-22 16:18:53 +00:00
// authorative response with recursion available
hdr_fields = reply_flags(hdr_fields);
2019-02-22 16:18:53 +00:00
// don't allow recursion on this request
hdr_fields &= ~flags_RD;
2019-04-12 15:19:51 +00:00
hdr_fields |= flags_RCODENameError;
2018-12-03 22:22:59 +00:00
}
}
2019-02-24 23:46:37 +00:00
std::ostream&
Message::print(std::ostream& stream, int level, int spaces) const
{
Printer printer(stream, level, spaces);
printer.printAttributeAsHex("dns message id", hdr_id);
printer.printAttributeAsHex("fields", hdr_fields);
printer.printAttribute("questions", questions);
printer.printAttribute("answers", answers);
printer.printAttribute("nameserer", authorities);
printer.printAttribute("additional", additional);
return stream;
}
2018-12-03 22:22:59 +00:00
} // namespace dns
} // namespace llarp