Merge pull request #1573 from jagerman/more-code-refactors

More code refactors
pull/1596/head
Jeff 3 years ago committed by GitHub
commit cb2254ba46
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -107,7 +107,7 @@ namespace llarp
net::IPRangeMap<service::Address> m_ExitMap; net::IPRangeMap<service::Address> m_ExitMap;
net::IPRangeMap<std::string> m_LNSExitMap; net::IPRangeMap<std::string> m_LNSExitMap;
std::unordered_map<service::Address, service::AuthInfo, service::Address::Hash> m_ExitAuths; std::unordered_map<service::Address, service::AuthInfo> m_ExitAuths;
std::unordered_map<std::string, service::AuthInfo> m_LNSExitAuths; std::unordered_map<std::string, service::AuthInfo> m_LNSExitAuths;
std::unordered_map<huint128_t, service::Address> m_mapAddrs; std::unordered_map<huint128_t, service::Address> m_mapAddrs;
@ -115,7 +115,7 @@ namespace llarp
service::AuthType m_AuthType = service::AuthType::eAuthTypeNone; service::AuthType m_AuthType = service::AuthType::eAuthTypeNone;
std::optional<std::string> m_AuthUrl; std::optional<std::string> m_AuthUrl;
std::optional<std::string> m_AuthMethod; std::optional<std::string> m_AuthMethod;
std::unordered_set<service::Address, service::Address::Hash> m_AuthWhitelist; std::unordered_set<service::Address> m_AuthWhitelist;
std::vector<llarp::dns::SRVData> m_SRVRecords; std::vector<llarp::dns::SRVData> m_SRVRecords;

@ -243,3 +243,10 @@ namespace llarp
/// SH(result, body) /// SH(result, body)
using shorthash_func = std::function<bool(ShortHash&, const llarp_buffer_t&)>; using shorthash_func = std::function<bool(ShortHash&, const llarp_buffer_t&)>;
} // namespace llarp } // namespace llarp
namespace std
{
template <>
struct hash<llarp::PubKey> : hash<llarp::AlignedBuffer<llarp::PubKey::SIZE>>
{};
}; // namespace std

@ -34,9 +34,9 @@ namespace llarp
struct AbstractContext struct AbstractContext
{ {
using PendingIntrosetLookups = TXHolder<TXOwner, service::EncryptedIntroSet, TXOwner::Hash>; using PendingIntrosetLookups = TXHolder<TXOwner, service::EncryptedIntroSet>;
using PendingRouterLookups = TXHolder<RouterID, RouterContact, RouterID::Hash>; using PendingRouterLookups = TXHolder<RouterID, RouterContact>;
using PendingExploreLookups = TXHolder<RouterID, RouterID, RouterID::Hash>; using PendingExploreLookups = TXHolder<RouterID, RouterID>;
virtual ~AbstractContext() = 0; virtual ~AbstractContext() = 0;

@ -13,16 +13,16 @@ namespace llarp
{ {
namespace dht namespace dht
{ {
template <typename K, typename V, typename K_Hash> template <typename K, typename V>
struct TXHolder struct TXHolder
{ {
using TXPtr = std::unique_ptr<TX<K, V>>; using TXPtr = std::unique_ptr<TX<K, V>>;
// tx who are waiting for a reply for each key // tx who are waiting for a reply for each key
std::unordered_multimap<K, TXOwner, K_Hash> waiting; std::unordered_multimap<K, TXOwner> waiting;
// tx timesouts by key // tx timesouts by key
std::unordered_map<K, llarp_time_t, K_Hash> timeouts; std::unordered_map<K, llarp_time_t> timeouts;
// maps remote peer with tx to handle reply from them // maps remote peer with tx to handle reply from them
std::unordered_map<TXOwner, TXPtr, TXOwner::Hash> tx; std::unordered_map<TXOwner, TXPtr> tx;
const TX<K, V>* const TX<K, V>*
GetPendingLookupFrom(const TXOwner& owner) const; GetPendingLookupFrom(const TXOwner& owner) const;
@ -106,9 +106,9 @@ namespace llarp
Expire(llarp_time_t now); Expire(llarp_time_t now);
}; };
template <typename K, typename V, typename K_Hash> template <typename K, typename V>
const TX<K, V>* const TX<K, V>*
TXHolder<K, V, K_Hash>::GetPendingLookupFrom(const TXOwner& owner) const TXHolder<K, V>::GetPendingLookupFrom(const TXOwner& owner) const
{ {
auto itr = tx.find(owner); auto itr = tx.find(owner);
if (itr == tx.end()) if (itr == tx.end())
@ -119,9 +119,9 @@ namespace llarp
return itr->second.get(); return itr->second.get();
} }
template <typename K, typename V, typename K_Hash> template <typename K, typename V>
void void
TXHolder<K, V, K_Hash>::NewTX( TXHolder<K, V>::NewTX(
const TXOwner& askpeer, const TXOwner& askpeer,
const TXOwner& whoasked, const TXOwner& whoasked,
const K& k, const K& k,
@ -144,9 +144,9 @@ namespace llarp
} }
} }
template <typename K, typename V, typename K_Hash> template <typename K, typename V>
void void
TXHolder<K, V, K_Hash>::NotFound(const TXOwner& from, const std::unique_ptr<Key_t>&) TXHolder<K, V>::NotFound(const TXOwner& from, const std::unique_ptr<Key_t>&)
{ {
auto txitr = tx.find(from); auto txitr = tx.find(from);
if (txitr == tx.end()) if (txitr == tx.end())
@ -156,9 +156,9 @@ namespace llarp
Inform(from, txitr->second->target, {}, true, true); Inform(from, txitr->second->target, {}, true, true);
} }
template <typename K, typename V, typename K_Hash> template <typename K, typename V>
void void
TXHolder<K, V, K_Hash>::Inform( TXHolder<K, V>::Inform(
TXOwner from, K key, std::vector<V> values, bool sendreply, bool removeTimeouts) TXOwner from, K key, std::vector<V> values, bool sendreply, bool removeTimeouts)
{ {
auto range = waiting.equal_range(key); auto range = waiting.equal_range(key);
@ -192,9 +192,9 @@ namespace llarp
} }
} }
template <typename K, typename V, typename K_Hash> template <typename K, typename V>
void void
TXHolder<K, V, K_Hash>::Expire(llarp_time_t now) TXHolder<K, V>::Expire(llarp_time_t now)
{ {
auto itr = timeouts.begin(); auto itr = timeouts.begin();
while (itr != timeouts.end()) while (itr != timeouts.end())

@ -44,17 +44,21 @@ namespace llarp
{ {
return std::tie(txid, node) < std::tie(other.txid, other.node); return std::tie(txid, node) < std::tie(other.txid, other.node);
} }
struct Hash
{
std::size_t
operator()(const TXOwner& o) const noexcept
{
std::size_t sz2;
memcpy(&sz2, o.node.data(), sizeof(std::size_t));
return o.txid ^ (sz2 << 1);
}
};
}; };
} // namespace dht } // namespace dht
} // namespace llarp } // namespace llarp
namespace std
{
template <>
struct hash<llarp::dht::TXOwner>
{
std::size_t
operator()(const llarp::dht::TXOwner& o) const noexcept
{
std::size_t sz2;
memcpy(&sz2, o.node.data(), sizeof(std::size_t));
return o.txid ^ (sz2 << 1);
}
};
} // namespace std

@ -39,7 +39,7 @@ namespace llarp
FindEndpointForPath(const PathID_t& path) const; FindEndpointForPath(const PathID_t& path) const;
/// calculate (pk, tx, rx) for all exit traffic /// calculate (pk, tx, rx) for all exit traffic
using TrafficStats = std::unordered_map<PubKey, std::pair<uint64_t, uint64_t>, PubKey::Hash>; using TrafficStats = std::unordered_map<PubKey, std::pair<uint64_t, uint64_t>>;
void void
CalculateExitTraffic(TrafficStats& stats); CalculateExitTraffic(TrafficStats& stats);

@ -134,13 +134,13 @@ namespace llarp
bool m_ShouldInitTun; bool m_ShouldInitTun;
std::string m_Name; std::string m_Name;
bool m_PermitExit; bool m_PermitExit;
std::unordered_map<PathID_t, PubKey, PathID_t::Hash> m_Paths; std::unordered_map<PathID_t, PubKey> m_Paths;
std::unordered_map<PubKey, exit::Endpoint*, PubKey::Hash> m_ChosenExits; std::unordered_map<PubKey, exit::Endpoint*> m_ChosenExits;
std::unordered_multimap<PubKey, std::unique_ptr<exit::Endpoint>, PubKey::Hash> m_ActiveExits; std::unordered_multimap<PubKey, std::unique_ptr<exit::Endpoint>> m_ActiveExits;
using KeyMap_t = std::unordered_map<PubKey, huint128_t, PubKey::Hash>; using KeyMap_t = std::unordered_map<PubKey, huint128_t>;
KeyMap_t m_KeyToIP; KeyMap_t m_KeyToIP;
@ -148,8 +148,7 @@ namespace llarp
/// set of pubkeys we treat as snodes /// set of pubkeys we treat as snodes
SNodes_t m_SNodeKeys; SNodes_t m_SNodeKeys;
using SNodeSessions_t = using SNodeSessions_t = std::unordered_map<RouterID, std::shared_ptr<exit::SNodeSession>>;
std::unordered_map<RouterID, std::shared_ptr<exit::SNodeSession>, RouterID::Hash>;
/// snode sessions we are talking to directly /// snode sessions we are talking to directly
SNodeSessions_t m_SNodeSessions; SNodeSessions_t m_SNodeSessions;

@ -61,8 +61,8 @@ namespace llarp
hdr->ttl = 64; hdr->ttl = 64;
hdr->frag_off = htons(0b0100000000000000); hdr->frag_off = htons(0b0100000000000000);
hdr->saddr = from.getIPv4(); hdr->saddr = from.getIPv4().n;
hdr->daddr = to.getIPv4(); hdr->daddr = to.getIPv4().n;
// make udp packet // make udp packet
uint8_t* ptr = pkt.buf + 20; uint8_t* ptr = pkt.buf + 20;
@ -98,8 +98,8 @@ namespace llarp
const uint8_t* ptr = pkt.buf + ip_header_size; const uint8_t* ptr = pkt.buf + ip_header_size;
const auto dst = ToNet(pkt.dstv4()); const auto dst = ToNet(pkt.dstv4());
const auto src = ToNet(pkt.srcv4()); const auto src = ToNet(pkt.srcv4());
const SockAddr laddr{src.n, *reinterpret_cast<const uint16_t*>(ptr)}; const SockAddr laddr{src, nuint16_t{*reinterpret_cast<const uint16_t*>(ptr)}};
const SockAddr raddr{dst.n, *reinterpret_cast<const uint16_t*>(ptr + 2)}; const SockAddr raddr{dst, nuint16_t{*reinterpret_cast<const uint16_t*>(ptr + 2)}};
OwnedBuffer buf{pkt.sz - (udp_header_size + ip_header_size)}; OwnedBuffer buf{pkt.sz - (udp_header_size + ip_header_size)};
std::copy_n(ptr + udp_header_size, buf.sz, buf.buf.get()); std::copy_n(ptr + udp_header_size, buf.sz, buf.buf.get());
@ -931,7 +931,7 @@ namespace llarp
{ {
(void)ip; (void)ip;
SendToServiceOrQueue( SendToServiceOrQueue(
service::Address{addr.as_array()}, pkt.ConstBuffer(), service::eProtocolExit); service::Address{addr.as_array()}, pkt.ConstBuffer(), service::ProtocolType::Exit);
} }
return; return;
} }
@ -966,7 +966,7 @@ namespace llarp
{ {
ctx->sendTimeout = 5s; ctx->sendTimeout = 5s;
} }
self->SendToServiceOrQueue(addr, pkt.ConstBuffer(), service::eProtocolExit); self->SendToServiceOrQueue(addr, pkt.ConstBuffer(), service::ProtocolType::Exit);
}, },
1s); 1s);
} }
@ -989,7 +989,7 @@ namespace llarp
this, this,
service::Address(itr->second.as_array()), service::Address(itr->second.as_array()),
std::placeholders::_1, std::placeholders::_1,
service::eProtocolExit); service::ProtocolType::Exit);
} }
else else
{ {
@ -1025,8 +1025,8 @@ namespace llarp
service::ProtocolType t, service::ProtocolType t,
uint64_t seqno) uint64_t seqno)
{ {
if (t != service::eProtocolTrafficV4 && t != service::eProtocolTrafficV6 if (t != service::ProtocolType::TrafficV4 && t != service::ProtocolType::TrafficV6
&& t != service::eProtocolExit) && t != service::ProtocolType::Exit)
return false; return false;
AlignedBuffer<32> addr; AlignedBuffer<32> addr;
bool snode = false; bool snode = false;
@ -1042,7 +1042,7 @@ namespace llarp
{ {
// exit side from exit // exit side from exit
src = ObtainIPForAddr(addr, snode); src = ObtainIPForAddr(addr, snode);
if (t == service::eProtocolExit) if (t == service::ProtocolType::Exit)
{ {
if (pkt.IsV4()) if (pkt.IsV4())
dst = pkt.dst4to6(); dst = pkt.dst4to6();
@ -1058,7 +1058,7 @@ namespace llarp
dst = m_OurIP; dst = m_OurIP;
} }
} }
else if (t == service::eProtocolExit) else if (t == service::ProtocolType::Exit)
{ {
// client side exit traffic from exit // client side exit traffic from exit
if (pkt.IsV4()) if (pkt.IsV4())

@ -200,11 +200,11 @@ namespace llarp
/// maps ip to key (host byte order) /// maps ip to key (host byte order)
std::unordered_map<huint128_t, AlignedBuffer<32>> m_IPToAddr; std::unordered_map<huint128_t, AlignedBuffer<32>> m_IPToAddr;
/// maps key to ip (host byte order) /// maps key to ip (host byte order)
std::unordered_map<AlignedBuffer<32>, huint128_t, AlignedBuffer<32>::Hash> m_AddrToIP; std::unordered_map<AlignedBuffer<32>, huint128_t> m_AddrToIP;
/// maps key to true if key is a service node, maps key to false if key is /// maps key to true if key is a service node, maps key to false if key is
/// a hidden service /// a hidden service
std::unordered_map<AlignedBuffer<32>, bool, AlignedBuffer<32>::Hash> m_SNodes; std::unordered_map<AlignedBuffer<32>, bool> m_SNodes;
private: private:
template <typename Addr_t, typename Endpoint_t> template <typename Addr_t, typename Endpoint_t>

@ -61,8 +61,8 @@ namespace llarp::iwp
HandleWakeupPlaintext(); HandleWakeupPlaintext();
const std::shared_ptr<EventLoopWakeup> m_Wakeup; const std::shared_ptr<EventLoopWakeup> m_Wakeup;
std::unordered_map<SockAddr, std::weak_ptr<Session>, SockAddr::Hash> m_PlaintextRecv; std::unordered_map<SockAddr, std::weak_ptr<Session>> m_PlaintextRecv;
std::unordered_map<SockAddr, RouterID, SockAddr::Hash> m_AuthedAddrs; std::unordered_map<SockAddr, RouterID> m_AuthedAddrs;
const bool permitInbound; const bool permitInbound;
}; };

@ -296,7 +296,7 @@ namespace llarp
bool bool
LinkManager::GetRandomConnectedRouter(RouterContact& router) const LinkManager::GetRandomConnectedRouter(RouterContact& router) const
{ {
std::unordered_map<RouterID, RouterContact, RouterID::Hash> connectedRouters; std::unordered_map<RouterID, RouterContact> connectedRouters;
ForEachPeer( ForEachPeer(
[&connectedRouters](const ILinkSession* peer, bool unused) { [&connectedRouters](const ILinkSession* peer, bool unused) {

@ -104,10 +104,9 @@ namespace llarp
LinkSet inboundLinks; LinkSet inboundLinks;
// sessions to persist -> timestamp to end persist at // sessions to persist -> timestamp to end persist at
std::unordered_map<RouterID, llarp_time_t, RouterID::Hash> m_PersistingSessions std::unordered_map<RouterID, llarp_time_t> m_PersistingSessions GUARDED_BY(_mutex);
GUARDED_BY(_mutex);
std::unordered_map<RouterID, SessionStats, RouterID::Hash> m_lastRouterStats; std::unordered_map<RouterID, SessionStats> m_lastRouterStats;
IOutboundSessionMaker* _sessionMaker; IOutboundSessionMaker* _sessionMaker;
}; };

@ -172,7 +172,7 @@ namespace llarp
void void
ILinkLayer::Pump() ILinkLayer::Pump()
{ {
std::unordered_set<RouterID, RouterID::Hash> closedSessions; std::unordered_set<RouterID> closedSessions;
std::vector<std::shared_ptr<ILinkSession>> closedPending; std::vector<std::shared_ptr<ILinkSession>> closedPending;
auto _now = Now(); auto _now = Now();
{ {

@ -244,16 +244,14 @@ namespace llarp
std::shared_ptr<llarp::UDPHandle> m_udp; std::shared_ptr<llarp::UDPHandle> m_udp;
SecretKey m_SecretKey; SecretKey m_SecretKey;
using AuthedLinks = using AuthedLinks = std::unordered_multimap<RouterID, std::shared_ptr<ILinkSession>>;
std::unordered_multimap<RouterID, std::shared_ptr<ILinkSession>, RouterID::Hash>; using Pending = std::unordered_multimap<SockAddr, std::shared_ptr<ILinkSession>>;
using Pending =
std::unordered_multimap<SockAddr, std::shared_ptr<ILinkSession>, SockAddr::Hash>;
mutable DECLARE_LOCK(Mutex_t, m_AuthedLinksMutex, ACQUIRED_BEFORE(m_PendingMutex)); mutable DECLARE_LOCK(Mutex_t, m_AuthedLinksMutex, ACQUIRED_BEFORE(m_PendingMutex));
AuthedLinks m_AuthedLinks GUARDED_BY(m_AuthedLinksMutex); AuthedLinks m_AuthedLinks GUARDED_BY(m_AuthedLinksMutex);
mutable DECLARE_LOCK(Mutex_t, m_PendingMutex, ACQUIRED_AFTER(m_AuthedLinksMutex)); mutable DECLARE_LOCK(Mutex_t, m_PendingMutex, ACQUIRED_AFTER(m_AuthedLinksMutex));
Pending m_Pending GUARDED_BY(m_PendingMutex); Pending m_Pending GUARDED_BY(m_PendingMutex);
std::unordered_map<SockAddr, llarp_time_t, SockAddr::Hash> m_RecentlyClosed; std::unordered_map<SockAddr, llarp_time_t> m_RecentlyClosed;
private: private:
std::shared_ptr<int> m_repeater_keepalive; std::shared_ptr<int> m_repeater_keepalive;

@ -49,15 +49,6 @@ namespace llarp
std::ostream& std::ostream&
print(std::ostream& stream, int level, int spaces) const; print(std::ostream& stream, int level, int spaces) const;
struct Hash
{
size_t
operator()(const AddressInfo& addr) const
{
return AlignedBuffer<PUBKEYSIZE>::Hash()(addr.pubkey);
}
};
}; };
void void
@ -76,3 +67,16 @@ namespace llarp
operator<(const AddressInfo& lhs, const AddressInfo& rhs); operator<(const AddressInfo& lhs, const AddressInfo& rhs);
} // namespace llarp } // namespace llarp
namespace std
{
template <>
struct hash<llarp::AddressInfo>
{
size_t
operator()(const llarp::AddressInfo& addr) const
{
return std::hash<llarp::PubKey>{}(addr.pubkey);
}
};
} // namespace std

@ -132,7 +132,7 @@ namespace llarp
// TODO: other utility functions left over from Addr which may be useful // TODO: other utility functions left over from Addr which may be useful
// IsBogon() const; // IsBogon() const;
// isPrivate() const; // isPrivate() const;
// struct Hash // std::hash
// to string / stream / etc // to string / stream / etc
bool bool
@ -141,15 +141,6 @@ namespace llarp
bool bool
operator==(const IpAddress& other) const; operator==(const IpAddress& other) const;
struct Hash
{
std::size_t
operator()(const IpAddress& address) const noexcept
{
return std::hash<std::string>{}(address.toString());
}
};
private: private:
bool m_empty = true; bool m_empty = true;
std::string m_ipAddress; std::string m_ipAddress;
@ -160,3 +151,16 @@ namespace llarp
operator<<(std::ostream& out, const IpAddress& address); operator<<(std::ostream& out, const IpAddress& address);
} // namespace llarp } // namespace llarp
namespace std
{
template <>
struct hash<llarp::IpAddress>
{
std::size_t
operator()(const llarp::IpAddress& address) const noexcept
{
return std::hash<std::string>{}(address.toString());
}
};
} // namespace std

@ -226,11 +226,11 @@ namespace llarp
ServiceProtocol() const ServiceProtocol() const
{ {
if (IsV4()) if (IsV4())
return service::eProtocolTrafficV4; return service::ProtocolType::TrafficV4;
if (IsV6()) if (IsV6())
return service::eProtocolTrafficV6; return service::ProtocolType::TrafficV6;
return service::eProtocolControl; return service::ProtocolType::Control;
} }
huint128_t huint128_t

@ -4,27 +4,42 @@
namespace llarp namespace llarp
{ {
template <> huint16_t
ToHost(nuint16_t n)
{
return xntohs(n);
}
huint32_t huint32_t
ToHost(nuint32_t n) ToHost(nuint32_t n)
{ {
return xntohl(n); return xntohl(n);
} }
template <> huint128_t
ToHost(nuint128_t n)
{
return {ntoh128(n.n)};
}
nuint16_t nuint16_t
ToNet(huint16_t h) ToNet(huint16_t h)
{ {
return xhtons(h); return xhtons(h);
} }
template <>
nuint32_t nuint32_t
ToNet(huint32_t h) ToNet(huint32_t h)
{ {
return xhtonl(h); return xhtonl(h);
} }
nuint128_t
ToNet(huint128_t h)
{
return {hton128(h.h)};
}
template <> template <>
void void
huint32_t::ToV6(V6Container& c) huint32_t::ToV6(V6Container& c)

@ -220,14 +220,13 @@ namespace llarp
return huint16_t{ntohs(x.n)}; return huint16_t{ntohs(x.n)};
} }
template <typename UInt_t> huint16_t ToHost(nuint16_t);
huint_t<UInt_t> huint32_t ToHost(nuint32_t);
ToHost(nuint_t<UInt_t> h); huint128_t ToHost(nuint128_t);
template <typename UInt_t>
nuint_t<UInt_t>
ToNet(huint_t<UInt_t> h);
nuint16_t ToNet(huint16_t);
nuint32_t ToNet(huint32_t);
nuint128_t ToNet(huint128_t);
} // namespace llarp } // namespace llarp
namespace std namespace std

@ -39,23 +39,32 @@ namespace llarp
init(); init();
} }
SockAddr::SockAddr(uint8_t a, uint8_t b, uint8_t c, uint8_t d) SockAddr::SockAddr(uint8_t a, uint8_t b, uint8_t c, uint8_t d, huint16_t port)
{ {
init(); init();
setIPv4(a, b, c, d); setIPv4(a, b, c, d);
setPort(port);
} }
SockAddr::SockAddr(uint8_t a, uint8_t b, uint8_t c, uint8_t d, uint16_t port) SockAddr::SockAddr(nuint32_t ip, nuint16_t port)
: SockAddr{a, b, c, d}
{ {
init();
setIPv4(ip);
setPort(port); setPort(port);
} }
SockAddr::SockAddr(uint32_t ip, uint16_t port) SockAddr::SockAddr(huint128_t ip, huint16_t port)
{ {
init(); init();
setIPv4(ip); setIPv6(ip);
setPort(ntohs(port)); setPort(port);
}
SockAddr::SockAddr(nuint128_t ip, nuint16_t port)
{
init();
setIPv6(ip);
setPort(port);
} }
SockAddr::SockAddr(std::string_view addr) SockAddr::SockAddr(std::string_view addr)
@ -66,13 +75,13 @@ namespace llarp
SockAddr::SockAddr(std::string_view addr, uint16_t port) SockAddr::SockAddr(std::string_view addr, uint16_t port)
{ {
init(); init();
setPort(port); setPort(huint16_t{port});
fromString(addr, false); fromString(addr, false);
} }
SockAddr::SockAddr(const AddressInfo& info) : SockAddr{info.ip} SockAddr::SockAddr(const AddressInfo& info) : SockAddr{info.ip}
{ {
setPort(info.port); setPort(huint16_t{info.port});
} }
SockAddr::SockAddr(const SockAddr& other) SockAddr::SockAddr(const SockAddr& other)
@ -138,12 +147,14 @@ namespace llarp
memcpy(&m_addr, &other, sizeof(sockaddr_in6)); memcpy(&m_addr, &other, sizeof(sockaddr_in6));
if (ipv6_is_mapped_ipv4(other.sin6_addr)) if (ipv6_is_mapped_ipv4(other.sin6_addr))
{
setIPv4( setIPv4(
other.sin6_addr.s6_addr[12], other.sin6_addr.s6_addr[12],
other.sin6_addr.s6_addr[13], other.sin6_addr.s6_addr[13],
other.sin6_addr.s6_addr[14], other.sin6_addr.s6_addr[14],
other.sin6_addr.s6_addr[15]); other.sin6_addr.s6_addr[15]);
setPort(ntohs(other.sin6_port)); m_addr4.sin_port = m_addr.sin6_port;
}
m_empty = false; m_empty = false;
return *this; return *this;
@ -161,7 +172,10 @@ namespace llarp
memcpy(&m_addr.sin6_addr.s6_addr, &other.s6_addr, sizeof(m_addr.sin6_addr.s6_addr)); memcpy(&m_addr.sin6_addr.s6_addr, &other.s6_addr, sizeof(m_addr.sin6_addr.s6_addr));
if (ipv6_is_mapped_ipv4(other)) if (ipv6_is_mapped_ipv4(other))
{
setIPv4(other.s6_addr[12], other.s6_addr[13], other.s6_addr[14], other.s6_addr[15]); setIPv4(other.s6_addr[12], other.s6_addr[13], other.s6_addr[14], other.s6_addr[15]);
m_addr4.sin_port = m_addr.sin6_port;
}
m_empty = false; m_empty = false;
return *this; return *this;
@ -302,14 +316,14 @@ namespace llarp
return m_empty; return m_empty;
} }
uint32_t nuint32_t
SockAddr::getIPv4() const SockAddr::getIPv4() const
{ {
return m_addr4.sin_addr.s_addr; return {m_addr4.sin_addr.s_addr};
} }
void void
SockAddr::setIPv4(uint32_t ip) SockAddr::setIPv4(nuint32_t ip)
{ {
uint8_t* ip6 = m_addr.sin6_addr.s6_addr; uint8_t* ip6 = m_addr.sin6_addr.s6_addr;
llarp::Zero(ip6, sizeof(m_addr.sin6_addr.s6_addr)); llarp::Zero(ip6, sizeof(m_addr.sin6_addr.s6_addr));
@ -317,10 +331,16 @@ namespace llarp
applyIPv4MapBytes(); applyIPv4MapBytes();
std::memcpy(ip6 + 12, &ip, 4); std::memcpy(ip6 + 12, &ip, 4);
m_addr4.sin_addr.s_addr = ip; m_addr4.sin_addr.s_addr = ip.n;
m_empty = false; m_empty = false;
} }
void
SockAddr::setIPv4(huint32_t ip)
{
setIPv4(ToNet(ip));
}
void void
SockAddr::setIPv4(uint8_t a, uint8_t b, uint8_t c, uint8_t d) SockAddr::setIPv4(uint8_t a, uint8_t b, uint8_t c, uint8_t d)
{ {
@ -339,10 +359,37 @@ namespace llarp
} }
void void
SockAddr::setPort(uint16_t port) SockAddr::setIPv6(huint128_t ip)
{
return setIPv6(ToNet(ip));
}
void
SockAddr::setIPv6(nuint128_t ip)
{
std::memcpy(&m_addr.sin6_addr, &ip, sizeof(m_addr.sin6_addr));
if (ipv6_is_mapped_ipv4(m_addr.sin6_addr))
{
setIPv4(
m_addr.sin6_addr.s6_addr[12],
m_addr.sin6_addr.s6_addr[13],
m_addr.sin6_addr.s6_addr[14],
m_addr.sin6_addr.s6_addr[15]);
m_addr4.sin_port = m_addr.sin6_port;
}
}
void
SockAddr::setPort(nuint16_t port)
{
m_addr.sin6_port = port.n;
m_addr4.sin_port = port.n;
}
void
SockAddr::setPort(huint16_t port)
{ {
m_addr.sin6_port = htons(port); setPort(ToNet(port));
m_addr4.sin_port = htons(port);
} }
uint16_t uint16_t

@ -27,11 +27,20 @@ namespace llarp
struct SockAddr struct SockAddr
{ {
SockAddr(); SockAddr();
SockAddr(uint8_t a, uint8_t b, uint8_t c, uint8_t d); // IPv4 constructors:
SockAddr(uint8_t a, uint8_t b, uint8_t c, uint8_t d, uint16_t port); SockAddr(uint8_t a, uint8_t b, uint8_t c, uint8_t d, huint16_t port = {0});
SockAddr(nuint32_t ip, nuint16_t port);
SockAddr(huint32_t ip, huint16_t port);
// IPv6 (or IPv4 if given a special IPv4-mapped IPv6 addr) in host order (including port).
SockAddr(huint128_t ip, huint16_t port = {0});
// IPv6 (or IPv4 if given a special IPv4-mapped IPv6 addr) in network order. NB: port is also
// in network order!
SockAddr(nuint128_t ip, nuint16_t port = {0});
// String ctors
SockAddr(std::string_view addr); SockAddr(std::string_view addr);
SockAddr(std::string_view addr, uint16_t port); SockAddr(std::string_view addr, uint16_t port); // port is in native (host) order
SockAddr(uint32_t ip, uint16_t port);
SockAddr(const AddressInfo&); SockAddr(const AddressInfo&);
@ -81,37 +90,47 @@ namespace llarp
void void
setIPv4(uint8_t a, uint8_t b, uint8_t c, uint8_t d); setIPv4(uint8_t a, uint8_t b, uint8_t c, uint8_t d);
/// port is in host order
void void
setIPv4(uint32_t ip); setIPv4(nuint32_t ip);
void void
setPort(uint16_t port); setIPv4(huint32_t ip);
/// port is in host order void
setIPv6(huint128_t ip);
void
setIPv6(nuint128_t ip);
void
setPort(huint16_t port);
void
setPort(nuint16_t port);
// Port is a native (host) value
void
setPort(uint16_t port)
{
setPort(huint16_t{port});
}
/// port is always returned in native (host) order
uint16_t uint16_t
getPort() const; getPort() const;
huint128_t
asIPv6() const;
/// in network order /// in network order
uint32_t nuint128_t
getIPv6() const;
nuint32_t
getIPv4() const; getIPv4() const;
/// in host order
huint128_t
asIPv6() const;
huint32_t huint32_t
asIPv4() const; asIPv4() const;
struct Hash
{
size_t
operator()(const SockAddr& addr) const noexcept
{
const std::hash<uint16_t> port{};
const std::hash<huint128_t> ip{};
return (port(addr.getPort()) << 3) ^ ip(addr.asIPv6());
}
};
private: private:
bool m_empty = true; bool m_empty = true;
sockaddr_in6 m_addr; sockaddr_in6 m_addr;
@ -128,3 +147,18 @@ namespace llarp
operator<<(std::ostream& out, const SockAddr& address); operator<<(std::ostream& out, const SockAddr& address);
} // namespace llarp } // namespace llarp
namespace std
{
template <>
struct hash<llarp::SockAddr>
{
size_t
operator()(const llarp::SockAddr& addr) const noexcept
{
const std::hash<uint16_t> port{};
const std::hash<llarp::huint128_t> ip{};
return (port(addr.getPort()) << 3) ^ ip(addr.asIPv6());
}
};
} // namespace std

@ -314,3 +314,9 @@ ntoh128(llarp::uint128_t i)
return {loSwapped, hiSwapped}; return {loSwapped, hiSwapped};
#endif #endif
} }
inline llarp::uint128_t
hton128(llarp::uint128_t i)
{
return ntoh128(i); // Same bit flipping as n-to-h
}

@ -115,16 +115,16 @@ namespace llarp
const auto& tx = p.hops[0].txID; const auto& tx = p.hops[0].txID;
const auto& rx = p.hops[0].rxID; const auto& rx = p.hops[0].rxID;
const auto& r = p.hops[0].upstream; const auto& r = p.hops[0].upstream;
const size_t rhash = std::accumulate(r.begin(), r.end(), 0, std::bit_xor<size_t>()); const size_t rhash = std::accumulate(r.begin(), r.end(), 0, std::bit_xor{});
return std::accumulate( return std::accumulate(
rx.begin(), rx.begin(),
rx.begin(), rx.begin(),
std::accumulate(tx.begin(), tx.end(), rhash, std::bit_xor<size_t>()), std::accumulate(tx.begin(), tx.end(), rhash, std::bit_xor{}),
std::bit_xor<size_t>()); std::bit_xor{});
} }
}; };
/// hash for std::shared_ptr /// hash for std::shared_ptr<Path>
struct Ptr_Hash struct Ptr_Hash
{ {
size_t size_t
@ -136,7 +136,7 @@ namespace llarp
} }
}; };
/// hash for std::shared_ptr by path endpoint /// hash for std::shared_ptr<Path> by path endpoint
struct Endpoint_Hash struct Endpoint_Hash
{ {
size_t size_t
@ -144,7 +144,7 @@ namespace llarp
{ {
if (p == nullptr) if (p == nullptr)
return 0; return 0;
return RouterID::Hash{}(p->Endpoint()); return std::hash<RouterID>{}(p->Endpoint());
} }
}; };

@ -109,7 +109,7 @@ namespace llarp
void void
RemovePathSet(PathSet_ptr set); RemovePathSet(PathSet_ptr set);
using TransitHopsMap_t = std::unordered_multimap<PathID_t, TransitHop_ptr, PathID_t::Hash>; using TransitHopsMap_t = std::unordered_multimap<PathID_t, TransitHop_ptr>;
struct SyncTransitMap_t struct SyncTransitMap_t
{ {
@ -129,7 +129,7 @@ namespace llarp
}; };
// maps path id -> pathset owner of path // maps path id -> pathset owner of path
using OwnedPathsMap_t = std::unordered_map<PathID_t, Path_ptr, PathID_t::Hash>; using OwnedPathsMap_t = std::unordered_map<PathID_t, Path_ptr>;
struct SyncOwnedPathsMap_t struct SyncOwnedPathsMap_t
{ {

@ -6,8 +6,13 @@
namespace llarp namespace llarp
{ {
struct PathID_t final : public AlignedBuffer<PATHIDSIZE> struct PathID_t final : public AlignedBuffer<PATHIDSIZE>
{ {};
using Hash = AlignedBuffer<PATHIDSIZE>::Hash;
};
} // namespace llarp } // namespace llarp
namespace std
{
template <>
struct hash<llarp::PathID_t> : hash<llarp::AlignedBuffer<llarp::PathID_t::SIZE>>
{};
} // namespace std

@ -13,6 +13,19 @@
#include <map> #include <map>
#include <tuple> #include <tuple>
namespace std
{
template <>
struct hash<std::pair<llarp::RouterID, llarp::PathID_t>>
{
size_t
operator()(const std::pair<llarp::RouterID, llarp::PathID_t>& i) const
{
return hash<llarp::RouterID>{}(i.first) ^ hash<llarp::PathID_t>{}(i.second);
}
};
} // namespace std
namespace llarp namespace llarp
{ {
struct RouterContact; struct RouterContact;
@ -294,29 +307,9 @@ namespace llarp
void void
TickPaths(AbstractRouter* r); TickPaths(AbstractRouter* r);
using PathInfo_t = std::pair<RouterID, PathID_t>;
struct PathInfoHash
{
size_t
operator()(const PathInfo_t& i) const
{
return RouterID::Hash()(i.first) ^ PathID_t::Hash()(i.second);
}
};
struct PathInfoEquals
{
bool
operator()(const PathInfo_t& left, const PathInfo_t& right) const
{
return left.first == right.first && left.second == right.second;
}
};
using Mtx_t = util::NullMutex; using Mtx_t = util::NullMutex;
using Lock_t = util::NullLock; using Lock_t = util::NullLock;
using PathMap_t = std::unordered_map<PathInfo_t, Path_ptr, PathInfoHash, PathInfoEquals>; using PathMap_t = std::unordered_map<std::pair<RouterID, PathID_t>, Path_ptr>;
mutable Mtx_t m_PathsMutex; mutable Mtx_t m_PathsMutex;
PathMap_t m_Paths; PathMap_t m_Paths;
}; };

@ -30,28 +30,6 @@ namespace llarp
std::ostream& std::ostream&
print(std::ostream& stream, int level, int spaces) const; print(std::ostream& stream, int level, int spaces) const;
struct PathIDHash
{
std::size_t
operator()(const PathID_t& a) const
{
return AlignedBuffer<PathID_t::SIZE>::Hash()(a);
}
};
struct Hash
{
std::size_t
operator()(TransitHopInfo const& a) const
{
std::size_t idx0 = RouterID::Hash()(a.upstream);
std::size_t idx1 = RouterID::Hash()(a.downstream);
std::size_t idx2 = PathIDHash()(a.txID);
std::size_t idx3 = PathIDHash()(a.rxID);
return idx0 ^ idx1 ^ idx2 ^ idx3;
}
};
}; };
inline bool inline bool
@ -235,3 +213,18 @@ namespace llarp
} }
} // namespace path } // namespace path
} // namespace llarp } // namespace llarp
namespace std
{
template <>
struct hash<llarp::path::TransitHopInfo>
{
std::size_t
operator()(llarp::path::TransitHopInfo const& a) const
{
hash<llarp::RouterID> RHash{};
hash<llarp::PathID_t> PHash{};
return RHash(a.upstream) ^ RHash(a.downstream) ^ PHash(a.txID) ^ PHash(a.rxID);
}
};
} // namespace std

@ -127,7 +127,7 @@ namespace llarp
ExtractStatus() const; ExtractStatus() const;
private: private:
std::unordered_map<RouterID, PeerStats, RouterID::Hash> m_peerStats; std::unordered_map<RouterID, PeerStats> m_peerStats;
mutable std::mutex m_statsLock; mutable std::mutex m_statsLock;
std::unique_ptr<PeerDbStorage> m_storage; std::unique_ptr<PeerDbStorage> m_storage;

@ -128,10 +128,9 @@ namespace llarp
mutable util::Mutex _mutex; // protects pendingSessionMessageQueues mutable util::Mutex _mutex; // protects pendingSessionMessageQueues
std::unordered_map<RouterID, MessageQueue, RouterID::Hash> pendingSessionMessageQueues std::unordered_map<RouterID, MessageQueue> pendingSessionMessageQueues GUARDED_BY(_mutex);
GUARDED_BY(_mutex);
std::unordered_map<PathID_t, MessageQueue, PathID_t::Hash> outboundMessageQueues; std::unordered_map<PathID_t, MessageQueue> outboundMessageQueues;
std::queue<PathID_t> roundRobinOrder; std::queue<PathID_t> roundRobinOrder;

@ -100,11 +100,10 @@ namespace llarp
mutable util::Mutex _mutex; // protects pendingSessions, pendingCallbacks mutable util::Mutex _mutex; // protects pendingSessions, pendingCallbacks
std::unordered_map<RouterID, std::shared_ptr<PendingSession>, RouterID::Hash> pendingSessions std::unordered_map<RouterID, std::shared_ptr<PendingSession>> pendingSessions
GUARDED_BY(_mutex); GUARDED_BY(_mutex);
std::unordered_map<RouterID, CallbacksQueue, RouterID::Hash> pendingCallbacks std::unordered_map<RouterID, CallbacksQueue> pendingCallbacks GUARDED_BY(_mutex);
GUARDED_BY(_mutex);
AbstractRouter* _router = nullptr; AbstractRouter* _router = nullptr;
ILinkManager* _linkManager = nullptr; ILinkManager* _linkManager = nullptr;

@ -114,8 +114,7 @@ namespace llarp
std::set<RouterContact> _bootstrapRCList; std::set<RouterContact> _bootstrapRCList;
std::unordered_set<RouterID> _bootstrapRouterIDList; std::unordered_set<RouterID> _bootstrapRouterIDList;
std::unordered_map<RouterID, CallbacksQueue, RouterID::Hash> pendingCallbacks std::unordered_map<RouterID, CallbacksQueue> pendingCallbacks GUARDED_BY(_mutex);
GUARDED_BY(_mutex);
bool useWhitelist = false; bool useWhitelist = false;
bool isServiceNode = false; bool isServiceNode = false;
@ -123,7 +122,7 @@ namespace llarp
std::unordered_set<RouterID> whitelistRouters GUARDED_BY(_mutex); std::unordered_set<RouterID> whitelistRouters GUARDED_BY(_mutex);
using TimePoint = std::chrono::steady_clock::time_point; using TimePoint = std::chrono::steady_clock::time_point;
std::unordered_map<RouterID, TimePoint, RouterID::Hash> _routerLookupTimes; std::unordered_map<RouterID, TimePoint> _routerLookupTimes;
}; };
} // namespace llarp } // namespace llarp

@ -797,7 +797,7 @@ namespace llarp
}); });
// find all deregistered relays // find all deregistered relays
std::unordered_set<PubKey, PubKey::Hash> closePeers; std::unordered_set<PubKey> closePeers;
_linkManager.ForEachPeer([&](auto session) { _linkManager.ForEachPeer([&](auto session) {
if (whitelistRouters and not gotWhitelist) if (whitelistRouters and not gotWhitelist)

@ -83,15 +83,6 @@ namespace llarp
Clear(); Clear();
} }
struct Hash
{
size_t
operator()(const RouterContact& r) const
{
return PubKey::Hash()(r.pubkey);
}
};
// advertised addresses // advertised addresses
std::vector<AddressInfo> addrs; std::vector<AddressInfo> addrs;
// network identifier // network identifier
@ -240,3 +231,16 @@ namespace llarp
using RouterLookupHandler = std::function<void(const std::vector<RouterContact>&)>; using RouterLookupHandler = std::function<void(const std::vector<RouterContact>&)>;
} // namespace llarp } // namespace llarp
namespace std
{
template <>
struct hash<llarp::RouterContact>
{
size_t
operator()(const llarp::RouterContact& r) const
{
return std::hash<llarp::PubKey>{}(r.pubkey);
}
};
} // namespace std

@ -11,8 +11,7 @@ namespace llarp
using Data = std::array<byte_t, SIZE>; using Data = std::array<byte_t, SIZE>;
RouterID() RouterID() = default;
{}
RouterID(const byte_t* buf) : AlignedBuffer<SIZE>(buf) RouterID(const byte_t* buf) : AlignedBuffer<SIZE>(buf)
{} {}
@ -44,8 +43,6 @@ namespace llarp
{ {
return out << id.ToString(); return out << id.ToString();
} }
using Hash = AlignedBuffer<SIZE>::Hash;
}; };
inline bool inline bool
@ -59,13 +56,6 @@ namespace llarp
namespace std namespace std
{ {
template <> template <>
struct hash<llarp::RouterID> struct hash<llarp::RouterID> : hash<llarp::AlignedBuffer<llarp::RouterID::SIZE>>
{ {};
size_t
operator()(const llarp::RouterID& id) const
{
const llarp::RouterID::Hash h{};
return h(id);
}
};
} // namespace std } // namespace std

@ -65,7 +65,7 @@ namespace llarp::rpc
return; return;
} }
if (msg->proto != llarp::service::eProtocolAuth) if (msg->proto != llarp::service::ProtocolType::Auth)
{ {
// not an auth message, reject // not an auth message, reject
reply(service::AuthResult{service::AuthResultCode::eAuthRejected, "protocol error"}); reply(service::AuthResult{service::AuthResultCode::eAuthRejected, "protocol error"});

@ -15,7 +15,7 @@ namespace llarp::rpc
{ {
using LMQ_ptr = std::shared_ptr<oxenmq::OxenMQ>; using LMQ_ptr = std::shared_ptr<oxenmq::OxenMQ>;
using Endpoint_ptr = std::shared_ptr<llarp::service::Endpoint>; using Endpoint_ptr = std::shared_ptr<llarp::service::Endpoint>;
using Whitelist_t = std::unordered_set<llarp::service::Address, llarp::service::Address::Hash>; using Whitelist_t = std::unordered_set<llarp::service::Address>;
explicit EndpointAuthRPC( explicit EndpointAuthRPC(
std::string url, std::string url,

@ -89,15 +89,6 @@ namespace llarp
{ {
return RouterID(as_array()); return RouterID(as_array());
} }
struct Hash
{
size_t
operator()(const Address& buf) const
{
return std::accumulate(buf.begin(), buf.end(), 0, std::bit_xor<size_t>());
}
};
}; };
} // namespace service } // namespace service
@ -111,7 +102,7 @@ namespace std
size_t size_t
operator()(const llarp::service::Address& addr) const operator()(const llarp::service::Address& addr) const
{ {
return llarp::service::Address::Hash{}(addr); return std::accumulate(addr.begin(), addr.end(), 0, std::bit_xor{});
} }
}; };
} // namespace std } // namespace std

@ -958,14 +958,14 @@ namespace llarp
bool bool
Endpoint::ProcessDataMessage(std::shared_ptr<ProtocolMessage> msg) Endpoint::ProcessDataMessage(std::shared_ptr<ProtocolMessage> msg)
{ {
if ((msg->proto == eProtocolExit if ((msg->proto == ProtocolType::Exit
&& (m_state->m_ExitEnabled || m_ExitMap.ContainsValue(msg->sender.Addr()))) && (m_state->m_ExitEnabled || m_ExitMap.ContainsValue(msg->sender.Addr())))
|| msg->proto == eProtocolTrafficV4 || msg->proto == eProtocolTrafficV6) || msg->proto == ProtocolType::TrafficV4 || msg->proto == ProtocolType::TrafficV6)
{ {
m_InboundTrafficQueue.tryPushBack(std::move(msg)); m_InboundTrafficQueue.tryPushBack(std::move(msg));
return true; return true;
} }
if (msg->proto == eProtocolControl) if (msg->proto == ProtocolType::Control)
{ {
// TODO: implement me (?) // TODO: implement me (?)
// right now it's just random noise // right now it's just random noise
@ -1014,7 +1014,7 @@ namespace llarp
msg.PutBuffer(reason); msg.PutBuffer(reason);
f.N.Randomize(); f.N.Randomize();
f.C.Zero(); f.C.Zero();
msg.proto = eProtocolAuth; msg.proto = ProtocolType::Auth;
if (not GetReplyIntroFor(tag, msg.introReply)) if (not GetReplyIntroFor(tag, msg.introReply))
{ {
LogError("Failed to send auth reply: no reply intro"); LogError("Failed to send auth reply: no reply intro");
@ -1252,7 +1252,7 @@ namespace llarp
return false; return false;
pkt.UpdateIPv4Address(src, dst); pkt.UpdateIPv4Address(src, dst);
/// TODO: V6 /// TODO: V6
return HandleInboundPacket(tag, pkt.ConstBuffer(), eProtocolTrafficV4, 0); return HandleInboundPacket(tag, pkt.ConstBuffer(), ProtocolType::TrafficV4, 0);
}, },
Router(), Router(),
numDesiredPaths, numDesiredPaths,
@ -1294,31 +1294,25 @@ namespace llarp
void Endpoint::Pump(llarp_time_t) void Endpoint::Pump(llarp_time_t)
{ {
const auto& sessions = m_state->m_SNodeSessions; FlushRecvData();
auto& queue = m_InboundTrafficQueue; // send downstream packets to user for snode
for (const auto& [router, session] : m_state->m_SNodeSessions)
auto epPump = [&]() { session.first->FlushDownstream();
FlushRecvData(); // send downstream traffic to user for hidden service
// send downstream packets to user for snode while (not m_InboundTrafficQueue.empty())
for (const auto& item : sessions) {
item.second.first->FlushDownstream(); auto msg = m_InboundTrafficQueue.popFront();
// send downstream traffic to user for hidden service const llarp_buffer_t buf(msg->payload);
while (not queue.empty()) HandleInboundPacket(msg->tag, buf, msg->proto, msg->seqno);
{ }
auto msg = queue.popFront();
const llarp_buffer_t buf(msg->payload);
HandleInboundPacket(msg->tag, buf, msg->proto, msg->seqno);
}
};
epPump();
auto router = Router(); auto router = Router();
// TODO: locking on this container // TODO: locking on this container
for (const auto& item : m_state->m_RemoteSessions) for (const auto& [addr, outctx] : m_state->m_RemoteSessions)
item.second->FlushUpstream(); outctx->FlushUpstream();
// TODO: locking on this container // TODO: locking on this container
for (const auto& item : sessions) for (const auto& [router, session] : m_state->m_SNodeSessions)
item.second.first->FlushUpstream(); session.first->FlushUpstream();
// send queue flush // send queue flush
while (not m_SendQueue.empty()) while (not m_SendQueue.empty())
@ -1332,17 +1326,6 @@ namespace llarp
router->linkManager().PumpLinks(); router->linkManager().PumpLinks();
} }
bool
Endpoint::EnsureConvo(
const AlignedBuffer<32> /*addr*/, bool snode, ConvoEventListener_ptr /*ev*/)
{
if (snode)
{}
// TODO: something meaningful
return false;
}
std::optional<ConvoTag> std::optional<ConvoTag>
Endpoint::GetBestConvoTagForService(Address remote) const Endpoint::GetBestConvoTagForService(Address remote) const
{ {

@ -247,9 +247,6 @@ namespace llarp
void void
HandlePathBuilt(path::Path_ptr path) override; HandlePathBuilt(path::Path_ptr path) override;
bool
EnsureConvo(const AlignedBuffer<32> addr, bool snode, ConvoEventListener_ptr ev);
bool bool
SendTo(ConvoTag tag, const llarp_buffer_t& pkt, ProtocolType t); SendTo(ConvoTag tag, const llarp_buffer_t& pkt, ProtocolType t);
@ -445,7 +442,7 @@ namespace llarp
bool m_PublishIntroSet = true; bool m_PublishIntroSet = true;
std::unique_ptr<EndpointState> m_state; std::unique_ptr<EndpointState> m_state;
std::shared_ptr<IAuthPolicy> m_AuthPolicy; std::shared_ptr<IAuthPolicy> m_AuthPolicy;
std::unordered_map<Address, AuthInfo, Address::Hash> m_RemoteAuthInfos; std::unordered_map<Address, AuthInfo> m_RemoteAuthInfos;
/// (lns name, optional exit range, optional auth info) for looking up on startup /// (lns name, optional exit range, optional auth info) for looking up on startup
std::unordered_map<std::string, std::pair<std::optional<IPRange>, std::optional<AuthInfo>>> std::unordered_map<std::string, std::pair<std::optional<IPRange>, std::optional<AuthInfo>>>
@ -466,7 +463,7 @@ namespace llarp
const IntroSet& introSet() const; const IntroSet& introSet() const;
IntroSet& introSet(); IntroSet& introSet();
using ConvoMap = std::unordered_map< ConvoTag, Session, ConvoTag::Hash >; using ConvoMap = std::unordered_map<ConvoTag, Session>;
const ConvoMap& Sessions() const; const ConvoMap& Sessions() const;
ConvoMap& Sessions(); ConvoMap& Sessions();
// clang-format on // clang-format on

@ -43,10 +43,10 @@ namespace llarp
SNodeSessions m_SNodeSessions; SNodeSessions m_SNodeSessions;
std::unordered_multimap<Address, PathEnsureHook, Address::Hash> m_PendingServiceLookups; std::unordered_multimap<Address, PathEnsureHook> m_PendingServiceLookups;
std::unordered_map<Address, llarp_time_t, Address::Hash> m_LastServiceLookupTimes; std::unordered_map<Address, llarp_time_t> m_LastServiceLookupTimes;
std::unordered_map<RouterID, uint32_t, RouterID::Hash> m_ServiceLookupFails; std::unordered_map<RouterID, uint32_t> m_ServiceLookupFails;
PendingRouters m_PendingRouters; PendingRouters m_PendingRouters;

@ -30,26 +30,25 @@ namespace llarp
using SendMessageQueue_t = thread::Queue<SendEvent_t>; using SendMessageQueue_t = thread::Queue<SendEvent_t>;
using PendingBufferQueue = std::deque<PendingBuffer>; using PendingBufferQueue = std::deque<PendingBuffer>;
using PendingTraffic = std::unordered_map<Address, PendingBufferQueue, Address::Hash>; using PendingTraffic = std::unordered_map<Address, PendingBufferQueue>;
using ProtocolMessagePtr = std::shared_ptr<ProtocolMessage>; using ProtocolMessagePtr = std::shared_ptr<ProtocolMessage>;
using RecvPacketQueue_t = thread::Queue<ProtocolMessagePtr>; using RecvPacketQueue_t = thread::Queue<ProtocolMessagePtr>;
using PendingRouters = std::unordered_map<RouterID, RouterLookupJob, RouterID::Hash>; using PendingRouters = std::unordered_map<RouterID, RouterLookupJob>;
using PendingLookups = std::unordered_map<uint64_t, std::unique_ptr<IServiceLookup>>; using PendingLookups = std::unordered_map<uint64_t, std::unique_ptr<IServiceLookup>>;
using Sessions = using Sessions = std::unordered_multimap<Address, std::shared_ptr<OutboundContext>>;
std::unordered_multimap<Address, std::shared_ptr<OutboundContext>, Address::Hash>;
using SNodeSessionValue = std::pair<std::shared_ptr<exit::BaseSession>, ConvoTag>; using SNodeSessionValue = std::pair<std::shared_ptr<exit::BaseSession>, ConvoTag>;
using SNodeSessions = std::unordered_multimap<RouterID, SNodeSessionValue, RouterID::Hash>; using SNodeSessions = std::unordered_multimap<RouterID, SNodeSessionValue>;
using ConvoMap = std::unordered_map<ConvoTag, Session, ConvoTag::Hash>; using ConvoMap = std::unordered_map<ConvoTag, Session>;
/// set of outbound addresses to maintain to /// set of outbound addresses to maintain to
using OutboundSessions_t = std::unordered_set<Address, Address::Hash>; using OutboundSessions_t = std::unordered_set<Address>;
using PathEnsureHook = std::function<void(Address, OutboundContext*)>; using PathEnsureHook = std::function<void(Address, OutboundContext*)>;

@ -12,7 +12,8 @@ namespace llarp
{ {
namespace service namespace service
{ {
using ConvoTag = AlignedBuffer<16>; struct ConvoTag final : AlignedBuffer<16>
{};
struct ProtocolMessage; struct ProtocolMessage;
struct RecvDataEvent struct RecvDataEvent

@ -70,15 +70,6 @@ namespace llarp
{ {
return pathID != other.pathID || router != other.router; return pathID != other.pathID || router != other.router;
} }
struct Hash
{
size_t
operator()(const Introduction& i) const
{
return PubKey::Hash()(i.router) ^ PathID_t::Hash()(i.pathID);
}
};
}; };
inline std::ostream& inline std::ostream&
@ -88,3 +79,16 @@ namespace llarp
} }
} // namespace service } // namespace service
} // namespace llarp } // namespace llarp
namespace std
{
template <>
struct hash<llarp::service::Introduction>
{
size_t
operator()(const llarp::service::Introduction& i) const
{
return std::hash<llarp::PubKey>{}(i.router) ^ std::hash<llarp::PathID_t>{}(i.pathID);
}
};
} // namespace std

@ -327,7 +327,7 @@ namespace llarp
Encrypted<64> tmp; Encrypted<64> tmp;
tmp.Randomize(); tmp.Randomize();
llarp_buffer_t buf(tmp.data(), tmp.size()); llarp_buffer_t buf(tmp.data(), tmp.size());
AsyncEncryptAndSendTo(buf, eProtocolControl); AsyncEncryptAndSendTo(buf, ProtocolType::Control);
} }
} }
} }
@ -549,7 +549,7 @@ namespace llarp
ProtocolMessage msg{}; ProtocolMessage msg{};
if (frame.DecryptPayloadInto(sessionKey, msg)) if (frame.DecryptPayloadInto(sessionKey, msg))
{ {
if (msg.proto == eProtocolAuth and not msg.payload.empty()) if (msg.proto == ProtocolType::Auth and not msg.payload.empty())
{ {
result.reason = std::string{ result.reason = std::string{
reinterpret_cast<const char*>(msg.payload.data()), msg.payload.size()}; reinterpret_cast<const char*>(msg.payload.data()), msg.payload.size()};
@ -572,7 +572,7 @@ namespace llarp
authResultListener = nullptr; authResultListener = nullptr;
hook = [handler](std::shared_ptr<ProtocolMessage> msg) { hook = [handler](std::shared_ptr<ProtocolMessage> msg) {
AuthResult result{AuthResultCode::eAuthAccepted, "OK"}; AuthResult result{AuthResultCode::eAuthAccepted, "OK"};
if (msg->proto == eProtocolAuth and not msg->payload.empty()) if (msg->proto == ProtocolType::Auth and not msg->payload.empty())
{ {
result.reason = std::string{ result.reason = std::string{
reinterpret_cast<const char*>(msg->payload.data()), msg->payload.size()}; reinterpret_cast<const char*>(msg->payload.data()), msg->payload.size()};
@ -603,7 +603,7 @@ namespace llarp
void void
OutboundContext::SendPacketToRemote(const llarp_buffer_t& buf) OutboundContext::SendPacketToRemote(const llarp_buffer_t& buf)
{ {
AsyncEncryptAndSendTo(buf, eProtocolExit); AsyncEncryptAndSendTo(buf, ProtocolType::Exit);
} }
} // namespace service } // namespace service

@ -135,7 +135,7 @@ namespace llarp
uint64_t m_UpdateIntrosetTX = 0; uint64_t m_UpdateIntrosetTX = 0;
IntroSet currentIntroSet; IntroSet currentIntroSet;
Introduction m_NextIntro; Introduction m_NextIntro;
std::unordered_map<Introduction, llarp_time_t, Introduction::Hash> m_BadIntros; std::unordered_map<Introduction, llarp_time_t> m_BadIntros;
llarp_time_t lastShift = 0s; llarp_time_t lastShift = 0s;
uint16_t m_LookupFails = 0; uint16_t m_LookupFails = 0;
uint16_t m_BuildFails = 0; uint16_t m_BuildFails = 0;

@ -37,7 +37,7 @@ namespace llarp
ProtocolMessage(const ConvoTag& tag); ProtocolMessage(const ConvoTag& tag);
ProtocolMessage(); ProtocolMessage();
~ProtocolMessage(); ~ProtocolMessage();
ProtocolType proto = eProtocolTrafficV4; ProtocolType proto = ProtocolType::TrafficV4;
llarp_time_t queued = 0s; llarp_time_t queued = 0s;
std::vector<byte_t> payload; std::vector<byte_t> payload;
Introduction introReply; Introduction introReply;

@ -4,11 +4,14 @@
namespace llarp::service namespace llarp::service
{ {
using ProtocolType = uint64_t; // Supported protocol types; the values are given explicitly because they are specifically used
// when sending over the wire.
constexpr ProtocolType eProtocolControl = 0UL; enum class ProtocolType : uint64_t
constexpr ProtocolType eProtocolTrafficV4 = 1UL; {
constexpr ProtocolType eProtocolTrafficV6 = 2UL; Control = 0UL,
constexpr ProtocolType eProtocolExit = 3UL; TrafficV4 = 1UL,
constexpr ProtocolType eProtocolAuth = 4UL; TrafficV6 = 2UL,
Exit = 3UL,
Auth = 4UL,
};
} // namespace llarp::service } // namespace llarp::service

@ -114,7 +114,7 @@ namespace llarp
{ {
// send auth message // send auth message
const llarp_buffer_t authdata{maybe->token}; const llarp_buffer_t authdata{maybe->token};
AsyncGenIntro(authdata, eProtocolAuth); AsyncGenIntro(authdata, ProtocolType::Auth);
authResultListener = resultHandler; authResultListener = resultHandler;
} }
else else
@ -134,7 +134,7 @@ namespace llarp
{ {
// send auth message // send auth message
const llarp_buffer_t authdata(maybe->token); const llarp_buffer_t authdata(maybe->token);
AsyncGenIntro(authdata, eProtocolAuth); AsyncGenIntro(authdata, ProtocolType::Auth);
} }
else else
{ {

@ -49,8 +49,13 @@ namespace llarp
{ {
return data()[0] == 0; return data()[0] == 0;
} }
using Hash = AlignedBuffer<SIZE>::Hash;
}; };
} // namespace service } // namespace service
} // namespace llarp } // namespace llarp
namespace std
{
template <>
struct hash<llarp::service::Tag> : hash<llarp::AlignedBuffer<llarp::service::Tag::SIZE>>
{};
} // namespace std

@ -83,8 +83,8 @@ namespace tooling
GetRelayRCs(); GetRelayRCs();
std::mutex routerMutex; std::mutex routerMutex;
std::unordered_map<llarp::RouterID, Context_ptr, llarp::RouterID::Hash> relays; std::unordered_map<llarp::RouterID, Context_ptr> relays;
std::unordered_map<llarp::RouterID, Context_ptr, llarp::RouterID::Hash> clients; std::unordered_map<llarp::RouterID, Context_ptr> clients;
std::vector<std::thread> routerMainThreads; std::vector<std::thread> routerMainThreads;

@ -289,18 +289,22 @@ namespace llarp
return stream; return stream;
} }
struct Hash
{
std::size_t
operator()(const AlignedBuffer& buf) const noexcept
{
std::size_t h = 0;
std::memcpy(&h, buf.data(), sizeof(std::size_t));
return h;
}
};
private: private:
Data m_data; Data m_data;
}; };
} // namespace llarp } // namespace llarp
namespace std
{
template <size_t sz>
struct hash<llarp::AlignedBuffer<sz>>
{
std::size_t
operator()(const llarp::AlignedBuffer<sz>& buf) const noexcept
{
std::size_t h = 0;
std::memcpy(&h, buf.data(), sizeof(std::size_t));
return h;
}
};
} // namespace std

@ -6,6 +6,7 @@
#include <llarp/util/logging/logger.hpp> #include <llarp/util/logging/logger.hpp>
#include "mem.hpp" #include "mem.hpp"
#include <type_traits>
#include <fstream> #include <fstream>
#include <set> #include <set>
#include <vector> #include <vector>
@ -41,7 +42,12 @@ namespace llarp
bool bool
BEncodeWriteDictInt(const char* k, const Int_t& i, llarp_buffer_t* buf) BEncodeWriteDictInt(const char* k, const Int_t& i, llarp_buffer_t* buf)
{ {
return bencode_write_bytestring(buf, k, 1) && bencode_write_uint64(buf, i); if (!bencode_write_bytestring(buf, k, 1))
return false;
if constexpr (std::is_enum_v<Int_t>)
return bencode_write_uint64(buf, static_cast<std::underlying_type_t<Int_t>>(i));
else
return bencode_write_uint64(buf, i);
} }
template <typename List_t> template <typename List_t>
@ -92,7 +98,7 @@ namespace llarp
return false; return false;
} }
i = Int_t(read_i); i = static_cast<Int_t>(read_i);
read = true; read = true;
} }
return true; return true;

@ -7,7 +7,7 @@ namespace llarp
{ {
namespace util namespace util
{ {
template <typename Val_t, typename Hash_t = typename Val_t::Hash> template <typename Val_t, typename Hash_t = std::hash<Val_t>>
struct DecayingHashSet struct DecayingHashSet
{ {
using Time_t = std::chrono::milliseconds; using Time_t = std::chrono::milliseconds;

@ -5,7 +5,7 @@
namespace llarp::util namespace llarp::util
{ {
template <typename Key_t, typename Value_t, typename Hash_t = typename Key_t::Hash> template <typename Key_t, typename Value_t, typename Hash_t = std::hash<Key_t>>
struct DecayingHashTable struct DecayingHashTable
{ {
DecayingHashTable(std::chrono::milliseconds cacheInterval = 1h) : m_CacheInterval(cacheInterval) DecayingHashTable(std::chrono::milliseconds cacheInterval = 1h) : m_CacheInterval(cacheInterval)

@ -1,8 +1,9 @@
#include <common.hpp> #include <common.hpp>
#include <llarp.hpp> #include <llarp.hpp>
#include <llarp/tooling/hive_context.hpp> #include <llarp/tooling/hive_context.hpp>
#include <llarp/router/router.cpp> #include <llarp/router/router.hpp>
#include <llarp/handlers/pyhandler.hpp> #include <llarp/handlers/pyhandler.hpp>
#include "service/protocol_type.hpp"
namespace llarp namespace llarp
{ {
void void
@ -28,7 +29,8 @@ namespace llarp
std::vector<byte_t> buf; std::vector<byte_t> buf;
buf.resize(pkt.size()); buf.resize(pkt.size());
std::copy_n(pkt.c_str(), pkt.size(), buf.data()); std::copy_n(pkt.c_str(), pkt.size(), buf.data());
return ep and ep->SendToServiceOrQueue(to, std::move(buf), service::eProtocolControl); return ep
and ep->SendToServiceOrQueue(to, std::move(buf), service::ProtocolType::Control);
}) })
.def( .def(
"AddEndpoint", "AddEndpoint",

@ -2,6 +2,7 @@
#include <net/ip.hpp> #include <net/ip.hpp>
#include <net/ip_range.hpp> #include <net/ip_range.hpp>
#include <net/net.hpp> #include <net/net.hpp>
#include <oxenmq/hex.h>
#include <catch2/catch.hpp> #include <catch2/catch.hpp>
@ -102,3 +103,30 @@ TEST_CASE("Bogon")
REQUIRE_FALSE(llarp::IsIPv4Bogon(llarp::ipaddr_ipv4_bits(79, 12, 3, 4))); REQUIRE_FALSE(llarp::IsIPv4Bogon(llarp::ipaddr_ipv4_bits(79, 12, 3, 4)));
} }
} }
TEST_CASE("uint128_t")
{
SECTION("layout")
{
llarp::uint128_t i{0x0011223f44556677ULL, 0x8899aabbc3ddeeffULL};
REQUIRE(oxenmq::to_hex(std::string_view{reinterpret_cast<const char*>(&i), sizeof(i)}) ==
#ifdef __BIG_ENDIAN__
"0011223f445566778899aabbc3ddeeff"
#else
"ffeeddc3bbaa9988776655443f221100"
#endif
);
}
SECTION("ntoh")
{
llarp::uint128_t i{0x0011223f44556677ULL, 0x8899aabbc3ddeeffULL};
auto be = ntoh128(i);
REQUIRE(be == llarp::uint128_t{0xffeeddc3bbaa9988ULL, 0x776655443f221100ULL});
}
SECTION("hton")
{
llarp::uint128_t i{0x0011223f44556677ULL, 0x8899aabbc3ddeeffULL};
auto be = ntoh128(i);
REQUIRE(be == llarp::uint128_t{0xffeeddc3bbaa9988ULL, 0x776655443f221100ULL});
}
}

@ -162,7 +162,7 @@ TEMPLATE_LIST_TEST_CASE("AlignedBuffer", "[AlignedBuffer]", TestSizes)
SECTION("TestHash") SECTION("TestHash")
{ {
using Map_t = std::unordered_map<Buffer, int, typename Buffer::Hash>; using Map_t = std::unordered_map<Buffer, int>;
Buffer k, other_k; Buffer k, other_k;
k.Randomize(); k.Randomize();

Loading…
Cancel
Save