Create CopyableBuffer type

This commit is contained in:
Michael 2019-02-02 23:12:42 +00:00
parent 2de621b0ad
commit f3b0af9d2f
No known key found for this signature in database
GPG Key ID: 2D51757B47E2434C
79 changed files with 517 additions and 526 deletions

View File

@ -60,11 +60,13 @@ namespace abyss
}
static void
OnRead(llarp_tcp_conn* conn, llarp_buffer_t buf)
OnRead(llarp_tcp_conn* conn, const llarp_buffer_t& buf)
{
ConnImpl* self = static_cast< ConnImpl* >(conn->user);
if(!self->ProcessRead((const char*)buf.base, buf.sz))
{
self->CloseError();
}
}
static void
@ -220,7 +222,7 @@ namespace abyss
body.size());
if(sz <= 0)
return;
if(!llarp_tcp_conn_async_write(m_Conn, llarp::InitBuffer(buf, sz)))
if(!llarp_tcp_conn_async_write(m_Conn, llarp_buffer_t(buf, sz)))
{
llarp::LogError("failed to write first part of request");
CloseError();
@ -237,15 +239,14 @@ namespace abyss
{
// header name
if(!llarp_tcp_conn_async_write(
m_Conn,
llarp::InitBuffer(item.first.c_str(), item.first.size())))
m_Conn, llarp_buffer_t(item.first.c_str(), item.first.size())))
{
CloseError();
return;
}
// header delimiter
if(!llarp_tcp_conn_async_write(
m_Conn, llarp::InitBuffer(buf, 2 * sizeof(char))))
if(!llarp_tcp_conn_async_write(m_Conn,
llarp_buffer_t(buf, 2 * sizeof(char))))
{
CloseError();
return;
@ -253,14 +254,14 @@ namespace abyss
// header value
if(!llarp_tcp_conn_async_write(
m_Conn,
llarp::InitBuffer(item.second.c_str(), item.second.size())))
llarp_buffer_t(item.second.c_str(), item.second.size())))
{
CloseError();
return;
}
// CRLF
if(!llarp_tcp_conn_async_write(
m_Conn, llarp::InitBuffer(buf + 2, 2 * sizeof(char))))
m_Conn, llarp_buffer_t(buf + 2, 2 * sizeof(char))))
{
CloseError();
return;
@ -268,14 +269,14 @@ namespace abyss
}
// CRLF
if(!llarp_tcp_conn_async_write(
m_Conn, llarp::InitBuffer(buf + 2, 2 * sizeof(char))))
m_Conn, llarp_buffer_t(buf + 2, 2 * sizeof(char))))
{
CloseError();
return;
}
// request body
if(!llarp_tcp_conn_async_write(
m_Conn, llarp::InitBuffer(body.c_str(), body.size())))
m_Conn, llarp_buffer_t(body.c_str(), body.size())))
{
CloseError();
return;

View File

@ -112,13 +112,13 @@ namespace abyss
code, msg.c_str(), contentType, contentLength);
if(sz <= 0)
return false;
if(!llarp_tcp_conn_async_write(_conn, llarp::InitBuffer(buf, sz)))
if(!llarp_tcp_conn_async_write(_conn, llarp_buffer_t(buf, sz)))
return false;
m_State = eWriteHTTPBody;
return llarp_tcp_conn_async_write(
_conn, llarp::InitBuffer(content, contentLength));
_conn, llarp_buffer_t(content, contentLength));
}
bool
@ -260,7 +260,7 @@ namespace abyss
}
static void
OnRead(llarp_tcp_conn* conn, llarp_buffer_t buf)
OnRead(llarp_tcp_conn* conn, const llarp_buffer_t& buf)
{
ConnImpl* self = static_cast< ConnImpl* >(conn->user);
if(!self->ProcessRead((const char*)buf.base, buf.sz))

View File

@ -4,7 +4,7 @@
#include <crypto/constants.hpp>
#include <crypto/types.hpp>
#include <util/buffer.h>
#include <util/buffer.hpp>
#include <functional>
#include <stdbool.h>

View File

@ -4,7 +4,7 @@
#include <constants/link_layer.hpp>
#include <util/aligned.hpp>
#include <util/bencode.h>
#include <util/buffer.h>
#include <util/buffer.hpp>
#include <util/mem.hpp>
#include <vector>
@ -84,7 +84,7 @@ namespace llarp
Encrypted&
operator=(const Encrypted& other)
{
return (*this) = other.Buffer();
return (*this) = other.Buffer().underlying;
}
Encrypted&
@ -102,9 +102,7 @@ namespace llarp
void
Fill(byte_t fill)
{
size_t idx = 0;
while(idx < _sz)
_buf[idx++] = fill;
std::fill(_buf.begin(), _buf.begin() + _sz, fill);
}
void
@ -135,10 +133,10 @@ namespace llarp
return &m_Buffer;
}
llarp_buffer_t
CopyableBuffer
Buffer() const
{
return m_Buffer.clone();
return CopyableBuffer{m_Buffer};
}
size_t

View File

@ -41,7 +41,7 @@ namespace llarp
return true;
}
std::array< byte_t, 128 > tmp;
llarp_buffer_t buf = llarp::Buffer(tmp);
llarp_buffer_t buf(tmp);
if(sz > sizeof(tmp))
{
return false;
@ -53,8 +53,8 @@ namespace llarp
bool
SecretKey::SaveToFile(const char* fname) const
{
byte_t tmp[128];
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, 128 > tmp;
llarp_buffer_t buf(tmp);
if(!BEncode(&buf))
{
return false;

View File

@ -3,7 +3,7 @@
#include <crypto/crypto.hpp>
#include <router_contact.hpp>
#include <util/buffer.h>
#include <util/buffer.hpp>
/**
* dht.h

View File

@ -1,5 +1,6 @@
#include <dnsd.hpp> // for llarp_handle_dnsd_recvfrom, dnsc
#include <util/buffer.hpp>
#include <util/endian.hpp>
#include <util/logger.hpp>
@ -605,17 +606,17 @@ extern "C"
void
llarp_handle_dns_recvfrom(struct llarp_udp_io *udp,
const struct sockaddr *addr, llarp_buffer_t buf)
const struct sockaddr *addr, CopyableBuffer buf)
{
// auto buffer = llarp::StackBuffer< decltype(castBuf) >(castBuf);
dns_msg_header hdr;
if(!decode_hdr(&buf, &hdr))
if(!decode_hdr(&buf.underlying, &hdr))
{
llarp::LogError("failed to decode dns header");
return;
}
// rewind
buf.cur = buf.base;
buf.underlying.cur = buf.underlying.base;
llarp::LogDebug("msg id ", hdr.id);
llarp::LogDebug("msg qr ", (uint8_t)hdr.qr);
if(!udp)
@ -629,12 +630,12 @@ extern "C"
if(hdr.qr)
{
llarp::LogDebug("handling as dnsc answer");
llarp_handle_dnsc_recvfrom(udp, addr, buf.clone());
llarp_handle_dnsc_recvfrom(udp, addr, buf);
}
else
{
llarp::LogDebug("handling as dnsd question");
llarp_handle_dnsd_recvfrom(udp, addr, buf.clone());
llarp_handle_dnsd_recvfrom(udp, addr, buf);
}
}
}

View File

@ -147,6 +147,6 @@ extern "C"
void
llarp_handle_dns_recvfrom(struct llarp_udp_io *udp,
const struct sockaddr *addr, llarp_buffer_t buf);
const struct sockaddr *addr, CopyableBuffer buf);
}
#endif

View File

@ -5,6 +5,8 @@
#include <util/endian.hpp>
#include <util/logger.hpp>
#include <array>
namespace llarp
{
namespace dns
@ -175,13 +177,14 @@ namespace llarp
hdr_fields |= (1 << 15);
const auto& question = questions[0];
answers.emplace_back();
auto& rec = answers.back();
rec.rr_name = question.qname;
rec.rr_type = question.qtype;
rec.rr_class = qClassIN;
rec.ttl = ttl;
byte_t tmp[512] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
auto& rec = answers.back();
rec.rr_name = question.qname;
rec.rr_type = question.qtype;
rec.rr_class = qClassIN;
rec.ttl = ttl;
std::array< byte_t, 512 > tmp = {0};
;
llarp_buffer_t buf(tmp);
if(EncodeName(&buf, name))
{
buf.sz = buf.cur - buf.base;
@ -199,13 +202,13 @@ namespace llarp
hdr_fields |= (1 << 15);
const auto& question = questions[0];
answers.emplace_back();
auto& rec = answers.back();
rec.rr_name = question.qname;
rec.rr_type = qTypeCNAME;
rec.rr_class = qClassIN;
rec.ttl = ttl;
byte_t tmp[512] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
auto& rec = answers.back();
rec.rr_name = question.qname;
rec.rr_type = qTypeCNAME;
rec.rr_class = qClassIN;
rec.ttl = ttl;
std::array< byte_t, 512 > tmp = {0};
llarp_buffer_t buf(tmp);
if(EncodeName(&buf, name))
{
buf.sz = buf.cur - buf.base;
@ -223,13 +226,13 @@ namespace llarp
hdr_fields |= (1 << 15);
const auto& question = questions[0];
answers.emplace_back();
auto& rec = answers.back();
rec.rr_name = question.qname;
rec.rr_type = qTypeMX;
rec.rr_class = qClassIN;
rec.ttl = ttl;
byte_t tmp[512] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
auto& rec = answers.back();
rec.rr_name = question.qname;
rec.rr_type = qTypeMX;
rec.rr_class = qClassIN;
rec.ttl = ttl;
std::array< byte_t, 512 > tmp = {0};
llarp_buffer_t buf(tmp);
llarp_buffer_put_uint16(&buf, priority);
if(EncodeName(&buf, name))
{

View File

@ -2,7 +2,7 @@
#define LLARP_DNS_NAME_HPP
#include <net/net_int.hpp>
#include <util/buffer.h>
#include <util/buffer.hpp>
#include <string>

View File

@ -1,8 +1,8 @@
#ifndef LLARP_DNS_REC_TYPES_HPP
#define LLARP_DNS_REC_TYPES_HPP
#include <net/net.hpp> // for llarp::Addr , llarp::huint32_t
#include <util/buffer.h> // for byte_t
#include <net/net.hpp> // for llarp::Addr , llarp::huint32_t
#include <util/types.hpp> // for byte_t
#include <vector>

View File

@ -1,7 +1,7 @@
#ifndef LLARP_DNS_SERIALIZE_HPP
#define LLARP_DNS_SERIALIZE_HPP
#include <util/buffer.h>
#include <util/buffer.hpp>
#include <vector>

View File

@ -2,6 +2,8 @@
#include <crypto/crypto.hpp>
#include <array>
namespace llarp
{
namespace dns
@ -40,16 +42,16 @@ namespace llarp
void
Proxy::HandleUDPRecv_server(llarp_udp_io* u, const sockaddr* from,
llarp_buffer_t buf)
CopyableBuffer buf)
{
static_cast< Proxy* >(u->user)->HandlePktServer(*from, &buf);
static_cast< Proxy* >(u->user)->HandlePktServer(*from, &buf.underlying);
}
void
Proxy::HandleUDPRecv_client(llarp_udp_io* u, const sockaddr* from,
llarp_buffer_t buf)
CopyableBuffer buf)
{
static_cast< Proxy* >(u->user)->HandlePktClient(*from, &buf);
static_cast< Proxy* >(u->user)->HandlePktClient(*from, &buf.underlying);
}
llarp::Addr
@ -73,8 +75,8 @@ namespace llarp
void
Proxy::SendMessageTo(llarp::Addr to, Message msg)
{
byte_t tmp[1500] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, 1500 > tmp = {0};
llarp_buffer_t buf(tmp);
if(msg.Encode(&buf))
{
buf.sz = buf.cur - buf.base;

View File

@ -42,10 +42,10 @@ namespace llarp
/// low level packet handler
static void
HandleUDPRecv_client(llarp_udp_io*, const struct sockaddr*,
llarp_buffer_t);
CopyableBuffer);
static void
HandleUDPRecv_server(llarp_udp_io*, const struct sockaddr*,
llarp_buffer_t);
CopyableBuffer);
/// low level ticker
static void

View File

@ -659,7 +659,7 @@ raw_resolve_host(struct dnsc_context *const dnsc, const char *url,
/// intermediate udp_io handler
void
llarp_handle_dnsc_recvfrom(struct llarp_udp_io *const udp,
const struct sockaddr *saddr, llarp_buffer_t buf)
const struct sockaddr *saddr, CopyableBuffer buf)
{
if(!saddr)
{
@ -667,12 +667,12 @@ llarp_handle_dnsc_recvfrom(struct llarp_udp_io *const udp,
}
// auto buffer = llarp::StackBuffer< decltype(castBuf) >(castBuf);
dns_msg_header hdr;
if(!decode_hdr(&buf, &hdr))
if(!decode_hdr(&buf.underlying, &hdr))
{
llarp::LogError("failed to decode dns header");
return;
}
buf.cur = buf.base; // reset cursor to beginning
buf.underlying.cur = buf.underlying.base; // reset cursor to beginning
llarp::LogDebug("Header got client responses for id: ", hdr.id);
@ -683,7 +683,7 @@ llarp_handle_dnsc_recvfrom(struct llarp_udp_io *const udp,
// sometimes we'll get double responses
if(request)
{
generic_handle_dnsc_recvfrom(request, buf, &hdr);
generic_handle_dnsc_recvfrom(request, buf.underlying, &hdr);
}
else
{
@ -754,7 +754,7 @@ llarp_resolve_host(struct dnsc_context *const dnsc, const char *url,
// ssize_t ret = llarp_ev_udp_sendto(dnsc->udp, dnsc->server, bytes, length);
ssize_t ret = llarp_ev_udp_sendto(
dnsc->udp, dnsc->resolvers[0],
llarp::InitBuffer(dns_packet->request, dns_packet->length));
llarp_buffer_t(dns_packet->request, dns_packet->length));
delete dns_packet;
if(ret < 0)
{

View File

@ -54,7 +54,7 @@ struct dnsc_answer_request
/// event handler for processing DNS responses
void
llarp_handle_dnsc_recvfrom(struct llarp_udp_io *const udp,
const struct sockaddr *addr, llarp_buffer_t buf);
const struct sockaddr *addr, CopyableBuffer buf);
/// generic handler for processing DNS responses
/// this doesn't look like it exists

View File

@ -1,4 +1,6 @@
#include <dnsd.hpp>
#include <util/buffer.hpp>
#include <net/net.hpp>
extern dns_tracker dns_udp_tracker;
@ -12,17 +14,18 @@ constexpr size_t BUFFER_SIZE = 1500;
ssize_t
raw_sendto_dns_hook_func(void *sock, const struct sockaddr *from,
llarp_buffer_t buf)
CopyableBuffer buf)
{
int *fd = (int *)sock;
// how do we get to these??
socklen_t addrLen = sizeof(struct sockaddr_in);
return sendto(*fd, (const char *)buf.base, buf.sz, 0, from, addrLen);
return sendto(*fd, (const char *)buf.underlying.base, buf.underlying.sz, 0,
from, addrLen);
}
ssize_t
llarp_sendto_dns_hook_func(void *sock, const struct sockaddr *from,
llarp_buffer_t buf)
CopyableBuffer buf)
{
struct llarp_udp_io *udp = (struct llarp_udp_io *)sock;
if(!udp)
@ -35,7 +38,7 @@ llarp_sendto_dns_hook_func(void *sock, const struct sockaddr *from,
// this call isn't calling the function...
// llarp::ev_io * evio = static_cast< llarp::ev_io * >(udp->impl);
// printf("ev_io[%x]\n", evio);
return llarp_ev_udp_sendto(udp, from, buf);
return llarp_ev_udp_sendto(udp, from, buf.underlying);
}
void
@ -72,7 +75,7 @@ write404_dnss_response(const dnsd_question_request *request)
llarp::LogDebug("Sending 404, ", out_bytes, " bytes");
// struct llarp_udp_io *udp = (struct llarp_udp_io *)request->user;
request->sendto_hook(request->user, request->from,
llarp::InitBuffer(buf, out_bytes));
CopyableBuffer(llarp_buffer_t(buf, out_bytes)));
}
void
@ -138,7 +141,7 @@ writecname_dnss_response(std::string cname,
llarp::LogDebug("Sending cname, ", out_bytes, " bytes");
// struct llarp_udp_io *udp = (struct llarp_udp_io *)request->user;
request->sendto_hook(request->user, request->from,
llarp::InitBuffer(buf, out_bytes));
CopyableBuffer(llarp_buffer_t(buf, out_bytes)));
}
void
@ -176,7 +179,7 @@ writesend_dnss_revresponse(std::string reverse,
llarp::LogDebug("Sending reverse: ", reverse, " ", out_bytes, " bytes");
// struct llarp_udp_io *udp = (struct llarp_udp_io *)request->user;
request->sendto_hook(request->user, request->from,
llarp::InitBuffer(buf, out_bytes));
CopyableBuffer(llarp_buffer_t(buf, out_bytes)));
}
// FIXME: we need an DNS answer not a sockaddr
@ -242,7 +245,7 @@ writesend_dnss_response(llarp::huint32_t *hostRes,
llarp::LogDebug("Sending found, ", out_bytes, " bytes");
// struct llarp_udp_io *udp = (struct llarp_udp_io *)request->user;
request->sendto_hook(request->user, request->from,
llarp::InitBuffer(buf, out_bytes));
CopyableBuffer(llarp_buffer_t(buf, out_bytes)));
}
void
@ -282,7 +285,8 @@ writesend_dnss_mxresponse(uint16_t priority, std::string mx,
uint32_t out_bytes = write_buffer - bufferBegin;
llarp::LogDebug("Sending found, ", out_bytes, " bytes");
// struct llarp_udp_io *udp = (struct llarp_udp_io *)request->user;
request->sendto_hook(request->user, from, llarp::InitBuffer(buf, out_bytes));
request->sendto_hook(request->user, from,
CopyableBuffer(llarp_buffer_t(buf, out_bytes)));
}
void
@ -322,7 +326,8 @@ writesend_dnss_txtresponse(std::string txt, const struct sockaddr *from,
uint32_t out_bytes = write_buffer - bufferBegin;
llarp::LogDebug("Sending found, ", out_bytes, " bytes");
// struct llarp_udp_io *udp = (struct llarp_udp_io *)request->user;
request->sendto_hook(request->user, from, llarp::InitBuffer(buf, out_bytes));
request->sendto_hook(request->user, from,
CopyableBuffer(llarp_buffer_t(buf, out_bytes)));
}
void
@ -342,7 +347,7 @@ handle_dnsc_result(dnsc_answer_request *client_request)
// bytes");
server_request->sendto_hook(server_request->user, server_request->from,
llarp::Buffer(test));
CopyableBuffer(llarp_buffer_t(test)));
llarp_host_resolved(client_request);
return;
@ -509,7 +514,7 @@ handle_recvfrom(llarp_buffer_t *buffer, dnsd_question_request *request)
void
llarp_handle_dnsd_recvfrom(struct llarp_udp_io *udp,
const struct sockaddr *saddr, llarp_buffer_t buf)
const struct sockaddr *saddr, CopyableBuffer buf)
{
if(!dns_udp_tracker.dnsd)
{
@ -526,12 +531,12 @@ llarp_handle_dnsd_recvfrom(struct llarp_udp_io *udp,
llarp_dns_request->sendto_hook =
&llarp_sendto_dns_hook_func; // set sock hook
// llarp::LogInfo("Server request's UDP ", llarp_dns_request->user);
handle_recvfrom(&buf, llarp_dns_request);
handle_recvfrom(&buf.underlying, llarp_dns_request);
}
void
raw_handle_recvfrom(int *sockfd, const struct sockaddr *saddr,
llarp_buffer_t buffer)
CopyableBuffer buffer)
{
if(!dns_udp_tracker.dnsd)
{
@ -546,7 +551,7 @@ raw_handle_recvfrom(int *sockfd, const struct sockaddr *saddr,
llarp_dns_request->llarp = false;
llarp_dns_request->sendto_hook = &raw_sendto_dns_hook_func;
handle_recvfrom(&buffer, llarp_dns_request);
handle_recvfrom(&buffer.underlying, llarp_dns_request);
}
bool

View File

@ -16,7 +16,7 @@ struct dnsd_context;
/// sendto hook functor
using sendto_dns_hook_func = std::function< ssize_t(
void *sock, const struct sockaddr *from, llarp_buffer_t) >;
void *sock, const struct sockaddr *from, CopyableBuffer) >;
// FIXME: llarp::Addr
/// DNS server query request
@ -53,7 +53,7 @@ struct dnsd_query_hook_response
/// called by the llarp_handle_dns_recvfrom generic (dnsd/dnsc) handler in dns
void
llarp_handle_dnsd_recvfrom(struct llarp_udp_io *udp,
const struct sockaddr *addr, llarp_buffer_t buf);
const struct sockaddr *addr, CopyableBuffer buf);
//
// output structures/functions:

View File

@ -221,7 +221,7 @@ llarp_ev_add_tun(llarp_ev_loop *loop, llarp_tun_io *tun)
#ifndef _WIN32
bool
llarp_ev_tun_async_write(struct llarp_tun_io *tun, llarp_buffer_t buf)
llarp_ev_tun_async_write(struct llarp_tun_io *tun, const llarp_buffer_t &buf)
{
if(buf.sz > EV_WRITE_BUF_SZ)
{
@ -232,7 +232,7 @@ llarp_ev_tun_async_write(struct llarp_tun_io *tun, llarp_buffer_t buf)
}
#else
bool
llarp_ev_tun_async_write(struct llarp_tun_io *tun, llarp_buffer_t buf)
llarp_ev_tun_async_write(struct llarp_tun_io *tun, const llarp_buffer_t &buf)
{
if(buf.sz > EV_WRITE_BUF_SZ)
{
@ -245,24 +245,27 @@ llarp_ev_tun_async_write(struct llarp_tun_io *tun, llarp_buffer_t buf)
#endif
bool
llarp_tcp_conn_async_write(struct llarp_tcp_conn *conn, llarp_buffer_t buf)
llarp_tcp_conn_async_write(struct llarp_tcp_conn *conn, const llarp_buffer_t &b)
{
CopyableBuffer buf{b};
llarp::tcp_conn *impl = static_cast< llarp::tcp_conn * >(conn->impl);
if(impl->_shouldClose)
{
llarp::LogError("write on closed connection");
return false;
}
size_t sz = buf.sz;
buf.cur = buf.base;
size_t sz = buf.underlying.sz;
buf.underlying.cur = buf.underlying.base;
while(sz > EV_WRITE_BUF_SZ)
{
if(!impl->queue_write(buf.cur, EV_WRITE_BUF_SZ))
if(!impl->queue_write(buf.underlying.cur, EV_WRITE_BUF_SZ))
{
return false;
buf.cur += EV_WRITE_BUF_SZ;
}
buf.underlying.cur += EV_WRITE_BUF_SZ;
sz -= EV_WRITE_BUF_SZ;
}
return impl->queue_write(buf.cur, sz);
return impl->queue_write(buf.underlying.cur, sz);
}
void

View File

@ -1,7 +1,7 @@
#ifndef LLARP_EV_H
#define LLARP_EV_H
#include <util/buffer.h>
#include <util/buffer.hpp>
#include <util/time.hpp>
#include <tuntap.h>
@ -77,7 +77,7 @@ struct llarp_udp_io
void (*tick)(struct llarp_udp_io *);
/// sockaddr * is the source address
void (*recvfrom)(struct llarp_udp_io *, const struct sockaddr *,
llarp_buffer_t);
CopyableBuffer);
};
/// add UDP handler
@ -107,7 +107,7 @@ struct llarp_tcp_conn
/// parent loop (dont set me)
struct llarp_ev_loop *loop;
/// handle read event
void (*read)(struct llarp_tcp_conn *, llarp_buffer_t);
void (*read)(struct llarp_tcp_conn *, const llarp_buffer_t &);
/// handle close event (free-ing is handled by event loop)
void (*closed)(struct llarp_tcp_conn *);
/// handle event loop tick
@ -117,7 +117,7 @@ struct llarp_tcp_conn
/// queue async write a buffer in full
/// return if we queueed it or not
bool
llarp_tcp_conn_async_write(struct llarp_tcp_conn *, llarp_buffer_t);
llarp_tcp_conn_async_write(struct llarp_tcp_conn *, const llarp_buffer_t &);
/// close a tcp connection
void
@ -214,6 +214,6 @@ llarp_ev_add_tun(struct llarp_ev_loop *ev, struct llarp_tun_io *tun);
/// async write a packet on tun interface
/// returns true if queued, returns false on drop
bool
llarp_ev_tun_async_write(struct llarp_tun_io *tun, llarp_buffer_t);
llarp_ev_tun_async_write(struct llarp_tun_io *tun, const llarp_buffer_t &);
#endif

View File

@ -2,7 +2,7 @@
#define LLARP_EV_HPP
#include <ev/ev.h>
#include <util/buffer.h>
#include <util/buffer.hpp>
#include <util/codel.hpp>
#include <util/threading.hpp>

View File

@ -4,7 +4,7 @@
#include <ev/ev.hpp>
#include <net/net.h>
#include <net/net.hpp>
#include <util/buffer.h>
#include <util/buffer.hpp>
#include <util/buffer.hpp>
#include <util/logger.hpp>
#include <util/mem.hpp>

View File

@ -8,7 +8,7 @@ namespace llarp
if(sz == 0)
{
if(tcp.read)
tcp.read(&tcp, llarp::InitBuffer(nullptr, 0));
tcp.read(&tcp, {nullptr, nullptr, 0});
return 0;
}
if(_shouldClose)
@ -19,7 +19,7 @@ namespace llarp
if(amount >= 0)
{
if(tcp.read)
tcp.read(&tcp, llarp::InitBuffer(buf, amount));
tcp.read(&tcp, llarp_buffer_t(buf, amount));
}
else
{
@ -148,7 +148,7 @@ namespace llarp
llarp::LogWarn("no source addr");
}
// Addr is the source
udp->recvfrom(udp, addr, llarp::InitBuffer(buf, ret));
udp->recvfrom(udp, addr, CopyableBuffer{llarp_buffer_t(buf, ret)});
return 0;
}
@ -237,7 +237,7 @@ namespace llarp
{
buf += offset;
ret -= offset;
auto pkt = llarp::InitBuffer(buf, ret);
llarp_buffer_t pkt(buf, ret);
t->recvpkt(t, pkt);
}
return ret;

View File

@ -4,7 +4,7 @@
#include <ev/ev.hpp>
#include <net/net.h>
#include <net/net.hpp>
#include <util/buffer.h>
#include <util/buffer.hpp>
#include <util/logger.hpp>
#include <sys/un.h>

View File

@ -3,7 +3,7 @@
#include <ev/ev.hpp>
#include <net/net.h>
#include <net/net.hpp>
#include <util/buffer.h>
#include <util/buffer.hpp>
#include <util/logger.hpp>
#include <windows.h>

View File

@ -24,7 +24,7 @@ namespace llarp
}
bool
CloseExitMessage::DecodeKey(const llarp_buffer_t &k, llarp_buffer_t* buf)
CloseExitMessage::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf)
{
bool read = false;
if(!BEncodeMaybeReadDictInt("S", S, read, k, buf))
@ -41,8 +41,8 @@ namespace llarp
bool
CloseExitMessage::Verify(llarp::Crypto* c, const llarp::PubKey& pk) const
{
byte_t tmp[512] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, 512 > tmp;
llarp_buffer_t buf(tmp);
CloseExitMessage copy;
copy = *this;
copy.Z.Zero();
@ -55,8 +55,8 @@ namespace llarp
bool
CloseExitMessage::Sign(llarp::Crypto* c, const llarp::SecretKey& sk)
{
byte_t tmp[512] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, 512 > tmp;
llarp_buffer_t buf(tmp);
Z.Zero();
Y.Randomize();
if(!BEncode(&buf))

View File

@ -86,14 +86,14 @@ namespace llarp
}
bool
Endpoint::QueueOutboundTraffic(llarp_buffer_t buf, uint64_t counter)
Endpoint::QueueOutboundTraffic(CopyableBuffer buf, uint64_t counter)
{
// queue overflow
if(m_UpstreamQueue.size() > MaxUpstreamQueueSize)
return false;
llarp::net::IPv4Packet pkt;
if(!pkt.Load(buf))
if(!pkt.Load(buf.underlying))
return false;
huint32_t dst;
@ -103,16 +103,16 @@ namespace llarp
dst = pkt.dst();
pkt.UpdateIPv4PacketOnDst(m_IP, dst);
m_UpstreamQueue.emplace(pkt, counter);
m_TxRate += buf.sz;
m_TxRate += buf.underlying.sz;
m_LastActive = m_Parent->Now();
return true;
}
bool
Endpoint::QueueInboundTraffic(llarp_buffer_t buf)
Endpoint::QueueInboundTraffic(CopyableBuffer buf)
{
llarp::net::IPv4Packet pkt;
if(!pkt.Load(buf))
if(!pkt.Load(buf.underlying))
return false;
huint32_t src;
@ -121,13 +121,13 @@ namespace llarp
else
src = pkt.src();
pkt.UpdateIPv4PacketOnDst(src, m_IP);
auto pktbuf = pkt.Buffer();
uint8_t queue_idx = pktbuf.sz / llarp::routing::ExitPadSize;
auto& queue = m_DownstreamQueues[queue_idx];
const llarp_buffer_t& pktbuf = pkt.Buffer(); // life time extension
uint8_t queue_idx = pktbuf.sz / llarp::routing::ExitPadSize;
auto& queue = m_DownstreamQueues[queue_idx];
if(queue.size() == 0)
{
queue.emplace_back();
return queue.back().PutBuffer(buf, m_Counter++);
return queue.back().PutBuffer(buf.underlying, m_Counter++);
}
auto& msg = queue.back();
if(msg.Size() + pktbuf.sz > llarp::routing::ExitPadSize)

View File

@ -48,7 +48,7 @@ namespace llarp
/// queue traffic from service node / internet to be transmitted
bool
QueueInboundTraffic(llarp_buffer_t buff);
QueueInboundTraffic(CopyableBuffer buff);
/// flush inbound and outbound traffic queues
bool
@ -57,7 +57,7 @@ namespace llarp
/// queue outbound traffic
/// does ip rewrite here
bool
QueueOutboundTraffic(llarp_buffer_t pkt, uint64_t counter);
QueueOutboundTraffic(CopyableBuffer pkt, uint64_t counter);
/// update local path id and cascade information to parent
/// return true if success

View File

@ -26,7 +26,7 @@ namespace llarp
}
bool
GrantExitMessage::DecodeKey(const llarp_buffer_t &k, llarp_buffer_t* buf)
GrantExitMessage::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf)
{
bool read = false;
if(!BEncodeMaybeReadDictInt("S", S, read, k, buf))
@ -45,8 +45,8 @@ namespace llarp
bool
GrantExitMessage::Verify(llarp::Crypto* c, const llarp::PubKey& pk) const
{
byte_t tmp[512] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, 512 > tmp;
llarp_buffer_t buf(tmp);
GrantExitMessage copy;
copy = *this;
copy.Z.Zero();
@ -59,8 +59,8 @@ namespace llarp
bool
GrantExitMessage::Sign(llarp::Crypto* c, const llarp::SecretKey& sk)
{
byte_t tmp[512] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, 512 > tmp;
llarp_buffer_t buf(tmp);
Z.Zero();
Y.Randomize();
if(!BEncode(&buf))

View File

@ -9,9 +9,9 @@ namespace llarp
bool
ObtainExitMessage::Sign(llarp::Crypto* c, const llarp::SecretKey& sk)
{
byte_t tmp[1024] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
I = llarp::seckey_topublic(sk);
std::array< byte_t, 1024 > tmp;
llarp_buffer_t buf(tmp);
I = llarp::seckey_topublic(sk);
Z.Zero();
if(!BEncode(&buf))
{
@ -24,8 +24,8 @@ namespace llarp
bool
ObtainExitMessage::Verify(llarp::Crypto* c) const
{
byte_t tmp[1024] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, 1024 > tmp;
llarp_buffer_t buf(tmp);
ObtainExitMessage copy;
copy = *this;
copy.Z.Zero();
@ -67,7 +67,7 @@ namespace llarp
}
bool
ObtainExitMessage::DecodeKey(const llarp_buffer_t &k, llarp_buffer_t* buf)
ObtainExitMessage::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf)
{
bool read = false;
if(!BEncodeMaybeReadDictList("B", B, read, k, buf))

View File

@ -30,7 +30,7 @@ namespace llarp
}
bool
RejectExitMessage::DecodeKey(const llarp_buffer_t &k, llarp_buffer_t* buf)
RejectExitMessage::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf)
{
bool read = false;
if(!BEncodeMaybeReadDictInt("B", B, read, k, buf))
@ -66,8 +66,8 @@ namespace llarp
bool
RejectExitMessage::Sign(llarp::Crypto* c, const llarp::SecretKey& sk)
{
byte_t tmp[512] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, 512 > tmp;
llarp_buffer_t buf(tmp);
Z.Zero();
Y.Randomize();
if(!BEncode(&buf))
@ -79,8 +79,8 @@ namespace llarp
bool
RejectExitMessage::Verify(llarp::Crypto* c, const llarp::PubKey& pk) const
{
byte_t tmp[512] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, 512 > tmp;
llarp_buffer_t buf(tmp);
RejectExitMessage copy;
copy = *this;
copy.Z.Zero();

View File

@ -149,8 +149,8 @@ namespace llarp
BaseSession::QueueUpstreamTraffic(llarp::net::IPv4Packet pkt,
const size_t N)
{
auto buf = pkt.Buffer();
auto& queue = m_Upstream[buf.sz / N];
const llarp_buffer_t& buf = pkt.Buffer();
auto& queue = m_Upstream[buf.sz / N];
// queue overflow
if(queue.size() >= MaxUpstreamQueueLength)
return false;

View File

@ -26,7 +26,7 @@ namespace llarp
}
bool
UpdateExitMessage::DecodeKey(const llarp_buffer_t &k, llarp_buffer_t* buf)
UpdateExitMessage::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf)
{
bool read = false;
if(!BEncodeMaybeReadDictInt("S", S, read, k, buf))
@ -46,8 +46,8 @@ namespace llarp
UpdateExitMessage::Verify(llarp::Crypto* c, const llarp::PubKey& pk) const
{
byte_t tmp[512] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, 512 > tmp;
llarp_buffer_t buf(tmp);
UpdateExitMessage copy;
copy = *this;
copy.Z.Zero();
@ -72,8 +72,8 @@ namespace llarp
bool
UpdateExitMessage::Sign(llarp::Crypto* c, const llarp::SecretKey& sk)
{
byte_t tmp[512] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, 512 > tmp;
llarp_buffer_t buf(tmp);
Y.Randomize();
if(!BEncode(&buf))
return false;
@ -104,7 +104,8 @@ namespace llarp
}
bool
UpdateExitVerifyMessage::DecodeKey(const llarp_buffer_t &k, llarp_buffer_t* buf)
UpdateExitVerifyMessage::DecodeKey(const llarp_buffer_t& k,
llarp_buffer_t* buf)
{
bool read = false;
if(!BEncodeMaybeReadDictInt("S", S, read, k, buf))

View File

@ -186,7 +186,7 @@ namespace llarp
}
else
{
if(!ep->QueueInboundTraffic(pkt.Buffer()))
if(!ep->QueueInboundTraffic(CopyableBuffer{pkt.Buffer()}))
{
LogWarn(Name(), " dropped inbound traffic for session ", pk,
" as we are overloaded (probably)");
@ -340,7 +340,7 @@ namespace llarp
bool
ExitEndpoint::QueueOutboundTraffic(const llarp_buffer_t &buf)
{
return llarp_ev_tun_async_write(&m_Tun, buf.clone());
return llarp_ev_tun_async_write(&m_Tun, buf);
}
void

View File

@ -532,7 +532,7 @@ namespace llarp
TunEndpoint::FlushSend()
{
m_UserToNetworkPktQueue.Process([&](net::IPv4Packet &pkt) {
std::function< bool(llarp_buffer_t) > sendFunc;
std::function< bool(const llarp_buffer_t &) > sendFunc;
auto itr = m_IPToAddr.find(pkt.dst());
if(itr == m_IPToAddr.end())
{

View File

@ -178,11 +178,11 @@ namespace llarp
bool
QueueInboundPacketForExit(const llarp_buffer_t& buf)
{
llarp_buffer_t copy = buf.clone();
CopyableBuffer copy{buf};
return m_NetworkToUserPktQueue.EmplaceIf(
[&](llarp::net::IPv4Packet& pkt) -> bool {
if(!pkt.Load(copy))
if(!pkt.Load(copy.underlying))
return false;
pkt.UpdateIPv4PacketOnDst(pkt.src(), m_OurIP);
return true;

View File

@ -35,7 +35,7 @@ namespace llarp
TickIO(llarp_time_t now);
bool
QueueMessageBuffer(const llarp_buffer_t& buf);
QueueMessageBuffer(const llarp_buffer_t &buf);
/// return true if the session is established and handshaked and all that
/// jazz
@ -142,7 +142,7 @@ namespace llarp
}
bool
Encode(llarp_buffer_t *buf, llarp_buffer_t body)
Encode(llarp_buffer_t *buf, const llarp_buffer_t &body)
{
if(body.sz > fragsize)
return false;
@ -234,7 +234,8 @@ namespace llarp
hdr.seqno = seqno;
hdr.cmd = XMIT;
AlignedBuffer< fragoverhead + fragsize > frag;
auto buf = frag.as_buffer();
CopyableBuffer copiedBuffer(frag.as_buffer());
auto &buf = copiedBuffer.underlying;
const byte_t *ptr = msg.data();
Fragno_t idx = 0;
FragLen_t len = sz;
@ -245,7 +246,7 @@ namespace llarp
{
hdr.fragno = idx;
hdr.fraglen = l;
if(!hdr.Encode(&buf, llarp::InitBuffer(ptr, l)))
if(!hdr.Encode(&buf, llarp_buffer_t(ptr, l)))
return false;
buf.sz = buf.cur - buf.base;
buf.cur = buf.base;
@ -281,8 +282,9 @@ namespace llarp
hdr.fraglen = 0;
hdr.fragno = 0;
AlignedBuffer< fragoverhead > frag;
auto buf = frag.as_buffer();
if(!hdr.Encode(&buf, llarp::InitBuffer(nullptr, 0)))
CopyableBuffer copiedBuffer(frag.as_buffer());
auto &buf = copiedBuffer.underlying;
if(!hdr.Encode(&buf, llarp_buffer_t(nullptr, nullptr, 0)))
return false;
return write_pkt(buf.base, buf.sz) == int(buf.sz);
}

View File

@ -76,7 +76,7 @@ namespace llarp
}
static void
udp_recv_from(llarp_udp_io* udp, const sockaddr* from, llarp_buffer_t buf)
udp_recv_from(llarp_udp_io* udp, const sockaddr* from, CopyableBuffer buf)
{
if(!udp)
{
@ -85,7 +85,8 @@ namespace llarp
}
// maybe check from too?
// no it's never null
static_cast< ILinkLayer* >(udp->user)->RecvFrom(*from, buf.base, buf.sz);
static_cast< ILinkLayer* >(udp->user)->RecvFrom(
*from, buf.underlying.base, buf.underlying.sz);
}
void

View File

@ -140,7 +140,7 @@ namespace llarp
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)))
if(!Crypto()->shorthash(t_h, llarp_buffer_t(tmp)))
{
llarp::LogError("failed to mix key to ", remoteAddr);
return false;
@ -160,7 +160,7 @@ namespace llarp
Session::MutateKey(SharedSecret& K, const AlignedBuffer< 24 >& A)
{
AlignedBuffer< 56 > tmp;
auto buf = tmp.as_buffer();
llarp_buffer_t buf{tmp};
std::copy(K.begin(), K.end(), buf.cur);
buf.cur += K.size();
std::copy(A.begin(), A.end(), buf.cur);
@ -580,8 +580,8 @@ namespace llarp
&& now - lastActive > 5000)
{
DiscardMessage msg;
byte_t tmp[128] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, 128 > tmp;
llarp_buffer_t buf(tmp);
if(!msg.BEncode(&buf))
return false;
buf.sz = buf.cur - buf.base;
@ -622,9 +622,9 @@ namespace llarp
remoteTransportPubKey = addr.pubkey;
remoteRC = rc;
RouterID rid = remoteRC.pubkey;
Crypto()->shorthash(txKey, rid.as_buffer());
Crypto()->shorthash(txKey, rid.as_buffer().underlying);
rid = p->GetOurRC().pubkey;
Crypto()->shorthash(rxKey, rid.as_buffer());
Crypto()->shorthash(rxKey, rid.as_buffer().underlying);
sock = s;
assert(utp_set_userdata(sock, this) == this);
@ -638,7 +638,7 @@ namespace llarp
Session::Session(LinkLayer* p, utp_socket* s, const Addr& addr) : Session(p)
{
RouterID rid = p->GetOurRC().pubkey;
Crypto()->shorthash(rxKey, rid.as_buffer());
Crypto()->shorthash(rxKey, rid.as_buffer().underlying);
remoteRC.Clear();
sock = s;
assert(s == sock);
@ -665,7 +665,7 @@ namespace llarp
if(!gotLIM)
{
remoteRC = msg->rc;
Crypto()->shorthash(txKey, remoteRC.pubkey.as_buffer());
Crypto()->shorthash(txKey, remoteRC.pubkey.as_buffer().underlying);
if(!DoKeyExchange(std::bind(&Crypto::transport_dh_server, Crypto(), _1,
_2, _3, _4),
@ -673,8 +673,8 @@ namespace llarp
parent->TransportSecretKey()))
return false;
byte_t tmp[LinkIntroMessage::MaxSize];
auto buf = StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, LinkIntroMessage::MaxSize > tmp;
llarp_buffer_t buf(tmp);
LinkIntroMessage replymsg;
replymsg.rc = parent->GetOurRC();
if(!replymsg.rc.Verify(Crypto(), parent->Now()))
@ -785,8 +785,8 @@ namespace llarp
void
Session::OutboundHandshake()
{
byte_t tmp[LinkIntroMessage::MaxSize];
auto buf = StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, LinkIntroMessage::MaxSize > tmp;
llarp_buffer_t buf(tmp);
// build our RC
LinkIntroMessage msg;
msg.rc = parent->GetOurRC();
@ -955,8 +955,8 @@ namespace llarp
// put body
memcpy(body, ptr, length);
auto payload =
InitBuffer(base, FragmentBufferSize - FragmentOverheadSize);
llarp_buffer_t payload(base, base,
FragmentBufferSize - FragmentOverheadSize);
TunnelNonce nonce(noncePtr);
@ -997,7 +997,7 @@ namespace llarp
}
// set remote rc
remoteRC = msg->rc;
// recalcuate rx key
// recalculate rx key
return DoKeyExchange(
std::bind(&Crypto::transport_dh_server, Crypto(), _1, _2, _3, _4),
rxKey, msg->N, remoteRC.enckey, parent->RouterEncryptionSecret());
@ -1006,14 +1006,15 @@ namespace llarp
bool
Session::Rehandshake()
{
byte_t tmp[LinkIntroMessage::MaxSize];
LinkIntroMessage lim;
lim.rc = parent->GetOurRC();
lim.N.Randomize();
lim.P = 60 * 1000 * 10;
if(!lim.Sign(parent->Sign))
return false;
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, LinkIntroMessage::MaxSize > tmp;
llarp_buffer_t buf(tmp);
if(!lim.BEncode(&buf))
return false;
// rewind and resize buffer
@ -1034,8 +1035,8 @@ namespace llarp
llarp::LogDebug("verify then decrypt ", remoteAddr);
ShortHash digest;
auto hbuf = InitBuffer(ptr + FragmentHashSize,
FragmentBufferSize - FragmentHashSize);
llarp_buffer_t hbuf(ptr + FragmentHashSize,
FragmentBufferSize - FragmentHashSize);
if(!Crypto()->hmac(digest.data(), hbuf, rxKey))
{
llarp::LogError("keyed hash failed");
@ -1050,37 +1051,39 @@ namespace llarp
return false;
}
auto in = InitBuffer(ptr + FragmentOverheadSize,
FragmentBufferSize - FragmentOverheadSize);
llarp_buffer_t in(ptr + FragmentOverheadSize,
FragmentBufferSize - FragmentOverheadSize);
llarp_buffer_t out = rxFragBody.as_buffer();
CopyableBuffer out = rxFragBody.as_buffer();
// decrypt
if(!Crypto()->xchacha20_alt(out, in, rxKey, ptr + FragmentHashSize))
if(!Crypto()->xchacha20_alt(out.underlying, in, rxKey,
ptr + FragmentHashSize))
{
llarp::LogError("failed to decrypt message from ", remoteAddr);
return false;
}
// get inner nonce
AlignedBuffer< 24 > A(out.base);
AlignedBuffer< 24 > A(out.underlying.base);
// advance buffer
out.cur += A.size();
out.underlying.cur += A.size();
// read msgid
uint32_t msgid;
if(!llarp_buffer_read_uint32(&out, &msgid))
if(!llarp_buffer_read_uint32(&out.underlying, &msgid))
{
llarp::LogError("failed to read msgid");
return false;
}
// read length and remaining
uint16_t length, remaining;
if(!(llarp_buffer_read_uint16(&out, &length)
&& llarp_buffer_read_uint16(&out, &remaining)))
if(!(llarp_buffer_read_uint16(&out.underlying, &length)
&& llarp_buffer_read_uint16(&out.underlying, &remaining)))
{
llarp::LogError("failed to read the rest of the header");
return false;
}
if(length > (out.sz - (out.cur - out.base)))
if(length
> (out.underlying.sz - (out.underlying.cur - out.underlying.base)))
{
// too big length
llarp::LogError("fragment body too big");
@ -1100,7 +1103,7 @@ namespace llarp
// add message activity
itr->second.lastActive = parent->Now();
// append data
if(!itr->second.AppendData(out.cur, length))
if(!itr->second.AppendData(out.underlying.cur, length))
{
llarp::LogError("inbound buffer is full");
return false; // not enough room
@ -1116,14 +1119,14 @@ namespace llarp
{
// we done with this guy, prune next tick
itr->second.lastActive = 0;
llarp_buffer_t buf(itr->second.buffer.clone());
CopyableBuffer buf(itr->second.buffer);
// resize
buf.sz = buf.cur - buf.base;
buf.underlying.sz = buf.underlying.cur - buf.underlying.base;
// rewind
buf.cur = buf.base;
buf.underlying.cur = buf.underlying.base;
// process buffer
llarp::LogDebug("got message ", msgid, " from ", remoteAddr);
return parent->HandleMessage(this, buf);
return parent->HandleMessage(this, buf.underlying);
}
return true;
}

View File

@ -61,7 +61,7 @@ namespace llarp
/// for accessing message buffer
llarp_buffer_t buffer;
InboundMessage() : lastActive(0), _msg(), buffer(_msg.as_buffer())
InboundMessage() : lastActive(0), _msg(), buffer(_msg)
{
}

View File

@ -136,8 +136,8 @@ namespace llarp
std::function< bool(Signature&, const llarp_buffer_t&) > signer)
{
Z.Zero();
byte_t tmp[MaxSize] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, MaxSize > tmp;
llarp_buffer_t buf(tmp);
if(!BEncode(&buf))
return false;
buf.sz = buf.cur - buf.base;
@ -151,8 +151,8 @@ namespace llarp
LinkIntroMessage copy;
copy = *this;
copy.Z.Zero();
byte_t tmp[MaxSize] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, MaxSize > tmp;
llarp_buffer_t buf(tmp);
if(!copy.BEncode(&buf))
return false;
buf.sz = buf.cur - buf.base;

View File

@ -102,8 +102,8 @@ namespace llarp
reader.on_key = &OnKey;
from = src;
firstkey = true;
llarp_buffer_t copy(buf.clone());
return bencode_read_dict(&copy, &reader);
CopyableBuffer copy(buf);
return bencode_read_dict(&copy.underlying, &reader);
}
void

View File

@ -41,7 +41,8 @@ namespace llarp
}
bool
RelayUpstreamMessage::DecodeKey(const llarp_buffer_t &key, llarp_buffer_t *buf)
RelayUpstreamMessage::DecodeKey(const llarp_buffer_t &key,
llarp_buffer_t *buf)
{
bool read = false;
if(!BEncodeMaybeReadDictEntry("p", pathid, read, key, buf))
@ -62,7 +63,7 @@ namespace llarp
auto path = r->paths.GetByDownstream(session->GetPubKey(), pathid);
if(path)
{
return path->HandleUpstream(X.Buffer(), Y, r);
return path->HandleUpstream(X.Buffer().underlying, Y, r);
}
return false;
}
@ -103,7 +104,8 @@ namespace llarp
}
bool
RelayDownstreamMessage::DecodeKey(const llarp_buffer_t &key, llarp_buffer_t *buf)
RelayDownstreamMessage::DecodeKey(const llarp_buffer_t &key,
llarp_buffer_t *buf)
{
bool read = false;
if(!BEncodeMaybeReadDictEntry("p", pathid, read, key, buf))
@ -124,7 +126,7 @@ namespace llarp
auto path = r->paths.GetByUpstream(session->GetPubKey(), pathid);
if(path)
{
return path->HandleDownstream(X.Buffer(), Y, r);
return path->HandleDownstream(X.Buffer().underlying, Y, r);
}
llarp::LogWarn("unhandled downstream message");
return false;

View File

@ -14,7 +14,7 @@ namespace llarp
}
bool
LR_CommitMessage::DecodeKey(const llarp_buffer_t &key, llarp_buffer_t* buf)
LR_CommitMessage::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf)
{
if(llarp_buffer_eq(key, "c"))
{
@ -279,7 +279,7 @@ namespace llarp
return;
}
// generate hash of hop key for nonce mutation
crypto->shorthash(self->hop->nonceXOR, self->hop->pathKey.as_buffer());
crypto->shorthash(self->hop->nonceXOR, self->hop->pathKey.as_buffer().underlying);
using namespace std::placeholders;
if(self->record.work
&& self->record.work->IsValid(

View File

@ -28,13 +28,13 @@ namespace llarp
llarp_buffer_t
IPv4Packet::ConstBuffer() const
{
return llarp::InitBuffer(buf, sz);
return {buf, sz};
}
llarp_buffer_t
IPv4Packet::Buffer()
{
return llarp::InitBuffer(buf, sz);
return {buf, sz};
}
#if 0

View File

@ -3,7 +3,7 @@
#include <ev/ev.h>
#include <net/net.hpp>
#include <util/buffer.h>
#include <util/buffer.hpp>
#include <util/time.hpp>
#ifndef _WIN32

View File

@ -102,8 +102,8 @@ llarp_nodedb::InsertAsync(llarp::RouterContact rc)
bool
llarp_nodedb::Insert(const llarp::RouterContact &rc)
{
byte_t tmp[MAX_RC_SIZE];
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, MAX_RC_SIZE > tmp;
llarp_buffer_t buf(tmp);
{
llarp::util::Lock lock(access);
entries.emplace(rc.pubkey.as_array(), rc);

View File

@ -588,8 +588,8 @@ namespace llarp
Path::SendRoutingMessage(const llarp::routing::IMessage* msg,
llarp::Router* r)
{
byte_t tmp[MAX_LINK_MSG_SIZE / 2];
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, MAX_LINK_MSG_SIZE / 2 > tmp;
llarp_buffer_t buf(tmp);
// should help prevent bad paths with uninitialised members
// FIXME: Why would we get uninitialised IMessages?
if(msg->version != LLARP_PROTO_VERSION)
@ -840,7 +840,7 @@ namespace llarp
return false;
uint64_t counter = bufbe64toh(pkt.data());
m_ExitTrafficHandler(
this, llarp::InitBuffer(pkt.data() + 8, pkt.size() - 8), counter);
this, llarp_buffer_t(pkt.data() + 8, pkt.size() - 8), counter);
}
return sent;
}

View File

@ -57,7 +57,7 @@ namespace llarp
return;
}
// generate nonceXOR valueself->hop->pathKey
ctx->crypto->shorthash(hop.nonceXOR, hop.shared.as_buffer());
ctx->crypto->shorthash(hop.nonceXOR, hop.shared.as_buffer().underlying);
++ctx->idx;
bool isFarthestHop = ctx->idx == ctx->path->hops.size();

View File

@ -59,8 +59,9 @@ namespace llarp
{
if(!IsEndpoint(r->pubkey()))
return false;
byte_t tmp[MAX_LINK_MSG_SIZE - 128];
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, MAX_LINK_MSG_SIZE - 128 > tmp;
llarp_buffer_t buf(tmp);
if(!msg->BEncode(&buf))
{
llarp::LogError("failed to encode routing message");
@ -83,8 +84,8 @@ namespace llarp
}
bool
TransitHop::HandleDownstream(const llarp_buffer_t& buf, const TunnelNonce& Y,
llarp::Router* r)
TransitHop::HandleDownstream(const llarp_buffer_t& buf,
const TunnelNonce& Y, llarp::Router* r)
{
RelayDownstreamMessage msg;
msg.pathid = info.rxID;
@ -269,7 +270,8 @@ namespace llarp
continue;
uint64_t counter = bufbe64toh(pkt.data());
sent &= endpoint->QueueOutboundTraffic(
llarp::InitBuffer(pkt.data() + 8, pkt.size() - 8), counter);
CopyableBuffer(llarp_buffer_t(pkt.data() + 8, pkt.size() - 8)),
counter);
}
return sent;
}
@ -291,8 +293,8 @@ namespace llarp
return SendRoutingMessage(&discarded, r);
}
byte_t tmp[service::MAX_PROTOCOL_MESSAGE_SIZE];
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, service::MAX_PROTOCOL_MESSAGE_SIZE > tmp;
llarp_buffer_t buf(tmp);
if(!msg->T.BEncode(&buf))
{
llarp::LogWarn(info, " failed to transfer data message, encode failed");

View File

@ -34,8 +34,8 @@ namespace llarp
return false;
ShortHash digest;
byte_t tmp[MaxSize];
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, MaxSize > tmp;
llarp_buffer_t buf(tmp);
// encode
if(!BEncode(&buf))
return false;

View File

@ -25,7 +25,7 @@ namespace llarp
}
bool
RouterProfile::DecodeKey(const llarp_buffer_t &k, llarp_buffer_t* buf)
RouterProfile::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf)
{
bool read = false;
if(!BEncodeMaybeReadDictInt("g", connectGoodCount, read, k, buf))
@ -101,7 +101,7 @@ namespace llarp
size_t sz = (m_Profiles.size() * (RouterProfile::MaxSize + 32 + 8)) + 8;
std::vector< byte_t > tmp(sz, 0);
auto buf = llarp::Buffer(tmp);
llarp_buffer_t buf(tmp);
auto res = BEncode(&buf);
if(res)
{
@ -134,7 +134,7 @@ namespace llarp
}
bool
Profiling::DecodeKey(const llarp_buffer_t &k, llarp_buffer_t* buf)
Profiling::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf)
{
if(k.sz != 32)
return false;

View File

@ -298,8 +298,7 @@ namespace llarp
outboundMessageQueue.insert(std::make_pair(remote, MessageQueue()));
}
// encode
llarp_buffer_t buf =
llarp::StackBuffer< decltype(linkmsg_buffer) >(linkmsg_buffer);
llarp_buffer_t buf(linkmsg_buffer);
if(!msg->BEncode(&buf))
return false;
// queue buffer
@ -825,8 +824,7 @@ namespace llarp
Router::SendTo(llarp::RouterID remote, const llarp::ILinkMessage *msg,
llarp::ILinkLayer *selected)
{
llarp_buffer_t buf =
llarp::StackBuffer< decltype(linkmsg_buffer) >(linkmsg_buffer);
llarp_buffer_t buf(linkmsg_buffer);
if(!msg->BEncode(&buf))
{
@ -906,7 +904,7 @@ namespace llarp
}
while(itr->second.size())
{
auto buf = llarp::ConstBuffer(itr->second.front());
llarp_buffer_t buf(itr->second.front());
if(!chosen->SendTo(remote, buf))
llarp::LogWarn("failed to send outbound message to ", remote, " via ",
chosen->Name());

View File

@ -16,7 +16,7 @@
#include <routing/message_parser.hpp>
#include <rpc/rpc.hpp>
#include <service/context.hpp>
#include <util/buffer.h>
#include <util/buffer.hpp>
#include <util/fs.hpp>
#include <util/logic.hpp>
#include <util/mem.hpp>
@ -120,7 +120,7 @@ namespace llarp
llarp_nodedb *nodedb;
// buffer for serializing link messages
byte_t linkmsg_buffer[MAX_LINK_MSG_SIZE];
std::array< byte_t, MAX_LINK_MSG_SIZE > linkmsg_buffer;
/// always maintain this many connections to other routers
size_t minConnectedRouters = 1;

View File

@ -243,9 +243,9 @@ namespace llarp
bool
RouterContact::Sign(llarp::Crypto *crypto, const SecretKey &secretkey)
{
pubkey = llarp::seckey_topublic(secretkey);
byte_t tmp[MAX_RC_SIZE] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
pubkey = llarp::seckey_topublic(secretkey);
std::array< byte_t, MAX_RC_SIZE > tmp;
llarp_buffer_t buf(tmp);
signature.Zero();
last_updated = time_now_ms();
if(!BEncode(&buf))
@ -296,8 +296,8 @@ namespace llarp
RouterContact copy;
copy = *this;
copy.signature.Zero();
byte_t tmp[MAX_RC_SIZE] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, MAX_RC_SIZE > tmp;
llarp_buffer_t buf(tmp);
if(!copy.BEncode(&buf))
{
llarp::LogError("bencode failed");
@ -311,8 +311,8 @@ namespace llarp
bool
RouterContact::Write(const char *fname) const
{
byte_t tmp[MAX_RC_SIZE] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, MAX_RC_SIZE > tmp;
llarp_buffer_t buf(tmp);
if(!BEncode(&buf))
return false;
buf.sz = buf.cur - buf.base;
@ -328,7 +328,8 @@ namespace llarp
bool
RouterContact::Read(const char *fname)
{
byte_t tmp[MAX_RC_SIZE] = {0};
std::array< byte_t, MAX_RC_SIZE > tmp;
llarp_buffer_t buf(tmp);
std::ifstream f;
f.open(fname, std::ios::binary);
if(!f.is_open())
@ -338,11 +339,10 @@ namespace llarp
}
f.seekg(0, std::ios::end);
size_t l = f.tellg();
if(l > sizeof(tmp))
if(l > tmp.size())
return false;
f.seekg(0, std::ios::beg);
f.read((char *)tmp, l);
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
f.read((char *)tmp.data(), l);
return BDecode(&buf);
}

View File

@ -6,7 +6,7 @@
#include <messages/path_latency.hpp>
#include <messages/path_transfer.hpp>
#include <messages/transfer_traffic.hpp>
#include <util/buffer.h>
#include <util/buffer.hpp>
namespace llarp
{

View File

@ -3,7 +3,7 @@
#include <path/path_types.hpp>
#include <util/bencode.hpp>
#include <util/buffer.h>
#include <util/buffer.hpp>
namespace llarp
{

View File

@ -95,7 +95,8 @@ namespace llarp
bool result = false;
msg = nullptr;
firstKey = true;
llarp_buffer_t copy(buf.clone());
CopyableBuffer copiedBuf(buf);
auto& copy = copiedBuf.underlying;
if(bencode_read_dict(&copy, &reader))
{
msg->from = from;

View File

@ -8,7 +8,7 @@
#include <messages/path_transfer.hpp>
#include <path/path_types.hpp>
#include <util/bencode.hpp>
#include <util/buffer.h>
#include <util/buffer.hpp>
namespace llarp
{

View File

@ -83,8 +83,8 @@ namespace llarp
bool
Identity::EnsureKeys(const std::string& fname, llarp::Crypto* c)
{
byte_t tmp[4096];
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, 4096 > tmp;
llarp_buffer_t buf(tmp);
std::error_code ec;
// check for file
if(!fs::exists(fname, ec))
@ -145,8 +145,8 @@ namespace llarp
i.K = pq_keypair_to_public(pq);
// zero out signature for signing process
i.Z.Zero();
byte_t tmp[MAX_INTROSET_SIZE];
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, MAX_INTROSET_SIZE > tmp;
llarp_buffer_t buf(tmp);
if(!i.BEncode(&buf))
return false;
// rewind and resize buffer

View File

@ -13,7 +13,7 @@ namespace llarp
}
bool
IntroSet::DecodeKey(const llarp_buffer_t &key, llarp_buffer_t* buf)
IntroSet::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf)
{
bool read = false;
if(!BEncodeMaybeReadDictEntry("a", A, read, key, buf))
@ -109,8 +109,8 @@ namespace llarp
bool
IntroSet::Verify(llarp::Crypto* crypto, llarp_time_t now) const
{
byte_t tmp[MAX_INTROSET_SIZE];
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, MAX_INTROSET_SIZE > tmp;
llarp_buffer_t buf(tmp);
IntroSet copy;
copy = *this;
copy.Z.Zero();

View File

@ -227,8 +227,8 @@ namespace llarp
{
if(HasPendingPathToService(introset.A.Addr()))
continue;
byte_t tmp[1024] = {0};
auto buf = StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, 1024 > tmp = {0};
llarp_buffer_t buf(tmp);
if(!SendToServiceOrQueue(introset.A.Addr().data().data(), buf,
eProtocolText))
{
@ -879,7 +879,7 @@ namespace llarp
{
if(msg->proto == eProtocolTraffic)
{
auto buf = llarp::Buffer(msg->payload);
llarp_buffer_t buf(msg->payload);
return HandleWriteIPPacket(buf,
std::bind(&Endpoint::ObtainIPForAddr, this,
msg->sender.Addr(), false));
@ -1157,7 +1157,8 @@ namespace llarp
}
bool
Endpoint::SendToSNodeOrQueue(const RouterID& addr, const llarp_buffer_t& buf)
Endpoint::SendToSNodeOrQueue(const RouterID& addr,
const llarp_buffer_t& buf)
{
llarp::net::IPv4Packet pkt;
if(!pkt.Load(buf))
@ -1502,13 +1503,12 @@ namespace llarp
{
llarp::LogError("failed to derive x25519 shared key component");
}
std::array< byte_t, 64 > tmp;
std::array< byte_t, 64 > tmp = {0};
// K
std::copy(K.begin(), K.end(), tmp.begin());
// H (K + PKE(A, B, N))
std::copy(sharedSecret.begin(), sharedSecret.end(), tmp.begin() + 32);
self->crypto->shorthash(self->sharedKey,
llarp::StackBuffer< decltype(tmp) >(tmp));
self->crypto->shorthash(self->sharedKey, llarp_buffer_t(tmp));
// set tag
self->msg.tag = self->tag;
// set sender

View File

@ -20,7 +20,7 @@ namespace llarp
{
namespace service
{
// foward declare
// forward declare
struct Context;
// forward declare
struct AsyncKeyExchange;
@ -193,10 +193,10 @@ namespace llarp
memcpy(payload.data(), buf.base, buf.sz);
}
llarp_buffer_t
CopyableBuffer
Buffer()
{
return llarp::Buffer(payload);
return CopyableBuffer{llarp_buffer_t(payload)};
}
};

View File

@ -67,8 +67,8 @@ namespace llarp
bool ServiceInfo::CalculateAddress(std::array< byte_t, 32 >& data) const
{
byte_t tmp[256] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, 256 > tmp;
llarp_buffer_t buf(tmp);
if(!BEncode(&buf))
return false;
return crypto_generichash_blake2b(data.data(), data.size(), buf.base,

View File

@ -170,8 +170,8 @@ namespace llarp
const SharedSecret& sessionKey,
const Identity& localIdent)
{
byte_t tmp[MAX_PROTOCOL_MESSAGE_SIZE];
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, MAX_PROTOCOL_MESSAGE_SIZE > tmp;
llarp_buffer_t buf(tmp);
// encode message
if(!msg.BEncode(&buf))
{
@ -187,7 +187,7 @@ namespace llarp
D = buf;
// zero out signature
Z.Zero();
auto buf2 = llarp::StackBuffer< decltype(tmp) >(tmp);
llarp_buffer_t buf2(tmp);
// encode frame
if(!BEncode(&buf2))
{
@ -287,7 +287,7 @@ namespace llarp
std::copy(K.begin(), K.end(), tmp.begin());
// S = HS( K + PKE( A, B, N))
std::copy(sharedSecret.begin(), sharedSecret.end(), tmp.begin() + 32);
crypto->shorthash(sharedKey, StackBuffer< decltype(tmp) >(tmp));
crypto->shorthash(sharedKey, llarp_buffer_t(tmp));
self->handler->PutIntroFor(self->msg->tag, self->msg->introReply);
self->handler->PutSenderFor(self->msg->tag, self->msg->sender);
@ -375,8 +375,8 @@ namespace llarp
// zero out signature for verify
copy.Z.Zero();
// serialize
byte_t tmp[MAX_PROTOCOL_MESSAGE_SIZE];
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, MAX_PROTOCOL_MESSAGE_SIZE > tmp;
llarp_buffer_t buf(tmp);
if(!copy.BEncode(&buf))
{
llarp::LogError("bencode fail");

View File

@ -227,14 +227,10 @@ namespace llarp
return as_array().cend();
}
llarp_buffer_t
CopyableBuffer
as_buffer()
{
llarp_buffer_t buff;
buff.base = data();
buff.cur = buff.base;
buff.sz = size();
return buff;
return CopyableBuffer(llarp_buffer_t(as_array()));
}
bool

View File

@ -2,7 +2,7 @@
#define LLARP_BENCODE_H
#include <constants/proto.hpp>
#include <util/buffer.h>
#include <util/buffer.hpp>
#include <util/common.hpp>
#include <functional>

View File

@ -6,8 +6,9 @@
#include <util/logger.hpp>
#include <util/mem.hpp>
#include <set>
#include <fstream>
#include <set>
#include <vector>
namespace llarp
{
@ -274,10 +275,12 @@ namespace llarp
void
Dump() const
{
byte_t tmp[bufsz] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, bufsz > tmp;
llarp_buffer_t buf(tmp);
if(BEncode(&buf))
{
llarp::DumpBuffer< decltype(buf), align >(buf);
}
}
};
@ -286,24 +289,26 @@ namespace llarp
bool
BDecodeReadFile(const char* fpath, T& t)
{
byte_t* ptr = nullptr;
size_t sz = 0;
std::vector< byte_t > ptr;
{
std::ifstream f;
f.open(fpath);
if(!f.is_open())
{
return false;
}
f.seekg(0, std::ios::end);
sz = f.tellg();
const std::streampos sz = f.tellg();
f.seekg(0, std::ios::beg);
ptr = new byte_t[sz];
f.read((char*)ptr, sz);
ptr.resize(sz);
f.read((char*)ptr.data(), sz);
}
llarp_buffer_t buf = InitBuffer(ptr, sz);
auto result = t.BDecode(&buf);
llarp_buffer_t buf(ptr);
auto result = t.BDecode(&buf);
if(!result)
{
DumpBuffer(buf);
delete[] ptr;
}
return result;
}
@ -312,8 +317,8 @@ namespace llarp
bool
BEncodeWriteFile(const char* fpath, const T& t)
{
uint8_t tmp[bufsz] = {0};
auto buf = StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, bufsz > tmp;
llarp_buffer_t buf(tmp);
if(!t.BEncode(&buf))
return false;
buf.sz = buf.cur - buf.base;

View File

@ -1,4 +1,4 @@
#include <util/buffer.h>
#include <util/buffer.hpp>
#include <util/endian.hpp>
#include <stdarg.h>
@ -70,12 +70,13 @@ llarp_buffer_read_until(llarp_buffer_t* buff, char delim, byte_t* result,
bool
llarp_buffer_eq(const llarp_buffer_t& buf, const char* str)
{
llarp_buffer_t copy = buf.clone();
while(*str && copy.cur != (copy.base + copy.sz))
CopyableBuffer copy{buf};
while(*str
&& copy.underlying.cur != (copy.underlying.base + copy.underlying.sz))
{
if(*copy.cur != *str)
if(*copy.underlying.cur != *str)
return false;
copy.cur++;
copy.underlying.cur++;
str++;
}
return *str == 0;

View File

@ -1,144 +0,0 @@
#ifndef LLARP_BUFFER_H_
#define LLARP_BUFFER_H_
#include <util/common.hpp>
#include <util/mem.h>
#include <util/types.hpp>
#include <cassert>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/**
* buffer.h
*
* generic memory buffer
*/
/**
llarp_buffer_t represents a region of memory that is ONLY
valid in the current scope.
make sure to follow the rules:
ALWAYS copy the contents of the buffer if that data is to be used outside the
current scope.
ALWAYS pass a llarp_buffer_t * if you plan on modifying the data associated
with the buffer
ALWAYS pass a llarp_buffer_t * if you plan on advancing the stream position
ALWAYS pass a llarp_buffer_t if you are doing a read only operation that does
not modify the buffer
ALWAYS pass a llarp_buffer_t if you don't want to advance the stream position
ALWAYS bail out of the current operation if you run out of space in a buffer
ALWAYS assume the pointers in the buffer are stack allocated memory
(yes even if you know they are not)
NEVER malloc() the pointers in the buffer when using it
NEVER realloc() the pointers in the buffer when using it
NEVER free() the pointers in the buffer when using it
NEVER use llarp_buffer_t ** (double pointers)
NEVER use llarp_buffer_t ** (double pointers)
ABSOLUTELY NEVER USE DOUBLE POINTERS.
*/
struct llarp_buffer_t
{
/// starting memory address
byte_t *base;
/// memory address of stream position
byte_t *cur;
/// max size of buffer
size_t sz;
byte_t operator[](size_t x)
{
return *(this->base + x);
}
llarp_buffer_t() : base(nullptr), cur(nullptr), sz(0)
{
}
llarp_buffer_t(const llarp_buffer_t &) = delete;
llarp_buffer_t(llarp_buffer_t &&) = default;
llarp_buffer_t(byte_t *b, byte_t *c, size_t s) : base(b), cur(c), sz(s)
{
assert(b != nullptr);
assert(c != nullptr);
assert(s != 0);
}
llarp_buffer_t
clone() const
{
return llarp_buffer_t(base, cur, sz);
}
};
struct CopyableBuffer
{
llarp_buffer_t underlying;
explicit CopyableBuffer(const llarp_buffer_t &b)
: underlying(b.base, b.cur, b.sz)
{
}
CopyableBuffer(CopyableBuffer &&) = default;
explicit CopyableBuffer(const CopyableBuffer &c)
: underlying(c.underlying.base, c.underlying.cur, c.underlying.sz)
{
}
};
/// how much room is left in buffer
size_t
llarp_buffer_size_left(const llarp_buffer_t &buff);
/// write a chunk of data size "sz"
bool
llarp_buffer_write(llarp_buffer_t *buff, const void *data, size_t sz);
/// write multiple strings
bool
llarp_buffer_writef(llarp_buffer_t *buff, const char *fmt, ...);
/// read buffer upto character delimiter
size_t
llarp_buffer_read_until(llarp_buffer_t *buff, char delim, byte_t *result,
size_t resultlen);
/// compare buffers, true if equal else false
bool
llarp_buffer_eq(const llarp_buffer_t &buff, const char *data);
/// put big endian unsigned 16 bit integer
bool
llarp_buffer_put_uint16(llarp_buffer_t *buf, uint16_t i);
/// put big endian unsigned 32 bit integer
bool
llarp_buffer_put_uint32(llarp_buffer_t *buf, uint32_t i);
/// read big endian unsigned 16 bit integer
bool
llarp_buffer_read_uint16(llarp_buffer_t *buf, uint16_t *i);
/// read big endian unsigned 32 bit integer
bool
llarp_buffer_read_uint32(llarp_buffer_t *buf, uint32_t *i);
#endif

View File

@ -1,57 +1,168 @@
#ifndef LLARP_BUFFER_HPP
#define LLARP_BUFFER_HPP
#include <util/buffer.h>
#include <util/common.hpp>
#include <util/mem.h>
#include <util/types.hpp>
namespace llarp
#include <cassert>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <utility>
/**
* buffer.h
*
* generic memory buffer
*/
/**
llarp_buffer_t represents a region of memory that is ONLY
valid in the current scope.
make sure to follow the rules:
ALWAYS copy the contents of the buffer if that data is to be used outside the
current scope.
ALWAYS pass a llarp_buffer_t * if you plan on modifying the data associated
with the buffer
ALWAYS pass a llarp_buffer_t * if you plan on advancing the stream position
ALWAYS pass a llarp_buffer_t if you are doing a read only operation that does
not modify the buffer
ALWAYS pass a llarp_buffer_t if you don't want to advance the stream position
ALWAYS bail out of the current operation if you run out of space in a buffer
ALWAYS assume the pointers in the buffer are stack allocated memory
(yes even if you know they are not)
NEVER malloc() the pointers in the buffer when using it
NEVER realloc() the pointers in the buffer when using it
NEVER free() the pointers in the buffer when using it
NEVER use llarp_buffer_t ** (double pointers)
NEVER use llarp_buffer_t ** (double pointers)
ABSOLUTELY NEVER USE DOUBLE POINTERS.
*/
struct CopyableBuffer;
struct llarp_buffer_t
{
template < typename T >
llarp_buffer_t
StackBuffer(T& stack)
/// starting memory address
byte_t *base;
/// memory address of stream position
byte_t *cur;
/// max size of buffer
size_t sz;
byte_t operator[](size_t x)
{
llarp_buffer_t buff;
buff.base = &stack[0];
buff.cur = buff.base;
buff.sz = sizeof(stack);
return buff;
return *(this->base + x);
}
/** initialize llarp_buffer_t from raw memory */
template < typename T >
llarp_buffer_t
InitBuffer(T buf, size_t sz)
llarp_buffer_t() : base(nullptr), cur(nullptr), sz(0)
{
}
llarp_buffer_t(byte_t *b, byte_t *c, size_t s) : base(b), cur(c), sz(s)
{
}
llarp_buffer_t(const CopyableBuffer &) = delete;
llarp_buffer_t(CopyableBuffer &&) = delete;
template < typename T >
llarp_buffer_t(T *buf, size_t _sz)
: base(reinterpret_cast< byte_t * >(buf)), cur(base), sz(_sz)
{
}
template < typename T >
llarp_buffer_t(const T *buf, size_t _sz)
: base(reinterpret_cast< byte_t * >(const_cast< T * >(buf)))
, cur(base)
, sz(_sz)
{
byte_t* ptr = (byte_t*)buf;
llarp_buffer_t ret;
ret.cur = ptr;
ret.base = ptr;
ret.sz = sz;
return ret;
}
/** initialize llarp_buffer_t from container */
template < typename T >
llarp_buffer_t
Buffer(T& t)
llarp_buffer_t(T &t) : base(t.data()), cur(t.data()), sz(t.size())
{
// use data over the first element to "enforce" the container used has
// contiguous memory. (Note this isn't required by the standard, but a
// reasonable test on most standard library implementations).
llarp_buffer_t buff(t.data(), t.data(), t.size());
return buff;
}
template < typename T >
llarp_buffer_t
ConstBuffer(const T& t)
llarp_buffer_t(const T &t) : base(t.data()), cur(t.data()), sz(t.size())
{
llarp_buffer_t buff;
buff.base = (byte_t*)&t[0];
buff.cur = buff.base;
buff.sz = t.size();
return buff;
}
} // namespace llarp
private:
friend struct CopyableBuffer;
llarp_buffer_t(const llarp_buffer_t &) = default;
llarp_buffer_t(llarp_buffer_t &&) = default;
};
struct CopyableBuffer
{
llarp_buffer_t underlying;
explicit CopyableBuffer(const llarp_buffer_t &b) : underlying(b)
{
}
CopyableBuffer(CopyableBuffer &&) = default;
CopyableBuffer(const CopyableBuffer &) = default;
};
/// how much room is left in buffer
size_t
llarp_buffer_size_left(const llarp_buffer_t &buff);
/// write a chunk of data size "sz"
bool
llarp_buffer_write(llarp_buffer_t *buff, const void *data, size_t sz);
/// write multiple strings
bool
llarp_buffer_writef(llarp_buffer_t *buff, const char *fmt, ...);
/// read buffer upto character delimiter
size_t
llarp_buffer_read_until(llarp_buffer_t *buff, char delim, byte_t *result,
size_t resultlen);
/// compare buffers, true if equal else false
bool
llarp_buffer_eq(const llarp_buffer_t &buff, const char *data);
/// put big endian unsigned 16 bit integer
bool
llarp_buffer_put_uint16(llarp_buffer_t *buf, uint16_t i);
/// put big endian unsigned 32 bit integer
bool
llarp_buffer_put_uint32(llarp_buffer_t *buf, uint32_t i);
/// read big endian unsigned 16 bit integer
bool
llarp_buffer_read_uint16(llarp_buffer_t *buf, uint16_t *i);
/// read big endian unsigned 32 bit integer
bool
llarp_buffer_read_uint32(llarp_buffer_t *buf, uint32_t *i);
#endif

View File

@ -1,7 +1,7 @@
#ifndef LLARP_MEM_HPP
#define LLARP_MEM_HPP
#include <util/buffer.h>
#include <util/buffer.hpp>
#include <util/mem.h>
#include <cctype>

View File

@ -35,11 +35,13 @@ namespace llarp
AlignedBuffer< 128 > random;
random.Randomize();
Signature sig;
ASSERT_TRUE(crypto.sign(sig, secret, random.as_buffer()));
ASSERT_TRUE(crypto.verify(secret.toPublic(), random.as_buffer(), sig));
const llarp_buffer_t& buf = random.as_buffer().underlying;
ASSERT_TRUE(crypto.sign(sig, secret, buf));
ASSERT_TRUE(crypto.verify(secret.toPublic(), buf, sig));
// mangle sig
sig.Randomize();
ASSERT_FALSE(crypto.verify(secret.toPublic(), random.as_buffer(), sig));
ASSERT_FALSE(crypto.verify(secret.toPublic(), buf, sig));
}
struct PQCryptoTest : public ::testing::Test

View File

@ -11,15 +11,13 @@
struct DNSLibTest : public ::testing::Test
{
byte_t mem[1500];
llarp_buffer_t buf = llarp::StackBuffer< decltype(mem) >(mem);
std::array< byte_t, 1500 > mem;
llarp_buffer_t buf;
void
SetUp()
DNSLibTest() : buf(mem)
{
buf.sz = sizeof(mem);
Rewind();
memset(mem, '$', sizeof(mem));
std::fill(mem.begin(), mem.end(), '$');
}
void

View File

@ -180,8 +180,8 @@ TEST_F(LinkLayerTest, TestUTPAliceRenegWithBob)
else
{
llarp::LinkIntroMessage msg;
llarp_buffer_t copy(buf.clone());
if(!msg.BDecode(&copy))
CopyableBuffer copy{buf};
if(!msg.BDecode(&copy.underlying))
return false;
if(!s->GotLIM(&msg))
return false;
@ -205,8 +205,8 @@ TEST_F(LinkLayerTest, TestUTPAliceRenegWithBob)
auto sendDiscardMessage = [](llarp::ILinkSession* s) -> bool {
// send discard message in reply to complete unit test
byte_t tmp[32] = {0};
auto otherBuf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, 32 > tmp;
llarp_buffer_t otherBuf(tmp);
llarp::DiscardMessage discard;
if(!discard.BEncode(&otherBuf))
return false;
@ -220,8 +220,8 @@ TEST_F(LinkLayerTest, TestUTPAliceRenegWithBob)
[&]() -> const llarp::RouterContact& { return Bob.GetRC(); },
[&](llarp::ILinkSession* s, const llarp_buffer_t& buf) -> bool {
llarp::LinkIntroMessage msg;
llarp_buffer_t copy(buf.clone());
if(!msg.BDecode(&copy))
CopyableBuffer copy{buf};
if(!msg.BDecode(&copy.underlying))
return false;
if(!s->GotLIM(&msg))
return false;
@ -270,8 +270,8 @@ TEST_F(LinkLayerTest, TestUTPAliceConnectToBob)
else
{
llarp::LinkIntroMessage msg;
llarp_buffer_t copy(buf.clone());
if(!msg.BDecode(&copy))
CopyableBuffer copy{buf};
if(!msg.BDecode(&copy.underlying))
return false;
if(!s->GotLIM(&msg))
return false;
@ -295,8 +295,8 @@ TEST_F(LinkLayerTest, TestUTPAliceConnectToBob)
auto sendDiscardMessage = [](llarp::ILinkSession* s) -> bool {
// send discard message in reply to complete unit test
byte_t tmp[32] = {0};
auto otherBuf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, 32 > tmp;
llarp_buffer_t otherBuf(tmp);
llarp::DiscardMessage discard;
if(!discard.BEncode(&otherBuf))
return false;
@ -310,8 +310,8 @@ TEST_F(LinkLayerTest, TestUTPAliceConnectToBob)
[&]() -> const llarp::RouterContact& { return Bob.GetRC(); },
[&](llarp::ILinkSession* s, const llarp_buffer_t& buf) -> bool {
llarp::LinkIntroMessage msg;
llarp_buffer_t copy(buf.clone());
if(!msg.BDecode(&copy))
CopyableBuffer copy{buf};
if(!msg.BDecode(&copy.underlying))
return false;
if(!s->GotLIM(&msg))
return false;

View File

@ -10,15 +10,15 @@ class TransferTrafficTest : public ::testing::Test
TEST_F(TransferTrafficTest, TestPutBufferOverflow)
{
TransferTrafficMessage msg;
byte_t tmp[llarp::routing::MaxExitMTU * 2] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, llarp::routing::MaxExitMTU* 2 > tmp = {0};
llarp_buffer_t buf(tmp);
ASSERT_FALSE(msg.PutBuffer(buf, 1));
};
TEST_F(TransferTrafficTest, TestPutBuffer)
{
TransferTrafficMessage msg;
byte_t tmp[llarp::routing::MaxExitMTU] = {0};
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
std::array< byte_t, llarp::routing::MaxExitMTU > tmp = {0};
llarp_buffer_t buf(tmp);
ASSERT_TRUE(msg.PutBuffer(buf, 1));
};

View File

@ -193,12 +193,11 @@ TEST_F(DNSTest, handleDNSrecvFrom)
{
llarp_udp_io_mock udp;
sockaddr addr;
char buffer[16];
llarp::Zero(&buffer, 15);
ssize_t sz = 0;
std::array< byte_t, 16 > buffer;
std::fill(buffer.begin(), buffer.end(), 0);
// hdr->qr decides dnsc (1) or dnsd (0)
llarp_handle_dns_recvfrom((llarp_udp_io *)&udp, &addr,
llarp::InitBuffer(buffer, sz));
CopyableBuffer(llarp_buffer_t(buffer)));
// llarp_handle_dnsc_recvfrom
// llarp_handle_dnsd_recvfrom
}

View File

@ -12,17 +12,17 @@ std::string g_result = "";
ssize_t
test_sendto_dns_hook(__attribute__((unused)) void *sock,
__attribute__((unused)) const struct sockaddr *from,
llarp_buffer_t buf)
CopyableBuffer buf)
{
char *hex_buffer = new char[buf.sz * 3 + 1];
hex_buffer[buf.sz * 3] = 0;
for(unsigned int j = 0; j < buf.sz; j++)
sprintf(&hex_buffer[3 * j], "%02X ", ((char *)buf.base)[j]);
char *hex_buffer = new char[buf.underlying.sz * 3 + 1];
hex_buffer[buf.underlying.sz * 3] = 0;
for(unsigned int j = 0; j < buf.underlying.sz; j++)
sprintf(&hex_buffer[3 * j], "%02X ", ((char *)buf.underlying.base)[j]);
// printf("Got [%zu] bytes: [%s]\n", length, hex_buffer);
g_result = hex_buffer;
g_length = buf.sz;
g_length = buf.underlying.sz;
delete[] hex_buffer;
return buf.sz;
return buf.underlying.sz;
}
struct llarpDNSdTest : public ::testing::Test

View File

@ -45,7 +45,7 @@ TEST_P(ReadInt, readInt)
{
auto d = GetParam();
llarp_buffer_t buffer(llarp::Buffer(d.buffer));
llarp_buffer_t buffer(d.buffer);
uint64_t result = 0;
bool rc = bencode_read_integer(&buffer, &result);
@ -90,7 +90,7 @@ TEST_P(ReadStr, readStr)
{
auto d = GetParam();
llarp_buffer_t buffer = llarp::Buffer(d.buffer);
llarp_buffer_t buffer(d.buffer);
llarp_buffer_t result;
bool rc = bencode_read_string(&buffer, &result);
@ -140,7 +140,7 @@ TEST_P(WriteByteStr, writeByte)
auto d = GetParam();
std::vector< byte_t > backingBuffer(d.bufferSize, 0);
llarp_buffer_t buffer = llarp::Buffer(backingBuffer);
llarp_buffer_t buffer(backingBuffer);
bool rc = bencode_write_bytestring(&buffer, d.input.data(), d.input.size());
@ -175,7 +175,7 @@ TEST_P(WriteInt, writeInt)
auto d = GetParam();
std::vector< byte_t > backingBuffer(d.bufferSize, 0);
llarp_buffer_t buffer = llarp::Buffer(backingBuffer);
llarp_buffer_t buffer(backingBuffer);
bool rc = bencode_write_uint64(&buffer, d.input);
@ -207,16 +207,16 @@ TEST_P(WriteIntValues, anyvalue)
std::vector< byte_t > backingBuffer(100, 0);
{
llarp_buffer_t buffer = llarp::Buffer(backingBuffer);
llarp_buffer_t buffer(backingBuffer);
bool rc = bencode_write_uint64(&buffer, val);
ASSERT_TRUE(rc);
}
{
uint64_t result = 0;
llarp_buffer_t buffer = llarp::Buffer(backingBuffer);
bool rc = bencode_read_integer(&buffer, &result);
uint64_t result = 0;
llarp_buffer_t buffer(backingBuffer);
bool rc = bencode_read_integer(&buffer, &result);
ASSERT_TRUE(rc);
ASSERT_EQ(result, val);
}
@ -232,7 +232,7 @@ INSTANTIATE_TEST_CASE_P(
TEST(TestBencode, good_version)
{
std::vector< byte_t > backingBuffer(100, 0);
llarp_buffer_t buffer = llarp::Buffer(backingBuffer);
llarp_buffer_t buffer(backingBuffer);
ASSERT_TRUE(bencode_write_version_entry(&buffer));
@ -242,7 +242,7 @@ TEST(TestBencode, good_version)
TEST(TestBencode, bad_version)
{
std::vector< byte_t > otherBuffer(1, 0);
llarp_buffer_t buffer = llarp::Buffer(otherBuffer);
llarp_buffer_t buffer(otherBuffer);
ASSERT_FALSE(bencode_write_version_entry(&buffer));
}
@ -271,7 +271,7 @@ TEST_P(ListTest, list)
auto d = GetParam();
std::vector< byte_t > backingBuffer(d.bufferSize, 0);
llarp_buffer_t buffer = llarp::Buffer(backingBuffer);
llarp_buffer_t buffer(backingBuffer);
ASSERT_TRUE(bencode_start_list(&buffer));
@ -323,7 +323,7 @@ TEST_P(DictTest, dict)
auto d = GetParam();
std::vector< byte_t > backingBuffer(d.bufferSize, 0);
llarp_buffer_t buffer = llarp::Buffer(backingBuffer);
llarp_buffer_t buffer(backingBuffer);
ASSERT_TRUE(bencode_start_dict(&buffer));