You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lokinet/llarp/service/endpoint.hpp

530 lines
14 KiB
C++

#pragma once
#include <llarp/dns/server.hpp>
#include <llarp/endpoint_base.hpp>
#include <llarp/ev/ev.hpp>
#include <llarp/exit/session.hpp>
#include <llarp/net/ip_range_map.hpp>
#include <llarp/net/net.hpp>
#include <llarp/path/pathbuilder.hpp>
#include <llarp/service/address.hpp>
#include <llarp/service/auth.hpp>
#include <llarp/service/endpoint_types.hpp>
#include <llarp/service/identity.hpp>
#include <llarp/service/pendingbuffer.hpp>
#include <llarp/service/protocol.hpp>
#include <llarp/service/protocol_type.hpp>
#include <llarp/service/session.hpp>
#include <llarp/util/compare_ptr.hpp>
#include <llarp/vpn/egres_packet_router.hpp>
#include <oxenc/variant.h>
7 months ago
#include <optional>
#include <unordered_map>
#include <variant>
// minimum time between introset shifts
#ifndef MIN_SHIFT_INTERVAL
#define MIN_SHIFT_INTERVAL 5s
#endif
6 years ago
namespace llarp
{
QUIC lokinet integration refactor Refactors how quic packets get handled: the actual tunnels now live in tunnel.hpp's TunnelManager which holds and manages all the quic<->tcp tunnelling. service::Endpoint now holds a TunnelManager rather than a quic::Server. We only need one quic server, but we need a separate quic client instance per outgoing quic tunnel, and TunnelManager handles all that glue now. Adds QUIC packet handling to get to the right tunnel code. This required multiplexing incoming quic packets, as follows: Adds a very small quic tunnel packet header of 4 bytes: [1, SPORT, ECN] for client->server packets, where SPORT is our source "port" (really: just a uint16_t unique quic instance identifier) or [2, DPORT, ECN] for server->client packets where the DPORT is the SPORT from above. (This also reworks ECN bits to get properly carried over lokinet.) We don't need a destination/source port for the server-side because there is only ever one quic server (and we know we're going to it when the first byte of the header is 1). Removes the config option for quic exposing ports; a full lokinet will simply accept anything incoming on quic and tunnel it to the requested port on the the local endpoint IP (this handler will come in a following commit). Replace ConvoTags with full addresses: we need to carry the port, as well, which the ConvoTag can't give us, so change those to more general SockAddrs from which we can extract both the ConvoTag *and* the port. Add a pending connection queue along with new quic-side handlers to call when a stream becomes available (TunnelManager uses this to wire up pending incoming conns with quic streams as streams open up). Completely get rid of tunnel_server/tunnel_client.cpp code; it is now moved to tunnel.hpp. Add listen()/forget() methods in TunnelManager for setting up quic listening sockets (for liblokinet usage). Add open()/close() methods in TunnelManager for spinning up new quic clients for outgoing quic connections.
3 years ago
namespace quic
{
class TunnelManager;
}
6 years ago
namespace service
{
struct AsyncKeyExchange;
7 months ago
struct Context;
struct EndpointState;
struct OutboundContext;
/// minimum interval for publishing introsets
inline constexpr auto IntrosetPublishInterval = path::INTRO_PATH_SPREAD / 2;
/// how agressively should we retry publishing introset on failure
inline constexpr auto IntrosetPublishRetryCooldown = 1s;
/// how aggressively should we retry looking up introsets
inline constexpr auto IntrosetLookupCooldown = 250ms;
/// number of unique snodes we want to talk to do to ons lookups
inline constexpr size_t MIN_ONS_LOOKUP_ENDPOINTS = 2;
inline constexpr size_t MAX_ONS_LOOKUP_ENDPOINTS = 7;
8 months ago
// TODO: delete this, it is copied from the late llarp/service/handler.hpp
struct RecvDataEvent
{
path::Path_ptr fromPath;
PathID_t pathid;
std::shared_ptr<ProtocolMessage> msg;
};
struct Endpoint : public path::Builder, public EndpointBase
// public std::enable_shared_from_this<Endpoint>
6 years ago
{
Endpoint(Router* r, Context* parent);
~Endpoint() override;
6 years ago
/// return true if we are ready to recv packets from the void.
/// really should be ReadyForInboundTraffic() but the diff is HUGE and we need to rewrite this
/// component anyways.
bool
is_ready() const;
void
8 months ago
QueueRecvData(RecvDataEvent ev);
/// return true if our introset has expired intros
bool
IntrosetIsStale() const;
/// construct parameters for notify hooks
virtual std::unordered_map<std::string, std::string>
NotifyParams() const;
virtual util::StatusObject
ExtractStatus() const;
6 years ago
virtual bool
Configure(const NetworkConfig& conf, const DnsConfig& dnsConf);
6 years ago
void
Tick(llarp_time_t now) override;
/// return true if we have a resolvable ip address
virtual bool
HasIfAddr() const
{
return false;
}
virtual std::string
GetIfName() const = 0;
std::optional<ConvoTag>
GetBestConvoTagFor(std::variant<Address, RouterID> addr) const override;
/// get our ifaddr if it is set
5 years ago
virtual huint128_t
GetIfAddr() const
{
return {0};
}
/// get the exit policy for our exit if we have one
/// override me
virtual std::optional<net::TrafficPolicy>
GetExitPolicy() const
{
return std::nullopt;
};
/// get the ip ranges we claim to own
/// override me
virtual std::set<IPRange>
GetOwnedRanges() const
{
return {};
};
virtual void
Thaw(){};
void
ResetInternalState() override;
/// loop (via router)
/// use when sending any data on a path
const EventLoop_ptr&
Loop() override;
Router*
router();
virtual bool
LoadKeyFile();
6 years ago
virtual bool
6 years ago
Start();
std::string
Name() const override;
6 years ago
AddressVariant_t
LocalAddress() const override;
std::optional<SendStat>
GetStatFor(AddressVariant_t remote) const override;
std::unordered_set<AddressVariant_t>
AllRemoteEndpoints() const override;
6 years ago
bool
ShouldPublishDescriptors(llarp_time_t now) const override;
6 years ago
void
SRVRecordsChanged() override;
void
HandlePathDied(path::Path_ptr p) override;
virtual vpn::EgresPacketRouter*
EgresPacketRouter()
{
return nullptr;
4 months ago
}
virtual vpn::NetworkInterface*
GetVPNInterface()
{
return nullptr;
}
6 years ago
bool
8 months ago
publish_introset(const EncryptedIntroSet& i);
6 years ago
bool
HandleHiddenServiceFrame(path::Path_ptr p, const service::ProtocolFrameMessage& msg);
6 years ago
void
SetEndpointAuth(std::shared_ptr<IAuthPolicy> policy);
/// sets how we authenticate with remote address
void
SetAuthInfoForEndpoint(Address remote, AuthInfo info);
virtual huint128_t ObtainIPForAddr(std::variant<Address, RouterID>) = 0;
/// get a key for ip address
virtual std::optional<std::variant<service::Address, RouterID>>
ObtainAddrForIP(huint128_t ip) const = 0;
6 years ago
// virtual bool
// HasServiceAddress(const AlignedBuffer< 32 >& addr) const = 0;
/// return true if we have a pending job to build to a hidden service but
/// it's not done yet
bool
HasPendingPathToService(const Address& remote) const;
bool
HandleDataMessage(
8 months ago
path::Path_ptr path, const PathID_t from, std::shared_ptr<ProtocolMessage> msg);
/// handle packet io from service node or hidden service to frontend
virtual bool
HandleInboundPacket(
const ConvoTag tag, const llarp_buffer_t& pkt, ProtocolType t, uint64_t seqno) = 0;
// virtual bool
// HandleWriteIPPacket(const llarp_buffer_t& pkt,
// std::function< huint128_t(void) > getFromIP) = 0;
bool
ProcessDataMessage(std::shared_ptr<ProtocolMessage> msg);
// "find name"
void
lookup_name(std::string name, std::function<void(std::string, bool)> func = nullptr) override;
7 months ago
// "find introset?"
3 years ago
void
LookupServiceAsync(
std::string name,
std::string service,
std::function<void(std::vector<dns::SRVData>)> resultHandler) override;
5 years ago
/// called on event loop pump
virtual void
Pump(llarp_time_t now);
/// stop this endpoint
bool
Stop() override;
const Identity&
GetIdentity() const
{
return _identity;
}
void
MapExitRange(IPRange range, service::Address exit);
void
UnmapExitRange(IPRange range);
void
UnmapRangeByExit(IPRange range, std::string exit);
void
map_exit(
std::string name,
std::string token,
std::vector<IPRange> ranges,
std::function<void(bool, std::string)> result);
void
HandlePathBuilt(path::Path_ptr path) override;
bool
HandleDataDrop(path::Path_ptr p, const PathID_t& dst, uint64_t s);
bool
CheckPathIsDead(path::Path_ptr p, llarp_time_t latency);
using PendingBufferQueue = std::deque<PendingBuffer>;
6 years ago
size_t
RemoveAllConvoTagsFor(service::Address remote);
4 years ago
bool
8 months ago
WantsOutboundSession(const Address&) const;
4 years ago
/// this MUST be called if you want to call EnsurePathTo on the given address
void MarkAddressOutbound(service::Address) override;
4 years ago
void
BlacklistSNode(const RouterID snode) override;
/// maybe get an endpoint variant given its convo tag
std::optional<std::variant<Address, RouterID>>
GetEndpointWithConvoTag(ConvoTag t) const override;
5 years ago
bool
8 months ago
HasConvoTag(const ConvoTag& t) const;
5 years ago
bool
ShouldBuildMore(llarp_time_t now) const override;
virtual llarp_time_t
PathAlignmentTimeout() const
{
constexpr auto DefaultPathAlignmentTimeout = 30s;
return DefaultPathAlignmentTimeout;
}
bool
EnsurePathTo(
std::variant<Address, RouterID> addr,
std::function<void(std::optional<ConvoTag>)> hook,
llarp_time_t timeout) override;
static constexpr auto DefaultPathEnsureTimeout = 2s;
6 years ago
/// return false if we have already called this function before for this
/// address
bool
EnsurePathToService(
const Address remote,
std::function<void(Address, OutboundContext*)> h,
llarp_time_t timeoutMS = DefaultPathEnsureTimeout);
6 years ago
void
InformPathToService(const Address remote, OutboundContext* ctx);
/// ensure a path to a service node by public key
bool
EnsurePathToSNode(
const RouterID remote,
std::function<void(const RouterID, exit::BaseSession_ptr, ConvoTag)> h);
/// return true if this endpoint is trying to lookup this router right now
bool
HasPendingRouterLookup(const RouterID remote) const;
bool
HasPathToSNode(const RouterID remote) const;
bool
HasFlowToService(const Address remote) const;
void
8 months ago
PutSenderFor(const ConvoTag& tag, const ServiceInfo& info, bool inbound);
bool
8 months ago
HasInboundConvo(const Address& addr) const;
bool
8 months ago
HasOutboundConvo(const Address& addr) const;
bool
8 months ago
GetCachedSessionKeyFor(const ConvoTag& remote, SharedSecret& secret) const;
void
8 months ago
PutCachedSessionKeyFor(const ConvoTag& remote, const SharedSecret& secret);
bool
8 months ago
GetSenderFor(const ConvoTag& remote, ServiceInfo& si) const;
void
8 months ago
PutIntroFor(const ConvoTag& remote, const Introduction& intro);
bool
8 months ago
GetIntroFor(const ConvoTag& remote, Introduction& intro) const;
void
8 months ago
RemoveConvoTag(const ConvoTag& remote);
void
8 months ago
ConvoTagTX(const ConvoTag& remote);
void
8 months ago
ConvoTagRX(const ConvoTag& remote);
5 years ago
void
8 months ago
PutReplyIntroFor(const ConvoTag& remote, const Introduction& intro);
5 years ago
bool
8 months ago
GetReplyIntroFor(const ConvoTag& remote, Introduction& intro) const;
5 years ago
bool
8 months ago
GetConvoTagsForService(const Address& si, std::set<ConvoTag>& tag) const;
void
PutNewOutboundContext(const IntroSet& introset, llarp_time_t timeLeftToAlign);
std::optional<uint64_t>
GetSeqNoForConvo(const ConvoTag& tag);
/// count unique endpoints we are talking to
size_t
UniqueEndpoints() const;
bool
HasExit() const;
std::optional<std::vector<RemoteRC>>
GetHopsForBuild() override;
std::optional<std::vector<RemoteRC>>
GetHopsForBuildWithEndpoint(RouterID endpoint);
void
4 years ago
AsyncProcessAuthMessage(
std::shared_ptr<ProtocolMessage> msg, std::function<void(std::string, bool)> hook);
void
SendAuthResult(
path::Path_ptr path, PathID_t replyPath, ConvoTag tag, std::string result, bool success);
uint64_t
GenTXID();
void
ResetConvoTag(ConvoTag tag, path::Path_ptr path, PathID_t from);
const std::set<RouterID>&
SnodeBlacklist() const;
// Looks up the ConvoTag and, if it exists, calls SendToOrQueue to send it to a remote client
// or a snode (or nothing, if the convo tag is unknown).
bool
7 months ago
send_to(ConvoTag tag, std::string payload) override;
std::optional<AuthInfo>
MaybeGetAuthInfoForEndpoint(service::Address addr);
QUIC lokinet integration refactor Refactors how quic packets get handled: the actual tunnels now live in tunnel.hpp's TunnelManager which holds and manages all the quic<->tcp tunnelling. service::Endpoint now holds a TunnelManager rather than a quic::Server. We only need one quic server, but we need a separate quic client instance per outgoing quic tunnel, and TunnelManager handles all that glue now. Adds QUIC packet handling to get to the right tunnel code. This required multiplexing incoming quic packets, as follows: Adds a very small quic tunnel packet header of 4 bytes: [1, SPORT, ECN] for client->server packets, where SPORT is our source "port" (really: just a uint16_t unique quic instance identifier) or [2, DPORT, ECN] for server->client packets where the DPORT is the SPORT from above. (This also reworks ECN bits to get properly carried over lokinet.) We don't need a destination/source port for the server-side because there is only ever one quic server (and we know we're going to it when the first byte of the header is 1). Removes the config option for quic exposing ports; a full lokinet will simply accept anything incoming on quic and tunnel it to the requested port on the the local endpoint IP (this handler will come in a following commit). Replace ConvoTags with full addresses: we need to carry the port, as well, which the ConvoTag can't give us, so change those to more general SockAddrs from which we can extract both the ConvoTag *and* the port. Add a pending connection queue along with new quic-side handlers to call when a stream becomes available (TunnelManager uses this to wire up pending incoming conns with quic streams as streams open up). Completely get rid of tunnel_server/tunnel_client.cpp code; it is now moved to tunnel.hpp. Add listen()/forget() methods in TunnelManager for setting up quic listening sockets (for liblokinet usage). Add open()/close() methods in TunnelManager for spinning up new quic clients for outgoing quic connections.
3 years ago
/// Returns a pointer to the quic::Tunnel object handling quic connections for this endpoint.
/// Returns nullptr if quic is not supported.
link::TunnelManager*
GetQUICTunnel() override;
QUIC lokinet integration refactor Refactors how quic packets get handled: the actual tunnels now live in tunnel.hpp's TunnelManager which holds and manages all the quic<->tcp tunnelling. service::Endpoint now holds a TunnelManager rather than a quic::Server. We only need one quic server, but we need a separate quic client instance per outgoing quic tunnel, and TunnelManager handles all that glue now. Adds QUIC packet handling to get to the right tunnel code. This required multiplexing incoming quic packets, as follows: Adds a very small quic tunnel packet header of 4 bytes: [1, SPORT, ECN] for client->server packets, where SPORT is our source "port" (really: just a uint16_t unique quic instance identifier) or [2, DPORT, ECN] for server->client packets where the DPORT is the SPORT from above. (This also reworks ECN bits to get properly carried over lokinet.) We don't need a destination/source port for the server-side because there is only ever one quic server (and we know we're going to it when the first byte of the header is 1). Removes the config option for quic exposing ports; a full lokinet will simply accept anything incoming on quic and tunnel it to the requested port on the the local endpoint IP (this handler will come in a following commit). Replace ConvoTags with full addresses: we need to carry the port, as well, which the ConvoTag can't give us, so change those to more general SockAddrs from which we can extract both the ConvoTag *and* the port. Add a pending connection queue along with new quic-side handlers to call when a stream becomes available (TunnelManager uses this to wire up pending incoming conns with quic streams as streams open up). Completely get rid of tunnel_server/tunnel_client.cpp code; it is now moved to tunnel.hpp. Add listen()/forget() methods in TunnelManager for setting up quic listening sockets (for liblokinet usage). Add open()/close() methods in TunnelManager for spinning up new quic clients for outgoing quic connections.
3 years ago
protected:
/// parent context that owns this endpoint
Context* const context;
5 years ago
virtual bool
SupportsV6() const = 0;
void
regen_and_publish_introset();
6 years ago
IServiceLookup*
GenerateLookupByTag(const Tag& tag);
void
PrefetchServicesByTag(const Tag& tag);
private:
bool
6 years ago
DoNetworkIsolation(bool failed);
6 years ago
virtual bool
SetupNetworking()
{
// XXX: override me
return true;
}
6 years ago
virtual bool
IsolationFailed()
{
// XXX: override me
return false;
}
/// return true if we are ready to do outbound and inbound traffic
bool
ReadyForNetwork() const;
protected:
bool
ReadyToDoLookup(size_t num_paths) const;
auto
GetUniqueEndpointsForLookup() const;
Identity _identity;
net::IPRangeMap<service::Address> _exit_map;
bool _publish_introset = true;
std::unique_ptr<EndpointState> _state;
std::shared_ptr<IAuthPolicy> _auth_policy;
std::unordered_map<Address, AuthInfo> _remote_auth_infos;
std::unique_ptr<link::TunnelManager> _tunnel_manager;
/// (ons name, optional exit range, optional auth info) for looking up on startup
std::unordered_map<std::string, std::pair<std::optional<IPRange>, std::optional<AuthInfo>>>
_startup_ons_mappings;
RecvPacketQueue_t _inbound_queue;
public:
8 months ago
SendMessageEventQueue _send_queue;
private:
llarp_time_t _last_introset_regen_attempt = 0s;
protected:
void
FlushRecvData();
friend struct EndpointUtil;
const IntroSet&
intro_set() const;
IntroSet&
intro_set();
const std::unordered_map<ConvoTag, Session>&
Sessions() const;
std::unordered_map<ConvoTag, Session>&
Sessions();
thread::Queue<RecvDataEvent> _recv_event_queue;
/// for rate limiting introset lookups
util::DecayingHashSet<Address> _introset_lookup_filter;
6 years ago
};
using Endpoint_ptr = std::shared_ptr<Endpoint>;
6 years ago
} // namespace service
} // namespace llarp