From 67b5d48095a991395f36d6c12ffcf41b6f1fbab2 Mon Sep 17 00:00:00 2001 From: Michael Date: Mon, 11 Feb 2019 14:43:48 +0000 Subject: [PATCH] Replace usage of new/delete with unique_ptr/stack allocation --- daemon/dns.cpp | 49 ++- include/llarp.hpp | 20 +- jni/lokinet_android.cpp | 38 ++- llarp/config.cpp | 88 ++--- llarp/config.h | 48 --- llarp/config.hpp | 12 +- llarp/context.cpp | 128 +++---- llarp/dns.cpp | 10 +- llarp/ev/ev.cpp | 23 +- llarp/ev/ev.h | 8 +- llarp/link/server.cpp | 2 +- llarp/messages/relay_commit.cpp | 26 +- llarp/messages/relay_commit.hpp | 5 +- llarp/router/router.cpp | 572 ++++++++++++++++---------------- llarp/router/router.hpp | 13 +- llarp/rpc/rpc.cpp | 6 +- llarp/rpc/rpc.hpp | 7 +- llarp/util/threadpool.cpp | 19 -- llarp/util/threadpool.h | 26 +- llarp/util/timer.cpp | 13 +- 20 files changed, 507 insertions(+), 606 deletions(-) delete mode 100644 llarp/config.h diff --git a/daemon/dns.cpp b/daemon/dns.cpp index ca98c453d..78503a2cd 100644 --- a/daemon/dns.cpp +++ b/daemon/dns.cpp @@ -1,4 +1,4 @@ -#include +#include #include #include #include @@ -38,29 +38,26 @@ struct dns_relay_config { std::string upstream_host; uint16_t upstream_port; -}; -void -dns_iter_config(llarp_config_iterator *itr, const char *section, - const char *key, const char *val) -{ - dns_relay_config *config = (dns_relay_config *)itr->user; - if(!strcmp(section, "dns")) + void + dns_iter_config(const char *section, const char *key, const char *val) { - if(!strcmp(key, "upstream-server")) + if(!strcmp(section, "dns")) { - config->upstream_host = strdup(val); - llarp::LogDebug("Config file setting dns server to ", - config->upstream_host); - } - if(!strcmp(key, "upstream-port")) - { - config->upstream_port = atoi(val); - llarp::LogDebug("Config file setting dns server port to ", - config->upstream_port); + if(!strcmp(key, "upstream-server")) + { + upstream_host = strdup(val); + llarp::LogDebug("Config file setting dns server to ", upstream_host); + } + if(!strcmp(key, "upstream-port")) + { + upstream_port = atoi(val); + llarp::LogDebug("Config file setting dns server port to ", + upstream_port); + } } } -} +}; int main(int argc, char *argv[]) @@ -74,19 +71,17 @@ main(int argc, char *argv[]) dns_relay_config dnsr_config; dnsr_config.upstream_host = "8.8.8.8"; dnsr_config.upstream_port = 53; - llarp_config *config_reader; - llarp_new_config(&config_reader); + llarp::Config config_reader; - if(llarp_load_config(config_reader, conffname)) + if(config_reader.load(conffname)) { - llarp_free_config(&config_reader); llarp::LogError("failed to load config file ", conffname); return 0; } - llarp_config_iterator iter; - iter.user = &dnsr_config; - iter.visit = &dns_iter_config; - llarp_config_iter(config_reader, &iter); + + using namespace std::placeholders; + config_reader.visit( + std::bind(&dns_relay_config::dns_iter_config, &dnsr_config, _1, _2, _3)); llarp::LogInfo("config [", conffname, "] loaded"); const uint16_t server_port = 53; diff --git a/include/llarp.hpp b/include/llarp.hpp index 2b002b761..4bf0f190e 100644 --- a/include/llarp.hpp +++ b/include/llarp.hpp @@ -8,8 +8,6 @@ #include #include -struct llarp_config; -struct llarp_config_iterator; struct llarp_ev_loop; struct llarp_nodedb; struct llarp_nodedb_iter; @@ -17,6 +15,7 @@ struct llarp_threadpool; namespace llarp { + struct Config; struct Crypto; class Logic; struct Router; @@ -29,12 +28,12 @@ namespace llarp int num_nethreads = 1; bool singleThreaded = false; std::unique_ptr< llarp::Crypto > crypto; - llarp::Router *router = nullptr; - llarp_threadpool *worker = nullptr; - llarp::Logic *logic = nullptr; - llarp_config *config = nullptr; - llarp_nodedb *nodedb = nullptr; - llarp_ev_loop *mainloop = nullptr; + std::unique_ptr< llarp::Router > router; + std::unique_ptr< llarp_threadpool > worker; + std::unique_ptr< llarp::Logic > logic; + std::unique_ptr< llarp::Config > config; + std::unique_ptr< llarp_nodedb > nodedb; + std::unique_ptr< llarp_ev_loop > mainloop; std::string nodedb_dir; bool @@ -83,9 +82,8 @@ namespace llarp bool ReloadConfig(); - static void - iter_config(llarp_config_iterator *itr, const char *section, - const char *key, const char *val); + void + iter_config(const char *section, const char *key, const char *val); void progress(); diff --git a/jni/lokinet_android.cpp b/jni/lokinet_android.cpp index e610141cc..1ca398695 100755 --- a/jni/lokinet_android.cpp +++ b/jni/lokinet_android.cpp @@ -1,12 +1,11 @@ +#include +#include +#include -//#include #include -#include -#include #include #include #include -#include "fs.hpp" struct AndroidMain { @@ -16,7 +15,7 @@ struct AndroidMain /// set configuration and ensure files bool - Configure(const char * conf, const char * basedir) + Configure(const char* conf, const char* basedir) { configFile = conf; return llarp_ensure_config(conf, basedir, false, false); @@ -66,14 +65,15 @@ struct AndroidMain { // on error llarp::LogError("daemon run fail"); - llarp_main * ptr = m_impl; - m_impl = nullptr; + llarp_main* ptr = m_impl; + m_impl = nullptr; llarp_main_signal(ptr, SIGINT); llarp_main_free(ptr); } } - const char * GetIfAddr() + const char* + GetIfAddr() { if(m_impl) { @@ -81,10 +81,11 @@ struct AndroidMain if(tun) return tun->tunif.ifaddr; } - return ""; + return ""; } - int GetIfRange() const + int + GetIfRange() const { if(m_impl) { @@ -165,13 +166,14 @@ extern "C" } JNIEXPORT void JNICALL - Java_network_loki_lokinet_Lokinet_1JNI_setVPNFileDescriptor(JNIEnv*, jclass, jint fd) + Java_network_loki_lokinet_Lokinet_1JNI_setVPNFileDescriptor(JNIEnv*, jclass, + jint fd) { daemon->SetVPN_FD(fd); } - JNIEXPORT jstring JNICALL Java_network_loki_lokinet_Lokinet_1JNI_getIfAddr - (JNIEnv * env, jclass) + JNIEXPORT jstring JNICALL + Java_network_loki_lokinet_Lokinet_1JNI_getIfAddr(JNIEnv* env, jclass) { if(daemon) return env->NewStringUTF(daemon->GetIfAddr()); @@ -179,18 +181,18 @@ extern "C" return env->NewStringUTF(""); } - JNIEXPORT jint JNICALL Java_network_loki_lokinet_Lokinet_1JNI_getIfRange - (JNIEnv *, jclass) + JNIEXPORT jint JNICALL + Java_network_loki_lokinet_Lokinet_1JNI_getIfRange(JNIEnv*, jclass) { - if(daemon) + if(daemon) return daemon->GetIfRange(); else return -1; } JNIEXPORT void JNICALL - Java_network_loki_lokinet_Lokinet_1JNI_onNetworkStateChanged(JNIEnv*, jclass, - jboolean isConnected) + Java_network_loki_lokinet_Lokinet_1JNI_onNetworkStateChanged( + JNIEnv*, jclass, jboolean isConnected) { if(isConnected) { diff --git a/llarp/config.cpp b/llarp/config.cpp index e2a52f3dd..dd2261492 100644 --- a/llarp/config.cpp +++ b/llarp/config.cpp @@ -1,4 +1,3 @@ -#include #include #include @@ -48,6 +47,35 @@ namespace llarp return true; }; + void + Config::visit(const Visitor &functor) + { + std::unordered_map< std::string, const llarp::Config::section_t & > + sections = {{"network", network}, {"connect", connect}, + {"bootstrap", bootstrap}, {"system", system}, + {"netdb", netdb}, {"api", api}, + {"services", services}}; + + auto visitor = [&](const char *name, const auto &item) { + functor(name, item.first.c_str(), item.second.c_str()); + }; + + using namespace std::placeholders; + + std::for_each(lokid.begin(), lokid.end(), std::bind(visitor, "lokid", _1)); + std::for_each(router.begin(), router.end(), + std::bind(visitor, "router", _1)); + + std::for_each(dns.begin(), dns.end(), std::bind(visitor, "dns", _1)); + std::for_each(iwp_links.begin(), iwp_links.end(), + std::bind(visitor, "bind", _1)); + + std::for_each(sections.begin(), sections.end(), [&](const auto §ion) { + std::for_each(section.second.begin(), section.second.end(), + std::bind(visitor, section.first.c_str(), _1)); + }); + } + } // namespace llarp extern "C" bool @@ -333,61 +361,3 @@ llarp_ensure_client_config(std::ofstream &f, std::string basepath) f << "enabled=true" << std::endl; return true; } - -extern "C" -{ - void - llarp_new_config(struct llarp_config **conf) - { - llarp_config *c = new llarp_config(); - *conf = c; - } - - void - llarp_free_config(struct llarp_config **conf) - { - if(*conf) - delete *conf; - *conf = nullptr; - } - - int - llarp_load_config(struct llarp_config *conf, const char *fname) - { - if(!conf->impl.Load(fname)) - return -1; - return 0; - } - - void - llarp_config_iter(struct llarp_config *conf, - struct llarp_config_iterator *iter) - { - iter->conf = conf; - std::unordered_map< std::string, const llarp::Config::section_t & > - sections = {{"network", conf->impl.network}, - {"connect", conf->impl.connect}, - {"bootstrap", conf->impl.bootstrap}, - {"system", conf->impl.system}, - {"netdb", conf->impl.netdb}, - {"api", conf->impl.api}, - {"services", conf->impl.services}}; - - for(const auto &item : conf->impl.lokid) - iter->visit(iter, "lokid", item.first.c_str(), item.second.c_str()); - - for(const auto &item : conf->impl.router) - iter->visit(iter, "router", item.first.c_str(), item.second.c_str()); - - for(const auto &item : conf->impl.dns) - iter->visit(iter, "dns", item.first.c_str(), item.second.c_str()); - - for(const auto &item : conf->impl.iwp_links) - iter->visit(iter, "bind", item.first.c_str(), item.second.c_str()); - - for(const auto §ion : sections) - for(const auto &item : section.second) - iter->visit(iter, section.first.c_str(), item.first.c_str(), - item.second.c_str()); - } -} diff --git a/llarp/config.h b/llarp/config.h deleted file mode 100644 index 90408a703..000000000 --- a/llarp/config.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef LLARP_CONFIG_H_ -#define LLARP_CONFIG_H_ - -#ifdef __cplusplus -extern "C" -{ -#endif - /** - * config.h - * - * library configuration utilties - */ - - struct llarp_config; - - /// allocate config - void - llarp_new_config(struct llarp_config **conf); - - /// deallocate config - void - llarp_free_config(struct llarp_config **conf); - - /// @brief return -1 on fail otherwiwse 0 - int - llarp_load_config(struct llarp_config *conf, const char *fname); - - /// config iterator configuration - struct llarp_config_iterator - { - /// a customizable pointer to pass data to iteration functor - void *user; - /// set by llarp_config_iter - struct llarp_config *conf; - /// visit (self, section, key, value) - void (*visit)(struct llarp_config_iterator *, const char *, const char *, - const char *); - }; - - /// iterator over "conf" and call visit functor defined in "iter" - void - llarp_config_iter(struct llarp_config *conf, - struct llarp_config_iterator *iter); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/llarp/config.hpp b/llarp/config.hpp index eb37c9f34..8f9e068f9 100644 --- a/llarp/config.hpp +++ b/llarp/config.hpp @@ -1,6 +1,5 @@ #ifndef LLARP_CONFIG_HPP #define LLARP_CONFIG_HPP -#include #include #include @@ -25,15 +24,16 @@ namespace llarp bool Load(const char *fname); + + using Visitor = std::function< void(const char *section, const char *key, + const char *val) >; + + void + visit(const Visitor &visitor); }; } // namespace llarp -struct llarp_config -{ - llarp::Config impl; -}; - void llarp_generic_ensure_config(std::ofstream &f, std::string basepath); diff --git a/llarp/context.cpp b/llarp/context.cpp index 18e459ece..6c8d815c7 100644 --- a/llarp/context.cpp +++ b/llarp/context.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include #include @@ -23,7 +24,8 @@ namespace llarp { Context::~Context() { - llarp_ev_loop_free(&mainloop); + llarp_ev_loop *ptr = mainloop.release(); + llarp_ev_loop_free(&ptr); } void @@ -36,55 +38,51 @@ namespace llarp Context::Configure() { // llarp::LogInfo("loading config at ", configfile); - if(llarp_load_config(config, configfile.c_str())) + if(config->Load(configfile.c_str())) { - llarp_free_config(&config); + config.release(); llarp::LogError("failed to load config file ", configfile); return false; } - llarp_config_iterator iter; - iter.user = this; - iter.visit = &iter_config; - llarp_config_iter(config, &iter); + using namespace std::placeholders; + config->visit(std::bind(&Context::iter_config, this, _1, _2, _3)); return true; } void - Context::iter_config(llarp_config_iterator *itr, const char *section, - const char *key, const char *val) + Context::iter_config(const char *section, const char *key, const char *val) { - Context *ctx = static_cast< Context * >(itr->user); if(!strcmp(section, "system")) { if(!strcmp(key, "pidfile")) { - ctx->SetPIDFile(val); + SetPIDFile(val); } } if(!strcmp(section, "router")) { - if(!strcmp(key, "worker-threads") && !ctx->singleThreaded) + if(!strcmp(key, "worker-threads") && !singleThreaded) { int workers = atoi(val); - if(workers > 0 && ctx->worker == nullptr) + if(workers > 0 && worker == nullptr) { - ctx->worker = llarp_init_threadpool(workers, "llarp-worker"); + worker.reset(llarp_init_threadpool(workers, "llarp-worker")); } } else if(!strcmp(key, "net-threads")) { - ctx->num_nethreads = atoi(val); - if(ctx->num_nethreads <= 0) - ctx->num_nethreads = 1; - if(ctx->singleThreaded) - ctx->num_nethreads = 0; + num_nethreads = atoi(val); + if(num_nethreads <= 0) + num_nethreads = 1; + if(singleThreaded) + num_nethreads = 0; } } if(!strcmp(section, "netdb")) { if(!strcmp(key, "dir")) { - ctx->nodedb_dir = val; + nodedb_dir = val; } } } @@ -99,7 +97,7 @@ namespace llarp Context::LoadDatabase() { crypto = std::make_unique< sodium::CryptoLibSodium >(); - nodedb = new llarp_nodedb(crypto.get(), router->disk); + nodedb = std::make_unique< llarp_nodedb >(crypto.get(), router->disk); if(!llarp_nodedb::ensure_dir(nodedb_dir.c_str())) { @@ -146,26 +144,27 @@ namespace llarp { llarp::LogInfo(LLARP_VERSION, " ", LLARP_RELEASE_MOTTO); llarp::LogInfo("starting up"); - llarp_ev_loop_alloc(&mainloop); + mainloop = llarp_make_ev_loop(); // ensure worker thread pool if(!worker && !singleThreaded) - worker = llarp_init_threadpool(2, "llarp-worker"); + worker.reset(llarp_init_threadpool(2, "llarp-worker")); else if(singleThreaded) { llarp::LogInfo("running in single threaded mode"); - worker = llarp_init_same_process_threadpool(); + worker.reset(llarp_init_same_process_threadpool()); } // ensure netio thread if(singleThreaded) { - logic = new Logic(worker); + logic = std::make_unique< Logic >(worker.get()); } else - logic = new Logic; + logic = std::make_unique< Logic >(); - router = new Router(worker, mainloop, logic); - if(!router->Configure(config)) + router = + std::make_unique< Router >(worker.get(), mainloop.get(), logic.get()); + if(!router->Configure(config.get())) { llarp::LogError("Failed to configure router"); return 1; @@ -190,12 +189,12 @@ namespace llarp if(!WritePIDFile()) return 1; // run - if(!router->Run(nodedb)) + if(!router->Run(nodedb.get())) return 1; // run net io thread llarp::LogInfo("running mainloop"); - llarp_ev_loop_run_single_process(mainloop, worker, logic); + llarp_ev_loop_run_single_process(mainloop.get(), worker.get(), logic.get()); // waits for router graceful stop return 0; } @@ -242,31 +241,26 @@ namespace llarp llarp::LogInfo("SIGHUP"); if(router) { - llarp_config *newconfig = nullptr; - llarp_new_config(&newconfig); - if(llarp_load_config(newconfig, configfile.c_str())) + Config newconfig; + if(newconfig.Load(configfile.c_str())) { - llarp_free_config(&newconfig); llarp::LogError("failed to load config file ", configfile); return; } // validate config - if(!router->ValidateConfig(newconfig)) + if(!router->ValidateConfig(&newconfig)) { llarp::LogWarn("new configuration is invalid"); - llarp_free_config(&newconfig); return; } // reconfigure - if(!router->Reconfigure(newconfig)) + if(!router->Reconfigure(&newconfig)) { - llarp_free_config(&newconfig); llarp::LogError("Failed to reconfigure so we will stop."); router->Stop(); return; } llarp::LogInfo("router reconfigured"); - llarp_free_config(&newconfig); } } #endif @@ -284,7 +278,7 @@ namespace llarp { if(logic) logic->stop(); - llarp_ev_loop_stop(mainloop); + llarp_ev_loop_stop(mainloop.get()); Close(); } } @@ -294,40 +288,34 @@ namespace llarp { llarp::LogDebug("stop workers"); if(worker) - llarp_threadpool_stop(worker); + llarp_threadpool_stop(worker.get()); llarp::LogDebug("join workers"); if(worker) - llarp_threadpool_join(worker); + llarp_threadpool_join(worker.get()); llarp::LogDebug("free config"); - llarp_free_config(&config); + config.release(); llarp::LogDebug("free workers"); - llarp_free_threadpool(&worker); + worker.release(); llarp::LogDebug("free nodedb"); - delete nodedb; + nodedb.release(); + + llarp::LogDebug("free router"); + router.release(); + + llarp::LogDebug("free logic"); + logic.release(); - if(router) - { - llarp::LogDebug("free router"); - delete router; - router = nullptr; - } - if(logic) - { - llarp::LogDebug("free logic"); - delete logic; - logic = nullptr; - } RemovePIDFile(); } bool Context::LoadConfig(const std::string &fname) { - llarp_new_config(&config); + config = std::make_unique< Config >(); configfile = fname; return Configure(); } @@ -415,8 +403,9 @@ extern "C" const llarp::Addr &dnsd_sockaddr, const llarp::Addr &dnsc_sockaddr) { - return llarp_dnsd_init(dnsd, ptr->ctx->logic, ptr->ctx->mainloop, - dnsd_sockaddr, dnsc_sockaddr); + return llarp_dnsd_init(dnsd, ptr->ctx->logic.get(), + ptr->ctx->mainloop.get(), dnsd_sockaddr, + dnsc_sockaddr); } bool @@ -425,7 +414,7 @@ extern "C" { (void)ptr; (void)dll; - // TODO: gutt me + // TODO: gut me return false; } @@ -462,23 +451,6 @@ extern "C" llarp::RouterContact * llarp_main_getLocalRC(__attribute__((unused)) struct llarp_main *ptr) { - // - /* - llarp_config_iterator iter; - iter.user = this; - iter.visit = &iter_config; - llarp_config_iter(ctx->config, &iter); - */ - // llarp_rc *rc = new llarp_rc; - // llarp::RouterContact *rc = new llarp::RouterContact; - // llarp_rc_new(rc); - // llarp::LogInfo("FIXME: Loading ", ptr->ctx->conatctFile); - // FIXME - /* - if(llarp_rc_read(ptr->ctx->conatctFile, rc)) - return rc; - else - */ return nullptr; } diff --git a/llarp/dns.cpp b/llarp/dns.cpp index 7093b062a..7564c2205 100644 --- a/llarp/dns.cpp +++ b/llarp/dns.cpp @@ -8,26 +8,24 @@ void hexDump(const char *buffer, uint16_t size) { // would rather heap allocate than use VLA - char *hex_buffer = new char[size * 3 + 1]; + std::vector< char > hex_buffer(size * 3 + 1); hex_buffer[size * 3] = 0; for(unsigned int j = 0; j < size; j++) sprintf(&hex_buffer[3 * j], "%02X ", buffer[j]); - std::string str(hex_buffer); + std::string str(hex_buffer.begin(), hex_buffer.end()); llarp::LogInfo("First ", size, " bytes: ", str); - delete[] hex_buffer; } void hexDumpAt(const char *const buffer, uint32_t pos, uint16_t size) { // would rather heap allocate than use VLA - char *hex_buffer = new char[size * 3 + 1]; + std::vector< char > hex_buffer(size * 3 + 1); hex_buffer[size * 3] = 0; for(unsigned int j = 0; j < size; j++) sprintf(&hex_buffer[3 * j], "%02X ", buffer[pos + j]); - std::string str(hex_buffer); + std::string str(hex_buffer.begin(), hex_buffer.end()); llarp::LogInfo(pos, " ", size, " bytes: ", str); - delete[] hex_buffer; } /* diff --git a/llarp/ev/ev.cpp b/llarp/ev/ev.cpp index 11edf7539..34aa4d026 100644 --- a/llarp/ev/ev.cpp +++ b/llarp/ev/ev.cpp @@ -24,7 +24,7 @@ llarp_ev_loop_alloc(struct llarp_ev_loop **ev) *ev = new llarp_epoll_loop; #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \ || (__APPLE__ && __MACH__) - *ev = new llarp_kqueue_loop; + *ev = new llarp_kqueue_loop; #elif defined(_WIN32) || defined(_WIN64) || defined(__NT__) *ev = new llarp_win32_loop; #else @@ -35,6 +35,27 @@ llarp_ev_loop_alloc(struct llarp_ev_loop **ev) (*ev)->_now = llarp::time_now_ms(); } +std::unique_ptr< llarp_ev_loop > +llarp_make_ev_loop() +{ +#if __linux__ || __sun__ + std::unique_ptr< llarp_ev_loop > r = std::make_unique< llarp_epoll_loop >(); +#elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \ + || (__APPLE__ && __MACH__) + std::unique_ptr< llarp_ev_loop > r = std::make_unique< llarp_kqueue_loop >(); +#elif defined(_WIN32) || defined(_WIN64) || defined(__NT__) + std::unique_ptr< llarp_win32_loop > r = + std::make_unique< llarp_kqueue_loop >(); +#else +// TODO: fall back to a generic select-based event loop +#error no event loop subclass +#endif + r->init(); + r->_now = llarp::time_now_ms(); + + return r; +} + void llarp_ev_loop_free(struct llarp_ev_loop **ev) { diff --git a/llarp/ev/ev.h b/llarp/ev/ev.h index bdf864cbd..704d3640f 100644 --- a/llarp/ev/ev.h +++ b/llarp/ev/ev.h @@ -17,6 +17,7 @@ #include #endif +#include #include #include #include @@ -43,6 +44,9 @@ namespace llarp void llarp_ev_loop_alloc(struct llarp_ev_loop **ev); +std::unique_ptr< llarp_ev_loop > +llarp_make_ev_loop(); + // deallocator void llarp_ev_loop_free(struct llarp_ev_loop **ev); @@ -115,7 +119,7 @@ struct llarp_tcp_conn }; /// queue async write a buffer in full -/// return if we queueed it or not +/// return if we queued it or not bool llarp_tcp_conn_async_write(struct llarp_tcp_conn *, const llarp_buffer_t &); @@ -164,7 +168,7 @@ struct llarp_tcp_acceptor /// bind to an address and start serving async /// return false if failed to bind -/// return true on successs +/// return true on success bool llarp_tcp_serve(struct llarp_ev_loop *loop, struct llarp_tcp_acceptor *t, const sockaddr *bindaddr); diff --git a/llarp/link/server.cpp b/llarp/link/server.cpp index cd7bb7f93..853e38bab 100644 --- a/llarp/link/server.cpp +++ b/llarp/link/server.cpp @@ -334,7 +334,7 @@ namespace llarp auto itr = m_Pending.find(addr); if(itr != m_Pending.end()) return false; - m_Pending.insert(std::make_pair(addr, std::unique_ptr< ILinkSession >(s))); + m_Pending.emplace(addr, std::unique_ptr< ILinkSession >(s)); return true; } diff --git a/llarp/messages/relay_commit.cpp b/llarp/messages/relay_commit.cpp index 1ea9bdc9e..d63f0cd5a 100644 --- a/llarp/messages/relay_commit.cpp +++ b/llarp/messages/relay_commit.cpp @@ -105,12 +105,6 @@ namespace llarp return bencode_end(buf); } - LR_CommitRecord::~LR_CommitRecord() - { - if(work) - delete work; - } - bool LR_CommitRecord::OnKey(dict_reader* r, llarp_buffer_t* key) { @@ -146,7 +140,7 @@ namespace llarp return false; } - self->work = new PoW(); + self->work = std::make_unique< PoW >(); return self->work->BDecode(r->buffer); } return read; @@ -178,7 +172,7 @@ namespace llarp typedef llarp::path::PathContext Context; typedef llarp::path::TransitHop Hop; typedef AsyncFrameDecrypter< LRCMFrameDecrypt > Decrypter; - Decrypter* decrypter; + std::unique_ptr< Decrypter > decrypter; std::array< EncryptedFrame, 8 > frames; Context* context; // decrypted record @@ -188,21 +182,24 @@ namespace llarp LRCMFrameDecrypt(Context* ctx, Decrypter* dec, const LR_CommitMessage* commit) - : decrypter(dec), frames(commit->frames), context(ctx), hop(new Hop()) + : decrypter(dec) + , frames(commit->frames) + , context(ctx) + , hop(std::make_shared< Hop >()) { hop->info.downstream = commit->session->GetPubKey(); } ~LRCMFrameDecrypt() { - delete decrypter; } /// this is done from logic thread static void SendLRCM(void* user) { - LRCMFrameDecrypt* self = static_cast< LRCMFrameDecrypt* >(user); + std::unique_ptr< LRCMFrameDecrypt > self( + static_cast< LRCMFrameDecrypt* >(user)); // persist sessions to upstream and downstream routers until the commit // ends self->context->Router()->PersistSessionUntil(self->hop->info.downstream, @@ -214,14 +211,14 @@ namespace llarp // forward to next hop self->context->ForwardLRCM(self->hop->info.upstream, self->frames); self->hop = nullptr; - delete self; } // this is called from the logic thread static void SendPathConfirm(void* user) { - LRCMFrameDecrypt* self = static_cast< LRCMFrameDecrypt* >(user); + std::unique_ptr< LRCMFrameDecrypt > self( + static_cast< LRCMFrameDecrypt* >(user)); // persist session to downstream until path expiration self->context->Router()->PersistSessionUntil(self->hop->info.downstream, self->hop->ExpireTime()); @@ -235,7 +232,6 @@ namespace llarp self->hop->info); } self->hop = nullptr; - delete self; } static void @@ -284,7 +280,7 @@ namespace llarp using namespace std::placeholders; if(self->record.work && self->record.work->IsValid( - std::bind(&Crypto::shorthash, crypto, _1, _2), now)) + std::bind(&Crypto::shorthash, crypto, _1, _2), now)) { llarp::LogDebug("LRCM extended lifetime by ", self->record.work->extendedLifetime, " seconds for ", diff --git a/llarp/messages/relay_commit.hpp b/llarp/messages/relay_commit.hpp index 0da56e84e..a37aea74d 100644 --- a/llarp/messages/relay_commit.hpp +++ b/llarp/messages/relay_commit.hpp @@ -8,6 +8,7 @@ #include #include +#include namespace llarp { @@ -24,7 +25,7 @@ namespace llarp TunnelNonce tunnelNonce; PathID_t txid, rxid; - PoW *work = nullptr; + std::unique_ptr< PoW > work; uint64_t version = 0; uint64_t lifetime = 0; @@ -34,8 +35,6 @@ namespace llarp bool BEncode(llarp_buffer_t *buf) const; - ~LR_CommitRecord(); - bool operator==(const LR_CommitRecord &other) const; diff --git a/llarp/router/router.cpp b/llarp/router/router.cpp index 58afb3b1d..4254d0fbd 100644 --- a/llarp/router/router.cpp +++ b/llarp/router/router.cpp @@ -1,5 +1,6 @@ #include +#include #include #include #include @@ -25,10 +26,6 @@ namespace llarp { - void - router_iter_config(llarp_config_iterator *iter, const char *section, - const char *key, const char *val); - struct async_verify_context { Router *router; @@ -441,12 +438,10 @@ namespace llarp } bool - Router::Configure(struct llarp_config *conf) + Router::Configure(Config *conf) { - llarp_config_iterator iter; - iter.user = this; - iter.visit = llarp::router_iter_config; - llarp_config_iter(conf, &iter); + using namespace std::placeholders; + conf->visit(std::bind(&Router::router_iter_config, this, _1, _2, _3)); if(!InitOutboundLinks()) return false; if(!Ready()) @@ -703,6 +698,268 @@ namespace llarp return SaveRC(); } // namespace llarp + void + Router::router_iter_config(const char *section, const char *key, + const char *val) + { + llarp::LogDebug(section, " ", key, "=", val); + + int af; + uint16_t proto; + if(StrEq(val, "eth")) + { +#ifdef AF_LINK + af = AF_LINK; +#endif +#ifdef AF_PACKET + af = AF_PACKET; +#endif + proto = LLARP_ETH_PROTO; + } + else + { + // try IPv4 first + af = AF_INET; + proto = std::atoi(val); + } + + if(StrEq(section, "bind")) + { + if(!StrEq(key, "*")) + { + auto server = llarp::utp::NewServerFromRouter(this); + if(!server->EnsureKeys(transport_keyfile.string().c_str())) + { + llarp::LogError("failed to ensure keyfile ", transport_keyfile); + return; + } + if(server->Configure(netloop, key, af, proto)) + { + AddInboundLink(server); + return; + } + if(af == AF_INET6) + { + // we failed to configure IPv6 + // try IPv4 + llarp::LogInfo("link ", key, + " failed to configure IPv6, trying IPv4"); + af = AF_INET; + if(server->Configure(netloop, key, af, proto)) + { + AddInboundLink(server); + return; + } + } + llarp::LogError("Failed to set up curvecp link"); + } + } + else if(StrEq(section, "network")) + { + if(StrEq(key, "profiles")) + { + routerProfilesFile = val; + routerProfiling.Load(val); + llarp::LogInfo("setting profiles to ", routerProfilesFile); + } + else if(StrEq(key, "strict-connect")) + { + if(IsServiceNode()) + { + llarp::LogError("cannot use strict-connect option as service node"); + return; + } + llarp::RouterID snode; + llarp::PubKey pk; + if(pk.FromString(val)) + { + if(strictConnectPubkeys.emplace(pk).second) + llarp::LogInfo("added ", pk, " to strict connect list"); + else + llarp::LogWarn("duplicate key for strict connect: ", pk); + } + else if(snode.FromString(val)) + { + if(strictConnectPubkeys.insert(snode).second) + llarp::LogInfo("added ", snode, " to strict connect list"); + else + llarp::LogWarn("duplicate key for strict connect: ", snode); + } + else + llarp::LogError("invalid key for strict-connect: ", val); + } + else + { + netConfig.insert(std::make_pair(key, val)); + } + } + else if(StrEq(section, "api")) + { + if(StrEq(key, "enabled")) + { + enableRPCServer = IsTrueValue(val); + } + if(StrEq(key, "bind")) + { + rpcBindAddr = val; + } + if(StrEq(key, "authkey")) + { + // TODO: add pubkey to whitelist + } + } + else if(StrEq(section, "services")) + { + if(LoadHiddenServiceConfig(val)) + { + llarp::LogInfo("loaded hidden service config for ", key); + } + else + { + llarp::LogWarn("failed to load hidden service config for ", key); + } + } + else if(StrEq(section, "lokid")) + { + if(StrEq(key, "service-node-seed")) + { + usingSNSeed = true; + ident_keyfile = val; + } + if(StrEq(key, "enabled")) + { + whitelistRouters = IsTrueValue(val); + } + if(StrEq(key, "jsonrpc")) + { + lokidRPCAddr = val; + } + if(StrEq(key, "username")) + { + lokidRPCUser = val; + } + if(StrEq(key, "password")) + { + lokidRPCPassword = val; + } + } + else if(StrEq(section, "dns")) + { + if(StrEq(key, "upstream")) + { + llarp::LogInfo("add upstream resolver ", val); + netConfig.emplace("upstream-dns", val); + } + if(StrEq(key, "bind")) + { + llarp::LogInfo("set local dns to ", val); + netConfig.emplace("local-dns", val); + } + } + else if(StrEq(section, "connect") + || (StrEq(section, "bootstrap") && StrEq(key, "add-node"))) + { + // llarp::LogDebug("connect section has ", key, "=", val); + bootstrapRCList.emplace_back(); + auto &rc = bootstrapRCList.back(); + if(!rc.Read(val)) + { + llarp::LogWarn("failed to decode bootstrap RC, file='", val, + "' rc=", rc); + bootstrapRCList.pop_back(); + return; + } + if(rc.Verify(crypto(), Now())) + { + llarp::LogInfo("Added bootstrap node ", RouterID(rc.pubkey)); + } + else + { + if(rc.IsExpired(Now())) + { + llarp::LogWarn("Bootstrap node ", RouterID(rc.pubkey), + " is too old and needs to be refreshed"); + } + else + { + llarp::LogError("malformed rc file='", val, "' rc=", rc); + } + bootstrapRCList.pop_back(); + } + } + else if(StrEq(section, "router")) + { + if(StrEq(key, "netid")) + { + if(strlen(val) <= _rc.netID.size()) + { + llarp::LogWarn("!!!! you have manually set netid to be '", val, + "' which does not equal '", Version::LLARP_NET_ID, + "' you will run as a different network, good luck " + "and " + "don't forget: something something MUH traffic " + "shape " + "correlation !!!!"); + llarp::NetID::DefaultValue() = + llarp::NetID(reinterpret_cast< const byte_t * >(strdup(val))); + // re set netid in our rc + _rc.netID = llarp::NetID(); + } + else + llarp::LogError("invalid netid '", val, "', is too long"); + } + if(StrEq(key, "nickname")) + { + _rc.SetNick(val); + // set logger name here + _glog.nodeName = rc().Nick(); + } + if(StrEq(key, "encryption-privkey")) + { + encryption_keyfile = val; + } + if(StrEq(key, "contact-file")) + { + our_rc_file = val; + } + if(StrEq(key, "transport-privkey")) + { + transport_keyfile = val; + } + if((StrEq(key, "identity-privkey") || StrEq(key, "ident-privkey")) + && !usingSNSeed) + { + ident_keyfile = val; + } + if(StrEq(key, "public-address") || StrEq(key, "public-ip")) + { + llarp::LogInfo("public ip ", val, " size ", strlen(val)); + if(strlen(val) < 17) + { + // assume IPv4 + // inet_pton(AF_INET, val, &ip4addr.sin_addr); + // struct sockaddr dest; + // sockaddr *dest = (sockaddr *)&ip4addr; + llarp::Addr a(val); + llarp::LogInfo("setting public ipv4 ", a); + addrInfo.ip = *a.addr6(); + publicOverride = true; + } + // llarp::Addr a(val); + } + if(StrEq(key, "public-port")) + { + llarp::LogInfo("Setting public port ", val); + int p = atoi(val); + // Not needed to flip upside-down - this is done in llarp::Addr(const + // AddressInfo&) + ip4addr.sin_port = p; + addrInfo.port = p; + publicOverride = true; + } + } + } + bool Router::CheckRenegotiateValid(RouterContact newrc, RouterContact oldrc) { @@ -1237,9 +1494,9 @@ namespace llarp if(defaultIfAddr == "") { llarp::LogError( - "Could not find any free lokitun interface names, can't - auto set up " "default HS context for client"); defaultIfAddr = "no"; - netConfig.emplace(std::make_pair("defaultIfAddr", defaultIfAddr)); + "Could not find any free lokitun interface names, + can't auto set up " "default HS context for client"); defaultIfAddr = + "no"; netConfig.emplace(std::make_pair("defaultIfAddr", defaultIfAddr)); return false; } netConfig.emplace(std::make_pair("defaultIfAddr", defaultIfAddr)); @@ -1325,27 +1582,24 @@ namespace llarp /// router struct RouterConfigValidator { - static void - ValidateEntry(llarp_config_iterator *i, const char *section, - const char *key, const char *val) + void + ValidateEntry(const char *section, const char *key, const char *val) { - RouterConfigValidator *self = - static_cast< RouterConfigValidator * >(i->user); - if(self->valid) + if(valid) { - if(!self->OnEntry(section, key, val)) + if(!OnEntry(section, key, val)) { llarp::LogError("invalid entry in section [", section, "]: '", key, "'='", val, "'"); - self->valid = false; + valid = false; } } } const Router *router; - llarp_config *config; + Config *config; bool valid; - RouterConfigValidator(const Router *r, llarp_config *conf) + RouterConfigValidator(const Router *r, Config *conf) : router(r), config(conf), valid(true) { } @@ -1366,23 +1620,22 @@ namespace llarp bool Validate() { - llarp_config_iterator iter; - iter.user = this; - iter.visit = &ValidateEntry; - llarp_config_iter(config, &iter); + using namespace std::placeholders; + config->visit( + std::bind(&RouterConfigValidator::ValidateEntry, this, _1, _2, _3)); return valid; } }; bool - Router::ValidateConfig(llarp_config *conf) const + Router::ValidateConfig(Config *conf) const { RouterConfigValidator validator(this, conf); return validator.Validate(); } bool - Router::Reconfigure(llarp_config *) + Router::Reconfigure(Config *) { // TODO: implement me return true; @@ -1475,267 +1728,4 @@ namespace llarp } return true; } - - void - router_iter_config(llarp_config_iterator *iter, const char *section, - const char *key, const char *val) - { - llarp::LogDebug(section, " ", key, "=", val); - Router *self = static_cast< Router * >(iter->user); - - int af; - uint16_t proto; - if(StrEq(val, "eth")) - { -#ifdef AF_LINK - af = AF_LINK; -#endif -#ifdef AF_PACKET - af = AF_PACKET; -#endif - proto = LLARP_ETH_PROTO; - } - else - { - // try IPv4 first - af = AF_INET; - proto = std::atoi(val); - } - - if(StrEq(section, "bind")) - { - if(!StrEq(key, "*")) - { - auto server = llarp::utp::NewServerFromRouter(self); - if(!server->EnsureKeys(self->transport_keyfile.string().c_str())) - { - llarp::LogError("failed to ensure keyfile ", self->transport_keyfile); - return; - } - if(server->Configure(self->netloop, key, af, proto)) - { - self->AddInboundLink(server); - return; - } - if(af == AF_INET6) - { - // we failed to configure IPv6 - // try IPv4 - llarp::LogInfo("link ", key, - " failed to configure IPv6, trying IPv4"); - af = AF_INET; - if(server->Configure(self->netloop, key, af, proto)) - { - self->AddInboundLink(server); - return; - } - } - llarp::LogError("Failed to set up curvecp link"); - } - } - else if(StrEq(section, "network")) - { - if(StrEq(key, "profiles")) - { - self->routerProfilesFile = val; - self->routerProfiling.Load(val); - llarp::LogInfo("setting profiles to ", self->routerProfilesFile); - } - else if(StrEq(key, "strict-connect")) - { - if(self->IsServiceNode()) - { - llarp::LogError("cannot use strict-connect option as service node"); - return; - } - llarp::RouterID snode; - llarp::PubKey pk; - if(pk.FromString(val)) - { - if(self->strictConnectPubkeys.emplace(pk).second) - llarp::LogInfo("added ", pk, " to strict connect list"); - else - llarp::LogWarn("duplicate key for strict connect: ", pk); - } - else if(snode.FromString(val)) - { - if(self->strictConnectPubkeys.insert(snode).second) - llarp::LogInfo("added ", snode, " to strict connect list"); - else - llarp::LogWarn("duplicate key for strict connect: ", snode); - } - else - llarp::LogError("invalid key for strict-connect: ", val); - } - else - { - self->netConfig.insert(std::make_pair(key, val)); - } - } - else if(StrEq(section, "api")) - { - if(StrEq(key, "enabled")) - { - self->enableRPCServer = IsTrueValue(val); - } - if(StrEq(key, "bind")) - { - self->rpcBindAddr = val; - } - if(StrEq(key, "authkey")) - { - // TODO: add pubkey to whitelist - } - } - else if(StrEq(section, "services")) - { - if(self->LoadHiddenServiceConfig(val)) - { - llarp::LogInfo("loaded hidden service config for ", key); - } - else - { - llarp::LogWarn("failed to load hidden service config for ", key); - } - } - else if(StrEq(section, "lokid")) - { - if(StrEq(key, "service-node-seed")) - { - self->usingSNSeed = true; - self->ident_keyfile = val; - } - if(StrEq(key, "enabled")) - { - self->whitelistRouters = IsTrueValue(val); - } - if(StrEq(key, "jsonrpc")) - { - self->lokidRPCAddr = val; - } - if(StrEq(key, "username")) - { - self->lokidRPCUser = val; - } - if(StrEq(key, "password")) - { - self->lokidRPCPassword = val; - } - } - else if(StrEq(section, "dns")) - { - if(StrEq(key, "upstream")) - { - llarp::LogInfo("add upstream resolver ", val); - self->netConfig.emplace(std::make_pair("upstream-dns", val)); - } - if(StrEq(key, "bind")) - { - llarp::LogInfo("set local dns to ", val); - self->netConfig.emplace(std::make_pair("local-dns", val)); - } - } - else if(StrEq(section, "connect") - || (StrEq(section, "bootstrap") && StrEq(key, "add-node"))) - { - // llarp::LogDebug("connect section has ", key, "=", val); - self->bootstrapRCList.emplace_back(); - auto &rc = self->bootstrapRCList.back(); - if(!rc.Read(val)) - { - llarp::LogWarn("failed to decode bootstrap RC, file='", val, - "' rc=", rc); - self->bootstrapRCList.pop_back(); - return; - } - if(rc.Verify(self->crypto(), self->Now())) - { - llarp::LogInfo("Added bootstrap node ", RouterID(rc.pubkey)); - } - else - { - if(rc.IsExpired(self->Now())) - { - llarp::LogWarn("Bootstrap node ", RouterID(rc.pubkey), - " is too old and needs to be refreshed"); - } - else - { - llarp::LogError("malformed rc file='", val, "' rc=", rc); - } - self->bootstrapRCList.pop_back(); - } - } - else if(StrEq(section, "router")) - { - if(StrEq(key, "netid")) - { - if(strlen(val) <= self->_rc.netID.size()) - { - llarp::LogWarn("!!!! you have manually set netid to be '", val, - "' which does not equal '", Version::LLARP_NET_ID, - "' you will run as a different network, good luck " - "and " - "don't forget: something something MUH traffic " - "shape " - "correlation !!!!"); - llarp::NetID::DefaultValue() = - llarp::NetID(reinterpret_cast< const byte_t * >(strdup(val))); - // re set netid in our rc - self->_rc.netID = llarp::NetID(); - } - else - llarp::LogError("invalid netid '", val, "', is too long"); - } - if(StrEq(key, "nickname")) - { - self->_rc.SetNick(val); - // set logger name here - _glog.nodeName = self->rc().Nick(); - } - if(StrEq(key, "encryption-privkey")) - { - self->encryption_keyfile = val; - } - if(StrEq(key, "contact-file")) - { - self->our_rc_file = val; - } - if(StrEq(key, "transport-privkey")) - { - self->transport_keyfile = val; - } - if((StrEq(key, "identity-privkey") || StrEq(key, "ident-privkey")) - && !self->usingSNSeed) - { - self->ident_keyfile = val; - } - if(StrEq(key, "public-address") || StrEq(key, "public-ip")) - { - llarp::LogInfo("public ip ", val, " size ", strlen(val)); - if(strlen(val) < 17) - { - // assume IPv4 - // inet_pton(AF_INET, val, &self->ip4addr.sin_addr); - // struct sockaddr dest; - // sockaddr *dest = (sockaddr *)&self->ip4addr; - llarp::Addr a(val); - llarp::LogInfo("setting public ipv4 ", a); - self->addrInfo.ip = *a.addr6(); - self->publicOverride = true; - } - // llarp::Addr a(val); - } - if(StrEq(key, "public-port")) - { - llarp::LogInfo("Setting public port ", val); - int p = atoi(val); - // Not needed to flip upside-down - this is done in llarp::Addr(const - // AddressInfo&) - self->ip4addr.sin_port = p; - self->addrInfo.port = p; - self->publicOverride = true; - } - } - } // namespace llarp } // namespace llarp diff --git a/llarp/router/router.hpp b/llarp/router/router.hpp index 17b96ca44..97e7875fd 100644 --- a/llarp/router/router.hpp +++ b/llarp/router/router.hpp @@ -1,7 +1,6 @@ #ifndef LLARP_ROUTER_HPP #define LLARP_ROUTER_HPP -#include #include #include #include @@ -33,8 +32,9 @@ namespace llarp { + struct Config; struct Crypto; -} +} // namespace llarp bool llarp_findOrCreateEncryption(llarp::Crypto *crypto, const fs::path &fpath, @@ -342,7 +342,7 @@ namespace llarp AddHiddenService(const llarp::service::Config::section_t &config); bool - Configure(struct llarp_config *conf); + Configure(Config *conf); bool Ready(); @@ -391,13 +391,13 @@ namespace llarp /// inject configuration and reconfigure router bool - Reconfigure(llarp_config *conf); + Reconfigure(Config *conf); /// validate new configuration against old one /// return true on 100% valid /// return false if not 100% valid bool - ValidateConfig(llarp_config *conf) const; + ValidateConfig(Config *conf) const; /// send to remote router or queue for sending /// returns false on overflow @@ -539,6 +539,9 @@ namespace llarp for(const auto &item : in) out.push_back({item.first, item.second}); } + + void + router_iter_config(const char *section, const char *key, const char *val); }; } // namespace llarp diff --git a/llarp/rpc/rpc.cpp b/llarp/rpc/rpc.cpp index 56254b5f4..e8ce6959b 100644 --- a/llarp/rpc/rpc.cpp +++ b/llarp/rpc/rpc.cpp @@ -388,13 +388,12 @@ namespace llarp #endif - Caller::Caller(Router* r) : m_Impl(new CallerImpl(r)) + Caller::Caller(Router* r) : m_Impl(std::make_unique< CallerImpl >(r)) { } Caller::~Caller() { - delete m_Impl; } void @@ -421,13 +420,12 @@ namespace llarp m_Impl->SetBasicAuth(user, passwd); } - Server::Server(Router* r) : m_Impl(new ServerImpl(r)) + Server::Server(Router* r) : m_Impl(std::make_unique< ServerImpl >(r)) { } Server::~Server() { - delete m_Impl; } void diff --git a/llarp/rpc/rpc.hpp b/llarp/rpc/rpc.hpp index 611962b47..2fe990a03 100644 --- a/llarp/rpc/rpc.hpp +++ b/llarp/rpc/rpc.hpp @@ -3,8 +3,9 @@ #include -#include #include +#include +#include namespace llarp { @@ -29,7 +30,7 @@ namespace llarp Stop(); private: - ServerImpl* m_Impl; + std::unique_ptr< ServerImpl > m_Impl; }; struct CallerImpl; @@ -57,7 +58,7 @@ namespace llarp Tick(llarp_time_t now); private: - CallerImpl* m_Impl; + std::unique_ptr< CallerImpl > m_Impl; }; } // namespace rpc diff --git a/llarp/util/threadpool.cpp b/llarp/util/threadpool.cpp index 50a48d1ab..23e128daf 100644 --- a/llarp/util/threadpool.cpp +++ b/llarp/util/threadpool.cpp @@ -6,25 +6,6 @@ #include #include -struct llarp_threadpool -{ - std::unique_ptr< llarp::thread::Pool > impl; - - llarp::util::Mutex m_access; - uint32_t ids = 0; - std::queue< std::function< void(void) > > jobs; - - llarp_threadpool(int workers, const char *name) - { - (void)name; - impl.reset(new llarp::thread::Pool(workers, workers * 128)); - } - - llarp_threadpool() - { - } -}; - struct llarp_threadpool * llarp_init_threadpool(int workers, const char *name) { diff --git a/llarp/util/threadpool.h b/llarp/util/threadpool.h index d07b3b111..c7a068bbc 100644 --- a/llarp/util/threadpool.h +++ b/llarp/util/threadpool.h @@ -1,7 +1,31 @@ #ifndef LLARP_THREADPOOL_H #define LLARP_THREADPOOL_H -struct llarp_threadpool; +#include +#include + +#include +#include + +struct llarp_threadpool +{ + std::unique_ptr< llarp::thread::ThreadPool > impl; + + llarp::util::Mutex m_access; + uint32_t ids = 0; + std::queue< std::function< void(void) > > jobs; + + llarp_threadpool(int workers, const char *name) + : impl( + std::make_unique< llarp::thread::ThreadPool >(workers, workers * 128)) + { + (void)name; + } + + llarp_threadpool() + { + } +}; struct llarp_threadpool * llarp_init_threadpool(int workers, const char *name); diff --git a/llarp/util/timer.cpp b/llarp/util/timer.cpp index c0b829136..3611e2e38 100644 --- a/llarp/util/timer.cpp +++ b/llarp/util/timer.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -59,7 +60,7 @@ struct llarp_timer_context std::unordered_map< uint32_t, std::unique_ptr< llarp::timer > > timers; std::priority_queue< std::unique_ptr< llarp::timer > > calling; llarp::util::Mutex tickerMutex; - llarp::util::Condition* ticker = nullptr; + std::unique_ptr< llarp::util::Condition > ticker; std::chrono::milliseconds nextTickLen = std::chrono::milliseconds(100); llarp_time_t m_Now; @@ -74,8 +75,6 @@ struct llarp_timer_context ~llarp_timer_context() { - if(ticker) - delete ticker; } bool @@ -117,10 +116,8 @@ struct llarp_timer_context llarp::util::Lock lock(timersMutex); uint32_t id = ++ids; - timers.insert( - std::make_pair(id, - std::unique_ptr< llarp::timer >( - new llarp::timer(m_Now, timeout_ms, user, func)))); + timers.emplace( + id, std::make_unique< llarp::timer >(m_Now, timeout_ms, user, func)); return id; } @@ -247,7 +244,7 @@ llarp_timer_tick_all_async(struct llarp_timer_context* t, void llarp_timer_run(struct llarp_timer_context* t, struct llarp_threadpool* pool) { - t->ticker = new llarp::util::Condition(); + t->ticker = std::make_unique< llarp::util::Condition >(); while(t->run()) { // wait for timer mutex