lokinet/llarp/link/utp.cpp

1033 lines
28 KiB
C++
Raw Normal View History

2018-12-12 00:33:54 +00:00
#include <buffer.hpp>
#include <endian.hpp>
2018-12-12 01:32:10 +00:00
#include <link/server.hpp>
#include <link/utp.hpp>
#include <messages/discard.hpp>
#include <messages/link_intro.hpp>
2018-12-12 00:33:54 +00:00
#include <router.hpp>
#include <utp.h>
2018-12-12 00:33:54 +00:00
2018-09-06 11:46:19 +00:00
#include <cassert>
2018-09-07 17:41:49 +00:00
#include <tuple>
2018-09-07 20:36:06 +00:00
#include <deque>
2018-09-06 20:31:58 +00:00
#ifdef __linux__
#include <linux/errqueue.h>
#include <netinet/ip_icmp.h>
#endif
2018-09-25 08:31:29 +00:00
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#include <wspiapi.h>
2018-09-25 08:31:29 +00:00
#endif
#ifndef IP_DONTFRAGMENT
#define IP_DONTFRAGMENT IP_DONTFRAG
2018-09-25 08:31:29 +00:00
#endif
namespace llarp
{
namespace utp
{
2018-09-06 20:31:58 +00:00
constexpr size_t FragmentHashSize = 32;
2018-09-07 17:41:49 +00:00
constexpr size_t FragmentNonceSize = 24;
constexpr size_t FragmentOverheadSize =
FragmentHashSize + FragmentNonceSize;
2018-09-07 20:36:06 +00:00
constexpr size_t FragmentBodyPayloadSize = 1024;
2018-09-07 17:41:49 +00:00
constexpr size_t FragmentBodyOverhead = sizeof(uint32_t) * 2;
constexpr size_t FragmentBodySize =
FragmentBodyOverhead + FragmentBodyPayloadSize;
2018-09-06 20:31:58 +00:00
constexpr size_t FragmentBufferSize =
2018-09-07 17:41:49 +00:00
FragmentOverheadSize + FragmentBodySize;
2018-09-06 11:46:19 +00:00
typedef llarp::AlignedBuffer< FragmentBufferSize > FragmentBuffer;
/// maximum size for send queue for a session before we drop
constexpr size_t MaxSendQueueSize = 1024;
2018-09-06 20:31:58 +00:00
typedef llarp::AlignedBuffer< MAX_LINK_MSG_SIZE > MessageBuffer;
struct LinkLayer;
struct BaseSession : public ILinkSession
{
RouterContact remoteRC;
2018-09-06 11:46:19 +00:00
utp_socket* sock;
LinkLayer* parent;
bool gotLIM;
PubKey remoteTransportPubKey;
Addr remoteAddr;
SharedSecret sessionKey;
llarp_time_t lastActive;
2018-09-07 17:41:49 +00:00
const static llarp_time_t sessionTimeout = 30 * 1000;
2018-09-12 13:29:42 +00:00
std::deque< utp_iovec > vecq;
2018-09-07 20:36:06 +00:00
std::deque< FragmentBuffer > sendq;
2018-09-07 17:41:49 +00:00
FragmentBuffer recvBuf;
2018-09-06 11:46:19 +00:00
size_t recvBufOffset;
2018-09-06 20:31:58 +00:00
MessageBuffer recvMsg;
size_t recvMsgOffset;
bool stalled = false;
2018-09-06 11:46:19 +00:00
2018-09-06 13:16:24 +00:00
void
2018-09-06 20:31:58 +00:00
Alive();
2018-09-06 13:16:24 +00:00
2018-09-06 11:46:19 +00:00
/// base
BaseSession(LinkLayer* p);
2018-09-06 11:46:19 +00:00
/// outbound
BaseSession(LinkLayer* p, utp_socket* s, const RouterContact& rc,
2018-09-06 11:46:19 +00:00
const AddressInfo& addr);
/// inbound
BaseSession(LinkLayer* p, utp_socket* s, const Addr& remote);
2018-09-04 19:15:06 +00:00
enum State
{
eInitial,
eConnecting,
eLinkEstablished, // when utp connection is established
eCryptoHandshake, // crypto handshake initiated
eSessionReady, // session is ready
eClose // utp connection is closed
};
llarp::Router*
2018-09-06 11:46:19 +00:00
Router();
State state;
void
2018-09-06 11:46:19 +00:00
OnLinkEstablished(LinkLayer* p)
{
2018-09-06 11:46:19 +00:00
parent = p;
EnterState(eLinkEstablished);
llarp::LogDebug("link established with ", remoteAddr);
}
2018-09-06 11:46:19 +00:00
void
EnterState(State st);
2018-09-04 19:15:06 +00:00
BaseSession();
2018-09-10 13:43:36 +00:00
~BaseSession();
void
2018-09-06 13:16:24 +00:00
PumpWrite()
{
2018-09-12 13:29:42 +00:00
if(!sock)
return;
ssize_t expect = 0;
std::vector< utp_iovec > vecs;
for(const auto& vec : vecq)
{
expect += vec.iov_len;
vecs.push_back(vec);
}
if(expect)
{
ssize_t s = utp_writev(sock, vecs.data(), vecs.size());
llarp::LogDebug("utp_writev wrote=", s, " expect=", expect,
" to=", remoteAddr);
while(s > static_cast< ssize_t >(vecq.front().iov_len))
2018-09-12 13:29:42 +00:00
{
s -= vecq.front().iov_len;
vecq.pop_front();
sendq.pop_front();
}
if(vecq.size())
{
auto& front = vecq.front();
front.iov_len -= s;
front.iov_base = ((byte_t*)front.iov_base) + s;
}
}
/*
2018-09-07 17:41:49 +00:00
while(sendq.size() > 0 && !stalled)
{
2018-09-07 17:41:49 +00:00
ssize_t expect = FragmentBufferSize - sendBufOffset;
2018-09-12 13:29:42 +00:00
ssize_t s = write_ll(sendq.front().data() + sendBufOffset,
expect); if(s != expect)
2018-09-06 20:31:58 +00:00
{
2018-09-07 17:41:49 +00:00
llarp::LogDebug("stalled at offset=", sendBufOffset, " sz=", s,
" to ", remoteAddr);
sendBufOffset += s;
2018-09-06 20:31:58 +00:00
stalled = true;
}
2018-09-07 17:41:49 +00:00
else
{
sendBufOffset = 0;
2018-09-07 20:36:06 +00:00
sendq.pop_front();
2018-09-07 17:41:49 +00:00
}
}
2018-09-12 13:29:42 +00:00
*/
}
2018-09-06 20:31:58 +00:00
ssize_t
2018-09-07 17:41:49 +00:00
write_ll(byte_t* buf, size_t sz)
{
2018-09-06 13:16:24 +00:00
if(sock == nullptr)
{
llarp::LogWarn("write_ll failed: no socket");
2018-09-06 20:31:58 +00:00
return 0;
}
2018-09-07 17:41:49 +00:00
ssize_t s = utp_write(sock, buf, sz);
llarp::LogDebug("write_ll ", s, " of ", sz, " bytes to ", remoteAddr);
return s;
}
bool
2018-09-07 17:41:49 +00:00
VerifyThenDecrypt(byte_t* buf);
void
2018-09-07 20:36:06 +00:00
EncryptThenHash(const byte_t* ptr, uint32_t sz, bool isLastFragment);
bool
2018-10-29 16:48:36 +00:00
QueueWriteBuffers(llarp_buffer_t buf);
2018-09-06 11:46:19 +00:00
void
Connect()
{
utp_connect(sock, remoteAddr, remoteAddr.SockLen());
EnterState(eConnecting);
}
void
OutboundLinkEstablished(LinkLayer* p)
{
OnLinkEstablished(p);
OutboundHandshake();
2018-09-06 11:46:19 +00:00
}
// send first message
2018-09-06 11:46:19 +00:00
void
OutboundHandshake();
2018-09-06 11:46:19 +00:00
// mix keys
2018-09-04 19:15:06 +00:00
bool
DoKeyExchange(transport_dh_func dh, const KeyExchangeNonce& n,
const PubKey& other, const byte_t* secret)
{
ShortHash t_h;
AlignedBuffer< 64 > tmp;
memcpy(tmp.data(), sessionKey, sessionKey.size());
memcpy(tmp.data() + sessionKey.size(), n, n.size());
// t_h = HS(K + L.n)
if(!Router()->crypto.shorthash(t_h, ConstBuffer(tmp)))
{
llarp::LogError("failed to mix key to ", remoteAddr);
return false;
}
// K = TKE(a.p, B_a.e, sk, t_h)
if(!dh(sessionKey, other, secret, t_h))
{
llarp::LogError("key exchange with ", other, " failed");
2018-09-04 19:15:06 +00:00
return false;
}
llarp::LogDebug("keys mixed with session to ", remoteAddr);
2018-09-04 19:15:06 +00:00
return true;
}
void
TickImpl(__attribute__((unused)) llarp_time_t now)
{
}
void
2018-09-07 17:41:49 +00:00
Close();
bool
Recv(const void* buf, size_t sz)
{
2018-09-07 17:41:49 +00:00
Alive();
byte_t* ptr = (byte_t*)buf;
llarp::LogDebug("utp read ", sz, " from ", remoteAddr);
2018-09-06 20:31:58 +00:00
size_t s = sz;
2018-09-07 17:41:49 +00:00
// process leftovers
if(recvBufOffset)
{
2018-09-07 20:36:06 +00:00
auto left = FragmentBufferSize - recvBufOffset;
2018-09-07 17:41:49 +00:00
if(s >= left)
2018-09-06 20:31:58 +00:00
{
2018-09-07 20:36:06 +00:00
// yes it fills it
2018-09-07 17:41:49 +00:00
llarp::LogDebug("process leftovers, offset=", recvBufOffset,
" sz=", s, " left=", left);
memcpy(recvBuf.data() + recvBufOffset, ptr, left);
s -= left;
recvBufOffset = 0;
ptr += left;
2018-09-07 20:36:06 +00:00
if(!VerifyThenDecrypt(recvBuf.data()))
2018-09-06 20:31:58 +00:00
return false;
}
}
2018-09-07 20:36:06 +00:00
// process full fragments
2018-09-07 17:41:49 +00:00
while(s >= FragmentBufferSize)
{
2018-09-07 20:36:06 +00:00
recvBufOffset = 0;
2018-09-07 17:41:49 +00:00
llarp::LogDebug("process full sz=", s);
if(!VerifyThenDecrypt(ptr))
return false;
ptr += FragmentBufferSize;
s -= FragmentBufferSize;
}
if(s)
{
// hold onto leftovers
llarp::LogDebug("leftovers sz=", s);
2018-09-07 20:36:06 +00:00
memcpy(recvBuf.data() + recvBufOffset, ptr, s);
recvBufOffset += s;
2018-09-07 17:41:49 +00:00
}
return true;
}
bool
InboundLIM(const LinkIntroMessage* msg);
bool
OutboundLIM(const LinkIntroMessage* msg);
bool
2018-09-06 11:46:19 +00:00
IsTimedOut(llarp_time_t now) const
{
2018-09-18 18:05:41 +00:00
if(state == eClose)
return true;
if(now < lastActive)
return false;
2018-09-07 17:41:49 +00:00
auto dlt = now - lastActive;
if(dlt >= sessionTimeout)
{
llarp::LogDebug("session timeout reached for ", remoteAddr);
return true;
}
return false;
}
const PubKey&
2018-09-06 13:16:24 +00:00
RemotePubKey() const
{
return remoteRC.pubkey;
}
const Addr&
2018-09-07 17:41:49 +00:00
RemoteEndpoint() const
{
return remoteAddr;
}
void
MarkEstablished();
2018-09-04 19:15:06 +00:00
}; // namespace utp
struct LinkLayer : public ILinkLayer
{
utp_context* _utp_ctx = nullptr;
llarp::Router* router = nullptr;
static uint64
2018-09-06 11:46:19 +00:00
OnRead(utp_callback_arguments* arg);
static uint64
SendTo(utp_callback_arguments* arg)
{
LinkLayer* l =
static_cast< LinkLayer* >(utp_context_get_userdata(arg->context));
llarp::LogDebug("utp_sendto ", Addr(*arg->address), " ", arg->len,
2018-09-06 20:31:58 +00:00
" bytes");
// For whatever reason, the UTP_UDP_DONTFRAG flag is set
// on the socket itself....which isn't correct and causes
// winsock (at minimum) to reeee
// here, we check its value, then set fragmentation the _right_
// way. Naturally, Linux has its own special procedure.
// Of course, the flag itself is cleared. -rick
#ifndef _WIN32
2018-11-22 17:46:52 +00:00
// No practical method of doing this on NetBSD or Darwin
// without resorting to raw sockets
#if !(__NetBSD__ || __OpenBSD__ || (__APPLE__ && __MACH__))
#ifndef __linux__
if(arg->flags == 2)
{
int val = 1;
setsockopt(l->m_udp.fd, IPPROTO_IP, IP_DONTFRAGMENT, &val,
sizeof(val));
}
else
{
int val = 0;
setsockopt(l->m_udp.fd, IPPROTO_IP, IP_DONTFRAGMENT, &val,
sizeof(val));
}
#else
if(arg->flags == 2)
{
int val = IP_PMTUDISC_DO;
setsockopt(l->m_udp.fd, IPPROTO_IP, IP_MTU_DISCOVER, &val,
sizeof(val));
}
else
{
int val = IP_PMTUDISC_DONT;
setsockopt(l->m_udp.fd, IPPROTO_IP, IP_MTU_DISCOVER, &val,
sizeof(val));
}
2018-11-22 17:46:52 +00:00
#endif
#endif
arg->flags = 0;
if(::sendto(l->m_udp.fd, (char*)arg->buf, arg->len, arg->flags,
arg->address, arg->address_len)
2018-10-05 07:57:48 +00:00
== -1
&& errno)
#else
if(arg->flags == 2)
2018-09-06 20:31:58 +00:00
{
char val = 1;
setsockopt(l->m_udp.fd, IPPROTO_IP, IP_DONTFRAGMENT, &val,
sizeof(val));
}
else
{
char val = 0;
setsockopt(l->m_udp.fd, IPPROTO_IP, IP_DONTFRAGMENT, &val,
sizeof(val));
}
arg->flags = 0;
if(::sendto(l->m_udp.fd, (char*)arg->buf, arg->len, arg->flags,
arg->address, arg->address_len)
== -1)
#endif
2018-09-06 20:31:58 +00:00
{
2018-11-20 15:38:46 +00:00
#ifdef _WIN32
char buf[1024];
int err = WSAGetLastError();
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nullptr, err, LANG_NEUTRAL,
buf, 1024, nullptr);
llarp::LogError("sendto failed: ", buf);
2018-11-20 15:38:46 +00:00
#else
2018-09-06 20:31:58 +00:00
llarp::LogError("sendto failed: ", strerror(errno));
2018-11-20 15:38:46 +00:00
#endif
2018-09-06 20:31:58 +00:00
}
return 0;
}
static uint64
OnError(utp_callback_arguments* arg)
{
BaseSession* session =
static_cast< BaseSession* >(utp_get_userdata(arg->socket));
if(session)
{
2018-10-04 17:34:26 +00:00
session->Router()->OnConnectTimeout(session->GetPubKey());
llarp::LogError(utp_error_code_names[arg->error_code], " via ",
session->remoteAddr);
2018-09-18 18:05:41 +00:00
session->Close();
}
return 0;
}
static uint64
2018-09-06 11:46:19 +00:00
OnStateChange(utp_callback_arguments*);
static uint64
OnAccept(utp_callback_arguments*);
2018-09-06 20:31:58 +00:00
static uint64
OnLog(utp_callback_arguments* arg)
{
llarp::LogDebug(arg->buf);
return 0;
}
LinkLayer(llarp::Router* r) : ILinkLayer()
{
2018-12-03 18:28:16 +00:00
router = r;
_utp_ctx = utp_init(2);
utp_context_set_userdata(_utp_ctx, this);
utp_set_callback(_utp_ctx, UTP_SENDTO, &LinkLayer::SendTo);
utp_set_callback(_utp_ctx, UTP_ON_ACCEPT, &LinkLayer::OnAccept);
2018-09-06 11:46:19 +00:00
utp_set_callback(_utp_ctx, UTP_ON_STATE_CHANGE,
&LinkLayer::OnStateChange);
utp_set_callback(_utp_ctx, UTP_ON_READ, &LinkLayer::OnRead);
2018-09-06 20:31:58 +00:00
utp_set_callback(_utp_ctx, UTP_ON_ERROR, &LinkLayer::OnError);
utp_set_callback(_utp_ctx, UTP_LOG, &LinkLayer::OnLog);
2018-09-04 19:15:06 +00:00
utp_context_set_option(_utp_ctx, UTP_LOG_NORMAL, 1);
utp_context_set_option(_utp_ctx, UTP_LOG_MTU, 1);
utp_context_set_option(_utp_ctx, UTP_LOG_DEBUG, 1);
2018-09-07 17:41:49 +00:00
utp_context_set_option(_utp_ctx, UTP_SNDBUF, MAX_LINK_MSG_SIZE * 16);
2018-09-06 20:31:58 +00:00
utp_context_set_option(_utp_ctx, UTP_RCVBUF, MAX_LINK_MSG_SIZE * 64);
}
~LinkLayer()
{
utp_destroy(_utp_ctx);
}
uint16_t
Rank() const
{
return 1;
}
void
RecvFrom(const Addr& from, const void* buf, size_t sz)
{
utp_process_udp(_utp_ctx, (const byte_t*)buf, sz, from, from.SockLen());
}
2018-09-06 20:31:58 +00:00
#ifdef __linux__
void
ProcessICMP()
{
do
{
byte_t vec_buf[4096], ancillary_buf[4096];
struct iovec iov = {vec_buf, sizeof(vec_buf)};
struct sockaddr_in remote;
struct msghdr msg;
ssize_t len;
struct cmsghdr* cmsg;
struct sock_extended_err* e;
struct sockaddr* icmp_addr;
struct sockaddr_in* icmp_sin;
memset(&msg, 0, sizeof(msg));
2018-12-03 18:28:16 +00:00
msg.msg_name = &remote;
msg.msg_namelen = sizeof(remote);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_flags = 0;
msg.msg_control = ancillary_buf;
2018-09-06 20:31:58 +00:00
msg.msg_controllen = sizeof(ancillary_buf);
len = recvmsg(m_udp.fd, &msg, MSG_ERRQUEUE | MSG_DONTWAIT);
if(len < 0)
{
if(errno == EAGAIN || errno == EWOULDBLOCK)
errno = 0;
else
llarp::LogError("failed to read icmp for utp ", strerror(errno));
return;
}
for(cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg))
{
if(cmsg->cmsg_type != IP_RECVERR)
{
continue;
}
if(cmsg->cmsg_level != SOL_IP)
{
continue;
}
e = (struct sock_extended_err*)CMSG_DATA(cmsg);
if(!e)
continue;
if(e->ee_origin != SO_EE_ORIGIN_ICMP)
{
continue;
}
icmp_addr = (struct sockaddr*)SO_EE_OFFENDER(e);
2018-12-03 18:28:16 +00:00
icmp_sin = (struct sockaddr_in*)icmp_addr;
2018-09-06 20:31:58 +00:00
if(icmp_sin->sin_port != 0)
{
continue;
}
if(e->ee_type == 3 && e->ee_code == 4)
{
utp_process_icmp_fragmentation(_utp_ctx, vec_buf, len,
(struct sockaddr*)&remote,
sizeof(remote), e->ee_info);
}
else
{
utp_process_icmp_error(_utp_ctx, vec_buf, len,
(struct sockaddr*)&remote, sizeof(remote));
}
}
} while(true);
}
#endif
void
Pump()
{
2018-09-07 17:41:49 +00:00
utp_issue_deferred_acks(_utp_ctx);
2018-09-06 20:31:58 +00:00
#ifdef __linux__
ProcessICMP();
#endif
std::set< RouterID > sessions;
2018-09-10 13:43:36 +00:00
{
Lock l(m_AuthedLinksMutex);
auto itr = m_AuthedLinks.begin();
while(itr != m_AuthedLinks.end())
{
sessions.insert(itr->first);
++itr;
}
}
2018-09-07 17:41:49 +00:00
ILinkLayer::Pump();
2018-09-10 13:43:36 +00:00
{
Lock l(m_AuthedLinksMutex);
for(const auto& pk : sessions)
{
2018-10-04 17:41:23 +00:00
if(m_AuthedLinks.count(pk) == 0)
2018-09-10 13:43:36 +00:00
{
// all sessions were removed
router->SessionClosed(pk);
}
}
}
2018-09-06 20:31:58 +00:00
}
void
Stop()
{
}
llarp::Router*
2018-09-06 11:46:19 +00:00
GetRouter();
bool
KeyGen(SecretKey& k)
{
2018-09-06 11:46:19 +00:00
router->crypto.encryption_keygen(k);
return true;
}
2018-09-06 20:31:58 +00:00
void
Tick(llarp_time_t now)
{
utp_check_timeouts(_utp_ctx);
ILinkLayer::Tick(now);
}
2018-09-06 13:16:24 +00:00
ILinkSession*
NewOutboundSession(const RouterContact& rc, const AddressInfo& addr);
utp_socket*
NewSocket()
{
return utp_create_socket(_utp_ctx);
}
const char*
Name() const
{
return "utp";
}
};
std::unique_ptr< ILinkLayer >
NewServer(llarp::Router* r)
{
2018-09-04 19:15:06 +00:00
return std::unique_ptr< LinkLayer >(new LinkLayer(r));
}
BaseSession::BaseSession(LinkLayer* p)
{
parent = p;
2018-09-07 17:41:49 +00:00
remoteTransportPubKey.Zero();
2018-09-06 20:31:58 +00:00
recvMsgOffset = 0;
SendQueueBacklog = [&]() -> size_t { return sendq.size(); };
2018-09-06 20:31:58 +00:00
SendKeepAlive = [&]() -> bool {
2018-10-29 16:48:36 +00:00
auto now = parent->now();
if(sendq.size() == 0 && state == eSessionReady && now > lastActive
2018-11-19 22:04:23 +00:00
&& now - lastActive > 5000)
2018-09-06 20:31:58 +00:00
{
DiscardMessage msg;
byte_t tmp[128] = {0};
2018-12-03 18:28:16 +00:00
auto buf = llarp::StackBuffer< decltype(tmp) >(tmp);
2018-09-06 20:31:58 +00:00
if(!msg.BEncode(&buf))
return false;
2018-12-03 18:28:16 +00:00
buf.sz = buf.cur - buf.base;
2018-09-06 20:31:58 +00:00
buf.cur = buf.base;
if(!this->QueueWriteBuffers(buf))
return false;
}
return true;
};
2018-12-03 18:28:16 +00:00
gotLIM = false;
2018-09-06 11:46:19 +00:00
recvBufOffset = 0;
2018-12-03 18:28:16 +00:00
TimedOut = [&](llarp_time_t now) -> bool {
2018-09-07 17:41:49 +00:00
return this->IsTimedOut(now) || this->state == eClose;
2018-09-06 11:46:19 +00:00
};
2018-12-03 18:28:16 +00:00
GetPubKey = std::bind(&BaseSession::RemotePubKey, this);
2018-10-29 16:48:36 +00:00
lastActive = parent->now();
2018-09-12 13:29:42 +00:00
// Pump = []() {};
Pump = std::bind(&BaseSession::PumpWrite, this);
2018-09-06 11:46:19 +00:00
Tick = std::bind(&BaseSession::TickImpl, this, std::placeholders::_1);
2018-09-07 17:41:49 +00:00
SendMessageBuffer = std::bind(&BaseSession::QueueWriteBuffers, this,
std::placeholders::_1);
IsEstablished = [=]() {
return this->state == eSessionReady || this->state == eLinkEstablished;
2018-09-06 11:46:19 +00:00
};
2018-09-07 17:41:49 +00:00
2018-12-03 18:28:16 +00:00
SendClose = std::bind(&BaseSession::Close, this);
2018-09-07 17:41:49 +00:00
GetRemoteEndpoint = std::bind(&BaseSession::RemoteEndpoint, this);
2018-09-06 11:46:19 +00:00
}
BaseSession::BaseSession(LinkLayer* p, utp_socket* s,
2018-09-06 11:46:19 +00:00
const RouterContact& rc, const AddressInfo& addr)
: BaseSession(p)
{
2018-09-06 11:46:19 +00:00
remoteRC.Clear();
remoteTransportPubKey = addr.pubkey;
2018-12-03 18:28:16 +00:00
remoteRC = rc;
sock = s;
2018-09-06 11:46:19 +00:00
assert(utp_set_userdata(sock, this) == this);
2018-09-06 13:16:24 +00:00
assert(s == sock);
2018-09-06 11:46:19 +00:00
remoteAddr = addr;
2018-12-03 18:28:16 +00:00
Start = std::bind(&BaseSession::Connect, this);
GotLIM =
std::bind(&BaseSession::OutboundLIM, this, std::placeholders::_1);
2018-09-06 11:46:19 +00:00
}
BaseSession::BaseSession(LinkLayer* p, utp_socket* s, const Addr& addr)
: BaseSession(p)
2018-09-06 11:46:19 +00:00
{
p->router->crypto.shorthash(sessionKey,
InitBuffer(p->router->pubkey(), PUBKEYSIZE));
2018-09-06 11:46:19 +00:00
remoteRC.Clear();
sock = s;
2018-09-06 13:16:24 +00:00
assert(s == sock);
2018-09-06 11:46:19 +00:00
assert(utp_set_userdata(sock, this) == this);
remoteAddr = addr;
2018-12-03 18:28:16 +00:00
Start = []() {};
GotLIM = std::bind(&BaseSession::InboundLIM, this, std::placeholders::_1);
}
bool
BaseSession::InboundLIM(const LinkIntroMessage* msg)
{
if(gotLIM && remoteRC.pubkey != msg->rc.pubkey)
{
return false;
}
remoteRC = msg->rc;
2018-12-03 18:28:16 +00:00
gotLIM = true;
if(!DoKeyExchange(Router()->crypto.transport_dh_server, msg->N,
remoteRC.enckey, parent->TransportSecretKey()))
return false;
EnterState(eSessionReady);
return true;
}
2018-10-29 16:48:36 +00:00
bool
BaseSession::QueueWriteBuffers(llarp_buffer_t buf)
{
if(sendq.size() >= MaxSendQueueSize)
return false;
llarp::LogDebug("write ", buf.sz, " bytes to ", remoteAddr);
2018-12-03 18:28:16 +00:00
lastActive = parent->now();
size_t sz = buf.sz;
2018-10-29 16:48:36 +00:00
byte_t* ptr = buf.base;
while(sz)
{
uint32_t s = std::min(FragmentBodyPayloadSize, sz);
EncryptThenHash(ptr, s, ((sz - s) == 0));
ptr += s;
sz -= s;
}
return true;
}
bool
BaseSession::OutboundLIM(const LinkIntroMessage* msg)
{
if(gotLIM && remoteRC.pubkey != msg->rc.pubkey)
{
return false;
}
remoteRC = msg->rc;
2018-12-03 18:28:16 +00:00
gotLIM = true;
// TODO: update address info pubkey
return DoKeyExchange(Router()->crypto.transport_dh_client, msg->N,
remoteTransportPubKey, Router()->encryption);
}
void
BaseSession::OutboundHandshake()
{
// set session key
Router()->crypto.shorthash(sessionKey, ConstBuffer(remoteRC.pubkey));
byte_t tmp[LinkIntroMessage::MaxSize];
auto buf = StackBuffer< decltype(tmp) >(tmp);
// build our RC
LinkIntroMessage msg;
msg.rc = Router()->rc();
2018-10-15 12:02:32 +00:00
if(!msg.rc.Verify(&Router()->crypto))
{
llarp::LogError("our RC is invalid? closing session to", remoteAddr);
Close();
return;
}
msg.N.Randomize();
msg.P = DefaultLinkSessionLifetime;
if(!msg.Sign(&Router()->crypto, Router()->identity))
{
llarp::LogError("failed to sign LIM for outbound handshake to ",
remoteAddr);
Close();
return;
}
// encode
if(!msg.BEncode(&buf))
{
llarp::LogError("failed to encode LIM for handshake to ", remoteAddr);
Close();
return;
}
// rewind
2018-12-03 18:28:16 +00:00
buf.sz = buf.cur - buf.base;
buf.cur = buf.base;
// send
if(!SendMessageBuffer(buf))
{
llarp::LogError("failed to send handshake to ", remoteAddr);
Close();
return;
}
// mix keys
if(!DoKeyExchange(Router()->crypto.transport_dh_client, msg.N,
remoteTransportPubKey, Router()->encryption))
{
llarp::LogError("failed to mix keys for outbound session to ",
remoteAddr);
Close();
return;
}
EnterState(eSessionReady);
2018-09-06 11:46:19 +00:00
}
llarp::Router*
2018-09-06 11:46:19 +00:00
BaseSession::Router()
{
2018-09-06 11:46:19 +00:00
return parent->router;
}
BaseSession::~BaseSession()
{
2018-09-06 13:16:24 +00:00
if(sock)
{
2018-09-23 11:29:41 +00:00
utp_shutdown(sock, SHUT_RDWR);
utp_close(sock);
2018-09-06 13:16:24 +00:00
utp_set_userdata(sock, nullptr);
}
}
2018-09-06 13:16:24 +00:00
ILinkSession*
LinkLayer::NewOutboundSession(const RouterContact& rc,
const AddressInfo& addr)
{
return new BaseSession(this, utp_create_socket(_utp_ctx), rc, addr);
2018-09-06 11:46:19 +00:00
}
uint64
LinkLayer::OnRead(utp_callback_arguments* arg)
{
BaseSession* self =
static_cast< BaseSession* >(utp_get_userdata(arg->socket));
2018-09-07 17:41:49 +00:00
2018-09-06 11:46:19 +00:00
if(self)
{
2018-09-06 13:16:24 +00:00
if(self->state == BaseSession::eClose)
{
return 0;
}
if(!self->Recv(arg->buf, arg->len))
2018-09-06 20:31:58 +00:00
{
llarp::LogDebug("recv fail for ", self->remoteAddr);
self->Close();
return 0;
2018-09-06 11:46:19 +00:00
}
utp_read_drained(arg->socket);
2018-09-06 11:46:19 +00:00
}
else
{
llarp::LogWarn("utp_socket got data with no underlying session");
2018-09-18 12:29:27 +00:00
utp_close(arg->socket);
2018-09-06 11:46:19 +00:00
}
return 0;
}
2018-09-06 11:46:19 +00:00
uint64
LinkLayer::OnStateChange(utp_callback_arguments* arg)
{
2018-09-06 11:46:19 +00:00
LinkLayer* l =
static_cast< LinkLayer* >(utp_context_get_userdata(arg->context));
BaseSession* session =
static_cast< BaseSession* >(utp_get_userdata(arg->socket));
2018-09-06 13:16:24 +00:00
if(session)
2018-09-06 11:46:19 +00:00
{
2018-09-06 13:16:24 +00:00
if(arg->state == UTP_STATE_CONNECT)
{
if(session->state == BaseSession::eClose)
{
return 0;
}
session->OutboundLinkEstablished(l);
}
2018-09-06 20:31:58 +00:00
else if(arg->state == UTP_STATE_WRITABLE)
{
2018-09-12 13:29:42 +00:00
session->PumpWrite();
2018-09-06 20:31:58 +00:00
}
2018-09-06 13:16:24 +00:00
else if(arg->state == UTP_STATE_EOF)
{
2018-09-07 17:41:49 +00:00
llarp::LogDebug("got eof from ", session->remoteAddr);
session->Close();
2018-09-06 13:16:24 +00:00
}
2018-09-06 11:46:19 +00:00
}
return 0;
}
uint64
LinkLayer::OnAccept(utp_callback_arguments* arg)
{
LinkLayer* self =
static_cast< LinkLayer* >(utp_context_get_userdata(arg->context));
Addr remote(*arg->address);
llarp::LogDebug("utp accepted from ", remote);
BaseSession* session = new BaseSession(self, arg->socket, remote);
2018-09-10 13:43:36 +00:00
self->PutSession(session);
2018-09-06 11:46:19 +00:00
session->OnLinkEstablished(self);
return 0;
}
2018-09-06 11:46:19 +00:00
void
2018-09-07 20:36:06 +00:00
BaseSession::EncryptThenHash(const byte_t* ptr, uint32_t sz,
bool isLastFragment)
2018-09-06 11:46:19 +00:00
{
sendq.emplace_back();
auto& buf = sendq.back();
2018-09-12 13:29:42 +00:00
vecq.emplace_back();
2018-12-03 18:28:16 +00:00
auto& vec = vecq.back();
2018-09-12 13:29:42 +00:00
vec.iov_base = buf.data();
2018-12-03 18:28:16 +00:00
vec.iov_len = FragmentBufferSize;
2018-09-06 20:31:58 +00:00
llarp::LogDebug("encrypt then hash ", sz, " bytes last=", isLastFragment);
2018-09-06 11:46:19 +00:00
buf.Randomize();
2018-09-07 20:36:06 +00:00
byte_t* nonce = buf.data() + FragmentHashSize;
2018-12-03 18:28:16 +00:00
byte_t* body = nonce + FragmentNonceSize;
byte_t* base = body;
2018-09-06 11:46:19 +00:00
if(isLastFragment)
htobe32buf(body, 0);
2018-09-07 17:41:49 +00:00
else
htobe32buf(body, 1);
2018-09-06 11:46:19 +00:00
body += sizeof(uint32_t);
htobe32buf(body, sz);
body += sizeof(uint32_t);
memcpy(body, ptr, sz);
2018-09-07 20:36:06 +00:00
auto payload =
InitBuffer(base, FragmentBufferSize - FragmentOverheadSize);
// encrypt
2018-09-07 17:41:49 +00:00
Router()->crypto.xchacha20(payload, sessionKey, nonce);
2018-09-07 20:36:06 +00:00
payload.base = nonce;
2018-12-03 18:28:16 +00:00
payload.cur = payload.base;
payload.sz = FragmentBufferSize - FragmentHashSize;
2018-09-07 20:36:06 +00:00
// key'd hash
2018-09-07 17:41:49 +00:00
Router()->crypto.hmac(buf.data(), payload, sessionKey);
2018-09-06 11:46:19 +00:00
}
void
BaseSession::EnterState(State st)
{
2018-09-06 13:16:24 +00:00
state = st;
2018-11-21 17:46:33 +00:00
Alive();
2018-09-06 11:46:19 +00:00
if(st == eSessionReady)
{
2018-09-07 17:41:49 +00:00
parent->MapAddr(remoteRC.pubkey, this);
2018-11-21 17:46:33 +00:00
Router()->HandleLinkSessionEstablished(remoteRC, parent);
2018-09-06 11:46:19 +00:00
}
}
bool
2018-09-07 17:41:49 +00:00
BaseSession::VerifyThenDecrypt(byte_t* buf)
2018-09-06 11:46:19 +00:00
{
2018-09-06 20:31:58 +00:00
llarp::LogDebug("verify then decrypt ", remoteAddr);
2018-09-06 11:46:19 +00:00
ShortHash digest;
2018-09-06 20:31:58 +00:00
2018-09-07 17:41:49 +00:00
auto hbuf = InitBuffer(buf + FragmentHashSize,
FragmentBufferSize - FragmentHashSize);
if(!Router()->crypto.hmac(digest.data(), hbuf, sessionKey))
2018-09-06 11:46:19 +00:00
{
llarp::LogError("keyed hash failed");
return false;
}
2018-09-07 17:41:49 +00:00
ShortHash expected(buf);
if(expected != digest)
2018-09-06 11:46:19 +00:00
{
2018-09-06 20:31:58 +00:00
llarp::LogError("Message Integrity Failed: got ", digest, " from ",
2018-09-07 17:41:49 +00:00
remoteAddr, " instead of ", expected);
llarp::DumpBuffer(InitBuffer(buf, FragmentBufferSize));
2018-09-06 11:46:19 +00:00
return false;
}
2018-09-07 17:41:49 +00:00
auto body = InitBuffer(buf + FragmentOverheadSize,
2018-09-06 11:46:19 +00:00
FragmentBufferSize - FragmentOverheadSize);
2018-09-07 17:41:49 +00:00
Router()->crypto.xchacha20(body, sessionKey, buf + FragmentHashSize);
2018-09-06 11:46:19 +00:00
uint32_t upper, lower;
if(!(llarp_buffer_read_uint32(&body, &upper)
&& llarp_buffer_read_uint32(&body, &lower)))
return false;
bool fragmentEnd = upper == 0;
2018-09-06 20:31:58 +00:00
llarp::LogDebug("fragment size ", lower, " from ", remoteAddr);
if(lower + recvMsgOffset > recvMsg.size())
2018-09-06 11:46:19 +00:00
{
llarp::LogError("Fragment too big: ", lower, " bytes");
return false;
}
2018-09-07 20:36:06 +00:00
memcpy(recvMsg.data() + recvMsgOffset, body.cur, lower);
2018-09-06 20:31:58 +00:00
recvMsgOffset += lower;
2018-09-06 11:46:19 +00:00
if(fragmentEnd)
{
// got a message
2018-09-06 20:31:58 +00:00
llarp::LogDebug("end of message from ", remoteAddr);
2018-09-07 20:36:06 +00:00
auto mbuf = InitBuffer(recvMsg.data(), recvMsgOffset);
if(!Router()->HandleRecvLinkMessageBuffer(this, mbuf))
2018-09-06 20:31:58 +00:00
{
llarp::LogWarn("failed to handle message from ", remoteAddr);
llarp::DumpBuffer(mbuf);
}
recvMsgOffset = 0;
2018-09-06 11:46:19 +00:00
}
return true;
}
2018-09-06 20:31:58 +00:00
void
2018-09-07 17:41:49 +00:00
BaseSession::Close()
2018-09-06 20:31:58 +00:00
{
if(state != eClose)
{
2018-09-07 20:36:06 +00:00
if(sock)
{
utp_shutdown(sock, SHUT_RDWR);
utp_close(sock);
llarp::LogDebug("utp_close ", remoteAddr);
utp_set_userdata(sock, nullptr);
}
2018-09-06 20:31:58 +00:00
}
EnterState(eClose);
sock = nullptr;
}
void
BaseSession::Alive()
{
2018-10-29 16:48:36 +00:00
lastActive = parent->now();
2018-09-06 11:46:19 +00:00
}
} // namespace utp
} // namespace llarp