diff --git a/.travis.yml b/.travis.yml index ff4ccdb96..192bd8b7d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -44,6 +44,10 @@ matrix: os: osx osx_image: xcode10.2 env: BUILD_TYPE=Release PATH="/usr/local/opt/ccache/libexec:$PATH" + - name: "make iOS" + os: osx + osx_image: xcode10.2 + env: MAKE_TARGET=ios PATH="/usr/local/opt/ccache/libexec:$PATH" - name: "make windows (macOS)" os: osx osx_image: xcode10.2 diff --git a/CMakeLists.txt b/CMakeLists.txt index 71882d928..8d03b7099 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -42,22 +42,7 @@ endif() list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake") -# Basic definitions -set(LIB lokinet) -set(SHARED_LIB ${LIB}-shared) -set(STATIC_LIB ${LIB}-static) -set(CRYPTOGRAPHY_LIB ${LIB}-cryptography) -set(UTIL_LIB ${LIB}-util) -set(PLATFORM_LIB ${LIB}-platform) -set(ANDROID_LIB ${LIB}android) -set(ABYSS libabyss) -set(ABYSS_LIB abyss) -set(ABYSS_EXE ${ABYSS_LIB}-main) -get_filename_component(TT_ROOT "vendor/libtuntap-master" ABSOLUTE) -add_definitions(-D${CMAKE_SYSTEM_NAME}) - -get_filename_component(CORE_INCLUDE "${CMAKE_CURRENT_SOURCE_DIR}/include" ABSOLUTE) -get_filename_component(ABYSS_INCLUDE "${CMAKE_CURRENT_SOURCE_DIR}/${ABYSS}/include" ABSOLUTE) +include(cmake/basic_definitions.cmake) if(MSVC_VERSION) enable_language(ASM_MASM) @@ -211,7 +196,7 @@ if(NOT GIT_VERSION) string(STRIP "${GIT_VERSION_UNSTRIP}" GIT_VERSION) endif(NOT GIT_VERSION) -string(REGEX REPLACE ^fatal.*$ nogit GIT_VERSION_REAL "${GIT_VERSION}") +string(REGEX REPLACE "^fatal.*$" nogit GIT_VERSION_REAL "${GIT_VERSION}") add_definitions("-DGIT_REV=\"${GIT_VERSION_REAL}\"") set(EXE lokinet) diff --git a/Makefile b/Makefile index 4fd99230d..816ac81e2 100644 --- a/Makefile +++ b/Makefile @@ -208,6 +208,10 @@ $(LIBUV_PREFIX): mkdir -p $(BUILD_ROOT) git clone -b "$(LIBUV_VERSION)" https://github.com/libuv/libuv "$(LIBUV_PREFIX)" +ios: + cmake -S ui-ios -B build -G Xcode -DCMAKE_TOOLCHAIN_FILE=$(shell pwd)/ui-ios/ios-toolchain.cmake -DCMAKE_SYSTEM_NAME=iOS "-DCMAKE_OSX_ARCHITECTURES=arm64;x86_64" -DCMAKE_OSX_DEPLOYMENT_TARGET=12.2 -DCMAKE_XCODE_ATTRIBUTE_ONLY_ACTIVE_ARCH=NO -DCMAKE_IOS_INSTALL_COMBINED=YES + cmake --build build + android-gradle-prepare: $(LIBUV_PREFIX) rm -f $(ANDROID_PROPS) rm -f $(ANDROID_LOCAL_PROPS) diff --git a/cmake/basic_definitions.cmake b/cmake/basic_definitions.cmake new file mode 100644 index 000000000..d89364363 --- /dev/null +++ b/cmake/basic_definitions.cmake @@ -0,0 +1,16 @@ +# Basic definitions +set(LIB lokinet) +set(SHARED_LIB ${LIB}-shared) +set(STATIC_LIB ${LIB}-static) +set(CRYPTOGRAPHY_LIB ${LIB}-cryptography) +set(UTIL_LIB ${LIB}-util) +set(PLATFORM_LIB ${LIB}-platform) +set(ANDROID_LIB ${LIB}android) +set(ABYSS libabyss) +set(ABYSS_LIB abyss) +set(ABYSS_EXE ${ABYSS_LIB}-main) +get_filename_component(TT_ROOT "vendor/libtuntap-master" ABSOLUTE) +add_definitions(-D${CMAKE_SYSTEM_NAME}) + +get_filename_component(CORE_INCLUDE "${CMAKE_CURRENT_SOURCE_DIR}/include" ABSOLUTE) +get_filename_component(ABYSS_INCLUDE "${CMAKE_CURRENT_SOURCE_DIR}/${ABYSS}/include" ABSOLUTE) diff --git a/cmake/unix.cmake b/cmake/unix.cmake index 817adc79f..3d437f159 100644 --- a/cmake/unix.cmake +++ b/cmake/unix.cmake @@ -18,7 +18,7 @@ if(LIBUV_ROOT) set(LIBUV_LIBRARY uv_a) add_definitions(-D_LARGEFILE_SOURCE) add_definitions(-D_FILE_OFFSET_BITS=64) -else() +elseif(NOT LIBUV_IN_SOURCE) find_package(LibUV 1.28.0 REQUIRED) endif() @@ -46,7 +46,7 @@ elseif (${CMAKE_SYSTEM_NAME} MATCHES "NetBSD") elseif (${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD" OR ${CMAKE_SYSTEM_NAME} MATCHES "DragonFly") find_library(FS_LIB NAMES c++experimental) set(LIBTUNTAP_IMPL ${TT_ROOT}/tuntap-unix-freebsd.c ${TT_ROOT}/tuntap-unix-bsd.c) -elseif (${CMAKE_SYSTEM_NAME} MATCHES "Darwin") +elseif (${CMAKE_SYSTEM_NAME} MATCHES "Darwin" OR ${CMAKE_SYSTEM_NAME} MATCHES "iOS") find_library(FS_LIB NAMES c++fs c++experimental stdc++fs) if(FS_LIB STREQUAL FS_LIB-NOTFOUND) include_directories("${CMAKE_CURRENT_LIST_DIR}/../vendor/cppbackport-master/lib") @@ -69,7 +69,7 @@ elseif (${CMAKE_SYSTEM_NAME} MATCHES "SunOS") set(FS_LIB stdc++fs) endif() else() - message(FATAL_ERROR "Your operating system is not supported yet") + message(FATAL_ERROR "Your operating system - ${CMAKE_SYSTEM_NAME} is not supported yet") endif() diff --git a/contrib/cross/mingw.cmake b/contrib/cross/mingw.cmake index 0a591fb53..94221affd 100644 --- a/contrib/cross/mingw.cmake +++ b/contrib/cross/mingw.cmake @@ -1,6 +1,6 @@ set(CMAKE_SYSTEM_NAME Windows) set(TOOLCHAIN_PREFIX x86_64-w64-mingw32) -set(TOOLCHAIN_SUFFIX "") +set(TOOLCHAIN_SUFFIX "-posix") set(WIN64_CROSS_COMPILE ON) set(TOOLCHAIN_PATHS diff --git a/daemon/main.cpp b/daemon/main.cpp index d2a489e0e..61aa78440 100644 --- a/daemon/main.cpp +++ b/daemon/main.cpp @@ -1,4 +1,5 @@ #include // for ensure_config +#include #include #include #include @@ -13,6 +14,7 @@ #include #include #include +#include #ifdef _WIN32 #define wmin(x, y) (((x) < (y)) ? (x) : (y)) @@ -84,12 +86,12 @@ resolvePath(std::string conffname) /// this sets up, configures and runs the main context static void -run_main_context(std::string conffname, bool multiThreaded, bool debugMode) +run_main_context(std::string conffname, llarp_main_runtime_opts opts) { // this is important, can downgrade from Info though llarp::LogDebug("Running from: ", fs::current_path().string()); llarp::LogInfo("Using config file: ", conffname); - ctx = llarp_main_init(conffname.c_str(), multiThreaded); + ctx = llarp_main_init(conffname.c_str()); int code = 1; if(ctx) { @@ -98,10 +100,10 @@ run_main_context(std::string conffname, bool multiThreaded, bool debugMode) #ifndef _WIN32 signal(SIGHUP, handle_signal); #endif - code = llarp_main_setup(ctx, debugMode); + code = llarp_main_setup(ctx); llarp::util::SetThreadName("llarp-mainloop"); if(code == 0) - code = llarp_main_run(ctx); + code = llarp_main_run(ctx, opts); llarp_main_free(ctx); } exit_code.set_value(code); @@ -110,11 +112,11 @@ run_main_context(std::string conffname, bool multiThreaded, bool debugMode) int main(int argc, char *argv[]) { - bool multiThreaded = true; + llarp_main_runtime_opts opts; const char *singleThreadVar = getenv("LLARP_SHADOW"); if(singleThreadVar && std::string(singleThreadVar) == "1") { - multiThreaded = false; + opts.singleThreaded = true; } #ifdef _WIN32 @@ -136,22 +138,21 @@ main(int argc, char *argv[]) options.add_options() ("v,verbose", "Verbose", cxxopts::value()) ("h,help", "help", cxxopts::value()) + ("version", "version", cxxopts::value()) ("g,generate", "generate client config", cxxopts::value()) ("r,router", "generate router config", cxxopts::value()) ("f,force", "overwrite", cxxopts::value()) ("c,colour", "colour output", cxxopts::value()->default_value("true")) - ("d,debug", "debug mode - UNENCRYPTED TRAFFIC", cxxopts::value()) + ("b,background", "background mode (start, but do not connect to the network)", cxxopts::value()) ("config","path to configuration file", cxxopts::value()); options.parse_positional("config"); // clang-format on - bool genconfigOnly = false; - bool asRouter = false; - bool overWrite = false; - bool debugMode = false; + bool genconfigOnly = false; + bool asRouter = false; + bool overWrite = false; std::string conffname; // suggestions: confFName? conf_fname? - try { auto result = options.parse(argc, argv); @@ -174,14 +175,20 @@ main(int argc, char *argv[]) return 0; } + if(result.count("version")) + { + std::cout << llarp_version() << std::endl; + return 0; + } + if(result.count("generate") > 0) { genconfigOnly = true; } - if(result.count("debug") > 0) + if(result.count("background") > 0) { - debugMode = true; + opts.background = true; } if(result.count("force") > 0) @@ -313,7 +320,7 @@ main(int argc, char *argv[]) } std::thread main_thread{ - std::bind(&run_main_context, conffname, multiThreaded, debugMode)}; + std::bind(&run_main_context, conffname, opts)}; auto ftr = exit_code.get_future(); do { @@ -321,11 +328,9 @@ main(int argc, char *argv[]) } while(ftr.wait_for(std::chrono::seconds(1)) != std::future_status::ready); main_thread.join(); - + const auto code = ftr.get(); #ifdef _WIN32 ::WSACleanup(); #endif - const auto code = ftr.get(); - exit(code); return code; } diff --git a/include/llarp.h b/include/llarp.h index c1213d799..cb4bca0c2 100644 --- a/include/llarp.h +++ b/include/llarp.h @@ -1,6 +1,7 @@ #ifndef LLARP_H_ #define LLARP_H_ -#include +#include +#include #ifdef __cplusplus extern "C" { @@ -19,6 +20,14 @@ extern "C" /// llarp application context for C api struct llarp_main; + /// runtime options for main context from cli + struct llarp_main_runtime_opts + { + bool background = false; + bool debug = false; + bool singleThreaded = false; + }; + /// llarp_application config struct llarp_config; @@ -57,23 +66,24 @@ extern "C" { /// name of the network interface char ifname[64]; - /// interface's address - struct sockaddr_storage ifaddr; - /// interface's netmask - struct sockaddr_storage netmask; + /// interface's address as string + char ifaddr[128]; + /// netmask bits + unsigned char netmask; }; /// initialize llarp_vpn_io private implementation - void - llarp_vpn_io_init(struct llarp_vpn_io *io); + /// returns false if either parameter is nullptr + bool + llarp_vpn_io_init(struct llarp_main *m, struct llarp_vpn_io *io); /// get the packet pipe for writing IP packets to lokinet internals - /// can return nullptr + /// returns nullptr if llarp_vpn_io is nullptr or not initialized struct llarp_vpn_pkt_writer * llarp_vpn_io_packet_writer(struct llarp_vpn_io *io); /// get the packet pipe for reading IP packets from lokinet internals - /// can return nullptr + /// returns nullptr if llarp_vpn_io is nullptr or not initialized struct llarp_vpn_pkt_reader * llarp_vpn_io_packet_reader(struct llarp_vpn_io *io); @@ -107,18 +117,18 @@ extern "C" /// associated info tries to give the vpn io to endpoint with name epName a /// deferred call to llarp_vpn_io.injected is queued unconditionally /// thread safe - void + bool llarp_main_inject_vpn_by_name(struct llarp_main *m, const char *epName, struct llarp_vpn_io *io, struct llarp_vpn_ifaddr_info info); /// give main context a vpn io on its default endpoint - static void + static bool llarp_main_inject_default_vpn(struct llarp_main *m, struct llarp_vpn_io *io, struct llarp_vpn_ifaddr_info info) { - llarp_main_inject_vpn_by_name(m, llarp_main_get_default_endpoint_name(m), - io, info); + return llarp_main_inject_vpn_by_name( + m, llarp_main_get_default_endpoint_name(m), io, info); } /// load config from file by name @@ -131,13 +141,13 @@ extern "C" /// initialize application context and load config static struct llarp_main * - llarp_main_init(const char *fname, bool) + llarp_main_init(const char *fname) { - struct llarp_config *conf = NULL; + struct llarp_config *conf = 0; if(!llarp_config_load_file(fname, &conf)) - return NULL; + return 0; if(conf == NULL) - return NULL; + return 0; return llarp_main_init_from_config(conf); } @@ -147,8 +157,8 @@ extern "C" { struct llarp_config *conf; conf = llarp_default_config(); - if(conf == NULL) - return NULL; + if(conf == 0) + return 0; return llarp_main_init_from_config(conf); } @@ -158,16 +168,20 @@ extern "C" /// setup main context, returns 0 on success int - llarp_main_setup(struct llarp_main *ptr, bool debugMode); + llarp_main_setup(struct llarp_main *ptr); /// run main context, returns 0 on success, blocks until program end int - llarp_main_run(struct llarp_main *ptr); + llarp_main_run(struct llarp_main *ptr, struct llarp_main_runtime_opts opts); /// free main context and end all operations void llarp_main_free(struct llarp_main *ptr); + /// get version string + const char * + llarp_version(); + #ifdef __cplusplus } #endif diff --git a/include/llarp.hpp b/include/llarp.hpp index d380350eb..a630708e2 100644 --- a/include/llarp.hpp +++ b/include/llarp.hpp @@ -1,6 +1,6 @@ #ifndef LLARP_HPP #define LLARP_HPP - +#include #include #include #include @@ -43,6 +43,10 @@ namespace llarp struct Context { + /// get context from main pointer + static Context * + Get(llarp_main *); + Context(); ~Context(); @@ -72,23 +76,23 @@ namespace llarp LoadDatabase(); int - IterateDatabase(llarp_nodedb_iter &i); - - bool - PutDatabase(struct llarp::RouterContact &rc); - - llarp::RouterContact * - GetDatabase(const byte_t *pk); - - int - Setup(bool debug = false); + Setup(); int - Run(); + Run(llarp_main_runtime_opts opts); void HandleSignal(int sig); + bool + Configure(); + + /// call a function in logic thread + /// return true if queued for calling + /// return false if not queued for calling + bool + CallSafe(std::function< void(void) > f); + private: void SetPIDFile(const std::string &fname); @@ -99,9 +103,6 @@ namespace llarp void RemovePIDFile() const; - bool - Configure(); - void SigINT(); @@ -119,7 +120,4 @@ namespace llarp }; } // namespace llarp -llarp::Context * -llarp_main_get_context(llarp_main *m); - #endif diff --git a/include/tuntap.h b/include/tuntap.h index 6cc444a70..5981793f6 100644 --- a/include/tuntap.h +++ b/include/tuntap.h @@ -42,6 +42,8 @@ #endif #if defined Linux #include +#elif defined(iOS) +#include #else #include #endif diff --git a/llarp/CMakeLists.txt b/llarp/CMakeLists.txt index 264e90ed3..9dc9510a8 100644 --- a/llarp/CMakeLists.txt +++ b/llarp/CMakeLists.txt @@ -78,6 +78,7 @@ set(LIB_PLATFORM_SRC # for networking ev/ev.cpp ev/pipe.cpp + ev/vpnio.cpp net/ip.cpp net/net.cpp net/net_addr.cpp diff --git a/llarp/context.cpp b/llarp/context.cpp index 894454602..5c47bfe98 100644 --- a/llarp/context.cpp +++ b/llarp/context.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include @@ -7,8 +8,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -34,6 +37,12 @@ namespace llarp m_scheduler->stop(); } + bool + Context::CallSafe(std::function< void(void) > f) + { + return logic && logic->queue_func(std::move(f)); + } + void Context::progress() { @@ -45,11 +54,14 @@ namespace llarp { logic = std::make_shared< Logic >(); // llarp::LogInfo("loading config at ", configfile); - if(!config->Load(configfile.c_str())) + if(configfile.size()) { - config.release(); - llarp::LogError("failed to load config file ", configfile); - return false; + if(!config->Load(configfile.c_str())) + { + config.release(); + llarp::LogError("failed to load config file ", configfile); + return false; + } } // System config @@ -176,56 +188,14 @@ __ ___ ____ _ _ ___ _ _ ____ return 1; } - bool - Context::PutDatabase(__attribute__((unused)) struct llarp::RouterContact &rc) - { - // FIXME - // return llarp_nodedb_put_rc(nodedb, rc); - return false; - } - - llarp::RouterContact * - Context::GetDatabase(__attribute__((unused)) const byte_t *pk) - { - // FIXME - // return llarp_nodedb_get_rc(nodedb, pk); - return nullptr; - } - int - Context::Setup(bool debug) + Context::Setup() { llarp::LogInfo(LLARP_VERSION, " ", LLARP_RELEASE_MOTTO); llarp::LogInfo("starting up"); mainloop = llarp_make_ev_loop(); - if(debug) - { - static std::string WARNING = R"( -__ ___ ____ _ _ ___ _ _ ____ -\ \ / / \ | _ \| \ | |_ _| \ | |/ ___| - \ \ /\ / / _ \ | |_) | \| || || \| | | _ - \ V V / ___ \| _ <| |\ || || |\ | |_| | - \_/\_/_/ \_\_| \_\_| \_|___|_| \_|\____| - -This Lokinet session is not private!! - -Sending traffic unencrypted!! -__ ___ ____ _ _ ___ _ _ ____ -\ \ / / \ | _ \| \ | |_ _| \ | |/ ___| - \ \ /\ / / _ \ | |_) | \| || || \| | | _ - \ V V / ___ \| _ <| |\ || || |\ | |_| | - \_/\_/_/ \_\_| \_\_| \_|___|_| \_|\____| - - )"; - - std::cerr << WARNING << '\n'; - crypto = std::make_unique< NoOpCrypto >(); - } - else - { - crypto = std::make_unique< sodium::CryptoLibSodium >(); - } + crypto = std::make_unique< sodium::CryptoLibSodium >(); cryptoManager = std::make_unique< CryptoManager >(crypto.get()); router = std::make_unique< Router >(worker, mainloop, logic); @@ -248,7 +218,7 @@ __ ___ ____ _ _ ___ _ _ ____ } int - Context::Run() + Context::Run(llarp_main_runtime_opts opts) { if(router == nullptr) { @@ -259,9 +229,15 @@ __ ___ ____ _ _ ___ _ _ ____ if(!WritePIDFile()) return 1; // run - if(!router->Run(nodedb.get())) + if(!router->StartJsonRpc()) return 1; + if(!opts.background) + { + if(!router->Run()) + return 2; + } + // run net io thread llarp::LogInfo("running mainloop"); llarp_ev_loop_run_single_process(mainloop, logic); @@ -395,39 +371,62 @@ __ ___ ____ _ _ ___ _ _ ____ } } // namespace llarp -struct llarp_main -{ - std::unique_ptr< llarp::Context > ctx; -}; - -llarp::Context * -llarp_main_get_context(llarp_main *m) -{ - return m->ctx.get(); -} - extern "C" { - struct llarp_main * - llarp_main_init(const char *fname, bool multiProcess) + struct llarp_main { - (void)multiProcess; - if(!fname) - fname = "daemon.ini"; - char *var = getenv("LLARP_DEBUG"); - if(var && *var == '1') + llarp_main(llarp_config *conf); + ~llarp_main() = default; + std::unique_ptr< llarp::Context > ctx; + }; + + struct llarp_config + { + llarp::Config impl; + llarp_config() = default; + + llarp_config(const llarp_config *other) : impl(other->impl) { - cSetLogLevel(eLogDebug); } - auto *m = new llarp_main; - m->ctx = std::make_unique< llarp::Context >(); - if(!m->ctx->LoadConfig(fname)) + }; + + struct llarp_config * + llarp_default_config() + { + static llarp_config conf; +#ifdef ANDROID + // put andrid config overrides here +#endif +#ifdef IOS + // put IOS config overrides here +#endif + return &conf; + } + + struct llarp_main * + llarp_main_init_from_config(struct llarp_config *conf) + { + if(conf == nullptr) + conf = new llarp_config(llarp_default_config()); + llarp_main *m = new llarp_main(conf); + if(m->ctx->Configure()) + return m; + delete m; + return nullptr; + } + + bool + llarp_config_load_file(const char *fname, struct llarp_config **conf) + { + llarp_config *c = new llarp_config(); + if(c->impl.Load(fname)) { - m->ctx->Close(); - delete m; - return nullptr; + *conf = c; + return true; } - return m; + delete c; + *conf = nullptr; + return false; } void @@ -438,53 +437,103 @@ extern "C" } int - llarp_main_setup(struct llarp_main *ptr, bool debug) + llarp_main_setup(struct llarp_main *ptr) { - return ptr->ctx->Setup(debug); + return ptr->ctx->Setup(); } int - llarp_main_run(struct llarp_main *ptr) + llarp_main_run(struct llarp_main *ptr, struct llarp_main_runtime_opts opts) { - if(!ptr) - { - llarp::LogError("No ptr passed in"); - return 1; - } - return ptr->ctx->Run(); + return ptr->ctx->Run(opts); } - void - llarp_main_abort(struct llarp_main *ptr) + const char * + llarp_version() { - ptr->ctx->router->logic()->stop_timer(); + return LLARP_VERSION; } - void - llarp_main_queryDHT_RC(struct llarp_main *ptr, - struct llarp_router_lookup_job *job) + ssize_t + llarp_vpn_io_readpkt(struct llarp_vpn_pkt_reader *r, unsigned char *dst, + size_t dstlen) { - llarp_dht_lookup_router(ptr->ctx->router->dht(), job); + if(r == nullptr) + return -1; + if(not r->queue.enabled()) + return -1; + auto pkt = r->queue.popFront(); + ManagedBuffer mbuf = pkt.ConstBuffer(); + const llarp_buffer_t &buf = mbuf; + if(buf.sz > dstlen || buf.sz == 0) + return -1; + std::copy_n(buf.base, buf.sz, dst); + return buf.sz; } bool - llarp_main_init_dnsd(struct llarp_main *ptr, struct dnsd_context *dnsd, - const llarp::Addr &dnsd_sockaddr, - const llarp::Addr &dnsc_sockaddr) + llarp_vpn_io_writepkt(struct llarp_vpn_pkt_writer *w, unsigned char *pktbuf, + size_t pktlen) { - return llarp_dnsd_init(dnsd, ptr->ctx->logic.get(), - ptr->ctx->mainloop.get(), dnsd_sockaddr, - dnsc_sockaddr); + if(pktlen == 0 || pktbuf == nullptr) + return false; + if(w == nullptr) + return false; + llarp_vpn_pkt_queue::Packet_t pkt; + llarp_buffer_t buf(pktbuf, pktlen); + if(not pkt.Load(buf)) + return false; + return w->queue.pushBack(std::move(pkt)) + == llarp::thread::QueueReturn::Success; } bool - llarp_main_init_dotLokiLookup(struct llarp_main *ptr, - struct dotLokiLookup *dll) + llarp_main_inject_vpn_by_name(struct llarp_main *ptr, const char *name, + struct llarp_vpn_io *io, + struct llarp_vpn_ifaddr_info info) { - (void)ptr; - (void)dll; - // TODO: gut me - return false; + if(name == nullptr || io == nullptr) + return false; + if(ptr == nullptr || ptr->ctx == nullptr || ptr->ctx->router == nullptr) + return false; + auto ep = ptr->ctx->router->hiddenServiceContext().GetEndpointByName(name); + return ep && ep->InjectVPN(io, info); + } + + void + llarp_vpn_io_close_async(struct llarp_vpn_io *io) + { + if(io == nullptr || io->impl == nullptr) + return; + static_cast< llarp_vpn_io_impl * >(io->impl)->AsyncClose(); + } + + bool + llarp_vpn_io_init(struct llarp_main *ptr, struct llarp_vpn_io *io) + { + if(io == nullptr || ptr == nullptr) + return false; + llarp_vpn_io_impl *impl = new llarp_vpn_io_impl(ptr, io); + io->impl = impl; + return true; + } + + struct llarp_vpn_pkt_writer * + llarp_vpn_io_packet_writer(struct llarp_vpn_io *io) + { + if(io == nullptr || io->impl == nullptr) + return nullptr; + llarp_vpn_io_impl *vpn = static_cast< llarp_vpn_io_impl * >(io->impl); + return &vpn->writer; + } + + struct llarp_vpn_pkt_reader * + llarp_vpn_io_packet_reader(struct llarp_vpn_io *io) + { + if(io == nullptr || io->impl == nullptr) + return nullptr; + llarp_vpn_io_impl *vpn = static_cast< llarp_vpn_io_impl * >(io->impl); + return &vpn->reader; } void @@ -493,49 +542,27 @@ extern "C" delete ptr; } - int - llarp_main_loadDatabase(struct llarp_main *ptr) + const char * + llarp_main_get_default_endpoint_name(struct llarp_main *) { - return ptr->ctx->LoadDatabase(); + return "default"; } +} - const char * - handleBaseCmdLineArgs(int argc, char *argv[]) - { - // clang-format off - cxxopts::Options options( - "lokinet", - "Lokinet is a private, decentralized and IP based overlay network for the internet" - ); - options.add_options() - ("c,config", "Config file", cxxopts::value< std::string >()->default_value("daemon.ini")) - ("o,logLevel", "logging level"); - // clang-format on - - auto result = options.parse(argc, argv); - std::string logLevel = result["logLevel"].as< std::string >(); - - if(logLevel == "debug") - { - cSetLogLevel(eLogDebug); - } - else if(logLevel == "info") - { - cSetLogLevel(eLogInfo); - } - else if(logLevel == "warn") - { - cSetLogLevel(eLogWarn); - } - else if(logLevel == "error") - { - cSetLogLevel(eLogError); - } +llarp_main::llarp_main(llarp_config *conf) - // this isn't thread safe, but reconfiguring during run is likely unsafe - // either way - static std::string confname = result["config"].as< std::string >(); + : ctx(new llarp::Context()) +{ + ctx->config.reset(new llarp::Config(conf->impl)); +} - return confname.c_str(); +namespace llarp +{ + Context * + Context::Get(llarp_main *m) + { + if(m == nullptr || m->ctx == nullptr) + return nullptr; + return m->ctx.get(); } -} +} // namespace llarp diff --git a/llarp/ev/vpnio.cpp b/llarp/ev/vpnio.cpp new file mode 100644 index 000000000..ba107752f --- /dev/null +++ b/llarp/ev/vpnio.cpp @@ -0,0 +1,31 @@ +#include +#include +#include +#include + +void +llarp_vpn_io_impl::AsyncClose() +{ + reader.queue.disable(); + writer.queue.disable(); + CallSafe(std::bind(&llarp_vpn_io_impl::Expunge, this)); +} + +void +llarp_vpn_io_impl::CallSafe(std::function< void(void) > f) +{ + llarp::Context* ctx = llarp::Context::Get(ptr); + if(ctx && ctx->CallSafe(f)) + return; + else if(ctx == nullptr || ctx->logic == nullptr) + f(); +} + +void +llarp_vpn_io_impl::Expunge() +{ + parent->impl = nullptr; + if(parent->closed) + parent->closed(parent); + delete this; +} \ No newline at end of file diff --git a/llarp/ev/vpnio.hpp b/llarp/ev/vpnio.hpp new file mode 100644 index 000000000..d522ddb29 --- /dev/null +++ b/llarp/ev/vpnio.hpp @@ -0,0 +1,51 @@ +#ifndef LLARP_EV_VPNIO_HPP +#define LLARP_EV_VPNIO_HPP +#include +#include +#include + +struct llarp_main; +struct llarp_vpn_io; + +struct llarp_vpn_pkt_queue +{ + using Packet_t = llarp::net::IPPacket; + llarp::thread::Queue< Packet_t > queue; + + llarp_vpn_pkt_queue() : queue(1024){}; + ~llarp_vpn_pkt_queue() = default; +}; + +struct llarp_vpn_pkt_writer : public llarp_vpn_pkt_queue +{ +}; + +struct llarp_vpn_pkt_reader : public llarp_vpn_pkt_queue +{ +}; + +struct llarp_vpn_io_impl +{ + llarp_vpn_io_impl(llarp_main* p, llarp_vpn_io* io) : ptr(p), parent(io) + { + } + ~llarp_vpn_io_impl() = default; + + llarp_main* ptr; + llarp_vpn_io* parent; + + llarp_vpn_pkt_writer writer; + llarp_vpn_pkt_reader reader; + + void + AsyncClose(); + + private: + void + CallSafe(std::function< void(void) > f); + + void + Expunge(); +}; + +#endif \ No newline at end of file diff --git a/llarp/handlers/tun.cpp b/llarp/handlers/tun.cpp index 475b4ba67..837093bfd 100644 --- a/llarp/handlers/tun.cpp +++ b/llarp/handlers/tun.cpp @@ -24,10 +24,12 @@ namespace llarp { namespace handlers { - static llarp_fd_promise * - get_tun_fd_promise(llarp_tun_io *tun) + void + TunEndpoint::FlushToUser(std::function< bool(net::IPPacket &) > send) { - return static_cast< TunEndpoint * >(tun->user)->Promise.get(); + m_ExitMap.ForEachValue([](const auto &exit) { exit->FlushDownstream(); }); + // flush network to user + m_NetworkToUserPktQueue.Process(send); } static void @@ -38,7 +40,7 @@ namespace llarp } TunEndpoint::TunEndpoint(const std::string &nickname, AbstractRouter *r, - service::Context *parent) + service::Context *parent, bool lazyVPN) : service::Endpoint(nickname, r, parent) , m_UserToNetworkPktQueue(nickname + "_sendq", r->netloop(), r->netloop()) @@ -47,22 +49,19 @@ namespace llarp , m_Resolver(std::make_shared< dns::Proxy >( r->netloop(), r->logic(), r->netloop(), r->logic(), this)) { - std::fill(tunif.ifaddr, tunif.ifaddr + sizeof(tunif.ifaddr), 0); - std::fill(tunif.ifname, tunif.ifname + sizeof(tunif.ifname), 0); - tunif.netmask = 0; - -#ifdef ANDROID - tunif.get_fd_promise = &get_tun_fd_promise; - Promise.reset(new llarp_fd_promise(&m_VPNPromise)); -#else - tunif.get_fd_promise = nullptr; -#endif - tunif.user = this; - - // eh this shouldn't do anything on windows anyway - tunif.tick = &tunifTick; - tunif.before_write = &tunifBeforeWrite; - tunif.recvpkt = &tunifRecvPkt; + if(not lazyVPN) + { + tunif.reset(new llarp_tun_io()); + std::fill(tunif->ifaddr, tunif->ifaddr + sizeof(tunif->ifaddr), 0); + std::fill(tunif->ifname, tunif->ifname + sizeof(tunif->ifname), 0); + tunif->netmask = 0; + tunif->get_fd_promise = nullptr; + tunif->user = this; + // eh this shouldn't do anything on windows anyway + tunif->tick = &tunifTick; + tunif->before_write = &tunifBeforeWrite; + tunif->recvpkt = &tunifRecvPkt; + } } util::StatusObject @@ -241,18 +240,18 @@ namespace llarp } return MapAddress(addr, ipv6, false); } - if(k == "ifname") + if(k == "ifname" && tunif) { - if(v.length() >= sizeof(tunif.ifname)) + if(v.length() >= sizeof(tunif->ifname)) { llarp::LogError(Name() + " ifname '", v, "' is too long"); return false; } - strncpy(tunif.ifname, v.c_str(), sizeof(tunif.ifname) - 1); - llarp::LogInfo(Name() + " setting ifname to ", tunif.ifname); + strncpy(tunif->ifname, v.c_str(), sizeof(tunif->ifname) - 1); + llarp::LogInfo(Name() + " setting ifname to ", tunif->ifname); return true; } - if(k == "ifaddr") + if(k == "ifaddr" && tunif) { std::string addr; m_UseV6 = addr.find(":") != std::string::npos; @@ -268,8 +267,8 @@ namespace llarp #endif if(num > 0) { - tunif.netmask = num; - addr = v.substr(0, pos); + tunif->netmask = num; + addr = v.substr(0, pos); } else { @@ -280,14 +279,14 @@ namespace llarp else { if(m_UseV6) - tunif.netmask = 128; + tunif->netmask = 128; else - tunif.netmask = 32; + tunif->netmask = 32; addr = v; } llarp::LogInfo(Name() + " set ifaddr to ", addr, " with netmask ", - tunif.netmask); - strncpy(tunif.ifaddr, addr.c_str(), sizeof(tunif.ifaddr) - 1); + tunif->netmask); + strncpy(tunif->ifaddr, addr.c_str(), sizeof(tunif->ifaddr) - 1); return true; } return Endpoint::SetOption(k, v); @@ -585,80 +584,120 @@ namespace llarp bool TunEndpoint::SetupTun() { + lazy_vpn vpn; + huint32_t ip; auto loop = EndpointNetLoop(); - if(!llarp_ev_add_tun(loop.get(), &tunif)) - { - llarp::LogError(Name(), - " failed to set up tun interface: ", tunif.ifaddr, - " on ", tunif.ifname); - return false; - } - - struct addrinfo hint, *res = nullptr; - int ret; - - memset(&hint, 0, sizeof hint); - - hint.ai_family = PF_UNSPEC; - hint.ai_flags = AI_NUMERICHOST; - - ret = getaddrinfo(tunif.ifaddr, nullptr, &hint, &res); - if(ret) - { - llarp::LogError(Name(), - " failed to set up tun interface, cant determine " - "family from ", - tunif.ifaddr); - return false; - } - - /* - // output is in network byte order - unsigned char buf[sizeof(struct in6_addr)]; - int s = inet_pton(res->ai_family, tunif.ifaddr, buf); - if (s <= 0) - { - llarp::LogError(Name(), " failed to set up tun interface, cant parse - ", tunif.ifaddr); return false; - } - */ - if(res->ai_family == AF_INET6) + if(tunif == nullptr) { - m_UseV6 = true; - } + llarp::LogInfo(Name(), " waiting for vpn to start"); + vpn = m_LazyVPNPromise.get_future().get(); + vpnif = vpn.io; + if(vpnif == nullptr) + { + llarp::LogError(Name(), " failed to recieve vpn interface"); + return false; + } + llarp::LogInfo(Name(), " got vpn interface"); + auto self = shared_from_this(); + // function to queue a packet to send to vpn interface + auto sendpkt = [self](net::IPPacket &pkt) -> bool { + // drop if no endpoint + auto impl = self->GetVPNImpl(); + // drop if no vpn interface + if(impl == nullptr) + return true; + // drop if queue to vpn not enabled + if(not impl->reader.queue.enabled()) + return true; + // drop if queue to vpn full + if(impl->reader.queue.full()) + return true; + // queue to reader + impl->reader.queue.pushBack(pkt); + return false; + }; + // event loop ticker + auto ticker = [self, sendpkt]() { + TunEndpoint *ep = self.get(); + const bool running = not ep->IsStopped(); + auto impl = ep->GetVPNImpl(); + if(impl) + { + /// get packets from vpn + while(not impl->writer.queue.empty()) + { + // queue it to be sent over lokinet + auto pkt = impl->writer.queue.popFront(); + if(running) + ep->m_UserToNetworkPktQueue.Emplace(pkt); + } + } - freeaddrinfo(res); - if(m_UseV6) - { - llarp::LogInfo(Name(), " using IPV6"); + // process packets queued from vpn + if(running) + { + ep->Flush(); + ep->FlushToUser(sendpkt); + } + // if impl has a tick function call it + if(impl && impl->parent && impl->parent->tick) + impl->parent->tick(impl->parent); + }; + if(not loop->add_ticker(ticker)) + { + llarp::LogError(Name(), " failed to add vpn to event loop"); + if(vpnif->injected) + vpnif->injected(vpnif, false); + return false; + } } else { - struct in_addr addr; // network byte order - if(inet_aton(tunif.ifaddr, &addr) == 0) + if(!llarp_ev_add_tun(loop.get(), tunif.get())) { llarp::LogError(Name(), - " failed to set up tun interface, cant parse ", - tunif.ifaddr); + " failed to set up tun interface: ", tunif->ifaddr, + " on ", tunif->ifname); return false; } } - huint32_t ip; - if(ip.FromString(tunif.ifaddr)) + const char *ifname; + const char *ifaddr; + unsigned char netmask; + if(tunif) + { + ifname = tunif->ifname; + ifaddr = tunif->ifaddr; + netmask = tunif->netmask; + } + else + { + ifname = vpn.info.ifname; + ifaddr = vpn.info.ifaddr; + netmask = vpn.info.netmask; + } + if(ip.FromString(ifaddr)) { m_OurIP = net::IPPacket::ExpandV4(ip); - m_OurRange.netmask_bits = netmask_ipv6_bits(tunif.netmask + 96); + m_OurRange.netmask_bits = netmask_ipv6_bits(netmask + 96); } - else if(m_OurIP.FromString(tunif.ifaddr)) + else if(m_OurIP.FromString(ifaddr)) { - m_OurRange.netmask_bits = netmask_ipv6_bits(tunif.netmask); + m_OurRange.netmask_bits = netmask_ipv6_bits(netmask); + m_UseV6 = true; + } + else + { + LogError(Name(), " invalid interface address given, ifaddr=", ifaddr); + if(vpnif && vpnif->injected) + vpnif->injected(vpnif, false); + return false; } m_NextIP = m_OurIP; m_OurRange.addr = m_OurIP; m_MaxIP = m_OurRange.HighestAddr(); - llarp::LogInfo(Name(), " set ", tunif.ifname, " to have address ", - m_OurIP); + llarp::LogInfo(Name(), " set ", ifname, " to have address ", m_OurIP); llarp::LogInfo(Name(), " allocated up to ", m_MaxIP, " on range ", m_OurRange); @@ -667,6 +706,10 @@ namespace llarp { m_OnUp->NotifyAsync(NotifyParams()); } + if(vpnif && vpnif->injected) + { + vpnif->injected(vpnif, true); + } return true; } @@ -676,7 +719,8 @@ namespace llarp auto env = Endpoint::NotifyParams(); env.emplace("IP_ADDR", m_OurIP.ToString()); env.emplace("IF_ADDR", m_OurRange.ToString()); - env.emplace("IF_NAME", tunif.ifname); + if(tunif) + env.emplace("IF_NAME", tunif->ifname); std::string strictConnect; for(const auto &addr : m_StrictConnectAddrs) strictConnect += addr.ToString() + " "; @@ -929,20 +973,17 @@ namespace llarp TunEndpoint::tunifBeforeWrite(llarp_tun_io *tun) { // called in the isolated network thread - auto *self = static_cast< TunEndpoint * >(tun->user); - // flush user to network - self->EndpointLogic()->queue_func( - std::bind(&TunEndpoint::FlushSend, self)); - // flush exit traffic queues if it's there - self->EndpointLogic()->queue_func([self] { - self->m_ExitMap.ForEachValue( - [](const auto &exit) { exit->FlushDownstream(); }); - }); - // flush network to user - self->m_NetworkToUserPktQueue.Process([tun](net::IPPacket &pkt) { + auto *self = static_cast< TunEndpoint * >(tun->user); + auto sendpkt = [self, tun](net::IPPacket &pkt) -> bool { if(!llarp_ev_tun_async_write(tun, pkt.Buffer())) - llarp::LogWarn("packet dropped"); - }); + { + llarp::LogWarn(self->Name(), " packet dropped"); + return true; + } + return false; + }; + self->EndpointLogic()->queue_func(std::bind( + &TunEndpoint::FlushToUser, self->shared_from_this(), sendpkt)); } void diff --git a/llarp/handlers/tun.hpp b/llarp/handlers/tun.hpp index 61b60a85b..fc48ec547 100644 --- a/llarp/handlers/tun.hpp +++ b/llarp/handlers/tun.hpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -20,7 +21,7 @@ namespace llarp public std::enable_shared_from_this< TunEndpoint > { TunEndpoint(const std::string& nickname, AbstractRouter* r, - llarp::service::Context* parent); + llarp::service::Context* parent, bool lazyVPN = false); ~TunEndpoint() override; path::PathSet_ptr @@ -114,8 +115,17 @@ namespace llarp bool HasLocalIP(const huint128_t& ip) const; - llarp_tun_io tunif; - std::unique_ptr< llarp_fd_promise > Promise; + std::unique_ptr< llarp_tun_io > tunif; + llarp_vpn_io* vpnif = nullptr; + + bool + InjectVPN(llarp_vpn_io* io, llarp_vpn_ifaddr_info info) + { + if(tunif) + return false; + m_LazyVPNPromise.set_value(lazy_vpn{info, io}); + return true; + } /// called before writing to tun interface static void @@ -206,6 +216,14 @@ namespace llarp m_SNodes; private: + llarp_vpn_io_impl* + GetVPNImpl() + { + if(vpnif && vpnif->impl) + return static_cast< llarp_vpn_io_impl* >(vpnif->impl); + return nullptr; + } + bool QueueInboundPacketForExit(const llarp_buffer_t& buf) { @@ -255,12 +273,6 @@ namespace llarp reply(*query); delete query; } - -#ifndef WIN32 - /// handles fd injection force android - std::promise< std::pair< int, int > > m_VPNPromise; -#endif - /// our dns resolver std::shared_ptr< dns::Proxy > m_Resolver; @@ -283,6 +295,18 @@ namespace llarp std::vector< llarp::Addr > m_StrictConnectAddrs; /// use v6? bool m_UseV6; + struct lazy_vpn + { + llarp_vpn_ifaddr_info info; + llarp_vpn_io* io; + }; + std::promise< lazy_vpn > m_LazyVPNPromise; + + /// send packets on endpoint to user using send function + /// send function returns true to indicate stop iteration and do codel + /// drop + void + FlushToUser(std::function< bool(net::IPPacket&) > sendfunc); }; } // namespace handlers } // namespace llarp diff --git a/llarp/net/ip.cpp b/llarp/net/ip.cpp index 80df045e3..8dba138d2 100644 --- a/llarp/net/ip.cpp +++ b/llarp/net/ip.cpp @@ -90,20 +90,24 @@ namespace llarp if(pkt.sz > sizeof(buf)) return false; sz = pkt.sz; - memcpy(buf, pkt.base, sz); + std::copy_n(pkt.base, sz, buf); return true; } - llarp_buffer_t + ManagedBuffer IPPacket::ConstBuffer() const { - return {buf, sz}; + const byte_t *ptr = buf; + llarp_buffer_t b(ptr, sz); + return ManagedBuffer(b); } - llarp_buffer_t + ManagedBuffer IPPacket::Buffer() { - return {buf, sz}; + byte_t *ptr = buf; + llarp_buffer_t b(ptr, sz); + return ManagedBuffer(b); } huint32_t diff --git a/llarp/net/ip.hpp b/llarp/net/ip.hpp index 83ddf3714..ac1bb9c73 100644 --- a/llarp/net/ip.hpp +++ b/llarp/net/ip.hpp @@ -116,10 +116,10 @@ namespace llarp size_t sz; byte_t buf[MaxSize]; - llarp_buffer_t + ManagedBuffer Buffer(); - llarp_buffer_t + ManagedBuffer ConstBuffer() const; bool diff --git a/llarp/router/abstractrouter.hpp b/llarp/router/abstractrouter.hpp index ad2891834..08fbf449e 100644 --- a/llarp/router/abstractrouter.hpp +++ b/llarp/router/abstractrouter.hpp @@ -127,7 +127,10 @@ namespace llarp Configure(Config *conf, llarp_nodedb *nodedb) = 0; virtual bool - Run(struct llarp_nodedb *nodedb) = 0; + StartJsonRpc() = 0; + + virtual bool + Run() = 0; /// stop running the router logic gracefully virtual void diff --git a/llarp/router/router.cpp b/llarp/router/router.cpp index cef9d608e..5e9f7fd58 100644 --- a/llarp/router/router.cpp +++ b/llarp/router/router.cpp @@ -110,11 +110,18 @@ namespace llarp util::StatusObject Router::ExtractStatus() const { - return util::StatusObject{ - {"dht", _dht->impl->ExtractStatus()}, - {"services", _hiddenServiceContext.ExtractStatus()}, - {"exit", _exitContext.ExtractStatus()}, - {"links", _linkManager.ExtractStatus()}}; + if(_running) + { + return util::StatusObject{ + {"dht", _dht->impl->ExtractStatus()}, + {"services", _hiddenServiceContext.ExtractStatus()}, + {"exit", _exitContext.ExtractStatus()}, + {"links", _linkManager.ExtractStatus()}}; + } + else + { + return util::StatusObject{{"notRunning", true}}; + } } bool @@ -836,11 +843,10 @@ namespace llarp } bool - Router::Run(struct llarp_nodedb *nodedb) + Router::StartJsonRpc() { if(_running || _stopping) return false; - this->_nodedb = nodedb; if(enableRPCServer) { @@ -860,6 +866,16 @@ namespace llarp } LogInfo("Bound RPC server to ", rpcBindAddr); } + + return true; + } + + bool + Router::Run() + { + if(_running || _stopping) + return false; + if(whitelistRouters) { rpcCaller = std::make_unique< rpc::Caller >(this); @@ -1012,7 +1028,7 @@ namespace llarp _dht->impl->Nodes()->PutNode(rc); } - LogInfo("have ", nodedb->num_loaded(), " routers"); + LogInfo("have ", _nodedb->num_loaded(), " routers"); _netloop->add_ticker(std::bind(&Router::PumpLL, this)); ScheduleTicker(1000); _running.store(true); diff --git a/llarp/router/router.hpp b/llarp/router/router.hpp index dce19004f..e2d94536e 100644 --- a/llarp/router/router.hpp +++ b/llarp/router/router.hpp @@ -327,7 +327,10 @@ namespace llarp Configure(Config *conf, llarp_nodedb *nodedb = nullptr) override; bool - Run(struct llarp_nodedb *nodedb) override; + StartJsonRpc() override; + + bool + Run() override; /// stop running the router logic gracefully void diff --git a/llarp/rpc/rpc.cpp b/llarp/rpc/rpc.cpp index e2830389b..c1447e29c 100644 --- a/llarp/rpc/rpc.cpp +++ b/llarp/rpc/rpc.cpp @@ -1,5 +1,6 @@ #include +#include #include #include #include @@ -194,6 +195,13 @@ namespace llarp ~Handler() override = default; + Response + StartRouter() const + { + const bool rc = router->Run(); + return Response{{"status", rc}}; + } + Response DumpState() const { @@ -259,10 +267,21 @@ namespace llarp return resp; } + Response + DumpVersion() const + { + const Response resp{{"version", LLARP_VERSION}}; + return resp; + } + absl::optional< Response > HandleJSONRPC(Method_t method, ABSL_ATTRIBUTE_UNUSED const Params& params) override { + if(method == "llarp.admin.start") + { + return StartRouter(); + } if(method == "llarp.admin.link.neighboors") { return ListNeighboors(); @@ -279,6 +298,10 @@ namespace llarp { return DumpStatus(); } + if(method == "llarp.version") + { + return DumpVersion(); + } return false; } }; diff --git a/llarp/service/context.cpp b/llarp/service/context.cpp index 072f178d1..a02071e03 100644 --- a/llarp/service/context.cpp +++ b/llarp/service/context.cpp @@ -20,23 +20,18 @@ namespace llarp {"tun", [](const std::string &nick, AbstractRouter *r, service::Context *c) -> service::Endpoint_ptr { - return std::make_shared< handlers::TunEndpoint >(nick, r, c); + return std::make_shared< handlers::TunEndpoint >(nick, r, c, + false); }}, - {"android-tun", - [](const std::string &, AbstractRouter *, - service::Context *) -> service::Endpoint_ptr { - return nullptr; - /// SOOOOOOON (tm) - // return std::make_shared(nick, - // r, c); + {"android", + [](const std::string &nick, AbstractRouter *r, + service::Context *c) -> service::Endpoint_ptr { + return std::make_shared< handlers::TunEndpoint >(nick, r, c, true); }}, - {"ios-tun", - [](const std::string &, AbstractRouter *, - service::Context *) -> service::Endpoint_ptr { - return nullptr; - /// SOOOOOOON (tm) - // return std::make_shared(nick, r, - // c); + {"ios", + [](const std::string &nick, AbstractRouter *r, + service::Context *c) -> service::Endpoint_ptr { + return std::make_shared< handlers::TunEndpoint >(nick, r, c, true); }}, {"null", [](const std::string &nick, AbstractRouter *r, @@ -133,12 +128,22 @@ namespace llarp return m_Endpoints.size() ? true : false; } + static const char * + DefaultEndpointType() + { +#ifdef ANDROID + return "android"; +#else + return "tun"; +#endif + } + bool Context::AddDefaultEndpoint( const std::unordered_multimap< std::string, std::string > &opts) { Config::section_values_t configOpts; - configOpts.push_back({"type", "tun"}); + configOpts.push_back({"type", DefaultEndpointType()}); { auto itr = opts.begin(); while(itr != opts.end()) @@ -167,6 +172,15 @@ namespace llarp return true; } + Endpoint_ptr + Context::GetEndpointByName(const std::string & name) + { + auto itr = m_Endpoints.find(name); + if(itr != m_Endpoints.end()) + return itr->second; + return nullptr; + } + bool Context::AddEndpoint(const Config::section_t &conf, bool autostart) { @@ -180,7 +194,7 @@ namespace llarp } } // extract type - std::string endpointType = "tun"; + std::string endpointType = DefaultEndpointType(); std::string keyfile; for(const auto &option : conf.second) { diff --git a/llarp/service/context.hpp b/llarp/service/context.hpp index 9a860e30b..abc5fb716 100644 --- a/llarp/service/context.hpp +++ b/llarp/service/context.hpp @@ -51,6 +51,9 @@ namespace llarp bool RemoveEndpoint(const std::string &name); + Endpoint_ptr + GetEndpointByName(const std::string &name); + bool StartAll(); diff --git a/llarp/service/endpoint.hpp b/llarp/service/endpoint.hpp index 61467540f..68b088e01 100644 --- a/llarp/service/endpoint.hpp +++ b/llarp/service/endpoint.hpp @@ -1,6 +1,6 @@ #ifndef LLARP_SERVICE_ENDPOINT_HPP #define LLARP_SERVICE_ENDPOINT_HPP - +#include #include #include #include @@ -105,6 +105,14 @@ namespace llarp return false; } + /// inject vpn io + /// return false if not supported + virtual bool + InjectVPN(llarp_vpn_io*, llarp_vpn_ifaddr_info) + { + return false; + } + /// get our ifaddr if it is set virtual huint128_t GetIfAddr() const @@ -254,9 +262,6 @@ namespace llarp bool ShouldBundleRC() const override; - static void - HandlePathDead(void*); - /// return true if we have a convotag as an exit session /// or as a hidden service session /// set addr and issnode diff --git a/ui-ios/CMakeLists.txt b/ui-ios/CMakeLists.txt new file mode 100644 index 000000000..87022d5ec --- /dev/null +++ b/ui-ios/CMakeLists.txt @@ -0,0 +1,58 @@ +cmake_minimum_required(VERSION 3.14) +set(PROJECT_NAME lokinet) +project(${PROJECT_NAME} C CXX Swift) + +get_filename_component(LOKINET_ROOT .. ABSOLUTE BASE_DIR "${CMAKE_CURRENT_LIST_DIR}") + +include("${LOKINET_ROOT}/cmake/target_link_libraries_system.cmake") +include("${LOKINET_ROOT}/cmake/add_import_library.cmake") +include("${LOKINET_ROOT}/cmake/add_log_tag.cmake") +include("${LOKINET_ROOT}/cmake/libatomic.cmake") + +if (STATIC_LINK AND STATIC_LINK_RUNTIME) + message(FATAL "Cannot set both STATIC_LINK and STATIC_LINK_RUNTIME") +endif() + +set(CMAKE_Swift_LANGUAGE_VERSION 5.0) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +list(APPEND CMAKE_MODULE_PATH "${LOKINET_ROOT}/cmake") + +include(FetchContent) +FetchContent_Declare( + libuv + GIT_REPOSITORY https://github.com/libuv/libuv.git + GIT_TAG v1.32.0 +) +FetchContent_Populate(libuv) +add_subdirectory(${libuv_SOURCE_DIR} ${libuv_BINARY_DIR}) + +include("${LOKINET_ROOT}/cmake/basic_definitions.cmake") +set(LIBUV_IN_SOURCE ON) +include("${LOKINET_ROOT}/cmake/unix.cmake") + +find_package(Threads REQUIRED) + +set(ABSEIL_DIR "${LOKINET_ROOT}/vendor/abseil-cpp") + +macro(add_loki_dir name) + add_subdirectory("${LOKINET_ROOT}/${name}" "${name}") +endmacro() + +include_directories(SYSTEM ${ABSEIL_DIR}) +add_loki_dir(vendor/cxxopts) +add_loki_dir(vendor/nlohmann) +include_directories(SYSTEM "${LOKINET_ROOT}/vendor/cxxopts/include") +include_directories("${LOKINET_ROOT}/include") +include_directories("${libuv_SOURCE_DIR}/include") + +add_loki_dir(vendor/gtest) +add_subdirectory(${ABSEIL_DIR} "vendor/abseil-cpp") + +add_loki_dir(crypto) +add_loki_dir(llarp) +add_loki_dir(libabyss) + +add_subdirectory(lokinet) diff --git a/ui-ios/ios-toolchain.cmake b/ui-ios/ios-toolchain.cmake new file mode 100644 index 000000000..8d36fe7fc --- /dev/null +++ b/ui-ios/ios-toolchain.cmake @@ -0,0 +1,4 @@ +set(CMAKE_MACOSX_BUNDLE YES) +set(CMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED NO) +set(CMAKE_OSX_SYSROOT iphoneos) +set(CMAKE_XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "") diff --git a/ui-ios/lokinet/AppDelegate.swift b/ui-ios/lokinet/AppDelegate.swift new file mode 100644 index 000000000..dbb3fcde6 --- /dev/null +++ b/ui-ios/lokinet/AppDelegate.swift @@ -0,0 +1,92 @@ +// +// AppDelegate.swift +// lokinet +// +// Copyright © 2019 Loki. All rights reserved. +// + +import UIKit +import CoreData + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + // Override point for customization after application launch. + return true + } + + func applicationWillResignActive(_ application: UIApplication) { + // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. + } + + func applicationDidEnterBackground(_ application: UIApplication) { + // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. + } + + func applicationWillEnterForeground(_ application: UIApplication) { + // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. + } + + func applicationDidBecomeActive(_ application: UIApplication) { + // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. + } + + func applicationWillTerminate(_ application: UIApplication) { + // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. + // Saves changes in the application's managed object context before the application terminates. + self.saveContext() + } + + // MARK: - Core Data stack + + lazy var persistentContainer: NSPersistentContainer = { + /* + The persistent container for the application. This implementation + creates and returns a container, having loaded the store for the + application to it. This property is optional since there are legitimate + error conditions that could cause the creation of the store to fail. + */ + let container = NSPersistentContainer(name: "lokinet") + container.loadPersistentStores(completionHandler: { (storeDescription, error) in + if let error = error as NSError? { + // Replace this implementation with code to handle the error appropriately. + // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. + + /* + Typical reasons for an error here include: + * The parent directory does not exist, cannot be created, or disallows writing. + * The persistent store is not accessible, due to permissions or data protection when the device is locked. + * The device is out of space. + * The store could not be migrated to the current model version. + Check the error message to determine what the actual problem was. + */ + fatalError("Unresolved error \(error), \(error.userInfo)") + } + }) + return container + }() + + // MARK: - Core Data Saving support + + func saveContext () { + let context = persistentContainer.viewContext + if context.hasChanges { + do { + try context.save() + } catch { + // Replace this implementation with code to handle the error appropriately. + // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. + let nserror = error as NSError + fatalError("Unresolved error \(nserror), \(nserror.userInfo)") + } + } + } + +} + diff --git a/ui-ios/lokinet/Assets.xcassets/AppIcon.appiconset/Contents.json b/ui-ios/lokinet/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 000000000..d8db8d65f --- /dev/null +++ b/ui-ios/lokinet/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,98 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "3x" + }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "83.5x83.5", + "scale" : "2x" + }, + { + "idiom" : "ios-marketing", + "size" : "1024x1024", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/ui-ios/lokinet/Assets.xcassets/Contents.json b/ui-ios/lokinet/Assets.xcassets/Contents.json new file mode 100644 index 000000000..da4a164c9 --- /dev/null +++ b/ui-ios/lokinet/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/ui-ios/lokinet/Base.lproj/LaunchScreen.storyboard b/ui-ios/lokinet/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 000000000..bfa361294 --- /dev/null +++ b/ui-ios/lokinet/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ui-ios/lokinet/Base.lproj/Main.storyboard b/ui-ios/lokinet/Base.lproj/Main.storyboard new file mode 100644 index 000000000..f1bcf3840 --- /dev/null +++ b/ui-ios/lokinet/Base.lproj/Main.storyboard @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ui-ios/lokinet/CMakeLists.txt b/ui-ios/lokinet/CMakeLists.txt new file mode 100644 index 000000000..35fa08bd5 --- /dev/null +++ b/ui-ios/lokinet/CMakeLists.txt @@ -0,0 +1 @@ +add_executable(lokinet AppDelegate.swift ViewController.swift) diff --git a/ui-ios/lokinet/Info.plist b/ui-ios/lokinet/Info.plist new file mode 100644 index 000000000..16be3b681 --- /dev/null +++ b/ui-ios/lokinet/Info.plist @@ -0,0 +1,45 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/ui-ios/lokinet/ViewController.swift b/ui-ios/lokinet/ViewController.swift new file mode 100644 index 000000000..26e307e09 --- /dev/null +++ b/ui-ios/lokinet/ViewController.swift @@ -0,0 +1,19 @@ +// +// ViewController.swift +// lokinet +// +// Copyright © 2019 Loki. All rights reserved. +// + +import UIKit + +class ViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + // Do any additional setup after loading the view. + } + + +} + diff --git a/ui-ios/lokinet/lokinet.entitlements b/ui-ios/lokinet/lokinet.entitlements new file mode 100644 index 000000000..8f2ff3f1e --- /dev/null +++ b/ui-ios/lokinet/lokinet.entitlements @@ -0,0 +1,15 @@ + + + + + com.apple.developer.networking.networkextension + + dns-proxy + packet-tunnel-provider + + com.apple.developer.networking.vpn.api + + allow-vpn + + + diff --git a/ui-ios/lokinet/lokinet.xcdatamodeld/.xccurrentversion b/ui-ios/lokinet/lokinet.xcdatamodeld/.xccurrentversion new file mode 100644 index 000000000..bf2d08f0a --- /dev/null +++ b/ui-ios/lokinet/lokinet.xcdatamodeld/.xccurrentversion @@ -0,0 +1,8 @@ + + + + + _XCCurrentVersionName + lokinet.xcdatamodel + + diff --git a/ui-ios/lokinet/lokinet.xcdatamodeld/lokinet.xcdatamodel/contents b/ui-ios/lokinet/lokinet.xcdatamodeld/lokinet.xcdatamodel/contents new file mode 100644 index 000000000..476e5b6cf --- /dev/null +++ b/ui-ios/lokinet/lokinet.xcdatamodeld/lokinet.xcdatamodel/contents @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/vendor/cxxopts/test/options.cpp b/vendor/cxxopts/test/options.cpp index d110e0125..d3d3c7a69 100644 --- a/vendor/cxxopts/test/options.cpp +++ b/vendor/cxxopts/test/options.cpp @@ -9,7 +9,7 @@ class Argv { Argv(std::initializer_list args) : m_argv(new char*[args.size()]) - , m_argc(args.size()) + , m_argc(static_cast(args.size())) { int i = 0; auto iter = args.begin();