diff --git a/.gitignore b/.gitignore index a0733ae6..e942eca9 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ gotit.json .kdev4/ipfs-chromium.kdev4 *.autosave.* *.autosave +compile_commands.json diff --git a/cmake/patch.py b/cmake/patch.py index c2f71d2d..b2dd8527 100755 --- a/cmake/patch.py +++ b/cmake/patch.py @@ -189,7 +189,8 @@ def apply(self): verbose(f"{to_path} already copied") verbose("Done patching") - def edit_evidence(text): + @staticmethod + def edit_evidence(text: str): for tok in ['ipfs', 'ReadTagContent', 'SetTag(']: if tok in text: return True @@ -519,7 +520,7 @@ def list_ood(self, to_check: list[str], sense: bool, both: bool = False): if __name__ == "__main__": - chromium_src_dir = join(os.environ['CHROMIUM_SOURCE_TREE'], 'src') + chromium_src_dir = os.environ['CHROMIUM_SOURCE_TREE'] if len(argv) < 2: print("Give an argument to indicate what you'd like to do.") elif argv[1] == "apply": diff --git a/library/.clang-tidy b/library/.clang-tidy index 40eb32c2..cab9a606 100644 --- a/library/.clang-tidy +++ b/library/.clang-tidy @@ -1,41 +1,14 @@ - Checks: '-*, - bugprone-a*, - bugprone-b*, - bugprone-dangling-handle, - bugprone-forward-declaration-namespace, - bugprone-inaccurate-erase, - bugprone-string-constructor, - bugprone-string-integer-assignment, - bugprone-undefined-memory-manipulation, - bugprone-unique-ptr-array-mismatch, - bugprone-unused-raii, - bugprone-use-after-move, - bugprone-virtual-near-miss, - google-build-explicit-make-pair, - google-default-arguments, - google-explicit-constructor, - google-objc-avoid-nsobject-new, - google-upgrade-googletest-case, - misc-misleading-identifier, - misc-homoglyph, - modernize-avoid-bind, - modernize-concat-nested-namespaces, - modernize-loop-convert, - modernize-make-shared, - modernize-make-unique, - modernize-redundant-void-arg, - modernize-replace-random-shuffle, - modernize-shrink-to-fit, - modernize-use-bool-literals, - modernize-use-default-member-init, - modernize-use-emplace, - modernize-use-equals-default, - modernize-use-equals-delete, - modernize-use-noexcept, - modernize-use-nullptr, - modernize-use-override, - modernize-use-transparent-functors, - readability-redundant-member-init' + Checks: 'bu*, + -bugprone-reserved-identifier, + mi*, + -misc-const-correctness, + -misc-header-include-cycle, + -misc-no-recursion, + mo*, + re*, + -readability-container-size-empty, + -readability-else-after-return, + -readability-named-parameter' CheckOptions: - key: bugprone-assert-side-effect.AssertMacros value: assert,DCHECK @@ -54,5 +27,7 @@ # https://groups.google.com/a/chromium.org/g/cxx/c/noMMTNYiM0w . - key: modernize-use-emplace.IgnoreImplicitConstructors value: 1 -WarningsAsErrors: '*' +CompileFlags: + Add: -Wno-unknown-warning-option + Remove: -fprofile-abs-path ... diff --git a/library/include/ipfs_client/ctx/dns_txt_lookup.cc b/library/include/ipfs_client/ctx/dns_txt_lookup.cc deleted file mode 100644 index 4f926e60..00000000 --- a/library/include/ipfs_client/ctx/dns_txt_lookup.cc +++ /dev/null @@ -1 +0,0 @@ -#include "dns_txt_lookup.h" diff --git a/library/include/ipfs_client/ctx/dns_txt_lookup.h b/library/include/ipfs_client/ctx/dns_txt_lookup.h index 3c4285cf..7da94ca6 100644 --- a/library/include/ipfs_client/ctx/dns_txt_lookup.h +++ b/library/include/ipfs_client/ctx/dns_txt_lookup.h @@ -17,7 +17,7 @@ class DnsTxtLookup { DnsTextResultsCallback, DnsTextCompleteCallback) = 0; - virtual ~DnsTxtLookup() noexcept {} + virtual ~DnsTxtLookup() noexcept; }; } // namespace ipfs::ctx diff --git a/library/include/ipfs_client/gw/gateway_request.h b/library/include/ipfs_client/gw/gateway_request.h index 0264db16..b3d0f57f 100644 --- a/library/include/ipfs_client/gw/gateway_request.h +++ b/library/include/ipfs_client/gw/gateway_request.h @@ -1,19 +1,19 @@ #ifndef IPFS_TRUSTLESS_REQUEST_H_ #define IPFS_TRUSTLESS_REQUEST_H_ -#include +#include "gateway_request_type.h" +#include #include #include -#include #include #include #include #include #include -#include "gateway_request_type.h" +#include namespace ipfs { class IpfsRequest; @@ -62,7 +62,7 @@ class GatewayRequest : public std::enable_shared_from_this { std::optional cid; short parallel = 0; std::string affinity; - flat_set failures; + std::unordered_set failures; std::string url_suffix() const; std::string_view accept() const; diff --git a/library/include/ipfs_client/gw/requestor.h b/library/include/ipfs_client/gw/requestor.h index 11d3b132..7eac8db6 100644 --- a/library/include/ipfs_client/gw/requestor.h +++ b/library/include/ipfs_client/gw/requestor.h @@ -34,7 +34,7 @@ class Requestor : public std::enable_shared_from_this { virtual HandleOutcome handle(RequestPtr) = 0; - void definitive_failure(RequestPtr) const; + static void definitive_failure(RequestPtr) ; void forward(RequestPtr) const; std::shared_ptr api_; diff --git a/library/src/ipfs_client/car.cc b/library/src/ipfs_client/car.cc index d3c0bcc4..c1037c28 100644 --- a/library/src/ipfs_client/car.cc +++ b/library/src/ipfs_client/car.cc @@ -1,12 +1,20 @@ #include "car.h" #include +#include "ipfs_client/ctx/cbor_parser.h" #include +#include +#include "vocab/byte_view.h" #include "log_macros.h" +#include +#include + #include +#include +#include using Self = ipfs::Car; using Byte = ipfs::Byte; @@ -14,8 +22,8 @@ using ByteView = ipfs::ByteView; using VarInt = libp2p::multi::UVarint; namespace { -short ReadHeader(ByteView&, ipfs::ctx::CborParser&); -std::pair GetV1PayloadPos(ByteView); +auto ReadHeader(ByteView& /*bytes*/, ipfs::ctx::CborParser& /*cbor_parser*/) -> short; +auto GetV1PayloadPos(ByteView /*bytes*/) -> std::pair; } // namespace Self::Car(ByteView bytes, ctx::CborParser& cbor_parser) { @@ -71,7 +79,7 @@ auto Self::NextBlock() -> std::optional { namespace { // https://ipld.io/specs/transport/car/carv2/ -short ReadHeader(ByteView& bytes, ipfs::ctx::CborParser& cbor_parser) { +auto ReadHeader(ByteView& bytes, ipfs::ctx::CborParser& cbor_parser) -> short { auto header_len = VarInt::create(bytes); if (!header_len || header_len->toUInt64() + header_len->size() > bytes.size()) { @@ -90,11 +98,12 @@ short ReadHeader(ByteView& bytes, ipfs::ctx::CborParser& cbor_parser) { auto version = version_node->as_unsigned(); if (version) { bytes = bytes.subspan(header_len->toUInt64()); - return version.value(); + assert(version.value() < 0x8000U); + return static_cast(version.value()); } return 0; } -std::uint64_t read_le_u64(ByteView bytes, unsigned& off) { +auto read_le_u64(ByteView bytes, unsigned& off) -> std::uint64_t { auto b = bytes.subspan(off, off + 8); off += 8U; auto shift_in = [](std::uint64_t i, Byte y) { @@ -102,7 +111,7 @@ std::uint64_t read_le_u64(ByteView bytes, unsigned& off) { }; return std::accumulate(b.rbegin(), b.rend(), 0UL, shift_in); } -std::pair GetV1PayloadPos(ByteView bytes) { +auto GetV1PayloadPos(ByteView bytes) -> std::pair { // Following the 11 byte pragma, the CARv2 [header] is a fixed-length sequence // of 40 bytes, broken into the following sections: if (bytes.size() < 40) { diff --git a/library/src/ipfs_client/client.cc b/library/src/ipfs_client/client.cc index dd13cd76..cc253d58 100644 --- a/library/src/ipfs_client/client.cc +++ b/library/src/ipfs_client/client.cc @@ -1,9 +1,22 @@ #include +#include +#include +#include +#include +#include +#include +#include #include "crypto/openssl_sha2_256.h" #include "ipfs_client/crypto/openssl_signature_verifier.h" #include "ipfs_client/crypto/identity_hasher.h" -#include "ipfs_client/ctx/boost_beast_http.h" +#include "ipfs_client/crypto/signing_key_type.h" +#include "ipfs_client/crypto/signature_verifier.h" +#include "ipfs_client/ctx/http_api.h" +#include "ipfs_client/ctx/dns_txt_lookup.h" +#include "ipfs_client/ctx/gateway_config.h" +#include "ipfs_client/ctx/json_parser.h" +#include "ipfs_client/ctx/cbor_parser.h" #include "ipfs_client/ctx/nlohmann_cbor_parser.h" #include "ipfs_client/ctx/nlohmann_json_parser.h" #include "ipfs_client/ctx/null_dns_txt_lookup.h" @@ -11,10 +24,14 @@ #include "ipfs_client/ctx/transitory_gateway_config.h" #include "ipfs_client/gw/default_requestor.h" +#include "ipfs_client/multi_hash.h" +#include "ipfs_client/json_cbor_adapter.h" +#include "ipfs_client/gw/requestor.h" #include "ipfs_client/partition.h" #include "ipfs_client/web_util.h" #include "log_macros.h" +#include "vocab/byte.h" using Self = ipfs::Client; @@ -40,10 +57,10 @@ auto Self::Hash(HashType ht, ByteView data) } return it->second->hash(data); } -bool Self::VerifyKeySignature(SigningKeyType typ, +auto Self::VerifyKeySignature(SigningKeyType typ, ByteView signature, ByteView data, - ByteView key_bytes) const { + ByteView key_bytes) const -> bool { auto it = verifiers_.find(typ); if (verifiers_.end() == it || !(it->second)) { LOG(ERROR) @@ -53,9 +70,9 @@ bool Self::VerifyKeySignature(SigningKeyType typ, } return it->second->VerifySignature(signature, data, key_bytes); } -std::string Self::MimeType(std::string extension, +auto Self::MimeType(std::string extension, std::string_view content, - std::string const& url) { + std::string const& url) -> std::string { if (!deduce_mime_type_) { LOG(WARNING) << "No mime-type deduction algo provided. Will do something " "trivial/inaccurate."; @@ -63,7 +80,7 @@ std::string Self::MimeType(std::string extension, } return deduce_mime_type_(extension, content, url); } -std::string Self::UnescapeUrlComponent(std::string_view url_comp) { +auto Self::UnescapeUrlComponent(std::string_view url_comp) -> std::string { if (!unescape_) { LOG(WARNING) << "No URL (un)escaping algo provided. Will do something simple/wrong."; @@ -71,7 +88,7 @@ std::string Self::UnescapeUrlComponent(std::string_view url_comp) { } return unescape_(url_comp); } -bool Self::DnslinkFallback() const { +auto Self::DnslinkFallback() const -> bool { if (dns_fb_) { return dns_fb_(); } @@ -134,24 +151,24 @@ auto Self::requestor() -> std::shared_ptr { } return rtor_; } -Self& Self::with(std::unique_ptr p) { +auto Self::with(std::unique_ptr p) -> Self& { json_parser_ = std::move(p); return *this; } -Self& Self::with(std::unique_ptr p) { +auto Self::with(std::unique_ptr p) -> Self& { cbor_parser_ = std::move(p); return *this; } -Self& Self::with(std::unique_ptr p) { +auto Self::with(std::unique_ptr p) -> Self& { http_api_ = std::move(p); return *this; } -Self& Self::with(std::unique_ptr p) { +auto Self::with(std::unique_ptr p) -> Self& { dns_txt_ = std::move(p); return *this; } -Self& Self::with(SigningKeyType t, - std::unique_ptr p) { +auto Self::with(SigningKeyType t, + std::unique_ptr p) -> Self& { if (p) { verifiers_[t] = std::move(p); } else { @@ -159,23 +176,23 @@ Self& Self::with(SigningKeyType t, } return *this; } -Self& Self::with(ipfs::Client::MimeTypeDeduction deduce_mime_type) { +auto Self::with(ipfs::Client::MimeTypeDeduction deduce_mime_type) -> Self& { deduce_mime_type_ = deduce_mime_type; return *this; } -Self& Self::with(ipfs::Client::UrlUnescaping unescape) { +auto Self::with(ipfs::Client::UrlUnescaping unescape) -> Self& { unescape_ = unescape; return *this; } -Self& Self::with(std::unique_ptr p) { +auto Self::with(std::unique_ptr p) -> Self& { gateway_config_ = std::move(p); return *this; } -Self& Self::with(std::shared_ptr p) { +auto Self::with(std::shared_ptr p) -> Self& { rtor_ = p; return *this; } -Self& Self::with(DnslinkFallbackSwitch sw) { +auto Self::with(DnslinkFallbackSwitch sw) -> Self& { dns_fb_ = sw; return *this; } diff --git a/library/src/ipfs_client/ctx/ares_dns_txt_lookup.cc b/library/src/ipfs_client/ctx/ares_dns_txt_lookup.cc index a8ab5803..d3dd430b 100644 --- a/library/src/ipfs_client/ctx/ares_dns_txt_lookup.cc +++ b/library/src/ipfs_client/ctx/ares_dns_txt_lookup.cc @@ -1,4 +1,9 @@ #include +#include +#include +#include "ipfs_client/ctx/dns_txt_lookup.h" +#include +#include #if __has_include() #include @@ -12,7 +17,6 @@ #if HAS_ARES #include -#include #include "log_macros.h" @@ -30,10 +34,10 @@ static void c_ares_c_callback(void* vp, int /*timeouts*/, unsigned char* abuf, int alen) { - auto cbcb = reinterpret_cast(vp); + auto *cbcb = reinterpret_cast(vp); struct ares_txt_reply* txt_out = nullptr; LOG(INFO) << "Buffer contains " << alen << " bytes."; - if (abuf && alen && !ares_parse_txt_reply(abuf, alen, &txt_out) && txt_out) { + if ((abuf != nullptr) && (alen != 0) && (ares_parse_txt_reply(abuf, alen, &txt_out) == 0) && (txt_out != nullptr)) { cbcb->me->DnsResults(cbcb->host, txt_out); ares_free_data(txt_out); } else { @@ -45,10 +49,10 @@ static void c_ares_c_callback(void* vp, } Self::AresDnsTxtLookup(boost::asio::io_context* io) : io_{io} { - if (ares_library_init(ARES_LIB_INIT_ALL)) { + if (ares_library_init(ARES_LIB_INIT_ALL) != 0) { throw std::runtime_error("Failed to initialize c-ares library."); } - if (ares_init(&ares_channel_)) { + if (ares_init(&ares_channel_) != 0) { throw std::runtime_error("Failed to initialize c-ares channel."); } } @@ -67,13 +71,13 @@ void Self::SendDnsTextRequest( auto is_first = p.second; it->second.emplace_back(DnsCbs{rcb, ccb}); if (is_first) { - auto cbcb = new CallbackCallback; + auto *cbcb = new CallbackCallback; cbcb->me = this; cbcb->host = host; ares_query(ares_channel_, it->first.c_str(), ns_c_in, ns_t_txt, &c_ares_c_callback, cbcb); #if HAS_IO_CONTEXT - if (io_) { + if (io_ != nullptr) { io_->post([this]() { CAresProcess(); }); } else #endif @@ -89,8 +93,8 @@ void Self::DnsResults(std::string& host, ares_txt_reply const* result) { return; } std::vector v{std::string{}}; - for (auto r = result; r; r = r->next) { - auto p = reinterpret_cast(r->txt); + for (const auto *r = result; r != nullptr; r = r->next) { + const auto *p = reinterpret_cast(r->txt); v[0].assign(p, r->length); for (auto& cbs : i->second) { cbs.r(v); @@ -102,21 +106,23 @@ void Self::DnsResults(std::string& host, ares_txt_reply const* result) { pending_dns_.erase(i); } void Self::CAresProcess() { - fd_set readers, writers; - struct timeval tv, *tvp; + fd_set readers; + fd_set writers; + struct timeval tv; + struct timeval *tvp; FD_ZERO(&readers); FD_ZERO(&writers); auto nfds = ares_fds(ares_channel_, &readers, &writers); - if (nfds) { + if (nfds != 0) { tv.tv_sec = 30; tvp = ares_timeout(ares_channel_, &tv, &tv); auto count = select(nfds, &readers, &writers, nullptr, tvp); ares_process(ares_channel_, &readers, &writers); nfds += count; } - if (nfds || pending_dns_.size()) { + if ((nfds != 0) || (static_cast(!pending_dns_.empty()) != 0U)) { #if HAS_IO_CONTEXT - if (io_) { + if (io_ != nullptr) { io_->post([this]() { CAresProcess(); }); } else #endif diff --git a/library/src/ipfs_client/ctx/default_gateways.cc b/library/src/ipfs_client/ctx/default_gateways.cc index 3b2df004..5830cb6f 100644 --- a/library/src/ipfs_client/ctx/default_gateways.cc +++ b/library/src/ipfs_client/ctx/default_gateways.cc @@ -2,13 +2,17 @@ #include +#include #include +#include +#include +#include namespace ctx = ipfs::ctx; -bool ctx::LoadGatewaysFromEnvironmentVariable(ipfs::ctx::GatewayConfig& cfg) { +auto ctx::LoadGatewaysFromEnvironmentVariable(ipfs::ctx::GatewayConfig& cfg) -> bool { auto* ovr = std::getenv("IPFS_GATEWAY"); - if (!ovr) { + if (ovr == nullptr) { return false; } std::istringstream user_override{ovr}; diff --git a/library/src/ipfs_client/ctx/dns_txt_lookup.cc b/library/src/ipfs_client/ctx/dns_txt_lookup.cc new file mode 100644 index 00000000..be88069f --- /dev/null +++ b/library/src/ipfs_client/ctx/dns_txt_lookup.cc @@ -0,0 +1,3 @@ +#include + +ipfs::ctx::DnsTxtLookup::~DnsTxtLookup() noexcept = default; diff --git a/library/src/ipfs_client/ctx/null_dns_txt_lookup.cc b/library/src/ipfs_client/ctx/null_dns_txt_lookup.cc index c1fb0a33..10582cac 100644 --- a/library/src/ipfs_client/ctx/null_dns_txt_lookup.cc +++ b/library/src/ipfs_client/ctx/null_dns_txt_lookup.cc @@ -1,13 +1,14 @@ #include +#include #include "log_macros.h" using Self = ipfs::ctx::NullDnsTxtLookup; -void Self::SendDnsTextRequest(std::string, - DnsTextResultsCallback, - DnsTextCompleteCallback cb) { +void Self::SendDnsTextRequest(std::string /*hostname*/, + DnsTextResultsCallback /*unused*/, + DnsTextCompleteCallback callback) { LOG(ERROR) << "DNS TXT lookup provider not instantiated. DNSLink will not work."; - cb(); + callback(); } diff --git a/library/src/ipfs_client/gw/block_request_splitter.cc b/library/src/ipfs_client/gw/block_request_splitter.cc index 894dab13..a11890c3 100644 --- a/library/src/ipfs_client/gw/block_request_splitter.cc +++ b/library/src/ipfs_client/gw/block_request_splitter.cc @@ -3,13 +3,16 @@ #include #include +#include "ipfs_client/gw/requestor.h" #include "log_macros.h" #include +#include +#include using Self = ipfs::gw::BlockRequestSplitter; -std::string_view Self::name() const { +auto Self::name() const -> std::string_view { return "BlockRequestSplitter"; } auto Self::handle(ipfs::gw::RequestPtr r) -> HandleOutcome { @@ -22,8 +25,8 @@ auto Self::handle(ipfs::gw::RequestPtr r) -> HandleOutcome { br->path.clear(); forward(br); } - if (api_ && api_->gw_cfg().RoutingApiDiscoveryDefaultRate()) { - auto it = std::find(recent_provider_requests.begin(), + if (api_ && (api_->gw_cfg().RoutingApiDiscoveryDefaultRate() != 0U)) { + auto *it = std::find(recent_provider_requests.begin(), recent_provider_requests.end(), r->affinity); if (recent_provider_requests.end() == it) { auto i = old_provider_request % recent_provider_requests.size(); diff --git a/library/src/ipfs_client/gw/default_requestor.cc b/library/src/ipfs_client/gw/default_requestor.cc index be2976e7..3982583c 100644 --- a/library/src/ipfs_client/gw/default_requestor.cc +++ b/library/src/ipfs_client/gw/default_requestor.cc @@ -5,6 +5,8 @@ #include #include #include +#include +#include "ipfs_client/gw/requestor.h" auto ipfs::gw::default_requestor(std::shared_ptr early, std::shared_ptr api) diff --git a/library/src/ipfs_client/gw/dnslink_requestor.cc b/library/src/ipfs_client/gw/dnslink_requestor.cc index 9b11391c..3d015f5e 100644 --- a/library/src/ipfs_client/gw/dnslink_requestor.cc +++ b/library/src/ipfs_client/gw/dnslink_requestor.cc @@ -1,8 +1,8 @@ #include -#include "ipfs_client/ipld/dnslink_name.h" +#include "ipfs_client/ipld/block_source.h" +#include "ipfs_client/gw/requestor.h" -#include #include #include @@ -12,7 +12,11 @@ #include "ipfs_client/gw/gateway_request_type.h" #include "log_macros.h" -#include +#include +#include +#include +#include +#include using Self = ipfs::gw::DnsLinkRequestor; using Source = ipfs::ipld::BlockSource; @@ -21,14 +25,14 @@ using namespace std::literals; Self::DnsLinkRequestor(std::shared_ptr api) { api_ = api; } -std::string_view Self::name() const { +auto Self::name() const -> std::string_view { return "DNSLink requestor"; } namespace { -bool parse_results(ipfs::gw::RequestPtr req, +auto parse_results(ipfs::gw::RequestPtr req, std::vector const& results, - std::shared_ptr const&, - Source::Clock::time_point); + std::shared_ptr const& /*api*/, + Source::Clock::time_point /*start*/) -> bool; } auto Self::handle(ipfs::gw::RequestPtr req) -> HandleOutcome { if (req->type != GatewayRequestType::DnsLink) { @@ -37,10 +41,10 @@ auto Self::handle(ipfs::gw::RequestPtr req) -> HandleOutcome { // std::function requires target be copy-constructible auto success = std::make_shared(); *success = false; - auto a = api_; + auto api = api_;//Copy for lambda bind auto start = Source::Clock::now(); - auto res = [req, success, a, start](std::vector const& results) { - *success = *success || parse_results(req, results, a, start); + auto res = [req, success, api, start](std::vector const& results) { + *success = *success || parse_results(req, results, api, start); }; auto don = [this,success, req]() { if (!*success) { @@ -57,17 +61,17 @@ auto Self::handle(ipfs::gw::RequestPtr req) -> HandleOutcome { return HandleOutcome::PENDING; } namespace { -bool parse_results(ipfs::gw::RequestPtr req, +auto parse_results(ipfs::gw::RequestPtr req, std::vector const& results, std::shared_ptr const& api, - Source::Clock::time_point start) { + Source::Clock::time_point start) -> bool { constexpr auto prefix = "dnslink="sv; - auto t = Source::Clock::now(); - for (auto& result : results) { + auto fetched_at = Source::Clock::now(); + for (const auto& result : results) { if (result.starts_with(prefix)) { Source src; - src.fetched_at = t; - src.load_duration = t - start; + src.fetched_at = fetched_at; + src.load_duration = fetched_at - start; req->RespondSuccessfully(result.substr(prefix.size()), api, src); return true; } else { diff --git a/library/src/ipfs_client/gw/gateway_state.cc b/library/src/ipfs_client/gw/gateway_state.cc index 602b49ac..3f97d8e4 100644 --- a/library/src/ipfs_client/gw/gateway_state.cc +++ b/library/src/ipfs_client/gw/gateway_state.cc @@ -1,72 +1,81 @@ #include "gateway_state.h" #include +#include +#include +#include +#include +#include +#include +#include + +#include "ipfs_client/gw/gateway_request_type.h" #include "log_macros.h" using Self = ipfs::gw::GatewayState; Self::GatewayState(std::string_view prefix, std::shared_ptr api) - : prefix_{prefix}, api_{api} { + : prefix_{prefix}, api_{std::move(api)} { DCHECK(!prefix_.empty()); last_hist_update = std::time({}); sent_counts.fill(0U); } -long Self::score(GatewayRequest const& req, unsigned baseline) const { +auto Self::score(GatewayRequest const& req, unsigned baseline) const -> long { auto result = static_cast(baseline); result += 7L * cfg().GetTypeAffinity(prefix_, req.type); - auto i = affinity_success.find(req.affinity); - if (i != affinity_success.end()) { - result += 8L * i->second; + auto aff = affinity_success.find(req.affinity); + if (aff != affinity_success.end()) { + result += 8L * aff->second; } return result; } -bool Self::over_rate(unsigned req_per_min) { +auto Self::over_rate(unsigned req_per_min) -> bool { return total_sent + current_bucket() > static_cast(req_per_min) * MinutesTracked; } -bool Self::over_rate() { +auto Self::over_rate() -> bool { return over_rate(cfg().GetGatewayRate(prefix_)); } -bool Self::bored() const { +auto Self::bored() const -> bool { return total_sent == 0UL; } void Self::just_sent_one() { current_bucket()++; ++total_sent; } -unsigned int& Self::current_bucket() { +auto Self::current_bucket() -> unsigned int& { auto now = std::time({}); while (last_hist_update < now) { ++last_hist_update; - auto& c = sent_counts[last_hist_update % sent_counts.size()]; - total_sent -= c; - c = 0; + auto& count = sent_counts[last_hist_update % sent_counts.size()]; + total_sent -= count; + count = 0; } return sent_counts[last_hist_update % sent_counts.size()]; } void Self::hit(GatewayRequestType grt, GatewayRequest const& req) { - auto& c = cfg(); - auto typaff = c.GetTypeAffinity(prefix_, grt); - c.SetTypeAffinity(prefix_, grt, std::max(typaff + 9, 1)); + auto& config = cfg(); + auto typaff = config.GetTypeAffinity(prefix_, grt); + config.SetTypeAffinity(prefix_, grt, std::max(typaff + 9, 1)); affinity_success[req.affinity] += 9; - auto rpm = c.GetGatewayRate(prefix_); - for (auto i = 8; i; --i) { + auto rpm = config.GetGatewayRate(prefix_); + for (auto i = 8; i != 0; --i) { if (over_rate(++rpm / i)) { ++rpm; } else { break; } } - c.SetGatewayRate(prefix_, rpm); + config.SetGatewayRate(prefix_, rpm); } -bool Self::miss(GatewayRequestType grt, GatewayRequest const& req) { +auto Self::miss(GatewayRequestType grt, GatewayRequest const& req) -> bool { auto& c = cfg(); auto aff = c.GetTypeAffinity(prefix_, grt); if (aff > std::numeric_limits::min()) { c.SetTypeAffinity(prefix_, grt, --aff); } auto rpm = c.GetGatewayRate(prefix_); - if (!rpm) { + if (rpm == 0U) { for (auto i = 0U;; ++i) { if (auto gw = c.GetGateway(i)) { auto& p = gw->prefix; @@ -89,7 +98,7 @@ void Self::timed_out() { if (over_rate(rpm)) { return; } - if (--rpm && !over_rate(rpm / 2)) { + if ((--rpm != 0U) && !over_rate(rpm / 2)) { --rpm; } c.SetGatewayRate(prefix_, rpm); diff --git a/library/src/ipfs_client/gw/gateway_state.h b/library/src/ipfs_client/gw/gateway_state.h index 990189e2..dd64c112 100644 --- a/library/src/ipfs_client/gw/gateway_state.h +++ b/library/src/ipfs_client/gw/gateway_state.h @@ -2,13 +2,13 @@ #define IPFS_GATEWAY_STATE_H_ #include -#include #include #include #include #include +#include namespace ipfs { class Client; @@ -25,7 +25,7 @@ class GatewayRequest; class GatewayState { std::string prefix_; std::shared_ptr api_; - flat_map affinity_success; + std::unordered_map affinity_success; static constexpr short MinutesTracked = 4; std::array sent_counts; std::size_t total_sent = 0UL; diff --git a/library/src/ipfs_client/gw/inline_request_handler.cc b/library/src/ipfs_client/gw/inline_request_handler.cc index 863f2def..d6c2961b 100644 --- a/library/src/ipfs_client/gw/inline_request_handler.cc +++ b/library/src/ipfs_client/gw/inline_request_handler.cc @@ -1,23 +1,26 @@ #include +#include +#include #include -#include -#include -#include "ipfs_client/gw/gateway_request_type.h" +#include +#include + #include "log_macros.h" using Self = ipfs::gw::InlineRequestHandler; -std::string_view Self::name() const { +auto Self::name() const -> std::string_view { return "InlineRequestHandler"; } -auto Self::handle(ipfs::gw::RequestPtr req) -> HandleOutcome { - if (req->type != GatewayRequestType::Identity) { +auto Self::handle(RequestPtr reqp) -> HandleOutcome { + GatewayRequest& req = *reqp; + if (req.type != GatewayRequestType::Identity) { return HandleOutcome::NOT_HANDLED; } - std::string data{req->identity_data()}; + std::string const data{req.identity_data()}; VLOG(2) << "Responding to inline CID without using network."; - req->RespondSuccessfully(data, api_, {}); + req.RespondSuccessfully(data, api_, {}); return HandleOutcome::DONE; } diff --git a/library/src/ipfs_client/gw/providers_response.cc b/library/src/ipfs_client/gw/providers_response.cc index 5816e947..35a3d362 100644 --- a/library/src/ipfs_client/gw/providers_response.cc +++ b/library/src/ipfs_client/gw/providers_response.cc @@ -4,6 +4,8 @@ #include #include +#include +#include #include "log_macros.h" @@ -12,40 +14,47 @@ using namespace std::literals; namespace prov = ipfs::providers; namespace { -bool default_port(std::string_view scheme, std::string_view port) { - if (scheme == "http") { - return port == "80"; - } else if (scheme == "https") { - return port == "443"; - } else { - LOG(ERROR) - << "Expected gateway's scheme to be either http or https, but it was '" - << scheme << "'."; - return false; +class Scheme { + char last_ = '!'; + public: + Scheme(std::string_view const name) + { + if (name.starts_with("http")) { + last_ = name.back(); + } } -} -std::string MultiaddrToGatewayPrefix(ipfs::SlashDelimited ma, bool http) { - /* auto addr_proto = */ ma.pop(); - auto host = ma.pop(); - auto tcp = ma.pop(); + [[nodiscard]] auto is_default_port(std::string_view port) const -> bool { + switch (last_) { + case 'p': return port == "80"; + case 's': return port == "443"; + default: return false; + } + } +}; + +auto MultiaddrToGatewayPrefix(ipfs::SlashDelimited maddr, bool http) -> std::string { + /* auto addr_proto = */ maddr.pop(); + auto host = maddr.pop(); + auto tcp = maddr.pop(); DCHECK_EQ(tcp, "tcp"); - auto port = ma.pop(); - auto app_proto = ma.pop(); + auto port = maddr.pop(); + auto app_proto = maddr.pop(); if (app_proto == "http" && !http) { LOG(INFO) << "Rejecting http:// gateway discovery due to config."; return ""; } DCHECK_EQ(app_proto.substr(0, 4), "http"); - std::string rv{app_proto}; - rv.append("://").append(host); - if (!default_port(app_proto, port)) { - rv.append(":").append(port); + std::string prefix{app_proto}; + prefix.append("://").append(host); + Scheme const schm{app_proto}; + if (!schm.is_default_port(port)) { + prefix.append(":").append(port); } - rv.append("/").append(ma.to_view()); - return rv; + prefix.append("/").append(maddr.to_view()); + return prefix; } -bool ParseProvider(ipfs::DagJsonValue const& provider, ipfs::Client& api) { +auto ParseProvider(ipfs::DagJsonValue const& provider, ipfs::Client& api) -> bool { auto proto = provider["Protocol"sv]; if (!proto) { // Perhaps Schema == peer. Not an error, but not used as of now. @@ -71,9 +80,9 @@ bool ParseProvider(ipfs::DagJsonValue const& provider, ipfs::Client& api) { if (auto s = addr.get_if_string()) { auto& c = api.gw_cfg(); auto http = c.RoutingApiDiscoveryOfUnencryptedGateways(); - ipfs::SlashDelimited sd{s.value()}; + ipfs::SlashDelimited const sd{s.value()}; auto gw_pre = MultiaddrToGatewayPrefix(sd, http); - if (gw_pre.size()) { + if (static_cast(!gw_pre.empty()) != 0U) { c.AddGateway(gw_pre, c.RoutingApiDiscoveryDefaultRate()); rv = true; } @@ -91,7 +100,7 @@ bool ParseProvider(ipfs::DagJsonValue const& provider, ipfs::Client& api) { } } // namespace -bool prov::ProcessResponse(std::string_view json_str, Client& api) { +auto prov::ProcessResponse(std::string_view json_str, Client& api) -> bool { if (json_str.empty()) { LOG(ERROR) << "Empty body in response to routing/v1 providers request."; return false; diff --git a/library/src/ipfs_client/gw/requestor.cc b/library/src/ipfs_client/gw/requestor.cc index c10ef491..2a750d98 100644 --- a/library/src/ipfs_client/gw/requestor.cc +++ b/library/src/ipfs_client/gw/requestor.cc @@ -7,13 +7,15 @@ #include #include #include +#include +#include "ipfs_client/gw/gateway_request_type.h" #include "log_macros.h" using Self = ipfs::gw::Requestor; using ReqPtr = std::shared_ptr; -Self& Self::or_else(std::shared_ptr p) { +auto Self::or_else(std::shared_ptr p) -> Self& { if (next_) { next_->or_else(p); } else { @@ -56,7 +58,7 @@ void Self::request(ReqPtr req) { break; } } -void Self::definitive_failure(ipfs::gw::RequestPtr r) const { +void Self::definitive_failure(ipfs::gw::RequestPtr r) { if (!r) { LOG(ERROR) << "nullptr definitively failing?"; } else if (!(r->dependent)) { @@ -73,7 +75,7 @@ void Self::forward(ipfs::gw::RequestPtr req) const { next_->request(req); } } -Self& Self::api(std::shared_ptr a) { +auto Self::api(std::shared_ptr a) -> Self& { api_ = a; return *this; } diff --git a/library/src/ipfs_client/gw/terminating_requestor.cc b/library/src/ipfs_client/gw/terminating_requestor.cc index f23c3426..0ec5d55e 100644 --- a/library/src/ipfs_client/gw/terminating_requestor.cc +++ b/library/src/ipfs_client/gw/terminating_requestor.cc @@ -1,25 +1,29 @@ #include "ipfs_client/gw/terminating_requestor.h" +#include +#include #include -#include "ipfs_client/gw/gateway_request_type.h" #include "log_macros.h" +#include + using Self = ipfs::gw::TerminatingRequestor; -std::string_view Self::name() const { +auto Self::name() const -> std::string_view { return "Terminating requestor"; } -auto Self::handle(ipfs::gw::RequestPtr r) -> HandleOutcome { - if (r->Finished()) { +auto Self::handle(RequestPtr reqp) -> HandleOutcome { + GatewayRequest& req = *reqp; + if (req.Finished()) { return HandleOutcome::DONE; - } else if (r->parallel) { + } else if (req.parallel != 0) { return HandleOutcome::PENDING; } else { LOG(ERROR) << "Out of options, giving up on gateway request " - << r->debug_string(); - definitive_failure(r); - r->type = GatewayRequestType::Zombie; + << req.debug_string(); + definitive_failure(reqp); + req.type = GatewayRequestType::Zombie; return HandleOutcome::DONE; } } diff --git a/library/src/ipfs_client/ipld/chunk.cc b/library/src/ipfs_client/ipld/chunk.cc index 2737a448..f2985024 100644 --- a/library/src/ipfs_client/ipld/chunk.cc +++ b/library/src/ipfs_client/ipld/chunk.cc @@ -1,15 +1,25 @@ #include "chunk.h" +#include +#include +#include + #include "log_macros.h" +#include +#include +#include + +constexpr std::uint16_t cSuccess = 200U; + using Chunk = ipfs::ipld::Chunk; -Chunk::Chunk(std::string data) : data_{data} {} +Chunk::Chunk(std::string data) : data_{std::move(data)} {} Chunk::~Chunk() noexcept = default; auto Chunk::resolve(ResolutionState& params) -> ResolveResult { if (params.IsFinalComponent()) { - return Response{"", 200, data_, params.MyPath().to_string(), {}}; + return Response{"", cSuccess, data_, params.MyPath().to_string(), {}}; } else { VLOG(2) << "Can't resolve a path (" << params.MyPath() << ") inside of a file chunk!"; diff --git a/library/src/ipfs_client/ipld/dag_cbor_node.cc b/library/src/ipfs_client/ipld/dag_cbor_node.cc index 57ae0858..e257d023 100644 --- a/library/src/ipfs_client/ipld/dag_cbor_node.cc +++ b/library/src/ipfs_client/ipld/dag_cbor_node.cc @@ -1,16 +1,24 @@ #include "dag_cbor_node.h" +#include +#include +#include +#include -#include "log_macros.h" +#include "ipfs_client/ipld/resolution_state.h" +#include "ipfs_client/ipld/dag_node.h" +#include "ipfs_client/response.h" using Self = ipfs::ipld::DagCborNode; +constexpr std::uint16_t cSuccess = 200U; + auto Self::resolve(ResolutionState& params) -> ResolveResult { if (auto cid = doc_->as_link()) { auto cid_str = cid.value().to_string(); return CallChild(params, "", cid_str); } if (params.IsFinalComponent()) { - return Response{"text/html", 200, doc_->html(), params.PathToResolve().to_string(), {}}; + return Response{"text/html", cSuccess, doc_->html(), params.PathToResolve().to_string(), {}}; } return CallChild(params, [this](std::string_view element_name) -> NodePtr { if (auto child = doc_->at(element_name)) { @@ -20,5 +28,5 @@ auto Self::resolve(ResolutionState& params) -> ResolveResult { }); } -Self::DagCborNode(std::unique_ptr p) : doc_{std::move(p)} {} +Self::DagCborNode(std::unique_ptr docptr) : doc_{std::move(docptr)} {} Self::~DagCborNode() noexcept = default; diff --git a/library/src/ipfs_client/ipld/dag_json_node.cc b/library/src/ipfs_client/ipld/dag_json_node.cc index ee1ef5eb..37e94437 100644 --- a/library/src/ipfs_client/ipld/dag_json_node.cc +++ b/library/src/ipfs_client/ipld/dag_json_node.cc @@ -2,7 +2,18 @@ #include +#include +#include #include +#include "ipfs_client/dag_json_value.h" +#include +#include "ipfs_client/ipld/link.h" +#include "ipfs_client/ipld/resolution_state.h" +#include "ipfs_client/ipld/dag_node.h" +#include +#include "ipfs_client/response.h" +#include +#include using Self = ipfs::ipld::DagJsonNode; @@ -12,7 +23,7 @@ Self::DagJsonNode(std::unique_ptr j) : data_(std::move(j)) { return; } auto cid_str = cid->to_string(); - if (cid_str.size()) { + if (static_cast(!cid_str.empty()) != 0U) { links_.emplace_back("", Link(cid_str)); } } @@ -20,7 +31,7 @@ Self::~DagJsonNode() noexcept = default; auto Self::resolve(ResolutionState& params) -> ResolveResult { auto respond_as_link = CallChild(params, ""); - if (!std::get_if(&respond_as_link)) { + if (std::get_if(&respond_as_link) == nullptr) { return respond_as_link; } if (params.IsFinalComponent()) { @@ -83,7 +94,7 @@ void write_body(std::ostream& str, ipfs::DagJsonValue const& val) { } } } // namespace -std::string const& Self::html() { +auto Self::html() -> std::string const& { if (html_.empty()) { std::ostringstream html; html << "Preview of DAG-JSON\n"; diff --git a/library/src/ipfs_client/ipld/dag_node.cc b/library/src/ipfs_client/ipld/dag_node.cc index 51e5e83f..a626d4d9 100644 --- a/library/src/ipfs_client/ipld/dag_node.cc +++ b/library/src/ipfs_client/ipld/dag_node.cc @@ -4,7 +4,9 @@ #include "dag_cbor_node.h" #include "dag_json_node.h" #include "directory_shard.h" -#include "dnslink_name.h" +#include "ipfs_client/multicodec.h" +#include "ipfs_client/ipld/resolution_state.h" +#include "ipfs_client/ipld/link.h" #include "root.h" #include "small_directory.h" #include "symlink.h" @@ -15,16 +17,26 @@ #include #include "log_macros.h" +#include "vocab/byte_view.h" +#include "vocab/byte.h" #include +#include +#include +#include +#include +#include #include +#include +#include +#include using Node = ipfs::ipld::DagNode; Node::~DagNode() noexcept = default; -std::shared_ptr Node::fromBytes(std::shared_ptr const& api, +auto Node::fromBytes(std::shared_ptr const& api, Cid const& cid, - std::string_view bytes) { + std::string_view bytes) -> std::shared_ptr { return fromBytes(api, cid, as_bytes(bytes)); } auto Node::fromBytes(std::shared_ptr const& api, @@ -56,7 +68,7 @@ auto Node::fromBytes(std::shared_ptr const& api, } switch (cid.codec()) { case MultiCodec::DAG_CBOR: { - auto p = reinterpret_cast(bytes.data()); + const auto *p = reinterpret_cast(bytes.data()); auto cbor = api->cbor().Parse({p, bytes.size()}); if (cbor) { result = std::make_shared(std::move(cbor)); @@ -66,7 +78,7 @@ auto Node::fromBytes(std::shared_ptr const& api, } } break; case MultiCodec::DAG_JSON: { - auto p = reinterpret_cast(bytes.data()); + const auto *p = reinterpret_cast(bytes.data()); auto json = api->json().Parse({p, bytes.size()}); if (json) { result = std::make_shared(std::move(json)); @@ -77,7 +89,7 @@ auto Node::fromBytes(std::shared_ptr const& api, } break; case MultiCodec::RAW: case MultiCodec::DAG_PB: { - ipfs::PbDag b{cid, bytes}; + ipfs::PbDag const b{cid, bytes}; if (b.valid()) { result = fromBlock(b); } else { @@ -104,7 +116,7 @@ auto Node::fromBytes(std::shared_ptr const& api, } return result; } -std::shared_ptr Node::fromBlock(ipfs::PbDag const& block) { +auto Node::fromBlock(ipfs::PbDag const& block) -> std::shared_ptr { std::shared_ptr result; switch (block.type()) { case PbDag::Type::FileChunk: @@ -147,10 +159,10 @@ std::shared_ptr Node::fromBlock(ipfs::PbDag const& block) { return result; } -std::shared_ptr Node::deroot() { +auto Node::deroot() -> std::shared_ptr { return shared_from_this(); } -std::shared_ptr Node::rooted() { +auto Node::rooted() -> std::shared_ptr { return std::make_shared(shared_from_this()); } void Node::set_api(std::shared_ptr api) { @@ -164,7 +176,7 @@ auto Node::resolve(SlashDelimited initial_path, BlockLookup blu) } */ auto Node::Resolve(ResolutionState& params) -> ResolveResult { - if (source_.cid.size()) { + if (static_cast(!source_.cid.empty()) != 0U) { params.headers.Add(source_); } return resolve(params); @@ -175,8 +187,8 @@ auto Node::CallChild(ipfs::ipld::ResolutionState& state) -> ResolveResult { auto Node::CallChild(ipfs::ipld::ResolutionState& state, std::string_view link_key, std::string_view block_key) -> ResolveResult { - auto child = FindChild(link_key); - if (!child) { + auto *child = FindChild(link_key); + if (child == nullptr) { links_.emplace_back(link_key, Link{std::string{block_key}, {}}); } return CallChild(state, link_key); @@ -184,7 +196,7 @@ auto Node::CallChild(ipfs::ipld::ResolutionState& state, auto Node::CallChild(ResolutionState& state, std::string_view link_key) -> ResolveResult { auto* child = FindChild(link_key); - if (!child) { + if (child == nullptr) { return ProvenAbsent{}; } auto& node = child->node; @@ -198,7 +210,7 @@ auto Node::CallChild(ResolutionState& state, std::string_view link_key) std::string needed{"/ipfs/"}; needed.append(child->cid); auto more = state.PathToResolve().to_view(); - if (more.size()) { + if (static_cast(!more.empty()) != 0U) { if (more.front() != '/') { needed.push_back('/'); } @@ -211,8 +223,8 @@ auto Node::CallChild(ResolutionState& state, std::function gen_child) -> ResolveResult { auto link_key = state.NextComponent(api_.get()); - auto child = FindChild(link_key); - if (!child) { + auto *child = FindChild(link_key); + if (child == nullptr) { links_.emplace_back(link_key, Link{{}, {}}); child = &links_.back().second; } @@ -234,13 +246,13 @@ auto Node::FindChild(std::string_view link_key) -> Link* { } return nullptr; } -bool Node::expired() const { +auto Node::expired() const -> bool { return false; } -bool Node::PreferOver(Node const&) const { +auto Node::PreferOver(Node const& /*unused*/) const -> bool { return false; } -std::ostream& operator<<(std::ostream& s, ipfs::ipld::PathChange const& c) { +auto operator<<(std::ostream& s, ipfs::ipld::PathChange const& c) -> std::ostream& { return s << "PathChange{" << c.new_path << '}'; } diff --git a/library/src/ipfs_client/ipld/directory_shard.cc b/library/src/ipfs_client/ipld/directory_shard.cc index 70deefc7..f14be165 100644 --- a/library/src/ipfs_client/ipld/directory_shard.cc +++ b/library/src/ipfs_client/ipld/directory_shard.cc @@ -1,22 +1,33 @@ #include "directory_shard.h" +#include "ipfs_client/response.h" +#include "ipfs_client/ipld/resolution_state.h" +#include "ipfs_client/ipld/dag_node.h" +#include "ipfs_client/response_semantic.h" #include "log_macros.h" -#include -#include +#include #include #include +#include +#include #include +#include +#include #include +#include +#include +#include +#include using namespace std::literals; using Self = ipfs::ipld::DirShard; namespace { - ipfs::Response DynamicListingHtml(std::string_view path); + auto DynamicListingHtml(std::string_view path) -> ipfs::Response; } auto Self::resolve(ResolutionState& parms) -> ResolveResult { @@ -27,15 +38,15 @@ auto Self::resolve(ResolutionState& parms) -> ResolveResult { // index.html hashes A0 6D 7E C8 78 79 38 1D B3 8D 36 0D 76 FA 7B BF auto index_parm = parms.WithPath("index.html"sv); auto result = resolve(index_parm); - auto resp = std::get_if(&result); - if (resp) { + auto *resp = std::get_if(&result); + if (resp != nullptr) { resp->mime_ = "text/html"; } else if (std::holds_alternative(result)){ return DynamicListingHtml(parms.MyPath().to_view()); } return result; } - std::string name{parms.NextComponent(api_.get())}; + std::string const name{parms.NextComponent(api_.get())}; auto hash = hexhash(name); return resolve_internal(hash.begin(), hash.end(), name, parms); } @@ -60,8 +71,8 @@ auto Self::resolve_internal(ipfs::ipld::DirShard::HashIter hash_b, // partially-consumed hash return MoreDataNeeded{{"/ipfs/" + link.cid}}; } - auto downcast = node->as_hamt(); - if (downcast) { + auto *downcast = node->as_hamt(); + if (downcast != nullptr) { if (hash_b == hash_e) { LOG(ERROR) << "Ran out of hash bits."; return ProvenAbsent{}; @@ -74,11 +85,11 @@ auto Self::resolve_internal(ipfs::ipld::DirShard::HashIter hash_b, } return ProvenAbsent{}; } -std::string Self::listing_json() const { +auto Self::listing_json() const -> std::string { std::string result{"{"}; auto first = true; auto const w = hex_width(); - for (auto& [index, link] : links_) { + for (const auto& [index, link] : links_) { auto hash_bits = std::string_view{index}.substr(0, w); if (first) { first = false; @@ -87,7 +98,7 @@ std::string Self::listing_json() const { } result.append("\n ").push_back('"'); result.append(hash_bits) - .append("\": {\"cid\": \"") + .append(R"(": {"cid": ")") .append(link.cid) .push_back('"'); if (index.size() > w) { @@ -96,7 +107,7 @@ std::string Self::listing_json() const { while ((quot = name.find('"')) < name.size()) { name.insert(quot, 1UL, '\\'); } - result.append(", \"name\": \"") + result.append(R"(, "name": ")") .append(name) .push_back('"'); } @@ -105,7 +116,7 @@ std::string Self::listing_json() const { result.append("\n}"); return result; } -std::size_t Self::hex_width() const { +auto Self::hex_width() const -> std::size_t { auto rv = 0U; for (auto x = fanout_; x > 1; ++rv) { x >>= 4; @@ -116,14 +127,14 @@ std::size_t Self::hex_width() const { return rv; } -std::vector Self::hexhash(std::string_view path_element) const { +auto Self::hexhash(std::string_view path_element) const -> std::vector { std::array digest = {0U, 0U}; MurmurHash3_x64_128(path_element.data(), static_cast(path_element.size()), 0, digest.data()); std::vector result; for (auto d : digest) { auto hash_bits = htobe64(d); - while (hash_bits) { + while (hash_bits != 0U) { // 2. Pop the log2(fanout_) lowest bits from the path component hash // digest,... auto popped = hash_bits % fanout_; @@ -140,12 +151,12 @@ std::vector Self::hexhash(std::string_view path_element) const { Self::DirShard(std::uint64_t fanout) : fanout_{fanout} {} Self::~DirShard() noexcept = default; -Self* Self::as_hamt() { +auto Self::as_hamt() -> Self* { return this; } namespace { - ipfs::Response DynamicListingHtml(std::string_view path) { + auto DynamicListingHtml(std::string_view path) -> ipfs::Response { std::string body = "\n\t\n\t\tDirectory Listing for "; body.append(path); if (!path.ends_with('/')) { diff --git a/library/src/ipfs_client/ipld/dnslink_name.cc b/library/src/ipfs_client/ipld/dnslink_name.cc index 77331d7e..3ec60c3a 100644 --- a/library/src/ipfs_client/ipld/dnslink_name.cc +++ b/library/src/ipfs_client/ipld/dnslink_name.cc @@ -1,6 +1,13 @@ #include "dnslink_name.h" +#include <string_view> +#include <chrono> +#include <variant> +#include "ipfs_client/ipld/link.h" +#include "ipfs_client/ipld/resolution_state.h" +#include "ipfs_client/ipld/dag_node.h" #include "log_macros.h" +#include "vocab/slash_delimited.h" using Self = ipfs::ipld::DnsLinkName; namespace ch = std::chrono; @@ -42,12 +49,12 @@ auto Self::resolve(ResolutionState& params) -> ResolveResult { } return lower; } -bool Self::expired() const { +auto Self::expired() const -> bool { return expiration_ < ch::system_clock::now(); } -bool Self::PreferOver(DagNode const& another) const { - auto* other = another.as_dnslink(); - if (!other) { +auto Self::PreferOver(DagNode const& another) const -> bool { + const auto* other = another.as_dnslink(); + if (other == nullptr) { return true; } return expiration_ > other->expiration_ + ch::seconds(1); diff --git a/library/src/ipfs_client/ipld/ipns_name.cc b/library/src/ipfs_client/ipld/ipns_name.cc index 941902f7..c9827cfa 100644 --- a/library/src/ipfs_client/ipld/ipns_name.cc +++ b/library/src/ipfs_client/ipld/ipns_name.cc @@ -1,8 +1,15 @@ #include "ipns_name.h" #include <ipfs_client/ipns_record.h> +#include <chrono> +#include <algorithm> +#include <variant> +#include "ipfs_client/ipld/link.h" +#include "ipfs_client/ipld/resolution_state.h" +#include "ipfs_client/ipld/dag_node.h" #include "log_macros.h" +#include "vocab/slash_delimited.h" using Self = ipfs::ipld::IpnsName; namespace ch = std::chrono; @@ -47,12 +54,12 @@ auto Self::resolve(ResolutionState& params) -> ResolveResult { } return lower; } -bool Self::expired() const { +auto Self::expired() const -> bool { return expiration_ < ch::system_clock::now(); } -bool Self::PreferOver(DagNode const& another) const { - auto other = another.as_ipns(); - if (!other) { +auto Self::PreferOver(DagNode const& another) const -> bool { + const auto *other = another.as_ipns(); + if (other == nullptr) { return true; } return serial_ > other->serial_; diff --git a/library/src/ipfs_client/ipld/resolution_state.cc b/library/src/ipfs_client/ipld/resolution_state.cc index e11740ae..d0a0f5ed 100644 --- a/library/src/ipfs_client/ipld/resolution_state.cc +++ b/library/src/ipfs_client/ipld/resolution_state.cc @@ -1,6 +1,12 @@ #include <ipfs_client/ipld/resolution_state.h> #include <ipfs_client/client.h> +#include "vocab/slash_delimited.h" +#include "ipfs_client/response_semantic.h" + +#include <utility> +#include <string> +#include <string_view> using Self = ipfs::ipld::ResolutionState; @@ -10,9 +16,9 @@ Self::ResolutionState(SlashDelimited path_to_resolve, : unresolved_path(path_to_resolve), semantic_{sem}, - get_available_block(blu) {} + get_available_block(std::move(blu)) {} -bool Self::IsFinalComponent() const { +auto Self::IsFinalComponent() const -> bool { return !unresolved_path; } auto Self::PathToResolve() const -> SlashDelimited { @@ -21,9 +27,9 @@ auto Self::PathToResolve() const -> SlashDelimited { auto Self::MyPath() const -> SlashDelimited { return SlashDelimited{resolved_path_components}; } -std::string Self::NextComponent(Client* api) const { +auto Self::NextComponent(Client* api) const -> std::string { auto copy = unresolved_path; - if (api) { + if (api != nullptr) { return api->UnescapeUrlComponent(copy.pop()); } else { return std::string{copy.pop()}; @@ -32,15 +38,15 @@ std::string Self::NextComponent(Client* api) const { auto Self::GetBlock(std::string const& block_key) const -> NodePtr { return get_available_block(block_key); } -Self Self::WithPath(std::string_view p) const { - auto rv = *this; - rv.unresolved_path = SlashDelimited{p}; - return rv; +auto Self::WithPath(std::string_view new_path) const -> Self { + auto result = *this; + result.unresolved_path = SlashDelimited{new_path}; + return result; } auto Self::RestartResolvedPath() const -> ResolutionState { - auto rv = *this; - rv.resolved_path_components.clear(); - return rv; + auto newme = *this; + newme.resolved_path_components.clear(); + return newme; } void Self::Descend() { auto next = unresolved_path.pop(); diff --git a/library/src/ipfs_client/ipld/root.cc b/library/src/ipfs_client/ipld/root.cc index def01f2b..36c60cac 100644 --- a/library/src/ipfs_client/ipld/root.cc +++ b/library/src/ipfs_client/ipld/root.cc @@ -1,5 +1,12 @@ #include "root.h" +#include <memory> +#include <variant> +#include "ipfs_client/ipld/dag_node.h" +#include "ipfs_client/ipld/link.h" +#include "ipfs_client/ipld/resolution_state.h" +#include "ipfs_client/response.h" +#include "ipfs_client/redirects.h" #include "log_macros.h" using namespace std::literals; @@ -12,13 +19,13 @@ Self::Root(std::shared_ptr<DagNode> under) { } Self::~Root() noexcept = default; -Ptr Self::deroot() { +auto Self::deroot() -> Ptr { return links_.at(0).second.node; } -Ptr Self::rooted() { +auto Self::rooted() -> Ptr { return shared_from_this(); } -bool Self::expired() const { +auto Self::expired() const -> bool { auto n = links_.at(0).second.node; return n ? n->expired() : true; } @@ -27,19 +34,19 @@ auto Self::resolve(ResolutionState& params) -> ResolveResult { auto location = params.PathToResolve().to_string(); auto result = deroot()->Resolve(params); params.headers.Finish(); - if (auto pc = std::get_if<PathChange>(&result)) { + if (auto *pc = std::get_if<PathChange>(&result)) { auto lower = params.WithPath(pc->new_path); result = resolve(lower); location.assign(lower.MyPath().to_view()); - } else if (std::get_if<ProvenAbsent>(&result)) { + } else if (std::get_if<ProvenAbsent>(&result) != nullptr) { if (params.NextComponent(api_.get()) == "_redirects") { return result; } if (!redirects_.has_value()) { auto redirects_path = params.WithPath("_redirects"); result = resolve(redirects_path); - auto redirect_resp = std::get_if<Response>(&result); - if (redirect_resp && redirect_resp->status_ == 200) { + auto *redirect_resp = std::get_if<Response>(&result); + if ((redirect_resp != nullptr) && redirect_resp->status_ == 200) { redirects_ = redirects::File(redirect_resp->body_); } else { // Either this is ProvenAbsent, in which case this will be interpreted @@ -70,11 +77,11 @@ auto Self::resolve(ResolutionState& params) -> ResolveResult { case 4: { result = deroot()->Resolve(lower_parm); location.assign(lower_parm.MyPath().to_view()); - if (std::get_if<ProvenAbsent>(&result)) { + if (std::get_if<ProvenAbsent>(&result) != nullptr) { return Response{"", 500, "", location, params.headers}; } resp = std::get_if<Response>(&result); - if (resp) { + if (resp != nullptr) { resp->status_ = status; resp->headers_ = params.headers; return *resp; @@ -88,8 +95,8 @@ auto Self::resolve(ResolutionState& params) -> ResolveResult { } } } - auto resp = std::get_if<Response>(&result); - if (resp) { + auto *resp = std::get_if<Response>(&result); + if (resp != nullptr) { if (resp->location_.empty()) { resp->location_ = location; } diff --git a/library/src/ipfs_client/ipld/small_directory.cc b/library/src/ipfs_client/ipld/small_directory.cc index ce6a187f..4375793f 100644 --- a/library/src/ipfs_client/ipld/small_directory.cc +++ b/library/src/ipfs_client/ipld/small_directory.cc @@ -1,24 +1,26 @@ #include "small_directory.h" -#include <ipfs_client/client.h> -#include "ipfs_client/generated_directory_listing.h" -#include "ipfs_client/path2url.h" +#include <ipfs_client/generated_directory_listing.h> +#include <ipfs_client/ipld/resolution_state.h> +#include <ipfs_client/ipld/dag_node.h> +#include <ipfs_client/response.h> -#include "log_macros.h" - -#include <numeric> +#include <cstdint> +#include <variant> using namespace std::literals; using Self = ipfs::ipld::SmallDirectory; +constexpr std::uint16_t cSuccess = 200U; + auto Self::resolve(ResolutionState& params) -> ResolveResult { if (params.IsFinalComponent()) { auto result = CallChild(params, "index.html"); - if (auto resp = std::get_if<Response>(&result)) { + if (auto *resp = std::get_if<Response>(&result)) { resp->mime_ = "text/html"; } - if (!std::get_if<ProvenAbsent>(&result)) { + if (std::get_if<ProvenAbsent>(&result) == nullptr) { return result; } auto dir_path = params.MyPath().to_view(); @@ -26,7 +28,7 @@ auto Self::resolve(ResolutionState& params) -> ResolveResult { for (auto& [name, link] : links_) { index_html.AddEntry(name); } - return Response{"text/html", 200, index_html.Finish(), "", {}}; + return Response{"text/html", cSuccess, index_html.Finish(), "", {}}; } return CallChild(params); } diff --git a/library/src/ipfs_client/ipld/symlink.cc b/library/src/ipfs_client/ipld/symlink.cc index 155c37af..e6214460 100644 --- a/library/src/ipfs_client/ipld/symlink.cc +++ b/library/src/ipfs_client/ipld/symlink.cc @@ -1,10 +1,18 @@ #include "symlink.h" +#include <utility> +#include <string> +#include <string_view> +#include <cstddef> + +#include "ipfs_client/ipld/resolution_state.h" +#include "ipfs_client/ipld/dag_node.h" #include "log_macros.h" +#include "vocab/slash_delimited.h" using Self = ipfs::ipld::Symlink; -Self::Symlink(std::string target) : target_{target} {} +Self::Symlink(std::string target) : target_{std::move(target)} {} Self::~Symlink() noexcept = default; @@ -17,7 +25,7 @@ auto Self::resolve(ResolutionState& params) -> ResolveResult { result.assign(left_path.to_view()); } SlashDelimited target{target_}; - for (std::string_view component; (component = target.pop()).size();) { + for (std::string_view component; static_cast<unsigned int>(!(component = target.pop()).empty()) != 0U;) { if (component == "..") { auto slash = result.rfind('/'); DCHECK(slash < result.size()); @@ -33,9 +41,9 @@ auto Self::resolve(ResolutionState& params) -> ResolveResult { if (!params.IsFinalComponent()) { result.append("/").append(params.PathToResolve().to_string()); } - std::size_t i; - while ((i = result.find("//")) != std::string::npos) { - result.erase(i, 1); + std::size_t pos; + while ((pos = result.find("//")) != std::string::npos) { + result.erase(pos, 1); } if (result.empty()) { result.assign(1UL, '/'); @@ -46,6 +54,6 @@ auto Self::resolve(ResolutionState& params) -> ResolveResult { return PathChange{result}; } -bool Self::is_absolute() const { +auto Self::is_absolute() const -> bool { return target_.at(0) == '/'; } diff --git a/library/src/ipfs_client/ipld/unixfs_file.cc b/library/src/ipfs_client/ipld/unixfs_file.cc index f02fe98e..fabbbb5b 100644 --- a/library/src/ipfs_client/ipld/unixfs_file.cc +++ b/library/src/ipfs_client/ipld/unixfs_file.cc @@ -1,11 +1,20 @@ #include "unixfs_file.h" +#include <cstdint> +#include <vector> +#include <string> +#include <variant> +#include "ipfs_client/ipld/resolution_state.h" +#include "ipfs_client/ipld/dag_node.h" +#include "ipfs_client/response.h" #include "log_macros.h" using namespace std::literals; using Self = ipfs::ipld::UnixfsFile; +constexpr std::uint16_t cSuccess = 200U; + auto Self::resolve(ResolutionState& params) -> ResolveResult { if (!params.IsFinalComponent()) { LOG(ERROR) << "Can't path through a file, (at " << params.MyPath() @@ -21,8 +30,8 @@ auto Self::resolve(ResolutionState& params) -> ResolveResult { } if (link.node) { auto recurse = link.node->Resolve(params); - auto mdn = std::get_if<MoreDataNeeded>(&recurse); - if (mdn) { + auto *mdn = std::get_if<MoreDataNeeded>(&recurse); + if (mdn != nullptr) { missing.insert(missing.end(), mdn->ipfs_abs_paths_.begin(), mdn->ipfs_abs_paths_.end()); continue; @@ -37,7 +46,7 @@ auto Self::resolve(ResolutionState& params) -> ResolveResult { if (missing.empty()) { return Response{ "", - 200, + cSuccess, body, params.MyPath().to_string(), {}, }; diff --git a/library/src/ipfs_client/ipns_record.cc b/library/src/ipfs_client/ipns_record.cc index 462ca3c9..9c1148f8 100644 --- a/library/src/ipfs_client/ipns_record.cc +++ b/library/src/ipfs_client/ipns_record.cc @@ -3,11 +3,27 @@ #include <ipfs_client/cid.h> #include <ipfs_client/client.h> #include <ipfs_client/dag_cbor_value.h> +#include <ipfs_client/keys.pb.h> +#include <ctime> +#include <ctime> +#include "ipfs_client/multi_hash.h" +#include "ipfs_client/ipns_cbor_entry.h" +#include "ipfs_client/multicodec.h" +#include "ipfs_client/crypto/signing_key_type.h" #include "log_macros.h" +#include "vocab/byte_view.h" +#include "vocab/byte.h" -#include <ctime> +#include <algorithm> +#include <cstdint> +#include <limits> +#include <optional> +#include <iomanip> +#include <ios> #include <sstream> +#include <string> +#include <string_view> #if __has_include(<third_party/ipfs_client/ipns_record.pb.h>) #include <third_party/ipfs_client/ipns_record.pb.h> @@ -16,9 +32,9 @@ #endif namespace { -bool matches(ipfs::MultiHash const& hash, +auto matches(ipfs::MultiHash const& hash, ipfs::ByteView pubkey_bytes, - ipfs::Client& api) { + ipfs::Client& api) -> bool { auto result = api.Hash(hash.type(), pubkey_bytes); if (!result.has_value()) { return false; @@ -29,16 +45,16 @@ bool matches(ipfs::MultiHash const& hash, void assign(std::string& out, ipfs::DagCborValue& top, std::string_view key) { - auto p = top.at(key); - if (!p) { + auto ptr = top.at(key); + if (!ptr) { out.assign("Key '").append(key).append("' not present in IPNS CBOR!"); } else { // YEP! as_bytes() . There are only 2 string values here, they are logically // text, but they are defined in the spec to be bytes. - auto o = p->as_bytes(); - if (o.has_value()) { - auto chars = reinterpret_cast<char const*>(o.value().data()); - out.assign(chars, o.value().size()); + auto byted = ptr->as_bytes(); + if (byted.has_value()) { + const auto *chars = reinterpret_cast<char const*>(byted.value().data()); + out.assign(chars, byted.value().size()); } else { out.assign("Key '").append(key).append( "' was not a string in IPNS CBOR!"); @@ -136,13 +152,13 @@ auto ipfs::ValidateIpnsRecord(ipfs::ByteView top_level_bytes, return {}; } ipfs::ipns::PublicKey pk; - auto* pkbp = reinterpret_cast<char const*>(public_key.data()); + const auto* pkbp = reinterpret_cast<char const*>(public_key.data()); if (!pk.ParseFromArray(pkbp, public_key.size())) { LOG(ERROR) << "Failed to parse public key bytes"; return {}; } - auto& signature_str = entry.signaturev2(); - ByteView signature{reinterpret_cast<ipfs::Byte const*>(signature_str.data()), + const auto& signature_str = entry.signaturev2(); + ByteView const signature{reinterpret_cast<ipfs::Byte const*>(signature_str.data()), signature_str.size()}; // https://specs.ipfs.tech/ipns/ipns-record/#record-verification // Create bytes for signature verification by concatenating @@ -150,10 +166,10 @@ auto ipfs::ValidateIpnsRecord(ipfs::ByteView top_level_bytes, // 69706e732d7369676e61747572653a) with raw CBOR bytes from IpnsEntry.data auto bytes_str = entry.data(); bytes_str.insert( - 0, "\x69\x70\x6e\x73\x2d\x73\x69\x67\x6e\x61\x74\x75\x72\x65\x3a"); - ByteView bytes{reinterpret_cast<ipfs::Byte const*>(bytes_str.data()), + 0, R"(ipns-signature:)"); + ByteView const bytes{reinterpret_cast<ipfs::Byte const*>(bytes_str.data()), bytes_str.size()}; - ByteView key_bytes{reinterpret_cast<ipfs::Byte const*>(pk.data().data()), + ByteView const key_bytes{reinterpret_cast<ipfs::Byte const*>(pk.data().data()), pk.data().size()}; if (!api.VerifyKeySignature(static_cast<crypto::SigningKeyType>(pk.type()), signature, bytes, key_bytes)) { @@ -208,7 +224,7 @@ ipfs::ValidatedIpns::ValidatedIpns(IpnsCborEntry const& e) std::istringstream ss{e.validity}; std::tm t = {}; ss >> std::get_time(&t, "%Y-%m-%dT%H:%M:%S"); - long ttl = static_cast<long>(e.ttl / 1'000'000'000UL) + 1; + long const ttl = static_cast<long>(e.ttl / 1'000'000'000UL) + 1; #ifdef _MSC_VER use_until = _mkgmtime(&t); #else @@ -217,7 +233,7 @@ ipfs::ValidatedIpns::ValidatedIpns(IpnsCborEntry const& e) cache_until = std::time(nullptr) + ttl; } -std::string ipfs::ValidatedIpns::Serialize() const { +auto ipfs::ValidatedIpns::Serialize() const -> std::string { DCHECK_EQ(value.find(' '), std::string::npos); DCHECK_EQ(gateway_source.find(' '), std::string::npos); std::ostringstream ss; diff --git a/library/src/ipfs_client/opinionated_context.cc b/library/src/ipfs_client/opinionated_context.cc index 36e560ac..ae6d394a 100644 --- a/library/src/ipfs_client/opinionated_context.cc +++ b/library/src/ipfs_client/opinionated_context.cc @@ -1,6 +1,13 @@ #include <ipfs_client/opinionated_context.h> #include <ipfs_client/gw/default_requestor.h> +#include <memory> +#include "ipfs_client/client.h" +#include "ipfs_client/crypto/signing_key_type.h" +#include "ipfs_client/ctx/boost_beast_http.h" +#include "ipfs_client/ctx/ares_dns_txt_lookup.h" +#include "ipfs_client/crypto/openssl_signature_verifier.h" +#include <openssl/evp.h> #if HAS_OPINIONATED_CONTEXT diff --git a/library/src/ipfs_client/partition.cc b/library/src/ipfs_client/partition.cc index d2448e24..cc2ce646 100644 --- a/library/src/ipfs_client/partition.cc +++ b/library/src/ipfs_client/partition.cc @@ -3,10 +3,19 @@ #include <ipfs_client/client.h> #include <ipfs_client/ipfs_request.h> +#include "ipfs_client/gw/requestor.h" +#include "ipfs_client/ipld/dag_node.h" +#include "ipfs_client/ipld/resolution_state.h" +#include "ipfs_client/gw/gateway_request.h" #include "log_macros.h" #include "path2url.h" +#include "vocab/slash_delimited.h" #include <algorithm> +#include <memory> +#include <utility> +#include <string> +#include <variant> using namespace std::literals; @@ -14,7 +23,7 @@ using Self = ipfs::Partition; Self::Partition(std::shared_ptr<gw::Requestor> requestor, std::shared_ptr<Client> api) - : api_{api}, requestor_{requestor} { + : api_{std::move(api)}, requestor_{requestor} { DCHECK(requestor); } @@ -25,7 +34,7 @@ void Self::build_response(std::shared_ptr<IpfsRequest> req) { } auto req_path = req->path(); req_path.pop(); // discard namespace ipfs or ipns - std::string affinity{req_path.pop()}; + std::string const affinity{req_path.pop()}; auto it = dags_.find(affinity); if (dags_.end() == it) { if (gw_request(req, req->path(), affinity)) { @@ -51,8 +60,8 @@ void Self::from_tree(std::shared_ptr<IpfsRequest> req, auto start = std::string{req->path().pop_n(2)}; ipfs::ipld::ResolutionState state{relative_path, req->semantic(), block_look_up}; auto result = root->Resolve(state); - auto response = std::get_if<Response>(&result); - if (response) { + auto *response = std::get_if<Response>(&result); + if (response != nullptr) { if (response->mime_.empty() && !response->body_.empty()) { if (response->location_.empty()) { response->mime_ = sniff(req->path(), response->body_); @@ -77,7 +86,7 @@ void Self::from_tree(std::shared_ptr<IpfsRequest> req, LOG(ERROR) << "Should not be getting a PathChange in orchestrator - " "should've been handled in the root, but got " << pc->new_path << " for " << req->path(); - } else if (std::get_if<ipld::ProvenAbsent>(&result)) { + } else if (std::get_if<ipld::ProvenAbsent>(&result) != nullptr) { req->finish(Response::IMMUTABLY_GONE); } else { auto& mps = std::get<ipld::MoreDataNeeded>(result).ipfs_abs_paths_; @@ -88,9 +97,9 @@ void Self::from_tree(std::shared_ptr<IpfsRequest> req, } } } -bool Self::gw_request(std::shared_ptr<IpfsRequest> ir, +auto Self::gw_request(std::shared_ptr<IpfsRequest> ir, ipfs::SlashDelimited path, - std::string const& aff) { + std::string const& aff) -> bool { auto req = gw::GatewayRequest::fromIpfsPath(path); if (req) { req->dependent = ir; @@ -103,7 +112,7 @@ bool Self::gw_request(std::shared_ptr<IpfsRequest> ir, return false; } -bool Self::add_node(std::string key, ipfs::ipld::NodePtr p) { +auto Self::add_node(std::string key, ipfs::ipld::NodePtr p) -> bool { if (!p) { LOG(INFO) << "NULL block attempted to be added for " << key; return false; @@ -120,11 +129,11 @@ bool Self::add_node(std::string key, ipfs::ipld::NodePtr p) { return true; } -std::string Self::sniff(ipfs::SlashDelimited p, std::string const& body) const { +auto Self::sniff(ipfs::SlashDelimited p, std::string const& body) const -> std::string { auto fake_url = path2url(p.to_string()); auto file_name = p.peek_back(); auto dot = file_name.find_last_of('.'); - std::string ext = ""; + std::string ext; if (dot < file_name.size()) { ext.assign(file_name, dot + 1); } @@ -132,6 +141,6 @@ std::string Self::sniff(ipfs::SlashDelimited p, std::string const& body) const { return result; } -bool Self::has_key(std::string const& k) const { - return dags_.count(k); +auto Self::has_key(std::string const& k) const -> bool { + return dags_.count(k) != 0U; } diff --git a/library/src/ipfs_client/pb_dag.cc b/library/src/ipfs_client/pb_dag.cc index c7399ceb..282545e0 100644 --- a/library/src/ipfs_client/pb_dag.cc +++ b/library/src/ipfs_client/pb_dag.cc @@ -2,9 +2,26 @@ #include <ipfs_client/client.h> +#include "ipfs_client/multicodec.h" +#include "ipfs_client/cid.h" +#include "ipfs_client/multi_hash.h" #include "log_macros.h" +#include "vocab/byte_view.h" +#include "vocab/byte.h" #include <algorithm> +#include <string> +#include <istream> +#include <iterator> +#include <utility> +#include <memory> +#include <tuple> +#include <string_view> +#include <vector> +#include <functional> +#include <optional> +#include <cstdint> +#include <ostream> #if __has_include(<third_party/ipfs_client/pb_dag.pb.h>) #include <third_party/ipfs_client/pb_dag.pb.h> @@ -15,27 +32,27 @@ #endif namespace { -std::string get_bytes(std::string const& s) { - return s; +auto get_bytes(std::string const& already_string) -> std::string { + return already_string; } -std::string get_bytes(std::istream& is) { - return std::string(std::istreambuf_iterator<char>(is), {}); +auto get_bytes(std::istream& strm) -> std::string { + return std::string(std::istreambuf_iterator<char>(strm), {}); } -bool parse(ipfs::pb_dag::PBNode& n, std::istream& s) { - return n.ParseFromIstream(&s); +auto parse(ipfs::pb_dag::PBNode& n, std::istream& strm) -> bool { + return n.ParseFromIstream(&strm); } -bool parse(ipfs::pb_dag::PBNode& n, std::string const& s) { +auto parse(ipfs::pb_dag::PBNode& n, std::string const& s) -> bool { return n.ParseFromString(s); } template <class From> -std::pair<bool, bool> InitBlock(ipfs::MultiCodec c, +auto InitBlock(ipfs::MultiCodec c, From& from, ipfs::pb_dag::PBNode& n, - ipfs::unix_fs::Data& d) { + ipfs::unix_fs::Data& d) -> std::pair<bool, bool> { using Cdc = ipfs::MultiCodec; switch (c) { case Cdc::DAG_PB: @@ -70,10 +87,10 @@ struct ipfs::PbDag::Data { unix_fs::Data fsdata_; }; -ipfs::PbDag::PbDag(Cid const& c, std::istream& s) - : pimpl_{std::make_unique<Data>()}, cid_(c) { +ipfs::PbDag::PbDag(Cid const& cid, std::istream& stream) + : pimpl_{std::make_unique<Data>()}, cid_(cid) { std::tie(valid_, fs_node_) = - InitBlock(c.codec(), s, pimpl_->node_, pimpl_->fsdata_); + InitBlock(cid.codec(), stream, pimpl_->node_, pimpl_->fsdata_); } ipfs::PbDag::PbDag(Cid const& c, ByteView s) @@ -97,7 +114,7 @@ ipfs::PbDag::PbDag() = default; ipfs::PbDag::~PbDag() noexcept = default; -bool ipfs::PbDag::valid() const { +auto ipfs::PbDag::valid() const -> bool { return valid_; } @@ -115,22 +132,22 @@ auto ipfs::PbDag::type() const -> Type { return Type::FileChunk; } } - if (pimpl_->fsdata_.type()) { + if (pimpl_->fsdata_.type() != 0) { return static_cast<Type>(pimpl_->fsdata_.type()); } return Type::Invalid; } -bool ipfs::PbDag::is_file() const { +auto ipfs::PbDag::is_file() const -> bool { return valid() && fs_node_ && pimpl_->fsdata_.type() == unix_fs::Data_DataType_File; } -std::string const& ipfs::PbDag::chunk_data() const { +auto ipfs::PbDag::chunk_data() const -> std::string const& { return pimpl_->fsdata_.data(); } -std::string const& ipfs::PbDag::unparsed() const { +auto ipfs::PbDag::unparsed() const -> std::string const& { return pimpl_->node_.data(); } @@ -139,8 +156,8 @@ auto ipfs::PbDag::cid() const -> Cid const& { return cid_.value(); } -std::string ipfs::PbDag::LinkCid(ipfs::ByteView binary_link_hash) const { - Cid result(binary_link_hash); +auto ipfs::PbDag::LinkCid(ipfs::ByteView binary_link_hash) const -> std::string { + Cid const result(binary_link_hash); if (!result.valid()) { LOG(FATAL) << "Failed to decode link CID as binary ( link from " << cid().to_string() << ")"; @@ -153,7 +170,7 @@ std::string ipfs::PbDag::LinkCid(ipfs::ByteView binary_link_hash) const { return str_res; } -bool ipfs::PbDag::cid_matches_data(Client& api) const { +auto ipfs::PbDag::cid_matches_data(Client& api) const -> bool { if (!cid_) { return true; } @@ -171,8 +188,8 @@ bool ipfs::PbDag::cid_matches_data(Client& api) const { hashed.end()); } -std::vector<ipfs::Byte> ipfs::PbDag::binary_hash(Client& api, - HashType algo) const { +auto ipfs::PbDag::binary_hash(Client& api, + HashType algo) const -> std::vector<ipfs::Byte> { if (algo == HashType::INVALID) { algo = cid().hash_type(); } @@ -186,7 +203,7 @@ std::vector<ipfs::Byte> ipfs::PbDag::binary_hash(Client& api, void ipfs::PbDag::List( std::function<bool(std::string const&, std::string)> foo) const { - for (auto& link : pimpl_->node_.links()) { + for (const auto& link : pimpl_->node_.links()) { // protobuf uses string for binary data, too auto hash = as_bytes(link.hash()); if (!foo(link.name(), LinkCid(hash))) { @@ -194,14 +211,14 @@ void ipfs::PbDag::List( } } } -std::optional<std::uint64_t> ipfs::PbDag::Fanout() const { +auto ipfs::PbDag::Fanout() const -> std::optional<std::uint64_t> { if (pimpl_ && fs_node_ && pimpl_->fsdata_.has_fanout()) { return pimpl_->fsdata_.fanout(); } return std::nullopt; } -std::ostream& operator<<(std::ostream& s, ipfs::PbDag::Type t) { +auto operator<<(std::ostream& s, ipfs::PbDag::Type t) -> std::ostream& { switch (t) { case ipfs::PbDag::Type::Raw: return s << "Raw"; diff --git a/library/src/vocab/slash_delimited.cc b/library/src/vocab/slash_delimited.cc index 48aa806e..2dffa19c 100644 --- a/library/src/vocab/slash_delimited.cc +++ b/library/src/vocab/slash_delimited.cc @@ -1,20 +1,19 @@ #include <vocab/slash_delimited.h> -#include <iostream> +#include <cstddef> -#if __has_include(<base/strings/string_piece.h>) -#include <base/strings/string_piece.h> -#define HAS_STRINGPIECE 1 -#endif +#include <iostream> +#include <string> +#include <string_view> using Self = ipfs::SlashDelimited; Self::SlashDelimited(std::string_view unowned) : remainder_{unowned} {} Self::operator bool() const { - return remainder_.find_first_not_of("/") < remainder_.size(); + return remainder_.find_first_not_of('/') < remainder_.size(); } -std::string_view Self::pop() { +auto Self::pop() -> std::string_view { if (remainder_.empty()) { return remainder_; } @@ -30,16 +29,16 @@ std::string_view Self::pop() { return result; } } -std::string_view Self::pop_all() { +auto Self::pop_all() -> std::string_view { auto result = remainder_; remainder_ = ""; return result; } -std::string_view Self::pop_n(std::size_t n) { - std::size_t a = 0UL; - while (n) { - auto slash = remainder_.find('/', a); - auto non_slash = remainder_.find_first_not_of("/", a); +auto Self::pop_n(std::size_t n) -> std::string_view { + std::size_t idx = 0UL; + while (n > 0UL) { + auto slash = remainder_.find('/', idx); + auto non_slash = remainder_.find_first_not_of('/', idx); if (slash == std::string_view::npos) { auto result = remainder_; remainder_ = ""; @@ -48,46 +47,45 @@ std::string_view Self::pop_n(std::size_t n) { if (non_slash < slash) { --n; } - a = slash + 1UL; + idx = slash + 1UL; } - auto result = remainder_.substr(0UL, a - 1); - remainder_.remove_prefix(a); + auto result = remainder_.substr(0UL, idx - 1); + remainder_.remove_prefix(idx); return result; } -std::string_view Self::peek_back() const { - auto s = remainder_; - while (!s.empty() && s.back() == '/') { - s.remove_suffix(1); +auto Self::peek_back() const -> std::string_view { + auto rem = remainder_; + while (!rem.empty() && rem.back() == '/') { + rem.remove_suffix(1); } - if (s.empty()) { - return s; + if (rem.empty()) { + return rem; } - auto last_slash = s.find_last_of('/'); - if (last_slash < remainder_.size()) { - return remainder_.substr(last_slash + 1); - } else { - return s; + auto last_slash = rem.find_last_of('/'); + if (last_slash < rem.size()) { + rem.remove_prefix(last_slash + 1); } + return rem; } -std::string Self::pop_back() { +auto Self::pop_back() -> std::string { auto non_slash = remainder_.find_last_not_of('/'); if (non_slash == std::string_view::npos) { return ""; } auto slash = remainder_.find_last_of('/', non_slash); - std::string rv; + std::string result; if (slash == std::string_view::npos) { - rv = remainder_; + result = remainder_; remainder_ = ""; } else { - rv = remainder_.substr(slash + 1, non_slash - slash); + result = remainder_.substr(slash + 1, non_slash - slash); remainder_ = remainder_.substr(0UL, slash); } - return rv; + return result; } -std::ostream& operator<<(std::ostream& str, ipfs::SlashDelimited const& sd) { - return str << sd.to_view(); +auto operator<<(std::ostream& stream, ipfs::SlashDelimited const& sdp) -> std::ostream& { + return stream << sdp.to_view(); } #ifndef NACL_TC_REV @@ -99,17 +97,17 @@ using namespace google::protobuf; #if PROTOBUF_VERSION >= 3020000 #include <google/protobuf/stubs/stringpiece.h> -LogMessage& operator<<(LogMessage& str, ipfs::SlashDelimited const& sd) { - return str << sd.to_view(); +LogMessage& operator<<(LogMessage& str, ipfs::SlashDelimited const& sdp) { + return str << sdp.to_view(); } #elif __has_include(<google/protobuf/stubs/stringpiece.h>) #include <google/protobuf/stubs/stringpiece.h> -LogMessage& operator<<(LogMessage& str, ipfs::SlashDelimited const& sd) { - return str << StringPiece{sd.to_view()}; +auto operator<<(LogMessage& str, ipfs::SlashDelimited const& sdp) -> LogMessage& { + return str << StringPiece{sdp.to_view()}; } #else -LogMessage& operator<<(LogMessage& str, ipfs::SlashDelimited const& sd) { - return str << std::string{sd.to_view()}; +LogMessage& operator<<(LogMessage& str, ipfs::SlashDelimited const& sdp) { + return str << std::string{sdp.to_view()}; } #endif