lokinet/llarp/net/exit_info.cpp

106 lines
2.4 KiB
C++
Raw Normal View History

#ifndef _WIN32
2018-04-05 14:43:16 +00:00
#include <arpa/inet.h>
#endif
#include <net/exit_info.hpp>
#include <util/bencode.h>
2019-02-07 00:22:54 +00:00
#include <util/bits.hpp>
#include <util/mem.h>
#include <list>
#include <string.h>
2018-05-10 23:32:46 +00:00
2018-08-31 12:46:54 +00:00
namespace llarp
{
2018-08-31 12:46:54 +00:00
ExitInfo::~ExitInfo()
{
2018-05-10 23:32:46 +00:00
}
2018-08-31 13:51:24 +00:00
ExitInfo&
ExitInfo::operator=(const ExitInfo& other)
{
memcpy(address.s6_addr, other.address.s6_addr, 16);
memcpy(netmask.s6_addr, other.netmask.s6_addr, 16);
pubkey = other.pubkey;
version = other.version;
return *this;
}
2018-08-31 12:46:54 +00:00
bool
ExitInfo::BEncode(llarp_buffer_t* buf) const
{
2018-08-31 12:46:54 +00:00
char tmp[128] = {0};
if(!bencode_start_dict(buf))
return false;
2018-11-09 14:48:43 +00:00
if(!inet_ntop(AF_INET6, (void*)&address, tmp, sizeof(tmp)))
return false;
2018-08-31 12:46:54 +00:00
if(!BEncodeWriteDictString("a", std::string(tmp), buf))
return false;
2018-11-09 14:48:43 +00:00
if(!inet_ntop(AF_INET6, (void*)&netmask, tmp, sizeof(tmp)))
return false;
2018-08-31 12:46:54 +00:00
if(!BEncodeWriteDictString("b", std::string(tmp), buf))
return false;
2018-08-31 12:46:54 +00:00
if(!BEncodeWriteDictEntry("k", pubkey, buf))
return false;
2018-08-31 12:46:54 +00:00
if(!BEncodeWriteDictInt("v", version, buf))
return false;
2018-08-31 12:46:54 +00:00
return bencode_end(buf);
}
2019-01-17 15:11:17 +00:00
static bool
bdecode_ip_string(llarp_buffer_t* buf, in6_addr& ip)
{
char tmp[128] = {0};
llarp_buffer_t strbuf;
if(!bencode_read_string(buf, &strbuf))
return false;
if(strbuf.sz >= sizeof(tmp))
return false;
memcpy(tmp, strbuf.base, strbuf.sz);
tmp[strbuf.sz] = 0;
return inet_pton(AF_INET6, tmp, &ip.s6_addr[0]) == 1;
}
2018-08-31 12:46:54 +00:00
bool
2019-02-05 00:41:33 +00:00
ExitInfo::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf)
2018-08-31 12:46:54 +00:00
{
bool read = false;
2019-01-17 15:11:17 +00:00
if(!BEncodeMaybeReadDictEntry("k", pubkey, read, k, buf))
return false;
if(!BEncodeMaybeReadDictInt("v", version, read, k, buf))
return false;
if(k == "a")
2019-01-17 15:11:17 +00:00
return bdecode_ip_string(buf, address);
if(k == "b")
2019-01-17 15:11:17 +00:00
return bdecode_ip_string(buf, netmask);
2018-08-31 12:46:54 +00:00
return read;
}
2018-05-30 20:56:47 +00:00
2019-02-07 00:22:54 +00:00
std::ostream&
operator<<(std::ostream& out, const ExitInfo& xi)
{
char tmp[128] = {0};
if(inet_ntop(AF_INET6, (void*)&xi.address, tmp, sizeof(tmp)))
out << std::string(tmp);
else
return out;
out << std::string("/");
#if defined(ANDROID) || defined(RPI)
snprintf(tmp, sizeof(tmp), "%zu",
llarp::bits::count_array_bits(xi.netmask.s6_addr));
return out << tmp;
#else
return out << std::to_string(
llarp::bits::count_array_bits(xi.netmask.s6_addr));
#endif
}
2018-08-31 12:46:54 +00:00
} // namespace llarp