lokinet/llarp/dns/name.cpp

104 lines
2.4 KiB
C++
Raw Normal View History

2018-12-12 00:58:08 +00:00
#include <dns/name.hpp>
#include <net/net.hpp>
2018-12-12 00:58:08 +00:00
2018-12-03 22:22:59 +00:00
#include <algorithm>
2018-12-12 00:58:08 +00:00
#include <sstream>
2018-12-03 22:22:59 +00:00
namespace llarp
{
namespace dns
{
bool
DecodeName(llarp_buffer_t* buf, Name_t& name)
{
if(llarp_buffer_size_left(*buf) < 1)
return false;
std::stringstream ss;
size_t l;
do
{
l = *buf->cur;
buf->cur++;
if(l)
2018-12-04 16:16:43 +00:00
{
if(l > 63)
{
llarp::LogError("decode name failed, field too big: ", l, " > 63");
llarp::DumpBuffer(*buf);
return false;
}
if(llarp_buffer_size_left(*buf) < l)
return false;
2018-12-03 22:22:59 +00:00
ss << Name_t((const char*)buf->cur, l);
2018-12-04 16:16:43 +00:00
ss << ".";
}
buf->cur = buf->cur + l;
2018-12-03 22:22:59 +00:00
} while(l);
name = ss.str();
return true;
}
bool
EncodeName(llarp_buffer_t* buf, const Name_t& name)
{
2018-12-04 16:16:43 +00:00
std::stringstream ss;
if(name.size() && name[name.size() - 1] == '.')
ss << name.substr(0, name.size() - 1);
else
ss << name;
2018-12-03 22:22:59 +00:00
std::string part;
while(std::getline(ss, part, '.'))
{
2018-12-04 16:16:43 +00:00
size_t l = part.length();
if(l > 63)
2018-12-03 22:22:59 +00:00
return false;
2018-12-04 16:16:43 +00:00
*(buf->cur) = l;
2018-12-03 22:22:59 +00:00
buf->cur++;
if(llarp_buffer_size_left(*buf) < l)
return false;
2018-12-04 16:16:43 +00:00
if(l)
{
memcpy(buf->cur, part.data(), l);
buf->cur += l;
}
else
break;
2018-12-03 22:22:59 +00:00
}
2018-12-04 16:16:43 +00:00
*buf->cur = 0;
buf->cur++;
2018-12-03 22:22:59 +00:00
return true;
}
bool
DecodePTR(const Name_t& name, huint32_t& ip)
{
2018-12-04 16:52:48 +00:00
auto pos = name.find(".in-addr.arpa");
if(pos == std::string::npos)
2018-12-03 22:22:59 +00:00
return false;
2018-12-04 16:52:48 +00:00
std::string sub = name.substr(0, pos + 1);
2018-12-03 22:22:59 +00:00
if(std::count(sub.begin(), sub.end(), '.') == 4)
{
uint8_t a, b, c, d;
pos = sub.find('.');
d = atoi(sub.substr(0, pos).c_str());
2018-12-04 16:52:48 +00:00
sub = sub.substr(pos + 1);
2018-12-03 22:22:59 +00:00
pos = sub.find('.');
c = atoi(sub.substr(0, pos).c_str());
2018-12-04 16:52:48 +00:00
sub = sub.substr(pos + 1);
2018-12-03 22:22:59 +00:00
pos = sub.find('.');
b = atoi(sub.substr(0, pos).c_str());
2018-12-04 16:52:48 +00:00
sub = sub.substr(pos + 1);
2018-12-03 22:22:59 +00:00
pos = sub.find('.');
a = atoi(sub.substr(0, pos).c_str());
ip = llarp::ipaddr_ipv4_bits(a, b, c, d);
return true;
}
else
return false;
}
} // namespace dns
} // namespace llarp