diff --git a/include/opendht/dht_interface.h b/include/opendht/dht_interface.h index 3f8c7eb3..2ccc80ee 100644 --- a/include/opendht/dht_interface.h +++ b/include/opendht/dht_interface.h @@ -27,19 +27,14 @@ namespace dht { namespace net { -class DatagramSocket; + class DatagramSocket; } -class OPENDHT_PUBLIC DhtInterface -{ +class OPENDHT_PUBLIC DhtInterface { public: DhtInterface() = default; - DhtInterface(const Logger& l) - : logger_(std::make_shared(l)) - {} - DhtInterface(const std::shared_ptr& l) - : logger_(l) - {} + DhtInterface(const Logger& l) : logger_(std::make_shared(l)) {} + DhtInterface(const std::shared_ptr& l) : logger_(l) {} virtual ~DhtInterface() = default; // [[deprecated]] @@ -54,7 +49,9 @@ public: virtual NodeStatus getStatus(sa_family_t af) const = 0; virtual NodeStatus getStatus() const = 0; - void addOnConnectedCallback(std::function cb) { onConnectCallbacks_.emplace(std::move(cb)); } + void addOnConnectedCallback(std::function cb) { + onConnectCallbacks_.emplace(std::move(cb)); + } virtual void setOnPublicAddressChanged(PublicAddressChangedCb) {} virtual net::DatagramSocket* getSocket() const { return {}; } @@ -94,12 +91,10 @@ public: virtual void insertNode(const InfoHash& id, const SockAddr&) = 0; virtual void insertNode(const NodeExport& n) = 0; - virtual void pingNode(SockAddr, DoneCallbackSimple&& cb = {}) = 0; + virtual void pingNode(SockAddr, DoneCallbackSimple&& cb={}) = 0; - virtual time_point periodic(const uint8_t* buf, size_t buflen, SockAddr, const time_point& now) = 0; - virtual time_point periodic( - const uint8_t* buf, size_t buflen, const sockaddr* from, socklen_t fromlen, const time_point& now) - = 0; + virtual time_point periodic(const uint8_t *buf, size_t buflen, SockAddr, const time_point& now) = 0; + virtual time_point periodic(const uint8_t *buf, size_t buflen, const sockaddr* from, socklen_t fromlen, const time_point& now) = 0; /** * Get a value by searching on all available protocols (IPv4, IPv6), @@ -111,18 +106,10 @@ public: cb and donecb won't be called again afterward. * @param f a filter function used to prefilter values. */ - virtual void get( - const InfoHash& key, GetCallback cb, DoneCallback donecb = {}, Value::Filter&& f = {}, Where&& w = {}) - = 0; - virtual void get( - const InfoHash& key, GetCallback cb, DoneCallbackSimple donecb = {}, Value::Filter&& f = {}, Where&& w = {}) - = 0; - virtual void get( - const InfoHash& key, GetCallbackSimple cb, DoneCallback donecb = {}, Value::Filter&& f = {}, Where&& w = {}) - = 0; - virtual void get( - const InfoHash& key, GetCallbackSimple cb, DoneCallbackSimple donecb, Value::Filter&& f = {}, Where&& w = {}) - = 0; + virtual void get(const InfoHash& key, GetCallback cb, DoneCallback donecb={}, Value::Filter&& f={}, Where&& w = {}) = 0; + virtual void get(const InfoHash& key, GetCallback cb, DoneCallbackSimple donecb={}, Value::Filter&& f={}, Where&& w = {}) = 0; + virtual void get(const InfoHash& key, GetCallbackSimple cb, DoneCallback donecb={}, Value::Filter&& f={}, Where&& w = {}) = 0; + virtual void get(const InfoHash& key, GetCallbackSimple cb, DoneCallbackSimple donecb, Value::Filter&& f={}, Where&& w = {}) = 0; /** * Similar to Dht::get, but sends a Query to filter data remotely. @@ -154,29 +141,25 @@ public: * The done callback will be called once, when the first announce succeeds, or fails. */ virtual void put(const InfoHash& key, - Sp, - DoneCallback cb = nullptr, - time_point created = time_point::max(), - bool permanent = false) - = 0; + Sp, + DoneCallback cb=nullptr, + time_point created=time_point::max(), + bool permanent = false) = 0; virtual void put(const InfoHash& key, - const Sp& v, - DoneCallbackSimple cb, - time_point created = time_point::max(), - bool permanent = false) - = 0; + const Sp& v, + DoneCallbackSimple cb, + time_point created=time_point::max(), + bool permanent = false) = 0; virtual void put(const InfoHash& key, - Value&& v, - DoneCallback cb = nullptr, - time_point created = time_point::max(), - bool permanent = false) - = 0; + Value&& v, + DoneCallback cb=nullptr, + time_point created=time_point::max(), + bool permanent = false) = 0; virtual void put(const InfoHash& key, - Value&& v, - DoneCallbackSimple cb, - time_point created = time_point::max(), - bool permanent = false) - = 0; + Value&& v, + DoneCallbackSimple cb, + time_point created=time_point::max(), + bool permanent = false) = 0; /** * Get data currently being put at the given hash. @@ -201,9 +184,9 @@ public: * * @return a token to cancel the listener later. */ - virtual size_t listen(const InfoHash&, GetCallback, Value::Filter = {}, Where w = {}) = 0; - virtual size_t listen(const InfoHash& key, GetCallbackSimple cb, Value::Filter f = {}, Where w = {}) = 0; - virtual size_t listen(const InfoHash&, ValueCallback, Value::Filter = {}, Where w = {}) = 0; + virtual size_t listen(const InfoHash&, GetCallback, Value::Filter={}, Where w = {}) = 0; + virtual size_t listen(const InfoHash& key, GetCallbackSimple cb, Value::Filter f={}, Where w = {}) = 0; + virtual size_t listen(const InfoHash&, ValueCallback, Value::Filter={}, Where w = {}) = 0; virtual bool cancelListen(const InfoHash&, size_t token) = 0; @@ -250,7 +233,16 @@ public: virtual std::vector getPublicAddress(sa_family_t family = 0) = 0; - virtual void setLogger(const std::shared_ptr& l) { logger_ = l; } + virtual void setLogger(const Logger& l) { + if (logger_) + *logger_ = l; + else + logger_= std::make_shared(l); + } + + virtual void setLogger(const std::shared_ptr& l) { + logger_ = l; + } /** * Only print logs related to the given InfoHash (if given), or disable filter (if zeroes). diff --git a/include/opendht/logger.h b/include/opendht/logger.h index 188b865e..15acba30 100644 --- a/include/opendht/logger.h +++ b/include/opendht/logger.h @@ -32,45 +32,17 @@ namespace log { enum class LogLevel { debug, warning, error }; -using LogMethod = std::function; +using LogMethod = std::function; struct OPENDHT_PUBLIC Logger { Logger() = delete; - Logger(LogMethod&& l, std::string tag = "") - : logger_(std::move(l)) - , tag_(std::move(tag)) - , prefix_(tag_.empty() ? "" : fmt::format("[{}] ", tag_)) + Logger(LogMethod&& l) + : logger(std::move(l)) { - if (!logger_) - throw std::invalid_argument {"logger must be set"}; + if (!logger) + throw std::invalid_argument {"logger and loggerf must be set"}; } - Logger(const Logger& parent, std::string tag) - : logger_(parent.logger_) - , tag_(std::move(tag)) - , prefix_(fmt::format("{}[{}] ", parent.prefix_, tag_)) - {} - - std::shared_ptr createChild(std::string tag) - { - auto child = std::make_shared(*this, std::move(tag)); - children_.push_back(child); - return child; - } - - void setFilter(std::string_view tag) - { - enable_ = tag.empty() or tag_ == tag; - for (auto it = children_.begin(); it != children_.end();) { - if (auto c = it->lock()) { - c->setFilter(enable_ ? std::string_view {} : tag); - ++it; - } else { - it = children_.erase(it); - } - } - } - void setFilter(const InfoHash& f) { filter_ = f; @@ -78,37 +50,34 @@ struct OPENDHT_PUBLIC Logger } inline void log0(LogLevel level, fmt::string_view format, fmt::printf_args args) const { - if (enable_ and not filterEnable_) - logger_(level, prefix_, fmt::vsprintf(format, args)); + if (not filterEnable_) + logger(level, fmt::vsprintf(format, args)); } inline void log1(LogLevel level, const InfoHash& f, fmt::string_view format, fmt::printf_args args) const { - if (enable_ and (not filterEnable_ or f == filter_)) - logger_(level, prefix_, fmt::vsprintf(format, args)); + if (not filterEnable_ or f == filter_) + logger(level, fmt::vsprintf(format, args)); } inline void log2( LogLevel level, const InfoHash& f1, const InfoHash& f2, fmt::string_view format, fmt::printf_args args) const { - if (enable_ and (not filterEnable_ or f1 == filter_ or f2 == filter_)) - logger_(level, prefix_, fmt::vsprintf(format, args)); + if (not filterEnable_ or f1 == filter_ or f2 == filter_) + logger(level, fmt::vsprintf(format, args)); } template inline void debug(fmt::format_string format, Args&&... args) const { - if (enable_) - logger_(LogLevel::debug, prefix_, fmt::format(format, std::forward(args)...)); + logger(LogLevel::debug, fmt::format(format, std::forward(args)...)); } template inline void warn(fmt::format_string format, Args&&... args) const { - if (enable_) - logger_(LogLevel::warning, prefix_, fmt::format(format, std::forward(args)...)); + logger(LogLevel::warning, fmt::format(format, std::forward(args)...)); } template inline void error(fmt::format_string format, Args&&... args) const { - if (enable_) - logger_(LogLevel::error, prefix_, fmt::format(format, std::forward(args)...)); + logger(LogLevel::error, fmt::format(format, std::forward(args)...)); } template inline void d(fmt::format_string format, T&&... args) const @@ -157,13 +126,9 @@ struct OPENDHT_PUBLIC Logger } private: - const LogMethod logger_ = {}; - const std::string tag_ {}; - const std::string prefix_ {}; - bool enable_ {true}; + LogMethod logger = {}; bool filterEnable_ {false}; InfoHash filter_ {}; - std::vector> children_ {}; }; } // namespace log diff --git a/include/opendht/securedht.h b/include/opendht/securedht.h index c845e690..026389e5 100644 --- a/include/opendht/securedht.h +++ b/include/opendht/securedht.h @@ -30,9 +30,9 @@ namespace dht { -class OPENDHT_PUBLIC SecureDht final : public DhtInterface -{ +class OPENDHT_PUBLIC SecureDht final : public DhtInterface { public: + typedef std::function SignatureCheckCallback; using Config = SecureDhtConfig; @@ -41,7 +41,7 @@ public: { auto c = conf.node_config; if (not c.node_id and conf.id.second) - c.node_id = InfoHash::get("node:" + conf.id.second->getId().toString()); + c.node_id = InfoHash::get("node:"+conf.id.second->getId().toString()); return c; } @@ -51,37 +51,36 @@ public: * id: the identity to use for the crypto layer and to compute * our own hash on the Dht. */ - SecureDht(std::unique_ptr dht, - Config config, - IdentityAnnouncedCb iacb = {}, - const std::shared_ptr& l = {}); + SecureDht(std::unique_ptr dht, Config config, IdentityAnnouncedCb iacb = {}, const std::shared_ptr& l = {}); virtual ~SecureDht(); - InfoHash getId() const { return key_ ? key_->getPublicKey().getId() : InfoHash(); } - PkId getLongId() const { return key_ ? key_->getPublicKey().getLongId() : PkId(); } - Sp getPublicKey() const { return key_ ? key_->getSharedPublicKey() : Sp {}; } + InfoHash getId() const { + return key_ ? key_->getPublicKey().getId() : InfoHash(); + } + PkId getLongId() const { + return key_ ? key_->getPublicKey().getLongId() : PkId(); + } + Sp getPublicKey() const { + return key_ ? key_->getSharedPublicKey() : Sp{}; + } ValueType secureType(ValueType&& type); - ValueType secureType(const ValueType& type) - { + ValueType secureType(const ValueType& type) { ValueType tmp_type = type; return secureType(std::move(tmp_type)); } - void registerType(const ValueType& type) override - { + void registerType(const ValueType& type) override { if (dht_) dht_->registerType(secureType(type)); } - void registerType(ValueType&& type) - { + void registerType(ValueType&& type) { if (dht_) dht_->registerType(secureType(std::forward(type))); } - void registerInsecureType(const ValueType& type) - { + void registerInsecureType(const ValueType& type) { if (dht_) dht_->registerType(type); } @@ -91,29 +90,14 @@ public: * If the signature is unable to be checked, or if the data is unable to be decrypted, it is not returned. * Public, non-signed & non-encrypted data is retransmitted as-is. */ - void get(const InfoHash& id, GetCallback cb, DoneCallback donecb = {}, Value::Filter&& = {}, Where&& w = {}) override; - void get(const InfoHash& id, - GetCallback cb, - DoneCallbackSimple donecb = {}, - Value::Filter&& f = {}, - Where&& w = {}) override - { + void get(const InfoHash& id, GetCallback cb, DoneCallback donecb={}, Value::Filter&& = {}, Where&& w = {}) override; + void get(const InfoHash& id, GetCallback cb, DoneCallbackSimple donecb={}, Value::Filter&& f = {}, Where&& w = {}) override { get(id, cb, bindDoneCb(donecb), std::forward(f), std::forward(w)); } - void get(const InfoHash& key, - GetCallbackSimple cb, - DoneCallback donecb = {}, - Value::Filter&& f = {}, - Where&& w = {}) override - { + void get(const InfoHash& key, GetCallbackSimple cb, DoneCallback donecb={}, Value::Filter&& f={}, Where&& w = {}) override { get(key, bindGetCb(cb), donecb, std::forward(f), std::forward(w)); } - void get(const InfoHash& key, - GetCallbackSimple cb, - DoneCallbackSimple donecb, - Value::Filter&& f = {}, - Where&& w = {}) override - { + void get(const InfoHash& key, GetCallbackSimple cb, DoneCallbackSimple donecb, Value::Filter&& f={}, Where&& w = {}) override { get(key, bindGetCb(cb), bindDoneCb(donecb), std::forward(f), std::forward(w)); } @@ -121,8 +105,7 @@ public: * Will take ownership of the value, sign it using our private key and put it in the DHT. */ void putSigned(const InfoHash& hash, Sp val, DoneCallback callback, bool permanent = false); - void putSigned(const InfoHash& hash, Value&& v, DoneCallback callback, bool permanent = false) - { + void putSigned(const InfoHash& hash, Value&& v, DoneCallback callback, bool permanent = false) { putSigned(hash, std::make_shared(std::move(v)), callback, permanent); } @@ -131,24 +114,16 @@ public: * and put it in the DHT. * The operation will be immediate if the recipient' public key is known (otherwise it will be retrived first). */ - void putEncrypted( - const InfoHash& hash, const InfoHash& to, Sp val, DoneCallback callback, bool permanent = false); + void putEncrypted(const InfoHash& hash, const InfoHash& to, Sp val, DoneCallback callback, bool permanent = false); [[deprecated("Use the shared_ptr version instead")]] - void putEncrypted(const InfoHash& hash, const InfoHash& to, Value&& v, DoneCallback callback, bool permanent = false) - { + void putEncrypted(const InfoHash& hash, const InfoHash& to, Value&& v, DoneCallback callback, bool permanent = false) { putEncrypted(hash, to, std::make_shared(std::move(v)), callback, permanent); } - void putEncrypted(const InfoHash& hash, - const crypto::PublicKey& to, - Sp val, - DoneCallback callback, - bool permanent = false); + void putEncrypted(const InfoHash& hash, const crypto::PublicKey& to, Sp val, DoneCallback callback, bool permanent = false); [[deprecated("Use the shared_ptr version instead")]] - void putEncrypted( - const InfoHash& hash, const crypto::PublicKey& to, Value&& v, DoneCallback callback, bool permanent = false) - { + void putEncrypted(const InfoHash& hash, const crypto::PublicKey& to, Value&& v, DoneCallback callback, bool permanent = false) { putEncrypted(hash, to, std::make_shared(std::move(v)), callback, permanent); } @@ -182,136 +157,201 @@ public: * The search key used is the public key ID, so there may be multiple certificates retured, signed with * the same private key. */ - void setLocalCertificateStore(CertificateStoreQueryLegacy&& query_method) - { + void setLocalCertificateStore(CertificateStoreQueryLegacy&& query_method) { localQueryMethodLegacy_ = std::move(query_method); } - void setLocalCertificateStore(CertificateStoreQuery&& query_method) { localQueryMethod_ = std::move(query_method); } - void setOnPublicAddressChanged(PublicAddressChangedCb cb) override { dht_->setOnPublicAddressChanged(cb); } + void setLocalCertificateStore(CertificateStoreQuery&& query_method) { + localQueryMethod_ = std::move(query_method); + } + void setOnPublicAddressChanged(PublicAddressChangedCb cb) override { + dht_->setOnPublicAddressChanged(cb); + } /** * SecureDht to Dht proxy */ - void shutdown(ShutdownCallback cb, bool stop = false) override { dht_->shutdown(cb, stop); } - void dumpTables() const override { dht_->dumpTables(); } + void shutdown(ShutdownCallback cb, bool stop = false) override { + dht_->shutdown(cb, stop); + } + void dumpTables() const override { + dht_->dumpTables(); + } inline const InfoHash& getNodeId() const override { return dht_->getNodeId(); } - std::pair getStoreSize() const override { return dht_->getStoreSize(); } - std::string getStorageLog() const override { return dht_->getStorageLog(); } - std::string getStorageLog(const InfoHash& h) const override { return dht_->getStorageLog(h); } - void setStorageLimit(size_t limit = DEFAULT_STORAGE_LIMIT) override { dht_->setStorageLimit(limit); } - size_t getStorageLimit() const override { return dht_->getStorageLimit(); } + std::pair getStoreSize() const override { + return dht_->getStoreSize(); + } + std::string getStorageLog() const override { + return dht_->getStorageLog(); + } + std::string getStorageLog(const InfoHash& h) const override { + return dht_->getStorageLog(h); + } + void setStorageLimit(size_t limit = DEFAULT_STORAGE_LIMIT) override { + dht_->setStorageLimit(limit); + } + size_t getStorageLimit() const override { + return dht_->getStorageLimit(); + } - std::vector exportNodes() const override { return dht_->exportNodes(); } - std::vector exportValues() const override { return dht_->exportValues(); } - void importValues(const std::vector& v) override { dht_->importValues(v); } - NodeStats getNodesStats(sa_family_t af) const override { return dht_->getNodesStats(af); } - std::vector getNodeMessageStats(bool in = false) override { return dht_->getNodeMessageStats(in); } - std::string getRoutingTablesLog(sa_family_t af) const override { return dht_->getRoutingTablesLog(af); } - std::string getSearchesLog(sa_family_t af) const override { return dht_->getSearchesLog(af); } - std::string getSearchLog(const InfoHash& h, sa_family_t af = AF_UNSPEC) const override - { + std::vector exportNodes() const override { + return dht_->exportNodes(); + } + std::vector exportValues() const override { + return dht_->exportValues(); + } + void importValues(const std::vector& v) override { + dht_->importValues(v); + } + NodeStats getNodesStats(sa_family_t af) const override { + return dht_->getNodesStats(af); + } + std::vector getNodeMessageStats(bool in = false) override { + return dht_->getNodeMessageStats(in); + } + std::string getRoutingTablesLog(sa_family_t af) const override { + return dht_->getRoutingTablesLog(af); + } + std::string getSearchesLog(sa_family_t af) const override { + return dht_->getSearchesLog(af); + } + std::string getSearchLog(const InfoHash& h, sa_family_t af = AF_UNSPEC) const override { return dht_->getSearchLog(h, af); } - std::vector getPublicAddress(sa_family_t family = 0) override { return dht_->getPublicAddress(family); } - time_point periodic(const uint8_t* buf, size_t buflen, SockAddr sa, const time_point& now) override - { + std::vector getPublicAddress(sa_family_t family = 0) override { + return dht_->getPublicAddress(family); + } + time_point periodic(const uint8_t *buf, size_t buflen, SockAddr sa, const time_point& now) override { return dht_->periodic(buf, buflen, std::move(sa), now); } - time_point periodic( - const uint8_t* buf, size_t buflen, const sockaddr* from, socklen_t fromlen, const time_point& now) override - { + time_point periodic(const uint8_t *buf, size_t buflen, const sockaddr* from, socklen_t fromlen, const time_point& now) override { return dht_->periodic(buf, buflen, from, fromlen, now); } - NodeStatus updateStatus(sa_family_t af) override { return dht_->updateStatus(af); } - NodeStatus getStatus(sa_family_t af) const override { return dht_->getStatus(af); } - NodeStatus getStatus() const override { return dht_->getStatus(); } - net::DatagramSocket* getSocket() const override { return dht_->getSocket(); }; - bool isRunning(sa_family_t af = 0) const override { return dht_->isRunning(af); } - const ValueType& getType(ValueType::Id type_id) const override { return dht_->getType(type_id); } - void addBootstrap(const std::string& host, const std::string& service) override - { + NodeStatus updateStatus(sa_family_t af) override { + return dht_->updateStatus(af); + } + NodeStatus getStatus(sa_family_t af) const override { + return dht_->getStatus(af); + } + NodeStatus getStatus() const override { + return dht_->getStatus(); + } + net::DatagramSocket* getSocket() const override { + return dht_->getSocket(); + }; + bool isRunning(sa_family_t af = 0) const override { + return dht_->isRunning(af); + } + const ValueType& getType(ValueType::Id type_id) const override { + return dht_->getType(type_id); + } + void addBootstrap(const std::string& host, const std::string& service) override { dht_->addBootstrap(host, service); } - void clearBootstrap() override { dht_->clearBootstrap(); } - void insertNode(const InfoHash& id, const SockAddr& sa) override { dht_->insertNode(id, sa); } - void insertNode(const NodeExport& n) override { dht_->insertNode(n); } - void pingNode(SockAddr sa, DoneCallbackSimple&& cb = {}) override { dht_->pingNode(std::move(sa), std::move(cb)); } - void query(const InfoHash& key, QueryCallback cb, DoneCallback done_cb = {}, Query&& q = {}) override - { + void clearBootstrap() override { + dht_->clearBootstrap(); + } + void insertNode(const InfoHash& id, const SockAddr& sa) override { + dht_->insertNode(id, sa); + } + void insertNode(const NodeExport& n) override { + dht_->insertNode(n); + } + void pingNode(SockAddr sa, DoneCallbackSimple&& cb={}) override { + dht_->pingNode(std::move(sa), std::move(cb)); + } + void query(const InfoHash& key, QueryCallback cb, DoneCallback done_cb = {}, Query&& q = {}) override { dht_->query(key, cb, done_cb, std::move(q)); } - void query(const InfoHash& key, QueryCallback cb, DoneCallbackSimple done_cb = {}, Query&& q = {}) override - { + void query(const InfoHash& key, QueryCallback cb, DoneCallbackSimple done_cb = {}, Query&& q = {}) override { dht_->query(key, cb, done_cb, std::move(q)); } - std::vector> getLocal(const InfoHash& key, const Value::Filter& f = {}) const override - { + std::vector> getLocal(const InfoHash& key, const Value::Filter& f = {}) const override { return dht_->getLocal(key, f); } - Sp getLocalById(const InfoHash& key, Value::Id vid) const override { return dht_->getLocalById(key, vid); } + Sp getLocalById(const InfoHash& key, Value::Id vid) const override { + return dht_->getLocalById(key, vid); + } void put(const InfoHash& key, - Sp v, - DoneCallback cb = nullptr, - time_point created = time_point::max(), - bool permanent = false) override + Sp v, + DoneCallback cb=nullptr, + time_point created=time_point::max(), + bool permanent = false) override { dht_->put(key, v, cb, created, permanent); } void put(const InfoHash& key, - const Sp& v, - DoneCallbackSimple cb, - time_point created = time_point::max(), - bool permanent = false) override + const Sp& v, + DoneCallbackSimple cb, + time_point created=time_point::max(), + bool permanent = false) override { dht_->put(key, v, cb, created, permanent); } void put(const InfoHash& key, - Value&& v, - DoneCallback cb = nullptr, - time_point created = time_point::max(), - bool permanent = false) override + Value&& v, + DoneCallback cb=nullptr, + time_point created=time_point::max(), + bool permanent = false) override { dht_->put(key, std::move(v), cb, created, permanent); } void put(const InfoHash& key, - Value&& v, - DoneCallbackSimple cb, - time_point created = time_point::max(), - bool permanent = false) override + Value&& v, + DoneCallbackSimple cb, + time_point created=time_point::max(), + bool permanent = false) override { dht_->put(key, std::move(v), cb, created, permanent); } - std::vector> getPut(const InfoHash& h) const override { return dht_->getPut(h); } - Sp getPut(const InfoHash& h, const Value::Id& vid) const override { return dht_->getPut(h, vid); } - bool cancelPut(const InfoHash& h, const Value::Id& vid) override { return dht_->cancelPut(h, vid); } + std::vector> getPut(const InfoHash& h) const override { + return dht_->getPut(h); + } + Sp getPut(const InfoHash& h, const Value::Id& vid) const override { + return dht_->getPut(h, vid); + } + bool cancelPut(const InfoHash& h, const Value::Id& vid) override { + return dht_->cancelPut(h, vid); + } - size_t listen(const InfoHash& key, ValueCallback, Value::Filter = {}, Where = {}) override; + size_t listen(const InfoHash& key, ValueCallback, Value::Filter={}, Where={}) override; size_t listen(const InfoHash& key, GetCallback cb, Value::Filter = {}, Where w = {}) override; - size_t listen(const InfoHash& key, GetCallbackSimple cb, Value::Filter f = {}, Where w = {}) override - { + size_t listen(const InfoHash& key, GetCallbackSimple cb, Value::Filter f={}, Where w = {}) override { return listen(key, bindGetCb(cb), f, w); } - bool cancelListen(const InfoHash& h, size_t token) override { return dht_->cancelListen(h, token); } - void connectivityChanged(sa_family_t af) override { dht_->connectivityChanged(af); } - void connectivityChanged() override { dht_->connectivityChanged(); } + bool cancelListen(const InfoHash& h, size_t token) override { + return dht_->cancelListen(h, token); + } + void connectivityChanged(sa_family_t af) override { + dht_->connectivityChanged(af); + } + void connectivityChanged() override { + dht_->connectivityChanged(); + } - void forwardAllMessages(bool forward) { forward_all_ = forward; } + void forwardAllMessages(bool forward) { + forward_all_ = forward; + } - void setPushNotificationToken(const std::string& token = "") override { dht_->setPushNotificationToken(token); } + void setPushNotificationToken(const std::string& token = "") override { + dht_->setPushNotificationToken(token); + } /** * Call linked callback with push_notification * @param notification to process */ - PushNotificationResult pushNotificationReceived(const std::map& notification) override - { + PushNotificationResult pushNotificationReceived(const std::map& notification) override { return dht_->pushNotificationReceived(notification); } - void setLogger(const std::shared_ptr& logger) override - { + void setLogger(const Logger& logger) override { + DhtInterface::setLogger(logger); + dht_->setLogger(logger); + } + + void setLogger(const std::shared_ptr& logger) override { DhtInterface::setLogger(logger); dht_->setLogger(logger); } @@ -319,8 +359,7 @@ public: /** * Only print logs related to the given InfoHash (if given), or disable filter (if zeroes). */ - void setLogFilter(const InfoHash& f) override - { + void setLogFilter(const InfoHash& f) override { DhtInterface::setLogFilter(f); dht_->setLogFilter(f); } @@ -355,27 +394,23 @@ private: bool enableCache_ {false}; }; -const ValueType CERTIFICATE_TYPE = {8, - "Certificate", - std::chrono::hours(24 * 7), - // A certificate can only be stored at its public key ID. - [](InfoHash id, Sp& v, const InfoHash&, const SockAddr&) { - try { - crypto::Certificate crt(v->data); - // TODO check certificate signature - return crt.getPublicKey().getId() == id - || InfoHash::get(crt.getPublicKey().getLongId()) == id; - } catch (const std::exception& e) { - } - return false; - }, - [](InfoHash, const Sp& o, Sp& n, const InfoHash&, const SockAddr&) { - try { - return crypto::Certificate(o->data).getPublicKey().getLongId() - == crypto::Certificate(n->data).getPublicKey().getLongId(); - } catch (const std::exception& e) { - } - return false; - }}; +const ValueType CERTIFICATE_TYPE = { + 8, "Certificate", std::chrono::hours(24 * 7), + // A certificate can only be stored at its public key ID. + [](InfoHash id, Sp& v, const InfoHash&, const SockAddr&) { + try { + crypto::Certificate crt(v->data); + // TODO check certificate signature + return crt.getPublicKey().getId() == id || InfoHash::get(crt.getPublicKey().getLongId()) == id; + } catch (const std::exception& e) {} + return false; + }, + [](InfoHash, const Sp& o, Sp& n, const InfoHash&, const SockAddr&) { + try { + return crypto::Certificate(o->data).getPublicKey().getLongId() == crypto::Certificate(n->data).getPublicKey().getLongId(); + } catch (const std::exception& e) {} + return false; + } +}; -} // namespace dht +} diff --git a/src/log.cpp b/src/log.cpp index f4d05f54..5d6876f2 100644 --- a/src/log.cpp +++ b/src/log.cpp @@ -38,28 +38,27 @@ namespace log { * Terminal colors for logging */ namespace Color { -enum Code { - FG_RED = 31, - FG_GREEN = 32, - FG_YELLOW = 33, - FG_BLUE = 34, - FG_DEFAULT = 39, - BG_RED = 41, - BG_GREEN = 42, - BG_BLUE = 44, - BG_DEFAULT = 49 -}; -class Modifier -{ - const Code code; - -public: - constexpr Modifier(Code pCode) - : code(pCode) - {} - friend std::ostream& operator<<(std::ostream& os, const Modifier& mod) { return os << "\033[" << mod.code << 'm'; } -}; -} // namespace Color + enum Code { + FG_RED = 31, + FG_GREEN = 32, + FG_YELLOW = 33, + FG_BLUE = 34, + FG_DEFAULT = 39, + BG_RED = 41, + BG_GREEN = 42, + BG_BLUE = 44, + BG_DEFAULT = 49 + }; + class Modifier { + const Code code; + public: + constexpr Modifier(Code pCode) : code(pCode) {} + friend std::ostream& + operator<<(std::ostream& os, const Modifier& mod) { + return os << "\033[" << mod.code << 'm'; + } + }; +} constexpr const Color::Modifier def(Color::FG_DEFAULT); constexpr const Color::Modifier red(Color::FG_RED); @@ -69,54 +68,53 @@ constexpr const Color::Modifier yellow(Color::FG_YELLOW); * Print va_list to std::ostream (used for logging). */ void -printfLog(std::ostream& s, std::string_view prefix, const std::string& message) -{ +printfLog(std::ostream& s, const std::string& message) { using namespace std::chrono; using log_precision = microseconds; auto num = duration_cast(steady_clock::now().time_since_epoch()).count(); constexpr auto den = log_precision::period::den; - fmt::print(s, "[{:06d}.{:06d}] {}", num / den, num % den, prefix); + fmt::print(s, "[{:06d}.{:06d}] ", num / den, num % den); s << message << std::endl; } void -printLog(std::ostream& s, std::string_view prefix, fmt::string_view format, fmt::format_args args) -{ +printLog(std::ostream& s, fmt::string_view format, fmt::format_args args) { using namespace std::chrono; using log_precision = microseconds; auto num = duration_cast(steady_clock::now().time_since_epoch()).count(); constexpr auto den = log_precision::period::den; - fmt::print(s, "[{:06d}.{:06d}] {}", num / den, num % den, prefix); + fmt::print(s, "[{:06d}.{:06d}] ", num / den, num % den); fmt::vprint(s, format, args); s << std::endl; } std::shared_ptr -getStdLogger() -{ - return std::make_shared([](LogLevel level, std::string_view prefix, std::string&& message) { - if (level == LogLevel::error) - std::cerr << red; - else if (level == LogLevel::warning) - std::cerr << yellow; - printfLog(std::cerr, prefix, message); - std::cerr << def; - }); +getStdLogger() { + return std::make_shared( + [](LogLevel level, std::string&& message) { + if (level == LogLevel::error) + std::cerr << red; + else if (level == LogLevel::warning) + std::cerr << yellow; + printfLog(std::cerr, message); + std::cerr << def; + } + ); } std::shared_ptr -getFileLogger(const std::string& path) -{ +getFileLogger(const std::string &path) { auto logfile = std::make_shared(); logfile->open(path, std::ios::out); - return std::make_shared([logfile](LogLevel /*level*/, std::string_view prefix, std::string&& message) { - printfLog(*logfile, prefix, message); - }); + return std::make_shared( + [logfile](LogLevel /*level*/, std::string&& message) { + printfLog(*logfile, message); + } + ); } #ifndef _WIN32 -constexpr int -syslogLevel(LogLevel level) -{ +constexpr +int syslogLevel(LogLevel level) { switch (level) { case LogLevel::error: return LOG_ERR; @@ -130,13 +128,15 @@ syslogLevel(LogLevel level) #endif std::shared_ptr -getSyslogLogger(const char* name) -{ +getSyslogLogger(const char* name) { #ifndef _WIN32 - struct Syslog - { - explicit Syslog(const char* n) { openlog(n, LOG_NDELAY, LOG_USER); } - ~Syslog() { closelog(); } + struct Syslog { + explicit Syslog(const char* n) { + openlog(n, LOG_NDELAY, LOG_USER); + } + ~Syslog() { + closelog(); + } }; // syslog is global. Existing instance must be reused. static std::weak_ptr opened_logfile; @@ -145,37 +145,34 @@ getSyslogLogger(const char* name) logfile = std::make_shared(name); opened_logfile = logfile; } - return std::make_shared([logfile](LogLevel level, std::string_view prefix, std::string&& message) { - syslog(syslogLevel(level), "%.*s%.*s", (int) prefix.size(), prefix.data(), (int) message.size(), message.c_str()); - }); + return std::make_shared( + [logfile](LogLevel level, std::string&& message) { + syslog(syslogLevel(level), "%s", message.c_str()); + }); #else return getStdLogger(); #endif } void -enableLogging(dht::DhtRunner& dht) -{ +enableLogging(dht::DhtRunner &dht) { dht.setLogger(getStdLogger()); } void -enableFileLogging(dht::DhtRunner& dht, const std::string& path) -{ +enableFileLogging(dht::DhtRunner &dht, const std::string &path) { dht.setLogger(getFileLogger(path)); } OPENDHT_PUBLIC void -enableSyslog(dht::DhtRunner& dht, const char* name) -{ +enableSyslog(dht::DhtRunner &dht, const char* name) { dht.setLogger(getSyslogLogger(name)); } void -disableLogging(dht::DhtRunner& dht) -{ +disableLogging(dht::DhtRunner &dht) { dht.setLogger(); } -} // namespace log -} // namespace dht +} +}