lokinet/llarp/service/address.cpp

72 lines
1.9 KiB
C++
Raw Normal View History

2018-12-12 02:15:08 +00:00
#include <service/address.hpp>
2020-01-27 21:30:41 +00:00
#include <crypto/crypto.hpp>
#include <algorithm>
2018-07-16 03:32:13 +00:00
namespace llarp
{
namespace service
{
const std::set<std::string> Address::AllowedTLDs = {".loki", ".snode"};
2019-04-26 12:11:34 +00:00
bool
Address::PermitTLD(const char* tld)
{
std::string gtld(tld);
std::transform(gtld.begin(), gtld.end(), gtld.begin(), ::tolower);
2019-04-26 13:02:08 +00:00
return AllowedTLDs.count(gtld) != 0;
2019-04-26 12:11:34 +00:00
}
2018-07-16 03:32:13 +00:00
std::string
2018-12-03 22:22:59 +00:00
Address::ToString(const char* tld) const
2018-07-16 03:32:13 +00:00
{
if (!PermitTLD(tld))
2019-04-26 12:11:34 +00:00
return "";
2018-07-16 03:32:13 +00:00
char tmp[(1 + 32) * 2] = {0};
std::string str = Base32Encode(*this, tmp);
if (subdomain.size())
2019-04-26 12:11:34 +00:00
str = subdomain + "." + str;
2018-12-03 22:22:59 +00:00
return str + tld;
2018-07-16 03:32:13 +00:00
}
bool
2018-12-03 22:22:59 +00:00
Address::FromString(const std::string& str, const char* tld)
{
if (!PermitTLD(tld))
2019-04-26 12:11:34 +00:00
return false;
static auto lowercase = [](const std::string s, bool stripDots) -> std::string {
2019-04-26 12:11:34 +00:00
std::string ret(s.size(), ' ');
std::transform(s.begin(), s.end(), ret.begin(), [stripDots](const char& ch) -> char {
if (ch == '.' && stripDots)
return ' ';
return ::tolower(ch);
});
2019-04-26 12:11:34 +00:00
return ret.substr(0, ret.find_last_of(' '));
};
const auto pos = str.find_last_of('.');
if (pos == std::string::npos)
return false;
if (str.substr(pos) != tld)
2019-04-26 12:11:34 +00:00
return false;
auto sub = str.substr(0, pos);
2019-04-26 12:11:34 +00:00
// set subdomains if they are there
const auto idx = sub.find_last_of('.');
if (idx != std::string::npos)
2019-04-26 12:11:34 +00:00
{
subdomain = lowercase(sub.substr(0, idx), false);
sub = sub.substr(idx + 1);
2019-04-26 12:11:34 +00:00
}
// make sure it's lowercase
2019-04-26 12:11:34 +00:00
return Base32Decode(lowercase(sub, true), *this);
}
2020-01-27 21:30:41 +00:00
dht::Key_t
Address::ToKey() const
{
PubKey k;
CryptoManager::instance()->derive_subkey(k, PubKey(data()), 1);
return dht::Key_t{k.as_array()};
}
2018-07-16 03:32:13 +00:00
} // namespace service
} // namespace llarp