lokinet/llarp/service/address.cpp

65 lines
1.8 KiB
C++
Raw Normal View History

2018-12-12 02:15:08 +00:00
#include <service/address.hpp>
#include <algorithm>
2018-07-16 03:32:13 +00:00
namespace llarp
{
namespace service
{
2019-04-26 13:02:08 +00:00
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
{
2019-04-26 12:11:34 +00:00
if(!PermitTLD(tld))
return "";
2018-07-16 03:32:13 +00:00
char tmp[(1 + 32) * 2] = {0};
std::string str = Base32Encode(*this, tmp);
2019-04-26 12:11:34 +00:00
if(subdomain.size())
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)
{
2019-04-26 12:11:34 +00:00
if(!PermitTLD(tld))
return false;
static auto lowercase = [](const std::string s,
bool stripDots) -> std::string {
std::string ret(s.size(), ' ');
std::transform(s.begin(), s.end(), ret.begin(),
[stripDots](const char& ch) -> char {
if(ch == '.' && stripDots)
2019-04-26 12:17:50 +00:00
return ' ';
2019-04-26 12:11:34 +00:00
return ::tolower(ch);
});
return ret.substr(0, ret.find_last_of(' '));
};
const auto pos = str.find_last_of('.');
if(pos == std::string::npos)
return false;
2019-04-26 12:11:34 +00:00
if(str.substr(pos) != tld)
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)
{
subdomain = lowercase(sub.substr(0, idx), false);
sub = sub.substr(idx + 1);
}
// make sure it's lowercase
2019-04-26 12:11:34 +00:00
return Base32Decode(lowercase(sub, true), *this);
}
2018-07-16 03:32:13 +00:00
} // namespace service
} // namespace llarp