Remove data() conversions from llarp::AlignedBuffer

pull/190/head
Michael 5 years ago
parent e4a23ad0fd
commit 334161c9bb
No known key found for this signature in database
GPG Key ID: 2D51757B47E2434C

@ -137,7 +137,7 @@ namespace llarp
/* encryption key */
if(!bencode_write_bytestring(buff, "e", 1))
return false;
if(!bencode_write_bytestring(buff, pubkey, PUBKEYSIZE))
if(!bencode_write_bytestring(buff, pubkey.as_array().data(), PUBKEYSIZE))
return false;
/** ip */
ipstr = inet_ntop(AF_INET6, (void *)&ip, ipbuff, sizeof(ipbuff));

@ -139,6 +139,18 @@ namespace llarp
return *this;
}
byte_t& operator[](size_t idx)
{
assert(idx < SIZE);
return as_array()[idx];
}
const byte_t& operator[](size_t idx) const
{
assert(idx < SIZE);
return as_array()[idx];
}
static constexpr size_t
size()
{
@ -184,18 +196,6 @@ namespace llarp
randombytes(as_array().data(), SIZE);
}
byte_t*
data()
{
return as_array().data();
}
const byte_t*
data() const
{
return as_array().data();
}
operator const byte_t*() const
{
return as_array().data();
@ -216,6 +216,30 @@ namespace llarp
return as_array();
}
typename Data::iterator
begin()
{
return as_array().begin();
}
typename Data::iterator
end()
{
return as_array().end();
}
typename Data::const_iterator
begin() const
{
return as_array().cbegin();
}
typename Data::const_iterator
end() const
{
return as_array().cend();
}
bool
BEncode(llarp_buffer_t* buf) const
{

@ -7,7 +7,7 @@ namespace llarp
bool
PubKey::FromString(const std::string& str)
{
return HexDecode(str.c_str(), data(), size());
return HexDecode(str.c_str(), as_array().data(), size());
}
std::string
@ -31,7 +31,8 @@ namespace llarp
if(sz == size())
{
// is raw buffer
f.read((char*)data(), 64);
std::copy(std::istream_iterator< byte_t >(f),
std::istream_iterator< byte_t >(), begin());
return true;
}
byte_t tmp[128];

@ -142,8 +142,9 @@ namespace llarp
struct PubKey final : public AlignedBuffer< PUBKEYSIZE >
{
PubKey() : AlignedBuffer< PUBKEYSIZE >(){};
PubKey(const byte_t *ptr) : AlignedBuffer< PUBKEYSIZE >(ptr){};
PubKey() : AlignedBuffer< SIZE >(){}
PubKey(const byte_t *ptr) : AlignedBuffer< SIZE >(ptr){}
PubKey(const Data& data) : AlignedBuffer< SIZE >(data){}
std::string
ToString() const;
@ -159,13 +160,13 @@ namespace llarp
operator RouterID() const
{
return RouterID(data());
return RouterID(as_array());
}
PubKey &
operator=(const byte_t *ptr)
{
memcpy(data(), ptr, size());
std::copy(ptr, ptr + SIZE, as_array().begin());
return *this;
}
};
@ -188,7 +189,7 @@ namespace llarp
SecretKey &
operator=(const byte_t *ptr)
{
memcpy(data(), ptr, size());
std::copy(ptr, ptr + SIZE, as_array().begin());
return *this;
}
};

@ -92,8 +92,9 @@ namespace llarp
uint64_t txid = ++ids;
TXOwner peer(askpeer, txid);
TXOwner whoasked(OurKey(), txid);
pendingExploreLookups.NewTX(peer, whoasked, askpeer.data(),
new ExploreNetworkJob(askpeer.data(), this));
pendingExploreLookups.NewTX(
peer, whoasked, askpeer.as_array(),
new ExploreNetworkJob(askpeer.as_array(), this));
}
void
@ -211,8 +212,8 @@ namespace llarp
// is the next peer we ask closer to the target than us?
if((next ^ target) < (ourKey ^ target))
{
// yes it is closer, ask neighboor recursively
LookupRouterRecursive(target.data(), requester, txid, next);
// yes it is closer, ask neighbour recursively
LookupRouterRecursive(target.as_array(), requester, txid, next);
}
else
{
@ -240,7 +241,8 @@ namespace llarp
Context::GetIntroSetByServiceAddress(
const llarp::service::Address &addr) const
{
auto itr = services->nodes.find(addr.data());
auto key = addr.ToKey();
auto itr = services->nodes.find(key);
if(itr == services->nodes.end())
return nullptr;
return &itr->second.introset;
@ -343,7 +345,7 @@ namespace llarp
bool
GetNextPeer(Key_t &next, const std::set< Key_t > &exclude) override
{
Key_t k = target.data();
Key_t k = target.ToKey();
return parent->nodes->FindCloseExcluding(k, next, exclude);
}
@ -392,8 +394,8 @@ namespace llarp
void
SendReply() override
{
auto path =
parent->router->paths.GetByUpstream(parent->OurKey(), localPath);
auto path = parent->router->paths.GetByUpstream(
parent->OurKey().as_array(), localPath);
if(!path)
{
llarp::LogWarn(
@ -619,8 +621,8 @@ namespace llarp
void
SendReply() override
{
auto path =
parent->router->paths.GetByUpstream(parent->OurKey(), localPath);
auto path = parent->router->paths.GetByUpstream(
parent->OurKey().as_array(), localPath);
if(!path)
{
llarp::LogWarn(
@ -657,7 +659,7 @@ namespace llarp
std::vector< std::unique_ptr< IMessage > > &reply)
{
std::vector< RouterID > closer;
Key_t t(target.data());
Key_t t(target.as_array());
std::set< Key_t > found;
if(!nodes)
return false;
@ -686,7 +688,7 @@ namespace llarp
return false;
}
for(const auto &f : found)
closer.emplace_back(f.data());
closer.emplace_back(f.as_array());
reply.emplace_back(new GotRouterMessage(txid, closer, false));
return true;
}
@ -762,8 +764,8 @@ namespace llarp
void
SendReply() override
{
auto path =
parent->router->paths.GetByUpstream(parent->OurKey(), localPath);
auto path = parent->router->paths.GetByUpstream(
parent->OurKey().as_array(), localPath);
if(!path)
{
llarp::LogWarn(

@ -100,7 +100,7 @@ namespace llarp
if(next)
{
// explicit next peer provided
peer = next->data();
peer = *next;
}
else if(!GetNextPeer(peer, peersAsked))
{
@ -109,7 +109,7 @@ namespace llarp
return false;
}
const Key_t targetKey = target.data();
const Key_t targetKey = target.as_array();
if((prevPeer ^ targetKey) < (peer ^ targetKey))
{
// next peer is not closer
@ -118,7 +118,9 @@ namespace llarp
return false;
}
else
{
peersAsked.insert(peer);
}
DoNextRequest(peer);
return true;
}
@ -166,7 +168,7 @@ namespace llarp
LookupRouter(const RouterID& target, RouterLookupHandler result)
{
Key_t askpeer;
if(!nodes->FindClosest(target.data(), askpeer))
if(!nodes->FindClosest(target.as_array(), askpeer))
return false;
LookupRouterRecursive(target, OurKey(), 0, askpeer, result);
return true;
@ -260,7 +262,7 @@ namespace llarp
Bucket< ISNode >* services = nullptr;
bool allowTransit = false;
const byte_t*
const Key_t&
OurKey() const
{
return ourKey;

@ -117,7 +117,7 @@ namespace llarp
if(R == 0)
{
// we don't have it
Key_t target = S.data();
Key_t target = S.ToKey();
Key_t closer;
// find closer peer
if(!dht.nodes->FindClosest(target, closer))
@ -131,7 +131,7 @@ namespace llarp
else
{
Key_t us = dht.OurKey();
Key_t target = S.data();
Key_t target = S.ToKey();
// we are recursive
if(dht.nodes->FindCloseExcluding(target, peer, exclude))
{

@ -21,21 +21,21 @@ namespace llarp
auto path = dht.router->paths.GetByUpstream(K, pathID);
if(path)
{
replies.emplace_back(
new GotRouterMessage(K.data(), txid, {dht.router->rc()}, false));
replies.emplace_back(new GotRouterMessage(K.as_array(), txid,
{dht.router->rc()}, false));
return true;
}
return false;
}
Key_t peer;
Key_t k = K.data();
Key_t k = K.as_array();
// check if we know this in our nodedb first
RouterContact found;
if(dht.router->nodedb->Get(K, found))
{
replies.emplace_back(
new GotRouterMessage(K.data(), txid, {found}, false));
new GotRouterMessage(K.as_array(), txid, {found}, false));
return true;
}
// lookup if we don't have it in our nodedb
@ -75,7 +75,7 @@ namespace llarp
// key
if(!bencode_write_bytestring(buf, "K", 1))
return false;
if(!bencode_write_bytestring(buf, K.data(), K.size()))
if(!bencode_write_bytestring(buf, K.as_array().data(), K.size()))
return false;
// txid
@ -124,7 +124,7 @@ namespace llarp
if(strbuf.sz != K.size())
return false;
memcpy(K.data(), strbuf.base, K.size());
std::copy(strbuf.base, strbuf.base + K.SIZE, K.as_array().begin());
return true;
}
if(llarp_buffer_eq(key, "T"))
@ -161,11 +161,11 @@ namespace llarp
else if(dht.router->nodedb->Get(K, found))
{
replies.emplace_back(
new GotRouterMessage(K.data(), txid, {found}, false));
new GotRouterMessage(K.as_array(), txid, {found}, false));
return true;
}
else
dht.LookupRouterRelayed(From, txid, K.data(), !iterative, replies);
dht.LookupRouterRelayed(From, txid, K.as_array(), !iterative, replies);
return true;
}
} // namespace dht

@ -99,7 +99,7 @@ namespace llarp
dht.pendingExploreLookups.NotFound(owner, K);
else
{
dht.pendingExploreLookups.Found(owner, From.data(), N);
dht.pendingExploreLookups.Found(owner, From.as_array(), N);
}
return true;
}

@ -23,7 +23,7 @@ namespace llarp
RCNode(const llarp::RouterContact& other)
{
rc = other;
ID = other.pubkey.data();
ID = other.pubkey.as_array();
}
bool
@ -47,7 +47,7 @@ namespace llarp
ISNode(const llarp::service::IntroSet& other)
{
introset = other;
introset.A.CalculateAddress(ID);
introset.A.CalculateAddress(ID.as_array());
}
bool

@ -41,12 +41,12 @@ decode_request_name(const std::string &name, llarp::AlignedBuffer< 32 > &addr,
auto pos = name.find(".snode");
if(pos != std::string::npos)
{
if(!llarp::HexDecode(name.substr(0, pos).c_str(), serviceAddr.data().data(),
serviceAddr.size()))
if(!llarp::HexDecode(name.substr(0, pos).c_str(),
serviceAddr.as_array().data(), serviceAddr.size()))
{
return false;
}
addr = snodeAddr.data();
addr = snodeAddr.as_array();
isSNode = true;
}
else
@ -55,7 +55,7 @@ decode_request_name(const std::string &name, llarp::AlignedBuffer< 32 > &addr,
{
return false;
}
addr = serviceAddr.data().data();
addr = serviceAddr.as_array();
isSNode = false;
}
return true;
@ -330,7 +330,7 @@ ReverseHandlerIter(struct llarp::service::Context::endpoint_iter *endpointCfg)
}
else
{
llarp::service::Address saddr = addr.data();
llarp::service::Address saddr = addr.as_array();
// llarp::LogInfo("Returning [", saddr.ToString(), "]");
writesend_dnss_revresponse(saddr.ToString(), context->request);
}
@ -448,7 +448,7 @@ llarp_dotlokilookup_handler(std::string name,
auto tun = routerHiddenServiceContext->getFirstTun();
if(isSNode)
{
if(tun->HasPathToSNode(addr.data()))
if(tun->HasPathToSNode(addr.as_array()))
{
llarp_dotlokilookup_checkQuery(qr, 0, 0);
response->dontSendResponse = true; // will send it shortly
@ -457,7 +457,7 @@ llarp_dotlokilookup_handler(std::string name,
}
else
{
if(tun->HasPathToService(addr.data()))
if(tun->HasPathToService(addr.as_array()))
{
llarp_dotlokilookup_checkQuery(qr, 0, 0);
response->dontSendResponse = true; // will send it shortly

@ -96,7 +96,7 @@ namespace llarp
if(r.FromString(msg.questions[0].qname))
{
huint32_t ip;
if(m_SNodeKeys.find(r.data()) == m_SNodeKeys.end())
if(m_SNodeKeys.find(r.as_array()) == m_SNodeKeys.end())
{
// we do not have it mapped
// map it
@ -106,7 +106,7 @@ namespace llarp
else
{
// we have it mapped already as a service node
auto itr = m_KeyToIP.find(r.data());
auto itr = m_KeyToIP.find(r.as_array());
if(itr != m_KeyToIP.end())
{
ip = itr->second;
@ -194,7 +194,7 @@ namespace llarp
{
if(!itr->second->Flush())
{
llarp::LogWarn("failed to flushsnode traffic to ", itr->first,
llarp::LogWarn("failed to flush snode traffic to ", itr->first,
" via outbound session");
}
++itr;
@ -485,8 +485,8 @@ namespace llarp
huint32_t
ExitEndpoint::ObtainServiceNodeIP(const llarp::RouterID &other)
{
huint32_t ip = GetIPForIdent(other.data());
if(m_SNodeKeys.insert(other.data()).second)
huint32_t ip = GetIPForIdent(other.as_array());
if(m_SNodeKeys.emplace(other.as_array()).second)
{
// this is a new service node make an outbound session to them
m_SNodeSessions.insert(
@ -509,16 +509,15 @@ namespace llarp
if(wantInternet && !m_PermitExit)
return false;
huint32_t ip = GetIPForIdent(pk);
if(Router()->paths.TransitHopPreviousIsRouter(path, pk.data()))
if(Router()->paths.TransitHopPreviousIsRouter(path, pk.as_array()))
{
// we think this path belongs to a service node
// mark it as such so we don't make an outbound session to them
m_SNodeKeys.insert(pk.data());
m_SNodeKeys.emplace(pk.as_array());
}
m_ActiveExits.insert(
std::make_pair(pk,
std::make_unique< llarp::exit::Endpoint >(
pk, path, !wantInternet, ip, this)));
m_ActiveExits.emplace(pk,
std::make_unique< llarp::exit::Endpoint >(
pk, path, !wantInternet, ip, this));
m_Paths[path] = pk;
return HasLocalMappedAddrFor(pk);

@ -19,7 +19,7 @@ namespace llarp
}
huint32_t
ObtainIPForAddr(const byte_t *, bool) override
ObtainIPForAddr(const AlignedBuffer< 32 > &, bool) override
{
return {0};
}

@ -226,9 +226,9 @@ namespace llarp
}
else if(addr.FromString(qname, ".loki"))
{
if(HasAddress(addr.data().data()))
if(HasAddress(addr.as_array().data()))
{
huint32_t ip = ObtainIPForAddr(addr.data().data(), false);
huint32_t ip = ObtainIPForAddr(addr.as_array().data(), false);
msg.AddINReply(ip);
}
else
@ -242,8 +242,8 @@ namespace llarp
else if(addr.FromString(qname, ".snode"))
{
// TODO: add hook to EnsurePathToSNode
EnsurePathToSNode(addr.data().data());
huint32_t ip = ObtainIPForAddr(addr.data().data(), true);
EnsurePathToSNode(addr.as_array());
huint32_t ip = ObtainIPForAddr(addr.as_array().data(), true);
msg.AddINReply(ip);
}
else
@ -325,7 +325,7 @@ namespace llarp
{
if(ctx)
{
huint32_t ip = ObtainIPForAddr(addr.data().data(), false);
huint32_t ip = ObtainIPForAddr(addr.as_array().data(), false);
request.AddINReply(ip);
}
else
@ -348,9 +348,9 @@ namespace llarp
}
llarp::LogInfo(Name() + " map ", addr.ToString(), " to ", ip);
m_IPToAddr[ip] = addr.data().data();
m_AddrToIP[addr.data().data()] = ip;
m_SNodes[addr.data().data()] = SNode;
m_IPToAddr[ip] = addr.as_array();
m_AddrToIP[addr.as_array()] = ip;
m_SNodes[addr.as_array()] = SNode;
MarkIPActiveForever(ip);
return true;
}
@ -495,12 +495,12 @@ namespace llarp
if(m_SNodes.at(itr->second))
{
sendFunc = std::bind(&TunEndpoint::SendToSNodeOrQueue, this,
itr->second.data(), std::placeholders::_1);
itr->second.as_array(), std::placeholders::_1);
}
else
{
sendFunc = std::bind(&TunEndpoint::SendToServiceOrQueue, this,
itr->second.data(), std::placeholders::_1,
itr->second.as_array(), std::placeholders::_1,
service::eProtocolTraffic);
}
// prepare packet for insertion into network
@ -555,11 +555,11 @@ namespace llarp
}
huint32_t
TunEndpoint::ObtainIPForAddr(const byte_t *a, bool snode)
TunEndpoint::ObtainIPForAddr(const AlignedBuffer< 32 >& addr, bool snode)
{
llarp_time_t now = Now();
huint32_t nextIP = {0};
AlignedBuffer< 32 > ident(a);
AlignedBuffer< 32 > ident(addr);
{
// previously allocated address
auto itr = m_AddrToIP.find(ident);

@ -111,7 +111,7 @@ namespace llarp
return addr;
}
// found
return itr->second.data();
return itr->second.as_array();
}
bool
@ -122,7 +122,8 @@ namespace llarp
/// get ip address for key unconditionally
huint32_t
ObtainIPForAddr(const byte_t* addr, bool serviceNode) override;
ObtainIPForAddr(const AlignedBuffer< 32 >& addr,
bool serviceNode) override;
/// flush network traffic
void

@ -24,10 +24,10 @@ namespace llarp
}
bool
ILinkLayer::HasSessionTo(const byte_t* pk)
ILinkLayer::HasSessionTo(const RouterID& id)
{
Lock l(m_AuthedLinksMutex);
return m_AuthedLinks.find(pk) != m_AuthedLinks.end();
return m_AuthedLinks.find(id) != m_AuthedLinks.end();
}
void
@ -43,7 +43,7 @@ namespace llarp
}
bool
ILinkLayer::VisitSessionByPubkey(const byte_t* pk,
ILinkLayer::VisitSessionByPubkey(const RouterID& pk,
std::function< bool(ILinkSession*) > visit)
{
auto itr = m_AuthedLinks.find(pk);
@ -124,7 +124,7 @@ namespace llarp
}
void
ILinkLayer::MapAddr(const byte_t* pk, ILinkSession* s)
ILinkLayer::MapAddr(const RouterID& pk, ILinkSession* s)
{
static constexpr size_t MaxSessionsPerKey = 16;
Lock l_authed(m_AuthedLinksMutex);
@ -135,7 +135,7 @@ namespace llarp
if(itr->get() == s)
{
if(m_AuthedLinks.count(pk) < MaxSessionsPerKey)
m_AuthedLinks.insert(std::make_pair(pk, std::move(*itr)));
m_AuthedLinks.emplace(pk, std::move(*itr));
else
s->SendClose();
itr = m_Pending.erase(itr);
@ -168,7 +168,7 @@ namespace llarp
llarp::AddressInfo to;
if(!PickAddress(rc, to))
return false;
llarp::LogInfo("Try establish to ", RouterID(rc.pubkey.data()));
llarp::LogInfo("Try establish to ", RouterID(rc.pubkey.as_array()));
llarp::Addr addr(to);
auto s = NewOutboundSession(rc, to);
s->Start();

@ -57,7 +57,7 @@ namespace llarp
}
bool
HasSessionTo(const byte_t* pk);
HasSessionTo(const RouterID& pk);
bool
HasSessionVia(const Addr& addr);
@ -128,7 +128,7 @@ namespace llarp
GetOurAddressInfo(AddressInfo& addr) const;
bool
VisitSessionByPubkey(const byte_t* pk,
VisitSessionByPubkey(const RouterID& pk,
std::function< bool(ILinkSession*) > visit);
virtual uint16_t
@ -156,7 +156,7 @@ namespace llarp
GenEphemeralKeys();
void
MapAddr(const byte_t* pk, ILinkSession* s);
MapAddr(const RouterID& pk, ILinkSession* s);
virtual void Tick(llarp_time_t)
{

@ -130,8 +130,8 @@ namespace llarp
{
ShortHash t_h;
AlignedBuffer< 64 > tmp;
memcpy(tmp.data(), K, K.size());
memcpy(tmp.data() + K.size(), n, n.size());
std::copy(K.begin(), K.end(), tmp.begin());
std::copy(n.begin(), n.end(), tmp.begin() + K.size());
// t_h = HS(K + L.n)
if(!Crypto()->shorthash(t_h, ConstBuffer(tmp)))
{
@ -154,7 +154,7 @@ namespace llarp
{
AlignedBuffer< 56 > tmp;
auto buf = llarp::Buffer(tmp);
memcpy(buf.cur, K.data(), K.size());
std::copy(K.begin(), K.end(), buf.cur);
buf.cur += K.size();
memcpy(buf.cur, A, A.size());
buf.cur = buf.base;
@ -183,11 +183,11 @@ namespace llarp
// yes it fills it
llarp::LogDebug("process leftovers, offset=", recvBufOffset,
" sz=", s, " left=", left);
memcpy(recvBuf.data() + recvBufOffset, buf, left);
std::copy(buf, buf + left, recvBuf.begin() + recvBufOffset);
s -= left;
recvBufOffset = 0;
buf += left;
if(!VerifyThenDecrypt(recvBuf.data()))
if(!VerifyThenDecrypt(recvBuf.as_array().data()))
return false;
}
}
@ -205,7 +205,7 @@ namespace llarp
{
// hold onto leftovers
llarp::LogDebug("leftovers sz=", s);
memcpy(recvBuf.data() + recvBufOffset, buf, s);
std::copy(buf, buf + s, recvBuf.begin() + recvBufOffset);
recvBufOffset += s;
}
return true;
@ -612,9 +612,9 @@ namespace llarp
remoteTransportPubKey = addr.pubkey;
remoteRC = rc;
RouterID rid = remoteRC.pubkey;
Crypto()->shorthash(txKey, InitBuffer(rid.data(), PUBKEYSIZE));
rid = p->GetOurRC().pubkey.data();
Crypto()->shorthash(rxKey, llarp::InitBuffer(rid.data(), PUBKEYSIZE));
Crypto()->shorthash(txKey, InitBuffer(rid.as_array().data(), PUBKEYSIZE));
rid = p->GetOurRC().pubkey.as_array();
Crypto()->shorthash(rxKey, InitBuffer(rid.as_array().data(), PUBKEYSIZE));
sock = s;
assert(utp_set_userdata(sock, this) == this);
@ -628,7 +628,7 @@ namespace llarp
Session::Session(LinkLayer* p, utp_socket* s, const Addr& addr) : Session(p)
{
RouterID rid = p->GetOurRC().pubkey;
Crypto()->shorthash(rxKey, InitBuffer(rid.data(), PUBKEYSIZE));
Crypto()->shorthash(rxKey, InitBuffer(rid.as_array().data(), PUBKEYSIZE));
remoteRC.Clear();
sock = s;
assert(s == sock);
@ -656,7 +656,8 @@ namespace llarp
{
remoteRC = msg->rc;
Crypto()->shorthash(
txKey, llarp::InitBuffer(remoteRC.pubkey.data(), PUBKEYSIZE));
txKey,
llarp::InitBuffer(remoteRC.pubkey.as_array().data(), PUBKEYSIZE));
if(!DoKeyExchange(Crypto()->transport_dh_server, rxKey, msg->N,
remoteRC.enckey, parent->TransportSecretKey()))
@ -753,7 +754,8 @@ namespace llarp
}
EnterState(eSessionReady);
/// future LIM are used for session renegotiation
GotLIM = std::bind(&Session::GotSessionRenegotiate, this,std::placeholders::_1);
GotLIM = std::bind(&Session::GotSessionRenegotiate, this,
std::placeholders::_1);
return true;
}
@ -903,10 +905,10 @@ namespace llarp
auto& buf = sendq.back();
vecq.emplace_back();
auto& vec = vecq.back();
vec.iov_base = buf.data();
vec.iov_base = buf.as_array().data();
vec.iov_len = FragmentBufferSize;
buf.Randomize();
byte_t* nonce = buf.data() + FragmentHashSize;
byte_t* nonce = buf.as_array().data() + FragmentHashSize;
byte_t* body = nonce + FragmentNonceSize;
byte_t* base = body;
AlignedBuffer< 24 > A = base;
@ -935,7 +937,7 @@ namespace llarp
payload.cur = payload.base;
payload.sz = FragmentBufferSize - FragmentHashSize;
// key'd hash
if(!Crypto()->hmac(buf.data(), payload, txKey))
if(!Crypto()->hmac(buf.as_array().data(), payload, txKey))
return false;
return MutateKey(txKey, A);
}
@ -947,7 +949,7 @@ namespace llarp
Alive();
if(st == eSessionReady)
{
parent->MapAddr(remoteRC.pubkey.data(), this);
parent->MapAddr(remoteRC.pubkey.as_array(), this);
parent->SessionEstablished(remoteRC);
}
}
@ -1001,7 +1003,7 @@ namespace llarp
auto hbuf = InitBuffer(ptr + FragmentHashSize,
FragmentBufferSize - FragmentHashSize);
if(!Crypto()->hmac(digest.data(), hbuf, rxKey))
if(!Crypto()->hmac(digest.as_array().data(), hbuf, rxKey))
{
llarp::LogError("keyed hash failed");
return false;
@ -1074,12 +1076,12 @@ namespace llarp
llarp::LogError("failed to mutate rx key");
return false;
}
if(remaining == 0)
{
// we done with this guy, prune next tick
itr->second.lastActive = 0;
llarp_buffer_t buf = itr->second.buffer;
llarp_buffer_t buf = itr->second.buffer;
// resize
buf.sz = buf.cur - buf.base;
// rewind

@ -55,7 +55,8 @@ namespace llarp
MessageBuffer _msg;
/// for accessing message buffer
llarp_buffer_t buffer = llarp::InitBuffer(_msg.data(), _msg.size());
llarp_buffer_t buffer =
llarp::InitBuffer(_msg.as_array().data(), _msg.size());
bool
operator==(const InboundMessage& other) const

@ -105,7 +105,7 @@ llarp_nodedb::Insert(const llarp::RouterContact &rc)
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
{
llarp::util::Lock lock(access);
entries.insert(std::make_pair(rc.pubkey.data(), rc));
entries.emplace(rc.pubkey.as_array(), rc);
}
if(!rc.BEncode(&buf))
return false;
@ -182,7 +182,7 @@ llarp_nodedb::loadfile(const fs::path &fpath)
}
{
llarp::util::Lock lock(access);
entries.insert(std::make_pair(rc.pubkey.data(), rc));
entries.emplace(rc.pubkey.as_array(), rc);
}
return true;
}

@ -61,14 +61,15 @@ namespace llarp
bool
PathContext::HopIsUs(const RouterID& k) const
{
return memcmp(k.data(), m_Router->pubkey(), PUBKEYSIZE) == 0;
return std::equal(m_Router->pubkey(), m_Router->pubkey() + PUBKEYSIZE,
k.begin());
}
bool
PathContext::ForwardLRCM(const RouterID& nextHop,
const std::array< EncryptedFrame, 8 >& frames)
{
llarp::LogDebug("fowarding LRCM to ", nextHop);
llarp::LogDebug("forwarding LRCM to ", nextHop);
LR_CommitMessage msg;
msg.frames = frames;
return m_Router->SendToOrQueue(nextHop, &msg);

@ -63,11 +63,11 @@ namespace llarp
if(isFarthestHop)
{
hop.upstream = hop.rc.pubkey.data();
hop.upstream = hop.rc.pubkey.as_array();
}
else
{
hop.upstream = ctx->path->hops[ctx->idx].rc.pubkey.data();
hop.upstream = ctx->path->hops[ctx->idx].rc.pubkey.as_array();
}
// build record
@ -219,8 +219,7 @@ namespace llarp
bool
Builder::BuildCooldownHit(llarp_time_t now) const
{
return now < lastBuild
|| now - lastBuild < buildIntervalLimit;
return now < lastBuild || now - lastBuild < buildIntervalLimit;
}
bool
@ -304,7 +303,8 @@ namespace llarp
{
// linear backoff
static constexpr llarp_time_t MaxBuildInterval = 10 * 1000;
buildIntervalLimit = std::max(1000 + buildIntervalLimit, MaxBuildInterval);
buildIntervalLimit =
std::max(1000 + buildIntervalLimit, MaxBuildInterval);
PathSet::HandlePathBuildTimeout(p);
}

@ -91,7 +91,7 @@ namespace llarp
Lock_t l(m_PathsMutex);
Path* path = nullptr;
AlignedBuffer< 32 > dist;
AlignedBuffer< 32 > to = id.data();
AlignedBuffer< 32 > to = id;
dist.Fill(0xff);
for(const auto& item : m_Paths)
{

@ -47,7 +47,8 @@ struct TryConnectJob
void
Failed()
{
llarp::LogInfo("session to ", llarp::RouterID(rc.pubkey.data()), " closed");
llarp::LogInfo("session to ", llarp::RouterID(rc.pubkey.as_array()),
" closed");
link->CloseSessionTo(rc.pubkey);
}
@ -110,10 +111,10 @@ llarp_router_try_connect(llarp::Router *router,
return false;
}
auto link = router->outboundLink.get();
auto itr = router->pendingEstablishJobs.insert(std::make_pair(
remote.pubkey.data(),
std::make_unique< TryConnectJob >(remote, link, numretries, router)));
auto link = router->outboundLink.get();
auto itr = router->pendingEstablishJobs.emplace(
remote.pubkey.as_array(),
std::make_unique< TryConnectJob >(remote, link, numretries, router));
TryConnectJob *job = itr.first->second.get();
// try establishing async
router->logic->queue_job({job, &on_try_connecting});
@ -162,14 +163,16 @@ llarp_findOrCreateEncryption(llarp::Crypto *crypto, const char *fpath,
std::ofstream f(path.string(), std::ios::binary);
if(f.is_open())
{
f.write((char *)encryption.data(), SECKEYSIZE);
std::copy(encryption.begin(), encryption.end(),
std::ostream_iterator< byte_t >(f));
}
}
std::ifstream f(path.string(), std::ios::binary);
if(f.is_open())
{
f.read((char *)encryption.data(), SECKEYSIZE);
f.read(reinterpret_cast< char * >(encryption.as_array().data()),
SECKEYSIZE);
return true;
}
llarp::LogInfo("failed to get encryption key");
@ -260,13 +263,13 @@ namespace llarp
{
for(const auto &link : inboundLinks)
{
if(link->HasSessionTo(remote.data()))
if(link->HasSessionTo(remote.as_array()))
{
SendTo(remote, msg, link.get());
return true;
}
}
if(outboundLink && outboundLink->HasSessionTo(remote.data()))
if(outboundLink && outboundLink->HasSessionTo(remote.as_array()))
{
SendTo(remote, msg, outboundLink.get());
return true;
@ -504,7 +507,7 @@ namespace llarp
llarp::RouterContact rc = job->rc;
router->validRouters.insert(std::make_pair(pk.data(), rc));
router->validRouters.emplace(pk.as_array(), rc);
// track valid router in dht
router->dht->impl.nodes->PutNode(rc);
@ -680,7 +683,7 @@ namespace llarp
// store it in nodedb async
nodedb->InsertAsync(newrc);
// update dht if required
if(dht->impl.nodes->HasNode(newrc.pubkey.data()))
if(dht->impl.nodes->HasNode(newrc.pubkey.as_array()))
{
dht->impl.nodes->PutNode(newrc);
}
@ -768,7 +771,7 @@ namespace llarp
for(const auto &rc : bootstrapRCList)
{
llarp_router_try_connect(this, rc, 4);
dht->impl.ExploreNetworkVia(rc.pubkey.data());
dht->impl.ExploreNetworkVia(rc.pubkey.as_array());
}
}
else
@ -1440,7 +1443,7 @@ namespace llarp
llarp::PubKey pk;
if(pk.FromString(val))
{
if(self->strictConnectPubkeys.insert(pk.data()).second)
if(self->strictConnectPubkeys.insert(pk.as_array()).second)
llarp::LogInfo("added ", pk, " to strict connect list");
else
llarp::LogWarn("duplicate key for strict connect: ", pk);
@ -1517,11 +1520,11 @@ namespace llarp
auto &rc = self->bootstrapRCList.back();
if(rc.Read(val) && rc.Verify(&self->crypto, self->Now()))
{
llarp::LogInfo("Added bootstrap node ", RouterID(rc.pubkey.data()));
llarp::LogInfo("Added bootstrap node ", RouterID(rc.pubkey.as_array()));
}
else if(self->Now() - rc.last_updated > RouterContact::Lifetime)
{
llarp::LogWarn("Bootstrap node ", RouterID(rc.pubkey.data()),
llarp::LogWarn("Bootstrap node ", RouterID(rc.pubkey.as_array()),
" is too old and needs to be refreshed");
self->bootstrapRCList.pop_back();
}

@ -25,7 +25,9 @@ namespace llarp
#endif
NetID::NetID() : AlignedBuffer< 8 >()
{
memcpy(data(), DefaultValue, strnlen((const char *)DefaultValue, size()));
size_t len =
strnlen(reinterpret_cast< const char * >(DefaultValue), size());
std::copy(DefaultValue, DefaultValue + len, as_array().begin());
}
bool
@ -37,8 +39,8 @@ namespace llarp
std::string
NetID::ToString() const
{
size_t l = strnlen((const char *)data(), size());
return std::string((const char *)data(), l);
auto term = std::find(begin(), end(), '\0');
return std::string(begin(), term);
}
bool
@ -50,15 +52,16 @@ namespace llarp
return false;
if(strbuf.sz > size())
return false;
memcpy(data(), strbuf.base, strbuf.sz);
std::copy(strbuf.base, strbuf.base + strbuf.sz, as_array().begin());
return true;
}
bool
NetID::BEncode(llarp_buffer_t *buf) const
{
size_t l = strnlen((const char *)data(), size());
return bencode_write_bytestring(buf, data(), l);
auto term = std::find(begin(), end(), '\0');
return bencode_write_bytestring(buf, begin(), std::distance(begin(), term));
}
bool
@ -158,7 +161,8 @@ namespace llarp
if(strbuf.sz > nickname.size())
return false;
nickname.Zero();
memcpy(nickname.data(), strbuf.base, strbuf.sz);
std::copy(strbuf.base, strbuf.base + strbuf.sz,
nickname.as_array().begin());
return true;
}
@ -218,8 +222,8 @@ namespace llarp
std::string
RouterContact::Nick() const
{
const char *n = (const char *)nickname.data();
return std::string(n, strnlen(n, nickname.size()));
auto term = std::find(nickname.begin(), nickname.end(), '\0');
return std::string(nickname.begin(), term);
}
bool

@ -32,7 +32,7 @@ namespace llarp
RouterID&
operator=(const byte_t* ptr)
{
memcpy(data(), ptr, SIZE);
std::copy(ptr, ptr + SIZE, as_array().begin());
return *this;
}

@ -275,7 +275,7 @@ namespace llarp
const byte_t* ptr = nullptr;
if(!vanity.IsZero())
ptr = vanity.data();
ptr = vanity.as_array().data();
// update pubkeys
pub.Update(llarp::seckey_topublic(enckey),
llarp::seckey_topublic(signkey), ptr);

@ -127,7 +127,7 @@ namespace llarp
BDecode(llarp_buffer_t* buf) override
{
if(IBEncodeMessage::BDecode(buf))
return CalculateAddress(m_CachedAddr.data());
return CalculateAddress(m_CachedAddr.as_array());
return false;
}

@ -14,88 +14,30 @@ namespace llarp
namespace service
{
/// Snapp/Snode Address
struct Address
struct Address : public AlignedBuffer< 32 >
{
static constexpr size_t SIZE = 32;
using Data = std::array< byte_t, SIZE >;
std::string
ToString(const char* tld = ".loki") const;
bool
FromString(const std::string& str, const char* tld = ".loki");
Address()
{
Zero();
}
Address(const byte_t* buf)
{
std::copy(buf, buf + SIZE, b.begin());
}
Address(const Address& other)
{
b = other.b;
}
byte_t& operator[](size_t idx)
Address() : AlignedBuffer< SIZE >()
{
return b[idx];
}
const byte_t& operator[](size_t idx) const
Address(const Data& buf) : AlignedBuffer< SIZE >(buf)
{
return b[idx];
}
bool
BEncode(llarp_buffer_t* buf) const
Address(const Address& other) : AlignedBuffer< SIZE >(other.as_array())
{
return bencode_write_bytestring(buf, b.data(), SIZE);
}
bool
BDecode(llarp_buffer_t* buf)
{
llarp_buffer_t strbuf;
if(!bencode_read_string(buf, &strbuf))
return false;
if(strbuf.sz != SIZE)
{
llarp::LogErrorTag("Address::BDecode",
"bdecode buffer size missmatch ", strbuf.sz,
"!=32");
return false;
}
std::copy(strbuf.base, strbuf.base + SIZE, b.begin());
return true;
}
static constexpr size_t
size()
{
return SIZE;
}
bool
IsZero() const
{
return b == Data{};
}
void
Zero()
{
b.fill(0);
}
bool
operator<(const Address& other) const
{
return data() < other.data();
return as_array() < other.as_array();
}
friend std::ostream&
@ -107,40 +49,28 @@ namespace llarp
bool
operator==(const Address& other) const
{
return data() == other.data();
return as_array() == other.as_array();
}
bool
operator!=(const Address& other) const
{
return !(*this == other);
return as_array() != other.as_array();
}
Address&
operator=(const Address& other) = default;
const dht::Key_t
dht::Key_t
ToKey() const
{
return dht::Key_t(data());
return dht::Key_t(as_array());
}
const RouterID
RouterID
ToRouter() const
{
return RouterID(data().data());
}
const Data&
data() const
{
return b;
}
Data&
data()
{
return b;
return RouterID(as_array());
}
struct Hash
@ -148,13 +78,10 @@ namespace llarp
size_t
operator()(const Address& buf) const
{
return std::accumulate(buf.data().begin(), buf.data().end(), 0,
return std::accumulate(buf.begin(), buf.end(), 0,
std::bit_xor< size_t >());
}
};
private:
Data b;
};
} // namespace service

@ -467,7 +467,7 @@ namespace llarp
auto itr = m_Sessions.find(tag);
if(itr == m_Sessions.end())
return false;
secret = itr->second.sharedKey.data();
secret = itr->second.sharedKey.as_array().data();
return true;
}
@ -563,7 +563,7 @@ namespace llarp
Endpoint::PublishIntroSet(llarp::Router* r)
{
// publish via near router
RouterID location = m_Identity.pub.Addr().data().data();
RouterID location = m_Identity.pub.Addr().as_array();
auto path = GetEstablishedPathClosestTo(location);
return path && PublishIntroSetVia(r, path);
}
@ -696,7 +696,7 @@ namespace llarp
Endpoint::PutNewOutboundContext(const llarp::service::IntroSet& introset)
{
Address addr;
introset.A.CalculateAddress(addr.data());
introset.A.CalculateAddress(addr.as_array());
if(m_RemoteSessions.count(addr) >= MAX_OUTBOUND_CONTEXT_COUNT)
{
@ -858,10 +858,9 @@ namespace llarp
if(msg->proto == eProtocolTraffic)
{
auto buf = llarp::Buffer(msg->payload);
return HandleWriteIPPacket(
buf,
std::bind(&Endpoint::ObtainIPForAddr, this,
msg->sender.Addr().data().data(), false));
return HandleWriteIPPacket(buf,
std::bind(&Endpoint::ObtainIPForAddr, this,
msg->sender.Addr(), false));
}
else if(msg->proto == eProtocolText)
{
@ -1139,7 +1138,7 @@ namespace llarp
}
bool
Endpoint::SendToSNodeOrQueue(const byte_t* addr, llarp_buffer_t buf)
Endpoint::SendToSNodeOrQueue(const RouterID& addr, llarp_buffer_t buf)
{
llarp::net::IPv4Packet pkt;
if(!pkt.Load(buf))
@ -1162,7 +1161,7 @@ namespace llarp
}
bool
Endpoint::SendToServiceOrQueue(const byte_t* addr, llarp_buffer_t data,
Endpoint::SendToServiceOrQueue(const RouterID& addr, llarp_buffer_t data,
ProtocolType t)
{
service::Address remote(addr);
@ -1583,7 +1582,7 @@ namespace llarp
if(randomizePath)
path = m_Endpoint->PickRandomEstablishedPath();
else
path = m_Endpoint->GetEstablishedPathClosestTo(addr.data());
path = m_Endpoint->GetEstablishedPathClosestTo(addr.as_array());
if(path)
{

@ -20,7 +20,7 @@ namespace llarp
{
namespace service
{
// foward declare
// forward declare
struct AsyncKeyExchange;
struct Endpoint : public path::Builder,
@ -104,7 +104,7 @@ namespace llarp
HasPathToService(const Address& remote) const;
virtual huint32_t
ObtainIPForAddr(const byte_t* addr, bool serviceNode) = 0;
ObtainIPForAddr(const AlignedBuffer< 32 >& addr, bool serviceNode) = 0;
virtual bool
HasAddress(const byte_t* addr) const = 0;
@ -154,11 +154,11 @@ namespace llarp
HandlePathBuilt(path::Path* path) override;
bool
SendToServiceOrQueue(const byte_t* addr, llarp_buffer_t payload,
SendToServiceOrQueue(const RouterID& addr, llarp_buffer_t payload,
ProtocolType t);
bool
SendToSNodeOrQueue(const byte_t* addr, llarp_buffer_t payload);
SendToSNodeOrQueue(const RouterID& addr, llarp_buffer_t payload);
void
FlushSNodeTraffic();

@ -50,7 +50,7 @@ namespace llarp
if(m_CachedAddr.IsZero())
{
Address addr;
CalculateAddress(addr.data());
CalculateAddress(addr.as_array());
return addr.ToString();
}
return m_CachedAddr.ToString();
@ -70,7 +70,7 @@ namespace llarp
bool
ServiceInfo::UpdateAddr()
{
return CalculateAddress(m_CachedAddr.data());
return CalculateAddress(m_CachedAddr.as_array());
}
} // namespace service

@ -7,7 +7,7 @@ namespace llarp
std::string
Tag::ToString() const
{
return std::string((const char *)data());
return std::string(begin(), end());
}
} // namespace service
} // namespace llarp

@ -16,11 +16,11 @@ namespace llarp
{
struct Tag : public llarp::AlignedBuffer< 16 >
{
Tag() : llarp::AlignedBuffer< 16 >()
Tag() : llarp::AlignedBuffer< SIZE >()
{
}
Tag(const byte_t* d) : llarp::AlignedBuffer< 16 >(d)
Tag(const byte_t* d) : llarp::AlignedBuffer< SIZE >(d)
{
}
@ -28,20 +28,22 @@ namespace llarp
{
// evidently, does nothing on LP64 systems (where size_t is *already*
// unsigned long but zero-extends this on LLP64 systems
memcpy(data(), str.c_str(), std::min(16UL, (unsigned long)str.size()));
std::copy(str.begin(), str.begin() + std::min(16UL, str.size()),
as_array().begin());
}
Tag&
operator=(const Tag& other)
{
memcpy(data(), other.data(), 16);
as_array() = other.as_array();
return *this;
}
Tag&
operator=(const std::string& str)
{
memcpy(data(), str.data(), std::min(16UL, (unsigned long)str.size()));
std::copy(str.begin(), str.begin() + std::min(16UL, str.size()),
as_array().begin());
return *this;
}

@ -5,11 +5,10 @@
struct HiddenServiceTest : public ::testing::Test
{
llarp::Crypto crypto;
llarp::Crypto crypto;
llarp::service::Identity ident;
HiddenServiceTest()
: crypto(llarp::Crypto::sodium{})
HiddenServiceTest() : crypto(llarp::Crypto::sodium{})
{
}
@ -31,7 +30,7 @@ struct HiddenServiceTest : public ::testing::Test
TEST_F(HiddenServiceTest, TestGenerateIntroSet)
{
llarp::service::Address addr;
ASSERT_TRUE(ident.pub.CalculateAddress(addr.data()));
ASSERT_TRUE(ident.pub.CalculateAddress(addr.as_array()));
llarp::service::IntroSet I;
auto now = llarp::time_now_ms();
I.T = now;

@ -66,7 +66,7 @@ TYPED_TEST(AlignedBufferTest, AltConstructors)
Buffer c(b.as_array());
EXPECT_FALSE(c.IsZero());
Buffer d(c.data());
Buffer d(c.as_array().data());
EXPECT_FALSE(d.IsZero());
}

@ -230,7 +230,7 @@ TEST_F(UTPTest, TestAliceRenegWithBob)
[&](llarp::RouterContact rc) {
ASSERT_EQ(rc, Alice.GetRC());
llarp::LogInfo("bob established with alice");
Bob.link->VisitSessionByPubkey(Alice.GetRC().pubkey.data(),
Bob.link->VisitSessionByPubkey(Alice.GetRC().pubkey.as_array(),
sendDiscardMessage);
},
[&](llarp::RouterContact newrc, llarp::RouterContact oldrc) -> bool {
@ -318,7 +318,7 @@ TEST_F(UTPTest, TestAliceConnectToBob)
[&](llarp::RouterContact rc) {
ASSERT_EQ(rc, Alice.GetRC());
llarp::LogInfo("bob established with alice");
Bob.link->VisitSessionByPubkey(Alice.GetRC().pubkey.data(),
Bob.link->VisitSessionByPubkey(Alice.GetRC().pubkey.as_array(),
sendDiscardMessage);
},
[&](llarp::RouterContact, llarp::RouterContact) -> bool { return true; },

Loading…
Cancel
Save