fix crash on premature close of event loop (also make format)

pull/90/head
Jeff Becker 6 years ago
parent 82af91213a
commit 622ed8d12e
No known key found for this signature in database
GPG Key ID: F357B3B42F6F9B05

@ -37,7 +37,7 @@ extern "C"
/// give main context a vpn file descriptor (android/ios) /// give main context a vpn file descriptor (android/ios)
void void
llarp_main_inject_vpn_fd(struct llarp_main * m, int fd); llarp_main_inject_vpn_fd(struct llarp_main *m, int fd);
/// setup main context /// setup main context
int int

@ -16,7 +16,6 @@ namespace llarp
int num_nethreads = 1; int num_nethreads = 1;
bool singleThreaded = false; bool singleThreaded = false;
std::vector< std::thread > netio_threads;
llarp_crypto crypto; llarp_crypto crypto;
llarp_router *router = nullptr; llarp_router *router = nullptr;
llarp_threadpool *worker = nullptr; llarp_threadpool *worker = nullptr;

@ -407,11 +407,10 @@ namespace llarp
llarp_time_t llarp_time_t
Now(); Now();
void void
ExploreNetworkVia(const Key_t& peer); ExploreNetworkVia(const Key_t& peer);
private: private:
void void
ScheduleCleanupTimer(); ScheduleCleanupTimer();

@ -49,7 +49,7 @@ struct dns_tracker
struct dns_msg_header struct dns_msg_header
{ {
uint16_t id; uint16_t id;
uint8_t qr : 1; uint8_t qr : 1;
uint8_t opcode : 4; uint8_t opcode : 4;
uint8_t aa : 1; uint8_t aa : 1;
@ -62,12 +62,13 @@ struct dns_msg_header
uint8_t cd : 1; uint8_t cd : 1;
uint8_t rcode : 4; uint8_t rcode : 4;
uint16_t fields() const uint16_t
fields() const
{ {
return (qr << 15) | (opcode << 14) | (aa << 10) | (tc << 9) | (rd << 8) << (ra << 7) | (z << 6) | rcode; return (qr << 15) | (opcode << 14) | (aa << 10) | (tc << 9)
| (rd << 8) << (ra << 7) | (z << 6) | rcode;
} }
uint16_t qdCount; uint16_t qdCount;
uint16_t anCount; uint16_t anCount;
uint16_t nsCount; uint16_t nsCount;
@ -128,7 +129,7 @@ extern "C"
get32bits(const char *&buffer) throw(); get32bits(const char *&buffer) throw();
bool bool
decode_hdr(llarp_buffer_t * buffer, dns_msg_header * hdr); decode_hdr(llarp_buffer_t *buffer, dns_msg_header *hdr);
dns_msg_question * dns_msg_question *
decode_question(const char *buffer, uint32_t *pos); decode_question(const char *buffer, uint32_t *pos);

@ -6,7 +6,7 @@
#include "dnsd.hpp" #include "dnsd.hpp"
using map_address_hook_func = using map_address_hook_func =
std::function< bool(const byte_t* addr,bool isSNode, uint32_t ip) >; std::function< bool(const byte_t *addr, bool isSNode, uint32_t ip) >;
/// dotLokiLookup context/config /// dotLokiLookup context/config
struct dotLokiLookup struct dotLokiLookup
@ -35,6 +35,6 @@ struct dotLokiLookup
dnsd_query_hook_response * dnsd_query_hook_response *
llarp_dotlokilookup_handler(std::string name, llarp_dotlokilookup_handler(std::string name,
const dnsd_question_request * request); const dnsd_question_request *request);
#endif #endif

@ -68,7 +68,8 @@ write404_dnss_response(const dnsd_question_request *request);
/// for hook functions to use /// for hook functions to use
void void
writecname_dnss_response(std::string cname, const dnsd_question_request *request); writecname_dnss_response(std::string cname,
const dnsd_question_request *request);
// FIXME: llarp::Addr // FIXME: llarp::Addr
/// send an A record found response /// send an A record found response
@ -79,7 +80,8 @@ writesend_dnss_response(llarp::huint32_t *hostRes,
/// send an PTR record found response /// send an PTR record found response
void void
writesend_dnss_revresponse(std::string reverse, const dnsd_question_request *request); writesend_dnss_revresponse(std::string reverse,
const dnsd_question_request *request);
// FIXME: llarp::Addr // FIXME: llarp::Addr
// //

@ -167,13 +167,11 @@ llarp_tcp_acceptor_close(struct llarp_tcp_acceptor *);
#define IFNAMSIZ (16) #define IFNAMSIZ (16)
#endif #endif
struct llarp_fd_promise; struct llarp_fd_promise;
/// wait until the fd promise is set /// wait until the fd promise is set
int int
llarp_fd_promise_wait_for_value(struct llarp_fd_promise * promise); llarp_fd_promise_wait_for_value(struct llarp_fd_promise *promise);
struct llarp_tun_io struct llarp_tun_io
{ {
@ -185,9 +183,9 @@ struct llarp_tun_io
void *user; void *user;
void *impl; void *impl;
/// functor for getting a promise that returns the vpn fd /// functor for getting a promise that returns the vpn fd
/// dont set me if you don't know how to use this /// dont set me if you don't know how to use this
struct llarp_fd_promise * (*get_fd_promise)(struct llarp_tun_io *); struct llarp_fd_promise *(*get_fd_promise)(struct llarp_tun_io *);
struct llarp_ev_loop *parent; struct llarp_ev_loop *parent;
/// called when we are able to write right before we write /// called when we are able to write right before we write
@ -203,7 +201,6 @@ struct llarp_tun_io
bool bool
llarp_ev_add_tun(struct llarp_ev_loop *ev, struct llarp_tun_io *tun); llarp_ev_add_tun(struct llarp_ev_loop *ev, struct llarp_tun_io *tun);
/// async write a packet on tun interface /// async write a packet on tun interface
/// returns true if queued, returns false on drop /// returns true if queued, returns false on drop
bool bool

@ -39,7 +39,7 @@ namespace llarp
ExpiresSoon(llarp_time_t now, llarp_time_t dlt = 5000) const; ExpiresSoon(llarp_time_t now, llarp_time_t dlt = 5000) const;
/// return true if this endpoint looks dead right now /// return true if this endpoint looks dead right now
bool bool
LooksDead(llarp_time_t now, llarp_time_t timeout = 10000) const; LooksDead(llarp_time_t now, llarp_time_t timeout = 10000) const;
/// tick ourself, reset tx/rx rates /// tick ourself, reset tx/rx rates
@ -105,27 +105,30 @@ namespace llarp
uint64_t m_TxRate, m_RxRate; uint64_t m_TxRate, m_RxRate;
llarp_time_t m_LastActive; llarp_time_t m_LastActive;
bool m_RewriteSource; bool m_RewriteSource;
using InboundTrafficQueue_t = std::deque<llarp::routing::TransferTrafficMessage>; using InboundTrafficQueue_t =
using TieredQueue = std::map<uint8_t, InboundTrafficQueue_t>; std::deque< llarp::routing::TransferTrafficMessage >;
using TieredQueue = std::map< uint8_t, InboundTrafficQueue_t >;
// maps number of fragments the message will fit in to the queue for it // maps number of fragments the message will fit in to the queue for it
TieredQueue m_DownstreamQueues; TieredQueue m_DownstreamQueues;
struct UpstreamBuffer struct UpstreamBuffer
{ {
UpstreamBuffer(const llarp::net::IPv4Packet & p, uint64_t c) : pkt(p), counter(c) UpstreamBuffer(const llarp::net::IPv4Packet& p, uint64_t c)
: pkt(p), counter(c)
{ {
} }
llarp::net::IPv4Packet pkt; llarp::net::IPv4Packet pkt;
uint64_t counter; uint64_t counter;
bool operator<(const UpstreamBuffer & other) const bool
operator<(const UpstreamBuffer& other) const
{ {
return counter < other.counter; return counter < other.counter;
} }
}; };
using UpstreamQueue_t = std::priority_queue<UpstreamBuffer>; using UpstreamQueue_t = std::priority_queue< UpstreamBuffer >;
UpstreamQueue_t m_UpstreamQueue; UpstreamQueue_t m_UpstreamQueue;
uint64_t m_Counter; uint64_t m_Counter;
}; };

@ -10,7 +10,6 @@ namespace llarp
{ {
namespace exit namespace exit
{ {
/// a persisiting exit session with an exit router /// a persisiting exit session with an exit router
struct BaseSession : public llarp::path::Builder struct BaseSession : public llarp::path::Builder
{ {
@ -38,16 +37,15 @@ namespace llarp
bool bool
FlushUpstreamTraffic(); FlushUpstreamTraffic();
bool bool
IsReady() const; IsReady() const;
protected: protected:
llarp::RouterID m_ExitRouter; llarp::RouterID m_ExitRouter;
std::function< bool(llarp_buffer_t) > m_WritePacket; std::function< bool(llarp_buffer_t) > m_WritePacket;
virtual void virtual void
PopulateRequest(llarp::routing::ObtainExitMessage & msg) const = 0; PopulateRequest(llarp::routing::ObtainExitMessage& msg) const = 0;
bool bool
HandleTrafficDrop(llarp::path::Path* p, const llarp::PathID_t& path, HandleTrafficDrop(llarp::path::Path* p, const llarp::PathID_t& path,
@ -59,9 +57,10 @@ namespace llarp
bool bool
HandleTraffic(llarp::path::Path* p, llarp_buffer_t buf); HandleTraffic(llarp::path::Path* p, llarp_buffer_t buf);
private: private:
using UpstreamTrafficQueue_t = std::deque<llarp::routing::TransferTrafficMessage>; using UpstreamTrafficQueue_t =
using TieredQueue_t = std::map<uint8_t, UpstreamTrafficQueue_t>; std::deque< llarp::routing::TransferTrafficMessage >;
using TieredQueue_t = std::map< uint8_t, UpstreamTrafficQueue_t >;
TieredQueue_t m_Upstream; TieredQueue_t m_Upstream;
uint64_t m_Counter; uint64_t m_Counter;
llarp::SecretKey m_ExitIdentity; llarp::SecretKey m_ExitIdentity;
@ -70,14 +69,15 @@ namespace llarp
struct ExitSession final : public BaseSession struct ExitSession final : public BaseSession
{ {
ExitSession(const llarp::RouterID& snodeRouter, ExitSession(const llarp::RouterID& snodeRouter,
std::function< bool(llarp_buffer_t) > writepkt, std::function< bool(llarp_buffer_t) > writepkt,
llarp_router* r, size_t numpaths, size_t hoplen) : BaseSession(snodeRouter, writepkt, r,numpaths, hoplen) {}; llarp_router* r, size_t numpaths, size_t hoplen)
: BaseSession(snodeRouter, writepkt, r, numpaths, hoplen){};
~ExitSession() {};
~ExitSession(){};
protected:
virtual void protected:
PopulateRequest(llarp::routing::ObtainExitMessage & msg) const override virtual void
PopulateRequest(llarp::routing::ObtainExitMessage& msg) const override
{ {
// TODO: set expiration time // TODO: set expiration time
msg.X = 0; msg.X = 0;
@ -88,14 +88,15 @@ namespace llarp
struct SNodeSession final : public BaseSession struct SNodeSession final : public BaseSession
{ {
SNodeSession(const llarp::RouterID& snodeRouter, SNodeSession(const llarp::RouterID& snodeRouter,
std::function< bool(llarp_buffer_t) > writepkt, std::function< bool(llarp_buffer_t) > writepkt,
llarp_router* r, size_t numpaths, size_t hoplen) : BaseSession(snodeRouter, writepkt, r,numpaths, hoplen) {}; llarp_router* r, size_t numpaths, size_t hoplen)
: BaseSession(snodeRouter, writepkt, r, numpaths, hoplen){};
~SNodeSession() {}; ~SNodeSession(){};
protected: protected:
void void
PopulateRequest(llarp::routing::ObtainExitMessage & msg) const override PopulateRequest(llarp::routing::ObtainExitMessage& msg) const override
{ {
// TODO: set expiration time // TODO: set expiration time
msg.X = 0; msg.X = 0;

@ -2,30 +2,34 @@
#define LLARP_HANDLERS_NULL_HPP #define LLARP_HANDLERS_NULL_HPP
#include <llarp/service/endpoint.hpp> #include <llarp/service/endpoint.hpp>
namespace llarp namespace llarp
{ {
namespace handlers namespace handlers
{ {
struct NullEndpoint final : public llarp::service::Endpoint struct NullEndpoint final : public llarp::service::Endpoint
{ {
NullEndpoint(const std::string & name, llarp_router *r) : llarp::service::Endpoint(name, r) {}; NullEndpoint(const std::string &name, llarp_router *r)
: llarp::service::Endpoint(name, r){};
bool HandleWriteIPPacket(llarp_buffer_t, std::function<huint32_t(void)>) override bool HandleWriteIPPacket(llarp_buffer_t,
std::function< huint32_t(void) >) override
{ {
return true; return true;
} }
huint32_t ObtainIPForAddr(const byte_t*, bool) override huint32_t
ObtainIPForAddr(const byte_t *, bool) override
{ {
return {0}; return {0};
} }
bool HasAddress(const byte_t *) const override bool
HasAddress(const byte_t *) const override
{ {
return false; return false;
} }
}; };
} } // namespace handlers
} } // namespace llarp
#endif #endif

@ -13,7 +13,6 @@ namespace llarp
{ {
namespace handlers namespace handlers
{ {
static const int DefaultTunNetmask = 16; static const int DefaultTunNetmask = 16;
static const char DefaultTunIfname[] = "lokinet0"; static const char DefaultTunIfname[] = "lokinet0";
static const char DefaultTunDstAddr[] = "10.10.0.1"; static const char DefaultTunDstAddr[] = "10.10.0.1";
@ -39,7 +38,7 @@ namespace llarp
bool bool
Start(); Start();
bool bool
IsSNode() const; IsSNode() const;
/// set up tun interface, blocking /// set up tun interface, blocking
@ -53,7 +52,8 @@ namespace llarp
/// overrides Endpoint /// overrides Endpoint
/// handle inbound traffic /// handle inbound traffic
bool bool
HandleWriteIPPacket(llarp_buffer_t buf, std::function<huint32_t(void)> getFromIP) override; HandleWriteIPPacket(llarp_buffer_t buf,
std::function< huint32_t(void) > getFromIP) override;
/// queue outbound packet to the world /// queue outbound packet to the world
bool bool
@ -77,7 +77,7 @@ namespace llarp
#endif #endif
llarp_tun_io tunif; llarp_tun_io tunif;
std::unique_ptr<llarp_fd_promise> Promise; std::unique_ptr< llarp_fd_promise > Promise;
/// called before writing to tun interface /// called before writing to tun interface
static void static void
@ -155,8 +155,10 @@ namespace llarp
AlignedBuffer< 32 >::Hash > AlignedBuffer< 32 >::Hash >
m_AddrToIP; m_AddrToIP;
/// maps key to true if key is a service node, maps key to false if key is a hidden service /// maps key to true if key is a service node, maps key to false if key is
std::unordered_map<AlignedBuffer<32>, bool, AlignedBuffer<32>::Hash> m_SNodes; /// a hidden service
std::unordered_map< AlignedBuffer< 32 >, bool, AlignedBuffer< 32 >::Hash >
m_SNodes;
private: private:
bool bool
@ -177,7 +179,7 @@ namespace llarp
std::promise< bool > m_TunSetupResult; std::promise< bool > m_TunSetupResult;
#endif #endif
std::promise<int> m_VPNPromise; std::promise< int > m_VPNPromise;
/// DNS server per tun /// DNS server per tun
struct dnsd_context dnsd; struct dnsd_context dnsd;

@ -10,13 +10,14 @@ namespace llarp
namespace routing namespace routing
{ {
constexpr size_t ExitPadSize = 512 - 48; constexpr size_t ExitPadSize = 512 - 48;
constexpr size_t MaxExitMTU = 1500; constexpr size_t MaxExitMTU = 1500;
struct TransferTrafficMessage final : public IMessage struct TransferTrafficMessage final : public IMessage
{ {
std::vector<llarp::Encrypted> X; std::vector< llarp::Encrypted > X;
size_t _size = 0; size_t _size = 0;
size_t Size() const size_t
Size() const
{ {
return _size; return _size;
} }

@ -254,9 +254,7 @@ namespace llarp
constexpr uint32_t constexpr uint32_t
__netmask_ipv4_bits(uint32_t numset) __netmask_ipv4_bits(uint32_t numset)
{ {
return (32 - numset) return (32 - numset) ? (1 << numset) | __netmask_ipv4_bits(numset + 1) : 0;
? (1 << numset) | __netmask_ipv4_bits(numset + 1)
: 0;
} }
/// get an ipv4 netmask given some /N range /// get an ipv4 netmask given some /N range

@ -190,8 +190,8 @@ namespace llarp
return *i.first.data_l() ^ *i.second.data_l(); return *i.first.data_l() ^ *i.second.data_l();
} }
}; };
using Mtx_t = llarp::util::Mutex; using Mtx_t = llarp::util::Mutex;
using Lock_t = llarp::util::Lock; using Lock_t = llarp::util::Lock;
using PathMap_t = std::unordered_map< PathInfo_t, Path*, PathInfoHash >; using PathMap_t = std::unordered_map< PathInfo_t, Path*, PathInfoHash >;
mutable Mtx_t m_PathsMutex; mutable Mtx_t m_PathsMutex;
PathMap_t m_Paths; PathMap_t m_Paths;

@ -13,10 +13,10 @@ namespace llarp
private: private:
llarp::PubKey enckey; llarp::PubKey enckey;
llarp::PubKey signkey; llarp::PubKey signkey;
public: public:
VanityNonce vanity; VanityNonce vanity;
ServiceInfo() = default; ServiceInfo() = default;
ServiceInfo(ServiceInfo&& other) ServiceInfo(ServiceInfo&& other)
@ -58,7 +58,8 @@ namespace llarp
} }
bool bool
Update(const byte_t* enc, const byte_t* sign, const byte_t * nonce=nullptr) Update(const byte_t* enc, const byte_t* sign,
const byte_t* nonce = nullptr)
{ {
enckey = enc; enckey = enc;
signkey = sign; signkey = sign;

@ -28,7 +28,7 @@ namespace llarp
getFirstEndpoint(); getFirstEndpoint();
bool bool
FindBestAddressFor(const byte_t* addr, bool isSNode, huint32_t &); FindBestAddressFor(const byte_t *addr, bool isSNode, huint32_t &);
/// DRY refactor /// DRY refactor
llarp::handlers::TunEndpoint * llarp::handlers::TunEndpoint *

@ -128,8 +128,9 @@ namespace llarp
bool bool
HandleDataMessage(const PathID_t&, ProtocolMessage* msg); HandleDataMessage(const PathID_t&, ProtocolMessage* msg);
virtual virtual bool
bool HandleWriteIPPacket(llarp_buffer_t pkt, std::function<huint32_t(void)> getFromIP) = 0; HandleWriteIPPacket(llarp_buffer_t pkt,
std::function< huint32_t(void) > getFromIP) = 0;
bool bool
ProcessDataMessage(ProtocolMessage* msg); ProcessDataMessage(ProtocolMessage* msg);
@ -154,10 +155,11 @@ namespace llarp
HandlePathBuilt(path::Path* path); HandlePathBuilt(path::Path* path);
bool bool
SendToServiceOrQueue(const byte_t* addr, llarp_buffer_t payload, ProtocolType t); SendToServiceOrQueue(const byte_t* addr, llarp_buffer_t payload,
ProtocolType t);
bool bool
SendToSNodeOrQueue(const byte_t * addr, llarp_buffer_t payload); SendToSNodeOrQueue(const byte_t* addr, llarp_buffer_t payload);
struct PendingBuffer struct PendingBuffer
{ {
@ -329,14 +331,15 @@ namespace llarp
EnsurePathToService(const Address& remote, PathEnsureHook h, EnsurePathToService(const Address& remote, PathEnsureHook h,
uint64_t timeoutMS, bool lookupOnRandomPath = false); uint64_t timeoutMS, bool lookupOnRandomPath = false);
using SNodeEnsureHook = std::function<void(RouterID, llarp::exit::BaseSession *)>; using SNodeEnsureHook =
std::function< void(RouterID, llarp::exit::BaseSession*) >;
/// ensure a path to a service node by public key /// ensure a path to a service node by public key
void void
EnsurePathToSNode(const RouterID & remote); EnsurePathToSNode(const RouterID& remote);
bool bool
HasPathToSNode(const RouterID &remote) const; HasPathToSNode(const RouterID& remote) const;
void void
PutSenderFor(const ConvoTag& tag, const ServiceInfo& info); PutSenderFor(const ConvoTag& tag, const ServiceInfo& info);
@ -445,7 +448,10 @@ namespace llarp
Sessions m_DeadSessions; Sessions m_DeadSessions;
using SNodeSessions = std::unordered_multimap<RouterID, std::unique_ptr<llarp::exit::BaseSession>, RouterID::Hash>; using SNodeSessions =
std::unordered_multimap< RouterID,
std::unique_ptr< llarp::exit::BaseSession >,
RouterID::Hash >;
SNodeSessions m_SNodeSessions; SNodeSessions m_SNodeSessions;

@ -140,7 +140,7 @@ extern "C"
/** set me on ios and android to block on a promise for the fd */ /** set me on ios and android to block on a promise for the fd */
int (*obtain_fd)(struct device *); int (*obtain_fd)(struct device *);
/** user data */ /** user data */
void * user; void *user;
t_tun tun_fd; t_tun tun_fd;
int ctrl_sock; int ctrl_sock;
int flags; /* ifr.ifr_flags on Unix */ int flags; /* ifr.ifr_flags on Unix */

@ -326,8 +326,8 @@ interpretLink(struct nlmsghdr *p_hdr, struct ifaddrs **p_resultList)
for(l_rta = IFLA_RTA(l_info); RTA_OK(l_rta, l_rtaSize); for(l_rta = IFLA_RTA(l_info); RTA_OK(l_rta, l_rtaSize);
l_rta = RTA_NEXT(l_rta, l_rtaSize)) l_rta = RTA_NEXT(l_rta, l_rtaSize))
{ {
void *l_rtaData = RTA_DATA(l_rta); void *l_rtaData = RTA_DATA(l_rta);
(void) l_rtaData; (void)l_rtaData;
size_t l_rtaDataSize = RTA_PAYLOAD(l_rta); size_t l_rtaDataSize = RTA_PAYLOAD(l_rta);
switch(l_rta->rta_type) switch(l_rta->rta_type)
{ {
@ -454,8 +454,8 @@ interpretAddr(struct nlmsghdr *p_hdr, struct ifaddrs **p_resultList,
for(l_rta = IFA_RTA(l_info); RTA_OK(l_rta, l_rtaSize); for(l_rta = IFA_RTA(l_info); RTA_OK(l_rta, l_rtaSize);
l_rta = RTA_NEXT(l_rta, l_rtaSize)) l_rta = RTA_NEXT(l_rta, l_rtaSize))
{ {
void *l_rtaData = RTA_DATA(l_rta); void *l_rtaData = RTA_DATA(l_rta);
(void) l_rtaData; (void)l_rtaData;
size_t l_rtaDataSize = RTA_PAYLOAD(l_rta); size_t l_rtaDataSize = RTA_PAYLOAD(l_rta);
switch(l_rta->rta_type) switch(l_rta->rta_type)

@ -182,7 +182,9 @@ llarp_generic_ensure_config(std::ofstream &f, std::string basepath)
f << "# bootstrap settings" << std::endl; f << "# bootstrap settings" << std::endl;
f << "[bootstrap]" << std::endl; f << "[bootstrap]" << std::endl;
f << "# add a bootstrap node's signed identity to the list of nodes we want to bootstrap from" << std::endl; f << "# add a bootstrap node's signed identity to the list of nodes we want "
"to bootstrap from"
<< std::endl;
f << "# if we don't have any peers we connect to this router" << std::endl; f << "# if we don't have any peers we connect to this router" << std::endl;
f << "add-node=" << basepath << "bootstrap.signed" << std::endl; f << "add-node=" << basepath << "bootstrap.signed" << std::endl;
f << "# add another bootstrap node" << std::endl; f << "# add another bootstrap node" << std::endl;
@ -265,9 +267,12 @@ llarp_ensure_client_config(std::ofstream &f, std::string basepath)
f << "# network settings " << std::endl; f << "# network settings " << std::endl;
f << "[network]" << std::endl; f << "[network]" << std::endl;
f << "profiles=" << basepath << "profiles.dat" << std::endl; f << "profiles=" << basepath << "profiles.dat" << std::endl;
f << "# uncomment next line to add router with pubkey to list of routers we connect directly to" << std::endl; f << "# uncomment next line to add router with pubkey to list of routers we "
"connect directly to"
<< std::endl;
f << "#strict-connect=pubkey" << std::endl; f << "#strict-connect=pubkey" << std::endl;
f << "# uncomment next line to use router with pubkey as an exit node" << std::endl; f << "# uncomment next line to use router with pubkey as an exit node"
<< std::endl;
f << "#exit-node=pubkey" << std::endl; f << "#exit-node=pubkey" << std::endl;
// pick ip // pick ip
std::string ip = llarp::findFreePrivateRange(); std::string ip = llarp::findFreePrivateRange();
@ -355,9 +360,9 @@ extern "C"
{ {
iter->conf = conf; iter->conf = conf;
std::map< std::string, llarp::Config::section_t & > sections = { std::map< std::string, llarp::Config::section_t & > sections = {
{"network", conf->impl.network}, {"connect", conf->impl.connect}, {"network", conf->impl.network}, {"connect", conf->impl.connect},
{"bootstrap", conf->impl.bootstrap}, {"system", conf->impl.system}, {"bootstrap", conf->impl.bootstrap}, {"system", conf->impl.system},
{"netdb", conf->impl.netdb}, {"api", conf->impl.api}, {"netdb", conf->impl.netdb}, {"api", conf->impl.api},
{"services", conf->impl.services}}; {"services", conf->impl.services}};
for(const auto item : conf->impl.router) for(const auto item : conf->impl.router)

@ -162,20 +162,15 @@ namespace llarp
int int
Context::Run() Context::Run()
{ {
// just check to make sure it's not already set up (either this or we add a if(router == nullptr)
// bool and/or add another function)
if(!this->router)
{ {
// set up all requirements // we are not set up so we should die
if(this->Setup()) llarp::LogError("cannot run non configured context");
{ return 1;
llarp::LogError("Failed to setup router");
return 1;
}
} }
// run // run
if(!llarp_run_router(router, nodedb)) if(!llarp_run_router(router, nodedb))
return 1; // success return 1;
// run net io thread // run net io thread
llarp::LogInfo("running mainloop"); llarp::LogInfo("running mainloop");
llarp_ev_loop_run_single_process(mainloop, worker, logic); llarp_ev_loop_run_single_process(mainloop, worker, logic);
@ -208,6 +203,14 @@ namespace llarp
void void
Context::Close() Context::Close()
{ {
llarp::LogDebug("stopping logic");
if(logic)
llarp_logic_stop(logic);
llarp::LogDebug("stopping event loop");
if(mainloop)
llarp_ev_loop_stop(mainloop);
llarp::LogDebug("stop router"); llarp::LogDebug("stop router");
if(router) if(router)
llarp_stop_router(router); llarp_stop_router(router);
@ -220,11 +223,6 @@ namespace llarp
if(worker) if(worker)
llarp_threadpool_join(worker); llarp_threadpool_join(worker);
llarp::LogDebug("stop logic");
if(logic)
llarp_logic_stop(logic);
llarp::LogDebug("free config"); llarp::LogDebug("free config");
llarp_free_config(&config); llarp_free_config(&config);
@ -242,14 +240,6 @@ namespace llarp
llarp::LogDebug("free logic"); llarp::LogDebug("free logic");
llarp_free_logic(&logic); llarp_free_logic(&logic);
for(auto &t : netio_threads)
{
llarp::LogDebug("join netio thread");
t.join();
}
netio_threads.clear();
} }
bool bool
@ -296,10 +286,11 @@ extern "C"
ptr->ctx->HandleSignal(sig); ptr->ctx->HandleSignal(sig);
} }
void void
llarp_main_inject_vpn_fd(struct llarp_main * ptr, int fd) llarp_main_inject_vpn_fd(struct llarp_main *ptr, int fd)
{ {
llarp::handlers::TunEndpoint * tun = ptr->ctx->router->hiddenServiceContext.getFirstTun(); llarp::handlers::TunEndpoint *tun =
ptr->ctx->router->hiddenServiceContext.getFirstTun();
if(!tun) if(!tun)
return; return;
if(!tun->Promise) if(!tun->Promise)

@ -78,7 +78,10 @@ namespace llarp
for(const auto &pk : valuesFound) for(const auto &pk : valuesFound)
{ {
// lookup router // lookup router
parent->LookupRouter(pk, std::bind(&llarp_router::HandleDHTLookupForExplore, parent->router, pk, std::placeholders::_1)); parent->LookupRouter(
pk,
std::bind(&llarp_router::HandleDHTLookupForExplore,
parent->router, pk, std::placeholders::_1));
} }
} }
}; };

@ -238,7 +238,7 @@ packet2bytes(dns_packet &in)
int fields = (in.header.qr << 15); // QR => message type, 1 = response int fields = (in.header.qr << 15); // QR => message type, 1 = response
fields += (in.header.opcode << 14); // I think opcode is always 0 fields += (in.header.opcode << 14); // I think opcode is always 0
fields += in.header.rcode; // response code (3 => not found, 0 = Ok) fields += in.header.rcode; // response code (3 => not found, 0 = Ok)
vput16bits(write_buffer, fields); vput16bits(write_buffer, fields);
// don't pull these from the header, trust what we actually have more // don't pull these from the header, trust what we actually have more
@ -308,14 +308,14 @@ extern "C"
} }
bool bool
decode_hdr(llarp_buffer_t * buffer, dns_msg_header * hdr) decode_hdr(llarp_buffer_t *buffer, dns_msg_header *hdr)
{ {
uint16_t fields; uint16_t fields;
// reads as HOST byte order // reads as HOST byte order
if(!llarp_buffer_read_uint16(buffer, &hdr->id)) if(!llarp_buffer_read_uint16(buffer, &hdr->id))
return false; return false;
if(!llarp_buffer_read_uint16(buffer, &fields)) if(!llarp_buffer_read_uint16(buffer, &fields))
return false; return false;
if(!llarp_buffer_read_uint16(buffer, &hdr->qdCount)) if(!llarp_buffer_read_uint16(buffer, &hdr->qdCount))
return false; return false;

@ -31,27 +31,30 @@ struct check_query_simple_request
std::unordered_map< std::string, struct dnsd_query_hook_response * > std::unordered_map< std::string, struct dnsd_query_hook_response * >
loki_tld_lookup_cache; loki_tld_lookup_cache;
static bool decode_request_name(const std::string & name, llarp::AlignedBuffer<32> & addr, bool &isSNode) static bool
decode_request_name(const std::string &name, llarp::AlignedBuffer< 32 > &addr,
bool &isSNode)
{ {
llarp::service::Address serviceAddr; llarp::service::Address serviceAddr;
llarp::RouterID snodeAddr; llarp::RouterID snodeAddr;
auto pos = name.find(".snode"); auto pos = name.find(".snode");
if(pos != std::string::npos) if(pos != std::string::npos)
{ {
if(!llarp::HexDecode(name.substr(0, pos).c_str(), serviceAddr.data(), serviceAddr.size())) if(!llarp::HexDecode(name.substr(0, pos).c_str(), serviceAddr.data(),
serviceAddr.size()))
{ {
return false; return false;
} }
addr = snodeAddr.data(); addr = snodeAddr.data();
isSNode = true; isSNode = true;
} }
else else
{ {
if(!serviceAddr.FromString(name)) if(!serviceAddr.FromString(name))
{ {
return false; return false;
} }
addr = serviceAddr.data(); addr = serviceAddr.data();
isSNode = false; isSNode = false;
} }
return true; return true;
@ -80,7 +83,7 @@ llarp_dotlokilookup_checkQuery(void *u, __attribute__((unused)) uint64_t orig,
// if so send that // if so send that
// else // else
// if we have a free private ip, send that // if we have a free private ip, send that
/* /*
// cache hit // cache hit
auto itr = loki_tld_lookup_cache.find(addr.ToString()); auto itr = loki_tld_lookup_cache.find(addr.ToString());
@ -109,7 +112,7 @@ llarp_dotlokilookup_checkQuery(void *u, __attribute__((unused)) uint64_t orig,
return; return;
} }
llarp::huint32_t serviceIP; llarp::huint32_t serviceIP;
llarp::AlignedBuffer<32> addr; llarp::AlignedBuffer< 32 > addr;
bool isSNode = false; bool isSNode = false;
if(!decode_request_name(qr->request->question.name, addr, isSNode)) if(!decode_request_name(qr->request->question.name, addr, isSNode))
{ {
@ -125,7 +128,6 @@ llarp_dotlokilookup_checkQuery(void *u, __attribute__((unused)) uint64_t orig,
delete qr; delete qr;
return; return;
} }
/* /*
bool mapResult = routerHiddenServiceContext->MapAddressAll( bool mapResult = routerHiddenServiceContext->MapAddressAll(
@ -260,7 +262,7 @@ ReverseHandlerIter(struct llarp::service::Context::endpoint_iter *endpointCfg)
llarp::iprange_ipv4(std::stoi(tokensCheck[0]), std::stoi(tokensCheck[1]), llarp::iprange_ipv4(std::stoi(tokensCheck[0]), std::stoi(tokensCheck[1]),
std::stoi(tokensCheck[2]), std::stoi(tokensCheck[3]), std::stoi(tokensCheck[2]), std::stoi(tokensCheck[3]),
tunEndpoint->tunif.netmask); // create range tunEndpoint->tunif.netmask); // create range
llarp::huint32_t searchIPv4 = llarp::ipaddr_ipv4_bits( llarp::huint32_t searchIPv4 = llarp::ipaddr_ipv4_bits(
std::stoi(tokensSearch[searchTokens - 3]), std::stoi(tokensSearch[searchTokens - 3]),
std::stoi(tokensSearch[searchTokens - 4]), std::stoi(tokensSearch[searchTokens - 4]),
@ -273,26 +275,25 @@ ReverseHandlerIter(struct llarp::service::Context::endpoint_iter *endpointCfg)
llarp::Addr searchAddr(searchIp); llarp::Addr searchAddr(searchIp);
llarp::Addr checkAddr(checkIp); llarp::Addr checkAddr(checkIp);
llarp::LogInfo(searchIPv4, " vs ", range, " = ", llarp::LogInfo(searchIPv4, " vs ", range, " = ",
inRange ? "inRange" : "not match"); inRange ? "inRange" : "not match");
if(inRange) if(inRange)
{ {
llarp::AlignedBuffer<32> addr = llarp::AlignedBuffer< 32 > addr =
tunEndpoint->ObtainAddrForIP< llarp::AlignedBuffer<32> >( tunEndpoint->ObtainAddrForIP< llarp::AlignedBuffer< 32 > >(searchIPv4,
searchIPv4, false); false);
if(addr.IsZero()) if(addr.IsZero())
{ {
addr = addr = tunEndpoint->ObtainAddrForIP< llarp::AlignedBuffer< 32 > >(
tunEndpoint->ObtainAddrForIP< llarp::AlignedBuffer<32> >( searchIPv4, true);
searchIPv4, true);
if(!addr.IsZero()) if(!addr.IsZero())
{ {
char stack[128] = {0}; char stack[128] = {0};
std::string saddr = llarp::HexEncode(addr, stack); std::string saddr = llarp::HexEncode(addr, stack);
saddr += ".snode"; saddr += ".snode";
writesend_dnss_revresponse(saddr, context->request); writesend_dnss_revresponse(saddr, context->request);
} }
else else
write404_dnss_response(context->request); write404_dnss_response(context->request);
} }
else else
@ -306,11 +307,13 @@ ReverseHandlerIter(struct llarp::service::Context::endpoint_iter *endpointCfg)
return true; // we don't do anything with the result yet return true; // we don't do anything with the result yet
} }
static bool should_intercept_query_with_name(const std::string & lName) static bool
should_intercept_query_with_name(const std::string &lName)
{ {
// null terminated list // null terminated list
static const char * const matches[] = { ".loki", ".snode", ".loki.", ".snode.", 0}; static const char *const matches[] = {".loki", ".snode", ".loki.", ".snode.",
size_t idx = 0; 0};
size_t idx = 0;
while(matches[idx]) while(matches[idx])
{ {
std::string match_str(matches[idx]); std::string match_str(matches[idx]);
@ -323,7 +326,7 @@ static bool should_intercept_query_with_name(const std::string & lName)
dnsd_query_hook_response * dnsd_query_hook_response *
llarp_dotlokilookup_handler(std::string name, llarp_dotlokilookup_handler(std::string name,
const dnsd_question_request * request) const dnsd_question_request *request)
{ {
dnsd_query_hook_response *response = new dnsd_query_hook_response; dnsd_query_hook_response *response = new dnsd_query_hook_response;
response->dontLookUp = false; response->dontLookUp = false;
@ -362,7 +365,7 @@ llarp_dotlokilookup_handler(std::string name,
if(!res) if(!res)
{ {
llarp::LogDebug("Reverse is ours"); llarp::LogDebug("Reverse is ours");
response->dontLookUp = true; response->dontLookUp = true;
response->dontSendResponse = true; // should have already sent it response->dontSendResponse = true; // should have already sent it
} }
else else
@ -384,11 +387,11 @@ llarp_dotlokilookup_handler(std::string name,
} }
// decode address // decode address
llarp::AlignedBuffer<32> addr; llarp::AlignedBuffer< 32 > addr;
bool isSNode = false; bool isSNode = false;
if(!decode_request_name(lName, addr, isSNode)) if(!decode_request_name(lName, addr, isSNode))
{ {
response->dontLookUp = true; response->dontLookUp = true;
return response; return response;
} }

@ -647,8 +647,8 @@ raw_resolve_host(struct dnsc_context *const dnsc, const char *url,
if(request) if(request)
{ {
request->packet.header = hdr; request->packet.header = hdr;
generic_handle_dnsc_recvfrom(tracker->client_request[hdr.id].get(), generic_handle_dnsc_recvfrom(tracker->client_request[hdr.id].get(), lbuffer,
lbuffer, &hdr); &hdr);
} }
else else
{ {
@ -672,7 +672,7 @@ llarp_handle_dnsc_recvfrom(struct llarp_udp_io *const udp,
llarp::LogError("failed to decode dns header"); llarp::LogError("failed to decode dns header");
return; return;
} }
buf.cur = buf.base; // reset cursor to beginning buf.cur = buf.base; // reset cursor to beginning
llarp::LogDebug("Header got client responses for id: ", hdr.id); llarp::LogDebug("Header got client responses for id: ", hdr.id);

@ -48,7 +48,7 @@ write404_dnss_response(const dnsd_question_request *request)
// build header // build header
put16bits(write_buffer, request->hdr.id); put16bits(write_buffer, request->hdr.id);
// not found flag set // not found flag set
put16bits(write_buffer, (1 << 15) | request->hdr.fields() | 3); put16bits(write_buffer, (1 << 15) | request->hdr.fields() | 3);
put16bits(write_buffer, 1); // QD (number of questions) put16bits(write_buffer, 1); // QD (number of questions)
put16bits(write_buffer, 0); // AN (number of answers) put16bits(write_buffer, 0); // AN (number of answers)
@ -63,11 +63,13 @@ write404_dnss_response(const dnsd_question_request *request)
uint32_t out_bytes = write_buffer - bufferBegin; uint32_t out_bytes = write_buffer - bufferBegin;
llarp::LogDebug("Sending 404, ", out_bytes, " bytes"); llarp::LogDebug("Sending 404, ", out_bytes, " bytes");
// struct llarp_udp_io *udp = (struct llarp_udp_io *)request->user; // struct llarp_udp_io *udp = (struct llarp_udp_io *)request->user;
request->sendto_hook(request->user, request->from, llarp::InitBuffer(buf, out_bytes)); request->sendto_hook(request->user, request->from,
llarp::InitBuffer(buf, out_bytes));
} }
void void
writecname_dnss_response(std::string cname, const dnsd_question_request *request) writecname_dnss_response(std::string cname,
const dnsd_question_request *request)
{ {
char buf[BUFFER_SIZE] = {0}; char buf[BUFFER_SIZE] = {0};
@ -127,11 +129,13 @@ writecname_dnss_response(std::string cname, const dnsd_question_request *request
uint32_t out_bytes = write_buffer - bufferBegin; uint32_t out_bytes = write_buffer - bufferBegin;
llarp::LogDebug("Sending cname, ", out_bytes, " bytes"); llarp::LogDebug("Sending cname, ", out_bytes, " bytes");
// struct llarp_udp_io *udp = (struct llarp_udp_io *)request->user; // struct llarp_udp_io *udp = (struct llarp_udp_io *)request->user;
request->sendto_hook(request->user, request->from, llarp::InitBuffer(buf, out_bytes)); request->sendto_hook(request->user, request->from,
llarp::InitBuffer(buf, out_bytes));
} }
void void
writesend_dnss_revresponse(std::string reverse, const dnsd_question_request *request) writesend_dnss_revresponse(std::string reverse,
const dnsd_question_request *request)
{ {
char buf[BUFFER_SIZE] = {0}; char buf[BUFFER_SIZE] = {0};
@ -140,7 +144,7 @@ writesend_dnss_revresponse(std::string reverse, const dnsd_question_request *req
// build header // build header
put16bits(write_buffer, request->hdr.id); put16bits(write_buffer, request->hdr.id);
// response // response
put16bits(write_buffer,request->hdr.fields() | (1 << 15) | (1 << 10)); put16bits(write_buffer, request->hdr.fields() | (1 << 15) | (1 << 10));
put16bits(write_buffer, 1); // QD (number of questions) put16bits(write_buffer, 1); // QD (number of questions)
put16bits(write_buffer, 1); // AN (number of answers) put16bits(write_buffer, 1); // AN (number of answers)
@ -156,14 +160,15 @@ writesend_dnss_revresponse(std::string reverse, const dnsd_question_request *req
code_domain(write_buffer, request->question.name); // com, type=6, ttl=0 code_domain(write_buffer, request->question.name); // com, type=6, ttl=0
put16bits(write_buffer, request->question.type); put16bits(write_buffer, request->question.type);
put16bits(write_buffer, request->question.qClass); put16bits(write_buffer, request->question.qClass);
put32bits(write_buffer, 1); // ttl put32bits(write_buffer, 1); // ttl
put16bits(write_buffer, reverse.size() + 2); // rdLength put16bits(write_buffer, reverse.size() + 2); // rdLength
code_domain(write_buffer, reverse); code_domain(write_buffer, reverse);
uint32_t out_bytes = write_buffer - bufferBegin; uint32_t out_bytes = write_buffer - bufferBegin;
llarp::LogDebug("Sending reverse: ", reverse, " ", out_bytes, " bytes"); llarp::LogDebug("Sending reverse: ", reverse, " ", out_bytes, " bytes");
// struct llarp_udp_io *udp = (struct llarp_udp_io *)request->user; // struct llarp_udp_io *udp = (struct llarp_udp_io *)request->user;
request->sendto_hook(request->user, request->from, llarp::InitBuffer(buf, out_bytes)); request->sendto_hook(request->user, request->from,
llarp::InitBuffer(buf, out_bytes));
} }
// FIXME: we need an DNS answer not a sockaddr // FIXME: we need an DNS answer not a sockaddr
@ -228,7 +233,8 @@ writesend_dnss_response(llarp::huint32_t *hostRes,
uint32_t out_bytes = write_buffer - bufferBegin; uint32_t out_bytes = write_buffer - bufferBegin;
llarp::LogDebug("Sending found, ", out_bytes, " bytes"); llarp::LogDebug("Sending found, ", out_bytes, " bytes");
// struct llarp_udp_io *udp = (struct llarp_udp_io *)request->user; // struct llarp_udp_io *udp = (struct llarp_udp_io *)request->user;
request->sendto_hook(request->user, request->from, llarp::InitBuffer(buf, out_bytes)); request->sendto_hook(request->user, request->from,
llarp::InitBuffer(buf, out_bytes));
} }
void void
@ -323,7 +329,7 @@ handle_dnsc_result(dnsc_answer_request *client_request)
} }
client_request->packet.header.id = server_request->hdr.id; // stomp ID client_request->packet.header.id = server_request->hdr.id; // stomp ID
std::vector< byte_t > test = packet2bytes(client_request->packet); std::vector< byte_t > test = packet2bytes(client_request->packet);
// llarp::LogInfo("packet2bytes figures we should send ", test.size(), " // llarp::LogInfo("packet2bytes figures we should send ", test.size(), "
// bytes"); // bytes");
@ -371,7 +377,7 @@ handle_dnsc_result(dnsc_answer_request *client_request)
// our generic version // our generic version
void void
handle_recvfrom(llarp_buffer_t * buffer, dnsd_question_request *request) handle_recvfrom(llarp_buffer_t *buffer, dnsd_question_request *request)
{ {
const size_t HDR_OFFSET = 12; const size_t HDR_OFFSET = 12;
const char *p_buffer = (const char *)buffer->base; const char *p_buffer = (const char *)buffer->base;
@ -379,7 +385,6 @@ handle_recvfrom(llarp_buffer_t * buffer, dnsd_question_request *request)
int rcode = (buffer->base[3] & 0x0F); int rcode = (buffer->base[3] & 0x0F);
llarp::LogDebug("dnsd rcode ", rcode); llarp::LogDebug("dnsd rcode ", rcode);
if(!decode_hdr(buffer, &request->hdr)) if(!decode_hdr(buffer, &request->hdr))
{ {
llarp::LogError("failed to decode dns header"); llarp::LogError("failed to decode dns header");

@ -10,7 +10,7 @@ namespace llarp
UpdateBuffer(); UpdateBuffer();
} }
Encrypted::Encrypted(Encrypted && other) Encrypted::Encrypted(Encrypted&& other)
{ {
_data = std::move(other._data); _data = std::move(other._data);
UpdateBuffer(); UpdateBuffer();

@ -20,7 +20,6 @@
#error No async event loop for your platform, subclass llarp_ev_loop #error No async event loop for your platform, subclass llarp_ev_loop
#endif #endif
void void
llarp_ev_loop_alloc(struct llarp_ev_loop **ev) llarp_ev_loop_alloc(struct llarp_ev_loop **ev)
{ {
@ -58,7 +57,8 @@ llarp_ev_loop_run(struct llarp_ev_loop *ev, struct llarp_logic *logic)
return 0; return 0;
} }
int llarp_fd_promise_wait_for_value(struct llarp_fd_promise * p) int
llarp_fd_promise_wait_for_value(struct llarp_fd_promise *p)
{ {
return p->Get(); return p->Get();
} }

@ -612,15 +612,19 @@ namespace llarp
struct llarp_fd_promise struct llarp_fd_promise
{ {
llarp_fd_promise(std::promise<int> * p) : _impl(p) {} llarp_fd_promise(std::promise< int >* p) : _impl(p)
std::promise<int> * _impl; {
}
void Set(int fd) std::promise< int >* _impl;
void
Set(int fd)
{ {
_impl->set_value(fd); _impl->set_value(fd);
} }
int Get() int
Get()
{ {
auto future = _impl->get_future(); auto future = _impl->get_future();
future.wait(); future.wait();

@ -138,7 +138,7 @@ namespace llarp
{ {
llarp_buffer_t b; llarp_buffer_t b;
b.base = buf; b.base = buf;
b.cur = b.base; b.cur = b.base;
sockaddr_in6 src; sockaddr_in6 src;
socklen_t slen = sizeof(sockaddr_in6); socklen_t slen = sizeof(sockaddr_in6);
sockaddr* addr = (sockaddr*)&src; sockaddr* addr = (sockaddr*)&src;
@ -217,7 +217,7 @@ namespace llarp
} }
int int
read(byte_t * buf, size_t sz) read(byte_t* buf, size_t sz)
{ {
ssize_t ret = tuntap_read(tunif, buf, sz); ssize_t ret = tuntap_read(tunif, buf, sz);
if(ret > 0 && t->recvpkt) if(ret > 0 && t->recvpkt)
@ -228,12 +228,13 @@ namespace llarp
return ret; return ret;
} }
static int wait_for_fd_promise(struct device * dev) static int
wait_for_fd_promise(struct device* dev)
{ {
llarp::tun *t = static_cast<llarp::tun *>(dev->user); llarp::tun* t = static_cast< llarp::tun* >(dev->user);
if(t->t->get_fd_promise) if(t->t->get_fd_promise)
{ {
struct llarp_fd_promise * promise = t->t->get_fd_promise(t->t); struct llarp_fd_promise* promise = t->t->get_fd_promise(t->t);
if(promise) if(promise)
return llarp_fd_promise_wait_for_value(promise); return llarp_fd_promise_wait_for_value(promise);
} }
@ -247,7 +248,7 @@ namespace llarp
if(t->get_fd_promise) if(t->get_fd_promise)
{ {
tunif->obtain_fd = &wait_for_fd_promise; tunif->obtain_fd = &wait_for_fd_promise;
tunif->user = this; tunif->user = this;
} }
llarp::LogDebug("set ifname to ", t->ifname); llarp::LogDebug("set ifname to ", t->ifname);
strncpy(tunif->if_name, t->ifname, sizeof(tunif->if_name)); strncpy(tunif->if_name, t->ifname, sizeof(tunif->if_name));
@ -513,8 +514,8 @@ struct llarp_epoll_loop : public llarp_ev_loop
llarp::tun* t = new llarp::tun(tun, this); llarp::tun* t = new llarp::tun(tun, this);
if(tun->get_fd_promise) if(tun->get_fd_promise)
{ {
}
} else if(t->setup()) else if(t->setup())
{ {
return t; return t;
} }
@ -577,6 +578,14 @@ struct llarp_epoll_loop : public llarp_ev_loop
void void
stop() stop()
{ {
// close all handlers before closing the epoll fd
auto itr = handlers.begin();
while(itr != handler.end())
{
close_ev(itr->get());
itr = handlers.erase(itr);
}
if(epollfd != -1) if(epollfd != -1)
close(epollfd); close(epollfd);
epollfd = -1; epollfd = -1;

@ -67,11 +67,12 @@ namespace llarp
return true; return true;
} }
bool Endpoint::LooksDead(llarp_time_t now, llarp_time_t timeout) const bool
Endpoint::LooksDead(llarp_time_t now, llarp_time_t timeout) const
{ {
if(ExpiresSoon(now, timeout)) if(ExpiresSoon(now, timeout))
return true; return true;
if (now > m_LastActive) if(now > m_LastActive)
return now - m_LastActive > timeout; return now - m_LastActive > timeout;
return true; return true;
} }
@ -82,11 +83,11 @@ namespace llarp
// queue overflow // queue overflow
if(m_UpstreamQueue.size() > MaxUpstreamQueueSize) if(m_UpstreamQueue.size() > MaxUpstreamQueueSize)
return false; return false;
llarp::net::IPv4Packet pkt; llarp::net::IPv4Packet pkt;
if(!pkt.Load(buf)) if(!pkt.Load(buf))
return false; return false;
huint32_t dst; huint32_t dst;
if(m_RewriteSource) if(m_RewriteSource)
dst = m_Parent->GetIfAddr(); dst = m_Parent->GetIfAddr();
@ -103,8 +104,8 @@ namespace llarp
Endpoint::QueueInboundTraffic(llarp_buffer_t buf) Endpoint::QueueInboundTraffic(llarp_buffer_t buf)
{ {
llarp::net::IPv4Packet pkt; llarp::net::IPv4Packet pkt;
if(!pkt.Load(buf)) if(!pkt.Load(buf))
return false; return false;
huint32_t src; huint32_t src;
if(m_RewriteSource) if(m_RewriteSource)
@ -112,15 +113,15 @@ namespace llarp
else else
src = pkt.src(); src = pkt.src();
pkt.UpdateIPv4PacketOnDst(src, m_IP); pkt.UpdateIPv4PacketOnDst(src, m_IP);
auto pktbuf = pkt.Buffer(); auto pktbuf = pkt.Buffer();
uint8_t queue_idx = pktbuf.sz / llarp::routing::ExitPadSize; uint8_t queue_idx = pktbuf.sz / llarp::routing::ExitPadSize;
auto & queue = m_DownstreamQueues[queue_idx]; auto& queue = m_DownstreamQueues[queue_idx];
if(queue.size() == 0) if(queue.size() == 0)
{ {
queue.emplace_back(); queue.emplace_back();
return queue.back().PutBuffer(buf, m_Counter++); return queue.back().PutBuffer(buf, m_Counter++);
} }
auto & msg = queue.back(); auto& msg = queue.back();
if(msg.Size() + pktbuf.sz > llarp::routing::ExitPadSize) if(msg.Size() + pktbuf.sz > llarp::routing::ExitPadSize)
{ {
queue.emplace_back(); queue.emplace_back();
@ -130,7 +131,7 @@ namespace llarp
return msg.PutBuffer(pktbuf, m_Counter++); return msg.PutBuffer(pktbuf, m_Counter++);
} }
bool bool
Endpoint::Flush() Endpoint::Flush()
{ {
// flush upstream queue // flush upstream queue
@ -144,13 +145,13 @@ namespace llarp
bool sent = path != nullptr; bool sent = path != nullptr;
if(path) if(path)
{ {
for(auto & item : m_DownstreamQueues) for(auto& item : m_DownstreamQueues)
{ {
auto & queue = item.second; auto& queue = item.second;
while(queue.size()) while(queue.size())
{ {
auto & msg = queue.front(); auto& msg = queue.front();
msg.S = path->NextSeqNo(); msg.S = path->NextSeqNo();
if(path->SendRoutingMessage(&msg, m_Parent->Router())) if(path->SendRoutingMessage(&msg, m_Parent->Router()))
{ {
m_RxRate += msg.Size(); m_RxRate += msg.Size();
@ -160,7 +161,7 @@ namespace llarp
} }
} }
} }
for(auto & item : m_DownstreamQueues) for(auto& item : m_DownstreamQueues)
item.second.clear(); item.second.clear();
return sent; return sent;
} }

@ -99,10 +99,11 @@ namespace llarp
} }
bool bool
BaseSession::QueueUpstreamTraffic(llarp::net::IPv4Packet pkt, const size_t N) BaseSession::QueueUpstreamTraffic(llarp::net::IPv4Packet pkt,
const size_t N)
{ {
auto buf = pkt.Buffer(); auto buf = pkt.Buffer();
auto & queue = m_Upstream[buf.sz / N]; auto& queue = m_Upstream[buf.sz / N];
// queue overflow // queue overflow
if(queue.size() >= MaxUpstreamQueueLength) if(queue.size() >= MaxUpstreamQueueLength)
return false; return false;
@ -111,41 +112,41 @@ namespace llarp
queue.emplace_back(); queue.emplace_back();
return queue.back().PutBuffer(buf, m_Counter++); return queue.back().PutBuffer(buf, m_Counter++);
} }
auto & back = queue.back(); auto& back = queue.back();
// pack to nearest N // pack to nearest N
if(back.Size() + buf.sz > N) if(back.Size() + buf.sz > N)
{ {
queue.emplace_back(); queue.emplace_back();
return queue.back().PutBuffer(buf, m_Counter++); return queue.back().PutBuffer(buf, m_Counter++);
} }
else else
return back.PutBuffer(buf, m_Counter++); return back.PutBuffer(buf, m_Counter++);
} }
bool bool
BaseSession::IsReady() const BaseSession::IsReady() const
{ {
return AvailablePaths(llarp::path::ePathRoleExit) > 0; return AvailablePaths(llarp::path::ePathRoleExit) > 0;
} }
bool bool
BaseSession::FlushUpstreamTraffic() BaseSession::FlushUpstreamTraffic()
{ {
auto path = PickRandomEstablishedPath(llarp::path::ePathRoleExit); auto path = PickRandomEstablishedPath(llarp::path::ePathRoleExit);
if(!path) if(!path)
{ {
// discard // discard
for(auto & item : m_Upstream) for(auto& item : m_Upstream)
item.second.clear(); item.second.clear();
return false; return false;
} }
for (auto & item : m_Upstream) for(auto& item : m_Upstream)
{ {
auto & queue = item.second; auto& queue = item.second;
while(queue.size()) while(queue.size())
{ {
auto & msg = queue.front(); auto& msg = queue.front();
msg.S = path->NextSeqNo(); msg.S = path->NextSeqNo();
path->SendRoutingMessage(&msg, router); path->SendRoutingMessage(&msg, router);
queue.pop_front(); queue.pop_front();
} }

@ -21,7 +21,7 @@ namespace llarp
if(buf.sz > MaxExitMTU) if(buf.sz > MaxExitMTU)
return false; return false;
X.emplace_back(buf.sz + 8); X.emplace_back(buf.sz + 8);
byte_t * ptr = X.back().data(); byte_t* ptr = X.back().data();
htobe64buf(ptr, counter); htobe64buf(ptr, counter);
ptr += 8; ptr += 8;
memcpy(ptr, buf.base, buf.sz); memcpy(ptr, buf.base, buf.sz);

@ -36,7 +36,7 @@ namespace llarp
{ {
} }
llarp_time_t llarp_time_t
ExitEndpoint::Now() const ExitEndpoint::Now() const
{ {
return m_Router->Now(); return m_Router->Now();
@ -73,17 +73,19 @@ namespace llarp
} }
++itr; ++itr;
} }
if(ep == nullptr) if(ep == nullptr)
{ {
// we may have all dead sessions, wtf now? // we may have all dead sessions, wtf now?
llarp::LogWarn(Name(), " dropped inbound traffic for session ", pk, " as we have no working endpoints"); llarp::LogWarn(Name(), " dropped inbound traffic for session ", pk,
" as we have no working endpoints");
} }
else else
{ {
if(!ep->QueueInboundTraffic(pkt.Buffer())) if(!ep->QueueInboundTraffic(pkt.Buffer()))
{ {
llarp::LogWarn(Name(), " dropped inbound traffic for session ", pk, " as we are overloaded (probably)"); llarp::LogWarn(Name(), " dropped inbound traffic for session ", pk,
" as we are overloaded (probably)");
} }
} }
}); });

@ -14,10 +14,10 @@ namespace llarp
{ {
namespace handlers namespace handlers
{ {
static llarp_fd_promise *
static llarp_fd_promise * get_tun_fd_promise(llarp_tun_io * tun) get_tun_fd_promise(llarp_tun_io *tun)
{ {
return static_cast<TunEndpoint *>(tun->user)->Promise.get(); return static_cast< TunEndpoint * >(tun->user)->Promise.get();
} }
TunEndpoint::TunEndpoint(const std::string &nickname, llarp_router *r) TunEndpoint::TunEndpoint(const std::string &nickname, llarp_router *r)
@ -25,10 +25,10 @@ namespace llarp
, m_UserToNetworkPktQueue(nickname + "_sendq", r->netloop, r->netloop) , m_UserToNetworkPktQueue(nickname + "_sendq", r->netloop, r->netloop)
, m_NetworkToUserPktQueue(nickname + "_recvq", r->netloop, r->netloop) , m_NetworkToUserPktQueue(nickname + "_recvq", r->netloop, r->netloop)
{ {
#ifdef ANDROID #ifdef ANDROID
tunif.get_fd_promise = &get_tun_fd_promise; tunif.get_fd_promise = &get_tun_fd_promise;
Promise.reset(new llarp_fd_promise(&m_VPNPromise)); Promise.reset(new llarp_fd_promise(&m_VPNPromise));
#else #else
tunif.get_fd_promise = nullptr; tunif.get_fd_promise = nullptr;
#endif #endif
tunif.user = this; tunif.user = this;
@ -180,7 +180,8 @@ namespace llarp
} }
bool bool
TunEndpoint::MapAddress(const service::Address &addr, huint32_t ip, bool SNode) TunEndpoint::MapAddress(const service::Address &addr, huint32_t ip,
bool SNode)
{ {
auto itr = m_IPToAddr.find(ip); auto itr = m_IPToAddr.find(ip);
if(itr != m_IPToAddr.end()) if(itr != m_IPToAddr.end())
@ -192,9 +193,9 @@ namespace llarp
} }
llarp::LogInfo(Name() + " map ", addr.ToString(), " to ", ip); llarp::LogInfo(Name() + " map ", addr.ToString(), " to ", ip);
m_IPToAddr[ip] = addr.data(); m_IPToAddr[ip] = addr.data();
m_AddrToIP[addr.data()] = ip; m_AddrToIP[addr.data()] = ip;
m_SNodes[addr.data()] = SNode; m_SNodes[addr.data()] = SNode;
MarkIPActiveForever(ip); MarkIPActiveForever(ip);
return true; return true;
} }
@ -242,7 +243,8 @@ namespace llarp
#endif #endif
} }
bool TunEndpoint::IsSNode() const bool
TunEndpoint::IsSNode() const
{ {
// TODO : implement me // TODO : implement me
return false; return false;
@ -365,30 +367,34 @@ namespace llarp
TunEndpoint::FlushSend() TunEndpoint::FlushSend()
{ {
m_UserToNetworkPktQueue.Process([&](net::IPv4Packet &pkt) { m_UserToNetworkPktQueue.Process([&](net::IPv4Packet &pkt) {
std::function<bool(llarp_buffer_t)> sendFunc; std::function< bool(llarp_buffer_t) > sendFunc;
auto itr = m_IPToAddr.find(pkt.dst()); auto itr = m_IPToAddr.find(pkt.dst());
if(itr == m_IPToAddr.end()) if(itr == m_IPToAddr.end())
{ {
if(m_Exit) if(m_Exit)
{ {
pkt.UpdateIPv4PacketOnDst({0}, pkt.dst()); pkt.UpdateIPv4PacketOnDst({0}, pkt.dst());
m_Exit->QueueUpstreamTraffic(std::move(pkt), llarp::routing::ExitPadSize); m_Exit->QueueUpstreamTraffic(std::move(pkt),
llarp::routing::ExitPadSize);
return true; return true;
} }
else else
{ {
llarp::LogWarn(Name(), " has no endpoint for ", pkt.dst()); llarp::LogWarn(Name(), " has no endpoint for ", pkt.dst());
return true; return true;
} }
} }
if(m_SNodes.at(itr->second)) if(m_SNodes.at(itr->second))
{ {
sendFunc = std::bind(&TunEndpoint::SendToSNodeOrQueue, this, itr->second.data(), std::placeholders::_1); sendFunc = std::bind(&TunEndpoint::SendToSNodeOrQueue, this,
itr->second.data(), std::placeholders::_1);
} }
else else
{ {
sendFunc = std::bind(&TunEndpoint::SendToServiceOrQueue, this, itr->second.data(), std::placeholders::_1, service::eProtocolTraffic); sendFunc = std::bind(&TunEndpoint::SendToServiceOrQueue, this,
itr->second.data(), std::placeholders::_1,
service::eProtocolTraffic);
} }
// prepare packet for insertion into network // prepare packet for insertion into network
// this includes clearing IP addresses, recalculating checksums, etc // this includes clearing IP addresses, recalculating checksums, etc
@ -404,35 +410,36 @@ namespace llarp
} }
bool bool
TunEndpoint::HandleWriteIPPacket(llarp_buffer_t buf, std::function<huint32_t(void)> getFromIP) TunEndpoint::HandleWriteIPPacket(llarp_buffer_t buf,
std::function< huint32_t(void) > getFromIP)
{ {
// llarp::LogInfo("got packet from ", msg->sender.Addr()); // llarp::LogInfo("got packet from ", msg->sender.Addr());
auto themIP = getFromIP(); auto themIP = getFromIP();
// llarp::LogInfo("themIP ", themIP); // llarp::LogInfo("themIP ", themIP);
auto usIP = m_OurIP; auto usIP = m_OurIP;
return m_NetworkToUserPktQueue.EmplaceIf( return m_NetworkToUserPktQueue.EmplaceIf(
[buf, themIP, usIP](net::IPv4Packet &pkt) -> bool { [buf, themIP, usIP](net::IPv4Packet &pkt) -> bool {
// load // load
if(!pkt.Load(buf)) if(!pkt.Load(buf))
return false; return false;
// filter out: // filter out:
// - packets smaller than minimal IPv4 header // - packets smaller than minimal IPv4 header
// - non-IPv4 packets // - non-IPv4 packets
// - packets with weird src/dst addresses // - packets with weird src/dst addresses
// (0.0.0.0/8 but not 0.0.0.0) // (0.0.0.0/8 but not 0.0.0.0)
// - packets with 0 src but non-0 dst and oposite // - packets with 0 src but non-0 dst and oposite
auto hdr = pkt.Header(); auto hdr = pkt.Header();
if(pkt.sz < sizeof(*hdr) || hdr->version != 4 if(pkt.sz < sizeof(*hdr) || hdr->version != 4
|| (hdr->saddr != 0 && *(byte_t *)&(hdr->saddr) == 0) || (hdr->saddr != 0 && *(byte_t *)&(hdr->saddr) == 0)
|| (hdr->daddr != 0 && *(byte_t *)&(hdr->daddr) == 0) || (hdr->daddr != 0 && *(byte_t *)&(hdr->daddr) == 0)
|| ((hdr->saddr == 0) != (hdr->daddr == 0))) || ((hdr->saddr == 0) != (hdr->daddr == 0)))
{ {
return false; return false;
} }
// update packet to use proper addresses, recalc checksums // update packet to use proper addresses, recalc checksums
pkt.UpdateIPv4PacketOnDst(themIP, usIP); pkt.UpdateIPv4PacketOnDst(themIP, usIP);
return true; return true;
}); });
} }
huint32_t huint32_t
@ -469,7 +476,7 @@ namespace llarp
{ {
m_AddrToIP[ident] = nextIP; m_AddrToIP[ident] = nextIP;
m_IPToAddr[nextIP] = ident; m_IPToAddr[nextIP] = ident;
m_SNodes[ident] = snode; m_SNodes[ident] = snode;
llarp::LogInfo(Name(), " mapped ", ident, " to ", nextIP); llarp::LogInfo(Name(), " mapped ", ident, " to ", nextIP);
MarkIPActive(nextIP); MarkIPActive(nextIP);
return nextIP; return nextIP;
@ -498,7 +505,7 @@ namespace llarp
// remap address // remap address
m_IPToAddr[oldest.first] = ident; m_IPToAddr[oldest.first] = ident;
m_AddrToIP[ident] = oldest.first; m_AddrToIP[ident] = oldest.first;
m_SNodes[ident] = snode; m_SNodes[ident] = snode;
nextIP = oldest.first; nextIP = oldest.first;
// mark ip active // mark ip active

@ -24,7 +24,7 @@ namespace llarp
} }
llarp_buffer_t llarp_buffer_t
IPv4Packet::ConstBuffer() const IPv4Packet::ConstBuffer() const
{ {
return llarp::InitBuffer(buf, sz); return llarp::InitBuffer(buf, sz);
} }

@ -801,12 +801,13 @@ namespace llarp
if(!m_ExitTrafficHandler) if(!m_ExitTrafficHandler)
return false; return false;
bool sent = msg->X.size() > 0; bool sent = msg->X.size() > 0;
for(const auto & pkt : msg->X) for(const auto& pkt : msg->X)
{ {
if(pkt.size() <= 8) if(pkt.size() <= 8)
return false; return false;
uint64_t counter = bufbe64toh(pkt.data()); uint64_t counter = bufbe64toh(pkt.data());
m_ExitTrafficHandler(this, llarp::InitBuffer(pkt.data() +8, pkt.size()-8), counter); m_ExitTrafficHandler(
this, llarp::InitBuffer(pkt.data() + 8, pkt.size() - 8), counter);
} }
return sent; return sent;
} }

@ -180,7 +180,8 @@ namespace llarp
{ {
(void)roles; (void)roles;
if(hop == 0) if(hop == 0)
return router->NumberOfConnectedRouters() && router->GetRandomConnectedRouter(cur); return router->NumberOfConnectedRouters()
&& router->GetRandomConnectedRouter(cur);
size_t tries = 5; size_t tries = 5;
do do

@ -242,7 +242,7 @@ namespace llarp
intros.clear(); intros.clear();
size_t count = 0; size_t count = 0;
Lock_t l(m_PathsMutex); Lock_t l(m_PathsMutex);
auto itr = m_Paths.begin(); auto itr = m_Paths.begin();
while(itr != m_Paths.end()) while(itr != m_Paths.end())
{ {
if(itr->second->IsReady() && filter(itr->second->intro)) if(itr->second->IsReady() && filter(itr->second->intro))
@ -262,7 +262,7 @@ namespace llarp
intros.clear(); intros.clear();
size_t count = 0; size_t count = 0;
Lock_t l(m_PathsMutex); Lock_t l(m_PathsMutex);
auto itr = m_Paths.begin(); auto itr = m_Paths.begin();
while(itr != m_Paths.end()) while(itr != m_Paths.end())
{ {
if(itr->second->IsReady()) if(itr->second->IsReady())
@ -287,7 +287,7 @@ namespace llarp
intro.Clear(); intro.Clear();
bool found = false; bool found = false;
Lock_t l(m_PathsMutex); Lock_t l(m_PathsMutex);
auto itr = m_Paths.begin(); auto itr = m_Paths.begin();
while(itr != m_Paths.end()) while(itr != m_Paths.end())
{ {
if(itr->second->IsReady() if(itr->second->IsReady()

@ -427,8 +427,8 @@ llarp_router::handle_router_ticker(void *user, uint64_t orig, uint64_t left)
self->ScheduleTicker(orig); self->ScheduleTicker(orig);
} }
bool bool
llarp_router::ConnectionToRouterAllowed(const llarp::RouterID & router) const llarp_router::ConnectionToRouterAllowed(const llarp::RouterID &router) const
{ {
if(strictConnectPubkeys.size() && strictConnectPubkeys.count(router) == 0) if(strictConnectPubkeys.size() && strictConnectPubkeys.count(router) == 0)
return false; return false;
@ -438,12 +438,13 @@ llarp_router::ConnectionToRouterAllowed(const llarp::RouterID & router) const
return true; return true;
} }
void void
llarp_router::HandleDHTLookupForExplore(llarp::RouterID remote, const std::vector< llarp::RouterContact > &results) llarp_router::HandleDHTLookupForExplore(
llarp::RouterID remote, const std::vector< llarp::RouterContact > &results)
{ {
if(results.size() == 0) if(results.size() == 0)
return; return;
for(const auto & rc: results) for(const auto &rc : results)
{ {
if(rc.Verify(&crypto)) if(rc.Verify(&crypto))
llarp_nodedb_put_rc(nodedb, rc); llarp_nodedb_put_rc(nodedb, rc);
@ -461,7 +462,8 @@ llarp_router::TryEstablishTo(const llarp::RouterID &remote)
{ {
if(!ConnectionToRouterAllowed(remote)) if(!ConnectionToRouterAllowed(remote))
{ {
llarp::LogWarn("not connecting to ", remote, " as it's not permitted by config"); llarp::LogWarn("not connecting to ", remote,
" as it's not permitted by config");
return; return;
} }
@ -566,7 +568,7 @@ llarp_router::Tick()
// TODO: only connect to random subset // TODO: only connect to random subset
if(bootstrapRCList.size()) if(bootstrapRCList.size())
{ {
for(const auto & rc : bootstrapRCList) for(const auto &rc : bootstrapRCList)
{ {
llarp_router_try_connect(this, rc, 4); llarp_router_try_connect(this, rc, 4);
dht->impl.ExploreNetworkVia(rc.pubkey.data()); dht->impl.ExploreNetworkVia(rc.pubkey.data());
@ -935,7 +937,6 @@ llarp_router::InitServiceNode()
return exitContext.AddExitEndpoint("default-connectivity", netConfig); return exitContext.AddExitEndpoint("default-connectivity", netConfig);
} }
bool bool
llarp_router::HasSessionTo(const llarp::RouterID &remote) const llarp_router::HasSessionTo(const llarp::RouterID &remote) const
{ {
@ -1309,10 +1310,11 @@ namespace llarp
self->netConfig.emplace(std::make_pair("local-dns", val)); self->netConfig.emplace(std::make_pair("local-dns", val));
} }
} }
else if(StrEq(section, "connect") || (StrEq(section, "bootstrap") && StrEq(key, "add-node"))) else if(StrEq(section, "connect")
|| (StrEq(section, "bootstrap") && StrEq(key, "add-node")))
{ {
self->bootstrapRCList.emplace_back(); self->bootstrapRCList.emplace_back();
auto & rc = self->bootstrapRCList.back(); auto &rc = self->bootstrapRCList.back();
if(rc.Read(val) && rc.Verify(&self->crypto)) if(rc.Read(val) && rc.Verify(&self->crypto))
{ {
llarp::LogInfo("Added bootstrap node ", rc.pubkey); llarp::LogInfo("Added bootstrap node ", rc.pubkey);

@ -106,11 +106,12 @@ struct llarp_router
/// default network config for default network interface /// default network config for default network interface
NetConfig_t netConfig; NetConfig_t netConfig;
/// identity keys whitelist of routers we will connect to directly (not for service nodes) /// identity keys whitelist of routers we will connect to directly (not for
std::set<llarp::PubKey> strictConnectPubkeys; /// service nodes)
std::set< llarp::PubKey > strictConnectPubkeys;
/// bootstrap RCs /// bootstrap RCs
std::list<llarp::RouterContact> bootstrapRCList; std::list< llarp::RouterContact > bootstrapRCList;
bool bool
ExitEnabled() const ExitEnabled() const
@ -213,17 +214,14 @@ struct llarp_router
void void
PersistSessionUntil(const llarp::RouterID &remote, llarp_time_t until); PersistSessionUntil(const llarp::RouterID &remote, llarp_time_t until);
bool bool
EnsureIdentity(); EnsureIdentity();
bool bool
EnsureEncryptionKey(); EnsureEncryptionKey();
bool bool
ConnectionToRouterAllowed(const llarp::RouterID & router) const; ConnectionToRouterAllowed(const llarp::RouterID &router) const;
bool bool
SaveRC(); SaveRC();
@ -271,8 +269,9 @@ struct llarp_router
void void
TryEstablishTo(const llarp::RouterID &remote); TryEstablishTo(const llarp::RouterID &remote);
void void
HandleDHTLookupForExplore(llarp::RouterID remote, const std::vector< llarp::RouterContact > &results); HandleDHTLookupForExplore(llarp::RouterID remote,
const std::vector< llarp::RouterContact > &results);
void void
ForEachPeer( ForEachPeer(

@ -262,8 +262,8 @@ namespace llarp
inf.read((char*)buf.base, sz); inf.read((char*)buf.base, sz);
if(!BDecode(&buf)) if(!BDecode(&buf))
return false; return false;
const byte_t * ptr = nullptr; const byte_t* ptr = nullptr;
if(!vanity.IsZero()) if(!vanity.IsZero())
ptr = vanity.data(); ptr = vanity.data();
// update pubkeys // update pubkeys

@ -46,7 +46,7 @@ namespace llarp
llarp::LogError("No endpoints found"); llarp::LogError("No endpoints found");
return nullptr; return nullptr;
} }
auto itr = m_Endpoints.begin(); auto itr = m_Endpoints.begin();
if(itr == m_Endpoints.end()) if(itr == m_Endpoints.end())
return nullptr; return nullptr;
return itr->second.get(); return itr->second.get();
@ -101,8 +101,7 @@ namespace llarp
} }
bool bool
Context::FindBestAddressFor(const byte_t * addr, bool isSNode, Context::FindBestAddressFor(const byte_t *addr, bool isSNode, huint32_t &ip)
huint32_t &ip)
{ {
auto itr = m_Endpoints.begin(); auto itr = m_Endpoints.begin();
while(itr != m_Endpoints.end()) while(itr != m_Endpoints.end())
@ -142,7 +141,6 @@ namespace llarp
10000); 10000);
} }
bool bool
MapAddressAllIter(struct Context::endpoint_iter *endpointCfg) MapAddressAllIter(struct Context::endpoint_iter *endpointCfg)
{ {
@ -155,8 +153,8 @@ namespace llarp
llarp::LogError("No tunnel endpoint found"); llarp::LogError("No tunnel endpoint found");
return true; // still continue return true; // still continue
} }
return tunEndpoint->MapAddress(context->serviceAddr, return tunEndpoint->MapAddress(
context->localPrivateIpAddr.xtohl(), false); context->serviceAddr, context->localPrivateIpAddr.xtohl(), false);
} }
bool bool

@ -197,7 +197,8 @@ namespace llarp
continue; continue;
byte_t tmp[1024] = {0}; byte_t tmp[1024] = {0};
auto buf = StackBuffer< decltype(tmp) >(tmp); auto buf = StackBuffer< decltype(tmp) >(tmp);
if(!SendToServiceOrQueue(introset.A.Addr().data(), buf, eProtocolText)) if(!SendToServiceOrQueue(introset.A.Addr().data(), buf,
eProtocolText))
{ {
llarp::LogWarn(Name(), " failed to send/queue data to ", llarp::LogWarn(Name(), " failed to send/queue data to ",
introset.A.Addr(), " for tag ", tag.ToString()); introset.A.Addr(), " for tag ", tag.ToString());
@ -784,12 +785,12 @@ namespace llarp
} }
bool bool
Endpoint::HasPathToSNode(const llarp::RouterID & ident) const Endpoint::HasPathToSNode(const llarp::RouterID& ident) const
{ {
auto range = m_SNodeSessions.equal_range(ident); auto range = m_SNodeSessions.equal_range(ident);
auto itr = range.first; auto itr = range.first;
while(itr != range.second) while(itr != range.second)
{ {
if(itr->second->IsReady()) if(itr->second->IsReady())
{ {
return true; return true;
@ -800,14 +801,16 @@ namespace llarp
} }
bool bool
Endpoint::ProcessDataMessage(ProtocolMessage *msg) Endpoint::ProcessDataMessage(ProtocolMessage* msg)
{ {
if(msg->proto == eProtocolTraffic) if(msg->proto == eProtocolTraffic)
{ {
auto buf = llarp::Buffer(msg->payload); auto buf = llarp::Buffer(msg->payload);
return HandleWriteIPPacket(buf, std::bind(&Endpoint::ObtainIPForAddr, this, msg->sender.Addr().data(), false)); return HandleWriteIPPacket(buf,
std::bind(&Endpoint::ObtainIPForAddr, this,
msg->sender.Addr().data(), false));
} }
else if (msg->proto == eProtocolText) else if(msg->proto == eProtocolText)
{ {
// TODO: implement me (?) // TODO: implement me (?)
return true; return true;
@ -1064,29 +1067,38 @@ namespace llarp
} }
void void
Endpoint::EnsurePathToSNode(const RouterID & snode) Endpoint::EnsurePathToSNode(const RouterID& snode)
{ {
auto range = m_SNodeSessions.equal_range(snode); auto range = m_SNodeSessions.equal_range(snode);
if(range.first == range.second) if(range.first == range.second)
{ {
auto themIP = ObtainIPForAddr(snode, true); auto themIP = ObtainIPForAddr(snode, true);
m_SNodeSessions.emplace(std::make_pair(snode, std::unique_ptr<llarp::exit::BaseSession>(new llarp::exit::SNodeSession(snode, std::bind(&Endpoint::HandleWriteIPPacket, this, std::placeholders::_1, [themIP]() -> huint32_t {return themIP;}), m_Router, 2, numHops)))); m_SNodeSessions.emplace(std::make_pair(
snode,
std::unique_ptr< llarp::exit::BaseSession >(
new llarp::exit::SNodeSession(
snode,
std::bind(&Endpoint::HandleWriteIPPacket, this,
std::placeholders::_1,
[themIP]() -> huint32_t { return themIP; }),
m_Router, 2, numHops))));
} }
} }
bool bool
Endpoint::SendToSNodeOrQueue(const byte_t * addr, llarp_buffer_t buf) Endpoint::SendToSNodeOrQueue(const byte_t* addr, llarp_buffer_t buf)
{ {
llarp::net::IPv4Packet pkt; llarp::net::IPv4Packet pkt;
if(!pkt.Load(buf)) if(!pkt.Load(buf))
return false; return false;
auto range = m_SNodeSessions.equal_range(addr); auto range = m_SNodeSessions.equal_range(addr);
auto itr = range.first; auto itr = range.first;
while(itr != range.second) while(itr != range.second)
{ {
if(itr->second->IsReady()) if(itr->second->IsReady())
{ {
if(itr->second->QueueUpstreamTraffic(pkt, llarp::routing::ExitPadSize)) if(itr->second->QueueUpstreamTraffic(pkt,
llarp::routing::ExitPadSize))
{ {
return true; return true;
} }
@ -1098,7 +1110,7 @@ namespace llarp
bool bool
Endpoint::SendToServiceOrQueue(const byte_t* addr, llarp_buffer_t data, Endpoint::SendToServiceOrQueue(const byte_t* addr, llarp_buffer_t data,
ProtocolType t) ProtocolType t)
{ {
service::Address remote(addr); service::Address remote(addr);

@ -259,13 +259,14 @@ namespace llarp
if(endpoint) if(endpoint)
{ {
bool sent = true; bool sent = true;
for(const auto & pkt : msg->X) for(const auto& pkt : msg->X)
{ {
// check short packet buffer // check short packet buffer
if(pkt.size() <= 8) if(pkt.size() <= 8)
continue; continue;
uint64_t counter = bufbe64toh(pkt.data()); uint64_t counter = bufbe64toh(pkt.data());
sent &= endpoint->QueueOutboundTraffic(llarp::InitBuffer(pkt.data() + 8, pkt.size() - 8), counter); sent &= endpoint->QueueOutboundTraffic(
llarp::InitBuffer(pkt.data() + 8, pkt.size() - 8), counter);
} }
return sent; return sent;
} }

Loading…
Cancel
Save