diff --git a/daemon/dns.cpp b/daemon/dns.cpp index 0583182ce..932fdaf34 100644 --- a/daemon/dns.cpp +++ b/daemon/dns.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include diff --git a/daemon/rcutil.cpp b/daemon/rcutil.cpp index 85416a01a..137f5cf38 100644 --- a/daemon/rcutil.cpp +++ b/daemon/rcutil.cpp @@ -3,15 +3,16 @@ #include #include "logger.hpp" +#include #include #include +#include #include #include "buffer.hpp" #include "crypto.hpp" #include "fs.hpp" #include "llarp/net.hpp" -#include "router.hpp" #include diff --git a/include/llarp.hpp b/include/llarp.hpp index 94ec620c5..18c466d24 100644 --- a/include/llarp.hpp +++ b/include/llarp.hpp @@ -8,6 +8,9 @@ #include #include +struct llarp_config; +struct llarp_config_iterator; + namespace llarp { struct Context @@ -17,7 +20,7 @@ namespace llarp int num_nethreads = 1; bool singleThreaded = false; llarp_crypto crypto; - llarp_router *router = nullptr; + llarp::Router *router = nullptr; llarp_threadpool *worker = nullptr; llarp::Logic *logic = nullptr; llarp_config *config = nullptr; diff --git a/include/llarp/dht.h b/include/llarp/dht.h index 55ec410f5..733df7d9b 100644 --- a/include/llarp/dht.h +++ b/include/llarp/dht.h @@ -2,7 +2,6 @@ #define LLARP_DHT_H_ #include -#include #include #include @@ -14,9 +13,11 @@ struct llarp_dht_context; +namespace llarp { struct Router; } + /// allocator struct llarp_dht_context* -llarp_dht_context_new(struct llarp_router* parent); +llarp_dht_context_new(llarp::Router* parent); /// deallocator void @@ -37,7 +38,6 @@ struct llarp_router_lookup_job void* user; llarp_router_lookup_handler hook; struct llarp_dht_context* dht; - // byte_t target[PUBKEYSIZE]; llarp::PubKey target; bool found; // make sure you initialize addr and exits diff --git a/include/llarp/dht/context.hpp b/include/llarp/dht/context.hpp index 134009815..3016d330a 100644 --- a/include/llarp/dht/context.hpp +++ b/include/llarp/dht/context.hpp @@ -7,7 +7,6 @@ #include #include #include -#include #include #include @@ -15,6 +14,8 @@ namespace llarp { + struct Router; + namespace dht { struct TXOwner @@ -234,7 +235,7 @@ namespace llarp /// initialize dht context and explore every exploreInterval milliseconds void - Init(const Key_t& us, llarp_router* router, llarp_time_t exploreInterval); + Init(const Key_t& us, llarp::Router* router, llarp_time_t exploreInterval); /// get localally stored introset by service address const llarp::service::IntroSet* @@ -250,7 +251,7 @@ namespace llarp void Explore(size_t N = 3); - llarp_router* router = nullptr; + llarp::Router* router = nullptr; // for router contacts Bucket< RCNode >* nodes = nullptr; @@ -427,8 +428,8 @@ namespace llarp struct llarp_dht_context { llarp::dht::Context impl; - llarp_router* parent; - llarp_dht_context(llarp_router* router); + llarp::Router* parent; + llarp_dht_context(llarp::Router* router); }; #endif diff --git a/include/llarp/dht/message.hpp b/include/llarp/dht/message.hpp index 15aabb42d..de232c374 100644 --- a/include/llarp/dht/message.hpp +++ b/include/llarp/dht/message.hpp @@ -24,7 +24,7 @@ namespace llarp virtual bool HandleMessage( - llarp_dht_context* dht, + struct llarp_dht_context* dht, std::vector< std::unique_ptr< IMessage > >& replies) const = 0; Key_t From; diff --git a/include/llarp/dht/messages/findintro.hpp b/include/llarp/dht/messages/findintro.hpp index 444514303..78185352b 100644 --- a/include/llarp/dht/messages/findintro.hpp +++ b/include/llarp/dht/messages/findintro.hpp @@ -1,6 +1,7 @@ #ifndef LLARP_DHT_MESSAGES_FIND_INTRO_HPP #define LLARP_DHT_MESSAGES_FIND_INTRO_HPP #include +#include #include #include diff --git a/include/llarp/exit/context.hpp b/include/llarp/exit/context.hpp index 2cc23e435..04e3f3293 100644 --- a/include/llarp/exit/context.hpp +++ b/include/llarp/exit/context.hpp @@ -4,7 +4,6 @@ #include #include #include -#include namespace llarp { @@ -15,7 +14,7 @@ namespace llarp { using Config_t = std::unordered_multimap< std::string, std::string >; - Context(llarp_router *r); + Context(llarp::Router *r); ~Context(); void @@ -43,7 +42,7 @@ namespace llarp CalculateExitTraffic(TrafficStats &stats); private: - llarp_router *m_Router; + llarp::Router *m_Router; std::unordered_map< std::string, std::unique_ptr< llarp::handlers::ExitEndpoint > > m_Exits; @@ -51,4 +50,4 @@ namespace llarp } // namespace exit } // namespace llarp -#endif \ No newline at end of file +#endif diff --git a/include/llarp/exit/endpoint.hpp b/include/llarp/exit/endpoint.hpp index 2a7e4a392..ae54e8343 100644 --- a/include/llarp/exit/endpoint.hpp +++ b/include/llarp/exit/endpoint.hpp @@ -2,7 +2,6 @@ #define LLARP_EXIT_ENDPOINT_HPP #include #include -#include #include #include diff --git a/include/llarp/exit/session.hpp b/include/llarp/exit/session.hpp index f53c8cec3..bfdea12c7 100644 --- a/include/llarp/exit/session.hpp +++ b/include/llarp/exit/session.hpp @@ -17,7 +17,7 @@ namespace llarp BaseSession(const llarp::RouterID& exitRouter, std::function< bool(llarp_buffer_t) > writepkt, - llarp_router* r, size_t numpaths, size_t hoplen); + llarp::Router* r, size_t numpaths, size_t hoplen); virtual ~BaseSession(); @@ -76,7 +76,7 @@ namespace llarp { ExitSession(const llarp::RouterID& snodeRouter, std::function< bool(llarp_buffer_t) > writepkt, - llarp_router* r, size_t numpaths, size_t hoplen) + llarp::Router* r, size_t numpaths, size_t hoplen) : BaseSession(snodeRouter, writepkt, r, numpaths, hoplen){}; ~ExitSession(){}; @@ -95,7 +95,7 @@ namespace llarp { SNodeSession(const llarp::RouterID& snodeRouter, std::function< bool(llarp_buffer_t) > writepkt, - llarp_router* r, size_t numpaths, size_t hoplen) + llarp::Router* r, size_t numpaths, size_t hoplen) : BaseSession(snodeRouter, writepkt, r, numpaths, hoplen){}; ~SNodeSession(){}; diff --git a/include/llarp/handlers/exit.hpp b/include/llarp/handlers/exit.hpp index b17174c62..80dbabe8a 100644 --- a/include/llarp/handlers/exit.hpp +++ b/include/llarp/handlers/exit.hpp @@ -11,7 +11,7 @@ namespace llarp { struct ExitEndpoint { - ExitEndpoint(const std::string& name, llarp_router* r); + ExitEndpoint(const std::string& name, llarp::Router* r); ~ExitEndpoint(); void @@ -41,7 +41,7 @@ namespace llarp void OnInetPacket(llarp_buffer_t buf); - llarp_router* + llarp::Router* Router(); llarp_time_t @@ -100,7 +100,7 @@ namespace llarp void KickIdentOffExit(const llarp::PubKey& pk); - llarp_router* m_Router; + llarp::Router* m_Router; bool m_ShouldInitTun; std::string m_Name; bool m_PermitExit; diff --git a/include/llarp/handlers/null.hpp b/include/llarp/handlers/null.hpp index b8b3aa4c8..79bbbca80 100644 --- a/include/llarp/handlers/null.hpp +++ b/include/llarp/handlers/null.hpp @@ -8,7 +8,7 @@ namespace llarp { struct NullEndpoint final : public llarp::service::Endpoint { - NullEndpoint(const std::string &name, llarp_router *r) + NullEndpoint(const std::string &name, llarp::Router *r) : llarp::service::Endpoint(name, r){}; bool HandleWriteIPPacket(llarp_buffer_t, @@ -32,4 +32,4 @@ namespace llarp } // namespace handlers } // namespace llarp -#endif \ No newline at end of file +#endif diff --git a/include/llarp/handlers/tun.hpp b/include/llarp/handlers/tun.hpp index 6581677c3..e11b4a86d 100644 --- a/include/llarp/handlers/tun.hpp +++ b/include/llarp/handlers/tun.hpp @@ -19,7 +19,7 @@ namespace llarp struct TunEndpoint : public service::Endpoint, public dns::IQueryHandler { - TunEndpoint(const std::string& nickname, llarp_router* r); + TunEndpoint(const std::string& nickname, llarp::Router* r); ~TunEndpoint(); virtual bool diff --git a/include/llarp/iwp.hpp b/include/llarp/iwp.hpp index 7ce082723..137e19902 100644 --- a/include/llarp/iwp.hpp +++ b/include/llarp/iwp.hpp @@ -3,12 +3,17 @@ #include #include +namespace llarp { + class Logic; + struct Router; +} + struct llarp_iwp_args { struct llarp_crypto* crypto; llarp::Logic* logic; struct llarp_threadpool* cryptoworker; - struct llarp_router* router; + struct llarp::Router* router; bool permitInbound; }; diff --git a/include/llarp/link/curvecp.hpp b/include/llarp/link/curvecp.hpp index 406b6299c..c34cd8a07 100644 --- a/include/llarp/link/curvecp.hpp +++ b/include/llarp/link/curvecp.hpp @@ -8,7 +8,7 @@ namespace llarp namespace curvecp { std::unique_ptr< ILinkLayer > - NewServer(llarp_router* r); + NewServer(llarp::Router* r); } } // namespace llarp diff --git a/include/llarp/link/server.hpp b/include/llarp/link/server.hpp index f051e6369..267deb52a 100644 --- a/include/llarp/link/server.hpp +++ b/include/llarp/link/server.hpp @@ -10,10 +10,10 @@ #include #include -struct llarp_router; - namespace llarp { + struct Router; + struct ILinkLayer { virtual ~ILinkLayer(); diff --git a/include/llarp/link/utp.hpp b/include/llarp/link/utp.hpp index 6824be0f4..f1cb33424 100644 --- a/include/llarp/link/utp.hpp +++ b/include/llarp/link/utp.hpp @@ -8,7 +8,7 @@ namespace llarp namespace utp { std::unique_ptr< ILinkLayer > - NewServer(llarp_router* r); + NewServer(llarp::Router* r); } } // namespace llarp diff --git a/include/llarp/link_message.hpp b/include/llarp/link_message.hpp index d2222e787..c9bcd7fc0 100644 --- a/include/llarp/link_message.hpp +++ b/include/llarp/link_message.hpp @@ -8,11 +8,10 @@ #include #include -struct llarp_router; - namespace llarp { struct ILinkSession; + struct Router; using SendQueue = std::queue< ILinkMessage* >; @@ -35,12 +34,12 @@ namespace llarp } virtual bool - HandleMessage(llarp_router* router) const = 0; + HandleMessage(Router* router) const = 0; }; struct InboundMessageParser { - InboundMessageParser(llarp_router* router); + InboundMessageParser(Router* router); dict_reader reader; static bool @@ -65,7 +64,7 @@ namespace llarp private: bool firstkey; - llarp_router* router; + Router* router; ILinkSession* from = nullptr; std::unique_ptr< ILinkMessage > msg; }; diff --git a/include/llarp/messages/dht.hpp b/include/llarp/messages/dht.hpp index 949b6f02e..8a7f56846 100644 --- a/include/llarp/messages/dht.hpp +++ b/include/llarp/messages/dht.hpp @@ -23,7 +23,7 @@ namespace llarp BEncode(llarp_buffer_t* buf) const override; bool - HandleMessage(IMessageHandler* h, llarp_router* r) const override; + HandleMessage(IMessageHandler* h, llarp::Router* r) const override; }; } // namespace routing } // namespace llarp diff --git a/include/llarp/messages/dht_immediate.hpp b/include/llarp/messages/dht_immediate.hpp index 87d5e7837..cffdcd300 100644 --- a/include/llarp/messages/dht_immediate.hpp +++ b/include/llarp/messages/dht_immediate.hpp @@ -27,7 +27,7 @@ namespace llarp BEncode(llarp_buffer_t* buf) const; bool - HandleMessage(llarp_router* router) const; + HandleMessage(llarp::Router* router) const; }; } // namespace llarp diff --git a/include/llarp/messages/discard.hpp b/include/llarp/messages/discard.hpp index 74778f1b8..7b3126193 100644 --- a/include/llarp/messages/discard.hpp +++ b/include/llarp/messages/discard.hpp @@ -43,7 +43,7 @@ namespace llarp } bool - HandleMessage(__attribute__((unused)) llarp_router* router) const override + HandleMessage(__attribute__((unused)) llarp::Router* router) const override { return true; } @@ -66,7 +66,7 @@ namespace llarp } bool - HandleMessage(IMessageHandler* h, llarp_router* r) const override + HandleMessage(IMessageHandler* h, llarp::Router* r) const override { return h->HandleDataDiscardMessage(this, r); } diff --git a/include/llarp/messages/exit.hpp b/include/llarp/messages/exit.hpp index 96965fce3..a2486b969 100644 --- a/include/llarp/messages/exit.hpp +++ b/include/llarp/messages/exit.hpp @@ -44,7 +44,7 @@ namespace llarp DecodeKey(llarp_buffer_t key, llarp_buffer_t* buf) override; bool - HandleMessage(IMessageHandler* h, llarp_router* r) const override; + HandleMessage(IMessageHandler* h, llarp::Router* r) const override; }; struct GrantExitMessage final : public IMessage @@ -77,7 +77,7 @@ namespace llarp DecodeKey(llarp_buffer_t key, llarp_buffer_t* buf) override; bool - HandleMessage(IMessageHandler* h, llarp_router* r) const override; + HandleMessage(IMessageHandler* h, llarp::Router* r) const override; }; struct RejectExitMessage final : public IMessage @@ -113,7 +113,7 @@ namespace llarp DecodeKey(llarp_buffer_t key, llarp_buffer_t* buf) override; bool - HandleMessage(IMessageHandler* h, llarp_router* r) const override; + HandleMessage(IMessageHandler* h, llarp::Router* r) const override; }; struct UpdateExitVerifyMessage final : public IMessage @@ -147,7 +147,7 @@ namespace llarp DecodeKey(llarp_buffer_t key, llarp_buffer_t* buf) override; bool - HandleMessage(IMessageHandler* h, llarp_router* r) const override; + HandleMessage(IMessageHandler* h, llarp::Router* r) const override; }; struct UpdateExitMessage final : public IMessage @@ -182,7 +182,7 @@ namespace llarp DecodeKey(llarp_buffer_t key, llarp_buffer_t* buf) override; bool - HandleMessage(IMessageHandler* h, llarp_router* r) const override; + HandleMessage(IMessageHandler* h, llarp::Router* r) const override; }; struct CloseExitMessage final : public IMessage @@ -210,7 +210,7 @@ namespace llarp DecodeKey(llarp_buffer_t key, llarp_buffer_t* buf) override; bool - HandleMessage(IMessageHandler* h, llarp_router* r) const override; + HandleMessage(IMessageHandler* h, llarp::Router* r) const override; bool Sign(llarp_crypto* c, const llarp::SecretKey& sk); @@ -222,4 +222,4 @@ namespace llarp } // namespace routing } // namespace llarp -#endif \ No newline at end of file +#endif diff --git a/include/llarp/messages/link_intro.hpp b/include/llarp/messages/link_intro.hpp index 5ce22c010..3f0007cf0 100644 --- a/include/llarp/messages/link_intro.hpp +++ b/include/llarp/messages/link_intro.hpp @@ -35,7 +35,7 @@ namespace llarp BEncode(llarp_buffer_t* buf) const; bool - HandleMessage(llarp_router* router) const; + HandleMessage(llarp::Router* router) const; bool Sign(llarp_crypto* c, const SecretKey& signKeySecret); diff --git a/include/llarp/messages/path_confirm.hpp b/include/llarp/messages/path_confirm.hpp index 49e1ce96f..7128a4eb1 100644 --- a/include/llarp/messages/path_confirm.hpp +++ b/include/llarp/messages/path_confirm.hpp @@ -22,7 +22,7 @@ namespace llarp DecodeKey(llarp_buffer_t key, llarp_buffer_t* val) override; bool - HandleMessage(IMessageHandler* h, llarp_router* r) const override; + HandleMessage(IMessageHandler* h, llarp::Router* r) const override; }; } // namespace routing } // namespace llarp diff --git a/include/llarp/messages/path_latency.hpp b/include/llarp/messages/path_latency.hpp index de6461bee..545a0ef55 100644 --- a/include/llarp/messages/path_latency.hpp +++ b/include/llarp/messages/path_latency.hpp @@ -20,7 +20,7 @@ namespace llarp DecodeKey(llarp_buffer_t key, llarp_buffer_t* val) override; bool - HandleMessage(IMessageHandler* h, llarp_router* r) const override; + HandleMessage(IMessageHandler* h, llarp::Router* r) const override; }; } // namespace routing } // namespace llarp diff --git a/include/llarp/messages/path_transfer.hpp b/include/llarp/messages/path_transfer.hpp index bc49fbe07..9ef90b251 100644 --- a/include/llarp/messages/path_transfer.hpp +++ b/include/llarp/messages/path_transfer.hpp @@ -31,7 +31,7 @@ namespace llarp BEncode(llarp_buffer_t* buf) const override; bool - HandleMessage(IMessageHandler*, llarp_router* r) const override; + HandleMessage(IMessageHandler*, llarp::Router* r) const override; }; } // namespace routing diff --git a/include/llarp/messages/relay.hpp b/include/llarp/messages/relay.hpp index 6320c26a7..e9d7fe1dd 100644 --- a/include/llarp/messages/relay.hpp +++ b/include/llarp/messages/relay.hpp @@ -26,7 +26,7 @@ namespace llarp BEncode(llarp_buffer_t* buf) const; bool - HandleMessage(llarp_router* router) const; + HandleMessage(llarp::Router* router) const; }; struct RelayDownstreamMessage : public ILinkMessage @@ -45,7 +45,7 @@ namespace llarp BEncode(llarp_buffer_t* buf) const; bool - HandleMessage(llarp_router* router) const; + HandleMessage(llarp::Router* router) const; }; } // namespace llarp diff --git a/include/llarp/messages/relay_commit.hpp b/include/llarp/messages/relay_commit.hpp index 1546e7c99..a932af2b6 100644 --- a/include/llarp/messages/relay_commit.hpp +++ b/include/llarp/messages/relay_commit.hpp @@ -67,7 +67,7 @@ namespace llarp BEncode(llarp_buffer_t *buf) const; bool - HandleMessage(llarp_router *router) const; + HandleMessage(llarp::Router *router) const; bool AsyncDecrypt(llarp::path::PathContext *context) const; diff --git a/include/llarp/messages/transfer_traffic.hpp b/include/llarp/messages/transfer_traffic.hpp index 3a18caf56..8356c3c52 100644 --- a/include/llarp/messages/transfer_traffic.hpp +++ b/include/llarp/messages/transfer_traffic.hpp @@ -36,9 +36,9 @@ namespace llarp DecodeKey(llarp_buffer_t k, llarp_buffer_t* val) override; bool - HandleMessage(IMessageHandler* h, llarp_router* r) const override; + HandleMessage(IMessageHandler* h, llarp::Router* r) const override; }; } // namespace routing } // namespace llarp -#endif \ No newline at end of file +#endif diff --git a/include/llarp/path.hpp b/include/llarp/path.hpp index d87813cb8..c9a06e3ea 100644 --- a/include/llarp/path.hpp +++ b/include/llarp/path.hpp @@ -1,6 +1,5 @@ #ifndef LLARP_PATH_HPP #define LLARP_PATH_HPP -#include #include #include #include @@ -110,17 +109,17 @@ namespace llarp /// send routing message and increment sequence number virtual bool SendRoutingMessage(const llarp::routing::IMessage* msg, - llarp_router* r) = 0; + llarp::Router* r) = 0; // handle data in upstream direction virtual bool HandleUpstream(llarp_buffer_t X, const TunnelNonce& Y, - llarp_router* r) = 0; + llarp::Router* r) = 0; // handle data in downstream direction virtual bool HandleDownstream(llarp_buffer_t X, const TunnelNonce& Y, - llarp_router* r) = 0; + llarp::Router* r) = 0; uint64_t NextSeqNo() @@ -176,55 +175,55 @@ namespace llarp // send routing message when end of path bool SendRoutingMessage(const llarp::routing::IMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; // handle routing message when end of path bool HandleRoutingMessage(const llarp::routing::IMessage* msg, - llarp_router* r); + llarp::Router* r); bool HandleDataDiscardMessage(const llarp::routing::DataDiscardMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandlePathConfirmMessage(const llarp::routing::PathConfirmMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandlePathTransferMessage(const llarp::routing::PathTransferMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandlePathLatencyMessage(const llarp::routing::PathLatencyMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandleObtainExitMessage(const llarp::routing::ObtainExitMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandleUpdateExitVerifyMessage( const llarp::routing::UpdateExitVerifyMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandleTransferTrafficMessage( const llarp::routing::TransferTrafficMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandleUpdateExitMessage(const llarp::routing::UpdateExitMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandleGrantExitMessage(const llarp::routing::GrantExitMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandleRejectExitMessage(const llarp::routing::RejectExitMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandleCloseExitMessage(const llarp::routing::CloseExitMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandleHiddenServiceFrame(__attribute__(( @@ -240,17 +239,17 @@ namespace llarp bool HandleDHTMessage(const llarp::dht::IMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; // handle data in upstream direction bool HandleUpstream(llarp_buffer_t X, const TunnelNonce& Y, - llarp_router* r) override; + llarp::Router* r) override; // handle data in downstream direction bool HandleDownstream(llarp_buffer_t X, const TunnelNonce& Y, - llarp_router* r) override; + llarp::Router* r) override; }; /// configuration for a single hop when building a path @@ -395,55 +394,55 @@ namespace llarp Expired(llarp_time_t now) const override; void - Tick(llarp_time_t now, llarp_router* r); + Tick(llarp_time_t now, llarp::Router* r); bool SendRoutingMessage(const llarp::routing::IMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandleObtainExitMessage(const llarp::routing::ObtainExitMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandleUpdateExitVerifyMessage( const llarp::routing::UpdateExitVerifyMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandleTransferTrafficMessage( const llarp::routing::TransferTrafficMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandleUpdateExitMessage(const llarp::routing::UpdateExitMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandleCloseExitMessage(const llarp::routing::CloseExitMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandleGrantExitMessage(const llarp::routing::GrantExitMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandleRejectExitMessage(const llarp::routing::RejectExitMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandleDataDiscardMessage(const llarp::routing::DataDiscardMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandlePathConfirmMessage(const llarp::routing::PathConfirmMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandlePathLatencyMessage(const llarp::routing::PathLatencyMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandlePathTransferMessage(const llarp::routing::PathTransferMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool HandleHiddenServiceFrame( @@ -454,20 +453,20 @@ namespace llarp bool HandleDHTMessage(const llarp::dht::IMessage* msg, - llarp_router* r) override; + llarp::Router* r) override; bool - HandleRoutingMessage(llarp_buffer_t buf, llarp_router* r); + HandleRoutingMessage(llarp_buffer_t buf, llarp::Router* r); // handle data in upstream direction bool HandleUpstream(llarp_buffer_t X, const TunnelNonce& Y, - llarp_router* r) override; + llarp::Router* r) override; // handle data in downstream direction bool HandleDownstream(llarp_buffer_t X, const TunnelNonce& Y, - llarp_router* r) override; + llarp::Router* r) override; bool IsReady() const; @@ -503,7 +502,7 @@ namespace llarp bool SendExitRequest(const llarp::routing::ObtainExitMessage* msg, - llarp_router* r); + llarp::Router* r); protected: llarp::routing::InboundMessageParser m_InboundMessageParser; @@ -540,7 +539,7 @@ namespace llarp struct PathContext { - PathContext(llarp_router* router); + PathContext(llarp::Router* router); ~PathContext(); /// called from router tick function @@ -634,7 +633,7 @@ namespace llarp llarp::Logic* Logic(); - llarp_router* + llarp::Router* Router(); byte_t* @@ -644,7 +643,7 @@ namespace llarp OurRouterID() const; private: - llarp_router* m_Router; + llarp::Router* m_Router; SyncTransitMap_t m_TransitPaths; SyncTransitMap_t m_Paths; SyncOwnedPathsMap_t m_OurPaths; diff --git a/include/llarp/pathbuilder.hpp b/include/llarp/pathbuilder.hpp index 88e6716c4..e7b7772f3 100644 --- a/include/llarp/pathbuilder.hpp +++ b/include/llarp/pathbuilder.hpp @@ -12,14 +12,14 @@ namespace llarp struct Builder : public PathSet { - struct llarp_router* router; + llarp::Router* router; struct llarp_dht_context* dht; llarp::SecretKey enckey; size_t numHops; llarp_time_t lastBuild = 0; llarp_time_t buildIntervalLimit = MIN_PATH_BUILD_INTERVAL; /// construct - Builder(llarp_router* p_router, struct llarp_dht_context* p_dht, + Builder(llarp::Router* p_router, struct llarp_dht_context* p_dht, size_t numPaths, size_t numHops); virtual ~Builder(); diff --git a/include/llarp/pathset.hpp b/include/llarp/pathset.hpp index 0dd2df2e3..af0398835 100644 --- a/include/llarp/pathset.hpp +++ b/include/llarp/pathset.hpp @@ -1,5 +1,6 @@ #ifndef LLARP_PATHSET_HPP #define LLARP_PATHSET_HPP + #include #include #include @@ -12,6 +13,8 @@ #include #include +struct llarp_nodedb; + namespace llarp { namespace dht @@ -58,7 +61,7 @@ namespace llarp /// tick owned paths void - Tick(llarp_time_t now, llarp_router* r); + Tick(llarp_time_t now, llarp::Router* r); /// count the number of paths that will exist at this timestamp in future size_t @@ -167,7 +170,7 @@ namespace llarp std::set< llarp::service::Introduction >& intros) const; virtual bool - PublishIntroSet(__attribute__((unused)) llarp_router* r) + PublishIntroSet(__attribute__((unused)) llarp::Router* r) { return false; } diff --git a/include/llarp/router.h b/include/llarp/router.h deleted file mode 100644 index d240bc24a..000000000 --- a/include/llarp/router.h +++ /dev/null @@ -1,30 +0,0 @@ -#ifndef LLARP_ROUTER_H_ -#define LLARP_ROUTER_H_ -#include -#include -#include -#include -#include - -struct llarp_nodedb; -struct llarp_router; - -bool -llarp_findOrCreateIdentity(struct llarp_crypto *crypto, const char *path, - byte_t *secretkey); - -struct llarp_router * -llarp_init_router(struct llarp_threadpool *worker, - struct llarp_ev_loop *netloop, llarp::Logic *logic); -void -llarp_free_router(struct llarp_router **router); -bool -llarp_configure_router(struct llarp_router *router, struct llarp_config *conf); - -bool -llarp_run_router(struct llarp_router *router, struct llarp_nodedb *nodedb); - -void -llarp_stop_router(struct llarp_router *router); - -#endif diff --git a/include/llarp/routing/handler.hpp b/include/llarp/routing/handler.hpp index bf17615f0..33377a123 100644 --- a/include/llarp/routing/handler.hpp +++ b/include/llarp/routing/handler.hpp @@ -2,7 +2,6 @@ #define LLARP_ROUTING_HANDLER_HPP #include -#include #include #include @@ -22,50 +21,50 @@ namespace llarp { virtual bool HandleObtainExitMessage(const ObtainExitMessage *msg, - llarp_router *r) = 0; + llarp::Router *r) = 0; virtual bool - HandleGrantExitMessage(const GrantExitMessage *msg, llarp_router *r) = 0; + HandleGrantExitMessage(const GrantExitMessage *msg, llarp::Router *r) = 0; virtual bool HandleRejectExitMessage(const RejectExitMessage *msg, - llarp_router *r) = 0; + llarp::Router *r) = 0; virtual bool HandleTransferTrafficMessage(const TransferTrafficMessage *msg, - llarp_router *r) = 0; + llarp::Router *r) = 0; virtual bool HandleUpdateExitMessage(const UpdateExitMessage *msg, - llarp_router *r) = 0; + llarp::Router *r) = 0; virtual bool HandleUpdateExitVerifyMessage(const UpdateExitVerifyMessage *msg, - llarp_router *r) = 0; + llarp::Router *r) = 0; virtual bool - HandleCloseExitMessage(const CloseExitMessage *msg, llarp_router *r) = 0; + HandleCloseExitMessage(const CloseExitMessage *msg, llarp::Router *r) = 0; virtual bool HandleDataDiscardMessage(const DataDiscardMessage *msg, - llarp_router *r) = 0; + llarp::Router *r) = 0; virtual bool HandlePathTransferMessage(const PathTransferMessage *msg, - llarp_router *r) = 0; + llarp::Router *r) = 0; virtual bool HandleHiddenServiceFrame(const service::ProtocolFrame *msg) = 0; virtual bool HandlePathConfirmMessage(const PathConfirmMessage *msg, - llarp_router *r) = 0; + llarp::Router *r) = 0; virtual bool HandlePathLatencyMessage(const PathLatencyMessage *msg, - llarp_router *r) = 0; + llarp::Router *r) = 0; virtual bool - HandleDHTMessage(const llarp::dht::IMessage *msg, llarp_router *r) = 0; + HandleDHTMessage(const llarp::dht::IMessage *msg, llarp::Router *r) = 0; }; } // namespace routing } // namespace llarp diff --git a/include/llarp/routing/message.hpp b/include/llarp/routing/message.hpp index e9e861f8c..765b65a5f 100644 --- a/include/llarp/routing/message.hpp +++ b/include/llarp/routing/message.hpp @@ -2,12 +2,12 @@ #define LLARP_ROUTING_MESSAGE_HPP #include -#include #include #include namespace llarp { + struct Router; namespace routing { struct IMessageHandler; @@ -24,7 +24,7 @@ namespace llarp virtual ~IMessage(){}; virtual bool - HandleMessage(IMessageHandler* h, llarp_router* r) const = 0; + HandleMessage(IMessageHandler* h, llarp::Router* r) const = 0; }; struct InboundMessageParser @@ -32,7 +32,7 @@ namespace llarp InboundMessageParser(); bool ParseMessageBuffer(llarp_buffer_t buf, IMessageHandler* handler, - const PathID_t& from, llarp_router* r); + const PathID_t& from, llarp::Router* r); private: static bool diff --git a/include/llarp/rpc.hpp b/include/llarp/rpc.hpp index 253b3fc47..5d3ba95a2 100644 --- a/include/llarp/rpc.hpp +++ b/include/llarp/rpc.hpp @@ -6,11 +6,10 @@ #include #include -// forward declare -struct llarp_router; - namespace llarp { + struct Router; + namespace rpc { struct ServerImpl; @@ -18,7 +17,7 @@ namespace llarp /// jsonrpc server struct Server { - Server(llarp_router* r); + Server(llarp::Router* r); ~Server(); bool @@ -33,7 +32,7 @@ namespace llarp /// jsonrpc caller struct Caller { - Caller(llarp_router* r); + Caller(llarp::Router* r); ~Caller(); /// start with jsonrpc endpoint address diff --git a/include/llarp/service/context.hpp b/include/llarp/service/context.hpp index b312cce3d..5435cd3c8 100644 --- a/include/llarp/service/context.hpp +++ b/include/llarp/service/context.hpp @@ -1,6 +1,5 @@ #ifndef LLARP_SERVICE_CONTEXT_HPP #define LLARP_SERVICE_CONTEXT_HPP -#include #include #include #include @@ -14,7 +13,7 @@ namespace llarp /// holds all the hidden service endpoints we own struct Context { - Context(llarp_router *r); + Context(llarp::Router *r); ~Context(); void @@ -74,7 +73,7 @@ namespace llarp StartAll(); private: - llarp_router *m_Router; + llarp::Router *m_Router; std::unordered_map< std::string, std::unique_ptr< Endpoint > > m_Endpoints; }; diff --git a/include/llarp/service/endpoint.hpp b/include/llarp/service/endpoint.hpp index 671d4bdbb..cdd5e8d95 100644 --- a/include/llarp/service/endpoint.hpp +++ b/include/llarp/service/endpoint.hpp @@ -34,7 +34,7 @@ namespace llarp static const size_t MAX_OUTBOUND_CONTEXT_COUNT = 4; - Endpoint(const std::string& nickname, llarp_router* r); + Endpoint(const std::string& nickname, llarp::Router* r); ~Endpoint(); void @@ -64,7 +64,7 @@ namespace llarp llarp_threadpool* Worker(); - llarp_router* + llarp::Router* Router() { return m_Router; @@ -90,10 +90,10 @@ namespace llarp EnsureReplyPath(const ServiceInfo& addr); bool - PublishIntroSet(llarp_router* r); + PublishIntroSet(llarp::Router* r); bool - PublishIntroSetVia(llarp_router* r, path::Path* p); + PublishIntroSetVia(llarp::Router* r, path::Path* p); bool HandleGotIntroMessage(const llarp::dht::GotIntroMessage* msg); @@ -428,7 +428,7 @@ namespace llarp std::unique_ptr< llarp::exit::BaseSession > m_Exit; private: - llarp_router* m_Router; + llarp::Router* m_Router; llarp_threadpool* m_IsolatedWorker = nullptr; llarp::Logic* m_IsolatedLogic = nullptr; llarp_ev_loop* m_IsolatedNetLoop = nullptr; diff --git a/include/llarp/service/lookup.hpp b/include/llarp/service/lookup.hpp index 87f32f5ab..aba015012 100644 --- a/include/llarp/service/lookup.hpp +++ b/include/llarp/service/lookup.hpp @@ -1,7 +1,6 @@ #ifndef LLARP_SERVICE_LOOKUP_HPP #define LLARP_SERVICE_LOOKUP_HPP -#include #include #include #include @@ -46,7 +45,7 @@ namespace llarp /// build a new requset message and send it via a path bool - SendRequestViaPath(llarp::path::Path* p, llarp_router* r); + SendRequestViaPath(llarp::path::Path* p, llarp::Router* r); ILookupHolder* parent; uint64_t txid; diff --git a/include/llarp/service/protocol.hpp b/include/llarp/service/protocol.hpp index f551ae8c7..e1d524108 100644 --- a/include/llarp/service/protocol.hpp +++ b/include/llarp/service/protocol.hpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -13,6 +14,8 @@ namespace llarp { + class Logic; + namespace service { constexpr std::size_t MAX_PROTOCOL_MESSAGE_SIZE = 2048 * 2; @@ -115,7 +118,7 @@ namespace llarp bool HandleMessage(llarp::routing::IMessageHandler* h, - llarp_router* r) const override; + llarp::Router* r) const override; }; } // namespace service } // namespace llarp diff --git a/llarp/context.cpp b/llarp/context.cpp index a64bbf9f9..e2334792b 100644 --- a/llarp/context.cpp +++ b/llarp/context.cpp @@ -4,7 +4,7 @@ #include #include // for MIN #include -#include "router.hpp" +#include #include #include @@ -149,9 +149,9 @@ namespace llarp else logic = new Logic; - router = llarp_init_router(worker, mainloop, logic); + router = new Router(worker, mainloop, logic); - if(!llarp_configure_router(router, config)) + if(!router->Configure(config)) { llarp::LogError("Failed to configure router"); return 1; @@ -169,7 +169,7 @@ namespace llarp return 1; } // run - if(!llarp_run_router(router, nodedb)) + if(!router->Run(nodedb)) return 1; // run net io thread llarp::LogInfo("running mainloop"); @@ -213,7 +213,7 @@ namespace llarp llarp::LogDebug("stop router"); if(router) - llarp_stop_router(router); + router->Stop(); llarp::LogDebug("stop workers"); if(worker) @@ -236,7 +236,7 @@ namespace llarp llarp_ev_loop_stop(mainloop); llarp::LogDebug("free router"); - llarp_free_router(&router); + delete router; llarp::LogDebug("free logic"); delete logic; diff --git a/llarp/dht.cpp b/llarp/dht.cpp index 5b0a943bf..9fd878326 100644 --- a/llarp/dht.cpp +++ b/llarp/dht.cpp @@ -1,14 +1,14 @@ #include -#include "router.hpp" +#include #include "router_contact.hpp" -llarp_dht_context::llarp_dht_context(llarp_router *router) +llarp_dht_context::llarp_dht_context(llarp::Router *router) { parent = router; } struct llarp_dht_context * -llarp_dht_context_new(struct llarp_router *router) +llarp_dht_context_new(llarp::Router *router) { return new llarp_dht_context(router); } diff --git a/llarp/dht/context.cpp b/llarp/dht/context.cpp index e0c430296..3da991b0f 100644 --- a/llarp/dht/context.cpp +++ b/llarp/dht/context.cpp @@ -2,8 +2,8 @@ #include #include #include -#include #include "router.hpp" +#include namespace llarp { @@ -79,7 +79,7 @@ namespace llarp // lookup router parent->LookupRouter( pk, - std::bind(&llarp_router::HandleDHTLookupForExplore, + std::bind(&llarp::Router::HandleDHTLookupForExplore, parent->router, pk, std::placeholders::_1)); } } @@ -258,7 +258,7 @@ namespace llarp } void - Context::Init(const Key_t &us, llarp_router *r, + Context::Init(const Key_t &us, llarp::Router *r, llarp_time_t exploreInterval) { router = r; diff --git a/llarp/dht/dht_immediate.cpp b/llarp/dht/dht_immediate.cpp index add6b8d13..48242c4dc 100644 --- a/llarp/dht/dht_immediate.cpp +++ b/llarp/dht/dht_immediate.cpp @@ -1,5 +1,6 @@ #include -#include "router.hpp" + +#include namespace llarp { @@ -57,7 +58,7 @@ namespace llarp } bool - DHTImmeidateMessage::HandleMessage(llarp_router *router) const + DHTImmeidateMessage::HandleMessage(llarp::Router *router) const { DHTImmeidateMessage reply(session); bool result = true; diff --git a/llarp/dht/find_intro.cpp b/llarp/dht/find_intro.cpp index 875ac0a0f..1cf69d7f3 100644 --- a/llarp/dht/find_intro.cpp +++ b/llarp/dht/find_intro.cpp @@ -10,7 +10,7 @@ namespace llarp /* struct IntroSetLookupInformer { - llarp_router* router; + llarp::Router* router; service::Address target; void diff --git a/llarp/dht/find_router.cpp b/llarp/dht/find_router.cpp index 7b201cf9a..bfd28224d 100644 --- a/llarp/dht/find_router.cpp +++ b/llarp/dht/find_router.cpp @@ -1,9 +1,9 @@ - #include #include #include #include -#include "router.hpp" + +#include namespace llarp { diff --git a/llarp/dht/got_intro.cpp b/llarp/dht/got_intro.cpp index 8e85444ed..2db7b7a04 100644 --- a/llarp/dht/got_intro.cpp +++ b/llarp/dht/got_intro.cpp @@ -1,8 +1,8 @@ - #include #include #include -#include "router.hpp" + +#include namespace llarp { diff --git a/llarp/dht/got_router.cpp b/llarp/dht/got_router.cpp index 219c4e687..07e632ff6 100644 --- a/llarp/dht/got_router.cpp +++ b/llarp/dht/got_router.cpp @@ -1,7 +1,8 @@ #include #include -#include "router.hpp" + +#include namespace llarp { diff --git a/llarp/dht/publish_intro.cpp b/llarp/dht/publish_intro.cpp index a205518ac..2e36de55c 100644 --- a/llarp/dht/publish_intro.cpp +++ b/llarp/dht/publish_intro.cpp @@ -1,9 +1,9 @@ - #include #include #include #include -#include "router.hpp" + +#include namespace llarp { diff --git a/llarp/dns_dotlokilookup.cpp b/llarp/dns_dotlokilookup.cpp index 66123b3ca..db244dcc0 100644 --- a/llarp/dns_dotlokilookup.cpp +++ b/llarp/dns_dotlokilookup.cpp @@ -1,6 +1,7 @@ #include #include #include +#include std::string const default_chars = "abcdefghijklmnaoqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; diff --git a/llarp/exit/close_exit.cpp b/llarp/exit/close_exit.cpp index 42d0ade2a..325c857dd 100644 --- a/llarp/exit/close_exit.cpp +++ b/llarp/exit/close_exit.cpp @@ -76,10 +76,10 @@ namespace llarp } bool - CloseExitMessage::HandleMessage(IMessageHandler* h, llarp_router* r) const + CloseExitMessage::HandleMessage(IMessageHandler* h, llarp::Router* r) const { return h->HandleCloseExitMessage(this, r); } } // namespace routing -} // namespace llarp \ No newline at end of file +} // namespace llarp diff --git a/llarp/exit/context.cpp b/llarp/exit/context.cpp index 90187cd01..cf7eff261 100644 --- a/llarp/exit/context.cpp +++ b/llarp/exit/context.cpp @@ -4,7 +4,7 @@ namespace llarp { namespace exit { - Context::Context(llarp_router* r) : m_Router(r) + Context::Context(llarp::Router* r) : m_Router(r) { } Context::~Context() @@ -94,4 +94,4 @@ namespace llarp } } // namespace exit -} // namespace llarp \ No newline at end of file +} // namespace llarp diff --git a/llarp/exit/endpoint.cpp b/llarp/exit/endpoint.cpp index ea6bcd6b1..eccd16d4e 100644 --- a/llarp/exit/endpoint.cpp +++ b/llarp/exit/endpoint.cpp @@ -1,5 +1,7 @@ #include -#include "router.hpp" +#include + +#include namespace llarp { @@ -173,4 +175,4 @@ namespace llarp return router->paths.GetByUpstream(router->pubkey(), m_CurrentPath); } } // namespace exit -} // namespace llarp \ No newline at end of file +} // namespace llarp diff --git a/llarp/exit/grant_exit.cpp b/llarp/exit/grant_exit.cpp index 8495abe5a..b3cfaf006 100644 --- a/llarp/exit/grant_exit.cpp +++ b/llarp/exit/grant_exit.cpp @@ -81,10 +81,10 @@ namespace llarp } bool - GrantExitMessage::HandleMessage(IMessageHandler* h, llarp_router* r) const + GrantExitMessage::HandleMessage(IMessageHandler* h, llarp::Router* r) const { return h->HandleGrantExitMessage(this, r); } } // namespace routing -} // namespace llarp \ No newline at end of file +} // namespace llarp diff --git a/llarp/exit/obtain_exit.cpp b/llarp/exit/obtain_exit.cpp index f5536c510..85b001dc5 100644 --- a/llarp/exit/obtain_exit.cpp +++ b/llarp/exit/obtain_exit.cpp @@ -103,10 +103,10 @@ namespace llarp } bool - ObtainExitMessage::HandleMessage(IMessageHandler* h, llarp_router* r) const + ObtainExitMessage::HandleMessage(IMessageHandler* h, llarp::Router* r) const { return h->HandleObtainExitMessage(this, r); } } // namespace routing -} // namespace llarp \ No newline at end of file +} // namespace llarp diff --git a/llarp/exit/reject_exit.cpp b/llarp/exit/reject_exit.cpp index dd5763622..0b344dbff 100644 --- a/llarp/exit/reject_exit.cpp +++ b/llarp/exit/reject_exit.cpp @@ -91,10 +91,10 @@ namespace llarp } bool - RejectExitMessage::HandleMessage(IMessageHandler* h, llarp_router* r) const + RejectExitMessage::HandleMessage(IMessageHandler* h, llarp::Router* r) const { return h->HandleRejectExitMessage(this, r); } } // namespace routing -} // namespace llarp \ No newline at end of file +} // namespace llarp diff --git a/llarp/exit/session.cpp b/llarp/exit/session.cpp index 22122a95b..da50920e0 100644 --- a/llarp/exit/session.cpp +++ b/llarp/exit/session.cpp @@ -1,5 +1,6 @@ #include -#include "router.hpp" +#include +#include namespace llarp { @@ -7,7 +8,7 @@ namespace llarp { BaseSession::BaseSession(const llarp::RouterID& router, std::function< bool(llarp_buffer_t) > writepkt, - llarp_router* r, size_t numpaths, size_t hoplen) + llarp::Router* r, size_t numpaths, size_t hoplen) : llarp::path::Builder(r, r->dht, numpaths, hoplen) , m_ExitRouter(router) , m_WritePacket(writepkt) diff --git a/llarp/exit/transfer_traffic.cpp b/llarp/exit/transfer_traffic.cpp index cc14df67a..2a65f73c7 100644 --- a/llarp/exit/transfer_traffic.cpp +++ b/llarp/exit/transfer_traffic.cpp @@ -61,10 +61,10 @@ namespace llarp bool TransferTrafficMessage::HandleMessage(IMessageHandler* h, - llarp_router* r) const + llarp::Router* r) const { return h->HandleTransferTrafficMessage(this, r); } } // namespace routing -} // namespace llarp \ No newline at end of file +} // namespace llarp diff --git a/llarp/exit/update_exit.cpp b/llarp/exit/update_exit.cpp index d07800bbe..53c4fbb82 100644 --- a/llarp/exit/update_exit.cpp +++ b/llarp/exit/update_exit.cpp @@ -82,7 +82,7 @@ namespace llarp } bool - UpdateExitMessage::HandleMessage(IMessageHandler* h, llarp_router* r) const + UpdateExitMessage::HandleMessage(IMessageHandler* h, llarp::Router* r) const { return h->HandleUpdateExitMessage(this, r); } @@ -118,10 +118,10 @@ namespace llarp bool UpdateExitVerifyMessage::HandleMessage(IMessageHandler* h, - llarp_router* r) const + llarp::Router* r) const { return h->HandleUpdateExitVerifyMessage(this, r); } } // namespace routing -} // namespace llarp \ No newline at end of file +} // namespace llarp diff --git a/llarp/handlers/exit.cpp b/llarp/handlers/exit.cpp index 48f07f03a..2139b171f 100644 --- a/llarp/handlers/exit.cpp +++ b/llarp/handlers/exit.cpp @@ -19,7 +19,7 @@ namespace llarp static_cast< ExitEndpoint * >(tun->user)->Flush(); } - ExitEndpoint::ExitEndpoint(const std::string &name, llarp_router *r) + ExitEndpoint::ExitEndpoint(const std::string &name, llarp::Router *r) : m_Router(r) , m_Name(name) , m_Tun{{0}, 0, {0}, 0, 0, 0, 0, 0, 0, 0} @@ -108,7 +108,7 @@ namespace llarp return true; } - llarp_router * + llarp::Router * ExitEndpoint::Router() { return m_Router; diff --git a/llarp/handlers/tun.cpp b/llarp/handlers/tun.cpp index 95be90f1c..b06d0659e 100644 --- a/llarp/handlers/tun.cpp +++ b/llarp/handlers/tun.cpp @@ -2,7 +2,6 @@ // harmless on other platforms #define __USE_MINGW_ANSI_STDIO 1 #include -#include "router.hpp" #include #ifndef _WIN32 #include @@ -10,6 +9,8 @@ #endif #include "ev.hpp" +#include + namespace llarp { namespace handlers @@ -20,7 +21,7 @@ namespace llarp 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) : service::Endpoint(nickname, r) , m_UserToNetworkPktQueue(nickname + "_sendq", r->netloop, r->netloop) , m_NetworkToUserPktQueue(nickname + "_recvq", r->netloop, r->netloop) diff --git a/llarp/link/curvecp.cpp b/llarp/link/curvecp.cpp index 6f31f4b1c..0bbbb29ad 100644 --- a/llarp/link/curvecp.cpp +++ b/llarp/link/curvecp.cpp @@ -1,5 +1,4 @@ #include -#include "router.hpp" #include namespace llarp @@ -7,7 +6,7 @@ namespace llarp namespace curvecp { std::unique_ptr< ILinkLayer > - NewServer(__attribute__((unused)) llarp_router* r) + NewServer(__attribute__((unused)) llarp::Router* r) { return nullptr; } diff --git a/llarp/link/utp.cpp b/llarp/link/utp.cpp index c4a2f5379..22479c0a6 100644 --- a/llarp/link/utp.cpp +++ b/llarp/link/utp.cpp @@ -1,5 +1,4 @@ #include -#include "router.hpp" #include #include #include @@ -9,6 +8,8 @@ #include #include +#include + #ifdef __linux__ #include #include @@ -92,7 +93,7 @@ namespace llarp eClose // utp connection is closed }; - llarp_router* + llarp::Router* Router(); State state; @@ -323,7 +324,7 @@ namespace llarp struct LinkLayer : public ILinkLayer { utp_context* _utp_ctx = nullptr; - llarp_router* router = nullptr; + llarp::Router* router = nullptr; static uint64 OnRead(utp_callback_arguments* arg); @@ -437,7 +438,7 @@ namespace llarp return 0; } - LinkLayer(llarp_router* r) : ILinkLayer() + LinkLayer(llarp::Router* r) : ILinkLayer() { router = r; _utp_ctx = utp_init(2); @@ -584,7 +585,7 @@ namespace llarp { } - llarp_router* + llarp::Router* GetRouter(); bool @@ -618,7 +619,7 @@ namespace llarp }; std::unique_ptr< ILinkLayer > - NewServer(llarp_router* r) + NewServer(llarp::Router* r) { return std::unique_ptr< LinkLayer >(new LinkLayer(r)); } @@ -803,7 +804,7 @@ namespace llarp EnterState(eSessionReady); } - llarp_router* + llarp::Router* BaseSession::Router() { return parent->router; diff --git a/llarp/link_intro.cpp b/llarp/link_intro.cpp index 9667b1fac..90a23d43d 100644 --- a/llarp/link_intro.cpp +++ b/llarp/link_intro.cpp @@ -114,7 +114,7 @@ namespace llarp } bool - LinkIntroMessage::HandleMessage(llarp_router* router) const + LinkIntroMessage::HandleMessage(llarp::Router* router) const { if(!Verify(&router->crypto)) return false; diff --git a/llarp/link_message.cpp b/llarp/link_message.cpp index f124173f2..3e32ec3dd 100644 --- a/llarp/link_message.cpp +++ b/llarp/link_message.cpp @@ -2,11 +2,10 @@ #include #include "buffer.hpp" #include "logger.hpp" -#include "router.hpp" namespace llarp { - InboundMessageParser::InboundMessageParser(llarp_router* _router) + InboundMessageParser::InboundMessageParser(Router* _router) : router(_router) { } diff --git a/llarp/path.cpp b/llarp/path.cpp index 91a14a15f..da49dac35 100644 --- a/llarp/path.cpp +++ b/llarp/path.cpp @@ -4,15 +4,15 @@ #include #include #include +#include #include "buffer.hpp" #include "router.hpp" -#include namespace llarp { namespace path { - PathContext::PathContext(llarp_router* router) + PathContext::PathContext(llarp::Router* router) : m_Router(router), m_AllowTransit(false) { } @@ -204,7 +204,7 @@ namespace llarp return m_Router->pubkey(); } - llarp_router* + llarp::Router* PathContext::Router() { return m_Router; @@ -418,7 +418,7 @@ namespace llarp } void - Path::Tick(llarp_time_t now, llarp_router* r) + Path::Tick(llarp_time_t now, llarp::Router* r) { if(Expired(now)) return; @@ -488,7 +488,7 @@ namespace llarp bool Path::HandleUpstream(llarp_buffer_t buf, const TunnelNonce& Y, - llarp_router* r) + llarp::Router* r) { TunnelNonce n = Y; for(const auto& hop : hops) @@ -527,7 +527,7 @@ namespace llarp bool Path::HandleDownstream(llarp_buffer_t buf, const TunnelNonce& Y, - llarp_router* r) + llarp::Router* r) { TunnelNonce n = Y; for(const auto& hop : hops) @@ -539,7 +539,7 @@ namespace llarp } bool - Path::HandleRoutingMessage(llarp_buffer_t buf, llarp_router* r) + Path::HandleRoutingMessage(llarp_buffer_t buf, llarp::Router* r) { if(!m_InboundMessageParser.ParseMessageBuffer(buf, this, RXID(), r)) { @@ -551,7 +551,7 @@ namespace llarp bool Path::HandleUpdateExitVerifyMessage( - const llarp::routing::UpdateExitVerifyMessage* msg, llarp_router* r) + const llarp::routing::UpdateExitVerifyMessage* msg, llarp::Router* r) { (void)r; if(m_UpdateExitTX && msg->T == m_UpdateExitTX) @@ -569,7 +569,7 @@ namespace llarp bool Path::SendRoutingMessage(const llarp::routing::IMessage* msg, - llarp_router* r) + llarp::Router* r) { byte_t tmp[MAX_LINK_MSG_SIZE / 2]; auto buf = llarp::StackBuffer< decltype(tmp) >(tmp); @@ -597,7 +597,7 @@ namespace llarp bool Path::HandlePathTransferMessage( __attribute__((unused)) const llarp::routing::PathTransferMessage* msg, - __attribute__((unused)) llarp_router* r) + __attribute__((unused)) llarp::Router* r) { llarp::LogWarn("unwarranted path transfer message on tx=", TXID(), " rx=", RXID()); @@ -606,7 +606,7 @@ namespace llarp bool Path::HandleDataDiscardMessage( - const llarp::routing::DataDiscardMessage* msg, llarp_router* r) + const llarp::routing::DataDiscardMessage* msg, llarp::Router* r) { MarkActive(r->Now()); if(m_DropHandler) @@ -617,7 +617,7 @@ namespace llarp bool Path::HandlePathConfirmMessage( __attribute__((unused)) const llarp::routing::PathConfirmMessage* msg, - llarp_router* r) + llarp::Router* r) { auto now = r->Now(); if(_status == ePathBuilding) @@ -658,7 +658,7 @@ namespace llarp bool Path::HandlePathLatencyMessage( - const llarp::routing::PathLatencyMessage* msg, llarp_router* r) + const llarp::routing::PathLatencyMessage* msg, llarp::Router* r) { auto now = r->Now(); MarkActive(now); @@ -680,7 +680,7 @@ namespace llarp } bool - Path::HandleDHTMessage(const llarp::dht::IMessage* msg, llarp_router* r) + Path::HandleDHTMessage(const llarp::dht::IMessage* msg, llarp::Router* r) { llarp::routing::DHTMessage reply; if(!msg->HandleMessage(r->dht, reply.M)) @@ -693,7 +693,7 @@ namespace llarp bool Path::HandleCloseExitMessage(const llarp::routing::CloseExitMessage* msg, - llarp_router* r) + llarp::Router* r) { /// allows exits to close from their end if(SupportsAnyRoles(ePathRoleExit | ePathRoleSVC)) @@ -714,7 +714,7 @@ namespace llarp bool Path::SendExitRequest(const llarp::routing::ObtainExitMessage* msg, - llarp_router* r) + llarp::Router* r) { llarp::LogInfo(Name(), " sending exit request to ", Endpoint()); m_ExitObtainTX = msg->T; @@ -723,7 +723,7 @@ namespace llarp bool Path::HandleObtainExitMessage(const llarp::routing::ObtainExitMessage* msg, - llarp_router* r) + llarp::Router* r) { (void)msg; (void)r; @@ -733,7 +733,7 @@ namespace llarp bool Path::HandleUpdateExitMessage(const llarp::routing::UpdateExitMessage* msg, - llarp_router* r) + llarp::Router* r) { (void)msg; (void)r; @@ -743,7 +743,7 @@ namespace llarp bool Path::HandleRejectExitMessage(const llarp::routing::RejectExitMessage* msg, - llarp_router* r) + llarp::Router* r) { if(m_ExitObtainTX && msg->T == m_ExitObtainTX) { @@ -762,7 +762,7 @@ namespace llarp bool Path::HandleGrantExitMessage(const llarp::routing::GrantExitMessage* msg, - llarp_router* r) + llarp::Router* r) { if(m_ExitObtainTX && msg->T == m_ExitObtainTX) { @@ -793,7 +793,7 @@ namespace llarp bool Path::HandleTransferTrafficMessage( - const llarp::routing::TransferTrafficMessage* msg, llarp_router* r) + const llarp::routing::TransferTrafficMessage* msg, llarp::Router* r) { // check if we can handle exit data if(!SupportsAnyRoles(ePathRoleExit | ePathRoleSVC)) diff --git a/llarp/pathbuilder.cpp b/llarp/pathbuilder.cpp index 954cb2c2f..150ce49de 100644 --- a/llarp/pathbuilder.cpp +++ b/llarp/pathbuilder.cpp @@ -20,7 +20,7 @@ namespace llarp Handler result; size_t idx = 0; - llarp_router* router = nullptr; + llarp::Router* router = nullptr; llarp_threadpool* worker = nullptr; llarp::Logic* logic = nullptr; llarp_crypto* crypto = nullptr; @@ -153,7 +153,7 @@ namespace llarp namespace path { - Builder::Builder(llarp_router* p_router, struct llarp_dht_context* p_dht, + Builder::Builder(llarp::Router* p_router, struct llarp_dht_context* p_dht, size_t pathNum, size_t hops) : llarp::path::PathSet(pathNum) , router(p_router) diff --git a/llarp/pathset.cpp b/llarp/pathset.cpp index e14ce17ee..c948e51ae 100644 --- a/llarp/pathset.cpp +++ b/llarp/pathset.cpp @@ -57,7 +57,7 @@ namespace llarp } void - PathSet::Tick(llarp_time_t now, llarp_router* r) + PathSet::Tick(llarp_time_t now, llarp::Router* r) { Lock_t l(m_PathsMutex); for(auto& item : m_Paths) diff --git a/llarp/relay_commit.cpp b/llarp/relay_commit.cpp index 3f829301a..68c7f990e 100644 --- a/llarp/relay_commit.cpp +++ b/llarp/relay_commit.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include "buffer.hpp" @@ -45,7 +46,7 @@ namespace llarp } bool - LR_CommitMessage::HandleMessage(llarp_router* router) const + LR_CommitMessage::HandleMessage(llarp::Router* router) const { if(frames.size() != MAXHOPS) { diff --git a/llarp/relay_up_down.cpp b/llarp/relay_up_down.cpp index 25ef53a49..75cc2a4c0 100644 --- a/llarp/relay_up_down.cpp +++ b/llarp/relay_up_down.cpp @@ -54,7 +54,7 @@ namespace llarp } bool - RelayUpstreamMessage::HandleMessage(llarp_router *r) const + RelayUpstreamMessage::HandleMessage(llarp::Router *r) const { auto path = r->paths.GetByDownstream(session->GetPubKey(), pathid); if(path) @@ -112,7 +112,7 @@ namespace llarp } bool - RelayDownstreamMessage::HandleMessage(llarp_router *r) const + RelayDownstreamMessage::HandleMessage(llarp::Router *r) const { auto path = r->paths.GetByUpstream(session->GetPubKey(), pathid); if(path) diff --git a/llarp/router.cpp b/llarp/router.cpp index f8cf28332..cf52fae17 100644 --- a/llarp/router.cpp +++ b/llarp/router.cpp @@ -1,4 +1,3 @@ -#include "router.hpp" #include #include #include @@ -9,6 +8,7 @@ #include "encode.hpp" #include "llarp/net.hpp" #include "logger.hpp" +#include "router.hpp" #include "str.hpp" #include @@ -25,7 +25,7 @@ namespace llarp struct async_verify_context { - llarp_router *router; + Router *router; TryConnectJob *establish_job; }; @@ -35,10 +35,10 @@ struct TryConnectJob { llarp::RouterContact rc; llarp::ILinkLayer *link; - llarp_router *router; + llarp::Router *router; uint16_t triesLeft; TryConnectJob(const llarp::RouterContact &remote, llarp::ILinkLayer *l, - uint16_t tries, llarp_router *r) + uint16_t tries, llarp::Router *r) : rc(remote), link(l), router(r), triesLeft(tries) { } @@ -98,7 +98,7 @@ on_try_connecting(void *u) } bool -llarp_router_try_connect(struct llarp_router *router, +llarp_router_try_connect(llarp::Router *router, const llarp::RouterContact &remote, uint16_t numretries) { @@ -119,1063 +119,1038 @@ llarp_router_try_connect(struct llarp_router *router, return true; } -void -llarp_router::HandleLinkSessionEstablished(llarp::RouterContact rc, - llarp::ILinkLayer *link) -{ - async_verify_RC(rc, link); -} - -llarp_router::llarp_router() - : ready(false) - , paths(this) - , exitContext(this) - , dht(llarp_dht_context_new(this)) - , inbound_link_msg_parser(this) - , hiddenServiceContext(this) - -{ - // set rational defaults - this->ip4addr.sin_family = AF_INET; - this->ip4addr.sin_port = htons(1090); -} - -llarp_router::~llarp_router() -{ - llarp_dht_context_free(dht); -} - bool -llarp_router::HandleRecvLinkMessageBuffer(llarp::ILinkSession *session, - llarp_buffer_t buf) +llarp_findOrCreateIdentity(llarp_crypto *crypto, const char *fpath, + byte_t *secretkey) { - if(!session) + llarp::LogDebug("find or create ", fpath); + fs::path path(fpath); + std::error_code ec; + if(!fs::exists(path, ec)) { - llarp::LogWarn("no link session"); - return false; + llarp::LogInfo("generating new identity key"); + crypto->identity_keygen(secretkey); + std::ofstream f(path.string(), std::ios::binary); + if(f.is_open()) + { + f.write((char *)secretkey, SECKEYSIZE); + } } - return inbound_link_msg_parser.ProcessFrom(session, buf); -} - -void -llarp_router::PersistSessionUntil(const llarp::RouterID &remote, - llarp_time_t until) -{ - llarp::LogDebug("persist session to ", remote, " until ", until); - m_PersistingSessions[remote] = std::max(until, m_PersistingSessions[remote]); + std::ifstream f(path.string(), std::ios::binary); + if(f.is_open()) + { + f.read((char *)secretkey, SECKEYSIZE); + return true; + } + llarp::LogInfo("failed to get identity key"); + return false; } -constexpr size_t MaxPendingSendQueueSize = 8; - +// C++ ... bool -llarp_router::SendToOrQueue(const llarp::RouterID &remote, - const llarp::ILinkMessage *msg) +llarp_findOrCreateEncryption(llarp_crypto *crypto, const char *fpath, + llarp::SecretKey &encryption) { - for(const auto &link : inboundLinks) + llarp::LogDebug("find or create ", fpath); + fs::path path(fpath); + std::error_code ec; + if(!fs::exists(path, ec)) { - if(link->HasSessionTo(remote.data())) + llarp::LogInfo("generating new encryption key"); + crypto->encryption_keygen(encryption); + std::ofstream f(path.string(), std::ios::binary); + if(f.is_open()) { - SendTo(remote, msg, link.get()); - return true; + f.write((char *)encryption.data(), SECKEYSIZE); } } - if(outboundLink && outboundLink->HasSessionTo(remote.data())) + + std::ifstream f(path.string(), std::ios::binary); + if(f.is_open()) { - SendTo(remote, msg, outboundLink.get()); + f.read((char *)encryption.data(), SECKEYSIZE); return true; } + llarp::LogInfo("failed to get encryption key"); + return false; +} + +namespace llarp +{ + void + Router::HandleLinkSessionEstablished(llarp::RouterContact rc, + llarp::ILinkLayer *link) + { + async_verify_RC(rc, link); + } - // no link available + Router::Router(struct llarp_threadpool *_tp, struct llarp_ev_loop *_netloop, + llarp::Logic *_logic) + : ready(false) + , netloop(_netloop) + , tp(_tp) + , logic(_logic) + , paths(this) + , exitContext(this) + , dht(llarp_dht_context_new(this)) + , inbound_link_msg_parser(this) + , hiddenServiceContext(this) - // this will create an entry in the obmq if it's not already there - auto itr = outboundMessageQueue.find(remote); - if(itr == outboundMessageQueue.end()) { - outboundMessageQueue.insert(std::make_pair(remote, MessageQueue())); + // set rational defaults + this->ip4addr.sin_family = AF_INET; + this->ip4addr.sin_port = htons(1090); + +#ifdef TESTNET + disk = tp; +#else + disk = llarp_init_threadpool(1, "llarp-diskio"); +#endif + llarp_crypto_init(&crypto); } - // encode - llarp_buffer_t buf = - llarp::StackBuffer< decltype(linkmsg_buffer) >(linkmsg_buffer); - if(!msg->BEncode(&buf)) - return false; - // queue buffer - auto &q = outboundMessageQueue[remote]; - if(q.size() < MaxPendingSendQueueSize) + Router::~Router() { - buf.sz = buf.cur - buf.base; - q.emplace(buf.sz); - memcpy(q.back().data(), buf.base, buf.sz); + llarp_dht_context_free(dht); } - else + + bool + Router::HandleRecvLinkMessageBuffer(llarp::ILinkSession *session, + llarp_buffer_t buf) { - llarp::LogWarn("tried to queue a message to ", remote, - " but the queue is full so we drop it like it's hawt"); + if(!session) + { + llarp::LogWarn("no link session"); + return false; + } + return inbound_link_msg_parser.ProcessFrom(session, buf); } - llarp::RouterContact remoteRC; - // we don't have an open session to that router right now - if(llarp_nodedb_get_rc(nodedb, remote, remoteRC)) + + void + Router::PersistSessionUntil(const llarp::RouterID &remote, llarp_time_t until) { - // try connecting directly as the rc is loaded from disk - llarp_router_try_connect(this, remoteRC, 10); - return true; + llarp::LogDebug("persist session to ", remote, " until ", until); + m_PersistingSessions[remote] = + std::max(until, m_PersistingSessions[remote]); } - // we don't have the RC locally so do a dht lookup - dht->impl.LookupRouter(remote, - std::bind(&llarp_router::HandleDHTLookupForSendTo, - this, remote, std::placeholders::_1)); - return true; -} + constexpr size_t MaxPendingSendQueueSize = 8; -void -llarp_router::HandleDHTLookupForSendTo( - llarp::RouterID remote, const std::vector< llarp::RouterContact > &results) -{ - if(results.size()) + bool + Router::SendToOrQueue(const llarp::RouterID &remote, + const llarp::ILinkMessage *msg) { - if(whitelistRouters && lokinetRouters.find(remote) == lokinetRouters.end()) + for(const auto &link : inboundLinks) { - return; + if(link->HasSessionTo(remote.data())) + { + SendTo(remote, msg, link.get()); + return true; + } } - if(results[0].Verify(&crypto)) + if(outboundLink && outboundLink->HasSessionTo(remote.data())) { - llarp_nodedb_put_rc(nodedb, results[0]); - llarp_router_try_connect(this, results[0], 10); + SendTo(remote, msg, outboundLink.get()); + return true; } + + // no link available + + // this will create an entry in the obmq if it's not already there + auto itr = outboundMessageQueue.find(remote); + if(itr == outboundMessageQueue.end()) + { + outboundMessageQueue.insert(std::make_pair(remote, MessageQueue())); + } + // encode + llarp_buffer_t buf = + llarp::StackBuffer< decltype(linkmsg_buffer) >(linkmsg_buffer); + if(!msg->BEncode(&buf)) + return false; + // queue buffer + auto &q = outboundMessageQueue[remote]; + + if(q.size() < MaxPendingSendQueueSize) + { + buf.sz = buf.cur - buf.base; + q.emplace(buf.sz); + memcpy(q.back().data(), buf.base, buf.sz); + } + else + { + llarp::LogWarn("tried to queue a message to ", remote, + " but the queue is full so we drop it like it's hawt"); + } + llarp::RouterContact remoteRC; + // we don't have an open session to that router right now + if(llarp_nodedb_get_rc(nodedb, remote, remoteRC)) + { + // try connecting directly as the rc is loaded from disk + llarp_router_try_connect(this, remoteRC, 10); + return true; + } + + // we don't have the RC locally so do a dht lookup + dht->impl.LookupRouter(remote, + std::bind(&Router::HandleDHTLookupForSendTo, this, + remote, std::placeholders::_1)); + return true; } - else - { - DiscardOutboundFor(remote); - } -} -void -llarp_router::ForEachPeer( - std::function< void(const llarp::ILinkSession *, bool) > visit) const -{ - outboundLink->ForEachSession( - [visit](const llarp::ILinkSession *peer) { visit(peer, true); }); - for(const auto &link : inboundLinks) + void + Router::HandleDHTLookupForSendTo( + llarp::RouterID remote, + const std::vector< llarp::RouterContact > &results) { - link->ForEachSession( - [visit](const llarp::ILinkSession *peer) { visit(peer, false); }); + if(results.size()) + { + if(whitelistRouters + && lokinetRouters.find(remote) == lokinetRouters.end()) + { + return; + } + if(results[0].Verify(&crypto)) + { + llarp_nodedb_put_rc(nodedb, results[0]); + llarp_router_try_connect(this, results[0], 10); + } + } + else + { + DiscardOutboundFor(remote); + } } -} -void -llarp_router::try_connect(fs::path rcfile) -{ - llarp::RouterContact remote; - if(!remote.Read(rcfile.string().c_str())) + void + Router::ForEachPeer( + std::function< void(const llarp::ILinkSession *, bool) > visit) const { - llarp::LogError("failure to decode or verify of remote RC"); - return; + outboundLink->ForEachSession( + [visit](const llarp::ILinkSession *peer) { visit(peer, true); }); + for(const auto &link : inboundLinks) + { + link->ForEachSession( + [visit](const llarp::ILinkSession *peer) { visit(peer, false); }); + } } - if(remote.Verify(&crypto)) + + void + Router::try_connect(fs::path rcfile) { - llarp::LogDebug("verified signature"); - // store into filesystem - if(!llarp_nodedb_put_rc(nodedb, remote)) + llarp::RouterContact remote; + if(!remote.Read(rcfile.string().c_str())) { - llarp::LogWarn("failed to store"); + llarp::LogError("failure to decode or verify of remote RC"); + return; } - if(!llarp_router_try_connect(this, remote, 10)) + if(remote.Verify(&crypto)) { - // or error? - llarp::LogWarn("session already made"); + llarp::LogDebug("verified signature"); + // store into filesystem + if(!llarp_nodedb_put_rc(nodedb, remote)) + { + llarp::LogWarn("failed to store"); + } + if(!llarp_router_try_connect(this, remote, 10)) + { + // or error? + llarp::LogWarn("session already made"); + } } + else + llarp::LogError(rcfile, " contains invalid RC"); } - else - llarp::LogError(rcfile, " contains invalid RC"); -} - -bool -llarp_router::EnsureIdentity() -{ - if(!EnsureEncryptionKey()) - return false; - return llarp_findOrCreateIdentity(&crypto, ident_keyfile.string().c_str(), - identity); -} -bool -llarp_router::EnsureEncryptionKey() -{ - return llarp_findOrCreateEncryption( - &crypto, encryption_keyfile.string().c_str(), encryption); -} - -void -llarp_router::AddInboundLink(std::unique_ptr< llarp::ILinkLayer > &link) -{ - inboundLinks.push_back(std::move(link)); -} + bool + Router::EnsureIdentity() + { + if(!EnsureEncryptionKey()) + return false; + return llarp_findOrCreateIdentity(&crypto, ident_keyfile.string().c_str(), + identity); + } -bool -llarp_router::Ready() -{ - return outboundLink != nullptr; -} + bool + Router::EnsureEncryptionKey() + { + return llarp_findOrCreateEncryption( + &crypto, encryption_keyfile.string().c_str(), encryption); + } -bool -llarp_router::SaveRC() -{ - llarp::LogDebug("verify RC signature"); - if(!rc().Verify(&crypto)) + void + Router::AddInboundLink(std::unique_ptr< llarp::ILinkLayer > &link) { - rc().Dump< MAX_RC_SIZE >(); - llarp::LogError("RC is invalid, not saving"); - return false; + inboundLinks.push_back(std::move(link)); } - return rc().Write(our_rc_file.string().c_str()); -} -bool -llarp_router::IsServiceNode() const -{ - return inboundLinks.size() > 0; -} + bool + Router::Configure(struct llarp_config *conf) + { + llarp_config_iterator iter; + iter.user = this; + iter.visit = llarp::router_iter_config; + llarp_config_iter(conf, &iter); + if(!InitOutboundLink()) + return false; + if(!Ready()) + { + return false; + } + return EnsureIdentity(); + } -void -llarp_router::Close() -{ - for(const auto &link : inboundLinks) + bool + Router::Ready() { - link->Stop(); + return outboundLink != nullptr; } - inboundLinks.clear(); - if(outboundLink) + + bool + Router::SaveRC() { - outboundLink->Stop(); - outboundLink.reset(nullptr); + llarp::LogDebug("verify RC signature"); + if(!rc().Verify(&crypto)) + { + rc().Dump< MAX_RC_SIZE >(); + llarp::LogError("RC is invalid, not saving"); + return false; + } + return rc().Write(our_rc_file.string().c_str()); } -} -void -llarp_router::on_verify_client_rc(llarp_async_verify_rc *job) -{ - llarp::async_verify_context *ctx = - static_cast< llarp::async_verify_context * >(job->user); - ctx->router->pendingEstablishJobs.erase(job->rc.pubkey); - auto router = ctx->router; - llarp::PubKey pk(job->rc.pubkey); - router->FlushOutboundFor(pk, router->GetLinkWithSessionByPubkey(pk)); - delete ctx; - router->pendingVerifyRC.erase(pk); -} + bool + Router::IsServiceNode() const + { + return inboundLinks.size() > 0; + } -void -llarp_router::on_verify_server_rc(llarp_async_verify_rc *job) -{ - llarp::async_verify_context *ctx = - static_cast< llarp::async_verify_context * >(job->user); - auto router = ctx->router; - llarp::PubKey pk(job->rc.pubkey); - if(!job->valid) + void + Router::Close() { - if(ctx->establish_job) + for(const auto &link : inboundLinks) { - // was an outbound attempt - ctx->establish_job->Failed(); + link->Stop(); } + inboundLinks.clear(); + if(outboundLink) + { + outboundLink->Stop(); + outboundLink.reset(nullptr); + } + } + + void + Router::on_verify_client_rc(llarp_async_verify_rc *job) + { + llarp::async_verify_context *ctx = + static_cast< llarp::async_verify_context * >(job->user); + ctx->router->pendingEstablishJobs.erase(job->rc.pubkey); + auto router = ctx->router; + llarp::PubKey pk(job->rc.pubkey); + router->FlushOutboundFor(pk, router->GetLinkWithSessionByPubkey(pk)); delete ctx; - router->DiscardOutboundFor(pk); router->pendingVerifyRC.erase(pk); - - return; } - // we're valid, which means it's already been committed to the nodedb - llarp::LogDebug("rc verified and saved to nodedb"); - - if(router->validRouters.count(pk)) + void + Router::on_verify_server_rc(llarp_async_verify_rc *job) { - router->validRouters.erase(pk); - } + llarp::async_verify_context *ctx = + static_cast< llarp::async_verify_context * >(job->user); + auto router = ctx->router; + llarp::PubKey pk(job->rc.pubkey); + if(!job->valid) + { + if(ctx->establish_job) + { + // was an outbound attempt + ctx->establish_job->Failed(); + } + delete ctx; + router->DiscardOutboundFor(pk); + router->pendingVerifyRC.erase(pk); - llarp::RouterContact rc = job->rc; + return; + } + // we're valid, which means it's already been committed to the nodedb - router->validRouters.insert(std::make_pair(pk.data(), rc)); + llarp::LogDebug("rc verified and saved to nodedb"); - // track valid router in dht - router->dht->impl.nodes->PutNode(rc); + if(router->validRouters.count(pk)) + { + router->validRouters.erase(pk); + } - // mark success in profile - router->routerProfiling.MarkSuccess(pk); + llarp::RouterContact rc = job->rc; - // this was an outbound establish job - if(ctx->establish_job) - { - ctx->establish_job->Success(); - } - else - router->FlushOutboundFor(pk, router->GetLinkWithSessionByPubkey(pk)); - delete ctx; - router->pendingVerifyRC.erase(pk); -} + router->validRouters.insert(std::make_pair(pk.data(), rc)); -void -llarp_router::handle_router_ticker(void *user, uint64_t orig, uint64_t left) -{ - if(left) - return; - llarp_router *self = static_cast< llarp_router * >(user); - self->ticker_job_id = 0; - self->Tick(); - self->ScheduleTicker(orig); -} + // track valid router in dht + router->dht->impl.nodes->PutNode(rc); -bool -llarp_router::ConnectionToRouterAllowed(const llarp::RouterID &router) const -{ - if(strictConnectPubkeys.size() && strictConnectPubkeys.count(router) == 0) - return false; - else if(IsServiceNode() && whitelistRouters) - return lokinetRouters.count(router) != 0; - else - return true; -} + // mark success in profile + router->routerProfiling.MarkSuccess(pk); -void -llarp_router::HandleDHTLookupForExplore( - llarp::RouterID remote, const std::vector< llarp::RouterContact > &results) -{ - if(results.size() == 0) - return; - for(const auto &rc : results) - { - if(rc.Verify(&crypto)) - llarp_nodedb_put_rc(nodedb, rc); + // this was an outbound establish job + if(ctx->establish_job) + { + ctx->establish_job->Success(); + } else - return; + router->FlushOutboundFor(pk, router->GetLinkWithSessionByPubkey(pk)); + delete ctx; + router->pendingVerifyRC.erase(pk); } - if(ConnectionToRouterAllowed(remote)) + + void + Router::handle_router_ticker(void *user, uint64_t orig, uint64_t left) { - TryEstablishTo(remote); + if(left) + return; + Router *self = static_cast< Router * >(user); + self->ticker_job_id = 0; + self->Tick(); + self->ScheduleTicker(orig); } -} -void -llarp_router::TryEstablishTo(const llarp::RouterID &remote) -{ - if(!ConnectionToRouterAllowed(remote)) + bool + Router::ConnectionToRouterAllowed(const llarp::RouterID &router) const { - llarp::LogWarn("not connecting to ", remote, - " as it's not permitted by config"); - return; + if(strictConnectPubkeys.size() && strictConnectPubkeys.count(router) == 0) + return false; + else if(IsServiceNode() && whitelistRouters) + return lokinetRouters.count(router) != 0; + else + return true; } - llarp::RouterContact rc; - if(llarp_nodedb_get_rc(nodedb, remote, rc)) + void + Router::HandleDHTLookupForExplore( + llarp::RouterID remote, + const std::vector< llarp::RouterContact > &results) { - // try connecting async - llarp_router_try_connect(this, rc, 5); + if(results.size() == 0) + return; + for(const auto &rc : results) + { + if(rc.Verify(&crypto)) + llarp_nodedb_put_rc(nodedb, rc); + else + return; + } + if(ConnectionToRouterAllowed(remote)) + { + TryEstablishTo(remote); + } } - else if(IsServiceNode() || !routerProfiling.IsBad(remote)) + + void + Router::TryEstablishTo(const llarp::RouterID &remote) { - if(dht->impl.HasRouterLookup(remote)) + if(!ConnectionToRouterAllowed(remote)) + { + llarp::LogWarn("not connecting to ", remote, + " as it's not permitted by config"); return; - llarp::LogInfo("looking up router ", remote); - // dht lookup as we don't know it - dht->impl.LookupRouter( - remote, - std::bind(&llarp_router::HandleDHTLookupForTryEstablishTo, this, remote, - std::placeholders::_1)); + } + + llarp::RouterContact rc; + if(llarp_nodedb_get_rc(nodedb, remote, rc)) + { + // try connecting async + llarp_router_try_connect(this, rc, 5); + } + else if(IsServiceNode() || !routerProfiling.IsBad(remote)) + { + if(dht->impl.HasRouterLookup(remote)) + return; + llarp::LogInfo("looking up router ", remote); + // dht lookup as we don't know it + dht->impl.LookupRouter( + remote, + std::bind(&Router::HandleDHTLookupForTryEstablishTo, this, remote, + std::placeholders::_1)); + } + else + { + llarp::LogWarn("not connecting to ", remote, " as it's unreliable"); + } } - else + + void + Router::OnConnectTimeout(const llarp::RouterID &remote) { - llarp::LogWarn("not connecting to ", remote, " as it's unreliable"); + auto itr = pendingEstablishJobs.find(remote); + if(itr != pendingEstablishJobs.end()) + { + itr->second->AttemptTimedout(); + } } -} -void -llarp_router::OnConnectTimeout(const llarp::RouterID &remote) -{ - auto itr = pendingEstablishJobs.find(remote); - if(itr != pendingEstablishJobs.end()) + void + Router::HandleDHTLookupForTryEstablishTo( + llarp::RouterID remote, + const std::vector< llarp::RouterContact > &results) { - itr->second->AttemptTimedout(); + if(results.size() == 0) + { + if(!IsServiceNode()) + routerProfiling.MarkTimeout(remote); + } + for(const auto &result : results) + { + if(whitelistRouters + && lokinetRouters.find(result.pubkey) == lokinetRouters.end()) + continue; + llarp_nodedb_put_rc(nodedb, result); + llarp_router_try_connect(this, result, 10); + } } -} -void -llarp_router::HandleDHTLookupForTryEstablishTo( - llarp::RouterID remote, const std::vector< llarp::RouterContact > &results) -{ - if(results.size() == 0) - { - if(!IsServiceNode()) - routerProfiling.MarkTimeout(remote); - } - for(const auto &result : results) + size_t + Router::NumberOfConnectedRouters() const { - if(whitelistRouters - && lokinetRouters.find(result.pubkey) == lokinetRouters.end()) - continue; - llarp_nodedb_put_rc(nodedb, result); - llarp_router_try_connect(this, result, 10); + return validRouters.size(); } -} -size_t -llarp_router::NumberOfConnectedRouters() const -{ - return validRouters.size(); -} - -void -llarp_router::Tick() -{ - // llarp::LogDebug("tick router"); - auto now = llarp_ev_loop_time_now_ms(netloop); - paths.TickPaths(now); - paths.ExpirePaths(now); + void + Router::Tick() { - auto itr = m_PersistingSessions.begin(); - while(itr != m_PersistingSessions.end()) + // llarp::LogDebug("tick router"); + auto now = llarp_ev_loop_time_now_ms(netloop); + paths.TickPaths(now); + paths.ExpirePaths(now); { - auto link = GetLinkWithSessionByPubkey(itr->first); - if(now < itr->second) + auto itr = m_PersistingSessions.begin(); + while(itr != m_PersistingSessions.end()) { - if(link) + auto link = GetLinkWithSessionByPubkey(itr->first); + if(now < itr->second) { - llarp::LogDebug("keepalive to ", itr->first); - link->KeepAliveSessionTo(itr->first); + if(link) + { + llarp::LogDebug("keepalive to ", itr->first); + link->KeepAliveSessionTo(itr->first); + } + else + { + llarp::LogDebug("establish to ", itr->first); + TryEstablishTo(itr->first); + } + ++itr; } else { - llarp::LogDebug("establish to ", itr->first); - TryEstablishTo(itr->first); + llarp::LogInfo("commit to ", itr->first, " expired"); + itr = m_PersistingSessions.erase(itr); } - ++itr; } - else + } + + if(inboundLinks.size() == 0) + { + size_t N = llarp_nodedb_num_loaded(nodedb); + if(N < minRequiredRouters) { - llarp::LogInfo("commit to ", itr->first, " expired"); - itr = m_PersistingSessions.erase(itr); + llarp::LogInfo("We need at least ", minRequiredRouters, + " service nodes to build paths but we have ", N); + // TODO: only connect to random subset + if(bootstrapRCList.size()) + { + for(const auto &rc : bootstrapRCList) + { + llarp_router_try_connect(this, rc, 4); + dht->impl.ExploreNetworkVia(rc.pubkey.data()); + } + } + else + llarp::LogError("we have no bootstrap nodes specified"); } + paths.BuildPaths(now); + hiddenServiceContext.Tick(now); + } + if(NumberOfConnectedRouters() < minConnectedRouters) + { + ConnectToRandomRouters(minConnectedRouters); } + exitContext.Tick(now); + if(rpcCaller) + rpcCaller->Tick(now); } - if(inboundLinks.size() == 0) + void + Router::SendTo(llarp::RouterID remote, const llarp::ILinkMessage *msg, + llarp::ILinkLayer *selected) { - size_t N = llarp_nodedb_num_loaded(nodedb); - if(N < minRequiredRouters) + llarp_buffer_t buf = + llarp::StackBuffer< decltype(linkmsg_buffer) >(linkmsg_buffer); + + if(!msg->BEncode(&buf)) + { + llarp::LogWarn("failed to encode outbound message, buffer size left: ", + llarp_buffer_size_left(buf)); + return; + } + // set size of message + buf.sz = buf.cur - buf.base; + buf.cur = buf.base; + llarp::LogDebug("send ", buf.sz, " bytes to ", remote); + if(selected) { - llarp::LogInfo("We need at least ", minRequiredRouters, - " service nodes to build paths but we have ", N); - // TODO: only connect to random subset - if(bootstrapRCList.size()) + if(selected->SendTo(remote, buf)) + return; + } + bool sent = outboundLink->SendTo(remote, buf); + if(!sent) + { + for(const auto &link : inboundLinks) { - for(const auto &rc : bootstrapRCList) + if(!sent) { - llarp_router_try_connect(this, rc, 4); - dht->impl.ExploreNetworkVia(rc.pubkey.data()); + sent = link->SendTo(remote, buf); } } - else - llarp::LogError("we have no bootstrap nodes specified"); } - paths.BuildPaths(now); - hiddenServiceContext.Tick(now); - } - if(NumberOfConnectedRouters() < minConnectedRouters) - { - ConnectToRandomRouters(minConnectedRouters); + if(!sent) + llarp::LogWarn("message to ", remote, " was dropped"); } - exitContext.Tick(now); - if(rpcCaller) - rpcCaller->Tick(now); -} - -void -llarp_router::SendTo(llarp::RouterID remote, const llarp::ILinkMessage *msg, - llarp::ILinkLayer *selected) -{ - llarp_buffer_t buf = - llarp::StackBuffer< decltype(linkmsg_buffer) >(linkmsg_buffer); - if(!msg->BEncode(&buf)) + void + Router::ScheduleTicker(uint64_t ms) { - llarp::LogWarn("failed to encode outbound message, buffer size left: ", - llarp_buffer_size_left(buf)); - return; + ticker_job_id = logic->call_later({ms, this, &handle_router_ticker}); } - // set size of message - buf.sz = buf.cur - buf.base; - buf.cur = buf.base; - llarp::LogDebug("send ", buf.sz, " bytes to ", remote); - if(selected) + + void + Router::SessionClosed(const llarp::RouterID &remote) { - if(selected->SendTo(remote, buf)) - return; + __llarp_dht_remove_peer(dht, remote); + // remove from valid routers if it's a valid router + validRouters.erase(remote); + llarp::LogInfo("Session to ", remote, " fully closed"); } - bool sent = outboundLink->SendTo(remote, buf); - if(!sent) + + llarp::ILinkLayer * + Router::GetLinkWithSessionByPubkey(const llarp::RouterID &pubkey) { + if(outboundLink->HasSessionTo(pubkey)) + return outboundLink.get(); for(const auto &link : inboundLinks) { - if(!sent) - { - sent = link->SendTo(remote, buf); - } + if(link->HasSessionTo(pubkey)) + return link.get(); } + return nullptr; } - if(!sent) - llarp::LogWarn("message to ", remote, " was dropped"); -} -void -llarp_router::ScheduleTicker(uint64_t ms) -{ - ticker_job_id = logic->call_later({ms, this, &handle_router_ticker}); -} - -void -llarp_router::SessionClosed(const llarp::RouterID &remote) -{ - __llarp_dht_remove_peer(dht, remote); - // remove from valid routers if it's a valid router - validRouters.erase(remote); - llarp::LogInfo("Session to ", remote, " fully closed"); -} - -llarp::ILinkLayer * -llarp_router::GetLinkWithSessionByPubkey(const llarp::RouterID &pubkey) -{ - if(outboundLink->HasSessionTo(pubkey)) - return outboundLink.get(); - for(const auto &link : inboundLinks) + void + Router::FlushOutboundFor(llarp::RouterID remote, llarp::ILinkLayer *chosen) { - if(link->HasSessionTo(pubkey)) - return link.get(); - } - return nullptr; -} + llarp::LogDebug("Flush outbound for ", remote); -void -llarp_router::FlushOutboundFor(llarp::RouterID remote, - llarp::ILinkLayer *chosen) -{ - llarp::LogDebug("Flush outbound for ", remote); + auto itr = outboundMessageQueue.find(remote); + if(itr == outboundMessageQueue.end()) + { + pendingEstablishJobs.erase(remote); + return; + } + if(!chosen) + { + DiscardOutboundFor(remote); + pendingEstablishJobs.erase(remote); + return; + } + while(itr->second.size()) + { + auto buf = llarp::ConstBuffer(itr->second.front()); + if(!chosen->SendTo(remote, buf)) + llarp::LogWarn("failed to send outboud message to ", remote, " via ", + chosen->Name()); - auto itr = outboundMessageQueue.find(remote); - if(itr == outboundMessageQueue.end()) - { - pendingEstablishJobs.erase(remote); - return; - } - if(!chosen) - { - DiscardOutboundFor(remote); + itr->second.pop(); + } pendingEstablishJobs.erase(remote); - return; - } - while(itr->second.size()) - { - auto buf = llarp::ConstBuffer(itr->second.front()); - if(!chosen->SendTo(remote, buf)) - llarp::LogWarn("failed to send outboud message to ", remote, " via ", - chosen->Name()); - - itr->second.pop(); } - pendingEstablishJobs.erase(remote); -} - -void -llarp_router::DiscardOutboundFor(const llarp::RouterID &remote) -{ - outboundMessageQueue.erase(remote); -} -bool -llarp_router::GetRandomConnectedRouter(llarp::RouterContact &result) const -{ - auto sz = validRouters.size(); - if(sz) + void + Router::DiscardOutboundFor(const llarp::RouterID &remote) { - auto itr = validRouters.begin(); - if(sz > 1) - std::advance(itr, llarp_randint() % sz); - result = itr->second; - return true; + outboundMessageQueue.erase(remote); } - return false; -} -void -llarp_router::async_verify_RC(const llarp::RouterContact &rc, - llarp::ILinkLayer *link) -{ - if(pendingVerifyRC.count(rc.pubkey)) - return; - if(rc.IsPublicRouter() && whitelistRouters) + bool + Router::GetRandomConnectedRouter(llarp::RouterContact &result) const { - if(lokinetRouters.find(rc.pubkey) == lokinetRouters.end()) + auto sz = validRouters.size(); + if(sz) { - llarp::LogInfo(rc.pubkey, " is NOT a valid service node, rejecting"); - link->CloseSessionTo(rc.pubkey); - return; + auto itr = validRouters.begin(); + if(sz > 1) + std::advance(itr, llarp_randint() % sz); + result = itr->second; + return true; } + return false; } - llarp_async_verify_rc *job = &pendingVerifyRC[rc.pubkey]; - llarp::async_verify_context *ctx = new llarp::async_verify_context(); - ctx->router = this; - ctx->establish_job = nullptr; - - auto itr = pendingEstablishJobs.find(rc.pubkey); - if(itr != pendingEstablishJobs.end()) - ctx->establish_job = itr->second.get(); - - job->user = ctx; - job->rc = rc; - job->valid = false; - job->hook = nullptr; - - job->nodedb = nodedb; - job->logic = logic; - // job->crypto = &crypto; // we already have this - job->cryptoworker = tp; - job->diskworker = disk; - if(rc.IsPublicRouter()) - job->hook = &llarp_router::on_verify_server_rc; - else - job->hook = &llarp_router::on_verify_client_rc; - - llarp_nodedb_async_verify(job); -} -bool -llarp_router::Run() -{ - if(enableRPCServer) + void + Router::async_verify_RC(const llarp::RouterContact &rc, + llarp::ILinkLayer *link) { - if(rpcBindAddr.empty()) + if(pendingVerifyRC.count(rc.pubkey)) + return; + if(rc.IsPublicRouter() && whitelistRouters) { - rpcBindAddr = DefaultRPCBindAddr; + if(lokinetRouters.find(rc.pubkey) == lokinetRouters.end()) + { + llarp::LogInfo(rc.pubkey, " is NOT a valid service node, rejecting"); + link->CloseSessionTo(rc.pubkey); + return; + } } - rpcServer = std::make_unique< llarp::rpc::Server >(this); - while(!rpcServer->Start(rpcBindAddr)) + llarp_async_verify_rc *job = &pendingVerifyRC[rc.pubkey]; + llarp::async_verify_context *ctx = new llarp::async_verify_context(); + ctx->router = this; + ctx->establish_job = nullptr; + + auto itr = pendingEstablishJobs.find(rc.pubkey); + if(itr != pendingEstablishJobs.end()) + ctx->establish_job = itr->second.get(); + + job->user = ctx; + job->rc = rc; + job->valid = false; + job->hook = nullptr; + + job->nodedb = nodedb; + job->logic = logic; + // job->crypto = &crypto; // we already have this + job->cryptoworker = tp; + job->diskworker = disk; + if(rc.IsPublicRouter()) + job->hook = &Router::on_verify_server_rc; + else + job->hook = &Router::on_verify_client_rc; + + llarp_nodedb_async_verify(job); + } + + bool + Router::Run(struct llarp_nodedb *nodedb) + { + this->nodedb = nodedb; + + if(enableRPCServer) { - llarp::LogError("failed to bind jsonrpc to ", rpcBindAddr); + if(rpcBindAddr.empty()) + { + rpcBindAddr = DefaultRPCBindAddr; + } + rpcServer = std::make_unique< llarp::rpc::Server >(this); + while(!rpcServer->Start(rpcBindAddr)) + { + llarp::LogError("failed to bind jsonrpc to ", rpcBindAddr); #if defined(ANDROID) || defined(RPI) - sleep(1); + sleep(1); #else - std::this_thread::sleep_for(std::chrono::seconds(1)); + std::this_thread::sleep_for(std::chrono::seconds(1)); #endif + } + llarp::LogInfo("Bound RPC server to ", rpcBindAddr); } - llarp::LogInfo("Bound RPC server to ", rpcBindAddr); - } - - llarp_threadpool_start(tp); - llarp_threadpool_start(disk); - routerProfiling.Load(routerProfilesFile.c_str()); + llarp_threadpool_start(tp); + llarp_threadpool_start(disk); - llarp::Addr publicAddr(this->addrInfo); + routerProfiling.Load(routerProfilesFile.c_str()); - if(this->publicOverride) - { - llarp::LogDebug("public address:port ", publicAddr); - } + llarp::Addr publicAddr(this->addrInfo); - llarp::LogInfo("You have ", inboundLinks.size(), " inbound links"); - for(const auto &link : inboundLinks) - { - llarp::AddressInfo addr; - if(!link->GetOurAddressInfo(addr)) - continue; - llarp::Addr a(addr); - if(this->publicOverride && a.sameAddr(publicAddr)) - { - llarp::LogInfo("Found adapter for public address"); - } - if(!llarp::IsBogon(*a.addr6())) + if(this->publicOverride) { - llarp::LogInfo("Loading Addr: ", a, " into our RC"); - _rc.addrs.push_back(addr); + llarp::LogDebug("public address:port ", publicAddr); } - }; - if(this->publicOverride) - { - llarp::ILinkLayer *link = nullptr; - // llarp::LogWarn("Need to load our public IP into RC!"); - if(inboundLinks.size() == 1) + + llarp::LogInfo("You have ", inboundLinks.size(), " inbound links"); + for(const auto &link : inboundLinks) { - link = inboundLinks[0].get(); - } - else + llarp::AddressInfo addr; + if(!link->GetOurAddressInfo(addr)) + continue; + llarp::Addr a(addr); + if(this->publicOverride && a.sameAddr(publicAddr)) + { + llarp::LogInfo("Found adapter for public address"); + } + if(!llarp::IsBogon(*a.addr6())) + { + llarp::LogInfo("Loading Addr: ", a, " into our RC"); + _rc.addrs.push_back(addr); + } + }; + if(this->publicOverride) { - if(inboundLinks.size()) + llarp::ILinkLayer *link = nullptr; + // llarp::LogWarn("Need to load our public IP into RC!"); + if(inboundLinks.size() == 1) { link = inboundLinks[0].get(); } else { - llarp::LogWarn( - "No need to set public ipv4 and port if no external interface " - "binds, turning off public override"); - this->publicOverride = false; - link = nullptr; + if(inboundLinks.size()) + { + link = inboundLinks[0].get(); + } + else + { + llarp::LogWarn( + "No need to set public ipv4 and port if no external interface " + "binds, turning off public override"); + this->publicOverride = false; + link = nullptr; + } + } + if(link && link->GetOurAddressInfo(this->addrInfo)) + { + // override ip and port + this->addrInfo.ip = *publicAddr.addr6(); + this->addrInfo.port = publicAddr.port(); + llarp::LogInfo("Loaded our public ", publicAddr, " override into RC!"); + _rc.addrs.push_back(this->addrInfo); } } - if(link && link->GetOurAddressInfo(this->addrInfo)) + + // set public encryption key + _rc.enckey = llarp::seckey_topublic(encryption); + // set public signing key + _rc.pubkey = llarp::seckey_topublic(identity); + if(ExitEnabled()) { - // override ip and port - this->addrInfo.ip = *publicAddr.addr6(); - this->addrInfo.port = publicAddr.port(); - llarp::LogInfo("Loaded our public ", publicAddr, " override into RC!"); - _rc.addrs.push_back(this->addrInfo); + llarp::nuint32_t a = publicAddr.xtonl(); + // TODO: enable this once the network can serialize xi + //_rc.exits.emplace_back(_rc.pubkey, a); + llarp::LogInfo( + "Neato tehl33toh, You are a freaking exit relay. w00t!!!!! your exit " + "is advertised as exiting at ", + a); + } + llarp::LogInfo("Signing rc..."); + if(!_rc.Sign(&crypto, identity)) + { + llarp::LogError("failed to sign rc"); + return false; } - } - - // set public encryption key - _rc.enckey = llarp::seckey_topublic(encryption); - // set public signing key - _rc.pubkey = llarp::seckey_topublic(identity); - if(ExitEnabled()) - { - llarp::nuint32_t a = publicAddr.xtonl(); - // TODO: enable this once the network can serialize xi - //_rc.exits.emplace_back(_rc.pubkey, a); - llarp::LogInfo( - "Neato tehl33toh, You are a freaking exit relay. w00t!!!!! your exit " - "is advertised as exiting at ", - a); - } - llarp::LogInfo("Signing rc..."); - if(!_rc.Sign(&crypto, identity)) - { - llarp::LogError("failed to sign rc"); - return false; - } - if(!SaveRC()) - { - llarp::LogError("failed to save RC"); - return false; - } + if(!SaveRC()) + { + llarp::LogError("failed to save RC"); + return false; + } - llarp::LogInfo("have ", llarp_nodedb_num_loaded(nodedb), " routers"); + llarp::LogInfo("have ", llarp_nodedb_num_loaded(nodedb), " routers"); - llarp::LogDebug("starting outbound link"); - if(!outboundLink->Start(logic)) - { - llarp::LogWarn("outbound link failed to start"); - return false; - } + llarp::LogDebug("starting outbound link"); + if(!outboundLink->Start(logic)) + { + llarp::LogWarn("outbound link failed to start"); + return false; + } - int IBLinksStarted = 0; + int IBLinksStarted = 0; - // start links - for(const auto &link : inboundLinks) - { - if(link->Start(logic)) + // start links + for(const auto &link : inboundLinks) { - llarp::LogDebug("Link ", link->Name(), " started"); - IBLinksStarted++; + if(link->Start(logic)) + { + llarp::LogDebug("Link ", link->Name(), " started"); + IBLinksStarted++; + } + else + llarp::LogWarn("Link ", link->Name(), " failed to start"); } - else - llarp::LogWarn("Link ", link->Name(), " failed to start"); - } - if(IBLinksStarted > 0) - { - // initialize as service node - if(!InitServiceNode()) + if(IBLinksStarted > 0) { - llarp::LogError("Failed to initialize service node"); - return false; + // initialize as service node + if(!InitServiceNode()) + { + llarp::LogError("Failed to initialize service node"); + return false; + } + llarp::RouterID us = pubkey(); + llarp::LogInfo("initalized service node: ", us); } - llarp::RouterID us = pubkey(); - llarp::LogInfo("initalized service node: ", us); - } - else - { - // we are a client - // regenerate keys and resign rc before everything else - crypto.identity_keygen(identity); - crypto.encryption_keygen(encryption); - _rc.pubkey = llarp::seckey_topublic(identity); - _rc.enckey = llarp::seckey_topublic(encryption); - if(!_rc.Sign(&crypto, identity)) + else { - llarp::LogError("failed to regenerate keys and sign RC"); - return false; + // we are a client + // regenerate keys and resign rc before everything else + crypto.identity_keygen(identity); + crypto.encryption_keygen(encryption); + _rc.pubkey = llarp::seckey_topublic(identity); + _rc.enckey = llarp::seckey_topublic(encryption); + if(!_rc.Sign(&crypto, identity)) + { + llarp::LogError("failed to regenerate keys and sign RC"); + return false; + } + // generate default hidden service + llarp::LogInfo("setting up default network endpoint"); + if(!CreateDefaultHiddenService()) + { + llarp::LogError("failed to set up default network endpoint"); + return false; + } } - // generate default hidden service - llarp::LogInfo("setting up default network endpoint"); - if(!CreateDefaultHiddenService()) + + llarp::LogInfo("starting hidden service context..."); + if(!hiddenServiceContext.StartAll()) { - llarp::LogError("failed to set up default network endpoint"); + llarp::LogError("Failed to start hidden service context"); return false; } + llarp_dht_context_start(dht, pubkey()); + ScheduleTicker(1000); + return true; } - llarp::LogInfo("starting hidden service context..."); - if(!hiddenServiceContext.StartAll()) + void + Router::Stop() { - llarp::LogError("Failed to start hidden service context"); - return false; + this->Close(); + this->routerProfiling.Save(this->routerProfilesFile.c_str()); } - llarp_dht_context_start(dht, pubkey()); - ScheduleTicker(1000); - return true; -} - -bool -llarp_router::InitServiceNode() -{ - llarp::LogInfo("accepting transit traffic"); - paths.AllowTransit(); - llarp_dht_allow_transit(dht); - return exitContext.AddExitEndpoint("default-connectivity", netConfig); -} - -bool -llarp_router::HasSessionTo(const llarp::RouterID &remote) const -{ - return validRouters.find(remote) != validRouters.end(); -} - -void -llarp_router::ConnectToRandomRouters(int want) -{ - int wanted = want; - llarp_router *self = this; - llarp_nodedb_visit_loaded( - self->nodedb, [self, &want](const llarp::RouterContact &other) -> bool { - // check if we really want to - if(!self->ConnectionToRouterAllowed(other.pubkey)) - return want > 0; - if(llarp_randint() % 2 == 0 - && !(self->HasSessionTo(other.pubkey) - || self->HasPendingConnectJob(other.pubkey))) - { - llarp_router_try_connect(self, other, 5); - --want; - } - return want > 0; - }); - if(wanted != want) - llarp::LogInfo("connecting to ", abs(want - wanted), " out of ", wanted, - " random routers"); -} - -bool -llarp_router::ReloadConfig(__attribute__((unused)) const llarp_config *conf) -{ - // TODO: implement me - return true; -} -bool -llarp_router::InitOutboundLink() -{ - if(outboundLink) - return true; - - auto link = llarp::utp::NewServer(this); - - if(!link->EnsureKeys(transport_keyfile.string().c_str())) + bool + Router::HasSessionTo(const llarp::RouterID &remote) const { - llarp::LogError("failed to load ", transport_keyfile); - return false; + return validRouters.find(remote) != validRouters.end(); } - auto afs = {AF_INET, AF_INET6}; - - for(auto af : afs) - { - if(link->Configure(netloop, "*", af, 0)) - { - outboundLink = std::move(link); - llarp::LogInfo("outbound link ready"); - return true; - } + void + Router::ConnectToRandomRouters(int want) + { + int wanted = want; + Router *self = this; + llarp_nodedb_visit_loaded( + self->nodedb, [self, &want](const llarp::RouterContact &other) -> bool { + // check if we really want to + if(!self->ConnectionToRouterAllowed(other.pubkey)) + return want > 0; + if(llarp_randint() % 2 == 0 + && !(self->HasSessionTo(other.pubkey) + || self->HasPendingConnectJob(other.pubkey))) + { + llarp_router_try_connect(self, other, 5); + --want; + } + return want > 0; + }); + if(wanted != want) + llarp::LogInfo("connecting to ", abs(want - wanted), " out of ", wanted, + " random routers"); } - return false; -} -bool -llarp_router::CreateDefaultHiddenService() -{ - // fallback defaults - static const std::unordered_map< std::string, - std::function< std::string(void) > > - netConfigDefaults = { - {"ifname", llarp::findFreeLokiTunIfName}, - {"ifaddr", llarp::findFreePrivateRange}, - {"local-dns", []() -> std::string { return "127.0.0.1:53"; }}, - {"upstream-dns", []() -> std::string { return "1.1.1.1:53"; }}}; - // populate with fallback defaults if values not present - auto itr = netConfigDefaults.begin(); - while(itr != netConfigDefaults.end()) + bool + Router::InitServiceNode() { - if(netConfig.count(itr->first) == 0) - { - netConfig.emplace(std::make_pair(itr->first, itr->second())); - } - ++itr; + llarp::LogInfo("accepting transit traffic"); + paths.AllowTransit(); + llarp_dht_allow_transit(dht); + return exitContext.AddExitEndpoint("default-connectivity", netConfig); } - // add endpoint - return hiddenServiceContext.AddDefaultEndpoint(netConfig); -} - -bool -llarp_router::HasPendingConnectJob(const llarp::RouterID &remote) -{ - return pendingEstablishJobs.find(remote) != pendingEstablishJobs.end(); -} -struct llarp_router * -llarp_init_router(struct llarp_threadpool *tp, struct llarp_ev_loop *netloop, - llarp::Logic *logic) -{ - llarp_router *router = new llarp_router(); - if(router) + bool + Router::ReloadConfig(__attribute__((unused)) const llarp_config *conf) { - router->netloop = netloop; - router->tp = tp; - router->logic = logic; -// TODO: make disk io threadpool count configurable (?) -#ifdef TESTNET - router->disk = tp; -#else - router->disk = llarp_init_threadpool(1, "llarp-diskio"); -#endif - llarp_crypto_init(&router->crypto); + // TODO: implement me + return true; } - return router; -} -bool -llarp_configure_router(struct llarp_router *router, struct llarp_config *conf) -{ - llarp_config_iterator iter; - iter.user = router; - iter.visit = llarp::router_iter_config; - llarp_config_iter(conf, &iter); - if(!router->InitOutboundLink()) - return false; - if(!router->Ready()) + bool + Router::InitOutboundLink() { - return false; - } - return router->EnsureIdentity(); -} + if(outboundLink) + return true; -bool -llarp_run_router(struct llarp_router *router, struct llarp_nodedb *nodedb) -{ - router->nodedb = nodedb; - return router->Run(); -} + auto link = llarp::utp::NewServer(this); -void -llarp_stop_router(struct llarp_router *router) -{ - if(router) - { - router->Close(); - router->routerProfiling.Save(router->routerProfilesFile.c_str()); - } -} + if(!link->EnsureKeys(transport_keyfile.string().c_str())) + { + llarp::LogError("failed to load ", transport_keyfile); + return false; + } -void -llarp_free_router(struct llarp_router **router) -{ - if(*router) - { - delete *router; - } - *router = nullptr; -} + auto afs = {AF_INET, AF_INET6}; -bool -llarp_findOrCreateIdentity(llarp_crypto *crypto, const char *fpath, - byte_t *secretkey) -{ - llarp::LogDebug("find or create ", fpath); - fs::path path(fpath); - std::error_code ec; - if(!fs::exists(path, ec)) - { - llarp::LogInfo("generating new identity key"); - crypto->identity_keygen(secretkey); - std::ofstream f(path.string(), std::ios::binary); - if(f.is_open()) + for(auto af : afs) { - f.write((char *)secretkey, SECKEYSIZE); + if(link->Configure(netloop, "*", af, 0)) + { + outboundLink = std::move(link); + llarp::LogInfo("outbound link ready"); + return true; + } } + return false; } - std::ifstream f(path.string(), std::ios::binary); - if(f.is_open()) - { - f.read((char *)secretkey, SECKEYSIZE); - return true; - } - llarp::LogInfo("failed to get identity key"); - return false; -} -// C++ ... -bool -llarp_findOrCreateEncryption(llarp_crypto *crypto, const char *fpath, - llarp::SecretKey &encryption) -{ - llarp::LogDebug("find or create ", fpath); - fs::path path(fpath); - std::error_code ec; - if(!fs::exists(path, ec)) - { - llarp::LogInfo("generating new encryption key"); - crypto->encryption_keygen(encryption); - std::ofstream f(path.string(), std::ios::binary); - if(f.is_open()) + bool + Router::CreateDefaultHiddenService() + { + // fallback defaults + static const std::unordered_map< std::string, + std::function< std::string(void) > > + netConfigDefaults = { + {"ifname", llarp::findFreeLokiTunIfName}, + {"ifaddr", llarp::findFreePrivateRange}, + {"local-dns", []() -> std::string { return "127.0.0.1:53"; }}, + {"upstream-dns", []() -> std::string { return "1.1.1.1:53"; }}}; + // populate with fallback defaults if values not present + auto itr = netConfigDefaults.begin(); + while(itr != netConfigDefaults.end()) { - f.write((char *)encryption.data(), SECKEYSIZE); + if(netConfig.count(itr->first) == 0) + { + netConfig.emplace(std::make_pair(itr->first, itr->second())); + } + ++itr; } + // add endpoint + return hiddenServiceContext.AddDefaultEndpoint(netConfig); } - std::ifstream f(path.string(), std::ios::binary); - if(f.is_open()) + bool + Router::HasPendingConnectJob(const llarp::RouterID &remote) { - f.read((char *)encryption.data(), SECKEYSIZE); - return true; + return pendingEstablishJobs.find(remote) != pendingEstablishJobs.end(); } - llarp::LogInfo("failed to get encryption key"); - return false; -} -bool -llarp_router::LoadHiddenServiceConfig(const char *fname) -{ - llarp::LogDebug("opening hidden service config ", fname); - llarp::service::Config conf; - if(!conf.Load(fname)) - return false; - for(const auto &config : conf.services) + bool + Router::LoadHiddenServiceConfig(const char *fname) { - llarp::service::Config::section_t filteredConfig; - mergeHiddenServiceConfig(config.second, filteredConfig.second); - filteredConfig.first = config.first; - if(!hiddenServiceContext.AddEndpoint(filteredConfig)) + llarp::LogDebug("opening hidden service config ", fname); + llarp::service::Config conf; + if(!conf.Load(fname)) return false; + for(const auto &config : conf.services) + { + llarp::service::Config::section_t filteredConfig; + mergeHiddenServiceConfig(config.second, filteredConfig.second); + filteredConfig.first = config.first; + if(!hiddenServiceContext.AddEndpoint(filteredConfig)) + return false; + } + return true; } - return true; -} -namespace llarp -{ void router_iter_config(llarp_config_iterator *iter, const char *section, const char *key, const char *val) { llarp::LogDebug(section, " ", key, "=", val); - llarp_router *self = static_cast< llarp_router * >(iter->user); + Router *self = static_cast< Router * >(iter->user); int af; uint16_t proto; diff --git a/llarp/router.hpp b/llarp/router.hpp index 07953f803..450cdb41a 100644 --- a/llarp/router.hpp +++ b/llarp/router.hpp @@ -1,11 +1,25 @@ #ifndef LLARP_ROUTER_HPP #define LLARP_ROUTER_HPP + +#include +#include #include +#include +#include +#include +#include +#include +#include +#include +#include #include -#include #include -#include +#include +#include +#include #include +#include +#include #include #include @@ -13,342 +27,353 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "crypto.hpp" -#include "fs.hpp" -#include "mem.hpp" -#include "str.hpp" +#include +#include +#include +#include bool llarp_findOrCreateEncryption(llarp_crypto *crypto, const char *fpath, llarp::SecretKey &encryption); +bool +llarp_findOrCreateIdentity(struct llarp_crypto *crypto, const char *path, + byte_t *secretkey); + struct TryConnectJob; -struct llarp_router +namespace llarp { - bool ready; - // transient iwp encryption key - fs::path transport_keyfile = "transport.key"; - - // nodes to connect to on startup - // DEPRECATED - // std::map< std::string, fs::path > connect; - - // long term identity key - fs::path ident_keyfile = "identity.key"; - - fs::path encryption_keyfile = "encryption.key"; - - // path to write our self signed rc to - fs::path our_rc_file = "rc.signed"; - - // our router contact - llarp::RouterContact _rc; - - /// should we obey the service node whitelist? - bool whitelistRouters = false; - - const llarp::RouterContact & - rc() const + struct Router { - return _rc; - } + bool ready; + // transient iwp encryption key + fs::path transport_keyfile = "transport.key"; - // our ipv4 public setting - bool publicOverride = false; - struct sockaddr_in ip4addr; - llarp::AddressInfo addrInfo; + // nodes to connect to on startup + // DEPRECATED + // std::map< std::string, fs::path > connect; - llarp_ev_loop *netloop; - llarp_threadpool *tp; - llarp::Logic *logic; - llarp_crypto crypto; - llarp::path::PathContext paths; - llarp::exit::Context exitContext; - llarp::SecretKey identity; - llarp::SecretKey encryption; - llarp_threadpool *disk; - llarp_dht_context *dht = nullptr; + // long term identity key + fs::path ident_keyfile = "identity.key"; - llarp_nodedb *nodedb; + fs::path encryption_keyfile = "encryption.key"; - // buffer for serializing link messages - byte_t linkmsg_buffer[MAX_LINK_MSG_SIZE]; + // path to write our self signed rc to + fs::path our_rc_file = "rc.signed"; - /// always maintain this many connections to other routers - size_t minConnectedRouters = 1; - /// hard upperbound limit on the number of router to router connections - size_t maxConnectedRouters = 2000; + // our router contact + llarp::RouterContact _rc; - size_t minRequiredRouters = 4; + /// should we obey the service node whitelist? + bool whitelistRouters = false; - // should we be sending padded messages every interval? - bool sendPadding = false; + const llarp::RouterContact & + rc() const + { + return _rc; + } - uint32_t ticker_job_id = 0; + // our ipv4 public setting + bool publicOverride = false; + struct sockaddr_in ip4addr; + llarp::AddressInfo addrInfo; - llarp::InboundMessageParser inbound_link_msg_parser; - llarp::routing::InboundMessageParser inbound_routing_msg_parser; + llarp_ev_loop *netloop; + llarp_threadpool *tp; + llarp::Logic *logic; + llarp_crypto crypto; + llarp::path::PathContext paths; + llarp::exit::Context exitContext; + llarp::SecretKey identity; + llarp::SecretKey encryption; + llarp_threadpool *disk; + llarp_dht_context *dht = nullptr; - llarp::service::Context hiddenServiceContext; + llarp_nodedb *nodedb; - using NetConfig_t = std::unordered_multimap< std::string, std::string >; + // buffer for serializing link messages + byte_t linkmsg_buffer[MAX_LINK_MSG_SIZE]; - /// default network config for default network interface - NetConfig_t netConfig; + /// always maintain this many connections to other routers + size_t minConnectedRouters = 1; + /// hard upperbound limit on the number of router to router connections + size_t maxConnectedRouters = 2000; - /// identity keys whitelist of routers we will connect to directly (not for - /// service nodes) - std::set< llarp::RouterID > strictConnectPubkeys; + size_t minRequiredRouters = 4; - /// bootstrap RCs - std::list< llarp::RouterContact > bootstrapRCList; + // should we be sending padded messages every interval? + bool sendPadding = false; - bool - ExitEnabled() const - { - // TODO: use equal_range ? - auto itr = netConfig.find("exit"); - if(itr == netConfig.end()) - return false; - return llarp::IsTrueValue(itr->second.c_str()); - } + uint32_t ticker_job_id = 0; - bool - CreateDefaultHiddenService(); + llarp::InboundMessageParser inbound_link_msg_parser; + llarp::routing::InboundMessageParser inbound_routing_msg_parser; - const std::string DefaultRPCBindAddr = "127.0.0.1:1190"; - bool enableRPCServer = true; - std::unique_ptr< llarp::rpc::Server > rpcServer; - std::string rpcBindAddr = DefaultRPCBindAddr; + llarp::service::Context hiddenServiceContext; - /// lokid caller - const std::string DefaultLokidRPCAddr = "127.0.0.1:22023"; - std::unique_ptr< llarp::rpc::Caller > rpcCaller; - std::string lokidRPCAddr = DefaultLokidRPCAddr; + using NetConfig_t = std::unordered_multimap< std::string, std::string >; - std::unique_ptr< llarp::ILinkLayer > outboundLink; - std::vector< std::unique_ptr< llarp::ILinkLayer > > inboundLinks; + /// default network config for default network interface + NetConfig_t netConfig; - llarp::Profiling routerProfiling; - std::string routerProfilesFile = "profiles.dat"; + /// identity keys whitelist of routers we will connect to directly (not for + /// service nodes) + std::set< llarp::RouterID > strictConnectPubkeys; - using MessageQueue = std::queue< std::vector< byte_t > >; + /// bootstrap RCs + std::list< llarp::RouterContact > bootstrapRCList; - /// outbound message queue - std::unordered_map< llarp::RouterID, MessageQueue, llarp::RouterID::Hash > - outboundMessageQueue; + bool + ExitEnabled() const + { + // TODO: use equal_range ? + auto itr = netConfig.find("exit"); + if(itr == netConfig.end()) + return false; + return llarp::IsTrueValue(itr->second.c_str()); + } - /// loki verified routers - std::unordered_map< llarp::RouterID, llarp::RouterContact, - llarp::RouterID::Hash > - validRouters; + bool + CreateDefaultHiddenService(); - // pending establishing session with routers - std::unordered_map< llarp::RouterID, std::unique_ptr< TryConnectJob >, - llarp::RouterID::Hash > - pendingEstablishJobs; + const std::string DefaultRPCBindAddr = "127.0.0.1:1190"; + bool enableRPCServer = true; + std::unique_ptr< llarp::rpc::Server > rpcServer; + std::string rpcBindAddr = DefaultRPCBindAddr; - // pending RCs to be verified by pubkey - std::unordered_map< llarp::RouterID, llarp_async_verify_rc, - llarp::RouterID::Hash > - pendingVerifyRC; + /// lokid caller + const std::string DefaultLokidRPCAddr = "127.0.0.1:22023"; + std::unique_ptr< llarp::rpc::Caller > rpcCaller; + std::string lokidRPCAddr = DefaultLokidRPCAddr; - // sessions to persist -> timestamp to end persist at - std::unordered_map< llarp::RouterID, llarp_time_t, llarp::RouterID::Hash > - m_PersistingSessions; + std::unique_ptr< llarp::ILinkLayer > outboundLink; + std::vector< std::unique_ptr< llarp::ILinkLayer > > inboundLinks; - // lokinet routers from lokid, maps pubkey to when we think it will expire, - // set to max value right now - std::unordered_map< llarp::RouterID, llarp_time_t, llarp::RouterID::Hash > - lokinetRouters; + llarp::Profiling routerProfiling; + std::string routerProfilesFile = "profiles.dat"; - llarp_router(); - ~llarp_router(); + using MessageQueue = std::queue< std::vector< byte_t > >; - void - HandleLinkSessionEstablished(llarp::RouterContact, llarp::ILinkLayer *); + /// outbound message queue + std::unordered_map< llarp::RouterID, MessageQueue, llarp::RouterID::Hash > + outboundMessageQueue; - bool - HandleRecvLinkMessageBuffer(llarp::ILinkSession *from, llarp_buffer_t msg); + /// loki verified routers + std::unordered_map< llarp::RouterID, llarp::RouterContact, + llarp::RouterID::Hash > + validRouters; - void - AddInboundLink(std::unique_ptr< llarp::ILinkLayer > &link); + // pending establishing session with routers + std::unordered_map< llarp::RouterID, std::unique_ptr< TryConnectJob >, + llarp::RouterID::Hash > + pendingEstablishJobs; - bool - InitOutboundLink(); + // pending RCs to be verified by pubkey + std::unordered_map< llarp::RouterID, llarp_async_verify_rc, + llarp::RouterID::Hash > + pendingVerifyRC; - /// initialize us as a service node - /// return true on success - bool - InitServiceNode(); + // sessions to persist -> timestamp to end persist at + std::unordered_map< llarp::RouterID, llarp_time_t, llarp::RouterID::Hash > + m_PersistingSessions; - /// return true if we are running in service node mode - bool - IsServiceNode() const; + // lokinet routers from lokid, maps pubkey to when we think it will expire, + // set to max value right now + std::unordered_map< llarp::RouterID, llarp_time_t, llarp::PubKey::Hash > + lokinetRouters; - void - Close(); + Router(struct llarp_threadpool *tp, struct llarp_ev_loop *netloop, + llarp::Logic *logic); - bool - LoadHiddenServiceConfig(const char *fname); + ~Router(); - bool - AddHiddenService(const llarp::service::Config::section_t &config); + void + HandleLinkSessionEstablished(llarp::RouterContact, llarp::ILinkLayer *); - bool - Ready(); + bool + HandleRecvLinkMessageBuffer(llarp::ILinkSession *from, llarp_buffer_t msg); - bool - Run(); + void + AddInboundLink(std::unique_ptr< llarp::ILinkLayer > &link); - void - PersistSessionUntil(const llarp::RouterID &remote, llarp_time_t until); + bool + InitOutboundLink(); - bool - EnsureIdentity(); + /// initialize us as a service node + /// return true on success + bool + InitServiceNode(); - bool - EnsureEncryptionKey(); + /// return true if we are running in service node mode + bool + IsServiceNode() const; - bool - ConnectionToRouterAllowed(const llarp::RouterID &router) const; + void + Close(); - bool - SaveRC(); + bool + LoadHiddenServiceConfig(const char *fname); - const byte_t * - pubkey() const - { - return llarp::seckey_topublic(identity); - } - - void - OnConnectTimeout(const llarp::RouterID &remote); + bool + AddHiddenService(const llarp::service::Config::section_t &config); - bool - HasPendingConnectJob(const llarp::RouterID &remote); + bool + Configure(struct llarp_config *conf); - void - try_connect(fs::path rcfile); + bool + Ready(); - bool - ReloadConfig(const llarp_config *conf); + bool + Run(struct llarp_nodedb *nodedb); - /// send to remote router or queue for sending - /// returns false on overflow - /// returns true on successful queue - /// NOT threadsafe - /// MUST be called in the logic thread - bool - SendToOrQueue(const llarp::RouterID &remote, const llarp::ILinkMessage *msg); + void + Stop(); - /// sendto or drop - void - SendTo(llarp::RouterID remote, const llarp::ILinkMessage *msg, - llarp::ILinkLayer *chosen); + void + PersistSessionUntil(const llarp::RouterID &remote, llarp_time_t until); - /// manually flush outbound message queue for just 1 router - void - FlushOutboundFor(llarp::RouterID remote, llarp::ILinkLayer *chosen = nullptr); + bool + EnsureIdentity(); - /// manually discard all pending messages to remote router - void - DiscardOutboundFor(const llarp::RouterID &remote); + bool + EnsureEncryptionKey(); - /// try establishing a session to a remote router - void - TryEstablishTo(const llarp::RouterID &remote); + bool + ConnectionToRouterAllowed(const llarp::RouterID &router) const; - void - HandleDHTLookupForExplore(llarp::RouterID remote, - const std::vector< llarp::RouterContact > &results); + bool + SaveRC(); - void - ForEachPeer( - std::function< void(const llarp::ILinkSession *, bool) > visit) const; + const byte_t * + pubkey() const + { + return llarp::seckey_topublic(identity); + } - /// flush outbound message queue - void - FlushOutbound(); + void + OnConnectTimeout(const llarp::RouterID &remote); - /// called by link when a remote session is expunged - void - SessionClosed(const llarp::RouterID &remote); + bool + HasPendingConnectJob(const llarp::RouterID &remote); - /// call internal router ticker - void - Tick(); + void + try_connect(fs::path rcfile); - /// get time from event loop - llarp_time_t - Now() const - { - return llarp_ev_loop_time_now_ms(netloop); - } + bool + ReloadConfig(const llarp_config *conf); - /// schedule ticker to call i ms from now - void - ScheduleTicker(uint64_t i = 1000); + /// send to remote router or queue for sending + /// returns false on overflow + /// returns true on successful queue + /// NOT threadsafe + /// MUST be called in the logic thread + bool + SendToOrQueue(const llarp::RouterID &remote, + const llarp::ILinkMessage *msg); - llarp::ILinkLayer * - GetLinkWithSessionByPubkey(const llarp::RouterID &remote); + /// sendto or drop + void + SendTo(llarp::RouterID remote, const llarp::ILinkMessage *msg, + llarp::ILinkLayer *chosen); - void - ConnectToRandomRouters(int N); + /// manually flush outbound message queue for just 1 router + void + FlushOutboundFor(llarp::RouterID remote, + llarp::ILinkLayer *chosen = nullptr); - size_t - NumberOfConnectedRouters() const; + /// manually discard all pending messages to remote router + void + DiscardOutboundFor(const llarp::RouterID &remote); - bool - GetRandomConnectedRouter(llarp::RouterContact &result) const; + /// try establishing a session to a remote router + void + TryEstablishTo(const llarp::RouterID &remote); - void - async_verify_RC(const llarp::RouterContact &rc, llarp::ILinkLayer *link); + void + HandleDHTLookupForExplore( + llarp::RouterID remote, + const std::vector< llarp::RouterContact > &results); - void - HandleDHTLookupForSendTo(llarp::RouterID remote, - const std::vector< llarp::RouterContact > &results); + void + ForEachPeer( + std::function< void(const llarp::ILinkSession *, bool) > visit) const; - bool - HasSessionTo(const llarp::RouterID &remote) const; + /// flush outbound message queue + void + FlushOutbound(); - void - HandleDHTLookupForTryEstablishTo( - llarp::RouterID remote, - const std::vector< llarp::RouterContact > &results); + /// called by link when a remote session is expunged + void + SessionClosed(const llarp::RouterID &remote); - static void - on_verify_client_rc(llarp_async_verify_rc *context); + /// call internal router ticker + void + Tick(); - static void - on_verify_server_rc(llarp_async_verify_rc *context); + /// get time from event loop + llarp_time_t + Now() const + { + return llarp_ev_loop_time_now_ms(netloop); + } - static void - handle_router_ticker(void *user, uint64_t orig, uint64_t left); + /// schedule ticker to call i ms from now + void + ScheduleTicker(uint64_t i = 1000); - static void - HandleAsyncLoadRCForSendTo(llarp_async_load_rc *async); + llarp::ILinkLayer * + GetLinkWithSessionByPubkey(const llarp::RouterID &remote); - private: - template < typename Config > - void - mergeHiddenServiceConfig(const Config &in, Config &out) - { - for(const auto &item : netConfig) - out.push_back({item.first, item.second}); - for(const auto &item : in) - out.push_back({item.first, item.second}); - } -}; + void + ConnectToRandomRouters(int N); + + size_t + NumberOfConnectedRouters() const; + + bool + GetRandomConnectedRouter(llarp::RouterContact &result) const; + + void + async_verify_RC(const llarp::RouterContact &rc, llarp::ILinkLayer *link); + + void + HandleDHTLookupForSendTo( + llarp::RouterID remote, + const std::vector< llarp::RouterContact > &results); + + bool + HasSessionTo(const llarp::RouterID &remote) const; + + void + HandleDHTLookupForTryEstablishTo( + llarp::RouterID remote, + const std::vector< llarp::RouterContact > &results); + + static void + on_verify_client_rc(llarp_async_verify_rc *context); + + static void + on_verify_server_rc(llarp_async_verify_rc *context); + + static void + handle_router_ticker(void *user, uint64_t orig, uint64_t left); + + static void + HandleAsyncLoadRCForSendTo(llarp_async_load_rc *async); + + private: + template < typename Config > + void + mergeHiddenServiceConfig(const Config &in, Config &out) + { + for(const auto &item : netConfig) + out.push_back({item.first, item.second}); + for(const auto &item : in) + out.push_back({item.first, item.second}); + } + }; + +} // namespace llarp #endif diff --git a/llarp/routing/dht_message.cpp b/llarp/routing/dht_message.cpp index 2a601b55b..5ceacf14d 100644 --- a/llarp/routing/dht_message.cpp +++ b/llarp/routing/dht_message.cpp @@ -48,7 +48,7 @@ namespace llarp } bool - DHTMessage::HandleMessage(IMessageHandler* h, llarp_router* r) const + DHTMessage::HandleMessage(IMessageHandler* h, llarp::Router* r) const { // set source as us llarp::dht::Key_t us = r->pubkey(); diff --git a/llarp/routing/message_parser.cpp b/llarp/routing/message_parser.cpp index 4f9b46d57..07c1c5d07 100644 --- a/llarp/routing/message_parser.cpp +++ b/llarp/routing/message_parser.cpp @@ -94,7 +94,7 @@ namespace llarp InboundMessageParser::ParseMessageBuffer(llarp_buffer_t buf, IMessageHandler* h, const PathID_t& from, - llarp_router* r) + llarp::Router* r) { bool result = false; msg = nullptr; diff --git a/llarp/routing/path_confirm.cpp b/llarp/routing/path_confirm.cpp index b7752e016..caa95612d 100644 --- a/llarp/routing/path_confirm.cpp +++ b/llarp/routing/path_confirm.cpp @@ -51,7 +51,7 @@ namespace llarp } bool - PathConfirmMessage::HandleMessage(IMessageHandler* h, llarp_router* r) const + PathConfirmMessage::HandleMessage(IMessageHandler* h, llarp::Router* r) const { return h && h->HandlePathConfirmMessage(this, r); } diff --git a/llarp/routing/path_latency.cpp b/llarp/routing/path_latency.cpp index 07b9cc322..6da1b8abd 100644 --- a/llarp/routing/path_latency.cpp +++ b/llarp/routing/path_latency.cpp @@ -45,10 +45,10 @@ namespace llarp } bool - PathLatencyMessage::HandleMessage(IMessageHandler* h, llarp_router* r) const + PathLatencyMessage::HandleMessage(IMessageHandler* h, llarp::Router* r) const { return h && h->HandlePathLatencyMessage(this, r); } } // namespace routing -} // namespace llarp \ No newline at end of file +} // namespace llarp diff --git a/llarp/routing/path_transfer.cpp b/llarp/routing/path_transfer.cpp index ad87a8039..8156089e2 100644 --- a/llarp/routing/path_transfer.cpp +++ b/llarp/routing/path_transfer.cpp @@ -57,7 +57,7 @@ namespace llarp bool PathTransferMessage::HandleMessage(IMessageHandler* h, - llarp_router* r) const + llarp::Router* r) const { return h->HandlePathTransferMessage(this, r); } diff --git a/llarp/rpc.cpp b/llarp/rpc.cpp index 832e909f5..de384173d 100644 --- a/llarp/rpc.cpp +++ b/llarp/rpc.cpp @@ -1,6 +1,5 @@ #include -#include "router.hpp" #ifdef USE_ABYSS #include #endif @@ -110,12 +109,12 @@ namespace llarp struct CallerImpl : public ::abyss::http::JSONRPC { - llarp_router* router; + llarp::Router* router; llarp_time_t m_NextKeyUpdate; const llarp_time_t KeyUpdateInterval = 1000 * 60 * 2; using PubkeyList_t = GetServiceNodeListHandler::PubkeyList_t; - CallerImpl(llarp_router* r) : ::abyss::http::JSONRPC(), router(r) + CallerImpl(llarp::Router* r) : ::abyss::http::JSONRPC(), router(r) { } @@ -179,8 +178,8 @@ namespace llarp struct Handler : public ::abyss::httpd::IRPCHandler { - llarp_router* router; - Handler(::abyss::httpd::ConnImpl* conn, llarp_router* r) + llarp::Router* router; + Handler(::abyss::httpd::ConnImpl* conn, llarp::Router* r) : ::abyss::httpd::IRPCHandler(conn), router(r) { } @@ -259,11 +258,11 @@ namespace llarp struct ReqHandlerImpl : public ::abyss::httpd::BaseReqHandler { - ReqHandlerImpl(llarp_router* r, llarp_time_t reqtimeout) + ReqHandlerImpl(llarp::Router* r, llarp_time_t reqtimeout) : ::abyss::httpd::BaseReqHandler(reqtimeout), router(r) { } - llarp_router* router; + llarp::Router* router; ::abyss::httpd::IRPCHandler* CreateHandler(::abyss::httpd::ConnImpl* conn) { @@ -273,10 +272,10 @@ namespace llarp struct ServerImpl { - llarp_router* router; + llarp::Router* router; ReqHandlerImpl _handler; - ServerImpl(llarp_router* r) : router(r), _handler(r, 2000) + ServerImpl(llarp::Router* r) : router(r), _handler(r, 2000) { } @@ -306,7 +305,7 @@ namespace llarp #else struct ServerImpl { - ServerImpl(__attribute__((unused)) llarp_router* r){}; + ServerImpl(__attribute__((unused)) llarp::Router* r){}; bool Start(__attribute__((unused)) const std::string& addr) @@ -317,7 +316,7 @@ namespace llarp struct CallerImpl { - CallerImpl(__attribute__((unused)) llarp_router* r) + CallerImpl(__attribute__((unused)) llarp::Router* r) { } @@ -340,7 +339,7 @@ namespace llarp #endif - Caller::Caller(llarp_router* r) : m_Impl(new CallerImpl(r)) + Caller::Caller(llarp::Router* r) : m_Impl(new CallerImpl(r)) { } @@ -361,7 +360,7 @@ namespace llarp m_Impl->Tick(now); } - Server::Server(llarp_router* r) : m_Impl(new ServerImpl(r)) + Server::Server(llarp::Router* r) : m_Impl(new ServerImpl(r)) { } diff --git a/llarp/service.cpp b/llarp/service.cpp index 68d03ccda..5f3522512 100644 --- a/llarp/service.cpp +++ b/llarp/service.cpp @@ -2,7 +2,6 @@ #include "buffer.hpp" #include "fs.hpp" #include "ini.hpp" -#include "router.hpp" namespace llarp { diff --git a/llarp/service/context.cpp b/llarp/service/context.cpp index 1464deebf..4ef303b4b 100644 --- a/llarp/service/context.cpp +++ b/llarp/service/context.cpp @@ -2,13 +2,12 @@ #include #include #include -#include "router.hpp" namespace llarp { namespace service { - Context::Context(llarp_router *r) : m_Router(r) + Context::Context(llarp::Router *r) : m_Router(r) { } @@ -229,16 +228,16 @@ namespace llarp static std::map< std::string, std::function< llarp::service::Endpoint *( - const std::string &, llarp_router *) > > + const std::string &, llarp::Router *) > > endpointConstructors = { {"tun", [](const std::string &nick, - llarp_router *r) -> llarp::service::Endpoint * { + llarp::Router *r) -> llarp::service::Endpoint * { return new llarp::handlers::TunEndpoint(nick, r); }}, {"null", [](const std::string &nick, - llarp_router *r) -> llarp::service::Endpoint * { + llarp::Router *r) -> llarp::service::Endpoint * { return new llarp::handlers::NullEndpoint(nick, r); }}}; diff --git a/llarp/service/endpoint.cpp b/llarp/service/endpoint.cpp index 64a12d8f0..8deea4d85 100644 --- a/llarp/service/endpoint.cpp +++ b/llarp/service/endpoint.cpp @@ -1,5 +1,6 @@ #include +#include #include #include #include @@ -10,7 +11,7 @@ namespace llarp { namespace service { - Endpoint::Endpoint(const std::string& name, llarp_router* r) + Endpoint::Endpoint(const std::string& name, llarp::Router* r) : path::Builder(r, r->dht, 6, 4), m_Router(r), m_Name(name) { m_Tag.Zero(); @@ -513,7 +514,7 @@ namespace llarp } bool - Endpoint::PublishIntroSet(llarp_router* r) + Endpoint::PublishIntroSet(llarp::Router* r) { // publish via near router RouterID location = m_Identity.pub.Addr().data(); @@ -561,7 +562,7 @@ namespace llarp } bool - Endpoint::PublishIntroSetVia(llarp_router* r, path::Path* path) + Endpoint::PublishIntroSetVia(llarp::Router* r, path::Path* path) { auto job = new PublishIntroSetJob(this, GenTXID(), m_IntroSet); if(job->SendRequestViaPath(path, r)) diff --git a/llarp/service/lookup.cpp b/llarp/service/lookup.cpp index 4e7b7d514..0a00c80fa 100644 --- a/llarp/service/lookup.cpp +++ b/llarp/service/lookup.cpp @@ -16,7 +16,7 @@ namespace llarp } bool - IServiceLookup::SendRequestViaPath(llarp::path::Path *path, llarp_router *r) + IServiceLookup::SendRequestViaPath(llarp::path::Path *path, llarp::Router *r) { auto msg = BuildRequestMessage(); if(!msg) diff --git a/llarp/service/protocol.cpp b/llarp/service/protocol.cpp index 5af7783ce..d343862e7 100644 --- a/llarp/service/protocol.cpp +++ b/llarp/service/protocol.cpp @@ -1,3 +1,4 @@ +#include #include #include #include "buffer.hpp" @@ -384,7 +385,7 @@ namespace llarp bool ProtocolFrame::HandleMessage(llarp::routing::IMessageHandler* h, - __attribute__((unused)) llarp_router* r) const + __attribute__((unused)) llarp::Router* r) const { return h->HandleHiddenServiceFrame(this); } diff --git a/llarp/transit_hop.cpp b/llarp/transit_hop.cpp index 9337a73d8..246edec8f 100644 --- a/llarp/transit_hop.cpp +++ b/llarp/transit_hop.cpp @@ -53,7 +53,7 @@ namespace llarp bool TransitHop::SendRoutingMessage(const llarp::routing::IMessage* msg, - llarp_router* r) + llarp::Router* r) { if(!IsEndpoint(r->pubkey())) return false; @@ -82,7 +82,7 @@ namespace llarp bool TransitHop::HandleDownstream(llarp_buffer_t buf, const TunnelNonce& Y, - llarp_router* r) + llarp::Router* r) { RelayDownstreamMessage msg; msg.pathid = info.rxID; @@ -96,7 +96,7 @@ namespace llarp bool TransitHop::HandleUpstream(llarp_buffer_t buf, const TunnelNonce& Y, - llarp_router* r) + llarp::Router* r) { r->crypto.xchacha20(buf, pathKey, Y); if(IsEndpoint(r->pubkey())) @@ -118,14 +118,14 @@ namespace llarp bool TransitHop::HandleDHTMessage(const llarp::dht::IMessage* msg, - llarp_router* r) + llarp::Router* r) { return r->dht->impl.RelayRequestForPath(info.rxID, msg); } bool TransitHop::HandlePathLatencyMessage( - const llarp::routing::PathLatencyMessage* msg, llarp_router* r) + const llarp::routing::PathLatencyMessage* msg, llarp::Router* r) { llarp::routing::PathLatencyMessage reply; reply.L = msg->T; @@ -135,7 +135,7 @@ namespace llarp bool TransitHop::HandlePathConfirmMessage( __attribute__((unused)) const llarp::routing::PathConfirmMessage* msg, - __attribute__((unused)) llarp_router* r) + __attribute__((unused)) llarp::Router* r) { llarp::LogWarn("unwarranted path confirm message on ", info); return false; @@ -144,7 +144,7 @@ namespace llarp bool TransitHop::HandleDataDiscardMessage( __attribute__((unused)) const llarp::routing::DataDiscardMessage* msg, - __attribute__((unused)) llarp_router* r) + __attribute__((unused)) llarp::Router* r) { llarp::LogWarn("unwarranted path data discard message on ", info); return false; @@ -152,7 +152,7 @@ namespace llarp bool TransitHop::HandleObtainExitMessage( - const llarp::routing::ObtainExitMessage* msg, llarp_router* r) + const llarp::routing::ObtainExitMessage* msg, llarp::Router* r) { if(msg->Verify(&r->crypto) && r->exitContext.ObtainNewExit(msg->I, info.rxID, msg->E != 0)) @@ -182,7 +182,7 @@ namespace llarp bool TransitHop::HandleCloseExitMessage( - const llarp::routing::CloseExitMessage* msg, llarp_router* r) + const llarp::routing::CloseExitMessage* msg, llarp::Router* r) { llarp::routing::DataDiscardMessage discard(info.rxID, msg->S); auto ep = r->exitContext.FindEndpointForPath(info.rxID); @@ -200,7 +200,7 @@ namespace llarp bool TransitHop::HandleUpdateExitVerifyMessage( - const llarp::routing::UpdateExitVerifyMessage* msg, llarp_router* r) + const llarp::routing::UpdateExitVerifyMessage* msg, llarp::Router* r) { (void)msg; (void)r; @@ -210,7 +210,7 @@ namespace llarp bool TransitHop::HandleUpdateExitMessage( - const llarp::routing::UpdateExitMessage* msg, llarp_router* r) + const llarp::routing::UpdateExitMessage* msg, llarp::Router* r) { auto ep = r->exitContext.FindEndpointForPath(msg->P); if(ep) @@ -233,7 +233,7 @@ namespace llarp bool TransitHop::HandleRejectExitMessage( - const llarp::routing::RejectExitMessage* msg, llarp_router* r) + const llarp::routing::RejectExitMessage* msg, llarp::Router* r) { (void)msg; (void)r; @@ -243,7 +243,7 @@ namespace llarp bool TransitHop::HandleGrantExitMessage( - const llarp::routing::GrantExitMessage* msg, llarp_router* r) + const llarp::routing::GrantExitMessage* msg, llarp::Router* r) { (void)msg; (void)r; @@ -253,7 +253,7 @@ namespace llarp bool TransitHop::HandleTransferTrafficMessage( - const llarp::routing::TransferTrafficMessage* msg, llarp_router* r) + const llarp::routing::TransferTrafficMessage* msg, llarp::Router* r) { auto endpoint = r->exitContext.FindEndpointForPath(info.rxID); if(endpoint) @@ -279,7 +279,7 @@ namespace llarp bool TransitHop::HandlePathTransferMessage( - const llarp::routing::PathTransferMessage* msg, llarp_router* r) + const llarp::routing::PathTransferMessage* msg, llarp::Router* r) { auto path = r->paths.GetPathForTransfer(msg->P); llarp::routing::DataDiscardMessage discarded(msg->P, msg->S); diff --git a/test/exit_unittest.cpp b/test/exit_unittest.cpp index 06b12eac6..1179cbb53 100644 --- a/test/exit_unittest.cpp +++ b/test/exit_unittest.cpp @@ -1,16 +1,13 @@ #include #include -#include "router.hpp" +#include struct ExitTest : public ::testing::Test { - ExitTest() + ExitTest() : r(nullptr, nullptr, nullptr) { - llarp_crypto_init(&r.crypto); - r.netloop = nullptr; // only windows uses defined sentinel values in - // uninitialised blocks } - llarp_router r; + llarp::Router r; }; TEST_F(ExitTest, AddMultipleIP) @@ -29,4 +26,4 @@ TEST_F(ExitTest, AddMultipleIP) ASSERT_TRUE(r.exitContext.ObtainNewExit(pk, secondPath, true)); ASSERT_TRUE(r.exitContext.FindEndpointForPath(firstPath)->LocalIP() == r.exitContext.FindEndpointForPath(secondPath)->LocalIP()); -}; \ No newline at end of file +};